just-bash 1.2.2 → 1.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- var ml=Object.defineProperty;var N=(t,e)=>()=>(t&&(e=t(t=0)),e);var O=(t,e)=>{for(var r in e)ml(t,r,{get:e[r],enumerable:!0})};var ns={};O(ns,{echoCommand:()=>gl});function yl(t){let e="",r=0;for(;r<t.length;)if(t[r]==="\\"){if(r+1>=t.length){e+="\\";break}let n=t[r+1];switch(n){case"\\":e+="\\",r+=2;break;case"n":e+=`
2
- `,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"e":case"E":e+="\x1B",r+=2;break;case"c":return{output:e,stop:!0};case"0":{let s="",i=r+2;for(;i<t.length&&i<r+5&&/[0-7]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\0";else{let a=parseInt(s,8)%256;e+=String.fromCharCode(a)}r=i;break}case"x":{let s="",i=r+2;for(;i<t.length&&i<r+4&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\\x",r+=2;else{let a=parseInt(s,16);e+=String.fromCharCode(a),r=i}break}case"u":{let s="",i=r+2;for(;i<t.length&&i<r+6&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\\u",r+=2;else{let a=parseInt(s,16);e+=String.fromCodePoint(a),r=i}break}case"U":{let s="",i=r+2;for(;i<t.length&&i<r+10&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\\U",r+=2;else{let a=parseInt(s,16);try{e+=String.fromCodePoint(a)}catch{e+=`\\U${s}`}r=i}break}default:e+=`\\${n}`,r+=2}}else e+=t[r],r++;return{output:e,stop:!1}}var gl,ss=N(()=>{"use strict";gl={name:"echo",async execute(t,e){let r=!1,n=!1,s=0;for(;s<t.length;){let a=t[s];if(a==="-n")r=!0,s++;else if(a==="-e")n=!0,s++;else if(a==="-E")n=!1,s++;else if(a==="-ne"||a==="-en")r=!0,n=!0,s++;else break}let i=t.slice(s).join(" ");if(n){let a=yl(i);if(i=a.output,a.stop)return{stdout:i,stderr:"",exitCode:0}}return r||(i+=`
3
- `),{stdout:i,stderr:"",exitCode:0}}}});function A(t){let e=`${t.name} - ${t.summary}
1
+ var El=Object.defineProperty;var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var D=(t,e)=>{for(var r in e)El(t,r,{get:e[r],enumerable:!0})};var as={};D(as,{echoCommand:()=>Sl});function bl(t){let e="",r=0;for(;r<t.length;)if(t[r]==="\\"){if(r+1>=t.length){e+="\\";break}let n=t[r+1];switch(n){case"\\":e+="\\",r+=2;break;case"n":e+=`
2
+ `,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"e":case"E":e+="\x1B",r+=2;break;case"c":return{output:e,stop:!0};case"0":{let s="",i=r+2;for(;i<t.length&&i<r+5&&/[0-7]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\0";else{let a=parseInt(s,8)%256;e+=String.fromCharCode(a)}r=i;break}case"x":{let s="",i=r+2;for(;i<t.length&&i<r+4&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\\x",r+=2;else{let a=parseInt(s,16);e+=String.fromCharCode(a),r=i}break}case"u":{let s="",i=r+2;for(;i<t.length&&i<r+6&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\\u",r+=2;else{let a=parseInt(s,16);e+=String.fromCodePoint(a),r=i}break}case"U":{let s="",i=r+2;for(;i<t.length&&i<r+10&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;if(s.length===0)e+="\\U",r+=2;else{let a=parseInt(s,16);try{e+=String.fromCodePoint(a)}catch{e+=`\\U${s}`}r=i}break}default:e+=`\\${n}`,r+=2}}else e+=t[r],r++;return{output:e,stop:!1}}var Sl,os=v(()=>{"use strict";Sl={name:"echo",async execute(t,e){let r=!1,n=!1,s=0;for(;s<t.length;){let a=t[s];if(a==="-n")r=!0,s++;else if(a==="-e")n=!0,s++;else if(a==="-E")n=!1,s++;else if(a==="-ne"||a==="-en")r=!0,n=!0,s++;else break}let i=t.slice(s).join(" ");if(n){let a=bl(i);if(i=a.output,a.stop)return{stdout:i,stderr:"",exitCode:0}}return r||(i+=`
3
+ `),{stdout:i,stderr:"",exitCode:0}}}});function C(t){let e=`${t.name} - ${t.summary}
4
4
 
5
5
  `;if(e+=`Usage: ${t.usage}
6
6
  `,t.description){if(e+=`
@@ -19,75 +19,75 @@ Examples:
19
19
  `}if(t.notes&&t.notes.length>0){e+=`
20
20
  Notes:
21
21
  `;for(let r of t.notes)e+=` ${r}
22
- `}return{stdout:e,stderr:"",exitCode:0}}function C(t){return t.includes("--help")}function T(t,e){return{stdout:"",stderr:e.startsWith("--")?`${t}: unrecognized option '${e}'
22
+ `}return{stdout:e,stderr:"",exitCode:0}}function N(t){return t.includes("--help")}function M(t,e){return{stdout:"",stderr:e.startsWith("--")?`${t}: unrecognized option '${e}'
23
23
  `:`${t}: invalid option -- '${e.replace(/^-/,"")}'
24
- `,exitCode:1}}var L=N(()=>{"use strict"});function H(t,e,r){let n=new Map,s=new Map;for(let[c,l]of Object.entries(r)){let u={name:c,type:l.type};l.short&&n.set(l.short,u),l.long&&s.set(l.long,u)}let i={};for(let[c,l]of Object.entries(r))l.default!==void 0?i[c]=l.default:l.type==="boolean"&&(i[c]=!1);let a=[],o=!1;for(let c=0;c<e.length;c++){let l=e[c];if(o||!l.startsWith("-")||l==="-"){a.push(l);continue}if(l==="--"){o=!0;continue}if(l.startsWith("--")){let u=l.indexOf("="),f,d;u!==-1?(f=l.slice(2,u),d=l.slice(u+1)):f=l.slice(2);let h=s.get(f);if(!h)return{ok:!1,error:T(t,l)};let{name:p,type:b}=h;if(b==="boolean")i[p]=!0;else{if(d===void 0){if(c+1>=e.length)return{ok:!1,error:{stdout:"",stderr:`${t}: option '--${f}' requires an argument
25
- `,exitCode:1}};d=e[++c]}i[p]=b==="number"?parseInt(d,10):d}}else{let u=l.slice(1);for(let f=0;f<u.length;f++){let d=u[f],h=n.get(d);if(!h)return{ok:!1,error:T(t,`-${d}`)};let{name:p,type:b}=h;if(b==="boolean")i[p]=!0;else{let w;if(f+1<u.length)w=u.slice(f+1);else if(c+1<e.length)w=e[++c];else return{ok:!1,error:{stdout:"",stderr:`${t}: option requires an argument -- '${d}'
26
- `,exitCode:1}};i[p]=b==="number"?parseInt(w,10):w;break}}}}return{ok:!0,result:{flags:i,positional:a}}}var ae=N(()=>{"use strict";L()});async function Et(t,e,r){let{cmdName:n,allowStdinMarker:s=!0,stopOnError:i=!1}=r;if(e.length===0)return{files:[{filename:"",content:t.stdin}],stderr:"",exitCode:0};let a=[],o="",c=0;for(let l of e){if(s&&l==="-"){a.push({filename:"-",content:t.stdin});continue}try{let u=t.fs.resolvePath(t.cwd,l),f=await t.fs.readFile(u);a.push({filename:l,content:f})}catch{if(o+=`${n}: ${l}: No such file or directory
27
- `,c=1,i)return{files:a,stderr:o,exitCode:c}}}return{files:a,stderr:o,exitCode:c}}async function Be(t,e,r){let n=await Et(t,e,{...r,stopOnError:!0});return n.exitCode!==0?{ok:!1,error:{stdout:"",stderr:n.stderr,exitCode:n.exitCode}}:{ok:!0,content:n.files.map(i=>i.content).join("")}}var Ze=N(()=>{"use strict"});var is={};O(is,{catCommand:()=>bl});function xl(t,e){let r=t.split(`
24
+ `,exitCode:1}}var F=v(()=>{"use strict"});function G(t,e,r){let n=new Map,s=new Map;for(let[c,l]of Object.entries(r)){let u={name:c,type:l.type};l.short&&n.set(l.short,u),l.long&&s.set(l.long,u)}let i={};for(let[c,l]of Object.entries(r))l.default!==void 0?i[c]=l.default:l.type==="boolean"&&(i[c]=!1);let a=[],o=!1;for(let c=0;c<e.length;c++){let l=e[c];if(o||!l.startsWith("-")||l==="-"){a.push(l);continue}if(l==="--"){o=!0;continue}if(l.startsWith("--")){let u=l.indexOf("="),f,d;u!==-1?(f=l.slice(2,u),d=l.slice(u+1)):f=l.slice(2);let h=s.get(f);if(!h)return{ok:!1,error:M(t,l)};let{name:p,type:E}=h;if(E==="boolean")i[p]=!0;else{if(d===void 0){if(c+1>=e.length)return{ok:!1,error:{stdout:"",stderr:`${t}: option '--${f}' requires an argument
25
+ `,exitCode:1}};d=e[++c]}i[p]=E==="number"?parseInt(d,10):d}}else{let u=l.slice(1);for(let f=0;f<u.length;f++){let d=u[f],h=n.get(d);if(!h)return{ok:!1,error:M(t,`-${d}`)};let{name:p,type:E}=h;if(E==="boolean")i[p]=!0;else{let w;if(f+1<u.length)w=u.slice(f+1);else if(c+1<e.length)w=e[++c];else return{ok:!1,error:{stdout:"",stderr:`${t}: option requires an argument -- '${d}'
26
+ `,exitCode:1}};i[p]=E==="number"?parseInt(w,10):w;break}}}}return{ok:!0,result:{flags:i,positional:a}}}var oe=v(()=>{"use strict";F()});async function St(t,e,r){let{cmdName:n,allowStdinMarker:s=!0,stopOnError:i=!1}=r;if(e.length===0)return{files:[{filename:"",content:t.stdin}],stderr:"",exitCode:0};let a=[],o="",c=0;for(let l of e){if(s&&l==="-"){a.push({filename:"-",content:t.stdin});continue}try{let u=t.fs.resolvePath(t.cwd,l),f=await t.fs.readFile(u);a.push({filename:l,content:f})}catch{if(o+=`${n}: ${l}: No such file or directory
27
+ `,c=1,i)return{files:a,stderr:o,exitCode:c}}}return{files:a,stderr:o,exitCode:c}}async function He(t,e,r){let n=await St(t,e,{...r,stopOnError:!0});return n.exitCode!==0?{ok:!1,error:{stdout:"",stderr:n.stderr,exitCode:n.exitCode}}:{ok:!0,content:n.files.map(i=>i.content).join("")}}var Ke=v(()=>{"use strict"});var ls={};D(ls,{catCommand:()=>Cl});function Nl(t,e){let r=t.split(`
28
28
  `),n=t.endsWith(`
29
29
  `),s=n?r.slice(0,-1):r;return{content:s.map((a,o)=>`${String(e+o).padStart(6," ")} ${a}`).join(`
30
30
  `)+(n?`
31
- `:""),nextLineNumber:e+s.length}}var wl,El,bl,as=N(()=>{"use strict";ae();Ze();L();wl={name:"cat",summary:"concatenate files and print on the standard output",usage:"cat [OPTION]... [FILE]...",options:["-n, --number number all output lines"," --help display this help and exit"]},El={number:{short:"n",long:"number",type:"boolean"}},bl={name:"cat",async execute(t,e){if(C(t))return A(wl);let r=H("cat",t,El);if(!r.ok)return r.error;let n=r.result.flags.number,s=r.result.positional,i=await Et(e,s,{cmdName:"cat",allowStdinMarker:!0,stopOnError:!1}),a="",o=1;for(let{content:c}of i.files)if(n){let l=xl(c,o);a+=l.content,o=l.nextLineNumber}else a+=c;return{stdout:a,stderr:i.stderr,exitCode:i.exitCode}}}});function Y(t){return t instanceof Error?t.message:String(t)}var ke=N(()=>{"use strict"});var ls={};O(ls,{printfCommand:()=>Al});import{sprintf as it}from"sprintf-js";function Cl(t){let e="",r=0;for(;r<t.length;)if(t[r]==="\\"&&r+1<t.length)switch(t[r+1]){case"n":e+=`
32
- `,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"\\":e+="\\",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let s="",i=r+1;for(;i<t.length&&i<r+4&&/[0-7]/.test(t[i]);)s+=t[i],i++;e+=String.fromCharCode(parseInt(s,8)),r=i;break}case"x":r+3<t.length&&/[0-9a-fA-F]{2}/.test(t.slice(r+2,r+4))?(e+=String.fromCharCode(parseInt(t.slice(r+2,r+4),16)),r+=4):(e+=t[r],r++);break;default:e+=t[r],r++}else e+=t[r],r++;return e}function Nl(t,e,r){let n="",s=0,i=0,a=!1,o="";for(;s<t.length;)if(t[s]==="%"&&s+1<t.length){let c=s;if(s++,t[s]==="%"){n+="%",s++;continue}for(;s<t.length&&"+-0 #'".includes(t[s]);)s++;let l=!1;if(t[s]==="*")l=!0,s++;else for(;s<t.length&&/\d/.test(t[s]);)s++;let u=!1;if(t[s]===".")if(s++,t[s]==="*")u=!0,s++;else for(;s<t.length&&/\d/.test(t[s]);)s++;s<t.length&&"hlL".includes(t[s])&&s++;let f=t[s]||"";s++;let h=t.slice(c,s);if(l){let x=parseInt(e[r+i]||"0",10);i++,h=h.replace("*",String(x))}if(u){let x=parseInt(e[r+i]||"0",10);i++,h=h.replace(".*",`.${x}`)}let p=e[r+i]||"";i++;let{value:b,parseError:w,parseErrMsg:g,stopped:E}=vl(h,f,p);if(n+=b,w&&(a=!0,g&&(o=g)),E)return{result:n,argsConsumed:i,error:a,errMsg:o,stopped:!0}}else n+=t[s],s++;return{result:n,argsConsumed:i,error:a,errMsg:o,stopped:!1}}function vl(t,e,r){let n=!1,s="";switch(e){case"d":case"i":{let i=Ft(r);return n=Ie,n&&(s=`printf: ${r}: invalid number
33
- `),{value:os(t,i),parseError:n,parseErrMsg:s}}case"o":{let i=Ft(r);return n=Ie,n&&(s=`printf: ${r}: invalid number
34
- `),{value:kl(t,i),parseError:n,parseErrMsg:s}}case"u":{let i=Ft(r);n=Ie,n&&(s=`printf: ${r}: invalid number
35
- `);let a=i<0?i>>>0:i;return{value:os(t.replace("u","d"),a),parseError:n,parseErrMsg:s}}case"x":case"X":{let i=Ft(r);return n=Ie,n&&(s=`printf: ${r}: invalid number
36
- `),{value:Il(t,i),parseError:n,parseErrMsg:s}}case"e":case"E":case"f":case"F":case"g":case"G":{let i=parseFloat(r)||0;return{value:Ol(t,e,i),parseError:!1,parseErrMsg:""}}case"c":return{value:r.charAt(0)||"",parseError:!1,parseErrMsg:""};case"s":return{value:$l(t,r),parseError:!1,parseErrMsg:""};case"q":return{value:Pl(t,r),parseError:!1,parseErrMsg:""};case"b":{let i=Dl(r);return{value:i.value,parseError:!1,parseErrMsg:"",stopped:i.stopped}}default:try{return{value:it(t,r),parseError:!1,parseErrMsg:""}}catch{return{value:"",parseError:!0,parseErrMsg:`printf: [sprintf] unexpected placeholder
37
- `}}}}function Ft(t){Ie=!1;let e=t.trimStart(),r=e!==e.trimEnd();if(t=e.trimEnd(),t.startsWith("'")&&t.length>=2||t.startsWith('"')&&t.length>=2)return t.charCodeAt(1);if(t.startsWith("\\'")&&t.length>=3||t.startsWith('\\"')&&t.length>=3)return t.charCodeAt(2);if(t.startsWith("+")&&(t=t.slice(1)),t.startsWith("0x")||t.startsWith("0X")){let n=parseInt(t,16);return Number.isNaN(n)?(Ie=!0,0):(r&&(Ie=!0),n)}if(t.startsWith("0")&&t.length>1&&/^-?0[0-7]+$/.test(t))return r&&(Ie=!0),parseInt(t,8)||0;if(/^\d+#/.test(t)){Ie=!0;let n=t.match(/^(\d+)#/);return n?parseInt(n[1],10):0}if(t!==""&&!/^-?\d+$/.test(t)){Ie=!0;let n=parseInt(t,10);return Number.isNaN(n)?0:n}return r&&(Ie=!0),parseInt(t,10)||0}function os(t,e){let r=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[diu]$/);if(!r)return it(t.replace(/\.\d*/,""),e);let n=r[1]||"",s=r[2]?parseInt(r[2],10):0,i=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,a=e<0,o=Math.abs(e),c=String(o);i>=0&&(c=c.padStart(i,"0"));let l="";a?l="-":n.includes("+")?l="+":n.includes(" ")&&(l=" ");let u=l+c;return s>u.length&&(n.includes("-")?u=u.padEnd(s," "):n.includes("0")&&i<0?u=l+c.padStart(s-l.length,"0"):u=u.padStart(s," ")),u}function kl(t,e){let r=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?o$/);if(!r)return it(t,e);let n=r[1]||"",s=r[2]?parseInt(r[2],10):0,i=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,a=Math.abs(e).toString(8);i>=0&&(a=a.padStart(i,"0")),n.includes("#")&&!a.startsWith("0")&&(a=`0${a}`);let o=a;return s>o.length&&(n.includes("-")?o=o.padEnd(s," "):n.includes("0")&&i<0?o=o.padStart(s,"0"):o=o.padStart(s," ")),o}function Il(t,e){let r=t.includes("X"),n=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[xX]$/);if(!n)return it(t,e);let s=n[1]||"",i=n[2]?parseInt(n[2],10):0,a=n[3]!==void 0?n[4]?parseInt(n[4],10):0:-1,o=Math.abs(e).toString(16);r&&(o=o.toUpperCase()),a>=0&&(o=o.padStart(a,"0"));let c="";s.includes("#")&&e!==0&&(c=r?"0X":"0x");let l=c+o;return i>l.length&&(s.includes("-")?l=l.padEnd(i," "):s.includes("0")&&a<0?l=c+o.padStart(i-c.length,"0"):l=l.padStart(i," ")),l}function Rl(t){if(t==="")return"''";if(/^[a-zA-Z0-9_./-]+$/.test(t))return t;if(/[\x00-\x1f\x7f]/.test(t)){let n="$'";for(let s of t){let i=s.charCodeAt(0);s==="'"?n+="\\'":s==="\\"?n+="\\\\":s===`
38
- `?n+="\\n":s===" "?n+="\\t":s==="\r"?n+="\\r":s==="\x07"?n+="\\a":s==="\b"?n+="\\b":s==="\f"?n+="\\f":s==="\v"?n+="\\v":s==="\x1B"?n+="\\E":i<32||i>126?n+=`\\x${i.toString(16).padStart(2,"0")}`:s==='"'?n+='\\"':n+=s}return n+="'",n}let r="";for(let n of t)" |&;<>()$`\\\"'*?[#~=%!{}".includes(n)?r+=`\\${n}`:r+=n;return r}function $l(t,e){let r=t.match(/^%(-?)(\d*)(\.(\d*))?s$/);if(!r)return it(t.replace(/0+(?=\d)/,""),e);let n=r[1]==="-",s=r[2]?parseInt(r[2],10):0,i=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,a=e;return i>=0&&a.length>i&&(a=a.slice(0,i)),s>a.length&&(n?a=a.padEnd(s," "):a=a.padStart(s," ")),a}function Pl(t,e){let r=Rl(e),n=t.match(/^%(-?)(\d*)q$/);if(!n)return r;let s=n[1]==="-",i=n[2]?parseInt(n[2],10):0,a=r;return i>a.length&&(s?a=a.padEnd(i," "):a=a.padStart(i," ")),a}function Ol(t,e,r){let n=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[eEfFgG]$/);if(!n)return it(t,r);let s=n[1]||"",i=n[2]?parseInt(n[2],10):0,a=n[3]!==void 0?n[4]?parseInt(n[4],10):0:6,o,c=e.toLowerCase();if(c==="e"?(o=r.toExponential(a),o=o.replace(/e([+-])(\d)$/,"e$10$2"),e==="E"&&(o=o.toUpperCase())):c==="f"?(o=r.toFixed(a),s.includes("#")&&a===0&&!o.includes(".")&&(o+=".")):c==="g"?(o=r.toPrecision(a||1),s.includes("#")||(o=o.replace(/\.?0+$/,""),o=o.replace(/\.?0+e/,"e")),o=o.replace(/e([+-])(\d)$/,"e$10$2"),e==="G"&&(o=o.toUpperCase())):o=r.toString(),r>=0&&(s.includes("+")?o=`+${o}`:s.includes(" ")&&(o=` ${o}`)),i>o.length)if(s.includes("-"))o=o.padEnd(i," ");else if(s.includes("0")){let l=o.match(/^[+ -]/)?.[0]||"",u=l?o.slice(1):o;o=l+u.padStart(i-l.length,"0")}else o=o.padStart(i," ");return o}function Dl(t){let e="",r=0;for(;r<t.length;)if(t[r]==="\\"&&r+1<t.length)switch(t[r+1]){case"n":e+=`
39
- `,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"\\":e+="\\",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"c":return{value:e,stopped:!0};case"x":{let s="",i=r+2;for(;i<t.length&&i<r+4&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;s?(e+=String.fromCharCode(parseInt(s,16)),r=i):(e+="\\x",r+=2);break}case"u":{let s="",i=r+2;for(;i<t.length&&i<r+6&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;s?(e+=String.fromCodePoint(parseInt(s,16)),r=i):(e+="\\u",r+=2);break}case"0":{let s="",i=r+2;for(;i<t.length&&i<r+5&&/[0-7]/.test(t[i]);)s+=t[i],i++;s?e+=String.fromCharCode(parseInt(s,8)):e+="\0",r=i;break}case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let s="",i=r+1;for(;i<t.length&&i<r+4&&/[0-7]/.test(t[i]);)s+=t[i],i++;e+=String.fromCharCode(parseInt(s,8)),r=i;break}default:e+=t[r],r++}else e+=t[r],r++;return{value:e,stopped:!1}}var Sl,Al,Ie,cs=N(()=>{"use strict";ke();L();Sl={name:"printf",summary:"format and print data",usage:"printf [-v var] FORMAT [ARGUMENT...]",options:[" -v var assign the output to shell variable VAR rather than display it"," --help display this help and exit"],notes:["FORMAT controls the output like in C printf.","Escape sequences: \\n (newline), \\t (tab), \\\\ (backslash)","Format specifiers: %s (string), %d (integer), %f (float), %x (hex), %o (octal), %% (literal %)","Width and precision: %10s (width 10), %.2f (2 decimal places), %010d (zero-padded)","Flags: %- (left-justify), %+ (show sign), %0 (zero-pad)"]},Al={name:"printf",async execute(t,e){if(C(t))return A(Sl);if(t.length===0)return{stdout:"",stderr:`printf: usage: printf format [arguments]
31
+ `:""),nextLineNumber:e+s.length}}var xl,Al,Cl,cs=v(()=>{"use strict";oe();Ke();F();xl={name:"cat",summary:"concatenate files and print on the standard output",usage:"cat [OPTION]... [FILE]...",options:["-n, --number number all output lines"," --help display this help and exit"]},Al={number:{short:"n",long:"number",type:"boolean"}},Cl={name:"cat",async execute(t,e){if(N(t))return C(xl);let r=G("cat",t,Al);if(!r.ok)return r.error;let n=r.result.flags.number,s=r.result.positional,i=await St(e,s,{cmdName:"cat",allowStdinMarker:!0,stopOnError:!1}),a="",o=1;for(let{content:c}of i.files)if(n){let l=Nl(c,o);a+=l.content,o=l.nextLineNumber}else a+=c;return{stdout:a,stderr:i.stderr,exitCode:i.exitCode}}}});function J(t){return t instanceof Error?t.message:String(t)}var Ie=v(()=>{"use strict"});function _t(t,e,r){let n=t;r>=0&&n.length>r&&(n=n.slice(0,r));let s=Math.abs(e);return s>n.length&&(e<0?n=n.padEnd(s," "):n=n.padStart(s," ")),n}function us(t,e){let r=e,n=0,s=-1,i=!1;for(r<t.length&&t[r]==="-"&&(i=!0,r++);r<t.length&&/\d/.test(t[r]);)n=n*10+parseInt(t[r],10),r++;if(r<t.length&&t[r]===".")for(r++,s=0;r<t.length&&/\d/.test(t[r]);)s=s*10+parseInt(t[r],10),r++;return i&&n>0&&(n=-n),[n,s,r-e]}function Wt(t){let e="",r=0;for(;r<t.length;)if(t[r]==="\\"&&r+1<t.length)switch(t[r+1]){case"n":e+=`
32
+ `,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"\\":e+="\\",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let s="",i=r+1;for(;i<t.length&&i<r+4&&/[0-7]/.test(t[i]);)s+=t[i],i++;e+=String.fromCharCode(parseInt(s,8)),r=i;break}case"x":r+3<t.length&&/[0-9a-fA-F]{2}/.test(t.slice(r+2,r+4))?(e+=String.fromCharCode(parseInt(t.slice(r+2,r+4),16)),r+=4):(e+=t[r],r++);break;default:e+=t[r],r++}else e+=t[r],r++;return e}var Or=v(()=>{"use strict"});var ds={};D(ds,{printfCommand:()=>kl});import{sprintf as lt}from"sprintf-js";function Il(t,e,r){let n="",s=0,i=0,a=!1,o="";for(;s<t.length;)if(t[s]==="%"&&s+1<t.length){let c=s;if(s++,t[s]==="%"){n+="%",s++;continue}for(;s<t.length&&"+-0 #'".includes(t[s]);)s++;let l=!1;if(t[s]==="*")l=!0,s++;else for(;s<t.length&&/\d/.test(t[s]);)s++;let u=!1;if(t[s]===".")if(s++,t[s]==="*")u=!0,s++;else for(;s<t.length&&/\d/.test(t[s]);)s++;s<t.length&&"hlL".includes(t[s])&&s++;let f=t[s]||"";s++;let h=t.slice(c,s);if(l){let S=parseInt(e[r+i]||"0",10);i++,h=h.replace("*",String(S))}if(u){let S=parseInt(e[r+i]||"0",10);i++,h=h.replace(".*",`.${S}`)}let p=e[r+i]||"";i++;let{value:E,parseError:w,parseErrMsg:g,stopped:b}=$l(h,f,p);if(n+=E,w&&(a=!0,g&&(o=g)),b)return{result:n,argsConsumed:i,error:a,errMsg:o,stopped:!0}}else n+=t[s],s++;return{result:n,argsConsumed:i,error:a,errMsg:o,stopped:!1}}function $l(t,e,r){let n=!1,s="";switch(e){case"d":case"i":{let i=Bt(r);return n=$e,n&&(s=`printf: ${r}: invalid number
33
+ `),{value:fs(t,i),parseError:n,parseErrMsg:s}}case"o":{let i=Bt(r);return n=$e,n&&(s=`printf: ${r}: invalid number
34
+ `),{value:Rl(t,i),parseError:n,parseErrMsg:s}}case"u":{let i=Bt(r);n=$e,n&&(s=`printf: ${r}: invalid number
35
+ `);let a=i<0?i>>>0:i;return{value:fs(t.replace("u","d"),a),parseError:n,parseErrMsg:s}}case"x":case"X":{let i=Bt(r);return n=$e,n&&(s=`printf: ${r}: invalid number
36
+ `),{value:Pl(t,i),parseError:n,parseErrMsg:s}}case"e":case"E":case"f":case"F":case"g":case"G":{let i=parseFloat(r)||0;return{value:Ll(t,e,i),parseError:!1,parseErrMsg:""}}case"c":return{value:r.charAt(0)||"",parseError:!1,parseErrMsg:""};case"s":return{value:Dl(t,r),parseError:!1,parseErrMsg:""};case"q":return{value:Tl(t,r),parseError:!1,parseErrMsg:""};case"b":{let i=Fl(r);return{value:i.value,parseError:!1,parseErrMsg:"",stopped:i.stopped}}default:try{return{value:lt(t,r),parseError:!1,parseErrMsg:""}}catch{return{value:"",parseError:!0,parseErrMsg:`printf: [sprintf] unexpected placeholder
37
+ `}}}}function Bt(t){$e=!1;let e=t.trimStart(),r=e!==e.trimEnd();if(t=e.trimEnd(),t.startsWith("'")&&t.length>=2||t.startsWith('"')&&t.length>=2)return t.charCodeAt(1);if(t.startsWith("\\'")&&t.length>=3||t.startsWith('\\"')&&t.length>=3)return t.charCodeAt(2);if(t.startsWith("+")&&(t=t.slice(1)),t.startsWith("0x")||t.startsWith("0X")){let n=parseInt(t,16);return Number.isNaN(n)?($e=!0,0):(r&&($e=!0),n)}if(t.startsWith("0")&&t.length>1&&/^-?0[0-7]+$/.test(t))return r&&($e=!0),parseInt(t,8)||0;if(/^\d+#/.test(t)){$e=!0;let n=t.match(/^(\d+)#/);return n?parseInt(n[1],10):0}if(t!==""&&!/^-?\d+$/.test(t)){$e=!0;let n=parseInt(t,10);return Number.isNaN(n)?0:n}return r&&($e=!0),parseInt(t,10)||0}function fs(t,e){let r=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[diu]$/);if(!r)return lt(t.replace(/\.\d*/,""),e);let n=r[1]||"",s=r[2]?parseInt(r[2],10):0,i=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,a=e<0,o=Math.abs(e),c=String(o);i>=0&&(c=c.padStart(i,"0"));let l="";a?l="-":n.includes("+")?l="+":n.includes(" ")&&(l=" ");let u=l+c;return s>u.length&&(n.includes("-")?u=u.padEnd(s," "):n.includes("0")&&i<0?u=l+c.padStart(s-l.length,"0"):u=u.padStart(s," ")),u}function Rl(t,e){let r=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?o$/);if(!r)return lt(t,e);let n=r[1]||"",s=r[2]?parseInt(r[2],10):0,i=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,a=Math.abs(e).toString(8);i>=0&&(a=a.padStart(i,"0")),n.includes("#")&&!a.startsWith("0")&&(a=`0${a}`);let o=a;return s>o.length&&(n.includes("-")?o=o.padEnd(s," "):n.includes("0")&&i<0?o=o.padStart(s,"0"):o=o.padStart(s," ")),o}function Pl(t,e){let r=t.includes("X"),n=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[xX]$/);if(!n)return lt(t,e);let s=n[1]||"",i=n[2]?parseInt(n[2],10):0,a=n[3]!==void 0?n[4]?parseInt(n[4],10):0:-1,o=Math.abs(e).toString(16);r&&(o=o.toUpperCase()),a>=0&&(o=o.padStart(a,"0"));let c="";s.includes("#")&&e!==0&&(c=r?"0X":"0x");let l=c+o;return i>l.length&&(s.includes("-")?l=l.padEnd(i," "):s.includes("0")&&a<0?l=c+o.padStart(i-c.length,"0"):l=l.padStart(i," ")),l}function Ol(t){if(t==="")return"''";if(/^[a-zA-Z0-9_./-]+$/.test(t))return t;if(/[\x00-\x1f\x7f]/.test(t)){let n="$'";for(let s of t){let i=s.charCodeAt(0);s==="'"?n+="\\'":s==="\\"?n+="\\\\":s===`
38
+ `?n+="\\n":s===" "?n+="\\t":s==="\r"?n+="\\r":s==="\x07"?n+="\\a":s==="\b"?n+="\\b":s==="\f"?n+="\\f":s==="\v"?n+="\\v":s==="\x1B"?n+="\\E":i<32||i>126?n+=`\\x${i.toString(16).padStart(2,"0")}`:s==='"'?n+='\\"':n+=s}return n+="'",n}let r="";for(let n of t)" |&;<>()$`\\\"'*?[#~=%!{}".includes(n)?r+=`\\${n}`:r+=n;return r}function Dl(t,e){let r=t.match(/^%(-?)(\d*)(\.(\d*))?s$/);if(!r)return lt(t.replace(/0+(?=\d)/,""),e);let n=r[1]==="-",s=r[2]?parseInt(r[2],10):0,i=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,a=n?-s:s;return _t(e,a,i)}function Tl(t,e){let r=Ol(e),n=t.match(/^%(-?)(\d*)q$/);if(!n)return r;let s=n[1]==="-",i=n[2]?parseInt(n[2],10):0,a=r;return i>a.length&&(s?a=a.padEnd(i," "):a=a.padStart(i," ")),a}function Ll(t,e,r){let n=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[eEfFgG]$/);if(!n)return lt(t,r);let s=n[1]||"",i=n[2]?parseInt(n[2],10):0,a=n[3]!==void 0?n[4]?parseInt(n[4],10):0:6,o,c=e.toLowerCase();if(c==="e"?(o=r.toExponential(a),o=o.replace(/e([+-])(\d)$/,"e$10$2"),e==="E"&&(o=o.toUpperCase())):c==="f"?(o=r.toFixed(a),s.includes("#")&&a===0&&!o.includes(".")&&(o+=".")):c==="g"?(o=r.toPrecision(a||1),s.includes("#")||(o=o.replace(/\.?0+$/,""),o=o.replace(/\.?0+e/,"e")),o=o.replace(/e([+-])(\d)$/,"e$10$2"),e==="G"&&(o=o.toUpperCase())):o=r.toString(),r>=0&&(s.includes("+")?o=`+${o}`:s.includes(" ")&&(o=` ${o}`)),i>o.length)if(s.includes("-"))o=o.padEnd(i," ");else if(s.includes("0")){let l=o.match(/^[+ -]/)?.[0]||"",u=l?o.slice(1):o;o=l+u.padStart(i-l.length,"0")}else o=o.padStart(i," ");return o}function Fl(t){let e="",r=0;for(;r<t.length;)if(t[r]==="\\"&&r+1<t.length)switch(t[r+1]){case"n":e+=`
39
+ `,r+=2;break;case"t":e+=" ",r+=2;break;case"r":e+="\r",r+=2;break;case"\\":e+="\\",r+=2;break;case"a":e+="\x07",r+=2;break;case"b":e+="\b",r+=2;break;case"f":e+="\f",r+=2;break;case"v":e+="\v",r+=2;break;case"c":return{value:e,stopped:!0};case"x":{let s="",i=r+2;for(;i<t.length&&i<r+4&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;s?(e+=String.fromCharCode(parseInt(s,16)),r=i):(e+="\\x",r+=2);break}case"u":{let s="",i=r+2;for(;i<t.length&&i<r+6&&/[0-9a-fA-F]/.test(t[i]);)s+=t[i],i++;s?(e+=String.fromCodePoint(parseInt(s,16)),r=i):(e+="\\u",r+=2);break}case"0":{let s="",i=r+2;for(;i<t.length&&i<r+5&&/[0-7]/.test(t[i]);)s+=t[i],i++;s?e+=String.fromCharCode(parseInt(s,8)):e+="\0",r=i;break}case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let s="",i=r+1;for(;i<t.length&&i<r+4&&/[0-7]/.test(t[i]);)s+=t[i],i++;e+=String.fromCharCode(parseInt(s,8)),r=i;break}default:e+=t[r],r++}else e+=t[r],r++;return{value:e,stopped:!1}}var vl,kl,$e,hs=v(()=>{"use strict";Ie();F();Or();vl={name:"printf",summary:"format and print data",usage:"printf [-v var] FORMAT [ARGUMENT...]",options:[" -v var assign the output to shell variable VAR rather than display it"," --help display this help and exit"],notes:["FORMAT controls the output like in C printf.","Escape sequences: \\n (newline), \\t (tab), \\\\ (backslash)","Format specifiers: %s (string), %d (integer), %f (float), %x (hex), %o (octal), %% (literal %)","Width and precision: %10s (width 10), %.2f (2 decimal places), %010d (zero-padded)","Flags: %- (left-justify), %+ (show sign), %0 (zero-pad)"]},kl={name:"printf",async execute(t,e){if(N(t))return C(vl);if(t.length===0)return{stdout:"",stderr:`printf: usage: printf format [arguments]
40
40
  `,exitCode:2};let r=null,n=0;for(;n<t.length;){let a=t[n];if(a==="--"){n++;break}if(a==="-v"){if(n+1>=t.length)return{stdout:"",stderr:`printf: -v: option requires an argument
41
41
  `,exitCode:1};if(r=t[n+1],!/^[a-zA-Z_][a-zA-Z0-9_]*(\[[^\]]+\])?$/.test(r))return{stdout:"",stderr:`printf: \`${r}': not a valid identifier
42
42
  `,exitCode:2};n+=2}else{if(a.startsWith("-")&&a!=="-")break;break}}if(n>=t.length)return{stdout:"",stderr:`printf: usage: printf format [arguments]
43
- `,exitCode:1};let s=t[n],i=t.slice(n+1);try{let a=Cl(s),o="",c=0,l=!1,u="";do{let{result:f,argsConsumed:d,error:h,errMsg:p,stopped:b}=Nl(a,i,c);if(o+=f,c+=d,h&&(l=!0,p&&(u=p)),b)break}while(c<i.length&&c>0);return c===0&&i.length>0,r?(e.env[r]=o,{stdout:"",stderr:u,exitCode:l?1:0}):{stdout:o,stderr:u,exitCode:l?1:0}}catch(a){return{stdout:"",stderr:`printf: ${Y(a)}
44
- `,exitCode:1}}}};Ie=!1});var ds={};O(ds,{lsCommand:()=>Fl});import{minimatch as us}from"minimatch";function Mt(t){if(t<1024)return String(t);if(t<1024*1024){let r=t/1024;return r<10?`${r.toFixed(1)}K`:`${Math.round(r)}K`}if(t<1024*1024*1024){let r=t/1048576;return r<10?`${r.toFixed(1)}M`:`${Math.round(r)}M`}let e=t/(1024*1024*1024);return e<10?`${e.toFixed(1)}G`:`${Math.round(e)}G`}function _t(t){let r=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()],n=String(t.getDate()).padStart(2," "),s=new Date,i=new Date(s.getTime()-4320*60*60*1e3);if(t>i){let o=String(t.getHours()).padStart(2,"0"),c=String(t.getMinutes()).padStart(2,"0");return`${r} ${n} ${o}:${c}`}let a=t.getFullYear();return`${r} ${n} ${a}`}async function Ml(t,e,r,n,s,i=!1,a=!1,o=!1){let c=r||n,l=e.fs.getAllPaths(),u=e.fs.resolvePath(e.cwd,"."),f=[];for(let d of l){let h=d.startsWith(u)&&d.slice(u.length+1)||d;if(us(h,t)||us(d,t)){let p=h.split("/").pop()||h;if(!c&&p.startsWith("."))continue;f.push(h||d)}}if(f.length===0)return{stdout:"",stderr:`ls: ${t}: No such file or directory
45
- `,exitCode:2};if(o){let d=[];for(let h of f){let p=e.fs.resolvePath(e.cwd,h);try{let b=await e.fs.stat(p);d.push({path:h,size:b.size??0})}catch{d.push({path:h,size:0})}}d.sort((h,p)=>p.size-h.size),f.length=0,f.push(...d.map(h=>h.path))}else f.sort();if(i&&f.reverse(),s){let d=[];for(let h of f){let p=e.fs.resolvePath(e.cwd,h);try{let b=await e.fs.stat(p),w=b.isDirectory?"drwxr-xr-x":"-rw-r--r--",g=b.isDirectory?"/":"",E=b.size??0,x=a?Mt(E).padStart(5):String(E).padStart(5),S=b.mtime??new Date(0),v=_t(S);d.push(`${w} 1 user user ${x} ${v} ${h}${g}`)}catch{d.push(`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${h}`)}}return{stdout:`${d.join(`
43
+ `,exitCode:1};let s=t[n],i=t.slice(n+1);try{let a=Wt(s),o="",c=0,l=!1,u="";do{let{result:f,argsConsumed:d,error:h,errMsg:p,stopped:E}=Il(a,i,c);if(o+=f,c+=d,h&&(l=!0,p&&(u=p)),E)break}while(c<i.length&&c>0);return c===0&&i.length>0,r?(e.env[r]=o,{stdout:"",stderr:u,exitCode:l?1:0}):{stdout:o,stderr:u,exitCode:l?1:0}}catch(a){return{stdout:"",stderr:`printf: ${J(a)}
44
+ `,exitCode:1}}}};$e=!1});var ys={};D(ys,{lsCommand:()=>Wl});import{minimatch as ps}from"minimatch";function Ht(t){if(t<1024)return String(t);if(t<1024*1024){let r=t/1024;return r<10?`${r.toFixed(1)}K`:`${Math.round(r)}K`}if(t<1024*1024*1024){let r=t/1048576;return r<10?`${r.toFixed(1)}M`:`${Math.round(r)}M`}let e=t/(1024*1024*1024);return e<10?`${e.toFixed(1)}G`:`${Math.round(e)}G`}function Ut(t){let r=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"][t.getMonth()],n=String(t.getDate()).padStart(2," "),s=new Date,i=new Date(s.getTime()-4320*60*60*1e3);if(t>i){let o=String(t.getHours()).padStart(2,"0"),c=String(t.getMinutes()).padStart(2,"0");return`${r} ${n} ${o}:${c}`}let a=t.getFullYear();return`${r} ${n} ${a}`}async function Bl(t,e,r,n,s,i=!1,a=!1,o=!1){let c=r||n,l=e.fs.getAllPaths(),u=e.fs.resolvePath(e.cwd,"."),f=[];for(let d of l){let h=d.startsWith(u)&&d.slice(u.length+1)||d;if(ps(h,t)||ps(d,t)){let p=h.split("/").pop()||h;if(!c&&p.startsWith("."))continue;f.push(h||d)}}if(f.length===0)return{stdout:"",stderr:`ls: ${t}: No such file or directory
45
+ `,exitCode:2};if(o){let d=[];for(let h of f){let p=e.fs.resolvePath(e.cwd,h);try{let E=await e.fs.stat(p);d.push({path:h,size:E.size??0})}catch{d.push({path:h,size:0})}}d.sort((h,p)=>p.size-h.size),f.length=0,f.push(...d.map(h=>h.path))}else f.sort();if(i&&f.reverse(),s){let d=[];for(let h of f){let p=e.fs.resolvePath(e.cwd,h);try{let E=await e.fs.stat(p),w=E.isDirectory?"drwxr-xr-x":"-rw-r--r--",g=E.isDirectory?"/":"",b=E.size??0,S=a?Ht(b).padStart(5):String(b).padStart(5),x=E.mtime??new Date(0),A=Ut(x);d.push(`${w} 1 user user ${S} ${A} ${h}${g}`)}catch{d.push(`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${h}`)}}return{stdout:`${d.join(`
46
46
  `)}
47
47
  `,stderr:"",exitCode:0}}return{stdout:`${f.join(`
48
48
  `)}
49
- `,stderr:"",exitCode:0}}async function fs(t,e,r,n,s,i,a,o=!1,c=!1,l=!1,u=!1){let f=r||n,d=e.fs.resolvePath(e.cwd,t);try{let h=await e.fs.stat(d);if(!h.isDirectory){if(s){let w=h.size??0,g=c?Mt(w).padStart(5):String(w).padStart(5),E=h.mtime??new Date(0),x=_t(E);return{stdout:`-rw-r--r-- 1 user user ${g} ${x} ${t}
49
+ `,stderr:"",exitCode:0}}async function ms(t,e,r,n,s,i,a,o=!1,c=!1,l=!1,u=!1){let f=r||n,d=e.fs.resolvePath(e.cwd,t);try{let h=await e.fs.stat(d);if(!h.isDirectory){if(s){let w=h.size??0,g=c?Ht(w).padStart(5):String(w).padStart(5),b=h.mtime??new Date(0),S=Ut(b);return{stdout:`-rw-r--r-- 1 user user ${g} ${S} ${t}
50
50
  `,stderr:"",exitCode:0}}return{stdout:`${t}
51
- `,stderr:"",exitCode:0}}let p=await e.fs.readdir(d);if(f||(p=p.filter(w=>!w.startsWith("."))),l){let w=[];for(let g of p){let E=d==="/"?`/${g}`:`${d}/${g}`;try{let x=await e.fs.stat(E);w.push({name:g,size:x.size??0})}catch{w.push({name:g,size:0})}}w.sort((g,E)=>E.size-g.size),p=w.map(g=>g.name)}else p.sort();r&&(p=[".","..",...p]),o&&p.reverse();let b="";if((i||a)&&(b+=`${t}:
52
- `),s){b+=`total ${p.length}
53
- `;for(let w of p){if(w==="."||w===".."){b+=`drwxr-xr-x 1 user user 0 Jan 1 00:00 ${w}
54
- `;continue}let g=d==="/"?`/${w}`:`${d}/${w}`;try{let E=await e.fs.stat(g),x=E.isDirectory?"drwxr-xr-x":"-rw-r--r--",S=E.isDirectory?"/":"",v=E.size??0,R=c?Mt(v).padStart(5):String(v).padStart(5),M=E.mtime??new Date(0),_=_t(M);b+=`${x} 1 user user ${R} ${_} ${w}${S}
55
- `}catch{b+=`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${w}
56
- `}}}else b+=p.join(`
51
+ `,stderr:"",exitCode:0}}let p=await e.fs.readdir(d);if(f||(p=p.filter(w=>!w.startsWith("."))),l){let w=[];for(let g of p){let b=d==="/"?`/${g}`:`${d}/${g}`;try{let S=await e.fs.stat(b);w.push({name:g,size:S.size??0})}catch{w.push({name:g,size:0})}}w.sort((g,b)=>b.size-g.size),p=w.map(g=>g.name)}else p.sort();r&&(p=[".","..",...p]),o&&p.reverse();let E="";if((i||a)&&(E+=`${t}:
52
+ `),s){E+=`total ${p.length}
53
+ `;for(let w of p){if(w==="."||w===".."){E+=`drwxr-xr-x 1 user user 0 Jan 1 00:00 ${w}
54
+ `;continue}let g=d==="/"?`/${w}`:`${d}/${w}`;try{let b=await e.fs.stat(g),S=b.isDirectory?"drwxr-xr-x":"-rw-r--r--",x=b.isDirectory?"/":"",A=b.size??0,O=c?Ht(A).padStart(5):String(A).padStart(5),L=b.mtime??new Date(0),R=Ut(L);E+=`${S} 1 user user ${O} ${R} ${w}${x}
55
+ `}catch{E+=`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${w}
56
+ `}}}else E+=p.join(`
57
57
  `)+(p.length?`
58
- `:"");if(i)for(let w of p){if(w==="."||w==="..")continue;let g=d==="/"?`/${w}`:`${d}/${w}`;try{if((await e.fs.stat(g)).isDirectory){b+=`
59
- `;let x=t==="."?`./${w}`:`${t}/${w}`,S=await fs(x,e,r,n,s,i,!1,o,c,l,!0);b+=S.stdout}}catch{}}return{stdout:b,stderr:"",exitCode:0}}catch{return{stdout:"",stderr:`ls: ${t}: No such file or directory
60
- `,exitCode:2}}}var Ll,Tl,Fl,hs=N(()=>{"use strict";ae();L();Ll={name:"ls",summary:"list directory contents",usage:"ls [OPTION]... [FILE]...",options:["-a, --all do not ignore entries starting with .","-A, --almost-all do not list . and ..","-d, --directory list directories themselves, not their contents","-h, --human-readable with -l, print sizes like 1K 234M 2G etc.","-l use a long listing format","-r, --reverse reverse order while sorting","-R, --recursive list subdirectories recursively","-S sort by file size, largest first","-t sort by time, newest first","-1 list one file per line"," --help display this help and exit"]},Tl={showAll:{short:"a",long:"all",type:"boolean"},showAlmostAll:{short:"A",long:"almost-all",type:"boolean"},longFormat:{short:"l",type:"boolean"},humanReadable:{short:"h",long:"human-readable",type:"boolean"},recursive:{short:"R",long:"recursive",type:"boolean"},reverse:{short:"r",long:"reverse",type:"boolean"},sortBySize:{short:"S",type:"boolean"},directoryOnly:{short:"d",long:"directory",type:"boolean"},sortByTime:{short:"t",type:"boolean"},onePerLine:{short:"1",type:"boolean"}},Fl={name:"ls",async execute(t,e){if(C(t))return A(Ll);let r=H("ls",t,Tl);if(!r.ok)return r.error;let n=r.result.flags.showAll,s=r.result.flags.showAlmostAll,i=r.result.flags.longFormat,a=r.result.flags.humanReadable,o=r.result.flags.recursive,c=r.result.flags.reverse,l=r.result.flags.sortBySize,u=r.result.flags.directoryOnly,f=r.result.flags.sortByTime;r.result.flags.onePerLine;let d=r.result.positional;d.length===0&&d.push(".");let h="",p="",b=0;for(let w=0;w<d.length;w++){let g=d[w];if(w>0&&h&&!h.endsWith(`
58
+ `:"");if(i)for(let w of p){if(w==="."||w==="..")continue;let g=d==="/"?`/${w}`:`${d}/${w}`;try{if((await e.fs.stat(g)).isDirectory){E+=`
59
+ `;let S=t==="."?`./${w}`:`${t}/${w}`,x=await ms(S,e,r,n,s,i,!1,o,c,l,!0);E+=x.stdout}}catch{}}return{stdout:E,stderr:"",exitCode:0}}catch{return{stdout:"",stderr:`ls: ${t}: No such file or directory
60
+ `,exitCode:2}}}var Ml,_l,Wl,gs=v(()=>{"use strict";oe();F();Ml={name:"ls",summary:"list directory contents",usage:"ls [OPTION]... [FILE]...",options:["-a, --all do not ignore entries starting with .","-A, --almost-all do not list . and ..","-d, --directory list directories themselves, not their contents","-h, --human-readable with -l, print sizes like 1K 234M 2G etc.","-l use a long listing format","-r, --reverse reverse order while sorting","-R, --recursive list subdirectories recursively","-S sort by file size, largest first","-t sort by time, newest first","-1 list one file per line"," --help display this help and exit"]},_l={showAll:{short:"a",long:"all",type:"boolean"},showAlmostAll:{short:"A",long:"almost-all",type:"boolean"},longFormat:{short:"l",type:"boolean"},humanReadable:{short:"h",long:"human-readable",type:"boolean"},recursive:{short:"R",long:"recursive",type:"boolean"},reverse:{short:"r",long:"reverse",type:"boolean"},sortBySize:{short:"S",type:"boolean"},directoryOnly:{short:"d",long:"directory",type:"boolean"},sortByTime:{short:"t",type:"boolean"},onePerLine:{short:"1",type:"boolean"}},Wl={name:"ls",async execute(t,e){if(N(t))return C(Ml);let r=G("ls",t,_l);if(!r.ok)return r.error;let n=r.result.flags.showAll,s=r.result.flags.showAlmostAll,i=r.result.flags.longFormat,a=r.result.flags.humanReadable,o=r.result.flags.recursive,c=r.result.flags.reverse,l=r.result.flags.sortBySize,u=r.result.flags.directoryOnly,f=r.result.flags.sortByTime;r.result.flags.onePerLine;let d=r.result.positional;d.length===0&&d.push(".");let h="",p="",E=0;for(let w=0;w<d.length;w++){let g=d[w];if(w>0&&h&&!h.endsWith(`
61
61
 
62
62
  `)&&(h+=`
63
- `),u){let E=e.fs.resolvePath(e.cwd,g);try{let x=await e.fs.stat(E);if(i){let S=x.isDirectory?"drwxr-xr-x":"-rw-r--r--",v=x.isDirectory?"/":"",R=x.size??0,M=a?Mt(R).padStart(5):String(R).padStart(5),_=x.mtime??new Date(0),Oe=_t(_);h+=`${S} 1 user user ${M} ${Oe} ${g}${v}
63
+ `),u){let b=e.fs.resolvePath(e.cwd,g);try{let S=await e.fs.stat(b);if(i){let x=S.isDirectory?"drwxr-xr-x":"-rw-r--r--",A=S.isDirectory?"/":"",O=S.size??0,L=a?Ht(O).padStart(5):String(O).padStart(5),R=S.mtime??new Date(0),U=Ut(R);h+=`${x} 1 user user ${L} ${U} ${g}${A}
64
64
  `}else h+=`${g}
65
65
  `}catch{p+=`ls: cannot access '${g}': No such file or directory
66
- `,b=2}continue}if(g.includes("*")||g.includes("?")||g.includes("[")){let E=await Ml(g,e,n,s,i,c,a,l);h+=E.stdout,p+=E.stderr,E.exitCode!==0&&(b=E.exitCode)}else{let E=await fs(g,e,n,s,i,o,d.length>1,c,a,l);h+=E.stdout,p+=E.stderr,E.exitCode!==0&&(b=E.exitCode)}}return{stdout:h,stderr:p,exitCode:b}}}});var ps={};O(ps,{mkdirCommand:()=>Wl});var _l,Wl,ms=N(()=>{"use strict";ke();ae();_l={recursive:{short:"p",long:"parents",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},Wl={name:"mkdir",async execute(t,e){let r=H("mkdir",t,_l);if(!r.ok)return r.error;let n=r.result.flags.recursive,s=r.result.flags.verbose,i=r.result.positional;if(i.length===0)return{stdout:"",stderr:`mkdir: missing operand
66
+ `,E=2}continue}if(g.includes("*")||g.includes("?")||g.includes("[")){let b=await Bl(g,e,n,s,i,c,a,l);h+=b.stdout,p+=b.stderr,b.exitCode!==0&&(E=b.exitCode)}else{let b=await ms(g,e,n,s,i,o,d.length>1,c,a,l);h+=b.stdout,p+=b.stderr,b.exitCode!==0&&(E=b.exitCode)}}return{stdout:h,stderr:p,exitCode:E}}}});var ws={};D(ws,{mkdirCommand:()=>Ul});var Hl,Ul,Es=v(()=>{"use strict";Ie();oe();Hl={recursive:{short:"p",long:"parents",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},Ul={name:"mkdir",async execute(t,e){let r=G("mkdir",t,Hl);if(!r.ok)return r.error;let n=r.result.flags.recursive,s=r.result.flags.verbose,i=r.result.positional;if(i.length===0)return{stdout:"",stderr:`mkdir: missing operand
67
67
  `,exitCode:1};let a="",o="",c=0;for(let l of i)try{let u=e.fs.resolvePath(e.cwd,l);await e.fs.mkdir(u,{recursive:n}),s&&(a+=`mkdir: created directory '${l}'
68
- `)}catch(u){let f=Y(u);f.includes("ENOENT")||f.includes("no such file")?o+=`mkdir: cannot create directory '${l}': No such file or directory
68
+ `)}catch(u){let f=J(u);f.includes("ENOENT")||f.includes("no such file")?o+=`mkdir: cannot create directory '${l}': No such file or directory
69
69
  `:f.includes("EEXIST")||f.includes("already exists")?o+=`mkdir: cannot create directory '${l}': File exists
70
70
  `:o+=`mkdir: cannot create directory '${l}': ${f}
71
- `,c=1}return{stdout:a,stderr:o,exitCode:c}}}});var ys={};O(ys,{touchCommand:()=>Bl});var Bl,gs=N(()=>{"use strict";ke();L();Bl={name:"touch",async execute(t,e){let r=[];for(let i of t){if(i.startsWith("--"))return T("touch",i);if(i.startsWith("-")&&i.length>1)return T("touch",i);r.push(i)}if(r.length===0)return{stdout:"",stderr:`touch: missing file operand
72
- `,exitCode:1};let n="",s=0;for(let i of r)try{let a=e.fs.resolvePath(e.cwd,i);await e.fs.exists(a)||await e.fs.writeFile(a,"")}catch(a){n+=`touch: cannot touch '${i}': ${Y(a)}
73
- `,s=1}return{stdout:"",stderr:n,exitCode:s}}}});var ws={};O(ws,{rmCommand:()=>Ul});var Hl,Ul,Es=N(()=>{"use strict";ke();ae();Hl={recursive:{short:"r",long:"recursive",type:"boolean"},recursiveUpper:{short:"R",type:"boolean"},force:{short:"f",long:"force",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},Ul={name:"rm",async execute(t,e){let r=H("rm",t,Hl);if(!r.ok)return r.error;let n=r.result.flags.recursive||r.result.flags.recursiveUpper,s=r.result.flags.force,i=r.result.flags.verbose,a=r.result.positional;if(a.length===0)return s?{stdout:"",stderr:"",exitCode:0}:{stdout:"",stderr:`rm: missing operand
71
+ `,c=1}return{stdout:a,stderr:o,exitCode:c}}}});var bs={};D(bs,{touchCommand:()=>zl});var zl,Ss=v(()=>{"use strict";Ie();F();zl={name:"touch",async execute(t,e){let r=[];for(let i of t){if(i.startsWith("--"))return M("touch",i);if(i.startsWith("-")&&i.length>1)return M("touch",i);r.push(i)}if(r.length===0)return{stdout:"",stderr:`touch: missing file operand
72
+ `,exitCode:1};let n="",s=0;for(let i of r)try{let a=e.fs.resolvePath(e.cwd,i);await e.fs.exists(a)||await e.fs.writeFile(a,"")}catch(a){n+=`touch: cannot touch '${i}': ${J(a)}
73
+ `,s=1}return{stdout:"",stderr:n,exitCode:s}}}});var xs={};D(xs,{rmCommand:()=>jl});var Gl,jl,As=v(()=>{"use strict";Ie();oe();Gl={recursive:{short:"r",long:"recursive",type:"boolean"},recursiveUpper:{short:"R",type:"boolean"},force:{short:"f",long:"force",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},jl={name:"rm",async execute(t,e){let r=G("rm",t,Gl);if(!r.ok)return r.error;let n=r.result.flags.recursive||r.result.flags.recursiveUpper,s=r.result.flags.force,i=r.result.flags.verbose,a=r.result.positional;if(a.length===0)return s?{stdout:"",stderr:"",exitCode:0}:{stdout:"",stderr:`rm: missing operand
74
74
  `,exitCode:1};let o="",c="",l=0;for(let u of a)try{let f=e.fs.resolvePath(e.cwd,u);if((await e.fs.stat(f)).isDirectory&&!n){c+=`rm: cannot remove '${u}': Is a directory
75
75
  `,l=1;continue}await e.fs.rm(f,{recursive:n,force:s}),i&&(o+=`removed '${u}'
76
- `)}catch(f){if(!s){let d=Y(f);d.includes("ENOENT")||d.includes("no such file")?c+=`rm: cannot remove '${u}': No such file or directory
76
+ `)}catch(f){if(!s){let d=J(f);d.includes("ENOENT")||d.includes("no such file")?c+=`rm: cannot remove '${u}': No such file or directory
77
77
  `:d.includes("ENOTEMPTY")||d.includes("not empty")?c+=`rm: cannot remove '${u}': Directory not empty
78
78
  `:c+=`rm: cannot remove '${u}': ${d}
79
- `,l=1}}return{stdout:o,stderr:c,exitCode:l}}}});var bs={};O(bs,{cpCommand:()=>jl});var zl,Gl,jl,xs=N(()=>{"use strict";ke();ae();L();zl={name:"cp",summary:"copy files and directories",usage:"cp [OPTION]... SOURCE... DEST",options:["-r, -R, --recursive copy directories recursively","-n, --no-clobber do not overwrite an existing file","-p, --preserve preserve file attributes","-v, --verbose explain what is being done"," --help display this help and exit"]},Gl={recursive:{short:"r",long:"recursive",type:"boolean"},recursiveUpper:{short:"R",type:"boolean"},noClobber:{short:"n",long:"no-clobber",type:"boolean"},preserve:{short:"p",long:"preserve",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},jl={name:"cp",async execute(t,e){if(C(t))return A(zl);let r=H("cp",t,Gl);if(!r.ok)return r.error;let n=r.result.flags.recursive||r.result.flags.recursiveUpper,s=r.result.flags.noClobber,i=r.result.flags.preserve,a=r.result.flags.verbose,o=r.result.positional;if(o.length<2)return{stdout:"",stderr:`cp: missing destination file operand
79
+ `,l=1}}return{stdout:o,stderr:c,exitCode:l}}}});var Cs={};D(Cs,{cpCommand:()=>Zl});var ql,Vl,Zl,Ns=v(()=>{"use strict";Ie();oe();F();ql={name:"cp",summary:"copy files and directories",usage:"cp [OPTION]... SOURCE... DEST",options:["-r, -R, --recursive copy directories recursively","-n, --no-clobber do not overwrite an existing file","-p, --preserve preserve file attributes","-v, --verbose explain what is being done"," --help display this help and exit"]},Vl={recursive:{short:"r",long:"recursive",type:"boolean"},recursiveUpper:{short:"R",type:"boolean"},noClobber:{short:"n",long:"no-clobber",type:"boolean"},preserve:{short:"p",long:"preserve",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},Zl={name:"cp",async execute(t,e){if(N(t))return C(ql);let r=G("cp",t,Vl);if(!r.ok)return r.error;let n=r.result.flags.recursive||r.result.flags.recursiveUpper,s=r.result.flags.noClobber,i=r.result.flags.preserve,a=r.result.flags.verbose,o=r.result.positional;if(o.length<2)return{stdout:"",stderr:`cp: missing destination file operand
80
80
  `,exitCode:1};let c=o.pop()??"",l=o,u=e.fs.resolvePath(e.cwd,c),f="",d="",h=0,p=!1;try{p=(await e.fs.stat(u)).isDirectory}catch{}if(l.length>1&&!p)return{stdout:"",stderr:`cp: target '${c}' is not a directory
81
- `,exitCode:1};for(let b of l)try{let w=e.fs.resolvePath(e.cwd,b),g=await e.fs.stat(w),E=u;if(p){let x=b.split("/").pop()||b;E=u==="/"?`/${x}`:`${u}/${x}`}if(g.isDirectory&&!n){d+=`cp: -r not specified; omitting directory '${b}'
82
- `,h=1;continue}if(s)try{await e.fs.stat(E);continue}catch{}await e.fs.cp(w,E,{recursive:n}),a&&(f+=`'${b}' -> '${E}'
83
- `)}catch(w){let g=Y(w);g.includes("ENOENT")||g.includes("no such file")?d+=`cp: cannot stat '${b}': No such file or directory
84
- `:d+=`cp: cannot copy '${b}': ${g}
85
- `,h=1}return{stdout:f,stderr:d,exitCode:h}}}});var Ss={};O(Ss,{mvCommand:()=>Zl});var ql,Vl,Zl,As=N(()=>{"use strict";ke();ae();L();ql={name:"mv",summary:"move (rename) files",usage:"mv [OPTION]... SOURCE... DEST",options:["-f, --force do not prompt before overwriting","-n, --no-clobber do not overwrite an existing file","-v, --verbose explain what is being done"," --help display this help and exit"]},Vl={force:{short:"f",long:"force",type:"boolean"},noClobber:{short:"n",long:"no-clobber",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},Zl={name:"mv",async execute(t,e){if(C(t))return A(ql);let r=H("mv",t,Vl);if(!r.ok)return r.error;let n=r.result.flags.force,s=r.result.flags.noClobber,i=r.result.flags.verbose,a=r.result.positional;if(s&&(n=!1),a.length<2)return{stdout:"",stderr:`mv: missing destination file operand
81
+ `,exitCode:1};for(let E of l)try{let w=e.fs.resolvePath(e.cwd,E),g=await e.fs.stat(w),b=u;if(p){let S=E.split("/").pop()||E;b=u==="/"?`/${S}`:`${u}/${S}`}if(g.isDirectory&&!n){d+=`cp: -r not specified; omitting directory '${E}'
82
+ `,h=1;continue}if(s)try{await e.fs.stat(b);continue}catch{}await e.fs.cp(w,b,{recursive:n}),a&&(f+=`'${E}' -> '${b}'
83
+ `)}catch(w){let g=J(w);g.includes("ENOENT")||g.includes("no such file")?d+=`cp: cannot stat '${E}': No such file or directory
84
+ `:d+=`cp: cannot copy '${E}': ${g}
85
+ `,h=1}return{stdout:f,stderr:d,exitCode:h}}}});var vs={};D(vs,{mvCommand:()=>Xl});var Ql,Kl,Xl,ks=v(()=>{"use strict";Ie();oe();F();Ql={name:"mv",summary:"move (rename) files",usage:"mv [OPTION]... SOURCE... DEST",options:["-f, --force do not prompt before overwriting","-n, --no-clobber do not overwrite an existing file","-v, --verbose explain what is being done"," --help display this help and exit"]},Kl={force:{short:"f",long:"force",type:"boolean"},noClobber:{short:"n",long:"no-clobber",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},Xl={name:"mv",async execute(t,e){if(N(t))return C(Ql);let r=G("mv",t,Kl);if(!r.ok)return r.error;let n=r.result.flags.force,s=r.result.flags.noClobber,i=r.result.flags.verbose,a=r.result.positional;if(s&&(n=!1),a.length<2)return{stdout:"",stderr:`mv: missing destination file operand
86
86
  `,exitCode:1};let o=a.pop()??"",c=a,l=e.fs.resolvePath(e.cwd,o),u="",f="",d=0,h=!1;try{h=(await e.fs.stat(l)).isDirectory}catch{}if(c.length>1&&!h)return{stdout:"",stderr:`mv: target '${o}' is not a directory
87
- `,exitCode:1};for(let p of c)try{let b=e.fs.resolvePath(e.cwd,p),w=l;if(h){let g=p.split("/").pop()||p;w=l==="/"?`/${g}`:`${l}/${g}`}if(s)try{await e.fs.stat(w);continue}catch{}if(await e.fs.mv(b,w),i){let g=h?`${o}/${p.split("/").pop()||p}`:o;u+=`renamed '${p}' -> '${g}'
88
- `}}catch(b){let w=Y(b);w.includes("ENOENT")||w.includes("no such file")?f+=`mv: cannot stat '${p}': No such file or directory
87
+ `,exitCode:1};for(let p of c)try{let E=e.fs.resolvePath(e.cwd,p),w=l;if(h){let g=p.split("/").pop()||p;w=l==="/"?`/${g}`:`${l}/${g}`}if(s)try{await e.fs.stat(w);continue}catch{}if(await e.fs.mv(E,w),i){let g=h?`${o}/${p.split("/").pop()||p}`:o;u+=`renamed '${p}' -> '${g}'
88
+ `}}catch(E){let w=J(E);w.includes("ENOENT")||w.includes("no such file")?f+=`mv: cannot stat '${p}': No such file or directory
89
89
  `:f+=`mv: cannot move '${p}': ${w}
90
- `,d=1}return{stdout:u,stderr:f,exitCode:d}}}});var Cs={};O(Cs,{lnCommand:()=>Kl});var Ql,Kl,Ns=N(()=>{"use strict";L();Ql={name:"ln",summary:"make links between files",usage:"ln [OPTIONS] TARGET LINK_NAME",options:["-s create a symbolic link instead of a hard link","-f remove existing destination files","-n treat LINK_NAME as a normal file if it is a symbolic link to a directory","-v print name of each linked file"," --help display this help and exit"]},Kl={name:"ln",async execute(t,e){if(C(t))return A(Ql);let r=!1,n=!1,s=!1,i=0;for(;i<t.length&&t[i].startsWith("-");){let f=t[i];if(f==="-s"||f==="--symbolic")r=!0,i++;else if(f==="-f"||f==="--force")n=!0,i++;else if(f==="-v"||f==="--verbose")s=!0,i++;else if(f==="-n"||f==="--no-dereference")i++;else if(/^-[sfvn]+$/.test(f))f.includes("s")&&(r=!0),f.includes("f")&&(n=!0),f.includes("v")&&(s=!0),i++;else if(f==="--"){i++;break}else return{stdout:"",stderr:`ln: invalid option -- '${f.slice(1)}'
90
+ `,d=1}return{stdout:u,stderr:f,exitCode:d}}}});var Is={};D(Is,{lnCommand:()=>Jl});var Yl,Jl,$s=v(()=>{"use strict";F();Yl={name:"ln",summary:"make links between files",usage:"ln [OPTIONS] TARGET LINK_NAME",options:["-s create a symbolic link instead of a hard link","-f remove existing destination files","-n treat LINK_NAME as a normal file if it is a symbolic link to a directory","-v print name of each linked file"," --help display this help and exit"]},Jl={name:"ln",async execute(t,e){if(N(t))return C(Yl);let r=!1,n=!1,s=!1,i=0;for(;i<t.length&&t[i].startsWith("-");){let f=t[i];if(f==="-s"||f==="--symbolic")r=!0,i++;else if(f==="-f"||f==="--force")n=!0,i++;else if(f==="-v"||f==="--verbose")s=!0,i++;else if(f==="-n"||f==="--no-dereference")i++;else if(/^-[sfvn]+$/.test(f))f.includes("s")&&(r=!0),f.includes("f")&&(n=!0),f.includes("v")&&(s=!0),i++;else if(f==="--"){i++;break}else return{stdout:"",stderr:`ln: invalid option -- '${f.slice(1)}'
91
91
  `,exitCode:1}}let a=t.slice(i);if(a.length<2)return{stdout:"",stderr:`ln: missing file operand
92
92
  `,exitCode:1};let o=a[0],c=a[1],l=e.fs.resolvePath(e.cwd,c);if(await e.fs.exists(l))if(n)try{await e.fs.rm(l,{force:!0})}catch{return{stdout:"",stderr:`ln: cannot remove '${c}': Permission denied
93
93
  `,exitCode:1}}else return{stdout:"",stderr:`ln: failed to create ${r?"symbolic ":""}link '${c}': File exists
@@ -95,73 +95,73 @@ Notes:
95
95
  `,exitCode:1};await e.fs.link(f,l)}}catch(f){let d=f;return d.message.includes("EPERM")?{stdout:"",stderr:`ln: '${o}': hard link not allowed for directory
96
96
  `,exitCode:1}:{stdout:"",stderr:`ln: ${d.message}
97
97
  `,exitCode:1}}let u="";return s&&(u=`'${c}' -> '${o}'
98
- `),{stdout:u,stderr:"",exitCode:0}}}});var ks={};O(ks,{chmodCommand:()=>Yl});async function vs(t,e,r,n){let s="",i=await t.fs.readdir(e);for(let a of i){let o=e==="/"?`/${a}`:`${e}/${a}`;await t.fs.chmod(o,r),n&&(s+=`mode of '${o}' changed to ${r.toString(8).padStart(4,"0")}
99
- `),(await t.fs.stat(o)).isDirectory&&(s+=await vs(t,o,r,n))}return s}function Jl(t){if(/^[0-7]+$/.test(t))return parseInt(t,8);let e=420,r=t.split(",");for(let n of r){let s=n.match(/^([ugoa]*)([+\-=])([rwxXst]*)$/);if(!s)throw new Error(`Invalid mode: ${t}`);let i=s[1]||"a",a=s[2],o=s[3];(i==="a"||i==="")&&(i="ugo");let c=0;o.includes("r")&&(c|=4),o.includes("w")&&(c|=2),(o.includes("x")||o.includes("X"))&&(c|=1);for(let l of i){let u=0;l==="u"?u=6:l==="g"?u=3:l==="o"&&(u=0);let f=c<<u;a==="+"?e|=f:a==="-"?e&=~f:a==="="&&(e&=~(7<<u),e|=f)}}return e}var Xl,Yl,Is=N(()=>{"use strict";L();Xl={name:"chmod",summary:"change file mode bits",usage:"chmod [OPTIONS] MODE FILE...",options:["-R change files recursively","-v output a diagnostic for every file processed"," --help display this help and exit"]},Yl={name:"chmod",async execute(t,e){if(C(t))return A(Xl);if(t.length<2)return{stdout:"",stderr:`chmod: missing operand
98
+ `),{stdout:u,stderr:"",exitCode:0}}}});var Ps={};D(Ps,{chmodCommand:()=>tc});async function Rs(t,e,r,n){let s="",i=await t.fs.readdir(e);for(let a of i){let o=e==="/"?`/${a}`:`${e}/${a}`;await t.fs.chmod(o,r),n&&(s+=`mode of '${o}' changed to ${r.toString(8).padStart(4,"0")}
99
+ `),(await t.fs.stat(o)).isDirectory&&(s+=await Rs(t,o,r,n))}return s}function rc(t){if(/^[0-7]+$/.test(t))return parseInt(t,8);let e=420,r=t.split(",");for(let n of r){let s=n.match(/^([ugoa]*)([+\-=])([rwxXst]*)$/);if(!s)throw new Error(`Invalid mode: ${t}`);let i=s[1]||"a",a=s[2],o=s[3];(i==="a"||i==="")&&(i="ugo");let c=0;o.includes("r")&&(c|=4),o.includes("w")&&(c|=2),(o.includes("x")||o.includes("X"))&&(c|=1);for(let l of i){let u=0;l==="u"?u=6:l==="g"?u=3:l==="o"&&(u=0);let f=c<<u;a==="+"?e|=f:a==="-"?e&=~f:a==="="&&(e&=~(7<<u),e|=f)}}return e}var ec,tc,Os=v(()=>{"use strict";F();ec={name:"chmod",summary:"change file mode bits",usage:"chmod [OPTIONS] MODE FILE...",options:["-R change files recursively","-v output a diagnostic for every file processed"," --help display this help and exit"]},tc={name:"chmod",async execute(t,e){if(N(t))return C(ec);if(t.length<2)return{stdout:"",stderr:`chmod: missing operand
100
100
  `,exitCode:1};let r=!1,n=!1,s=0;for(;s<t.length&&t[s].startsWith("-");){let f=t[s];if(f==="-R"||f==="--recursive")r=!0,s++;else if(f==="-v"||f==="--verbose")n=!0,s++;else if(f==="--"){s++;break}else{if(/^[+-]?[rwxugo]+/.test(f)||/^\d+$/.test(f))break;if(/^-[Rv]+$/.test(f)){f.includes("R")&&(r=!0),f.includes("v")&&(n=!0),s++;continue}return{stdout:"",stderr:`chmod: invalid option -- '${f.slice(1)}'
101
101
  `,exitCode:1}}}if(t.length-s<2)return{stdout:"",stderr:`chmod: missing operand
102
- `,exitCode:1};let i=t[s],a=t.slice(s+1),o;try{o=Jl(i)}catch{return{stdout:"",stderr:`chmod: invalid mode: '${i}'
102
+ `,exitCode:1};let i=t[s],a=t.slice(s+1),o;try{o=rc(i)}catch{return{stdout:"",stderr:`chmod: invalid mode: '${i}'
103
103
  `,exitCode:1}}let c="",l="",u=!1;for(let f of a){let d=e.fs.resolvePath(e.cwd,f);try{if(await e.fs.chmod(d,o),n&&(c+=`mode of '${f}' changed to ${o.toString(8).padStart(4,"0")}
104
- `),r&&(await e.fs.stat(d)).isDirectory){let p=await vs(e,d,o,n);c+=p}}catch{l+=`chmod: cannot access '${f}': No such file or directory
105
- `,u=!0}}return{stdout:c,stderr:l,exitCode:u?1:0}}}});var Rs={};O(Rs,{pwdCommand:()=>ec});var ec,$s=N(()=>{"use strict";ec={name:"pwd",async execute(t,e){return{stdout:`${e.cwd}
106
- `,stderr:"",exitCode:0}}}});var Ps={};O(Ps,{readlinkCommand:()=>rc});var tc,rc,Os=N(()=>{"use strict";L();tc={name:"readlink",summary:"print resolved symbolic links or canonical file names",usage:"readlink [OPTIONS] FILE...",options:["-f canonicalize by following every symlink in every component of the given name recursively"," --help display this help and exit"]},rc={name:"readlink",async execute(t,e){if(C(t))return A(tc);let r=!1,n=0;for(;n<t.length&&t[n].startsWith("-");){let o=t[n];if(o==="-f"||o==="--canonicalize")r=!0,n++;else if(o==="--"){n++;break}else return{stdout:"",stderr:`readlink: invalid option -- '${o.slice(1)}'
104
+ `),r&&(await e.fs.stat(d)).isDirectory){let p=await Rs(e,d,o,n);c+=p}}catch{l+=`chmod: cannot access '${f}': No such file or directory
105
+ `,u=!0}}return{stdout:c,stderr:l,exitCode:u?1:0}}}});var Ds={};D(Ds,{pwdCommand:()=>nc});var nc,Ts=v(()=>{"use strict";nc={name:"pwd",async execute(t,e){return{stdout:`${e.cwd}
106
+ `,stderr:"",exitCode:0}}}});var Ls={};D(Ls,{readlinkCommand:()=>ic});var sc,ic,Fs=v(()=>{"use strict";F();sc={name:"readlink",summary:"print resolved symbolic links or canonical file names",usage:"readlink [OPTIONS] FILE...",options:["-f canonicalize by following every symlink in every component of the given name recursively"," --help display this help and exit"]},ic={name:"readlink",async execute(t,e){if(N(t))return C(sc);let r=!1,n=0;for(;n<t.length&&t[n].startsWith("-");){let o=t[n];if(o==="-f"||o==="--canonicalize")r=!0,n++;else if(o==="--"){n++;break}else return{stdout:"",stderr:`readlink: invalid option -- '${o.slice(1)}'
107
107
  `,exitCode:1}}let s=t.slice(n);if(s.length===0)return{stdout:"",stderr:`readlink: missing operand
108
108
  `,exitCode:1};let i="",a=!1;for(let o of s){let c=e.fs.resolvePath(e.cwd,o);try{if(r){let l=c,u=new Set;for(;!u.has(l);){u.add(l);try{let f=await e.fs.readlink(l);if(f.startsWith("/"))l=f;else{let d=l.substring(0,l.lastIndexOf("/"))||"/";l=e.fs.resolvePath(d,f)}}catch{break}}i+=`${l}
109
109
  `}else{let l=await e.fs.readlink(c);i+=`${l}
110
110
  `}}catch{r?i+=`${c}
111
- `:a=!0}}return{stdout:i,stderr:"",exitCode:a?1:0}}}});function Wt(t,e){let r=10,n=null,s=!1,i=!1,a=!1,o=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="-n"&&c+1<t.length){let u=t[++c];e==="tail"&&u.startsWith("+")?(a=!0,r=parseInt(u.slice(1),10)):r=parseInt(u,10)}else if(e==="tail"&&l.startsWith("-n+"))a=!0,r=parseInt(l.slice(3),10);else if(l.startsWith("-n"))r=parseInt(l.slice(2),10);else if(l==="-c"&&c+1<t.length)n=parseInt(t[++c],10);else if(l.startsWith("-c"))n=parseInt(l.slice(2),10);else if(l.startsWith("--bytes="))n=parseInt(l.slice(8),10);else if(l.startsWith("--lines="))r=parseInt(l.slice(8),10);else if(l==="-q"||l==="--quiet"||l==="--silent")s=!0;else if(l==="-v"||l==="--verbose")i=!0;else if(l.match(/^-\d+$/))r=parseInt(l.slice(1),10);else{if(l.startsWith("--"))return{ok:!1,error:T(e,l)};if(l.startsWith("-")&&l!=="-")return{ok:!1,error:T(e,l)};o.push(l)}}return n!==null&&(Number.isNaN(n)||n<0)?{ok:!1,error:{stdout:"",stderr:`${e}: invalid number of bytes
111
+ `:a=!0}}return{stdout:i,stderr:"",exitCode:a?1:0}}}});function zt(t,e){let r=10,n=null,s=!1,i=!1,a=!1,o=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="-n"&&c+1<t.length){let u=t[++c];e==="tail"&&u.startsWith("+")?(a=!0,r=parseInt(u.slice(1),10)):r=parseInt(u,10)}else if(e==="tail"&&l.startsWith("-n+"))a=!0,r=parseInt(l.slice(3),10);else if(l.startsWith("-n"))r=parseInt(l.slice(2),10);else if(l==="-c"&&c+1<t.length)n=parseInt(t[++c],10);else if(l.startsWith("-c"))n=parseInt(l.slice(2),10);else if(l.startsWith("--bytes="))n=parseInt(l.slice(8),10);else if(l.startsWith("--lines="))r=parseInt(l.slice(8),10);else if(l==="-q"||l==="--quiet"||l==="--silent")s=!0;else if(l==="-v"||l==="--verbose")i=!0;else if(l.match(/^-\d+$/))r=parseInt(l.slice(1),10);else{if(l.startsWith("--"))return{ok:!1,error:M(e,l)};if(l.startsWith("-")&&l!=="-")return{ok:!1,error:M(e,l)};o.push(l)}}return n!==null&&(Number.isNaN(n)||n<0)?{ok:!1,error:{stdout:"",stderr:`${e}: invalid number of bytes
112
112
  `,exitCode:1}}:Number.isNaN(r)||r<0?{ok:!1,error:{stdout:"",stderr:`${e}: invalid number of lines
113
- `,exitCode:1}}:{ok:!0,options:{lines:r,bytes:n,quiet:s,verbose:i,files:o,fromLine:a}}}async function Bt(t,e,r,n){let{quiet:s,verbose:i,files:a}=e;if(a.length===0)return{stdout:n(t.stdin),stderr:"",exitCode:0};let o="",c="",l=0,u=i||!s&&a.length>1;for(let f=0;f<a.length;f++){let d=a[f];u&&(f>0&&(o+=`
113
+ `,exitCode:1}}:{ok:!0,options:{lines:r,bytes:n,quiet:s,verbose:i,files:o,fromLine:a}}}async function Gt(t,e,r,n){let{quiet:s,verbose:i,files:a}=e;if(a.length===0)return{stdout:n(t.stdin),stderr:"",exitCode:0};let o="",c="",l=0,u=i||!s&&a.length>1;for(let f=0;f<a.length;f++){let d=a[f];u&&(f>0&&(o+=`
114
114
  `),o+=`==> ${d} <==
115
115
  `);try{let h=t.fs.resolvePath(t.cwd,d),p=await t.fs.readFile(h);o+=n(p)}catch{c+=`${r}: ${d}: No such file or directory
116
- `,l=1}}return{stdout:o,stderr:c,exitCode:l}}function Ds(t,e,r){if(r!==null)return t.slice(0,r);if(e===0)return"";let n=0,s=0,i=t.length;for(;n<i&&s<e;){let a=t.indexOf(`
116
+ `,l=1}}return{stdout:o,stderr:c,exitCode:l}}function Ms(t,e,r){if(r!==null)return t.slice(0,r);if(e===0)return"";let n=0,s=0,i=t.length;for(;n<i&&s<e;){let a=t.indexOf(`
117
117
  `,n);if(a===-1)return`${t}
118
- `;s++,n=a+1}return n>0?t.slice(0,n):""}function Ls(t,e,r,n){if(r!==null)return t.slice(-r);let s=t.length;if(s===0)return"";if(n){let c=0,l=1;for(;c<s&&l<e;){let f=t.indexOf(`
118
+ `;s++,n=a+1}return n>0?t.slice(0,n):""}function _s(t,e,r,n){if(r!==null)return t.slice(-r);let s=t.length;if(s===0)return"";if(n){let c=0,l=1;for(;c<s&&l<e;){let f=t.indexOf(`
119
119
  `,c);if(f===-1)break;l++,c=f+1}let u=t.slice(c);return u.endsWith(`
120
120
  `)?u:`${u}
121
121
  `}if(e===0)return"";let i=s-1;t[i]===`
122
122
  `&&i--;let a=0;for(;i>=0&&a<e;){if(t[i]===`
123
123
  `&&(a++,a===e)){i++;break}i--}i<0&&(i=0);let o=t.slice(i);return t[s-1]===`
124
124
  `?o:`${o}
125
- `}var $r=N(()=>{"use strict";L()});var Ts={};O(Ts,{headCommand:()=>sc});var nc,sc,Fs=N(()=>{"use strict";L();$r();nc={name:"head",summary:"output the first part of files",usage:"head [OPTION]... [FILE]...",options:["-c, --bytes=NUM print the first NUM bytes","-n, --lines=NUM print the first NUM lines (default 10)","-q, --quiet never print headers giving file names","-v, --verbose always print headers giving file names"," --help display this help and exit"]},sc={name:"head",async execute(t,e){if(C(t))return A(nc);let r=Wt(t,"head");if(!r.ok)return r.error;let{lines:n,bytes:s}=r.options;return Bt(e,r.options,"head",i=>Ds(i,n,s))}}});var Ms={};O(Ms,{tailCommand:()=>ac});var ic,ac,_s=N(()=>{"use strict";$r();L();ic={name:"tail",summary:"output the last part of files",usage:"tail [OPTION]... [FILE]...",options:["-c, --bytes=NUM print the last NUM bytes","-n, --lines=NUM print the last NUM lines (default 10)","-n +NUM print starting from line NUM","-q, --quiet never print headers giving file names","-v, --verbose always print headers giving file names"," --help display this help and exit"]},ac={name:"tail",async execute(t,e){if(C(t))return A(ic);let r=Wt(t,"tail");if(!r.ok)return r.error;let{lines:n,bytes:s,fromLine:i}=r.options;return Bt(e,r.options,"tail",a=>Ls(a,n,s,i??!1))}}});var Bs={};O(Bs,{wcCommand:()=>cc});function Ws(t){let e=t.length,r=0,n=0,s=!1;for(let i=0;i<e;i++){let a=t[i];a===`
126
- `?(r++,s&&(n++,s=!1)):a===" "||a===" "||a==="\r"?s&&(n++,s=!1):s=!0}return s&&n++,{lines:r,words:n,chars:e}}function Pr(t,e,r,n,s){let i=[];e&&i.push(String(t.lines)),r&&i.push(String(t.words)),n&&i.push(String(t.chars));let a=i.join(" ");return s&&(a+=` ${s}`),a}var oc,lc,cc,Hs=N(()=>{"use strict";ae();Ze();L();oc={name:"wc",summary:"print newline, word, and byte counts for each file",usage:"wc [OPTION]... [FILE]...",options:["-c, --bytes print the byte counts","-m, --chars print the character counts","-l, --lines print the newline counts","-w, --words print the word counts"," --help display this help and exit"]},lc={lines:{short:"l",long:"lines",type:"boolean"},words:{short:"w",long:"words",type:"boolean"},bytes:{short:"c",long:"bytes",type:"boolean"},chars:{short:"m",long:"chars",type:"boolean"}},cc={name:"wc",async execute(t,e){if(C(t))return A(oc);let r=H("wc",t,lc);if(!r.ok)return r.error;let{lines:n,words:s}=r.result.flags,i=r.result.flags.bytes||r.result.flags.chars,a=r.result.positional;!n&&!s&&!i&&(n=s=i=!0);let o=await Et(e,a,{cmdName:"wc",stopOnError:!1});if(a.length===0){let d=Ws(o.files[0].content);return{stdout:`${Pr(d,n,s,i,"")}
127
- `,stderr:"",exitCode:0}}let c="",l=0,u=0,f=0;for(let{filename:d,content:h}of o.files){let p=Ws(h);l+=p.lines,u+=p.words,f+=p.chars,c+=`${Pr(p,n,s,i,d)}
128
- `}return a.length>1&&(c+=`${Pr({lines:l,words:u,chars:f},n,s,i,"total")}
129
- `),{stdout:c,stderr:o.stderr,exitCode:o.exitCode}}}});var zs={};O(zs,{statCommand:()=>dc});function Us(t,e){let r=e?"d":"-",n=[t&256?"r":"-",t&128?"w":"-",t&64?"x":"-",t&32?"r":"-",t&16?"w":"-",t&8?"x":"-",t&4?"r":"-",t&2?"w":"-",t&1?"x":"-"];return r+n.join("")}var uc,fc,dc,Gs=N(()=>{"use strict";ae();L();uc={name:"stat",summary:"display file or file system status",usage:"stat [OPTION]... FILE...",options:["-c FORMAT use the specified FORMAT instead of the default"," --help display this help and exit"]},fc={format:{short:"c",type:"string"}},dc={name:"stat",async execute(t,e){if(C(t))return A(uc);let r=H("stat",t,fc);if(!r.ok)return r.error;let n=r.result.flags.format??null,s=r.result.positional;if(s.length===0)return{stdout:"",stderr:`stat: missing operand
130
- `,exitCode:1};let i="",a="",o=!1;for(let c of s){let l=e.fs.resolvePath(e.cwd,c);try{let u=await e.fs.stat(l);if(n){let f=n,d=u.mode.toString(8),h=Us(u.mode,u.isDirectory);f=f.replace(/%n/g,c),f=f.replace(/%N/g,`'${c}'`),f=f.replace(/%s/g,String(u.size)),f=f.replace(/%F/g,u.isDirectory?"directory":"regular file"),f=f.replace(/%a/g,d),f=f.replace(/%A/g,h),f=f.replace(/%u/g,"1000"),f=f.replace(/%U/g,"user"),f=f.replace(/%g/g,"1000"),f=f.replace(/%G/g,"group"),i+=`${f}
131
- `}else{let f=u.mode.toString(8).padStart(4,"0"),d=Us(u.mode,u.isDirectory);i+=` File: ${c}
125
+ `}var Dr=v(()=>{"use strict";F()});var Ws={};D(Ws,{headCommand:()=>oc});var ac,oc,Bs=v(()=>{"use strict";F();Dr();ac={name:"head",summary:"output the first part of files",usage:"head [OPTION]... [FILE]...",options:["-c, --bytes=NUM print the first NUM bytes","-n, --lines=NUM print the first NUM lines (default 10)","-q, --quiet never print headers giving file names","-v, --verbose always print headers giving file names"," --help display this help and exit"]},oc={name:"head",async execute(t,e){if(N(t))return C(ac);let r=zt(t,"head");if(!r.ok)return r.error;let{lines:n,bytes:s}=r.options;return Gt(e,r.options,"head",i=>Ms(i,n,s))}}});var Hs={};D(Hs,{tailCommand:()=>cc});var lc,cc,Us=v(()=>{"use strict";Dr();F();lc={name:"tail",summary:"output the last part of files",usage:"tail [OPTION]... [FILE]...",options:["-c, --bytes=NUM print the last NUM bytes","-n, --lines=NUM print the last NUM lines (default 10)","-n +NUM print starting from line NUM","-q, --quiet never print headers giving file names","-v, --verbose always print headers giving file names"," --help display this help and exit"]},cc={name:"tail",async execute(t,e){if(N(t))return C(lc);let r=zt(t,"tail");if(!r.ok)return r.error;let{lines:n,bytes:s,fromLine:i}=r.options;return Gt(e,r.options,"tail",a=>_s(a,n,s,i??!1))}}});var Gs={};D(Gs,{wcCommand:()=>dc});function zs(t){let e=t.length,r=0,n=0,s=!1;for(let i=0;i<e;i++){let a=t[i];a===`
126
+ `?(r++,s&&(n++,s=!1)):a===" "||a===" "||a==="\r"?s&&(n++,s=!1):s=!0}return s&&n++,{lines:r,words:n,chars:e}}function Tr(t,e,r,n,s){let i=[];e&&i.push(String(t.lines)),r&&i.push(String(t.words)),n&&i.push(String(t.chars));let a=i.join(" ");return s&&(a+=` ${s}`),a}var uc,fc,dc,js=v(()=>{"use strict";oe();Ke();F();uc={name:"wc",summary:"print newline, word, and byte counts for each file",usage:"wc [OPTION]... [FILE]...",options:["-c, --bytes print the byte counts","-m, --chars print the character counts","-l, --lines print the newline counts","-w, --words print the word counts"," --help display this help and exit"]},fc={lines:{short:"l",long:"lines",type:"boolean"},words:{short:"w",long:"words",type:"boolean"},bytes:{short:"c",long:"bytes",type:"boolean"},chars:{short:"m",long:"chars",type:"boolean"}},dc={name:"wc",async execute(t,e){if(N(t))return C(uc);let r=G("wc",t,fc);if(!r.ok)return r.error;let{lines:n,words:s}=r.result.flags,i=r.result.flags.bytes||r.result.flags.chars,a=r.result.positional;!n&&!s&&!i&&(n=s=i=!0);let o=await St(e,a,{cmdName:"wc",stopOnError:!1});if(a.length===0){let d=zs(o.files[0].content);return{stdout:`${Tr(d,n,s,i,"")}
127
+ `,stderr:"",exitCode:0}}let c="",l=0,u=0,f=0;for(let{filename:d,content:h}of o.files){let p=zs(h);l+=p.lines,u+=p.words,f+=p.chars,c+=`${Tr(p,n,s,i,d)}
128
+ `}return a.length>1&&(c+=`${Tr({lines:l,words:u,chars:f},n,s,i,"total")}
129
+ `),{stdout:c,stderr:o.stderr,exitCode:o.exitCode}}}});var Vs={};D(Vs,{statCommand:()=>mc});function qs(t,e){let r=e?"d":"-",n=[t&256?"r":"-",t&128?"w":"-",t&64?"x":"-",t&32?"r":"-",t&16?"w":"-",t&8?"x":"-",t&4?"r":"-",t&2?"w":"-",t&1?"x":"-"];return r+n.join("")}var hc,pc,mc,Zs=v(()=>{"use strict";oe();F();hc={name:"stat",summary:"display file or file system status",usage:"stat [OPTION]... FILE...",options:["-c FORMAT use the specified FORMAT instead of the default"," --help display this help and exit"]},pc={format:{short:"c",type:"string"}},mc={name:"stat",async execute(t,e){if(N(t))return C(hc);let r=G("stat",t,pc);if(!r.ok)return r.error;let n=r.result.flags.format??null,s=r.result.positional;if(s.length===0)return{stdout:"",stderr:`stat: missing operand
130
+ `,exitCode:1};let i="",a="",o=!1;for(let c of s){let l=e.fs.resolvePath(e.cwd,c);try{let u=await e.fs.stat(l);if(n){let f=n,d=u.mode.toString(8),h=qs(u.mode,u.isDirectory);f=f.replace(/%n/g,c),f=f.replace(/%N/g,`'${c}'`),f=f.replace(/%s/g,String(u.size)),f=f.replace(/%F/g,u.isDirectory?"directory":"regular file"),f=f.replace(/%a/g,d),f=f.replace(/%A/g,h),f=f.replace(/%u/g,"1000"),f=f.replace(/%U/g,"user"),f=f.replace(/%g/g,"1000"),f=f.replace(/%G/g,"group"),i+=`${f}
131
+ `}else{let f=u.mode.toString(8).padStart(4,"0"),d=qs(u.mode,u.isDirectory);i+=` File: ${c}
132
132
  `,i+=` Size: ${u.size} Blocks: ${Math.ceil(u.size/512)}
133
133
  `,i+=`Access: (${f}/${d})
134
134
  `,i+=`Modify: ${u.mtime.toISOString()}
135
135
  `}}catch{a+=`stat: cannot stat '${c}': No such file or directory
136
- `,o=!0}}return{stdout:i,stderr:a,exitCode:o?1:0}}}});function be(t,e,r){let n=typeof r=="boolean"?{ignoreCase:r}:r??{},s=e;n.stripQuotes&&(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1));let i=n.ignoreCase?`i:${s}`:s,a=js.get(i);return a||(a=hc(s,n.ignoreCase),js.set(i,a)),a.test(t)}function hc(t,e){let r="^";for(let n=0;n<t.length;n++){let s=t[n];if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let i=n+1;for(;i<t.length&&t[i]!=="]";)i++;r+=t.slice(n,i+1),n=i}else s==="."||s==="+"||s==="^"||s==="$"||s==="{"||s==="}"||s==="("||s===")"||s==="|"||s==="\\"?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r,e?"i":"")}var js,Or=N(()=>{"use strict";js=new Map});var Ht={};O(Ht,{egrepCommand:()=>wc,fgrepCommand:()=>gc,grepCommand:()=>Lr});function mc(t){let e="",r=0;for(;r<t.length;){let n=t[r];if(n==="\\"&&r+1<t.length){let s=t[r+1];if(s==="|"||s==="("||s===")"){e+=s,r+=2;continue}else if(s==="{"||s==="}"){e+=`\\${s}`,r+=2;continue}}n==="+"||n==="?"||n==="|"||n==="("||n===")"||n==="{"||n==="}"?e+=`\\${n}`:e+=n,r++}return e}function qs(t,e,r,n,s,i,a=!1,o=0,c=0,l=0){let u=t.split(`
137
- `),f=u.length,d=f>0&&u[f-1]===""?f-1:f;if(s){let g=0;for(let x=0;x<d;x++)e.lastIndex=0,e.test(u[x])!==r&&g++;return{output:`${i?`${i}:${g}`:String(g)}
138
- `,matched:g>0}}if(o===0&&c===0){let g=[],E=!1,x=0;for(let S=0;S<d&&!(l>0&&x>=l);S++){let v=u[S];if(e.lastIndex=0,e.test(v)!==r)if(E=!0,x++,a){e.lastIndex=0;for(let M=e.exec(v);M!==null;M=e.exec(v))g.push(i?`${i}:${M[0]}`:M[0]),M[0].length===0&&e.lastIndex++}else n?g.push(i?`${i}:${S+1}:${v}`:`${S+1}:${v}`):g.push(i?`${i}:${v}`:v)}return{output:g.length>0?`${g.join(`
136
+ `,o=!0}}return{stdout:i,stderr:a,exitCode:o?1:0}}}});function xe(t,e,r){let n=typeof r=="boolean"?{ignoreCase:r}:r??{},s=e;n.stripQuotes&&(s.startsWith('"')&&s.endsWith('"')||s.startsWith("'")&&s.endsWith("'"))&&(s=s.slice(1,-1));let i=n.ignoreCase?`i:${s}`:s,a=Qs.get(i);return a||(a=yc(s,n.ignoreCase),Qs.set(i,a)),a.test(t)}function yc(t,e){let r="^";for(let n=0;n<t.length;n++){let s=t[n];if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let i=n+1;for(;i<t.length&&t[i]!=="]";)i++;r+=t.slice(n,i+1),n=i}else s==="."||s==="+"||s==="^"||s==="$"||s==="{"||s==="}"||s==="("||s===")"||s==="|"||s==="\\"?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r,e?"i":"")}var Qs,Lr=v(()=>{"use strict";Qs=new Map});var jt={};D(jt,{egrepCommand:()=>Sc,fgrepCommand:()=>bc,grepCommand:()=>Mr});function wc(t){let e="",r=0;for(;r<t.length;){let n=t[r];if(n==="\\"&&r+1<t.length){let s=t[r+1];if(s==="|"||s==="("||s===")"){e+=s,r+=2;continue}else if(s==="{"||s==="}"){e+=`\\${s}`,r+=2;continue}}n==="+"||n==="?"||n==="|"||n==="("||n===")"||n==="{"||n==="}"?e+=`\\${n}`:e+=n,r++}return e}function Ks(t,e,r,n,s,i,a=!1,o=0,c=0,l=0){let u=t.split(`
137
+ `),f=u.length,d=f>0&&u[f-1]===""?f-1:f;if(s){let g=0;for(let S=0;S<d;S++)e.lastIndex=0,e.test(u[S])!==r&&g++;return{output:`${i?`${i}:${g}`:String(g)}
138
+ `,matched:g>0}}if(o===0&&c===0){let g=[],b=!1,S=0;for(let x=0;x<d&&!(l>0&&S>=l);x++){let A=u[x];if(e.lastIndex=0,e.test(A)!==r)if(b=!0,S++,a){e.lastIndex=0;for(let L=e.exec(A);L!==null;L=e.exec(A))g.push(i?`${i}:${L[0]}`:L[0]),L[0].length===0&&e.lastIndex++}else n?g.push(i?`${i}:${x+1}:${A}`:`${x+1}:${A}`):g.push(i?`${i}:${A}`:A)}return{output:g.length>0?`${g.join(`
139
139
  `)}
140
- `:"",matched:E}}let h=[],p=0,b=new Set,w=[];for(let g=0;g<d&&!(l>0&&p>=l);g++)e.lastIndex=0,e.test(u[g])!==r&&(w.push(g),p++);for(let g of w){for(let x=Math.max(0,g-o);x<g;x++)if(!b.has(x)){b.add(x);let S=u[x];n&&(S=`${x+1}-${S}`),i&&(S=`${i}-${S}`),h.push(S)}if(!b.has(g)){b.add(g);let x=u[g];if(a){e.lastIndex=0;for(let S=e.exec(x);S!==null;S=e.exec(x))h.push(i?`${i}:${S[0]}`:S[0]),S[0].length===0&&e.lastIndex++}else{let S=x;n&&(S=`${g+1}:${S}`),i&&(S=`${i}:${S}`),h.push(S)}}let E=Math.min(d-1,g+c);for(let x=g+1;x<=E;x++)if(!b.has(x)){b.add(x);let S=u[x];n&&(S=`${x+1}-${S}`),i&&(S=`${i}-${S}`),h.push(S)}}return{output:h.length>0?`${h.join(`
140
+ `:"",matched:b}}let h=[],p=0,E=new Set,w=[];for(let g=0;g<d&&!(l>0&&p>=l);g++)e.lastIndex=0,e.test(u[g])!==r&&(w.push(g),p++);for(let g of w){for(let S=Math.max(0,g-o);S<g;S++)if(!E.has(S)){E.add(S);let x=u[S];n&&(x=`${S+1}-${x}`),i&&(x=`${i}-${x}`),h.push(x)}if(!E.has(g)){E.add(g);let S=u[g];if(a){e.lastIndex=0;for(let x=e.exec(S);x!==null;x=e.exec(S))h.push(i?`${i}:${x[0]}`:x[0]),x[0].length===0&&e.lastIndex++}else{let x=S;n&&(x=`${g+1}:${x}`),i&&(x=`${i}:${x}`),h.push(x)}}let b=Math.min(d-1,g+c);for(let S=g+1;S<=b;S++)if(!E.has(S)){E.add(S);let x=u[S];n&&(x=`${S+1}-${x}`),i&&(x=`${i}-${x}`),h.push(x)}}return{output:h.length>0?`${h.join(`
141
141
  `)}
142
- `:"",matched:p>0}}async function Dr(t,e,r=[],n=[],s=[]){let i=e.fs.resolvePath(e.cwd,t),a=[];try{if(!(await e.fs.stat(i)).isDirectory){let u=t.split("/").pop()||t;return n.length>0&&n.some(f=>be(u,f,{stripQuotes:!0}))?[]:r.length>0&&!r.some(f=>be(u,f,{stripQuotes:!0}))?[]:[t]}let c=t.split("/").pop()||t;if(s.length>0&&s.some(u=>be(c,u,{stripQuotes:!0})))return[];let l=await e.fs.readdir(i);for(let u of l){if(u.startsWith("."))continue;let f=t==="."?u:`${t}/${u}`,d=await Dr(f,e,r,n,s);a.push(...d)}}catch{}return a}async function yc(t,e){let r=[],n=t.lastIndexOf("/"),s,i;if(n===-1?(s=e.cwd,i=t):(s=t.slice(0,n)||"/",i=t.slice(n+1)),t.includes("**")){let o=t.split("**"),c=o[0].replace(/\/$/,"")||".",l=o[1]||"";return await Vs(c,l,e,r),r}let a=e.fs.resolvePath(e.cwd,s);try{let o=await e.fs.readdir(a);for(let c of o)if(be(c,i,{stripQuotes:!0})){let l=n===-1?c:`${s}/${c}`;r.push(l)}}catch{}return r.sort()}async function Vs(t,e,r,n){let s=r.fs.resolvePath(r.cwd,t);try{if(!(await r.fs.stat(s)).isDirectory){let o=t.split("/").pop()||"";if(e){let c=e.replace(/^\//,"");be(o,c,{stripQuotes:!0})&&n.push(t)}return}let a=await r.fs.readdir(s);for(let o of a){let c=t==="."?o:`${t}/${o}`,l=r.fs.resolvePath(r.cwd,c);if((await r.fs.stat(l)).isDirectory)await Vs(c,e,r,n);else if(e){let f=e.replace(/^\//,"");be(o,f,{stripQuotes:!0})&&n.push(c)}}}catch{}}var pc,Lr,gc,wc,Ut=N(()=>{"use strict";Or();L();pc={name:"grep",summary:"print lines that match patterns",usage:"grep [OPTION]... PATTERN [FILE]...",options:["-E, --extended-regexp PATTERN is an extended regular expression","-F, --fixed-strings PATTERN is a set of newline-separated strings","-i, --ignore-case ignore case distinctions","-v, --invert-match select non-matching lines","-w, --word-regexp match only whole words","-x, --line-regexp match only whole lines","-c, --count print only a count of matching lines","-l, --files-with-matches print only names of files with matches","-L, --files-without-match print names of files with no matches","-m NUM, --max-count=NUM stop after NUM matches","-n, --line-number print line number with output lines","-h, --no-filename suppress the file name prefix on output","-o, --only-matching show only nonempty parts of lines that match","-q, --quiet, --silent suppress all normal output","-r, -R, --recursive search directories recursively","-A NUM print NUM lines of trailing context","-B NUM print NUM lines of leading context","-C NUM print NUM lines of context","-e PATTERN use PATTERN for matching"," --include=GLOB search only files matching GLOB"," --exclude=GLOB skip files matching GLOB"," --exclude-dir=DIR skip directories matching DIR"," --help display this help and exit"]},Lr={name:"grep",async execute(t,e){if(C(t))return A(pc);let r=!1,n=!1,s=!1,i=!1,a=!1,o=!1,c=!1,l=!1,u=!1,f=!1,d=!1,h=!1,p=!1,b=!1,w=0,g=0,E=0,x=[],S=[],v=[],R=null,M=[];for(let V=0;V<t.length;V++){let z=t[V];if(z.startsWith("-")&&z!=="-"){if(z==="-e"&&V+1<t.length){R=t[++V];continue}if(z.startsWith("--include=")){x.push(z.slice(10));continue}if(z.startsWith("--exclude=")){S.push(z.slice(10));continue}if(z.startsWith("--exclude-dir=")){v.push(z.slice(14));continue}if(z.startsWith("--max-count=")){w=parseInt(z.slice(12),10);continue}let ve=z.match(/^-m(\d+)$/);if(ve){w=parseInt(ve[1],10);continue}if(z==="-m"&&V+1<t.length){w=parseInt(t[++V],10);continue}let We=z.match(/^-([ABC])(\d+)$/);if(We){let D=parseInt(We[2],10);We[1]==="A"?E=D:We[1]==="B"?g=D:We[1]==="C"&&(g=D,E=D);continue}if((z==="-A"||z==="-B"||z==="-C")&&V+1<t.length){let D=parseInt(t[++V],10);z==="-A"?E=D:z==="-B"?g=D:(g=D,E=D);continue}let Rr=z.startsWith("--")?[z]:z.slice(1).split("");for(let D of Rr)if(D==="i"||D==="--ignore-case")r=!0;else if(D==="n"||D==="--line-number")n=!0;else if(D==="v"||D==="--invert-match")s=!0;else if(D==="c"||D==="--count")i=!0;else if(D==="l"||D==="--files-with-matches")a=!0;else if(D==="L"||D==="--files-without-match")o=!0;else if(D==="r"||D==="R"||D==="--recursive")c=!0;else if(D==="w"||D==="--word-regexp")l=!0;else if(D==="x"||D==="--line-regexp")u=!0;else if(D==="E"||D==="--extended-regexp")f=!0;else if(D==="F"||D==="--fixed-strings")d=!0;else if(D==="o"||D==="--only-matching")h=!0;else if(D==="h"||D==="--no-filename")p=!0;else if(D==="q"||D==="--quiet"||D==="--silent")b=!0;else{if(D.startsWith("--"))return T("grep",D);if(D.length===1)return T("grep",`-${D}`)}}else R===null?R=z:M.push(z)}if(R===null)return{stdout:"",stderr:`grep: missing pattern
143
- `,exitCode:2};let _;d?_=R.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):f?_=R:_=mc(R),l&&(_=`\\b${_}\\b`),u&&(_=`^${_}$`);let Oe;try{Oe=new RegExp(_,r?"gi":"g")}catch{return{stdout:"",stderr:`grep: invalid regular expression: ${R}
144
- `,exitCode:2}}if(M.length===0&&e.stdin){let V=qs(e.stdin,Oe,s,n,i,"",h,g,E,w);return b?{stdout:"",stderr:"",exitCode:V.matched?0:1}:{stdout:V.output,stderr:"",exitCode:V.matched?0:1}}if(M.length===0)return{stdout:"",stderr:`grep: no input files
145
- `,exitCode:2};let K="",Ee="",ne=!1,de=!1,oe=[];for(let V of M)if(V.includes("*")||V.includes("?")||V.includes("[")){let z=await yc(V,e);if(c)for(let ve of z){let We=await Dr(ve,e,x,S,v);oe.push(...We)}else oe.push(...z)}else if(c){let z=await Dr(V,e,x,S,v);oe.push(...z)}else oe.push(V);let Ir=(oe.length>1||c)&&!p;for(let V of oe){let z=V.split("/").pop()||V;if(!(S.length>0&&!c&&S.some(ve=>be(z,ve,{stripQuotes:!0})))&&!(x.length>0&&!c&&!x.some(ve=>be(z,ve,{stripQuotes:!0}))))try{let ve=e.fs.resolvePath(e.cwd,V);if((await e.fs.stat(ve)).isDirectory){c||(Ee+=`grep: ${V}: Is a directory
146
- `);continue}let Rr=await e.fs.readFile(ve),D=qs(Rr,Oe,s,n,i,Ir?V:"",h,g,E,w);if(D.matched){if(ne=!0,b)return{stdout:"",stderr:"",exitCode:0};a?K+=`${V}
147
- `:o||(K+=D.output)}else o?K+=`${V}
148
- `:i&&!a&&(K+=D.output)}catch{Ee+=`grep: ${V}: No such file or directory
149
- `,de=!0}}let wt;return de?wt=2:o?wt=K.length>0?0:1:wt=ne?0:1,b?{stdout:"",stderr:"",exitCode:wt}:{stdout:K,stderr:Ee,exitCode:wt}}};gc={name:"fgrep",async execute(t,e){return Lr.execute(["-F",...t],e)}},wc={name:"egrep",async execute(t,e){return Lr.execute(["-E",...t],e)}}});function zt(t){return t instanceof ce||t instanceof pe||t instanceof ue}var xe,ce,pe,ue,Re,Se,Z,te,De,W,$e,X=N(()=>{"use strict";xe=class extends Error{stdout;stderr;constructor(e,r="",n=""){super(e),this.stdout=r,this.stderr=n}prependOutput(e,r){this.stdout=e+this.stdout,this.stderr=r+this.stderr}},ce=class extends xe{levels;name="BreakError";constructor(e=1,r="",n=""){super("break",r,n),this.levels=e}},pe=class extends xe{levels;name="ContinueError";constructor(e=1,r="",n=""){super("continue",r,n),this.levels=e}},ue=class extends xe{exitCode;name="ReturnError";constructor(e=0,r="",n=""){super("return",r,n),this.exitCode=e}},Re=class extends xe{exitCode;name="ErrexitError";constructor(e,r="",n=""){super(`errexit: command exited with status ${e}`,r,n),this.exitCode=e}},Se=class extends xe{varName;name="NounsetError";constructor(e,r=""){super(`${e}: unbound variable`,r,`bash: ${e}: unbound variable
150
- `),this.varName=e}},Z=class extends xe{exitCode;name="ExitError";constructor(e,r="",n=""){super("exit",r,n),this.exitCode=e}},te=class extends xe{name="ArithmeticError";constructor(e,r="",n=""){super(e,r,n),this.stderr=n||`bash: ${e}
151
- `}},De=class extends xe{name="BadSubstitutionError";constructor(e,r="",n=""){super(e,r,n),this.stderr=n||`bash: ${e}: bad substitution
152
- `}},W=class extends xe{limitType;name="ExecutionLimitError";static EXIT_CODE=126;constructor(e,r,n="",s=""){super(e,n,s),this.limitType=r,this.stderr=s||`bash: ${e}
153
- `}},$e=class extends xe{name="SubshellExitError";constructor(e="",r=""){super("subshell exit",e,r)}}});function Qs(t,e,r){return{patternSpace:"",holdSpace:"",lineNumber:0,totalLines:t,deleted:!1,printed:!1,quit:!1,quitSilent:!1,exitCode:void 0,appendBuffer:[],substitutionMade:!1,lineNumberOutput:[],restartCycle:!1,currentFilename:e,pendingFileReads:[],pendingFileWrites:[],pendingExecute:void 0,rangeStates:r||new Map}}function bc(t){return typeof t=="object"&&"first"in t&&"step"in t}function bt(t,e,r,n){if(t==="$")return e===r;if(typeof t=="number")return e===t;if(bc(t)){let{first:s,step:i}=t;return i===0?e===s:(e-s)%i===0&&e>=s}if(typeof t=="object"&&"pattern"in t)try{return new RegExp(t.pattern).test(n)}catch{return!1}return!1}function xc(t){let e=r=>r===void 0?"undefined":r==="$"?"$":typeof r=="number"?String(r):"pattern"in r?`/${r.pattern}/`:"first"in r?`${r.first}~${r.step}`:"unknown";return`${e(t.start)},${e(t.end)}`}function at(t,e,r,n,s){if(!t||!t.start&&!t.end)return!0;let i=t.start,a=t.end;if(i!==void 0&&a===void 0)return bt(i,e,r,n);if(i!==void 0&&a!==void 0){let o=typeof i=="object"&&"pattern"in i,c=typeof a=="object"&&"pattern"in a;if(!o&&!c){let u=typeof i=="number"?i:i==="$"?r:1,f=typeof a=="number"?a:r;return e>=u&&e<=f}if(s){let u=xc(t),f=s.get(u);return f||(f={active:!1},s.set(u,f)),f.active?(bt(a,e,r,n)&&(f.active=!1,s.set(u,f)),!0):bt(i,e,r,n)?(f.active=!0,f.startLine=e,s.set(u,f),bt(a,e,r,n)&&(f.active=!1,s.set(u,f)),!0):!1}return bt(i,e,r,n)}return!0}function Sc(t){let e="",r=0;for(;r<t.length;){if(t[r]==="\\"&&r+1<t.length){let n=t[r+1];if(n==="+"||n==="?"||n==="|"){e+=n,r+=2;continue}if(n==="("||n===")"){e+=n,r+=2;continue}if(n==="{"||n==="}"){e+=n,r+=2;continue}e+=t[r]+n,r+=2;continue}if(t[r]==="+"||t[r]==="?"||t[r]==="|"||t[r]==="("||t[r]===")"){e+=`\\${t[r]}`,r++;continue}e+=t[r],r++}return e}function Ac(t){let e="";for(let r=0;r<t.length;r++){let n=t[r],s=n.charCodeAt(0);n==="\\"?e+="\\\\":n===" "?e+="\\t":n===`
142
+ `:"",matched:p>0}}async function Fr(t,e,r=[],n=[],s=[]){let i=e.fs.resolvePath(e.cwd,t),a=[];try{if(!(await e.fs.stat(i)).isDirectory){let u=t.split("/").pop()||t;return n.length>0&&n.some(f=>xe(u,f,{stripQuotes:!0}))?[]:r.length>0&&!r.some(f=>xe(u,f,{stripQuotes:!0}))?[]:[t]}let c=t.split("/").pop()||t;if(s.length>0&&s.some(u=>xe(c,u,{stripQuotes:!0})))return[];let l=await e.fs.readdir(i);for(let u of l){if(u.startsWith("."))continue;let f=t==="."?u:`${t}/${u}`,d=await Fr(f,e,r,n,s);a.push(...d)}}catch{}return a}async function Ec(t,e){let r=[],n=t.lastIndexOf("/"),s,i;if(n===-1?(s=e.cwd,i=t):(s=t.slice(0,n)||"/",i=t.slice(n+1)),t.includes("**")){let o=t.split("**"),c=o[0].replace(/\/$/,"")||".",l=o[1]||"";return await Xs(c,l,e,r),r}let a=e.fs.resolvePath(e.cwd,s);try{let o=await e.fs.readdir(a);for(let c of o)if(xe(c,i,{stripQuotes:!0})){let l=n===-1?c:`${s}/${c}`;r.push(l)}}catch{}return r.sort()}async function Xs(t,e,r,n){let s=r.fs.resolvePath(r.cwd,t);try{if(!(await r.fs.stat(s)).isDirectory){let o=t.split("/").pop()||"";if(e){let c=e.replace(/^\//,"");xe(o,c,{stripQuotes:!0})&&n.push(t)}return}let a=await r.fs.readdir(s);for(let o of a){let c=t==="."?o:`${t}/${o}`,l=r.fs.resolvePath(r.cwd,c);if((await r.fs.stat(l)).isDirectory)await Xs(c,e,r,n);else if(e){let f=e.replace(/^\//,"");xe(o,f,{stripQuotes:!0})&&n.push(c)}}}catch{}}var gc,Mr,bc,Sc,qt=v(()=>{"use strict";Lr();F();gc={name:"grep",summary:"print lines that match patterns",usage:"grep [OPTION]... PATTERN [FILE]...",options:["-E, --extended-regexp PATTERN is an extended regular expression","-F, --fixed-strings PATTERN is a set of newline-separated strings","-i, --ignore-case ignore case distinctions","-v, --invert-match select non-matching lines","-w, --word-regexp match only whole words","-x, --line-regexp match only whole lines","-c, --count print only a count of matching lines","-l, --files-with-matches print only names of files with matches","-L, --files-without-match print names of files with no matches","-m NUM, --max-count=NUM stop after NUM matches","-n, --line-number print line number with output lines","-h, --no-filename suppress the file name prefix on output","-o, --only-matching show only nonempty parts of lines that match","-q, --quiet, --silent suppress all normal output","-r, -R, --recursive search directories recursively","-A NUM print NUM lines of trailing context","-B NUM print NUM lines of leading context","-C NUM print NUM lines of context","-e PATTERN use PATTERN for matching"," --include=GLOB search only files matching GLOB"," --exclude=GLOB skip files matching GLOB"," --exclude-dir=DIR skip directories matching DIR"," --help display this help and exit"]},Mr={name:"grep",async execute(t,e){if(N(t))return C(gc);let r=!1,n=!1,s=!1,i=!1,a=!1,o=!1,c=!1,l=!1,u=!1,f=!1,d=!1,h=!1,p=!1,E=!1,w=0,g=0,b=0,S=[],x=[],A=[],O=null,L=[];for(let z=0;z<t.length;z++){let W=t[z];if(W.startsWith("-")&&W!=="-"){if(W==="-e"&&z+1<t.length){O=t[++z];continue}if(W.startsWith("--include=")){S.push(W.slice(10));continue}if(W.startsWith("--exclude=")){x.push(W.slice(10));continue}if(W.startsWith("--exclude-dir=")){A.push(W.slice(14));continue}if(W.startsWith("--max-count=")){w=parseInt(W.slice(12),10);continue}let ce=W.match(/^-m(\d+)$/);if(ce){w=parseInt(ce[1],10);continue}if(W==="-m"&&z+1<t.length){w=parseInt(t[++z],10);continue}let Pe=W.match(/^-([ABC])(\d+)$/);if(Pe){let T=parseInt(Pe[2],10);Pe[1]==="A"?b=T:Pe[1]==="B"?g=T:Pe[1]==="C"&&(g=T,b=T);continue}if((W==="-A"||W==="-B"||W==="-C")&&z+1<t.length){let T=parseInt(t[++z],10);W==="-A"?b=T:W==="-B"?g=T:(g=T,b=T);continue}let ot=W.startsWith("--")?[W]:W.slice(1).split("");for(let T of ot)if(T==="i"||T==="--ignore-case")r=!0;else if(T==="n"||T==="--line-number")n=!0;else if(T==="v"||T==="--invert-match")s=!0;else if(T==="c"||T==="--count")i=!0;else if(T==="l"||T==="--files-with-matches")a=!0;else if(T==="L"||T==="--files-without-match")o=!0;else if(T==="r"||T==="R"||T==="--recursive")c=!0;else if(T==="w"||T==="--word-regexp")l=!0;else if(T==="x"||T==="--line-regexp")u=!0;else if(T==="E"||T==="--extended-regexp")f=!0;else if(T==="F"||T==="--fixed-strings")d=!0;else if(T==="o"||T==="--only-matching")h=!0;else if(T==="h"||T==="--no-filename")p=!0;else if(T==="q"||T==="--quiet"||T==="--silent")E=!0;else{if(T.startsWith("--"))return M("grep",T);if(T.length===1)return M("grep",`-${T}`)}}else O===null?O=W:L.push(W)}if(O===null)return{stdout:"",stderr:`grep: missing pattern
143
+ `,exitCode:2};let R;d?R=O.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):f?R=O:R=wc(O),l&&(R=`\\b${R}\\b`),u&&(R=`^${R}$`);let U;try{U=new RegExp(R,r?"gi":"g")}catch{return{stdout:"",stderr:`grep: invalid regular expression: ${O}
144
+ `,exitCode:2}}if(L.length===0&&e.stdin){let z=Ks(e.stdin,U,s,n,i,"",h,g,b,w);return E?{stdout:"",stderr:"",exitCode:z.matched?0:1}:{stdout:z.output,stderr:"",exitCode:z.matched?0:1}}if(L.length===0)return{stdout:"",stderr:`grep: no input files
145
+ `,exitCode:2};let Q="",pe="",re=!1,ge=!1,me=[];for(let z of L)if(z.includes("*")||z.includes("?")||z.includes("[")){let W=await Ec(z,e);if(c)for(let ce of W){let Pe=await Fr(ce,e,S,x,A);me.push(...Pe)}else me.push(...W)}else if(c){let W=await Fr(z,e,S,x,A);me.push(...W)}else me.push(z);let at=(me.length>1||c)&&!p;for(let z of me){let W=z.split("/").pop()||z;if(!(x.length>0&&!c&&x.some(ce=>xe(W,ce,{stripQuotes:!0})))&&!(S.length>0&&!c&&!S.some(ce=>xe(W,ce,{stripQuotes:!0}))))try{let ce=e.fs.resolvePath(e.cwd,z);if((await e.fs.stat(ce)).isDirectory){c||(pe+=`grep: ${z}: Is a directory
146
+ `);continue}let ot=await e.fs.readFile(ce),T=Ks(ot,U,s,n,i,at?z:"",h,g,b,w);if(T.matched){if(re=!0,E)return{stdout:"",stderr:"",exitCode:0};a?Q+=`${z}
147
+ `:o||(Q+=T.output)}else o?Q+=`${z}
148
+ `:i&&!a&&(Q+=T.output)}catch{pe+=`grep: ${z}: No such file or directory
149
+ `,ge=!0}}let Be;return ge?Be=2:o?Be=Q.length>0?0:1:Be=re?0:1,E?{stdout:"",stderr:"",exitCode:Be}:{stdout:Q,stderr:pe,exitCode:Be}}};bc={name:"fgrep",async execute(t,e){return Mr.execute(["-F",...t],e)}},Sc={name:"egrep",async execute(t,e){return Mr.execute(["-E",...t],e)}}});function Vt(t){return t instanceof ue||t instanceof ye||t instanceof fe}var Ae,ue,ye,fe,Re,Ce,K,ne,Te,B,Oe,Y=v(()=>{"use strict";Ae=class extends Error{stdout;stderr;constructor(e,r="",n=""){super(e),this.stdout=r,this.stderr=n}prependOutput(e,r){this.stdout=e+this.stdout,this.stderr=r+this.stderr}},ue=class extends Ae{levels;name="BreakError";constructor(e=1,r="",n=""){super("break",r,n),this.levels=e}},ye=class extends Ae{levels;name="ContinueError";constructor(e=1,r="",n=""){super("continue",r,n),this.levels=e}},fe=class extends Ae{exitCode;name="ReturnError";constructor(e=0,r="",n=""){super("return",r,n),this.exitCode=e}},Re=class extends Ae{exitCode;name="ErrexitError";constructor(e,r="",n=""){super(`errexit: command exited with status ${e}`,r,n),this.exitCode=e}},Ce=class extends Ae{varName;name="NounsetError";constructor(e,r=""){super(`${e}: unbound variable`,r,`bash: ${e}: unbound variable
150
+ `),this.varName=e}},K=class extends Ae{exitCode;name="ExitError";constructor(e,r="",n=""){super("exit",r,n),this.exitCode=e}},ne=class extends Ae{name="ArithmeticError";constructor(e,r="",n=""){super(e,r,n),this.stderr=n||`bash: ${e}
151
+ `}},Te=class extends Ae{name="BadSubstitutionError";constructor(e,r="",n=""){super(e,r,n),this.stderr=n||`bash: ${e}: bad substitution
152
+ `}},B=class extends Ae{limitType;name="ExecutionLimitError";static EXIT_CODE=126;constructor(e,r,n="",s=""){super(e,n,s),this.limitType=r,this.stderr=s||`bash: ${e}
153
+ `}},Oe=class extends Ae{name="SubshellExitError";constructor(e="",r=""){super("subshell exit",e,r)}}});function Js(t,e,r){return{patternSpace:"",holdSpace:"",lineNumber:0,totalLines:t,deleted:!1,printed:!1,quit:!1,quitSilent:!1,exitCode:void 0,appendBuffer:[],substitutionMade:!1,lineNumberOutput:[],restartCycle:!1,currentFilename:e,pendingFileReads:[],pendingFileWrites:[],pendingExecute:void 0,rangeStates:r||new Map}}function Ac(t){return typeof t=="object"&&"first"in t&&"step"in t}function xt(t,e,r,n){if(t==="$")return e===r;if(typeof t=="number")return e===t;if(Ac(t)){let{first:s,step:i}=t;return i===0?e===s:(e-s)%i===0&&e>=s}if(typeof t=="object"&&"pattern"in t)try{return new RegExp(t.pattern).test(n)}catch{return!1}return!1}function Cc(t){let e=r=>r===void 0?"undefined":r==="$"?"$":typeof r=="number"?String(r):"pattern"in r?`/${r.pattern}/`:"first"in r?`${r.first}~${r.step}`:"unknown";return`${e(t.start)},${e(t.end)}`}function ct(t,e,r,n,s){if(!t||!t.start&&!t.end)return!0;let i=t.start,a=t.end;if(i!==void 0&&a===void 0)return xt(i,e,r,n);if(i!==void 0&&a!==void 0){let o=typeof i=="object"&&"pattern"in i,c=typeof a=="object"&&"pattern"in a;if(!o&&!c){let u=typeof i=="number"?i:i==="$"?r:1,f=typeof a=="number"?a:r;return e>=u&&e<=f}if(s){let u=Cc(t),f=s.get(u);return f||(f={active:!1},s.set(u,f)),f.active?(xt(a,e,r,n)&&(f.active=!1,s.set(u,f)),!0):xt(i,e,r,n)?(f.active=!0,f.startLine=e,s.set(u,f),xt(a,e,r,n)&&(f.active=!1,s.set(u,f)),!0):!1}return xt(i,e,r,n)}return!0}function Nc(t){let e="",r=0;for(;r<t.length;){if(t[r]==="\\"&&r+1<t.length){let n=t[r+1];if(n==="+"||n==="?"||n==="|"){e+=n,r+=2;continue}if(n==="("||n===")"){e+=n,r+=2;continue}if(n==="{"||n==="}"){e+=n,r+=2;continue}e+=t[r]+n,r+=2;continue}if(t[r]==="+"||t[r]==="?"||t[r]==="|"||t[r]==="("||t[r]===")"){e+=`\\${t[r]}`,r++;continue}e+=t[r],r++}return e}function vc(t){let e="";for(let r=0;r<t.length;r++){let n=t[r],s=n.charCodeAt(0);n==="\\"?e+="\\\\":n===" "?e+="\\t":n===`
154
154
  `?e+=`$
155
- `:n==="\r"?e+="\\r":n==="\x07"?e+="\\a":n==="\b"?e+="\\b":n==="\f"?e+="\\f":n==="\v"?e+="\\v":s<32||s>=127?e+=`\\${s.toString(8).padStart(3,"0")}`:e+=n}return`${e}$`}function Zs(t,e,r){let n="",s=0;for(;s<t.length;){if(t[s]==="\\"&&s+1<t.length){let i=t[s+1];if(i==="&"){n+="&",s+=2;continue}if(i==="n"){n+=`
156
- `,s+=2;continue}if(i==="t"){n+=" ",s+=2;continue}let a=parseInt(i,10);if(a>=1&&a<=9){n+=r[a-1]||"",s+=2;continue}n+=i,s+=2;continue}if(t[s]==="&"){n+=e,s++;continue}n+=t[s],s++}return n}function Cc(t,e){let{lineNumber:r,totalLines:n,patternSpace:s}=e;if(t.type!=="label"&&at(t.address,r,n,s,e.rangeStates))switch(t.type){case"substitute":{let i=t,a="";i.global&&(a+="g"),i.ignoreCase&&(a+="i");let o=i.extendedRegex?i.pattern:Sc(i.pattern);try{let c=new RegExp(o,a),l=c.test(e.patternSpace);if(c.lastIndex=0,l){if(e.substitutionMade=!0,i.nthOccurrence&&i.nthOccurrence>0&&!i.global){let u=0,f=i.nthOccurrence;e.patternSpace=e.patternSpace.replace(new RegExp(o,`g${i.ignoreCase?"i":""}`),(d,...h)=>{if(u++,u===f){let p=h.slice(0,-2);return Zs(i.replacement,d,p)}return d})}else e.patternSpace=e.patternSpace.replace(c,(u,...f)=>{let d=f.slice(0,-2);return Zs(i.replacement,u,d)});i.printOnMatch&&(e.printed=!0)}}catch{}break}case"print":e.printed=!0;break;case"printFirstLine":{let i=e.patternSpace.indexOf(`
155
+ `:n==="\r"?e+="\\r":n==="\x07"?e+="\\a":n==="\b"?e+="\\b":n==="\f"?e+="\\f":n==="\v"?e+="\\v":s<32||s>=127?e+=`\\${s.toString(8).padStart(3,"0")}`:e+=n}return`${e}$`}function Ys(t,e,r){let n="",s=0;for(;s<t.length;){if(t[s]==="\\"&&s+1<t.length){let i=t[s+1];if(i==="&"){n+="&",s+=2;continue}if(i==="n"){n+=`
156
+ `,s+=2;continue}if(i==="t"){n+=" ",s+=2;continue}let a=parseInt(i,10);if(a>=1&&a<=9){n+=r[a-1]||"",s+=2;continue}n+=i,s+=2;continue}if(t[s]==="&"){n+=e,s++;continue}n+=t[s],s++}return n}function kc(t,e){let{lineNumber:r,totalLines:n,patternSpace:s}=e;if(t.type!=="label"&&ct(t.address,r,n,s,e.rangeStates))switch(t.type){case"substitute":{let i=t,a="";i.global&&(a+="g"),i.ignoreCase&&(a+="i");let o=i.extendedRegex?i.pattern:Nc(i.pattern);try{let c=new RegExp(o,a),l=c.test(e.patternSpace);if(c.lastIndex=0,l){if(e.substitutionMade=!0,i.nthOccurrence&&i.nthOccurrence>0&&!i.global){let u=0,f=i.nthOccurrence;e.patternSpace=e.patternSpace.replace(new RegExp(o,`g${i.ignoreCase?"i":""}`),(d,...h)=>{if(u++,u===f){let p=h.slice(0,-2);return Ys(i.replacement,d,p)}return d})}else e.patternSpace=e.patternSpace.replace(c,(u,...f)=>{let d=f.slice(0,-2);return Ys(i.replacement,u,d)});i.printOnMatch&&(e.printed=!0)}}catch{}break}case"print":e.printed=!0;break;case"printFirstLine":{let i=e.patternSpace.indexOf(`
157
157
  `);i!==-1?e.lineNumberOutput.push(e.patternSpace.slice(0,i)):e.lineNumberOutput.push(e.patternSpace);break}case"delete":e.deleted=!0;break;case"deleteFirstLine":{let i=e.patternSpace.indexOf(`
158
158
  `);i!==-1?(e.patternSpace=e.patternSpace.slice(i+1),e.restartCycle=!0):e.deleted=!0;break}case"zap":e.patternSpace="";break;case"append":e.appendBuffer.push(t.text);break;case"insert":e.appendBuffer.unshift(`__INSERT__${t.text}`);break;case"change":e.patternSpace=t.text,e.deleted=!0,e.appendBuffer.push(t.text);break;case"hold":e.holdSpace=e.patternSpace;break;case"holdAppend":e.holdSpace?e.holdSpace+=`
159
159
  ${e.patternSpace}`:e.holdSpace=e.patternSpace;break;case"get":e.patternSpace=e.holdSpace;break;case"getAppend":e.patternSpace+=`
160
- ${e.holdSpace}`;break;case"exchange":{let i=e.patternSpace;e.patternSpace=e.holdSpace,e.holdSpace=i;break}case"next":e.printed=!0;break;case"quit":e.quit=!0,t.exitCode!==void 0&&(e.exitCode=t.exitCode);break;case"quitSilent":e.quit=!0,e.quitSilent=!0,t.exitCode!==void 0&&(e.exitCode=t.exitCode);break;case"list":{let i=Ac(e.patternSpace);e.lineNumberOutput.push(i);break}case"printFilename":e.currentFilename&&e.lineNumberOutput.push(e.currentFilename);break;case"version":break;case"readFile":e.pendingFileReads.push({filename:t.filename,wholeFile:!0});break;case"readFileLine":e.pendingFileReads.push({filename:t.filename,wholeFile:!1});break;case"writeFile":e.pendingFileWrites.push({filename:t.filename,content:`${e.patternSpace}
160
+ ${e.holdSpace}`;break;case"exchange":{let i=e.patternSpace;e.patternSpace=e.holdSpace,e.holdSpace=i;break}case"next":e.printed=!0;break;case"quit":e.quit=!0,t.exitCode!==void 0&&(e.exitCode=t.exitCode);break;case"quitSilent":e.quit=!0,e.quitSilent=!0,t.exitCode!==void 0&&(e.exitCode=t.exitCode);break;case"list":{let i=vc(e.patternSpace);e.lineNumberOutput.push(i);break}case"printFilename":e.currentFilename&&e.lineNumberOutput.push(e.currentFilename);break;case"version":break;case"readFile":e.pendingFileReads.push({filename:t.filename,wholeFile:!0});break;case"readFileLine":e.pendingFileReads.push({filename:t.filename,wholeFile:!1});break;case"writeFile":e.pendingFileWrites.push({filename:t.filename,content:`${e.patternSpace}
161
161
  `});break;case"writeFirstLine":{let i=e.patternSpace.indexOf(`
162
162
  `),a=i!==-1?e.patternSpace.slice(0,i):e.patternSpace;e.pendingFileWrites.push({filename:t.filename,content:`${a}
163
- `});break}case"execute":t.command?e.pendingExecute={command:t.command,replacePattern:!1}:e.pendingExecute={command:e.patternSpace,replacePattern:!0};break;case"transliterate":e.patternSpace=Nc(e.patternSpace,t);break;case"lineNumber":e.lineNumberOutput.push(String(e.lineNumber));break;case"branch":break;case"branchOnSubst":break;case"branchOnNoSubst":break;case"group":break}}function Nc(t,e){let r="";for(let n of t){let s=e.source.indexOf(n);s!==-1?r+=e.dest[s]:r+=n}return r}function Tr(t,e,r,n){let s=new Map;for(let l=0;l<t.length;l++){let u=t[l];u.type==="label"&&s.set(u.name,l)}let i=n?.maxIterations??Ec,a=0,o=0,c=0;for(;c<t.length;){if(a++,a>i)throw new W(`sed: command execution exceeded maximum iterations (${i})`,"iterations");if(e.deleted||e.quit||e.quitSilent||e.restartCycle)break;let l=t[c];if(l.type==="nextAppend"){if(at(l.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates))if(r&&r.currentLineIndex+o+1<r.lines.length){o++;let u=r.lines[r.currentLineIndex+o];e.patternSpace+=`
164
- ${u}`,e.lineNumber=r.currentLineIndex+o+1}else{e.quit=!0,e.deleted=!0;break}c++;continue}if(l.type==="branch"){let u=l;if(at(u.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates)){if(u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="branchOnSubst"){let u=l;if(at(u.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates)&&e.substitutionMade){if(e.substitutionMade=!1,u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="branchOnNoSubst"){let u=l;if(at(u.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates)&&!e.substitutionMade){if(u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="group"){let u=l;at(u.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates)&&Tr(u.commands,e,r,n),c++;continue}Cc(l,e),c++}return o}var Ec,Ks=N(()=>{"use strict";X();Ec=1e4});var I,Gt,Xs=N(()=>{"use strict";(function(t){t.NUMBER="NUMBER",t.DOLLAR="DOLLAR",t.PATTERN="PATTERN",t.STEP="STEP",t.LBRACE="LBRACE",t.RBRACE="RBRACE",t.SEMICOLON="SEMICOLON",t.NEWLINE="NEWLINE",t.COMMA="COMMA",t.COMMAND="COMMAND",t.SUBSTITUTE="SUBSTITUTE",t.TRANSLITERATE="TRANSLITERATE",t.LABEL_DEF="LABEL_DEF",t.BRANCH="BRANCH",t.BRANCH_ON_SUBST="BRANCH_ON_SUBST",t.BRANCH_ON_NO_SUBST="BRANCH_ON_NO_SUBST",t.TEXT_CMD="TEXT_CMD",t.FILE_READ="FILE_READ",t.FILE_READ_LINE="FILE_READ_LINE",t.FILE_WRITE="FILE_WRITE",t.FILE_WRITE_LINE="FILE_WRITE_LINE",t.EXECUTE="EXECUTE",t.EOF="EOF",t.ERROR="ERROR"})(I||(I={}));Gt=class{input;pos=0;line=1;column=1;constructor(e){this.input=e}tokenize(){let e=[];for(;this.pos<this.input.length;){let r=this.nextToken();r&&e.push(r)}return e.push(this.makeToken(I.EOF,"")),e}makeToken(e,r,n){return{type:e,value:r,line:this.line,column:this.column,...n}}peek(e=0){return this.input[this.pos+e]||""}advance(){let e=this.input[this.pos++]||"";return e===`
163
+ `});break}case"execute":t.command?e.pendingExecute={command:t.command,replacePattern:!1}:e.pendingExecute={command:e.patternSpace,replacePattern:!0};break;case"transliterate":e.patternSpace=Ic(e.patternSpace,t);break;case"lineNumber":e.lineNumberOutput.push(String(e.lineNumber));break;case"branch":break;case"branchOnSubst":break;case"branchOnNoSubst":break;case"group":break}}function Ic(t,e){let r="";for(let n of t){let s=e.source.indexOf(n);s!==-1?r+=e.dest[s]:r+=n}return r}function _r(t,e,r,n){let s=new Map;for(let l=0;l<t.length;l++){let u=t[l];u.type==="label"&&s.set(u.name,l)}let i=n?.maxIterations??xc,a=0,o=0,c=0;for(;c<t.length;){if(a++,a>i)throw new B(`sed: command execution exceeded maximum iterations (${i})`,"iterations");if(e.deleted||e.quit||e.quitSilent||e.restartCycle)break;let l=t[c];if(l.type==="nextAppend"){if(ct(l.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates))if(r&&r.currentLineIndex+o+1<r.lines.length){o++;let u=r.lines[r.currentLineIndex+o];e.patternSpace+=`
164
+ ${u}`,e.lineNumber=r.currentLineIndex+o+1}else{e.quit=!0,e.deleted=!0;break}c++;continue}if(l.type==="branch"){let u=l;if(ct(u.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates)){if(u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="branchOnSubst"){let u=l;if(ct(u.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates)&&e.substitutionMade){if(e.substitutionMade=!1,u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="branchOnNoSubst"){let u=l;if(ct(u.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates)&&!e.substitutionMade){if(u.label){let f=s.get(u.label);if(f!==void 0){c=f;continue}}break}c++;continue}if(l.type==="group"){let u=l;ct(u.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates)&&_r(u.commands,e,r,n),c++;continue}kc(l,e),c++}return o}var xc,ei=v(()=>{"use strict";Y();xc=1e4});var I,Zt,ti=v(()=>{"use strict";(function(t){t.NUMBER="NUMBER",t.DOLLAR="DOLLAR",t.PATTERN="PATTERN",t.STEP="STEP",t.LBRACE="LBRACE",t.RBRACE="RBRACE",t.SEMICOLON="SEMICOLON",t.NEWLINE="NEWLINE",t.COMMA="COMMA",t.COMMAND="COMMAND",t.SUBSTITUTE="SUBSTITUTE",t.TRANSLITERATE="TRANSLITERATE",t.LABEL_DEF="LABEL_DEF",t.BRANCH="BRANCH",t.BRANCH_ON_SUBST="BRANCH_ON_SUBST",t.BRANCH_ON_NO_SUBST="BRANCH_ON_NO_SUBST",t.TEXT_CMD="TEXT_CMD",t.FILE_READ="FILE_READ",t.FILE_READ_LINE="FILE_READ_LINE",t.FILE_WRITE="FILE_WRITE",t.FILE_WRITE_LINE="FILE_WRITE_LINE",t.EXECUTE="EXECUTE",t.EOF="EOF",t.ERROR="ERROR"})(I||(I={}));Zt=class{input;pos=0;line=1;column=1;constructor(e){this.input=e}tokenize(){let e=[];for(;this.pos<this.input.length;){let r=this.nextToken();r&&e.push(r)}return e.push(this.makeToken(I.EOF,"")),e}makeToken(e,r,n){return{type:e,value:r,line:this.line,column:this.column,...n}}peek(e=0){return this.input[this.pos+e]||""}advance(){let e=this.input[this.pos++]||"";return e===`
165
165
  `?(this.line++,this.column=1):this.column++,e}skipWhitespace(){for(;this.pos<this.input.length;){let e=this.peek();if(e===" "||e===" "||e==="\r")this.advance();else if(e==="#")for(;this.pos<this.input.length&&this.peek()!==`
166
166
  `;)this.advance();else break}}nextToken(){if(this.skipWhitespace(),this.pos>=this.input.length)return null;let e=this.line,r=this.column,n=this.peek();return n===`
167
167
  `?(this.advance(),{type:I.NEWLINE,value:`
@@ -181,14 +181,14 @@ ${u}`,e.lineNumber=r.currentLineIndex+o+1}else{e.quit=!0,e.deleted=!0;break}c++;
181
181
  `;)s+=this.advance();return{type:I.TEXT_CMD,value:e,text:s.trim(),line:r,column:n}}readBranch(e,r,n,s){for(;this.peek()===" "||this.peek()===" ";)this.advance();let i="";for(;this.pos<this.input.length;){let a=this.peek();if(a===" "||a===" "||a===`
182
182
  `||a===";"||a==="}"||a==="{")break;i+=this.advance()}return{type:e,value:r,label:i||void 0,line:n,column:s}}readFileCommand(e,r,n,s){for(;this.peek()===" "||this.peek()===" ";)this.advance();let i="";for(;this.pos<this.input.length;){let a=this.peek();if(a===`
183
183
  `||a===";")break;i+=this.advance()}return{type:e,value:r,filename:i.trim(),line:n,column:s}}readExecute(e,r){for(;this.peek()===" "||this.peek()===" ";)this.advance();let n="";for(;this.pos<this.input.length;){let s=this.peek();if(s===`
184
- `||s===";")break;n+=this.advance()}return{type:I.EXECUTE,value:"e",command:n.trim()||void 0,line:e,column:r}}isDigit(e){return e>="0"&&e<="9"}}});function Ys(t,e=!1){return new Fr(t,e).parse()}var Fr,Js=N(()=>{"use strict";Xs();Fr=class{scripts;tokens=[];pos=0;extendedRegex=!1;constructor(e,r=!1){this.scripts=e,this.extendedRegex=r}parse(){let e=[];for(let r of this.scripts){let n=new Gt(r);for(this.tokens=n.tokenize(),this.pos=0;!this.isAtEnd();){if(this.check(I.NEWLINE)||this.check(I.SEMICOLON)){this.advance();continue}let s=this.parseCommand();if(s.error)return{commands:[],error:s.error};s.command&&e.push(s.command)}}return{commands:e}}parseCommand(){let e=this.parseAddressRange();for(;this.check(I.NEWLINE)||this.check(I.SEMICOLON);)this.advance();if(this.isAtEnd())return e&&(e.start!==void 0||e.end!==void 0)?{command:{type:"print",address:e}}:{command:null};let r=this.peek();switch(r.type){case I.COMMAND:return this.parseSimpleCommand(r,e);case I.SUBSTITUTE:return this.parseSubstituteFromToken(r,e);case I.TRANSLITERATE:return this.parseTransliterateFromToken(r,e);case I.LABEL_DEF:return this.advance(),{command:{type:"label",name:r.label||""}};case I.BRANCH:return this.advance(),{command:{type:"branch",address:e,label:r.label}};case I.BRANCH_ON_SUBST:return this.advance(),{command:{type:"branchOnSubst",address:e,label:r.label}};case I.BRANCH_ON_NO_SUBST:return this.advance(),{command:{type:"branchOnNoSubst",address:e,label:r.label}};case I.TEXT_CMD:return this.advance(),this.parseTextCommand(r,e);case I.FILE_READ:return this.advance(),{command:{type:"readFile",address:e,filename:r.filename||""}};case I.FILE_READ_LINE:return this.advance(),{command:{type:"readFileLine",address:e,filename:r.filename||""}};case I.FILE_WRITE:return this.advance(),{command:{type:"writeFile",address:e,filename:r.filename||""}};case I.FILE_WRITE_LINE:return this.advance(),{command:{type:"writeFirstLine",address:e,filename:r.filename||""}};case I.EXECUTE:return this.advance(),{command:{type:"execute",address:e,command:r.command}};case I.LBRACE:return this.parseGroup(e);case I.RBRACE:return{command:null};case I.ERROR:return{command:null,error:`invalid command: ${r.value}`};default:return e&&(e.start!==void 0||e.end!==void 0)?{command:{type:"print",address:e}}:{command:null}}}parseSimpleCommand(e,r){this.advance();let n=e.value;switch(n){case"p":return{command:{type:"print",address:r}};case"P":return{command:{type:"printFirstLine",address:r}};case"d":return{command:{type:"delete",address:r}};case"D":return{command:{type:"deleteFirstLine",address:r}};case"h":return{command:{type:"hold",address:r}};case"H":return{command:{type:"holdAppend",address:r}};case"g":return{command:{type:"get",address:r}};case"G":return{command:{type:"getAppend",address:r}};case"x":return{command:{type:"exchange",address:r}};case"n":return{command:{type:"next",address:r}};case"N":return{command:{type:"nextAppend",address:r}};case"q":return{command:{type:"quit",address:r}};case"Q":return{command:{type:"quitSilent",address:r}};case"z":return{command:{type:"zap",address:r}};case"=":return{command:{type:"lineNumber",address:r}};case"l":return{command:{type:"list",address:r}};case"F":return{command:{type:"printFilename",address:r}};case"v":return{command:{type:"version",address:r}};default:return{command:null,error:`unknown command: ${n}`}}}parseSubstituteFromToken(e,r){this.advance();let n=e.flags||"",s,i=n.match(/(\d+)/);return i&&(s=parseInt(i[1],10)),{command:{type:"substitute",address:r,pattern:e.pattern||"",replacement:e.replacement||"",global:n.includes("g"),ignoreCase:n.includes("i")||n.includes("I"),printOnMatch:n.includes("p"),nthOccurrence:s,extendedRegex:this.extendedRegex}}}parseTransliterateFromToken(e,r){this.advance();let n=e.source||"",s=e.dest||"";return n.length!==s.length?{command:null,error:"transliteration sets must have same length"}:{command:{type:"transliterate",address:r,source:n,dest:s}}}parseTextCommand(e,r){let n=e.value,s=e.text||"";switch(n){case"a":return{command:{type:"append",address:r,text:s}};case"i":return{command:{type:"insert",address:r,text:s}};case"c":return{command:{type:"change",address:r,text:s}};default:return{command:null,error:`unknown text command: ${n}`}}}parseGroup(e){this.advance();let r=[];for(;!this.isAtEnd()&&!this.check(I.RBRACE);){if(this.check(I.NEWLINE)||this.check(I.SEMICOLON)){this.advance();continue}let n=this.parseCommand();if(n.error)return{command:null,error:n.error};n.command&&r.push(n.command)}return this.check(I.RBRACE)?(this.advance(),{command:{type:"group",address:e,commands:r}}):{command:null,error:"unmatched brace in grouped commands"}}parseAddressRange(){let e=this.parseAddress();if(e===void 0)return;let r;return this.check(I.COMMA)&&(this.advance(),r=this.parseAddress()),{start:e,end:r}}parseAddress(){let e=this.peek();switch(e.type){case I.NUMBER:return this.advance(),e.value;case I.DOLLAR:return this.advance(),"$";case I.PATTERN:return this.advance(),{pattern:e.pattern||e.value};case I.STEP:return this.advance(),{first:e.first||0,step:e.step||0};default:return}}peek(){return this.tokens[this.pos]||{type:I.EOF,value:"",line:0,column:0}}advance(){return this.isAtEnd()||this.pos++,this.tokens[this.pos-1]}check(e){return this.peek().type===e}isAtEnd(){return this.peek().type===I.EOF}}});var ei={};O(ei,{sedCommand:()=>kc});async function Mr(t,e,r,n={}){let{limits:s,filename:i,fs:a,cwd:o}=n,c=t.split(`
185
- `);c.length>0&&c[c.length-1]===""&&c.pop();let l=c.length,u="",f,d="",h=new Map,p=new Map,b=new Map,w=new Map,g=s?{maxIterations:s.maxSedIterations}:void 0;for(let E=0;E<c.length;E++){let x={...Qs(l,i,h),patternSpace:c[E],holdSpace:d,lineNumber:E+1,totalLines:l,substitutionMade:!1},S={lines:c,currentLineIndex:E},v=0,R=1e4,M=0;do{if(v++,v>R)break;x.restartCycle=!1,x.pendingFileReads=[],x.pendingFileWrites=[];let K=Tr(e,x,S,g);if(M+=K,a&&o){for(let Ee of x.pendingFileReads){let ne=a.resolvePath(o,Ee.filename);try{if(Ee.wholeFile){let de=await a.readFile(ne);x.appendBuffer.push(de.replace(/\n$/,""))}else{if(!p.has(ne)){let Ir=await a.readFile(ne);p.set(ne,Ir.split(`
186
- `)),b.set(ne,0)}let de=p.get(ne),oe=b.get(ne);de&&oe!==void 0&&oe<de.length&&(x.appendBuffer.push(de[oe]),b.set(ne,oe+1))}}catch{}}for(let Ee of x.pendingFileWrites){let ne=a.resolvePath(o,Ee.filename),de=w.get(ne)||"";w.set(ne,de+Ee.content)}}S.currentLineIndex+=K}while(x.restartCycle&&!x.deleted&&!x.quit&&!x.quitSilent);E+=M,d=x.holdSpace;for(let K of x.lineNumberOutput)u+=`${K}
187
- `;let _=[],Oe=[];for(let K of x.appendBuffer)K.startsWith("__INSERT__")?_.push(K.slice(10)):Oe.push(K);for(let K of _)u+=`${K}
188
- `;!x.deleted&&!x.quitSilent&&(r?x.printed&&(u+=`${x.patternSpace}
189
- `):u+=`${x.patternSpace}
190
- `);for(let K of Oe)u+=`${K}
191
- `;if(x.quit||x.quitSilent){x.exitCode!==void 0&&(f=x.exitCode);break}}if(a&&o)for(let[E,x]of w)try{await a.writeFile(E,x)}catch{}return{output:u,exitCode:f}}var vc,kc,ti=N(()=>{"use strict";X();L();Ks();Js();vc={name:"sed",summary:"stream editor for filtering and transforming text",usage:"sed [OPTION]... {script} [input-file]...",options:["-n, --quiet, --silent suppress automatic printing of pattern space","-e script add the script to commands to be executed","-f script-file read script from file","-i, --in-place edit files in place","-E, -r, --regexp-extended use extended regular expressions"," --help display this help and exit"],description:`Commands:
184
+ `||s===";")break;n+=this.advance()}return{type:I.EXECUTE,value:"e",command:n.trim()||void 0,line:e,column:r}}isDigit(e){return e>="0"&&e<="9"}}});function ri(t,e=!1){return new Wr(t,e).parse()}var Wr,ni=v(()=>{"use strict";ti();Wr=class{scripts;tokens=[];pos=0;extendedRegex=!1;constructor(e,r=!1){this.scripts=e,this.extendedRegex=r}parse(){let e=[];for(let r of this.scripts){let n=new Zt(r);for(this.tokens=n.tokenize(),this.pos=0;!this.isAtEnd();){if(this.check(I.NEWLINE)||this.check(I.SEMICOLON)){this.advance();continue}let s=this.parseCommand();if(s.error)return{commands:[],error:s.error};s.command&&e.push(s.command)}}return{commands:e}}parseCommand(){let e=this.parseAddressRange();for(;this.check(I.NEWLINE)||this.check(I.SEMICOLON);)this.advance();if(this.isAtEnd())return e&&(e.start!==void 0||e.end!==void 0)?{command:{type:"print",address:e}}:{command:null};let r=this.peek();switch(r.type){case I.COMMAND:return this.parseSimpleCommand(r,e);case I.SUBSTITUTE:return this.parseSubstituteFromToken(r,e);case I.TRANSLITERATE:return this.parseTransliterateFromToken(r,e);case I.LABEL_DEF:return this.advance(),{command:{type:"label",name:r.label||""}};case I.BRANCH:return this.advance(),{command:{type:"branch",address:e,label:r.label}};case I.BRANCH_ON_SUBST:return this.advance(),{command:{type:"branchOnSubst",address:e,label:r.label}};case I.BRANCH_ON_NO_SUBST:return this.advance(),{command:{type:"branchOnNoSubst",address:e,label:r.label}};case I.TEXT_CMD:return this.advance(),this.parseTextCommand(r,e);case I.FILE_READ:return this.advance(),{command:{type:"readFile",address:e,filename:r.filename||""}};case I.FILE_READ_LINE:return this.advance(),{command:{type:"readFileLine",address:e,filename:r.filename||""}};case I.FILE_WRITE:return this.advance(),{command:{type:"writeFile",address:e,filename:r.filename||""}};case I.FILE_WRITE_LINE:return this.advance(),{command:{type:"writeFirstLine",address:e,filename:r.filename||""}};case I.EXECUTE:return this.advance(),{command:{type:"execute",address:e,command:r.command}};case I.LBRACE:return this.parseGroup(e);case I.RBRACE:return{command:null};case I.ERROR:return{command:null,error:`invalid command: ${r.value}`};default:return e&&(e.start!==void 0||e.end!==void 0)?{command:{type:"print",address:e}}:{command:null}}}parseSimpleCommand(e,r){this.advance();let n=e.value;switch(n){case"p":return{command:{type:"print",address:r}};case"P":return{command:{type:"printFirstLine",address:r}};case"d":return{command:{type:"delete",address:r}};case"D":return{command:{type:"deleteFirstLine",address:r}};case"h":return{command:{type:"hold",address:r}};case"H":return{command:{type:"holdAppend",address:r}};case"g":return{command:{type:"get",address:r}};case"G":return{command:{type:"getAppend",address:r}};case"x":return{command:{type:"exchange",address:r}};case"n":return{command:{type:"next",address:r}};case"N":return{command:{type:"nextAppend",address:r}};case"q":return{command:{type:"quit",address:r}};case"Q":return{command:{type:"quitSilent",address:r}};case"z":return{command:{type:"zap",address:r}};case"=":return{command:{type:"lineNumber",address:r}};case"l":return{command:{type:"list",address:r}};case"F":return{command:{type:"printFilename",address:r}};case"v":return{command:{type:"version",address:r}};default:return{command:null,error:`unknown command: ${n}`}}}parseSubstituteFromToken(e,r){this.advance();let n=e.flags||"",s,i=n.match(/(\d+)/);return i&&(s=parseInt(i[1],10)),{command:{type:"substitute",address:r,pattern:e.pattern||"",replacement:e.replacement||"",global:n.includes("g"),ignoreCase:n.includes("i")||n.includes("I"),printOnMatch:n.includes("p"),nthOccurrence:s,extendedRegex:this.extendedRegex}}}parseTransliterateFromToken(e,r){this.advance();let n=e.source||"",s=e.dest||"";return n.length!==s.length?{command:null,error:"transliteration sets must have same length"}:{command:{type:"transliterate",address:r,source:n,dest:s}}}parseTextCommand(e,r){let n=e.value,s=e.text||"";switch(n){case"a":return{command:{type:"append",address:r,text:s}};case"i":return{command:{type:"insert",address:r,text:s}};case"c":return{command:{type:"change",address:r,text:s}};default:return{command:null,error:`unknown text command: ${n}`}}}parseGroup(e){this.advance();let r=[];for(;!this.isAtEnd()&&!this.check(I.RBRACE);){if(this.check(I.NEWLINE)||this.check(I.SEMICOLON)){this.advance();continue}let n=this.parseCommand();if(n.error)return{command:null,error:n.error};n.command&&r.push(n.command)}return this.check(I.RBRACE)?(this.advance(),{command:{type:"group",address:e,commands:r}}):{command:null,error:"unmatched brace in grouped commands"}}parseAddressRange(){let e=this.parseAddress();if(e===void 0)return;let r;return this.check(I.COMMA)&&(this.advance(),r=this.parseAddress()),{start:e,end:r}}parseAddress(){let e=this.peek();switch(e.type){case I.NUMBER:return this.advance(),e.value;case I.DOLLAR:return this.advance(),"$";case I.PATTERN:return this.advance(),{pattern:e.pattern||e.value};case I.STEP:return this.advance(),{first:e.first||0,step:e.step||0};default:return}}peek(){return this.tokens[this.pos]||{type:I.EOF,value:"",line:0,column:0}}advance(){return this.isAtEnd()||this.pos++,this.tokens[this.pos-1]}check(e){return this.peek().type===e}isAtEnd(){return this.peek().type===I.EOF}}});var si={};D(si,{sedCommand:()=>Rc});async function Br(t,e,r,n={}){let{limits:s,filename:i,fs:a,cwd:o}=n,c=t.split(`
185
+ `);c.length>0&&c[c.length-1]===""&&c.pop();let l=c.length,u="",f,d="",h=new Map,p=new Map,E=new Map,w=new Map,g=s?{maxIterations:s.maxSedIterations}:void 0;for(let b=0;b<c.length;b++){let S={...Js(l,i,h),patternSpace:c[b],holdSpace:d,lineNumber:b+1,totalLines:l,substitutionMade:!1},x={lines:c,currentLineIndex:b},A=0,O=1e4,L=0;do{if(A++,A>O)break;S.restartCycle=!1,S.pendingFileReads=[],S.pendingFileWrites=[];let Q=_r(e,S,x,g);if(L+=Q,a&&o){for(let pe of S.pendingFileReads){let re=a.resolvePath(o,pe.filename);try{if(pe.wholeFile){let ge=await a.readFile(re);S.appendBuffer.push(ge.replace(/\n$/,""))}else{if(!p.has(re)){let at=await a.readFile(re);p.set(re,at.split(`
186
+ `)),E.set(re,0)}let ge=p.get(re),me=E.get(re);ge&&me!==void 0&&me<ge.length&&(S.appendBuffer.push(ge[me]),E.set(re,me+1))}}catch{}}for(let pe of S.pendingFileWrites){let re=a.resolvePath(o,pe.filename),ge=w.get(re)||"";w.set(re,ge+pe.content)}}x.currentLineIndex+=Q}while(S.restartCycle&&!S.deleted&&!S.quit&&!S.quitSilent);b+=L,d=S.holdSpace;for(let Q of S.lineNumberOutput)u+=`${Q}
187
+ `;let R=[],U=[];for(let Q of S.appendBuffer)Q.startsWith("__INSERT__")?R.push(Q.slice(10)):U.push(Q);for(let Q of R)u+=`${Q}
188
+ `;!S.deleted&&!S.quitSilent&&(r?S.printed&&(u+=`${S.patternSpace}
189
+ `):u+=`${S.patternSpace}
190
+ `);for(let Q of U)u+=`${Q}
191
+ `;if(S.quit||S.quitSilent){S.exitCode!==void 0&&(f=S.exitCode);break}}if(a&&o)for(let[b,S]of w)try{await a.writeFile(b,S)}catch{}return{output:u,exitCode:f}}var $c,Rc,ii=v(()=>{"use strict";Y();F();ei();ni();$c={name:"sed",summary:"stream editor for filtering and transforming text",usage:"sed [OPTION]... {script} [input-file]...",options:["-n, --quiet, --silent suppress automatic printing of pattern space","-e script add the script to commands to be executed","-f script-file read script from file","-i, --in-place edit files in place","-E, -r, --regexp-extended use extended regular expressions"," --help display this help and exit"],description:`Commands:
192
192
  s/regexp/replacement/[flags] substitute
193
193
  d delete pattern space
194
194
  p print pattern space
@@ -217,36 +217,36 @@ Addresses:
217
217
  $ last line
218
218
  /regexp/ lines matching regexp
219
219
  N,M range from line N to M
220
- first~step every step-th line starting at first`};kc={name:"sed",async execute(t,e){if(C(t))return A(vc);let r=[],n=[],s=!1,i=!1,a=!1,o=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-n"||d==="--quiet"||d==="--silent")s=!0;else if(d==="-i"||d==="--in-place")i=!0;else if(d.startsWith("-i"))i=!0;else if(d==="-E"||d==="-r"||d==="--regexp-extended")a=!0;else if(d==="-e")f+1<t.length&&r.push(t[++f]);else if(d==="-f")f+1<t.length&&n.push(t[++f]);else{if(d.startsWith("--"))return T("sed",d);if(d.startsWith("-")&&d.length>1){for(let h of d.slice(1))if(h!=="n"&&h!=="e"&&h!=="f"&&h!=="i"&&h!=="E"&&h!=="r")return T("sed",`-${h}`);d.includes("n")&&(s=!0),d.includes("i")&&(i=!0),(d.includes("E")||d.includes("r"))&&(a=!0),d.includes("e")&&!d.includes("n")&&!d.includes("i")&&f+1<t.length&&r.push(t[++f]),d.includes("f")&&!d.includes("e")&&f+1<t.length&&n.push(t[++f])}else!d.startsWith("-")&&r.length===0&&n.length===0?r.push(d):d.startsWith("-")||o.push(d)}}for(let f of n){let d=e.fs.resolvePath(e.cwd,f);try{let h=await e.fs.readFile(d);for(let p of h.split(`
221
- `)){let b=p.trim();b&&!b.startsWith("#")&&r.push(b)}}catch{return{stdout:"",stderr:`sed: couldn't open file ${f}: No such file or directory
220
+ first~step every step-th line starting at first`};Rc={name:"sed",async execute(t,e){if(N(t))return C($c);let r=[],n=[],s=!1,i=!1,a=!1,o=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-n"||d==="--quiet"||d==="--silent")s=!0;else if(d==="-i"||d==="--in-place")i=!0;else if(d.startsWith("-i"))i=!0;else if(d==="-E"||d==="-r"||d==="--regexp-extended")a=!0;else if(d==="-e")f+1<t.length&&r.push(t[++f]);else if(d==="-f")f+1<t.length&&n.push(t[++f]);else{if(d.startsWith("--"))return M("sed",d);if(d.startsWith("-")&&d.length>1){for(let h of d.slice(1))if(h!=="n"&&h!=="e"&&h!=="f"&&h!=="i"&&h!=="E"&&h!=="r")return M("sed",`-${h}`);d.includes("n")&&(s=!0),d.includes("i")&&(i=!0),(d.includes("E")||d.includes("r"))&&(a=!0),d.includes("e")&&!d.includes("n")&&!d.includes("i")&&f+1<t.length&&r.push(t[++f]),d.includes("f")&&!d.includes("e")&&f+1<t.length&&n.push(t[++f])}else!d.startsWith("-")&&r.length===0&&n.length===0?r.push(d):d.startsWith("-")||o.push(d)}}for(let f of n){let d=e.fs.resolvePath(e.cwd,f);try{let h=await e.fs.readFile(d);for(let p of h.split(`
221
+ `)){let E=p.trim();E&&!E.startsWith("#")&&r.push(E)}}catch{return{stdout:"",stderr:`sed: couldn't open file ${f}: No such file or directory
222
222
  `,exitCode:1}}}if(r.length===0)return{stdout:"",stderr:`sed: no script specified
223
- `,exitCode:1};let{commands:c,error:l}=Ys(r,a);if(l)return{stdout:"",stderr:`sed: ${l}
223
+ `,exitCode:1};let{commands:c,error:l}=ri(r,a);if(l)return{stdout:"",stderr:`sed: ${l}
224
224
  `,exitCode:1};if(c.length===0)return{stdout:"",stderr:`sed: no valid commands
225
- `,exitCode:1};let u="";if(o.length===0){u=e.stdin;try{let f=await Mr(u,c,s,{limits:e.limits,fs:e.fs,cwd:e.cwd});return{stdout:f.output,stderr:"",exitCode:f.exitCode??0}}catch(f){if(f instanceof W)return{stdout:"",stderr:`sed: ${f.message}
226
- `,exitCode:W.EXIT_CODE};throw f}}if(i){for(let f of o){let d=e.fs.resolvePath(e.cwd,f);try{let h=await e.fs.readFile(d),p=await Mr(h,c,s,{limits:e.limits,filename:f,fs:e.fs,cwd:e.cwd});await e.fs.writeFile(d,p.output)}catch(h){return h instanceof W?{stdout:"",stderr:`sed: ${h.message}
227
- `,exitCode:W.EXIT_CODE}:{stdout:"",stderr:`sed: ${f}: No such file or directory
228
- `,exitCode:1}}}return{stdout:"",stderr:"",exitCode:0}}for(let f of o){let d=e.fs.resolvePath(e.cwd,f);try{u+=await e.fs.readFile(d)}catch(h){return h instanceof W?{stdout:"",stderr:`sed: ${h.message}
229
- `,exitCode:W.EXIT_CODE}:{stdout:"",stderr:`sed: ${f}: No such file or directory
230
- `,exitCode:1}}}try{let f=await Mr(u,c,s,{limits:e.limits,filename:o.length===1?o[0]:void 0,fs:e.fs,cwd:e.cwd});return{stdout:f.output,stderr:"",exitCode:f.exitCode??0}}catch(f){if(f instanceof W)return{stdout:"",stderr:`sed: ${f.message}
231
- `,exitCode:W.EXIT_CODE};throw f}}}});function _r(t={}){let{fieldSep:e=/\s+/,maxIterations:r=1e4,maxRecursionDepth:n=100,fs:s,cwd:i}=t;return{FS:" ",OFS:" ",ORS:`
232
- `,NR:0,NF:0,FNR:0,FILENAME:"",RSTART:0,RLENGTH:-1,SUBSEP:"",fields:[],line:"",vars:{},arrays:{},ARGC:0,ARGV:{},functions:new Map,fieldSep:e,maxIterations:r,maxRecursionDepth:n,currentRecursionDepth:0,exitCode:0,shouldExit:!1,shouldNext:!1,shouldNextFile:!1,loopBreak:!1,loopContinue:!1,hasReturn:!1,output:"",openedFiles:new Set,fs:s,cwd:i}}var ri=N(()=>{"use strict"});function ni(t,e,r){switch(r){case"+":return t+e;case"-":return t-e;case"*":return t*e;case"/":return e!==0?t/e:0;case"%":return e!==0?t%e:0;case"^":case"**":return t**e;default:return 0}}var si=N(()=>{"use strict"});function me(t){if(typeof t=="number")return t;let e=parseFloat(t);return Number.isNaN(e)?0:e}function ee(t){return typeof t=="string"?t:(Number.isInteger(t),String(t))}async function Ic(t,e,r){return t.length===0?e.line.length:ee(await r.evalExpr(t[0])).length}async function Rc(t,e,r){if(t.length<2)return"";let n=ee(await r.evalExpr(t[0])),s=Math.floor(me(await r.evalExpr(t[1])))-1;if(t.length>=3){let i=Math.floor(me(await r.evalExpr(t[2])));return n.substr(Math.max(0,s),i)}return n.substr(Math.max(0,s))}async function $c(t,e,r){if(t.length<2)return 0;let n=ee(await r.evalExpr(t[0])),s=ee(await r.evalExpr(t[1])),i=n.indexOf(s);return i===-1?0:i+1}async function Pc(t,e,r){if(t.length<2)return 0;let n=ee(await r.evalExpr(t[0])),s=t[1];if(s.type!=="variable")return 0;let i=s.name,a=e.FS;if(t.length>=3){let c=ee(await r.evalExpr(t[2]));a=c===" "?/\s+/:c}else e.FS===" "&&(a=/\s+/);let o=n.split(a);e.arrays[i]={};for(let c=0;c<o.length;c++)e.arrays[i][String(c+1)]=o[c];return o.length}async function Oc(t,e,r){if(t.length<2)return 0;let n;t[0].type==="regex"?n=t[0].pattern:(n=ee(await r.evalExpr(t[0])),n.startsWith("/")&&n.endsWith("/")&&(n=n.slice(1,-1)));let s=ee(await r.evalExpr(t[1])),i="$0";if(t.length>=3){let o=t[2];o.type==="variable"?i=o.name:o.type==="field"&&(i=`$${Math.floor(me(await r.evalExpr(o.index)))}`)}let a;if(i==="$0")a=e.line;else if(i.startsWith("$")){let o=parseInt(i.slice(1),10)-1;a=e.fields[o]||""}else a=ee(e.vars[i]??"");try{let o=new RegExp(n),c=a.replace(o,ai(s)),l=c!==a?1:0;if(i==="$0")e.line=c,e.fields=e.FS===" "?c.trim().split(/\s+/).filter(Boolean):c.split(e.fieldSep),e.NF=e.fields.length;else if(i.startsWith("$")){let u=parseInt(i.slice(1),10)-1;for(;e.fields.length<=u;)e.fields.push("");e.fields[u]=c,e.NF=e.fields.length,e.line=e.fields.join(e.OFS)}else e.vars[i]=c;return l}catch{return 0}}async function Dc(t,e,r){if(t.length<2)return 0;let n;t[0].type==="regex"?n=t[0].pattern:(n=ee(await r.evalExpr(t[0])),n.startsWith("/")&&n.endsWith("/")&&(n=n.slice(1,-1)));let s=ee(await r.evalExpr(t[1])),i="$0";if(t.length>=3){let o=t[2];o.type==="variable"?i=o.name:o.type==="field"&&(i=`$${Math.floor(me(await r.evalExpr(o.index)))}`)}let a;if(i==="$0")a=e.line;else if(i.startsWith("$")){let o=parseInt(i.slice(1),10)-1;a=e.fields[o]||""}else a=ee(e.vars[i]??"");try{let o=new RegExp(n,"g"),c=a.match(o),l=c?c.length:0,u=a.replace(o,ai(s));if(i==="$0")e.line=u,e.fields=e.FS===" "?u.trim().split(/\s+/).filter(Boolean):u.split(e.fieldSep),e.NF=e.fields.length;else if(i.startsWith("$")){let f=parseInt(i.slice(1),10)-1;for(;e.fields.length<=f;)e.fields.push("");e.fields[f]=u,e.NF=e.fields.length,e.line=e.fields.join(e.OFS)}else e.vars[i]=u;return l}catch{return 0}}function ai(t){return e=>{let r="",n=0;for(;n<t.length;)if(t[n]==="\\"&&n+1<t.length){let s=t[n+1];s==="&"?(r+="&",n+=2):s==="\\"?(r+="\\",n+=2):(r+=t[n+1],n+=2)}else t[n]==="&"?(r+=e,n++):(r+=t[n],n++);return r}}async function Lc(t,e,r){if(t.length<2)return e.RSTART=0,e.RLENGTH=-1,0;let n=ee(await r.evalExpr(t[0])),s;t[1].type==="regex"?s=t[1].pattern:(s=ee(await r.evalExpr(t[1])),s.startsWith("/")&&s.endsWith("/")&&(s=s.slice(1,-1)));try{let a=new RegExp(s).exec(n);if(a)return e.RSTART=a.index+1,e.RLENGTH=a[0].length,e.RSTART}catch{}return e.RSTART=0,e.RLENGTH=-1,0}async function Tc(t,e,r){if(t.length<3)return"";let n;t[0].type==="regex"?n=t[0].pattern:(n=ee(await r.evalExpr(t[0])),n.startsWith("/")&&n.endsWith("/")&&(n=n.slice(1,-1)));let s=ee(await r.evalExpr(t[1])),i=ee(await r.evalExpr(t[2])),a=t.length>=4?ee(await r.evalExpr(t[3])):e.line;try{let o=i.toLowerCase()==="g",c=o?0:parseInt(i,10)||1;if(o){let l=new RegExp(n,"g");return a.replace(l,(u,...f)=>ii(s,u,f.slice(0,-2)))}else{let l=0,u=new RegExp(n,"g");return a.replace(u,(f,...d)=>(l++,l===c?ii(s,f,d.slice(0,-2)):f))}}catch{return a}}function ii(t,e,r){let n="",s=0;for(;s<t.length;)if(t[s]==="\\"&&s+1<t.length){let i=t[s+1];if(i==="&")n+="&",s+=2;else if(i==="0")n+=e,s+=2;else if(i>="1"&&i<="9"){let a=parseInt(i,10)-1;n+=r[a]||"",s+=2}else i==="n"?(n+=`
233
- `,s+=2):i==="t"?(n+=" ",s+=2):(n+=i,s+=2)}else t[s]==="&"?(n+=e,s++):(n+=t[s],s++);return n}async function Fc(t,e,r){return t.length===0?"":ee(await r.evalExpr(t[0])).toLowerCase()}async function Mc(t,e,r){return t.length===0?"":ee(await r.evalExpr(t[0])).toUpperCase()}async function _c(t,e,r){if(t.length===0)return"";let n=ee(await r.evalExpr(t[0])),s=[];for(let i=1;i<t.length;i++)s.push(await r.evalExpr(t[i]));return Hr(n,s)}async function Wc(t,e,r){return t.length===0?0:Math.floor(me(await r.evalExpr(t[0])))}async function Bc(t,e,r){return t.length===0?0:Math.sqrt(me(await r.evalExpr(t[0])))}async function Hc(t,e,r){return t.length===0?0:Math.sin(me(await r.evalExpr(t[0])))}async function Uc(t,e,r){return t.length===0?0:Math.cos(me(await r.evalExpr(t[0])))}async function zc(t,e,r){let n=t.length>0?me(await r.evalExpr(t[0])):0,s=t.length>1?me(await r.evalExpr(t[1])):0;return Math.atan2(n,s)}async function Gc(t,e,r){return t.length===0?0:Math.log(me(await r.evalExpr(t[0])))}async function jc(t,e,r){return t.length===0?1:Math.exp(me(await r.evalExpr(t[0])))}function qc(t,e,r){return e.random?e.random():Math.random()}async function Vc(t,e,r){let n=t.length>0?me(await r.evalExpr(t[0])):Date.now();return e.vars._srand_seed=n,n}function Wr(t,e){return()=>{throw new Error(`${t}() is not supported - ${e}`)}}function Br(t){return()=>{throw new Error(`function '${t}()' is not implemented`)}}function Hr(t,e){let r=0,n="",s=0;for(;s<t.length;)if(t[s]==="%"&&s+1<t.length){let i=s+1,a="",o="",c="";for(;i<t.length&&/[-+ #0]/.test(t[i]);)a+=t[i++];for(;i<t.length&&/\d/.test(t[i]);)o+=t[i++];if(t[i]===".")for(i++;i<t.length&&/\d/.test(t[i]);)c+=t[i++];let l=t[i],u=e[r];switch(l){case"s":{let f=u!==void 0?String(u):"";if(c&&(f=f.substring(0,parseInt(c,10))),o){let d=parseInt(o,10);a.includes("-")?f=f.padEnd(d):f=f.padStart(d)}n+=f,r++;break}case"d":case"i":{let f=u!==void 0?Math.floor(Number(u)):0;Number.isNaN(f)&&(f=0);let d=String(f);if(o){let h=parseInt(o,10);if(a.includes("-"))d=d.padEnd(h);else if(a.includes("0")&&!a.includes("-")){let p=f<0?"-":"";d=p+Math.abs(f).toString().padStart(h-p.length,"0")}else d=d.padStart(h)}n+=d,r++;break}case"f":{let f=u!==void 0?Number(u):0;Number.isNaN(f)&&(f=0);let d=c?parseInt(c,10):6,h=f.toFixed(d);if(o){let p=parseInt(o,10);a.includes("-")?h=h.padEnd(p):h=h.padStart(p)}n+=h,r++;break}case"e":case"E":{let f=u!==void 0?Number(u):0;Number.isNaN(f)&&(f=0);let d=c?parseInt(c,10):6,h=f.toExponential(d);if(l==="E"&&(h=h.toUpperCase()),o){let p=parseInt(o,10);a.includes("-")?h=h.padEnd(p):h=h.padStart(p)}n+=h,r++;break}case"g":case"G":{let f=u!==void 0?Number(u):0;Number.isNaN(f)&&(f=0);let d=c?parseInt(c,10):6,h=f!==0?Math.floor(Math.log10(Math.abs(f))):0,p;if(f===0?p="0":h<-4||h>=d?(p=f.toExponential(d-1),l==="G"&&(p=p.toUpperCase())):p=f.toPrecision(d),p=p.replace(/\.?0+$/,"").replace(/\.?0+e/,"e"),o){let b=parseInt(o,10);a.includes("-")?p=p.padEnd(b):p=p.padStart(b)}n+=p,r++;break}case"x":case"X":{let f=u!==void 0?Math.floor(Number(u)):0;Number.isNaN(f)&&(f=0);let d=Math.abs(f).toString(16);if(l==="X"&&(d=d.toUpperCase()),o){let h=parseInt(o,10);a.includes("0")?d=d.padStart(h,"0"):a.includes("-")?d=d.padEnd(h):d=d.padStart(h)}n+=f<0?`-${d}`:d,r++;break}case"o":{let f=u!==void 0?Math.floor(Number(u)):0;Number.isNaN(f)&&(f=0);let d=Math.abs(f).toString(8);if(o){let h=parseInt(o,10);a.includes("0")?d=d.padStart(h,"0"):a.includes("-")?d=d.padEnd(h):d=d.padStart(h)}n+=f<0?`-${d}`:d,r++;break}case"c":{typeof u=="number"?n+=String.fromCharCode(u):n+=String(u??"").charAt(0)||"",r++;break}case"%":n+="%";break;default:n+=t.substring(s,i+1)}s=i+1}else if(t[s]==="\\"&&s+1<t.length){let i=t[s+1];switch(i){case"n":n+=`
234
- `;break;case"t":n+=" ";break;case"r":n+="\r";break;case"\\":n+="\\";break;default:n+=i}s+=2}else n+=t[s++];return n}var oi,Ur=N(()=>{"use strict";oi={length:Ic,substr:Rc,index:$c,split:Pc,sub:Oc,gsub:Dc,match:Lc,gensub:Tc,tolower:Fc,toupper:Mc,sprintf:_c,int:Wc,sqrt:Bc,sin:Hc,cos:Uc,atan2:zc,log:Gc,exp:jc,rand:qc,srand:Vc,system:Wr("system","shell execution not allowed in sandboxed environment"),close:Wr("close","file operations not allowed"),fflush:Wr("fflush","file operations not allowed"),systime:Br("systime"),mktime:Br("mktime"),strftime:Br("strftime")}});function he(t){return typeof t=="number"?t!==0:t!==""}function B(t){if(typeof t=="number")return t;let e=parseFloat(t);return Number.isNaN(e)?0:e}function U(t){return typeof t=="string"?t:(Number.isInteger(t),String(t))}function zr(t){if(typeof t=="number")return!0;let e=String(t).trim();return e===""?!1:!Number.isNaN(Number(e))}function xt(t,e){try{return new RegExp(t).test(e)}catch{return!1}}var ot=N(()=>{"use strict"});function li(t,e){return t.FS===" "?e.trim().split(/\s+/).filter(Boolean):e.split(t.fieldSep)}function Qe(t,e){return e===0?t.line:e<0||e>t.fields.length?"":t.fields[e-1]??""}function lt(t,e,r){if(e===0)t.line=U(r),t.fields=li(t,t.line),t.NF=t.fields.length;else if(e>0){for(;t.fields.length<e;)t.fields.push("");t.fields[e-1]=U(r),t.NF=t.fields.length,t.line=t.fields.join(t.OFS)}}function St(t,e){t.line=e,t.fields=li(t,e),t.NF=t.fields.length}function ci(t,e){if(t.FS=e,e===" ")t.fieldSep=/\s+/;else try{t.fieldSep=new RegExp(e)}catch{t.fieldSep=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"))}}var jt=N(()=>{"use strict";ot()});function Ke(t,e){switch(e){case"FS":return t.FS;case"OFS":return t.OFS;case"ORS":return t.ORS;case"NR":return t.NR;case"NF":return t.NF;case"FNR":return t.FNR;case"FILENAME":return t.FILENAME;case"RSTART":return t.RSTART;case"RLENGTH":return t.RLENGTH;case"SUBSEP":return t.SUBSEP;case"ARGC":return t.ARGC}return t.vars[e]??""}function He(t,e,r){switch(e){case"FS":ci(t,U(r));return;case"OFS":t.OFS=U(r);return;case"ORS":t.ORS=U(r);return;case"NR":t.NR=Math.floor(B(r));return;case"NF":{let n=Math.floor(B(r));if(n<t.NF)t.fields=t.fields.slice(0,n),t.line=t.fields.join(t.OFS);else if(n>t.NF){for(;t.fields.length<n;)t.fields.push("");t.line=t.fields.join(t.OFS)}t.NF=n;return}case"FNR":t.FNR=Math.floor(B(r));return;case"FILENAME":t.FILENAME=U(r);return;case"RSTART":t.RSTART=Math.floor(B(r));return;case"RLENGTH":t.RLENGTH=Math.floor(B(r));return;case"SUBSEP":t.SUBSEP=U(r);return}t.vars[e]=r}function Xe(t,e,r){return e==="ARGV"?t.ARGV[r]??"":t.arrays[e]?.[r]??""}function ct(t,e,r,n){t.arrays[e]||(t.arrays[e]={}),t.arrays[e][r]=n}function ui(t,e,r){return e==="ARGV"?t.ARGV[r]!==void 0:t.arrays[e]?.[r]!==void 0}function fi(t,e,r){t.arrays[e]&&delete t.arrays[e][r]}function di(t,e){delete t.arrays[e]}var Gr=N(()=>{"use strict";jt();ot()});function hi(t){jr=t}async function P(t,e){switch(e.type){case"number":return e.value;case"string":return e.value;case"regex":return xt(e.pattern,t.line)?1:0;case"field":return Zc(t,e);case"variable":return Ke(t,e.name);case"array_access":return Qc(t,e);case"binary":return Kc(t,e);case"unary":return Jc(t,e);case"ternary":return he(await P(t,e.condition))?P(t,e.consequent):P(t,e.alternate);case"call":return eu(t,e.name,e.args);case"assignment":return ru(t,e);case"pre_increment":return nu(t,e.operand);case"pre_decrement":return su(t,e.operand);case"post_increment":return iu(t,e.operand);case"post_decrement":return au(t,e.operand);case"in":return ou(t,e.key,e.array);case"getline":return lu(t,e.variable,e.file);case"tuple":return uu(t,e.elements);default:return""}}async function Zc(t,e){let r=Math.floor(B(await P(t,e.index)));return Qe(t,r)}async function Qc(t,e){let r=U(await P(t,e.key));return Xe(t,e.array,r)}async function Kc(t,e){let r=e.operator;if(r==="||")return he(await P(t,e.left))||he(await P(t,e.right))?1:0;if(r==="&&")return he(await P(t,e.left))&&he(await P(t,e.right))?1:0;if(r==="~"){let o=await P(t,e.left),c=e.right.type==="regex"?e.right.pattern:U(await P(t,e.right));try{return new RegExp(c).test(U(o))?1:0}catch{return 0}}if(r==="!~"){let o=await P(t,e.left),c=e.right.type==="regex"?e.right.pattern:U(await P(t,e.right));try{return new RegExp(c).test(U(o))?0:1}catch{return 1}}let n=await P(t,e.left),s=await P(t,e.right);if(r===" ")return U(n)+U(s);if(Xc(r))return Yc(n,s,r);let i=B(n),a=B(s);return ni(i,a,r)}function Xc(t){return["<","<=",">",">=","==","!="].includes(t)}function Yc(t,e,r){let n=zr(t),s=zr(e);if(n&&s){let o=B(t),c=B(e);switch(r){case"<":return o<c?1:0;case"<=":return o<=c?1:0;case">":return o>c?1:0;case">=":return o>=c?1:0;case"==":return o===c?1:0;case"!=":return o!==c?1:0}}let i=U(t),a=U(e);switch(r){case"<":return i<a?1:0;case"<=":return i<=a?1:0;case">":return i>a?1:0;case">=":return i>=a?1:0;case"==":return i===a?1:0;case"!=":return i!==a?1:0}return 0}async function Jc(t,e){let r=await P(t,e.operand);switch(e.operator){case"!":return he(r)?0:1;case"-":return-B(r);case"+":return+B(r);default:return r}}async function eu(t,e,r){let n=oi[e];if(n)return n(r,t,{evalExpr:i=>P(t,i)});let s=t.functions.get(e);return s?tu(t,s,r):""}async function tu(t,e,r){if(t.currentRecursionDepth++,t.currentRecursionDepth>t.maxRecursionDepth)throw t.currentRecursionDepth--,new W(`awk: recursion depth exceeded maximum (${t.maxRecursionDepth})`,"recursion",t.output);let n={};for(let i of e.params)n[i]=t.vars[i];for(let i=0;i<e.params.length;i++){let a=e.params[i],o=i<r.length?await P(t,r[i]):"";t.vars[a]=o}t.hasReturn=!1,t.returnValue=void 0,jr&&await jr(t,e.body.statements);let s=t.returnValue??"";for(let i of e.params)n[i]!==void 0?t.vars[i]=n[i]:delete t.vars[i];return t.hasReturn=!1,t.returnValue=void 0,t.currentRecursionDepth--,s}async function ru(t,e){let r=await P(t,e.value),n=e.target,s=e.operator,i;if(s==="=")i=r;else{let a;if(n.type==="field"){let l=Math.floor(B(await P(t,n.index)));a=Qe(t,l)}else if(n.type==="variable")a=Ke(t,n.name);else{let l=U(await P(t,n.key));a=Xe(t,n.array,l)}let o=B(a),c=B(r);switch(s){case"+=":i=o+c;break;case"-=":i=o-c;break;case"*=":i=o*c;break;case"/=":i=c!==0?o/c:0;break;case"%=":i=c!==0?o%c:0;break;case"^=":i=o**c;break;default:i=r}}if(n.type==="field"){let a=Math.floor(B(await P(t,n.index)));lt(t,a,i)}else if(n.type==="variable")He(t,n.name,i);else{let a=U(await P(t,n.key));ct(t,n.array,a,i)}return i}async function nu(t,e){let r;if(e.type==="field"){let n=Math.floor(B(await P(t,e.index)));r=B(Qe(t,n))+1,lt(t,n,r)}else if(e.type==="variable")r=B(Ke(t,e.name))+1,He(t,e.name,r);else{let n=U(await P(t,e.key));r=B(Xe(t,e.array,n))+1,ct(t,e.array,n,r)}return r}async function su(t,e){let r;if(e.type==="field"){let n=Math.floor(B(await P(t,e.index)));r=B(Qe(t,n))-1,lt(t,n,r)}else if(e.type==="variable")r=B(Ke(t,e.name))-1,He(t,e.name,r);else{let n=U(await P(t,e.key));r=B(Xe(t,e.array,n))-1,ct(t,e.array,n,r)}return r}async function iu(t,e){let r;if(e.type==="field"){let n=Math.floor(B(await P(t,e.index)));r=B(Qe(t,n)),lt(t,n,r+1)}else if(e.type==="variable")r=B(Ke(t,e.name)),He(t,e.name,r+1);else{let n=U(await P(t,e.key));r=B(Xe(t,e.array,n)),ct(t,e.array,n,r+1)}return r}async function au(t,e){let r;if(e.type==="field"){let n=Math.floor(B(await P(t,e.index)));r=B(Qe(t,n)),lt(t,n,r-1)}else if(e.type==="variable")r=B(Ke(t,e.name)),He(t,e.name,r-1);else{let n=U(await P(t,e.key));r=B(Xe(t,e.array,n)),ct(t,e.array,n,r-1)}return r}async function ou(t,e,r){let n;if(e.type==="tuple"){let s=[];for(let i of e.elements)s.push(U(await P(t,i)));n=s.join(t.SUBSEP)}else n=U(await P(t,e));return ui(t,r,n)?1:0}async function lu(t,e,r){if(r)return cu(t,e,r);if(!t.lines||t.lineIndex===void 0)return-1;let n=t.lineIndex+1;if(n>=t.lines.length)return 0;let s=t.lines[n];return e?He(t,e,s):St(t,s),t.NR++,t.lineIndex=n,1}async function cu(t,e,r){if(!t.fs||!t.cwd)return-1;let n=U(await P(t,r)),s=t.fs.resolvePath(t.cwd,n),i=`__fc_${s}`,a=`__fi_${s}`,o,c;if(t.vars[i]===void 0)try{o=(await t.fs.readFile(s)).split(`
235
- `),o.length>0&&o[o.length-1]===""&&o.pop(),t.vars[i]=JSON.stringify(o),t.vars[a]=-1,c=-1}catch{return-1}else o=JSON.parse(t.vars[i]),c=t.vars[a];let l=c+1;if(l>=o.length)return 0;let u=o[l];return t.vars[a]=l,e?He(t,e,u):St(t,u),1}async function uu(t,e){if(e.length===0)return"";for(let r=0;r<e.length-1;r++)await P(t,e[r]);return P(t,e[e.length-1])}var jr,qr=N(()=>{"use strict";X();si();Ur();jt();ot();Gr();jr=null});async function ut(t,e){for(let r of e)if(await Ye(t,r),fu(t))break}function fu(t){return t.shouldExit||t.shouldNext||t.shouldNextFile||t.loopBreak||t.loopContinue||t.hasReturn}async function Ye(t,e){switch(e.type){case"block":await ut(t,e.statements);break;case"expr_stmt":await P(t,e.expression);break;case"print":await du(t,e.args,e.output);break;case"printf":await hu(t,e.format,e.args,e.output);break;case"if":await pu(t,e);break;case"while":await mu(t,e);break;case"do_while":await yu(t,e);break;case"for":await gu(t,e);break;case"for_in":await wu(t,e);break;case"break":t.loopBreak=!0;break;case"continue":t.loopContinue=!0;break;case"next":t.shouldNext=!0;break;case"nextfile":t.shouldNextFile=!0;break;case"exit":t.shouldExit=!0,t.exitCode=e.code?Math.floor(B(await P(t,e.code))):0;break;case"return":t.hasReturn=!0,t.returnValue=e.value?await P(t,e.value):"";break;case"delete":await Eu(t,e.target);break}}async function du(t,e,r){let n=[];for(let i of e)n.push(U(await P(t,i)));let s=n.join(t.OFS)+t.ORS;r?await pi(t,r.redirect,r.file,s):t.output+=s}async function hu(t,e,r,n){let s=U(await P(t,e)),i=[];for(let o of r)i.push(await P(t,o));let a=Hr(s,i);n?await pi(t,n.redirect,n.file,a):t.output+=a}async function pi(t,e,r,n){if(!t.fs||!t.cwd){t.output+=n;return}let s=U(await P(t,r)),i=t.fs.resolvePath(t.cwd,s);e===">"?t.openedFiles.has(i)?await t.fs.appendFile(i,n):(await t.fs.writeFile(i,n),t.openedFiles.add(i)):(t.openedFiles.has(i)||t.openedFiles.add(i),await t.fs.appendFile(i,n))}async function pu(t,e){he(await P(t,e.condition))?await Ye(t,e.consequent):e.alternate&&await Ye(t,e.alternate)}async function mu(t,e){let r=0;for(;he(await P(t,e.condition));){if(r++,r>t.maxIterations)throw new W(`awk: while loop exceeded maximum iterations (${t.maxIterations})`,"iterations",t.output);if(t.loopContinue=!1,await Ye(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break}}async function yu(t,e){let r=0;do{if(r++,r>t.maxIterations)throw new W(`awk: do-while loop exceeded maximum iterations (${t.maxIterations})`,"iterations",t.output);if(t.loopContinue=!1,await Ye(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break}while(he(await P(t,e.condition)))}async function gu(t,e){e.init&&await P(t,e.init);let r=0;for(;!e.condition||he(await P(t,e.condition));){if(r++,r>t.maxIterations)throw new W(`awk: for loop exceeded maximum iterations (${t.maxIterations})`,"iterations",t.output);if(t.loopContinue=!1,await Ye(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break;e.update&&await P(t,e.update)}}async function wu(t,e){let r=t.arrays[e.array];if(r)for(let n of Object.keys(r)){if(t.vars[e.variable]=n,t.loopContinue=!1,await Ye(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break}}async function Eu(t,e){if(e.type==="array_access"){let r=U(await P(t,e.key));fi(t,e.array,r)}else e.type==="variable"&&di(t,e.name)}var mi=N(()=>{"use strict";X();Ur();qr();ot();Gr();hi(ut)});var At,yi=N(()=>{"use strict";qr();jt();ot();mi();At=class{ctx;program=null;rangeStates=[];constructor(e){this.ctx=e}execute(e){this.program=e,this.ctx.output="";for(let r of e.functions)this.ctx.functions.set(r.name,r);this.rangeStates=e.rules.map(()=>!1)}async executeBegin(){if(this.program){for(let e of this.program.rules)if(e.pattern?.type==="begin"&&(await ut(this.ctx,e.action.statements),this.ctx.shouldExit))break}}async executeLine(e){if(!(!this.program||this.ctx.shouldExit)){St(this.ctx,e),this.ctx.NR++,this.ctx.FNR++,this.ctx.shouldNext=!1;for(let r=0;r<this.program.rules.length&&!(this.ctx.shouldExit||this.ctx.shouldNext||this.ctx.shouldNextFile);r++){let n=this.program.rules[r];n.pattern?.type==="begin"||n.pattern?.type==="end"||await this.matchesRule(n,r)&&await ut(this.ctx,n.action.statements)}}}async executeEnd(){if(!(!this.program||this.ctx.shouldExit)){for(let e of this.program.rules)if(e.pattern?.type==="end"&&(await ut(this.ctx,e.action.statements),this.ctx.shouldExit))break}}getOutput(){return this.ctx.output}getExitCode(){return this.ctx.exitCode}getContext(){return this.ctx}async matchesRule(e,r){let n=e.pattern;if(!n)return!0;switch(n.type){case"begin":case"end":return!1;case"regex_pattern":return xt(n.pattern,this.ctx.line);case"expr_pattern":return he(await P(this.ctx,n.expression));case"range":{let s=await this.matchPattern(n.start),i=await this.matchPattern(n.end);return this.rangeStates[r]?(i&&(this.rangeStates[r]=!1),!0):s?(this.rangeStates[r]=!0,i&&(this.rangeStates[r]=!1),!0):!1}default:return!1}}async matchPattern(e){switch(e.type){case"regex_pattern":return xt(e.pattern,this.ctx.line);case"expr_pattern":return he(await P(this.ctx,e.expression));default:return!1}}}});var gi=N(()=>{"use strict";ri();yi()});function xu(t){return t.replace(/\[\[:space:\]\]/g,"[ \\t\\n\\r\\f\\v]").replace(/\[\[:blank:\]\]/g,"[ \\t]").replace(/\[\[:alpha:\]\]/g,"[a-zA-Z]").replace(/\[\[:digit:\]\]/g,"[0-9]").replace(/\[\[:alnum:\]\]/g,"[a-zA-Z0-9]").replace(/\[\[:upper:\]\]/g,"[A-Z]").replace(/\[\[:lower:\]\]/g,"[a-z]").replace(/\[\[:punct:\]\]/g,"[!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~]").replace(/\[\[:xdigit:\]\]/g,"[0-9A-Fa-f]").replace(/\[\[:graph:\]\]/g,"[!-~]").replace(/\[\[:print:\]\]/g,"[ -~]").replace(/\[\[:cntrl:\]\]/g,"[\\x00-\\x1f\\x7f]")}var y,bu,qt,wi=N(()=>{"use strict";(function(t){t.NUMBER="NUMBER",t.STRING="STRING",t.REGEX="REGEX",t.IDENT="IDENT",t.BEGIN="BEGIN",t.END="END",t.IF="IF",t.ELSE="ELSE",t.WHILE="WHILE",t.DO="DO",t.FOR="FOR",t.IN="IN",t.BREAK="BREAK",t.CONTINUE="CONTINUE",t.NEXT="NEXT",t.NEXTFILE="NEXTFILE",t.EXIT="EXIT",t.RETURN="RETURN",t.DELETE="DELETE",t.FUNCTION="FUNCTION",t.PRINT="PRINT",t.PRINTF="PRINTF",t.GETLINE="GETLINE",t.PLUS="PLUS",t.MINUS="MINUS",t.STAR="STAR",t.SLASH="SLASH",t.PERCENT="PERCENT",t.CARET="CARET",t.EQ="EQ",t.NE="NE",t.LT="LT",t.GT="GT",t.LE="LE",t.GE="GE",t.MATCH="MATCH",t.NOT_MATCH="NOT_MATCH",t.AND="AND",t.OR="OR",t.NOT="NOT",t.ASSIGN="ASSIGN",t.PLUS_ASSIGN="PLUS_ASSIGN",t.MINUS_ASSIGN="MINUS_ASSIGN",t.STAR_ASSIGN="STAR_ASSIGN",t.SLASH_ASSIGN="SLASH_ASSIGN",t.PERCENT_ASSIGN="PERCENT_ASSIGN",t.CARET_ASSIGN="CARET_ASSIGN",t.INCREMENT="INCREMENT",t.DECREMENT="DECREMENT",t.QUESTION="QUESTION",t.COLON="COLON",t.COMMA="COMMA",t.SEMICOLON="SEMICOLON",t.NEWLINE="NEWLINE",t.LPAREN="LPAREN",t.RPAREN="RPAREN",t.LBRACE="LBRACE",t.RBRACE="RBRACE",t.LBRACKET="LBRACKET",t.RBRACKET="RBRACKET",t.DOLLAR="DOLLAR",t.APPEND="APPEND",t.PIPE="PIPE",t.EOF="EOF"})(y||(y={}));bu={BEGIN:y.BEGIN,END:y.END,if:y.IF,else:y.ELSE,while:y.WHILE,do:y.DO,for:y.FOR,in:y.IN,break:y.BREAK,continue:y.CONTINUE,next:y.NEXT,nextfile:y.NEXTFILE,exit:y.EXIT,return:y.RETURN,delete:y.DELETE,function:y.FUNCTION,print:y.PRINT,printf:y.PRINTF,getline:y.GETLINE};qt=class{input;pos=0;line=1;column=1;lastTokenType=null;constructor(e){this.input=e}tokenize(){let e=[];for(;this.pos<this.input.length;){let r=this.nextToken();r&&(e.push(r),this.lastTokenType=r.type)}return e.push(this.makeToken(y.EOF,"")),e}makeToken(e,r){return{type:e,value:r,line:this.line,column:this.column}}peek(e=0){return this.input[this.pos+e]||""}advance(){let e=this.input[this.pos++]||"";return e===`
225
+ `,exitCode:1};let u="";if(o.length===0){u=e.stdin;try{let f=await Br(u,c,s,{limits:e.limits,fs:e.fs,cwd:e.cwd});return{stdout:f.output,stderr:"",exitCode:f.exitCode??0}}catch(f){if(f instanceof B)return{stdout:"",stderr:`sed: ${f.message}
226
+ `,exitCode:B.EXIT_CODE};throw f}}if(i){for(let f of o){let d=e.fs.resolvePath(e.cwd,f);try{let h=await e.fs.readFile(d),p=await Br(h,c,s,{limits:e.limits,filename:f,fs:e.fs,cwd:e.cwd});await e.fs.writeFile(d,p.output)}catch(h){return h instanceof B?{stdout:"",stderr:`sed: ${h.message}
227
+ `,exitCode:B.EXIT_CODE}:{stdout:"",stderr:`sed: ${f}: No such file or directory
228
+ `,exitCode:1}}}return{stdout:"",stderr:"",exitCode:0}}for(let f of o){let d=e.fs.resolvePath(e.cwd,f);try{u+=await e.fs.readFile(d)}catch(h){return h instanceof B?{stdout:"",stderr:`sed: ${h.message}
229
+ `,exitCode:B.EXIT_CODE}:{stdout:"",stderr:`sed: ${f}: No such file or directory
230
+ `,exitCode:1}}}try{let f=await Br(u,c,s,{limits:e.limits,filename:o.length===1?o[0]:void 0,fs:e.fs,cwd:e.cwd});return{stdout:f.output,stderr:"",exitCode:f.exitCode??0}}catch(f){if(f instanceof B)return{stdout:"",stderr:`sed: ${f.message}
231
+ `,exitCode:B.EXIT_CODE};throw f}}}});function Hr(t={}){let{fieldSep:e=/\s+/,maxIterations:r=1e4,maxRecursionDepth:n=100,fs:s,cwd:i}=t;return{FS:" ",OFS:" ",ORS:`
232
+ `,NR:0,NF:0,FNR:0,FILENAME:"",RSTART:0,RLENGTH:-1,SUBSEP:"",fields:[],line:"",vars:{},arrays:{},ARGC:0,ARGV:{},functions:new Map,fieldSep:e,maxIterations:r,maxRecursionDepth:n,currentRecursionDepth:0,exitCode:0,shouldExit:!1,shouldNext:!1,shouldNextFile:!1,loopBreak:!1,loopContinue:!1,hasReturn:!1,output:"",openedFiles:new Set,fs:s,cwd:i}}var ai=v(()=>{"use strict"});function oi(t,e,r){switch(r){case"+":return t+e;case"-":return t-e;case"*":return t*e;case"/":return e!==0?t/e:0;case"%":return e!==0?t%e:0;case"^":case"**":return t**e;default:return 0}}var li=v(()=>{"use strict"});function we(t){if(typeof t=="number")return t;let e=parseFloat(t);return Number.isNaN(e)?0:e}function te(t){return typeof t=="string"?t:(Number.isInteger(t),String(t))}async function Pc(t,e,r){return t.length===0?e.line.length:te(await r.evalExpr(t[0])).length}async function Oc(t,e,r){if(t.length<2)return"";let n=te(await r.evalExpr(t[0])),s=Math.floor(we(await r.evalExpr(t[1])))-1;if(t.length>=3){let i=Math.floor(we(await r.evalExpr(t[2])));return n.substr(Math.max(0,s),i)}return n.substr(Math.max(0,s))}async function Dc(t,e,r){if(t.length<2)return 0;let n=te(await r.evalExpr(t[0])),s=te(await r.evalExpr(t[1])),i=n.indexOf(s);return i===-1?0:i+1}async function Tc(t,e,r){if(t.length<2)return 0;let n=te(await r.evalExpr(t[0])),s=t[1];if(s.type!=="variable")return 0;let i=s.name,a=e.FS;if(t.length>=3){let c=te(await r.evalExpr(t[2]));a=c===" "?/\s+/:c}else e.FS===" "&&(a=/\s+/);let o=n.split(a);e.arrays[i]={};for(let c=0;c<o.length;c++)e.arrays[i][String(c+1)]=o[c];return o.length}async function Lc(t,e,r){if(t.length<2)return 0;let n;t[0].type==="regex"?n=t[0].pattern:(n=te(await r.evalExpr(t[0])),n.startsWith("/")&&n.endsWith("/")&&(n=n.slice(1,-1)));let s=te(await r.evalExpr(t[1])),i="$0";if(t.length>=3){let o=t[2];o.type==="variable"?i=o.name:o.type==="field"&&(i=`$${Math.floor(we(await r.evalExpr(o.index)))}`)}let a;if(i==="$0")a=e.line;else if(i.startsWith("$")){let o=parseInt(i.slice(1),10)-1;a=e.fields[o]||""}else a=te(e.vars[i]??"");try{let o=new RegExp(n),c=a.replace(o,ui(s)),l=c!==a?1:0;if(i==="$0")e.line=c,e.fields=e.FS===" "?c.trim().split(/\s+/).filter(Boolean):c.split(e.fieldSep),e.NF=e.fields.length;else if(i.startsWith("$")){let u=parseInt(i.slice(1),10)-1;for(;e.fields.length<=u;)e.fields.push("");e.fields[u]=c,e.NF=e.fields.length,e.line=e.fields.join(e.OFS)}else e.vars[i]=c;return l}catch{return 0}}async function Fc(t,e,r){if(t.length<2)return 0;let n;t[0].type==="regex"?n=t[0].pattern:(n=te(await r.evalExpr(t[0])),n.startsWith("/")&&n.endsWith("/")&&(n=n.slice(1,-1)));let s=te(await r.evalExpr(t[1])),i="$0";if(t.length>=3){let o=t[2];o.type==="variable"?i=o.name:o.type==="field"&&(i=`$${Math.floor(we(await r.evalExpr(o.index)))}`)}let a;if(i==="$0")a=e.line;else if(i.startsWith("$")){let o=parseInt(i.slice(1),10)-1;a=e.fields[o]||""}else a=te(e.vars[i]??"");try{let o=new RegExp(n,"g"),c=a.match(o),l=c?c.length:0,u=a.replace(o,ui(s));if(i==="$0")e.line=u,e.fields=e.FS===" "?u.trim().split(/\s+/).filter(Boolean):u.split(e.fieldSep),e.NF=e.fields.length;else if(i.startsWith("$")){let f=parseInt(i.slice(1),10)-1;for(;e.fields.length<=f;)e.fields.push("");e.fields[f]=u,e.NF=e.fields.length,e.line=e.fields.join(e.OFS)}else e.vars[i]=u;return l}catch{return 0}}function ui(t){return e=>{let r="",n=0;for(;n<t.length;)if(t[n]==="\\"&&n+1<t.length){let s=t[n+1];s==="&"?(r+="&",n+=2):s==="\\"?(r+="\\",n+=2):(r+=t[n+1],n+=2)}else t[n]==="&"?(r+=e,n++):(r+=t[n],n++);return r}}async function Mc(t,e,r){if(t.length<2)return e.RSTART=0,e.RLENGTH=-1,0;let n=te(await r.evalExpr(t[0])),s;t[1].type==="regex"?s=t[1].pattern:(s=te(await r.evalExpr(t[1])),s.startsWith("/")&&s.endsWith("/")&&(s=s.slice(1,-1)));try{let a=new RegExp(s).exec(n);if(a)return e.RSTART=a.index+1,e.RLENGTH=a[0].length,e.RSTART}catch{}return e.RSTART=0,e.RLENGTH=-1,0}async function _c(t,e,r){if(t.length<3)return"";let n;t[0].type==="regex"?n=t[0].pattern:(n=te(await r.evalExpr(t[0])),n.startsWith("/")&&n.endsWith("/")&&(n=n.slice(1,-1)));let s=te(await r.evalExpr(t[1])),i=te(await r.evalExpr(t[2])),a=t.length>=4?te(await r.evalExpr(t[3])):e.line;try{let o=i.toLowerCase()==="g",c=o?0:parseInt(i,10)||1;if(o){let l=new RegExp(n,"g");return a.replace(l,(u,...f)=>ci(s,u,f.slice(0,-2)))}else{let l=0,u=new RegExp(n,"g");return a.replace(u,(f,...d)=>(l++,l===c?ci(s,f,d.slice(0,-2)):f))}}catch{return a}}function ci(t,e,r){let n="",s=0;for(;s<t.length;)if(t[s]==="\\"&&s+1<t.length){let i=t[s+1];if(i==="&")n+="&",s+=2;else if(i==="0")n+=e,s+=2;else if(i>="1"&&i<="9"){let a=parseInt(i,10)-1;n+=r[a]||"",s+=2}else i==="n"?(n+=`
233
+ `,s+=2):i==="t"?(n+=" ",s+=2):(n+=i,s+=2)}else t[s]==="&"?(n+=e,s++):(n+=t[s],s++);return n}async function Wc(t,e,r){return t.length===0?"":te(await r.evalExpr(t[0])).toLowerCase()}async function Bc(t,e,r){return t.length===0?"":te(await r.evalExpr(t[0])).toUpperCase()}async function Hc(t,e,r){if(t.length===0)return"";let n=te(await r.evalExpr(t[0])),s=[];for(let i=1;i<t.length;i++)s.push(await r.evalExpr(t[i]));return Gr(n,s)}async function Uc(t,e,r){return t.length===0?0:Math.floor(we(await r.evalExpr(t[0])))}async function zc(t,e,r){return t.length===0?0:Math.sqrt(we(await r.evalExpr(t[0])))}async function Gc(t,e,r){return t.length===0?0:Math.sin(we(await r.evalExpr(t[0])))}async function jc(t,e,r){return t.length===0?0:Math.cos(we(await r.evalExpr(t[0])))}async function qc(t,e,r){let n=t.length>0?we(await r.evalExpr(t[0])):0,s=t.length>1?we(await r.evalExpr(t[1])):0;return Math.atan2(n,s)}async function Vc(t,e,r){return t.length===0?0:Math.log(we(await r.evalExpr(t[0])))}async function Zc(t,e,r){return t.length===0?1:Math.exp(we(await r.evalExpr(t[0])))}function Qc(t,e,r){return e.random?e.random():Math.random()}async function Kc(t,e,r){let n=t.length>0?we(await r.evalExpr(t[0])):Date.now();return e.vars._srand_seed=n,n}function Ur(t,e){return()=>{throw new Error(`${t}() is not supported - ${e}`)}}function zr(t){return()=>{throw new Error(`function '${t}()' is not implemented`)}}function Gr(t,e){let r=0,n="",s=0;for(;s<t.length;)if(t[s]==="%"&&s+1<t.length){let i=s+1,a="",o="",c="";for(;i<t.length&&/[-+ #0]/.test(t[i]);)a+=t[i++];for(;i<t.length&&/\d/.test(t[i]);)o+=t[i++];if(t[i]===".")for(i++;i<t.length&&/\d/.test(t[i]);)c+=t[i++];let l=t[i],u=e[r];switch(l){case"s":{let f=u!==void 0?String(u):"";if(c&&(f=f.substring(0,parseInt(c,10))),o){let d=parseInt(o,10);a.includes("-")?f=f.padEnd(d):f=f.padStart(d)}n+=f,r++;break}case"d":case"i":{let f=u!==void 0?Math.floor(Number(u)):0;Number.isNaN(f)&&(f=0);let d=String(f);if(o){let h=parseInt(o,10);if(a.includes("-"))d=d.padEnd(h);else if(a.includes("0")&&!a.includes("-")){let p=f<0?"-":"";d=p+Math.abs(f).toString().padStart(h-p.length,"0")}else d=d.padStart(h)}n+=d,r++;break}case"f":{let f=u!==void 0?Number(u):0;Number.isNaN(f)&&(f=0);let d=c?parseInt(c,10):6,h=f.toFixed(d);if(o){let p=parseInt(o,10);a.includes("-")?h=h.padEnd(p):h=h.padStart(p)}n+=h,r++;break}case"e":case"E":{let f=u!==void 0?Number(u):0;Number.isNaN(f)&&(f=0);let d=c?parseInt(c,10):6,h=f.toExponential(d);if(l==="E"&&(h=h.toUpperCase()),o){let p=parseInt(o,10);a.includes("-")?h=h.padEnd(p):h=h.padStart(p)}n+=h,r++;break}case"g":case"G":{let f=u!==void 0?Number(u):0;Number.isNaN(f)&&(f=0);let d=c?parseInt(c,10):6,h=f!==0?Math.floor(Math.log10(Math.abs(f))):0,p;if(f===0?p="0":h<-4||h>=d?(p=f.toExponential(d-1),l==="G"&&(p=p.toUpperCase())):p=f.toPrecision(d),p=p.replace(/\.?0+$/,"").replace(/\.?0+e/,"e"),o){let E=parseInt(o,10);a.includes("-")?p=p.padEnd(E):p=p.padStart(E)}n+=p,r++;break}case"x":case"X":{let f=u!==void 0?Math.floor(Number(u)):0;Number.isNaN(f)&&(f=0);let d=Math.abs(f).toString(16);if(l==="X"&&(d=d.toUpperCase()),o){let h=parseInt(o,10);a.includes("0")?d=d.padStart(h,"0"):a.includes("-")?d=d.padEnd(h):d=d.padStart(h)}n+=f<0?`-${d}`:d,r++;break}case"o":{let f=u!==void 0?Math.floor(Number(u)):0;Number.isNaN(f)&&(f=0);let d=Math.abs(f).toString(8);if(o){let h=parseInt(o,10);a.includes("0")?d=d.padStart(h,"0"):a.includes("-")?d=d.padEnd(h):d=d.padStart(h)}n+=f<0?`-${d}`:d,r++;break}case"c":{typeof u=="number"?n+=String.fromCharCode(u):n+=String(u??"").charAt(0)||"",r++;break}case"%":n+="%";break;default:n+=t.substring(s,i+1)}s=i+1}else if(t[s]==="\\"&&s+1<t.length){let i=t[s+1];switch(i){case"n":n+=`
234
+ `;break;case"t":n+=" ";break;case"r":n+="\r";break;case"\\":n+="\\";break;default:n+=i}s+=2}else n+=t[s++];return n}var fi,jr=v(()=>{"use strict";fi={length:Pc,substr:Oc,index:Dc,split:Tc,sub:Lc,gsub:Fc,match:Mc,gensub:_c,tolower:Wc,toupper:Bc,sprintf:Hc,int:Uc,sqrt:zc,sin:Gc,cos:jc,atan2:qc,log:Vc,exp:Zc,rand:Qc,srand:Kc,system:Ur("system","shell execution not allowed in sandboxed environment"),close:Ur("close","file operations not allowed"),fflush:Ur("fflush","file operations not allowed"),systime:zr("systime"),mktime:zr("mktime"),strftime:zr("strftime")}});function he(t){return typeof t=="number"?t!==0:t!==""}function H(t){if(typeof t=="number")return t;let e=parseFloat(t);return Number.isNaN(e)?0:e}function j(t){return typeof t=="string"?t:(Number.isInteger(t),String(t))}function qr(t){if(typeof t=="number")return!0;let e=String(t).trim();return e===""?!1:!Number.isNaN(Number(e))}function At(t,e){try{return new RegExp(t).test(e)}catch{return!1}}var ut=v(()=>{"use strict"});function di(t,e){return t.FS===" "?e.trim().split(/\s+/).filter(Boolean):e.split(t.fieldSep)}function Xe(t,e){return e===0?t.line:e<0||e>t.fields.length?"":t.fields[e-1]??""}function ft(t,e,r){if(e===0)t.line=j(r),t.fields=di(t,t.line),t.NF=t.fields.length;else if(e>0){for(;t.fields.length<e;)t.fields.push("");t.fields[e-1]=j(r),t.NF=t.fields.length,t.line=t.fields.join(t.OFS)}}function Ct(t,e){t.line=e,t.fields=di(t,e),t.NF=t.fields.length}function hi(t,e){if(t.FS=e,e===" ")t.fieldSep=/\s+/;else try{t.fieldSep=new RegExp(e)}catch{t.fieldSep=new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"))}}var Qt=v(()=>{"use strict";ut()});function Ye(t,e){switch(e){case"FS":return t.FS;case"OFS":return t.OFS;case"ORS":return t.ORS;case"NR":return t.NR;case"NF":return t.NF;case"FNR":return t.FNR;case"FILENAME":return t.FILENAME;case"RSTART":return t.RSTART;case"RLENGTH":return t.RLENGTH;case"SUBSEP":return t.SUBSEP;case"ARGC":return t.ARGC}return t.vars[e]??""}function Ue(t,e,r){switch(e){case"FS":hi(t,j(r));return;case"OFS":t.OFS=j(r);return;case"ORS":t.ORS=j(r);return;case"NR":t.NR=Math.floor(H(r));return;case"NF":{let n=Math.floor(H(r));if(n<t.NF)t.fields=t.fields.slice(0,n),t.line=t.fields.join(t.OFS);else if(n>t.NF){for(;t.fields.length<n;)t.fields.push("");t.line=t.fields.join(t.OFS)}t.NF=n;return}case"FNR":t.FNR=Math.floor(H(r));return;case"FILENAME":t.FILENAME=j(r);return;case"RSTART":t.RSTART=Math.floor(H(r));return;case"RLENGTH":t.RLENGTH=Math.floor(H(r));return;case"SUBSEP":t.SUBSEP=j(r);return}t.vars[e]=r}function Je(t,e,r){return e==="ARGV"?t.ARGV[r]??"":t.arrays[e]?.[r]??""}function dt(t,e,r,n){t.arrays[e]||(t.arrays[e]={}),t.arrays[e][r]=n}function pi(t,e,r){return e==="ARGV"?t.ARGV[r]!==void 0:t.arrays[e]?.[r]!==void 0}function mi(t,e,r){t.arrays[e]&&delete t.arrays[e][r]}function yi(t,e){delete t.arrays[e]}var Vr=v(()=>{"use strict";Qt();ut()});function gi(t){Zr=t}async function P(t,e){switch(e.type){case"number":return e.value;case"string":return e.value;case"regex":return At(e.pattern,t.line)?1:0;case"field":return Xc(t,e);case"variable":return Ye(t,e.name);case"array_access":return Yc(t,e);case"binary":return Jc(t,e);case"unary":return ru(t,e);case"ternary":return he(await P(t,e.condition))?P(t,e.consequent):P(t,e.alternate);case"call":return nu(t,e.name,e.args);case"assignment":return iu(t,e);case"pre_increment":return au(t,e.operand);case"pre_decrement":return ou(t,e.operand);case"post_increment":return lu(t,e.operand);case"post_decrement":return cu(t,e.operand);case"in":return uu(t,e.key,e.array);case"getline":return fu(t,e.variable,e.file);case"tuple":return hu(t,e.elements);default:return""}}async function Xc(t,e){let r=Math.floor(H(await P(t,e.index)));return Xe(t,r)}async function Yc(t,e){let r=j(await P(t,e.key));return Je(t,e.array,r)}async function Jc(t,e){let r=e.operator;if(r==="||")return he(await P(t,e.left))||he(await P(t,e.right))?1:0;if(r==="&&")return he(await P(t,e.left))&&he(await P(t,e.right))?1:0;if(r==="~"){let o=await P(t,e.left),c=e.right.type==="regex"?e.right.pattern:j(await P(t,e.right));try{return new RegExp(c).test(j(o))?1:0}catch{return 0}}if(r==="!~"){let o=await P(t,e.left),c=e.right.type==="regex"?e.right.pattern:j(await P(t,e.right));try{return new RegExp(c).test(j(o))?0:1}catch{return 1}}let n=await P(t,e.left),s=await P(t,e.right);if(r===" ")return j(n)+j(s);if(eu(r))return tu(n,s,r);let i=H(n),a=H(s);return oi(i,a,r)}function eu(t){return["<","<=",">",">=","==","!="].includes(t)}function tu(t,e,r){let n=qr(t),s=qr(e);if(n&&s){let o=H(t),c=H(e);switch(r){case"<":return o<c?1:0;case"<=":return o<=c?1:0;case">":return o>c?1:0;case">=":return o>=c?1:0;case"==":return o===c?1:0;case"!=":return o!==c?1:0}}let i=j(t),a=j(e);switch(r){case"<":return i<a?1:0;case"<=":return i<=a?1:0;case">":return i>a?1:0;case">=":return i>=a?1:0;case"==":return i===a?1:0;case"!=":return i!==a?1:0}return 0}async function ru(t,e){let r=await P(t,e.operand);switch(e.operator){case"!":return he(r)?0:1;case"-":return-H(r);case"+":return+H(r);default:return r}}async function nu(t,e,r){let n=fi[e];if(n)return n(r,t,{evalExpr:i=>P(t,i)});let s=t.functions.get(e);return s?su(t,s,r):""}async function su(t,e,r){if(t.currentRecursionDepth++,t.currentRecursionDepth>t.maxRecursionDepth)throw t.currentRecursionDepth--,new B(`awk: recursion depth exceeded maximum (${t.maxRecursionDepth})`,"recursion",t.output);let n={};for(let i of e.params)n[i]=t.vars[i];for(let i=0;i<e.params.length;i++){let a=e.params[i],o=i<r.length?await P(t,r[i]):"";t.vars[a]=o}t.hasReturn=!1,t.returnValue=void 0,Zr&&await Zr(t,e.body.statements);let s=t.returnValue??"";for(let i of e.params)n[i]!==void 0?t.vars[i]=n[i]:delete t.vars[i];return t.hasReturn=!1,t.returnValue=void 0,t.currentRecursionDepth--,s}async function iu(t,e){let r=await P(t,e.value),n=e.target,s=e.operator,i;if(s==="=")i=r;else{let a;if(n.type==="field"){let l=Math.floor(H(await P(t,n.index)));a=Xe(t,l)}else if(n.type==="variable")a=Ye(t,n.name);else{let l=j(await P(t,n.key));a=Je(t,n.array,l)}let o=H(a),c=H(r);switch(s){case"+=":i=o+c;break;case"-=":i=o-c;break;case"*=":i=o*c;break;case"/=":i=c!==0?o/c:0;break;case"%=":i=c!==0?o%c:0;break;case"^=":i=o**c;break;default:i=r}}if(n.type==="field"){let a=Math.floor(H(await P(t,n.index)));ft(t,a,i)}else if(n.type==="variable")Ue(t,n.name,i);else{let a=j(await P(t,n.key));dt(t,n.array,a,i)}return i}async function au(t,e){let r;if(e.type==="field"){let n=Math.floor(H(await P(t,e.index)));r=H(Xe(t,n))+1,ft(t,n,r)}else if(e.type==="variable")r=H(Ye(t,e.name))+1,Ue(t,e.name,r);else{let n=j(await P(t,e.key));r=H(Je(t,e.array,n))+1,dt(t,e.array,n,r)}return r}async function ou(t,e){let r;if(e.type==="field"){let n=Math.floor(H(await P(t,e.index)));r=H(Xe(t,n))-1,ft(t,n,r)}else if(e.type==="variable")r=H(Ye(t,e.name))-1,Ue(t,e.name,r);else{let n=j(await P(t,e.key));r=H(Je(t,e.array,n))-1,dt(t,e.array,n,r)}return r}async function lu(t,e){let r;if(e.type==="field"){let n=Math.floor(H(await P(t,e.index)));r=H(Xe(t,n)),ft(t,n,r+1)}else if(e.type==="variable")r=H(Ye(t,e.name)),Ue(t,e.name,r+1);else{let n=j(await P(t,e.key));r=H(Je(t,e.array,n)),dt(t,e.array,n,r+1)}return r}async function cu(t,e){let r;if(e.type==="field"){let n=Math.floor(H(await P(t,e.index)));r=H(Xe(t,n)),ft(t,n,r-1)}else if(e.type==="variable")r=H(Ye(t,e.name)),Ue(t,e.name,r-1);else{let n=j(await P(t,e.key));r=H(Je(t,e.array,n)),dt(t,e.array,n,r-1)}return r}async function uu(t,e,r){let n;if(e.type==="tuple"){let s=[];for(let i of e.elements)s.push(j(await P(t,i)));n=s.join(t.SUBSEP)}else n=j(await P(t,e));return pi(t,r,n)?1:0}async function fu(t,e,r){if(r)return du(t,e,r);if(!t.lines||t.lineIndex===void 0)return-1;let n=t.lineIndex+1;if(n>=t.lines.length)return 0;let s=t.lines[n];return e?Ue(t,e,s):Ct(t,s),t.NR++,t.lineIndex=n,1}async function du(t,e,r){if(!t.fs||!t.cwd)return-1;let n=j(await P(t,r)),s=t.fs.resolvePath(t.cwd,n),i=`__fc_${s}`,a=`__fi_${s}`,o,c;if(t.vars[i]===void 0)try{o=(await t.fs.readFile(s)).split(`
235
+ `),o.length>0&&o[o.length-1]===""&&o.pop(),t.vars[i]=JSON.stringify(o),t.vars[a]=-1,c=-1}catch{return-1}else o=JSON.parse(t.vars[i]),c=t.vars[a];let l=c+1;if(l>=o.length)return 0;let u=o[l];return t.vars[a]=l,e?Ue(t,e,u):Ct(t,u),1}async function hu(t,e){if(e.length===0)return"";for(let r=0;r<e.length-1;r++)await P(t,e[r]);return P(t,e[e.length-1])}var Zr,Qr=v(()=>{"use strict";Y();li();jr();Qt();ut();Vr();Zr=null});async function ht(t,e){for(let r of e)if(await et(t,r),pu(t))break}function pu(t){return t.shouldExit||t.shouldNext||t.shouldNextFile||t.loopBreak||t.loopContinue||t.hasReturn}async function et(t,e){switch(e.type){case"block":await ht(t,e.statements);break;case"expr_stmt":await P(t,e.expression);break;case"print":await mu(t,e.args,e.output);break;case"printf":await yu(t,e.format,e.args,e.output);break;case"if":await gu(t,e);break;case"while":await wu(t,e);break;case"do_while":await Eu(t,e);break;case"for":await bu(t,e);break;case"for_in":await Su(t,e);break;case"break":t.loopBreak=!0;break;case"continue":t.loopContinue=!0;break;case"next":t.shouldNext=!0;break;case"nextfile":t.shouldNextFile=!0;break;case"exit":t.shouldExit=!0,t.exitCode=e.code?Math.floor(H(await P(t,e.code))):0;break;case"return":t.hasReturn=!0,t.returnValue=e.value?await P(t,e.value):"";break;case"delete":await xu(t,e.target);break}}async function mu(t,e,r){let n=[];for(let i of e)n.push(j(await P(t,i)));let s=n.join(t.OFS)+t.ORS;r?await wi(t,r.redirect,r.file,s):t.output+=s}async function yu(t,e,r,n){let s=j(await P(t,e)),i=[];for(let o of r)i.push(await P(t,o));let a=Gr(s,i);n?await wi(t,n.redirect,n.file,a):t.output+=a}async function wi(t,e,r,n){if(!t.fs||!t.cwd){t.output+=n;return}let s=j(await P(t,r)),i=t.fs.resolvePath(t.cwd,s);e===">"?t.openedFiles.has(i)?await t.fs.appendFile(i,n):(await t.fs.writeFile(i,n),t.openedFiles.add(i)):(t.openedFiles.has(i)||t.openedFiles.add(i),await t.fs.appendFile(i,n))}async function gu(t,e){he(await P(t,e.condition))?await et(t,e.consequent):e.alternate&&await et(t,e.alternate)}async function wu(t,e){let r=0;for(;he(await P(t,e.condition));){if(r++,r>t.maxIterations)throw new B(`awk: while loop exceeded maximum iterations (${t.maxIterations})`,"iterations",t.output);if(t.loopContinue=!1,await et(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break}}async function Eu(t,e){let r=0;do{if(r++,r>t.maxIterations)throw new B(`awk: do-while loop exceeded maximum iterations (${t.maxIterations})`,"iterations",t.output);if(t.loopContinue=!1,await et(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break}while(he(await P(t,e.condition)))}async function bu(t,e){e.init&&await P(t,e.init);let r=0;for(;!e.condition||he(await P(t,e.condition));){if(r++,r>t.maxIterations)throw new B(`awk: for loop exceeded maximum iterations (${t.maxIterations})`,"iterations",t.output);if(t.loopContinue=!1,await et(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break;e.update&&await P(t,e.update)}}async function Su(t,e){let r=t.arrays[e.array];if(r)for(let n of Object.keys(r)){if(t.vars[e.variable]=n,t.loopContinue=!1,await et(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break}}async function xu(t,e){if(e.type==="array_access"){let r=j(await P(t,e.key));mi(t,e.array,r)}else e.type==="variable"&&yi(t,e.name)}var Ei=v(()=>{"use strict";Y();jr();Qr();ut();Vr();gi(ht)});var Nt,bi=v(()=>{"use strict";Qr();Qt();ut();Ei();Nt=class{ctx;program=null;rangeStates=[];constructor(e){this.ctx=e}execute(e){this.program=e,this.ctx.output="";for(let r of e.functions)this.ctx.functions.set(r.name,r);this.rangeStates=e.rules.map(()=>!1)}async executeBegin(){if(this.program){for(let e of this.program.rules)if(e.pattern?.type==="begin"&&(await ht(this.ctx,e.action.statements),this.ctx.shouldExit))break}}async executeLine(e){if(!(!this.program||this.ctx.shouldExit)){Ct(this.ctx,e),this.ctx.NR++,this.ctx.FNR++,this.ctx.shouldNext=!1;for(let r=0;r<this.program.rules.length&&!(this.ctx.shouldExit||this.ctx.shouldNext||this.ctx.shouldNextFile);r++){let n=this.program.rules[r];n.pattern?.type==="begin"||n.pattern?.type==="end"||await this.matchesRule(n,r)&&await ht(this.ctx,n.action.statements)}}}async executeEnd(){if(!(!this.program||this.ctx.shouldExit)){for(let e of this.program.rules)if(e.pattern?.type==="end"&&(await ht(this.ctx,e.action.statements),this.ctx.shouldExit))break}}getOutput(){return this.ctx.output}getExitCode(){return this.ctx.exitCode}getContext(){return this.ctx}async matchesRule(e,r){let n=e.pattern;if(!n)return!0;switch(n.type){case"begin":case"end":return!1;case"regex_pattern":return At(n.pattern,this.ctx.line);case"expr_pattern":return he(await P(this.ctx,n.expression));case"range":{let s=await this.matchPattern(n.start),i=await this.matchPattern(n.end);return this.rangeStates[r]?(i&&(this.rangeStates[r]=!1),!0):s?(this.rangeStates[r]=!0,i&&(this.rangeStates[r]=!1),!0):!1}default:return!1}}async matchPattern(e){switch(e.type){case"regex_pattern":return At(e.pattern,this.ctx.line);case"expr_pattern":return he(await P(this.ctx,e.expression));default:return!1}}}});var Si=v(()=>{"use strict";ai();bi()});function Cu(t){return t.replace(/\[\[:space:\]\]/g,"[ \\t\\n\\r\\f\\v]").replace(/\[\[:blank:\]\]/g,"[ \\t]").replace(/\[\[:alpha:\]\]/g,"[a-zA-Z]").replace(/\[\[:digit:\]\]/g,"[0-9]").replace(/\[\[:alnum:\]\]/g,"[a-zA-Z0-9]").replace(/\[\[:upper:\]\]/g,"[A-Z]").replace(/\[\[:lower:\]\]/g,"[a-z]").replace(/\[\[:punct:\]\]/g,"[!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~]").replace(/\[\[:xdigit:\]\]/g,"[0-9A-Fa-f]").replace(/\[\[:graph:\]\]/g,"[!-~]").replace(/\[\[:print:\]\]/g,"[ -~]").replace(/\[\[:cntrl:\]\]/g,"[\\x00-\\x1f\\x7f]")}var y,Au,Kt,xi=v(()=>{"use strict";(function(t){t.NUMBER="NUMBER",t.STRING="STRING",t.REGEX="REGEX",t.IDENT="IDENT",t.BEGIN="BEGIN",t.END="END",t.IF="IF",t.ELSE="ELSE",t.WHILE="WHILE",t.DO="DO",t.FOR="FOR",t.IN="IN",t.BREAK="BREAK",t.CONTINUE="CONTINUE",t.NEXT="NEXT",t.NEXTFILE="NEXTFILE",t.EXIT="EXIT",t.RETURN="RETURN",t.DELETE="DELETE",t.FUNCTION="FUNCTION",t.PRINT="PRINT",t.PRINTF="PRINTF",t.GETLINE="GETLINE",t.PLUS="PLUS",t.MINUS="MINUS",t.STAR="STAR",t.SLASH="SLASH",t.PERCENT="PERCENT",t.CARET="CARET",t.EQ="EQ",t.NE="NE",t.LT="LT",t.GT="GT",t.LE="LE",t.GE="GE",t.MATCH="MATCH",t.NOT_MATCH="NOT_MATCH",t.AND="AND",t.OR="OR",t.NOT="NOT",t.ASSIGN="ASSIGN",t.PLUS_ASSIGN="PLUS_ASSIGN",t.MINUS_ASSIGN="MINUS_ASSIGN",t.STAR_ASSIGN="STAR_ASSIGN",t.SLASH_ASSIGN="SLASH_ASSIGN",t.PERCENT_ASSIGN="PERCENT_ASSIGN",t.CARET_ASSIGN="CARET_ASSIGN",t.INCREMENT="INCREMENT",t.DECREMENT="DECREMENT",t.QUESTION="QUESTION",t.COLON="COLON",t.COMMA="COMMA",t.SEMICOLON="SEMICOLON",t.NEWLINE="NEWLINE",t.LPAREN="LPAREN",t.RPAREN="RPAREN",t.LBRACE="LBRACE",t.RBRACE="RBRACE",t.LBRACKET="LBRACKET",t.RBRACKET="RBRACKET",t.DOLLAR="DOLLAR",t.APPEND="APPEND",t.PIPE="PIPE",t.EOF="EOF"})(y||(y={}));Au={BEGIN:y.BEGIN,END:y.END,if:y.IF,else:y.ELSE,while:y.WHILE,do:y.DO,for:y.FOR,in:y.IN,break:y.BREAK,continue:y.CONTINUE,next:y.NEXT,nextfile:y.NEXTFILE,exit:y.EXIT,return:y.RETURN,delete:y.DELETE,function:y.FUNCTION,print:y.PRINT,printf:y.PRINTF,getline:y.GETLINE};Kt=class{input;pos=0;line=1;column=1;lastTokenType=null;constructor(e){this.input=e}tokenize(){let e=[];for(;this.pos<this.input.length;){let r=this.nextToken();r&&(e.push(r),this.lastTokenType=r.type)}return e.push(this.makeToken(y.EOF,"")),e}makeToken(e,r){return{type:e,value:r,line:this.line,column:this.column}}peek(e=0){return this.input[this.pos+e]||""}advance(){let e=this.input[this.pos++]||"";return e===`
236
236
  `?(this.line++,this.column=1):this.column++,e}skipWhitespace(){for(;this.pos<this.input.length;){let e=this.peek();if(e===" "||e===" "||e==="\r")this.advance();else if(e==="\\")if(this.peek(1)===`
237
237
  `)this.advance(),this.advance();else break;else if(e==="#")for(;this.pos<this.input.length&&this.peek()!==`
238
238
  `;)this.advance();else break}}nextToken(){if(this.skipWhitespace(),this.pos>=this.input.length)return null;let e=this.line,r=this.column,n=this.peek();return n===`
239
239
  `?(this.advance(),{type:y.NEWLINE,value:`
240
240
  `,line:e,column:r}):n==='"'?this.readString():n==="/"&&this.canBeRegex()?this.readRegex():this.isDigit(n)||n==="."&&this.isDigit(this.peek(1))?this.readNumber():this.isAlpha(n)||n==="_"?this.readIdentifier():this.readOperator()}canBeRegex(){return new Set([null,y.NEWLINE,y.SEMICOLON,y.LBRACE,y.RBRACE,y.LPAREN,y.LBRACKET,y.COMMA,y.ASSIGN,y.PLUS_ASSIGN,y.MINUS_ASSIGN,y.STAR_ASSIGN,y.SLASH_ASSIGN,y.PERCENT_ASSIGN,y.CARET_ASSIGN,y.AND,y.OR,y.NOT,y.MATCH,y.NOT_MATCH,y.QUESTION,y.COLON,y.LT,y.GT,y.LE,y.GE,y.EQ,y.NE,y.PLUS,y.MINUS,y.STAR,y.PERCENT,y.CARET,y.PRINT,y.PRINTF,y.IF,y.WHILE,y.DO,y.FOR,y.RETURN]).has(this.lastTokenType)}readString(){let e=this.line,r=this.column;this.advance();let n="";for(;this.pos<this.input.length&&this.peek()!=='"';)if(this.peek()==="\\"){this.advance();let s=this.advance();switch(s){case"n":n+=`
241
241
  `;break;case"t":n+=" ";break;case"r":n+="\r";break;case"\\":n+="\\";break;case'"':n+='"';break;case"/":n+="/";break;default:n+=s}}else n+=this.advance();return this.peek()==='"'&&this.advance(),{type:y.STRING,value:n,line:e,column:r}}readRegex(){let e=this.line,r=this.column;this.advance();let n="";for(;this.pos<this.input.length&&this.peek()!=="/";)if(this.peek()==="\\")n+=this.advance(),this.pos<this.input.length&&(n+=this.advance());else{if(this.peek()===`
242
- `)break;n+=this.advance()}return this.peek()==="/"&&this.advance(),n=xu(n),{type:y.REGEX,value:n,line:e,column:r}}readNumber(){let e=this.line,r=this.column,n="";for(;this.isDigit(this.peek());)n+=this.advance();if(this.peek()==="."&&this.isDigit(this.peek(1)))for(n+=this.advance();this.isDigit(this.peek());)n+=this.advance();if(this.peek()==="e"||this.peek()==="E")for(n+=this.advance(),(this.peek()==="+"||this.peek()==="-")&&(n+=this.advance());this.isDigit(this.peek());)n+=this.advance();return{type:y.NUMBER,value:parseFloat(n),line:e,column:r}}readIdentifier(){let e=this.line,r=this.column,n="";for(;this.isAlphaNumeric(this.peek())||this.peek()==="_";)n+=this.advance();let s=bu[n];return s?{type:s,value:n,line:e,column:r}:{type:y.IDENT,value:n,line:e,column:r}}readOperator(){let e=this.line,r=this.column,n=this.advance(),s=this.peek();switch(n){case"+":return s==="+"?(this.advance(),{type:y.INCREMENT,value:"++",line:e,column:r}):s==="="?(this.advance(),{type:y.PLUS_ASSIGN,value:"+=",line:e,column:r}):{type:y.PLUS,value:"+",line:e,column:r};case"-":return s==="-"?(this.advance(),{type:y.DECREMENT,value:"--",line:e,column:r}):s==="="?(this.advance(),{type:y.MINUS_ASSIGN,value:"-=",line:e,column:r}):{type:y.MINUS,value:"-",line:e,column:r};case"*":return s==="*"?(this.advance(),{type:y.CARET,value:"**",line:e,column:r}):s==="="?(this.advance(),{type:y.STAR_ASSIGN,value:"*=",line:e,column:r}):{type:y.STAR,value:"*",line:e,column:r};case"/":return s==="="?(this.advance(),{type:y.SLASH_ASSIGN,value:"/=",line:e,column:r}):{type:y.SLASH,value:"/",line:e,column:r};case"%":return s==="="?(this.advance(),{type:y.PERCENT_ASSIGN,value:"%=",line:e,column:r}):{type:y.PERCENT,value:"%",line:e,column:r};case"^":return s==="="?(this.advance(),{type:y.CARET_ASSIGN,value:"^=",line:e,column:r}):{type:y.CARET,value:"^",line:e,column:r};case"=":return s==="="?(this.advance(),{type:y.EQ,value:"==",line:e,column:r}):{type:y.ASSIGN,value:"=",line:e,column:r};case"!":return s==="="?(this.advance(),{type:y.NE,value:"!=",line:e,column:r}):s==="~"?(this.advance(),{type:y.NOT_MATCH,value:"!~",line:e,column:r}):{type:y.NOT,value:"!",line:e,column:r};case"<":return s==="="?(this.advance(),{type:y.LE,value:"<=",line:e,column:r}):{type:y.LT,value:"<",line:e,column:r};case">":return s==="="?(this.advance(),{type:y.GE,value:">=",line:e,column:r}):s===">"?(this.advance(),{type:y.APPEND,value:">>",line:e,column:r}):{type:y.GT,value:">",line:e,column:r};case"&":return s==="&"?(this.advance(),{type:y.AND,value:"&&",line:e,column:r}):{type:y.IDENT,value:"&",line:e,column:r};case"|":return s==="|"?(this.advance(),{type:y.OR,value:"||",line:e,column:r}):{type:y.PIPE,value:"|",line:e,column:r};case"~":return{type:y.MATCH,value:"~",line:e,column:r};case"?":return{type:y.QUESTION,value:"?",line:e,column:r};case":":return{type:y.COLON,value:":",line:e,column:r};case",":return{type:y.COMMA,value:",",line:e,column:r};case";":return{type:y.SEMICOLON,value:";",line:e,column:r};case"(":return{type:y.LPAREN,value:"(",line:e,column:r};case")":return{type:y.RPAREN,value:")",line:e,column:r};case"{":return{type:y.LBRACE,value:"{",line:e,column:r};case"}":return{type:y.RBRACE,value:"}",line:e,column:r};case"[":return{type:y.LBRACKET,value:"[",line:e,column:r};case"]":return{type:y.RBRACKET,value:"]",line:e,column:r};case"$":return{type:y.DOLLAR,value:"$",line:e,column:r};default:return{type:y.IDENT,value:n,line:e,column:r}}}isDigit(e){return e>="0"&&e<="9"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}isAlphaNumeric(e){return this.isDigit(e)||this.isAlpha(e)}}});var Vt,Ei=N(()=>{"use strict";wi();Vt=class{tokens=[];pos=0;parse(e){let r=new qt(e);return this.tokens=r.tokenize(),this.pos=0,this.parseProgram()}current(){return this.tokens[this.pos]||{type:y.EOF,value:"",line:0,column:0}}advance(){let e=this.current();return this.pos<this.tokens.length&&this.pos++,e}match(...e){return e.includes(this.current().type)}check(e){return this.current().type===e}expect(e,r){if(!this.check(e)){let n=this.current();throw new Error(r||`Expected ${e}, got ${n.type} at line ${n.line}:${n.column}`)}return this.advance()}skipNewlines(){for(;this.check(y.NEWLINE);)this.advance()}skipTerminators(){for(;this.check(y.NEWLINE)||this.check(y.SEMICOLON);)this.advance()}parseProgram(){let e=[],r=[];for(this.skipNewlines();!this.check(y.EOF)&&(this.skipNewlines(),!this.check(y.EOF));)this.check(y.FUNCTION)?e.push(this.parseFunction()):r.push(this.parseRule()),this.skipTerminators();return{functions:e,rules:r}}parseFunction(){this.expect(y.FUNCTION);let e=this.expect(y.IDENT).value;this.expect(y.LPAREN);let r=[];if(!this.check(y.RPAREN))for(r.push(this.expect(y.IDENT).value);this.check(y.COMMA);)this.advance(),r.push(this.expect(y.IDENT).value);this.expect(y.RPAREN),this.skipNewlines();let n=this.parseBlock();return{name:e,params:r,body:n}}parseRule(){let e;if(this.check(y.BEGIN))this.advance(),e={type:"begin"};else if(this.check(y.END))this.advance(),e={type:"end"};else if(this.check(y.LBRACE))e=void 0;else if(this.check(y.REGEX)){let n=this.advance();if(this.check(y.AND)||this.check(y.OR)){let s={type:"binary",operator:"~",left:{type:"field",index:{type:"number",value:0}},right:{type:"regex",pattern:n.value}};e={type:"expr_pattern",expression:this.parseLogicalOrRest(s)}}else{let s={type:"regex_pattern",pattern:n.value};if(this.check(y.COMMA)){this.advance();let i;this.check(y.REGEX)?i={type:"regex_pattern",pattern:this.advance().value}:i={type:"expr_pattern",expression:this.parseExpression()},e={type:"range",start:s,end:i}}else e=s}}else{let s={type:"expr_pattern",expression:this.parseExpression()};if(this.check(y.COMMA)){this.advance();let i;this.check(y.REGEX)?i={type:"regex_pattern",pattern:this.advance().value}:i={type:"expr_pattern",expression:this.parseExpression()},e={type:"range",start:s,end:i}}else e=s}this.skipNewlines();let r;return this.check(y.LBRACE)?r=this.parseBlock():r={type:"block",statements:[{type:"print",args:[{type:"field",index:{type:"number",value:0}}]}]},{pattern:e,action:r}}parseBlock(){this.expect(y.LBRACE),this.skipNewlines();let e=[];for(;!this.check(y.RBRACE)&&!this.check(y.EOF);)e.push(this.parseStatement()),this.skipTerminators();return this.expect(y.RBRACE),{type:"block",statements:e}}parseStatement(){if(this.check(y.LBRACE))return this.parseBlock();if(this.check(y.IF))return this.parseIf();if(this.check(y.WHILE))return this.parseWhile();if(this.check(y.DO))return this.parseDoWhile();if(this.check(y.FOR))return this.parseFor();if(this.check(y.BREAK))return this.advance(),{type:"break"};if(this.check(y.CONTINUE))return this.advance(),{type:"continue"};if(this.check(y.NEXT))return this.advance(),{type:"next"};if(this.check(y.NEXTFILE))return this.advance(),{type:"nextfile"};if(this.check(y.EXIT)){this.advance();let r;return!this.check(y.NEWLINE)&&!this.check(y.SEMICOLON)&&!this.check(y.RBRACE)&&!this.check(y.EOF)&&(r=this.parseExpression()),{type:"exit",code:r}}if(this.check(y.RETURN)){this.advance();let r;return!this.check(y.NEWLINE)&&!this.check(y.SEMICOLON)&&!this.check(y.RBRACE)&&!this.check(y.EOF)&&(r=this.parseExpression()),{type:"return",value:r}}if(this.check(y.DELETE)){this.advance();let r=this.parsePrimary();if(r.type!=="array_access"&&r.type!=="variable")throw new Error("delete requires array element or array");return{type:"delete",target:r}}return this.check(y.PRINT)?this.parsePrint():this.check(y.PRINTF)?this.parsePrintf():{type:"expr_stmt",expression:this.parseExpression()}}parseIf(){this.expect(y.IF),this.expect(y.LPAREN);let e=this.parseExpression();this.expect(y.RPAREN),this.skipNewlines();let r=this.parseStatement();this.skipTerminators();let n;return this.check(y.ELSE)&&(this.advance(),this.skipNewlines(),n=this.parseStatement()),{type:"if",condition:e,consequent:r,alternate:n}}parseWhile(){this.expect(y.WHILE),this.expect(y.LPAREN);let e=this.parseExpression();this.expect(y.RPAREN),this.skipNewlines();let r=this.parseStatement();return{type:"while",condition:e,body:r}}parseDoWhile(){this.expect(y.DO),this.skipNewlines();let e=this.parseStatement();this.skipNewlines(),this.expect(y.WHILE),this.expect(y.LPAREN);let r=this.parseExpression();return this.expect(y.RPAREN),{type:"do_while",body:e,condition:r}}parseFor(){if(this.expect(y.FOR),this.expect(y.LPAREN),this.check(y.IDENT)){let i=this.advance();if(this.check(y.IN)){this.advance();let a=this.expect(y.IDENT).value;this.expect(y.RPAREN),this.skipNewlines();let o=this.parseStatement();return{type:"for_in",variable:i.value,array:a,body:o}}this.pos--}let e;this.check(y.SEMICOLON)||(e=this.parseExpression()),this.expect(y.SEMICOLON);let r;this.check(y.SEMICOLON)||(r=this.parseExpression()),this.expect(y.SEMICOLON);let n;this.check(y.RPAREN)||(n=this.parseExpression()),this.expect(y.RPAREN),this.skipNewlines();let s=this.parseStatement();return{type:"for",init:e,condition:r,update:n,body:s}}parsePrint(){this.expect(y.PRINT);let e=[];if(this.check(y.NEWLINE)||this.check(y.SEMICOLON)||this.check(y.RBRACE)||this.check(y.PIPE)||this.check(y.GT)||this.check(y.APPEND))e.push({type:"field",index:{type:"number",value:0}});else for(e.push(this.parsePrintArg());this.check(y.COMMA);)this.advance(),e.push(this.parsePrintArg());let r;return this.check(y.GT)?(this.advance(),r={redirect:">",file:this.parsePrimary()}):this.check(y.APPEND)&&(this.advance(),r={redirect:">>",file:this.parsePrimary()}),{type:"print",args:e,output:r}}parsePrintArg(){return this.lookAheadForTernary()?this.parseTernary():this.parsePrintOr()}lookAheadForTernary(){let e=0,r=this.pos;for(;r<this.tokens.length;){let n=this.tokens[r];if(n.type===y.LPAREN&&e++,n.type===y.RPAREN&&e--,n.type===y.QUESTION&&e===0)return!0;if(n.type===y.NEWLINE||n.type===y.SEMICOLON||n.type===y.RBRACE||n.type===y.COMMA||n.type===y.PIPE)return!1;r++}return!1}parsePrintOr(){let e=this.parsePrintAnd();for(;this.check(y.OR);){this.advance();let r=this.parsePrintAnd();e={type:"binary",operator:"||",left:e,right:r}}return e}parsePrintAnd(){let e=this.parsePrintIn();for(;this.check(y.AND);){this.advance();let r=this.parsePrintIn();e={type:"binary",operator:"&&",left:e,right:r}}return e}parsePrintIn(){let e=this.parsePrintMatch();if(this.check(y.IN)){this.advance();let r=String(this.expect(y.IDENT).value);return{type:"in",key:e,array:r}}return e}parsePrintMatch(){let e=this.parsePrintComparison();for(;this.match(y.MATCH,y.NOT_MATCH);){let r=this.advance().type===y.MATCH?"~":"!~",n=this.parsePrintComparison();e={type:"binary",operator:r,left:e,right:n}}return e}parsePrintComparison(){let e=this.parseConcatenation();for(;this.match(y.LT,y.LE,y.GE,y.EQ,y.NE);){let r=this.advance(),n=this.parseConcatenation();e={type:"binary",operator:{"<":"<","<=":"<=",">=":">=","==":"==","!=":"!="}[r.value],left:e,right:n}}return e}parsePrintf(){this.expect(y.PRINTF);let e=this.parsePrintArg(),r=[];for(;this.check(y.COMMA);)this.advance(),r.push(this.parsePrintArg());let n;return this.check(y.GT)?(this.advance(),n={redirect:">",file:this.parsePrimary()}):this.check(y.APPEND)&&(this.advance(),n={redirect:">>",file:this.parsePrimary()}),{type:"printf",format:e,args:r,output:n}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseTernary();if(this.match(y.ASSIGN,y.PLUS_ASSIGN,y.MINUS_ASSIGN,y.STAR_ASSIGN,y.SLASH_ASSIGN,y.PERCENT_ASSIGN,y.CARET_ASSIGN)){let r=this.advance(),n=this.parseAssignment();if(e.type!=="variable"&&e.type!=="field"&&e.type!=="array_access")throw new Error("Invalid assignment target");return{type:"assignment",operator:{"=":"=","+=":"+=","-=":"-=","*=":"*=","/=":"/=","%=":"%=","^=":"^="}[r.value],target:e,value:n}}return e}parseTernary(){let e=this.parseOr();if(this.check(y.QUESTION)){this.advance();let r=this.parseExpression();this.expect(y.COLON);let n=this.parseExpression();e={type:"ternary",condition:e,consequent:r,alternate:n}}return e}parseOr(){let e=this.parseAnd();for(;this.check(y.OR);){this.advance();let r=this.parseAnd();e={type:"binary",operator:"||",left:e,right:r}}return e}parseLogicalOrRest(e){for(e=this.parseLogicalAndRest(e);this.check(y.OR);){this.advance();let r=this.parseAnd();e={type:"binary",operator:"||",left:e,right:r}}return e}parseLogicalAndRest(e){for(;this.check(y.AND);){this.advance();let r=this.parseIn();e={type:"binary",operator:"&&",left:e,right:r}}return e}parseAnd(){let e=this.parseIn();for(;this.check(y.AND);){this.advance();let r=this.parseIn();e={type:"binary",operator:"&&",left:e,right:r}}return e}parseIn(){let e=this.parseMatch();if(this.check(y.IN)){this.advance();let r=this.expect(y.IDENT).value;return{type:"in",key:e,array:r}}return e}parseMatch(){let e=this.parseComparison();for(;this.match(y.MATCH,y.NOT_MATCH);){let r=this.advance().type===y.MATCH?"~":"!~",n=this.parseComparison();e={type:"binary",operator:r,left:e,right:n}}return e}parseComparison(){let e=this.parseConcatenation();for(;this.match(y.LT,y.LE,y.GT,y.GE,y.EQ,y.NE);){let r=this.advance(),n=this.parseConcatenation();e={type:"binary",operator:{"<":"<","<=":"<=",">":">",">=":">=","==":"==","!=":"!="}[r.value],left:e,right:n}}return e}parseConcatenation(){let e=this.parseAddSub();for(;this.canStartExpression()&&!this.isComparisonOrHigherOp();){let r=this.parseAddSub();e={type:"binary",operator:" ",left:e,right:r}}return e}canStartExpression(){return this.match(y.NUMBER,y.STRING,y.IDENT,y.DOLLAR,y.LPAREN,y.NOT,y.MINUS,y.PLUS,y.INCREMENT,y.DECREMENT)}isComparisonOrHigherOp(){return this.match(y.LT,y.LE,y.GT,y.GE,y.EQ,y.NE,y.AND,y.OR,y.QUESTION,y.MATCH,y.NOT_MATCH,y.ASSIGN,y.PLUS_ASSIGN,y.MINUS_ASSIGN,y.STAR_ASSIGN,y.SLASH_ASSIGN,y.PERCENT_ASSIGN,y.CARET_ASSIGN,y.COMMA,y.SEMICOLON,y.NEWLINE,y.RBRACE,y.RPAREN,y.RBRACKET,y.COLON,y.PIPE,y.APPEND,y.IN)}parseAddSub(){let e=this.parseMulDiv();for(;this.match(y.PLUS,y.MINUS);){let r=this.advance().value,n=this.parseMulDiv();e={type:"binary",operator:r,left:e,right:n}}return e}parseMulDiv(){let e=this.parseUnary();for(;this.match(y.STAR,y.SLASH,y.PERCENT);){let r=this.advance(),n=this.parseUnary();e={type:"binary",operator:{"*":"*","/":"/","%":"%"}[r.value],left:e,right:n}}return e}parseUnary(){if(this.check(y.INCREMENT)){this.advance();let e=this.parseUnary();return e.type!=="variable"&&e.type!=="field"&&e.type!=="array_access"?{type:"unary",operator:"+",operand:{type:"unary",operator:"+",operand:e}}:{type:"pre_increment",operand:e}}if(this.check(y.DECREMENT)){this.advance();let e=this.parseUnary();return e.type!=="variable"&&e.type!=="field"&&e.type!=="array_access"?{type:"unary",operator:"-",operand:{type:"unary",operator:"-",operand:e}}:{type:"pre_decrement",operand:e}}if(this.match(y.NOT,y.MINUS,y.PLUS)){let e=this.advance().value,r=this.parseUnary();return{type:"unary",operator:e,operand:r}}return this.parsePower()}parsePower(){let e=this.parsePostfix();if(this.check(y.CARET)){this.advance();let r=this.parsePower();e={type:"binary",operator:"^",left:e,right:r}}return e}parsePostfix(){let e=this.parsePrimary();if(this.check(y.INCREMENT)){if(this.advance(),e.type!=="variable"&&e.type!=="field"&&e.type!=="array_access")throw new Error("Invalid increment operand");return{type:"post_increment",operand:e}}if(this.check(y.DECREMENT)){if(this.advance(),e.type!=="variable"&&e.type!=="field"&&e.type!=="array_access")throw new Error("Invalid decrement operand");return{type:"post_decrement",operand:e}}return e}parsePrimary(){if(this.check(y.NUMBER))return{type:"number",value:this.advance().value};if(this.check(y.STRING))return{type:"string",value:this.advance().value};if(this.check(y.REGEX))return{type:"regex",pattern:this.advance().value};if(this.check(y.DOLLAR))return this.advance(),{type:"field",index:this.parsePrimary()};if(this.check(y.LPAREN)){this.advance();let e=this.parseExpression();if(this.check(y.COMMA)){let r=[e];for(;this.check(y.COMMA);)this.advance(),r.push(this.parseExpression());return this.expect(y.RPAREN),{type:"tuple",elements:r}}return this.expect(y.RPAREN),e}if(this.check(y.GETLINE)){this.advance();let e,r;return this.check(y.IDENT)&&(e=this.advance().value),this.check(y.LT)&&(this.advance(),r=this.parsePrimary()),{type:"getline",variable:e,file:r}}if(this.check(y.IDENT)){let e=this.advance().value;if(this.check(y.LPAREN)){this.advance();let r=[];if(!this.check(y.RPAREN))for(r.push(this.parseExpression());this.check(y.COMMA);)this.advance(),r.push(this.parseExpression());return this.expect(y.RPAREN),{type:"call",name:e,args:r}}if(this.check(y.LBRACKET)){this.advance();let r=[this.parseExpression()];for(;this.check(y.COMMA);)this.advance(),r.push(this.parseExpression());this.expect(y.RBRACKET);let n;if(r.length===1)n=r[0];else{n=r[0];for(let s=1;s<r.length;s++)n={type:"binary",operator:" ",left:{type:"binary",operator:" ",left:n,right:{type:"variable",name:"SUBSEP"}},right:r[s]}}return{type:"array_access",array:e,key:n}}return{type:"variable",name:e}}throw new Error(`Unexpected token: ${this.current().type} at line ${this.current().line}:${this.current().column}`)}}});var Ai={};O(Ai,{awkCommand2:()=>Au});function bi(t){return t.replace(/\\t/g," ").replace(/\\n/g,`
243
- `).replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function xi(t){if(t===" ")return/\s+/;if(/[[\](){}.*+?^$|\\]/.test(t))try{return new RegExp(t)}catch{return new RegExp(Si(t))}return new RegExp(Si(t))}function Si(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Su,Au,Ci=N(()=>{"use strict";X();L();gi();Ei();Su={name:"awk",summary:"pattern scanning and text processing language",usage:"awk [OPTIONS] 'PROGRAM' [FILE...]",options:["-F FS use FS as field separator","-v VAR=VAL assign VAL to variable VAR"," --help display this help and exit"]},Au={name:"awk",async execute(t,e){if(C(t))return A(Su);let r=/\s+/,n=" ",s={},i=0;for(let h=0;h<t.length;h++){let p=t[h];if(p==="-F"&&h+1<t.length)n=bi(t[++h]),r=xi(n),i=h+1;else if(p.startsWith("-F"))n=bi(p.slice(2)),r=xi(n),i=h+1;else if(p==="-v"&&h+1<t.length){let b=t[++h],w=b.indexOf("=");if(w>0){let g=b.slice(0,w),E=b.slice(w+1);s[g]=E}i=h+1}else{if(p.startsWith("--"))return T("awk",p);if(p.startsWith("-")&&p.length>1){let b=p[1];if(b!=="F"&&b!=="v")return T("awk",`-${b}`);i=h+1}else if(!p.startsWith("-")){i=h;break}}}if(i>=t.length)return{stdout:"",stderr:`awk: missing program
244
- `,exitCode:1};let a=t[i],o=t.slice(i+1),c=new Vt,l;try{l=c.parse(a)}catch(h){return{stdout:"",stderr:`awk: ${h instanceof Error?h.message:String(h)}
245
- `,exitCode:1}}let u={readFile:e.fs.readFile.bind(e.fs),writeFile:e.fs.writeFile.bind(e.fs),appendFile:async(h,p)=>{try{let b=await e.fs.readFile(h);await e.fs.writeFile(h,b+p)}catch{await e.fs.writeFile(h,p)}},resolvePath:e.fs.resolvePath.bind(e.fs)},f=_r({fieldSep:r,maxIterations:e.limits?.maxAwkIterations,fs:u,cwd:e.cwd});f.FS=n,f.vars={...s},f.ARGC=o.length+1,f.ARGV={0:"awk"};for(let h=0;h<o.length;h++)f.ARGV[String(h+1)]=o[h];let d=new At(f);d.execute(l);try{if(await d.executeBegin(),f.shouldExit)return{stdout:d.getOutput(),stderr:"",exitCode:d.getExitCode()};let h=[];if(o.length>0)for(let p of o)try{let b=e.fs.resolvePath(e.cwd,p),g=(await e.fs.readFile(b)).split(`
242
+ `)break;n+=this.advance()}return this.peek()==="/"&&this.advance(),n=Cu(n),{type:y.REGEX,value:n,line:e,column:r}}readNumber(){let e=this.line,r=this.column,n="";for(;this.isDigit(this.peek());)n+=this.advance();if(this.peek()==="."&&this.isDigit(this.peek(1)))for(n+=this.advance();this.isDigit(this.peek());)n+=this.advance();if(this.peek()==="e"||this.peek()==="E")for(n+=this.advance(),(this.peek()==="+"||this.peek()==="-")&&(n+=this.advance());this.isDigit(this.peek());)n+=this.advance();return{type:y.NUMBER,value:parseFloat(n),line:e,column:r}}readIdentifier(){let e=this.line,r=this.column,n="";for(;this.isAlphaNumeric(this.peek())||this.peek()==="_";)n+=this.advance();let s=Au[n];return s?{type:s,value:n,line:e,column:r}:{type:y.IDENT,value:n,line:e,column:r}}readOperator(){let e=this.line,r=this.column,n=this.advance(),s=this.peek();switch(n){case"+":return s==="+"?(this.advance(),{type:y.INCREMENT,value:"++",line:e,column:r}):s==="="?(this.advance(),{type:y.PLUS_ASSIGN,value:"+=",line:e,column:r}):{type:y.PLUS,value:"+",line:e,column:r};case"-":return s==="-"?(this.advance(),{type:y.DECREMENT,value:"--",line:e,column:r}):s==="="?(this.advance(),{type:y.MINUS_ASSIGN,value:"-=",line:e,column:r}):{type:y.MINUS,value:"-",line:e,column:r};case"*":return s==="*"?(this.advance(),{type:y.CARET,value:"**",line:e,column:r}):s==="="?(this.advance(),{type:y.STAR_ASSIGN,value:"*=",line:e,column:r}):{type:y.STAR,value:"*",line:e,column:r};case"/":return s==="="?(this.advance(),{type:y.SLASH_ASSIGN,value:"/=",line:e,column:r}):{type:y.SLASH,value:"/",line:e,column:r};case"%":return s==="="?(this.advance(),{type:y.PERCENT_ASSIGN,value:"%=",line:e,column:r}):{type:y.PERCENT,value:"%",line:e,column:r};case"^":return s==="="?(this.advance(),{type:y.CARET_ASSIGN,value:"^=",line:e,column:r}):{type:y.CARET,value:"^",line:e,column:r};case"=":return s==="="?(this.advance(),{type:y.EQ,value:"==",line:e,column:r}):{type:y.ASSIGN,value:"=",line:e,column:r};case"!":return s==="="?(this.advance(),{type:y.NE,value:"!=",line:e,column:r}):s==="~"?(this.advance(),{type:y.NOT_MATCH,value:"!~",line:e,column:r}):{type:y.NOT,value:"!",line:e,column:r};case"<":return s==="="?(this.advance(),{type:y.LE,value:"<=",line:e,column:r}):{type:y.LT,value:"<",line:e,column:r};case">":return s==="="?(this.advance(),{type:y.GE,value:">=",line:e,column:r}):s===">"?(this.advance(),{type:y.APPEND,value:">>",line:e,column:r}):{type:y.GT,value:">",line:e,column:r};case"&":return s==="&"?(this.advance(),{type:y.AND,value:"&&",line:e,column:r}):{type:y.IDENT,value:"&",line:e,column:r};case"|":return s==="|"?(this.advance(),{type:y.OR,value:"||",line:e,column:r}):{type:y.PIPE,value:"|",line:e,column:r};case"~":return{type:y.MATCH,value:"~",line:e,column:r};case"?":return{type:y.QUESTION,value:"?",line:e,column:r};case":":return{type:y.COLON,value:":",line:e,column:r};case",":return{type:y.COMMA,value:",",line:e,column:r};case";":return{type:y.SEMICOLON,value:";",line:e,column:r};case"(":return{type:y.LPAREN,value:"(",line:e,column:r};case")":return{type:y.RPAREN,value:")",line:e,column:r};case"{":return{type:y.LBRACE,value:"{",line:e,column:r};case"}":return{type:y.RBRACE,value:"}",line:e,column:r};case"[":return{type:y.LBRACKET,value:"[",line:e,column:r};case"]":return{type:y.RBRACKET,value:"]",line:e,column:r};case"$":return{type:y.DOLLAR,value:"$",line:e,column:r};default:return{type:y.IDENT,value:n,line:e,column:r}}}isDigit(e){return e>="0"&&e<="9"}isAlpha(e){return e>="a"&&e<="z"||e>="A"&&e<="Z"}isAlphaNumeric(e){return this.isDigit(e)||this.isAlpha(e)}}});var Xt,Ai=v(()=>{"use strict";xi();Xt=class{tokens=[];pos=0;parse(e){let r=new Kt(e);return this.tokens=r.tokenize(),this.pos=0,this.parseProgram()}current(){return this.tokens[this.pos]||{type:y.EOF,value:"",line:0,column:0}}advance(){let e=this.current();return this.pos<this.tokens.length&&this.pos++,e}match(...e){return e.includes(this.current().type)}check(e){return this.current().type===e}expect(e,r){if(!this.check(e)){let n=this.current();throw new Error(r||`Expected ${e}, got ${n.type} at line ${n.line}:${n.column}`)}return this.advance()}skipNewlines(){for(;this.check(y.NEWLINE);)this.advance()}skipTerminators(){for(;this.check(y.NEWLINE)||this.check(y.SEMICOLON);)this.advance()}parseProgram(){let e=[],r=[];for(this.skipNewlines();!this.check(y.EOF)&&(this.skipNewlines(),!this.check(y.EOF));)this.check(y.FUNCTION)?e.push(this.parseFunction()):r.push(this.parseRule()),this.skipTerminators();return{functions:e,rules:r}}parseFunction(){this.expect(y.FUNCTION);let e=this.expect(y.IDENT).value;this.expect(y.LPAREN);let r=[];if(!this.check(y.RPAREN))for(r.push(this.expect(y.IDENT).value);this.check(y.COMMA);)this.advance(),r.push(this.expect(y.IDENT).value);this.expect(y.RPAREN),this.skipNewlines();let n=this.parseBlock();return{name:e,params:r,body:n}}parseRule(){let e;if(this.check(y.BEGIN))this.advance(),e={type:"begin"};else if(this.check(y.END))this.advance(),e={type:"end"};else if(this.check(y.LBRACE))e=void 0;else if(this.check(y.REGEX)){let n=this.advance();if(this.check(y.AND)||this.check(y.OR)){let s={type:"binary",operator:"~",left:{type:"field",index:{type:"number",value:0}},right:{type:"regex",pattern:n.value}};e={type:"expr_pattern",expression:this.parseLogicalOrRest(s)}}else{let s={type:"regex_pattern",pattern:n.value};if(this.check(y.COMMA)){this.advance();let i;this.check(y.REGEX)?i={type:"regex_pattern",pattern:this.advance().value}:i={type:"expr_pattern",expression:this.parseExpression()},e={type:"range",start:s,end:i}}else e=s}}else{let s={type:"expr_pattern",expression:this.parseExpression()};if(this.check(y.COMMA)){this.advance();let i;this.check(y.REGEX)?i={type:"regex_pattern",pattern:this.advance().value}:i={type:"expr_pattern",expression:this.parseExpression()},e={type:"range",start:s,end:i}}else e=s}this.skipNewlines();let r;return this.check(y.LBRACE)?r=this.parseBlock():r={type:"block",statements:[{type:"print",args:[{type:"field",index:{type:"number",value:0}}]}]},{pattern:e,action:r}}parseBlock(){this.expect(y.LBRACE),this.skipNewlines();let e=[];for(;!this.check(y.RBRACE)&&!this.check(y.EOF);)e.push(this.parseStatement()),this.skipTerminators();return this.expect(y.RBRACE),{type:"block",statements:e}}parseStatement(){if(this.check(y.LBRACE))return this.parseBlock();if(this.check(y.IF))return this.parseIf();if(this.check(y.WHILE))return this.parseWhile();if(this.check(y.DO))return this.parseDoWhile();if(this.check(y.FOR))return this.parseFor();if(this.check(y.BREAK))return this.advance(),{type:"break"};if(this.check(y.CONTINUE))return this.advance(),{type:"continue"};if(this.check(y.NEXT))return this.advance(),{type:"next"};if(this.check(y.NEXTFILE))return this.advance(),{type:"nextfile"};if(this.check(y.EXIT)){this.advance();let r;return!this.check(y.NEWLINE)&&!this.check(y.SEMICOLON)&&!this.check(y.RBRACE)&&!this.check(y.EOF)&&(r=this.parseExpression()),{type:"exit",code:r}}if(this.check(y.RETURN)){this.advance();let r;return!this.check(y.NEWLINE)&&!this.check(y.SEMICOLON)&&!this.check(y.RBRACE)&&!this.check(y.EOF)&&(r=this.parseExpression()),{type:"return",value:r}}if(this.check(y.DELETE)){this.advance();let r=this.parsePrimary();if(r.type!=="array_access"&&r.type!=="variable")throw new Error("delete requires array element or array");return{type:"delete",target:r}}return this.check(y.PRINT)?this.parsePrint():this.check(y.PRINTF)?this.parsePrintf():{type:"expr_stmt",expression:this.parseExpression()}}parseIf(){this.expect(y.IF),this.expect(y.LPAREN);let e=this.parseExpression();this.expect(y.RPAREN),this.skipNewlines();let r=this.parseStatement();this.skipTerminators();let n;return this.check(y.ELSE)&&(this.advance(),this.skipNewlines(),n=this.parseStatement()),{type:"if",condition:e,consequent:r,alternate:n}}parseWhile(){this.expect(y.WHILE),this.expect(y.LPAREN);let e=this.parseExpression();this.expect(y.RPAREN),this.skipNewlines();let r=this.parseStatement();return{type:"while",condition:e,body:r}}parseDoWhile(){this.expect(y.DO),this.skipNewlines();let e=this.parseStatement();this.skipNewlines(),this.expect(y.WHILE),this.expect(y.LPAREN);let r=this.parseExpression();return this.expect(y.RPAREN),{type:"do_while",body:e,condition:r}}parseFor(){if(this.expect(y.FOR),this.expect(y.LPAREN),this.check(y.IDENT)){let i=this.advance();if(this.check(y.IN)){this.advance();let a=this.expect(y.IDENT).value;this.expect(y.RPAREN),this.skipNewlines();let o=this.parseStatement();return{type:"for_in",variable:i.value,array:a,body:o}}this.pos--}let e;this.check(y.SEMICOLON)||(e=this.parseExpression()),this.expect(y.SEMICOLON);let r;this.check(y.SEMICOLON)||(r=this.parseExpression()),this.expect(y.SEMICOLON);let n;this.check(y.RPAREN)||(n=this.parseExpression()),this.expect(y.RPAREN),this.skipNewlines();let s=this.parseStatement();return{type:"for",init:e,condition:r,update:n,body:s}}parsePrint(){this.expect(y.PRINT);let e=[];if(this.check(y.NEWLINE)||this.check(y.SEMICOLON)||this.check(y.RBRACE)||this.check(y.PIPE)||this.check(y.GT)||this.check(y.APPEND))e.push({type:"field",index:{type:"number",value:0}});else for(e.push(this.parsePrintArg());this.check(y.COMMA);)this.advance(),e.push(this.parsePrintArg());let r;return this.check(y.GT)?(this.advance(),r={redirect:">",file:this.parsePrimary()}):this.check(y.APPEND)&&(this.advance(),r={redirect:">>",file:this.parsePrimary()}),{type:"print",args:e,output:r}}parsePrintArg(){return this.lookAheadForTernary()?this.parseTernary():this.parsePrintOr()}lookAheadForTernary(){let e=0,r=this.pos;for(;r<this.tokens.length;){let n=this.tokens[r];if(n.type===y.LPAREN&&e++,n.type===y.RPAREN&&e--,n.type===y.QUESTION&&e===0)return!0;if(n.type===y.NEWLINE||n.type===y.SEMICOLON||n.type===y.RBRACE||n.type===y.COMMA||n.type===y.PIPE)return!1;r++}return!1}parsePrintOr(){let e=this.parsePrintAnd();for(;this.check(y.OR);){this.advance();let r=this.parsePrintAnd();e={type:"binary",operator:"||",left:e,right:r}}return e}parsePrintAnd(){let e=this.parsePrintIn();for(;this.check(y.AND);){this.advance();let r=this.parsePrintIn();e={type:"binary",operator:"&&",left:e,right:r}}return e}parsePrintIn(){let e=this.parsePrintMatch();if(this.check(y.IN)){this.advance();let r=String(this.expect(y.IDENT).value);return{type:"in",key:e,array:r}}return e}parsePrintMatch(){let e=this.parsePrintComparison();for(;this.match(y.MATCH,y.NOT_MATCH);){let r=this.advance().type===y.MATCH?"~":"!~",n=this.parsePrintComparison();e={type:"binary",operator:r,left:e,right:n}}return e}parsePrintComparison(){let e=this.parseConcatenation();for(;this.match(y.LT,y.LE,y.GE,y.EQ,y.NE);){let r=this.advance(),n=this.parseConcatenation();e={type:"binary",operator:{"<":"<","<=":"<=",">=":">=","==":"==","!=":"!="}[r.value],left:e,right:n}}return e}parsePrintf(){this.expect(y.PRINTF);let e=this.parsePrintArg(),r=[];for(;this.check(y.COMMA);)this.advance(),r.push(this.parsePrintArg());let n;return this.check(y.GT)?(this.advance(),n={redirect:">",file:this.parsePrimary()}):this.check(y.APPEND)&&(this.advance(),n={redirect:">>",file:this.parsePrimary()}),{type:"printf",format:e,args:r,output:n}}parseExpression(){return this.parseAssignment()}parseAssignment(){let e=this.parseTernary();if(this.match(y.ASSIGN,y.PLUS_ASSIGN,y.MINUS_ASSIGN,y.STAR_ASSIGN,y.SLASH_ASSIGN,y.PERCENT_ASSIGN,y.CARET_ASSIGN)){let r=this.advance(),n=this.parseAssignment();if(e.type!=="variable"&&e.type!=="field"&&e.type!=="array_access")throw new Error("Invalid assignment target");return{type:"assignment",operator:{"=":"=","+=":"+=","-=":"-=","*=":"*=","/=":"/=","%=":"%=","^=":"^="}[r.value],target:e,value:n}}return e}parseTernary(){let e=this.parseOr();if(this.check(y.QUESTION)){this.advance();let r=this.parseExpression();this.expect(y.COLON);let n=this.parseExpression();e={type:"ternary",condition:e,consequent:r,alternate:n}}return e}parseOr(){let e=this.parseAnd();for(;this.check(y.OR);){this.advance();let r=this.parseAnd();e={type:"binary",operator:"||",left:e,right:r}}return e}parseLogicalOrRest(e){for(e=this.parseLogicalAndRest(e);this.check(y.OR);){this.advance();let r=this.parseAnd();e={type:"binary",operator:"||",left:e,right:r}}return e}parseLogicalAndRest(e){for(;this.check(y.AND);){this.advance();let r=this.parseIn();e={type:"binary",operator:"&&",left:e,right:r}}return e}parseAnd(){let e=this.parseIn();for(;this.check(y.AND);){this.advance();let r=this.parseIn();e={type:"binary",operator:"&&",left:e,right:r}}return e}parseIn(){let e=this.parseMatch();if(this.check(y.IN)){this.advance();let r=this.expect(y.IDENT).value;return{type:"in",key:e,array:r}}return e}parseMatch(){let e=this.parseComparison();for(;this.match(y.MATCH,y.NOT_MATCH);){let r=this.advance().type===y.MATCH?"~":"!~",n=this.parseComparison();e={type:"binary",operator:r,left:e,right:n}}return e}parseComparison(){let e=this.parseConcatenation();for(;this.match(y.LT,y.LE,y.GT,y.GE,y.EQ,y.NE);){let r=this.advance(),n=this.parseConcatenation();e={type:"binary",operator:{"<":"<","<=":"<=",">":">",">=":">=","==":"==","!=":"!="}[r.value],left:e,right:n}}return e}parseConcatenation(){let e=this.parseAddSub();for(;this.canStartExpression()&&!this.isComparisonOrHigherOp();){let r=this.parseAddSub();e={type:"binary",operator:" ",left:e,right:r}}return e}canStartExpression(){return this.match(y.NUMBER,y.STRING,y.IDENT,y.DOLLAR,y.LPAREN,y.NOT,y.MINUS,y.PLUS,y.INCREMENT,y.DECREMENT)}isComparisonOrHigherOp(){return this.match(y.LT,y.LE,y.GT,y.GE,y.EQ,y.NE,y.AND,y.OR,y.QUESTION,y.MATCH,y.NOT_MATCH,y.ASSIGN,y.PLUS_ASSIGN,y.MINUS_ASSIGN,y.STAR_ASSIGN,y.SLASH_ASSIGN,y.PERCENT_ASSIGN,y.CARET_ASSIGN,y.COMMA,y.SEMICOLON,y.NEWLINE,y.RBRACE,y.RPAREN,y.RBRACKET,y.COLON,y.PIPE,y.APPEND,y.IN)}parseAddSub(){let e=this.parseMulDiv();for(;this.match(y.PLUS,y.MINUS);){let r=this.advance().value,n=this.parseMulDiv();e={type:"binary",operator:r,left:e,right:n}}return e}parseMulDiv(){let e=this.parseUnary();for(;this.match(y.STAR,y.SLASH,y.PERCENT);){let r=this.advance(),n=this.parseUnary();e={type:"binary",operator:{"*":"*","/":"/","%":"%"}[r.value],left:e,right:n}}return e}parseUnary(){if(this.check(y.INCREMENT)){this.advance();let e=this.parseUnary();return e.type!=="variable"&&e.type!=="field"&&e.type!=="array_access"?{type:"unary",operator:"+",operand:{type:"unary",operator:"+",operand:e}}:{type:"pre_increment",operand:e}}if(this.check(y.DECREMENT)){this.advance();let e=this.parseUnary();return e.type!=="variable"&&e.type!=="field"&&e.type!=="array_access"?{type:"unary",operator:"-",operand:{type:"unary",operator:"-",operand:e}}:{type:"pre_decrement",operand:e}}if(this.match(y.NOT,y.MINUS,y.PLUS)){let e=this.advance().value,r=this.parseUnary();return{type:"unary",operator:e,operand:r}}return this.parsePower()}parsePower(){let e=this.parsePostfix();if(this.check(y.CARET)){this.advance();let r=this.parsePower();e={type:"binary",operator:"^",left:e,right:r}}return e}parsePostfix(){let e=this.parsePrimary();if(this.check(y.INCREMENT)){if(this.advance(),e.type!=="variable"&&e.type!=="field"&&e.type!=="array_access")throw new Error("Invalid increment operand");return{type:"post_increment",operand:e}}if(this.check(y.DECREMENT)){if(this.advance(),e.type!=="variable"&&e.type!=="field"&&e.type!=="array_access")throw new Error("Invalid decrement operand");return{type:"post_decrement",operand:e}}return e}parsePrimary(){if(this.check(y.NUMBER))return{type:"number",value:this.advance().value};if(this.check(y.STRING))return{type:"string",value:this.advance().value};if(this.check(y.REGEX))return{type:"regex",pattern:this.advance().value};if(this.check(y.DOLLAR))return this.advance(),{type:"field",index:this.parsePrimary()};if(this.check(y.LPAREN)){this.advance();let e=this.parseExpression();if(this.check(y.COMMA)){let r=[e];for(;this.check(y.COMMA);)this.advance(),r.push(this.parseExpression());return this.expect(y.RPAREN),{type:"tuple",elements:r}}return this.expect(y.RPAREN),e}if(this.check(y.GETLINE)){this.advance();let e,r;return this.check(y.IDENT)&&(e=this.advance().value),this.check(y.LT)&&(this.advance(),r=this.parsePrimary()),{type:"getline",variable:e,file:r}}if(this.check(y.IDENT)){let e=this.advance().value;if(this.check(y.LPAREN)){this.advance();let r=[];if(!this.check(y.RPAREN))for(r.push(this.parseExpression());this.check(y.COMMA);)this.advance(),r.push(this.parseExpression());return this.expect(y.RPAREN),{type:"call",name:e,args:r}}if(this.check(y.LBRACKET)){this.advance();let r=[this.parseExpression()];for(;this.check(y.COMMA);)this.advance(),r.push(this.parseExpression());this.expect(y.RBRACKET);let n;if(r.length===1)n=r[0];else{n=r[0];for(let s=1;s<r.length;s++)n={type:"binary",operator:" ",left:{type:"binary",operator:" ",left:n,right:{type:"variable",name:"SUBSEP"}},right:r[s]}}return{type:"array_access",array:e,key:n}}return{type:"variable",name:e}}throw new Error(`Unexpected token: ${this.current().type} at line ${this.current().line}:${this.current().column}`)}}});var ki={};D(ki,{awkCommand2:()=>vu});function Ci(t){return t.replace(/\\t/g," ").replace(/\\n/g,`
243
+ `).replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function Ni(t){if(t===" ")return/\s+/;if(/[[\](){}.*+?^$|\\]/.test(t))try{return new RegExp(t)}catch{return new RegExp(vi(t))}return new RegExp(vi(t))}function vi(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var Nu,vu,Ii=v(()=>{"use strict";Y();F();Si();Ai();Nu={name:"awk",summary:"pattern scanning and text processing language",usage:"awk [OPTIONS] 'PROGRAM' [FILE...]",options:["-F FS use FS as field separator","-v VAR=VAL assign VAL to variable VAR"," --help display this help and exit"]},vu={name:"awk",async execute(t,e){if(N(t))return C(Nu);let r=/\s+/,n=" ",s={},i=0;for(let h=0;h<t.length;h++){let p=t[h];if(p==="-F"&&h+1<t.length)n=Ci(t[++h]),r=Ni(n),i=h+1;else if(p.startsWith("-F"))n=Ci(p.slice(2)),r=Ni(n),i=h+1;else if(p==="-v"&&h+1<t.length){let E=t[++h],w=E.indexOf("=");if(w>0){let g=E.slice(0,w),b=E.slice(w+1);s[g]=b}i=h+1}else{if(p.startsWith("--"))return M("awk",p);if(p.startsWith("-")&&p.length>1){let E=p[1];if(E!=="F"&&E!=="v")return M("awk",`-${E}`);i=h+1}else if(!p.startsWith("-")){i=h;break}}}if(i>=t.length)return{stdout:"",stderr:`awk: missing program
244
+ `,exitCode:1};let a=t[i],o=t.slice(i+1),c=new Xt,l;try{l=c.parse(a)}catch(h){return{stdout:"",stderr:`awk: ${h instanceof Error?h.message:String(h)}
245
+ `,exitCode:1}}let u={readFile:e.fs.readFile.bind(e.fs),writeFile:e.fs.writeFile.bind(e.fs),appendFile:async(h,p)=>{try{let E=await e.fs.readFile(h);await e.fs.writeFile(h,E+p)}catch{await e.fs.writeFile(h,p)}},resolvePath:e.fs.resolvePath.bind(e.fs)},f=Hr({fieldSep:r,maxIterations:e.limits?.maxAwkIterations,fs:u,cwd:e.cwd});f.FS=n,f.vars={...s},f.ARGC=o.length+1,f.ARGV={0:"awk"};for(let h=0;h<o.length;h++)f.ARGV[String(h+1)]=o[h];let d=new Nt(f);d.execute(l);try{if(await d.executeBegin(),f.shouldExit)return{stdout:d.getOutput(),stderr:"",exitCode:d.getExitCode()};let h=[];if(o.length>0)for(let p of o)try{let E=e.fs.resolvePath(e.cwd,p),g=(await e.fs.readFile(E)).split(`
246
246
  `);g.length>0&&g[g.length-1]===""&&g.pop(),h.push({filename:p,lines:g})}catch{return{stdout:"",stderr:`awk: ${p}: No such file or directory
247
247
  `,exitCode:1}}else{let p=e.stdin.split(`
248
- `);p.length>0&&p[p.length-1]===""&&p.pop(),h.push({filename:"",lines:p})}for(let p of h){for(f.FILENAME=p.filename,f.FNR=0,f.lines=p.lines,f.lineIndex=-1,f.shouldNextFile=!1;f.lineIndex<p.lines.length-1&&(f.lineIndex++,await d.executeLine(p.lines[f.lineIndex]),!(f.shouldExit||f.shouldNextFile)););if(f.shouldExit)break}return f.shouldExit||await d.executeEnd(),{stdout:d.getOutput(),stderr:"",exitCode:d.getExitCode()}}catch(h){let p=h instanceof Error?h.message:String(h),b=h instanceof W?W.EXIT_CODE:2;return{stdout:d.getOutput(),stderr:`awk: ${p}
249
- `,exitCode:b}}}}});function Vr(t,e,r){let n=r!==null?r:/\s+/,s=t.split(n),i=e.startField-1;if(i>=s.length)return"";if(e.endField===void 0){let c=s[i]||"";return e.startChar!==void 0&&(c=c.slice(e.startChar-1)),e.ignoreLeading&&(c=c.trimStart()),c}let a=Math.min(e.endField-1,s.length-1),o="";for(let c=i;c<=a&&c<s.length;c++){let l=s[c]||"";if(c===i&&e.startChar!==void 0&&(l=l.slice(e.startChar-1)),c===a&&e.endChar!==void 0){let u=c===i&&e.startChar!==void 0?e.endChar-e.startChar+1:e.endChar;l=l.slice(0,u)}c>i&&(o+=r||" "),o+=l}return e.ignoreLeading&&(o=o.trimStart()),o}function Cu(t,e,r,n){if(r){let a=parseFloat(t)||0,o=parseFloat(e)||0;return a-o}let s=t,i=e;return n&&(s=s.toLowerCase(),i=i.toLowerCase()),s.localeCompare(i)}function Ni(t){let{keys:e,fieldDelimiter:r,numeric:n,ignoreCase:s,reverse:i}=t;return(a,o)=>{if(e.length===0){let l=a,u=o;s&&(l=l.toLowerCase(),u=u.toLowerCase());let f;if(n){let d=parseFloat(l)||0,h=parseFloat(u)||0;if(f=d-h,f===0){let p=l.localeCompare(u);return i?-p:p}}else f=l.localeCompare(u);return i?-f:f}for(let l of e){let u=Vr(a,l,r),f=Vr(o,l,r),d=l.numeric??n,h=l.ignoreCase??s,p=l.reverse??i,b=Cu(u,f,d,h);if(b!==0)return p?-b:b}let c=a.localeCompare(o);return i?-c:c}}function vi(t,e){if(e.keys.length===0){if(e.ignoreCase){let s=new Set;return t.filter(i=>{let a=i.toLowerCase();return s.has(a)?!1:(s.add(a),!0)})}return[...new Set(t)]}let r=e.keys[0],n=new Set;return t.filter(s=>{let i=Vr(s,r,e.fieldDelimiter);return(r.ignoreCase??e.ignoreCase)&&(i=i.toLowerCase()),n.has(i)?!1:(n.add(i),!0)})}var ki=N(()=>{"use strict"});function Zt(t){let e={startField:1},r="",n=t,s=n.match(/([nrfb]+)$/i);s&&(r=s[1].toLowerCase(),n=n.slice(0,-r.length)),r.includes("n")&&(e.numeric=!0),r.includes("r")&&(e.reverse=!0),r.includes("f")&&(e.ignoreCase=!0),r.includes("b")&&(e.ignoreLeading=!0);let i=n.split(",");if(i.length===0||i[0]==="")return null;let a=i[0].split("."),o=parseInt(a[0],10);if(Number.isNaN(o)||o<1)return null;if(e.startField=o,a.length>1&&a[1]){let c=parseInt(a[1],10);!Number.isNaN(c)&&c>=1&&(e.startChar=c)}if(i.length>1&&i[1]){let c=i[1],l=c.match(/([nrfb]+)$/i);if(l){let f=l[1].toLowerCase();f.includes("n")&&(e.numeric=!0),f.includes("r")&&(e.reverse=!0),f.includes("f")&&(e.ignoreCase=!0),f.includes("b")&&(e.ignoreLeading=!0),c=c.slice(0,-f.length)}let u=c.split(".");if(u[0]){let f=parseInt(u[0],10);if(!Number.isNaN(f)&&f>=1&&(e.endField=f),u.length>1&&u[1]){let d=parseInt(u[1],10);!Number.isNaN(d)&&d>=1&&(e.endChar=d)}}}return e}var Ii=N(()=>{"use strict"});var Ri={};O(Ri,{sortCommand:()=>vu});var Nu,vu,$i=N(()=>{"use strict";Ze();L();ki();Ii();Nu={name:"sort",summary:"sort lines of text files",usage:"sort [OPTION]... [FILE]...",options:["-f, --ignore-case fold lower case to upper case characters","-n, --numeric-sort compare according to string numerical value","-r, --reverse reverse the result of comparisons","-u, --unique output only unique lines","-k, --key=KEYDEF sort via a key; KEYDEF gives location and type","-t, --field-separator=SEP use SEP as field separator"," --help display this help and exit"],description:`KEYDEF is F[.C][OPTS][,F[.C][OPTS]]
248
+ `);p.length>0&&p[p.length-1]===""&&p.pop(),h.push({filename:"",lines:p})}for(let p of h){for(f.FILENAME=p.filename,f.FNR=0,f.lines=p.lines,f.lineIndex=-1,f.shouldNextFile=!1;f.lineIndex<p.lines.length-1&&(f.lineIndex++,await d.executeLine(p.lines[f.lineIndex]),!(f.shouldExit||f.shouldNextFile)););if(f.shouldExit)break}return f.shouldExit||await d.executeEnd(),{stdout:d.getOutput(),stderr:"",exitCode:d.getExitCode()}}catch(h){let p=h instanceof Error?h.message:String(h),E=h instanceof B?B.EXIT_CODE:2;return{stdout:d.getOutput(),stderr:`awk: ${p}
249
+ `,exitCode:E}}}}});function Kr(t,e,r){let n=r!==null?r:/\s+/,s=t.split(n),i=e.startField-1;if(i>=s.length)return"";if(e.endField===void 0){let c=s[i]||"";return e.startChar!==void 0&&(c=c.slice(e.startChar-1)),e.ignoreLeading&&(c=c.trimStart()),c}let a=Math.min(e.endField-1,s.length-1),o="";for(let c=i;c<=a&&c<s.length;c++){let l=s[c]||"";if(c===i&&e.startChar!==void 0&&(l=l.slice(e.startChar-1)),c===a&&e.endChar!==void 0){let u=c===i&&e.startChar!==void 0?e.endChar-e.startChar+1:e.endChar;l=l.slice(0,u)}c>i&&(o+=r||" "),o+=l}return e.ignoreLeading&&(o=o.trimStart()),o}function ku(t,e,r,n){if(r){let a=parseFloat(t)||0,o=parseFloat(e)||0;return a-o}let s=t,i=e;return n&&(s=s.toLowerCase(),i=i.toLowerCase()),s.localeCompare(i)}function $i(t){let{keys:e,fieldDelimiter:r,numeric:n,ignoreCase:s,reverse:i}=t;return(a,o)=>{if(e.length===0){let l=a,u=o;s&&(l=l.toLowerCase(),u=u.toLowerCase());let f;if(n){let d=parseFloat(l)||0,h=parseFloat(u)||0;if(f=d-h,f===0){let p=l.localeCompare(u);return i?-p:p}}else f=l.localeCompare(u);return i?-f:f}for(let l of e){let u=Kr(a,l,r),f=Kr(o,l,r),d=l.numeric??n,h=l.ignoreCase??s,p=l.reverse??i,E=ku(u,f,d,h);if(E!==0)return p?-E:E}let c=a.localeCompare(o);return i?-c:c}}function Ri(t,e){if(e.keys.length===0){if(e.ignoreCase){let s=new Set;return t.filter(i=>{let a=i.toLowerCase();return s.has(a)?!1:(s.add(a),!0)})}return[...new Set(t)]}let r=e.keys[0],n=new Set;return t.filter(s=>{let i=Kr(s,r,e.fieldDelimiter);return(r.ignoreCase??e.ignoreCase)&&(i=i.toLowerCase()),n.has(i)?!1:(n.add(i),!0)})}var Pi=v(()=>{"use strict"});function Yt(t){let e={startField:1},r="",n=t,s=n.match(/([nrfb]+)$/i);s&&(r=s[1].toLowerCase(),n=n.slice(0,-r.length)),r.includes("n")&&(e.numeric=!0),r.includes("r")&&(e.reverse=!0),r.includes("f")&&(e.ignoreCase=!0),r.includes("b")&&(e.ignoreLeading=!0);let i=n.split(",");if(i.length===0||i[0]==="")return null;let a=i[0].split("."),o=parseInt(a[0],10);if(Number.isNaN(o)||o<1)return null;if(e.startField=o,a.length>1&&a[1]){let c=parseInt(a[1],10);!Number.isNaN(c)&&c>=1&&(e.startChar=c)}if(i.length>1&&i[1]){let c=i[1],l=c.match(/([nrfb]+)$/i);if(l){let f=l[1].toLowerCase();f.includes("n")&&(e.numeric=!0),f.includes("r")&&(e.reverse=!0),f.includes("f")&&(e.ignoreCase=!0),f.includes("b")&&(e.ignoreLeading=!0),c=c.slice(0,-f.length)}let u=c.split(".");if(u[0]){let f=parseInt(u[0],10);if(!Number.isNaN(f)&&f>=1&&(e.endField=f),u.length>1&&u[1]){let d=parseInt(u[1],10);!Number.isNaN(d)&&d>=1&&(e.endChar=d)}}}return e}var Oi=v(()=>{"use strict"});var Di={};D(Di,{sortCommand:()=>$u});var Iu,$u,Ti=v(()=>{"use strict";Ke();F();Pi();Oi();Iu={name:"sort",summary:"sort lines of text files",usage:"sort [OPTION]... [FILE]...",options:["-f, --ignore-case fold lower case to upper case characters","-n, --numeric-sort compare according to string numerical value","-r, --reverse reverse the result of comparisons","-u, --unique output only unique lines","-k, --key=KEYDEF sort via a key; KEYDEF gives location and type","-t, --field-separator=SEP use SEP as field separator"," --help display this help and exit"],description:`KEYDEF is F[.C][OPTS][,F[.C][OPTS]]
250
250
  F is a field number (1-indexed)
251
251
  C is a character position within the field (1-indexed)
252
252
  OPTS can be: n (numeric), r (reverse), f (fold case), b (ignore blanks)
@@ -256,24 +256,24 @@ Examples:
256
256
  -k2,2 sort by second field only
257
257
  -k1.3 sort by first field starting at 3rd character
258
258
  -k1,2n sort by fields 1-2 numerically
259
- -k2 -k1 sort by field 2, then by field 1`},vu={name:"sort",async execute(t,e){if(C(t))return A(Nu);let r={reverse:!1,numeric:!1,unique:!1,ignoreCase:!1,keys:[],fieldDelimiter:null},n=[];for(let l=0;l<t.length;l++){let u=t[l];if(u==="-r"||u==="--reverse")r.reverse=!0;else if(u==="-n"||u==="--numeric-sort")r.numeric=!0;else if(u==="-u"||u==="--unique")r.unique=!0;else if(u==="-f"||u==="--ignore-case")r.ignoreCase=!0;else if(u==="-t"||u==="--field-separator")r.fieldDelimiter=t[++l]||null;else if(u.startsWith("-t"))r.fieldDelimiter=u.slice(2)||null;else if(u.startsWith("--field-separator="))r.fieldDelimiter=u.slice(18)||null;else if(u==="-k"||u==="--key"){let f=t[++l];if(f){let d=Zt(f);d&&r.keys.push(d)}}else if(u.startsWith("-k")){let f=Zt(u.slice(2));f&&r.keys.push(f)}else if(u.startsWith("--key=")){let f=Zt(u.slice(6));f&&r.keys.push(f)}else{if(u.startsWith("--"))return T("sort",u);if(u.startsWith("-")&&!u.startsWith("--")){let f=!1;for(let d of u.slice(1))if(d==="r")r.reverse=!0;else if(d==="n")r.numeric=!0;else if(d==="u")r.unique=!0;else if(d==="f")r.ignoreCase=!0;else{f=!0;break}if(f)return T("sort",u)}else n.push(u)}}let s=await Be(e,n,{cmdName:"sort"});if(!s.ok)return s.error;let a=s.content.split(`
260
- `);a.length>0&&a[a.length-1]===""&&a.pop();let o=Ni(r);return a.sort(o),r.unique&&(a=vi(a,r)),{stdout:a.length>0?`${a.join(`
259
+ -k2 -k1 sort by field 2, then by field 1`},$u={name:"sort",async execute(t,e){if(N(t))return C(Iu);let r={reverse:!1,numeric:!1,unique:!1,ignoreCase:!1,keys:[],fieldDelimiter:null},n=[];for(let l=0;l<t.length;l++){let u=t[l];if(u==="-r"||u==="--reverse")r.reverse=!0;else if(u==="-n"||u==="--numeric-sort")r.numeric=!0;else if(u==="-u"||u==="--unique")r.unique=!0;else if(u==="-f"||u==="--ignore-case")r.ignoreCase=!0;else if(u==="-t"||u==="--field-separator")r.fieldDelimiter=t[++l]||null;else if(u.startsWith("-t"))r.fieldDelimiter=u.slice(2)||null;else if(u.startsWith("--field-separator="))r.fieldDelimiter=u.slice(18)||null;else if(u==="-k"||u==="--key"){let f=t[++l];if(f){let d=Yt(f);d&&r.keys.push(d)}}else if(u.startsWith("-k")){let f=Yt(u.slice(2));f&&r.keys.push(f)}else if(u.startsWith("--key=")){let f=Yt(u.slice(6));f&&r.keys.push(f)}else{if(u.startsWith("--"))return M("sort",u);if(u.startsWith("-")&&!u.startsWith("--")){let f=!1;for(let d of u.slice(1))if(d==="r")r.reverse=!0;else if(d==="n")r.numeric=!0;else if(d==="u")r.unique=!0;else if(d==="f")r.ignoreCase=!0;else{f=!0;break}if(f)return M("sort",u)}else n.push(u)}}let s=await He(e,n,{cmdName:"sort"});if(!s.ok)return s.error;let a=s.content.split(`
260
+ `);a.length>0&&a[a.length-1]===""&&a.pop();let o=$i(r);return a.sort(o),r.unique&&(a=Ri(a,r)),{stdout:a.length>0?`${a.join(`
261
261
  `)}
262
- `:"",stderr:"",exitCode:0}}}});var Pi={};O(Pi,{uniqCommand:()=>Ru});var ku,Iu,Ru,Oi=N(()=>{"use strict";ae();Ze();L();ku={name:"uniq",summary:"report or omit repeated lines",usage:"uniq [OPTION]... [INPUT [OUTPUT]]",options:["-c, --count prefix lines by the number of occurrences","-d, --repeated only print duplicate lines","-i, --ignore-case ignore case when comparing","-u, --unique only print unique lines"," --help display this help and exit"]},Iu={count:{short:"c",long:"count",type:"boolean"},duplicatesOnly:{short:"d",long:"repeated",type:"boolean"},uniqueOnly:{short:"u",long:"unique",type:"boolean"},ignoreCase:{short:"i",long:"ignore-case",type:"boolean"}},Ru={name:"uniq",async execute(t,e){if(C(t))return A(ku);let r=H("uniq",t,Iu);if(!r.ok)return r.error;let{count:n,duplicatesOnly:s,uniqueOnly:i,ignoreCase:a}=r.result.flags,o=r.result.positional,c=await Be(e,o,{cmdName:"uniq"});if(!c.ok)return c.error;let u=c.content.split(`
263
- `);if(u.length>0&&u[u.length-1]===""&&u.pop(),u.length===0)return{stdout:"",stderr:"",exitCode:0};let f=[],d=u[0],h=1,p=(g,E)=>a?g.toLowerCase()===E.toLowerCase():g===E;for(let g=1;g<u.length;g++)p(u[g],d)?h++:(f.push({line:d,count:h}),d=u[g],h=1);f.push({line:d,count:h});let b=f;s?b=f.filter(g=>g.count>1):i&&(b=f.filter(g=>g.count===1));let w="";for(let{line:g,count:E}of b)n?w+=`${String(E).padStart(4)} ${g}
262
+ `:"",stderr:"",exitCode:0}}}});var Li={};D(Li,{uniqCommand:()=>Ou});var Ru,Pu,Ou,Fi=v(()=>{"use strict";oe();Ke();F();Ru={name:"uniq",summary:"report or omit repeated lines",usage:"uniq [OPTION]... [INPUT [OUTPUT]]",options:["-c, --count prefix lines by the number of occurrences","-d, --repeated only print duplicate lines","-i, --ignore-case ignore case when comparing","-u, --unique only print unique lines"," --help display this help and exit"]},Pu={count:{short:"c",long:"count",type:"boolean"},duplicatesOnly:{short:"d",long:"repeated",type:"boolean"},uniqueOnly:{short:"u",long:"unique",type:"boolean"},ignoreCase:{short:"i",long:"ignore-case",type:"boolean"}},Ou={name:"uniq",async execute(t,e){if(N(t))return C(Ru);let r=G("uniq",t,Pu);if(!r.ok)return r.error;let{count:n,duplicatesOnly:s,uniqueOnly:i,ignoreCase:a}=r.result.flags,o=r.result.positional,c=await He(e,o,{cmdName:"uniq"});if(!c.ok)return c.error;let u=c.content.split(`
263
+ `);if(u.length>0&&u[u.length-1]===""&&u.pop(),u.length===0)return{stdout:"",stderr:"",exitCode:0};let f=[],d=u[0],h=1,p=(g,b)=>a?g.toLowerCase()===b.toLowerCase():g===b;for(let g=1;g<u.length;g++)p(u[g],d)?h++:(f.push({line:d,count:h}),d=u[g],h=1);f.push({line:d,count:h});let E=f;s?E=f.filter(g=>g.count>1):i&&(E=f.filter(g=>g.count===1));let w="";for(let{line:g,count:b}of E)n?w+=`${String(b).padStart(4)} ${g}
264
264
  `:w+=`${g}
265
- `;return{stdout:w,stderr:"",exitCode:0}}}});var Di={};O(Di,{cutCommand:()=>Du});function Pu(t){let e=[],r=t.split(",");for(let n of r)if(n.includes("-")){let[s,i]=n.split("-");e.push({start:s?parseInt(s,10):1,end:i?parseInt(i,10):null})}else{let s=parseInt(n,10);e.push({start:s,end:s})}return e}function Ou(t,e){let r=[];for(let n of e){let s=n.start-1,i=n.end===null?t.length:n.end;for(let a=s;a<i&&a<t.length;a++)a>=0&&!r.includes(t[a])&&r.push(t[a])}return r}var $u,Du,Li=N(()=>{"use strict";Ze();L();$u={name:"cut",summary:"remove sections from each line of files",usage:"cut [OPTION]... [FILE]...",options:["-c LIST select only these characters","-d DELIM use DELIM instead of TAB for field delimiter","-f LIST select only these fields","-s, --only-delimited do not print lines without delimiters"," --help display this help and exit"]};Du={name:"cut",async execute(t,e){if(C(t))return A($u);let r=" ",n=null,s=null,i=!1,a=[];for(let d=0;d<t.length;d++){let h=t[d];if(h==="-d")r=t[++d]||" ";else if(h.startsWith("-d"))r=h.slice(2);else if(h==="-f")n=t[++d];else if(h.startsWith("-f"))n=h.slice(2);else if(h==="-c")s=t[++d];else if(h.startsWith("-c"))s=h.slice(2);else if(h==="-s"||h==="--only-delimited")i=!0;else{if(h.startsWith("--"))return T("cut",h);if(h.startsWith("-")){let p=!1;for(let b of h.slice(1))if(b==="s")i=!0;else if(!"dfc".includes(b)){p=!0;break}if(p)return T("cut",h)}else a.push(h)}}if(!n&&!s)return{stdout:"",stderr:`cut: you must specify a list of bytes, characters, or fields
266
- `,exitCode:1};let o=await Be(e,a,{cmdName:"cut"});if(!o.ok)return o.error;let l=o.content.split(`
267
- `);l.length>0&&l[l.length-1]===""&&l.pop();let u=Pu(n||s||"1"),f="";for(let d of l)if(s){let h=d.split(""),p=[];for(let b of u){let w=b.start-1,g=b.end===null?h.length:b.end;for(let E=w;E<g&&E<h.length;E++)E>=0&&p.push(h[E])}f+=`${p.join("")}
268
- `}else{if(i&&!d.includes(r))continue;let h=d.split(r),p=Ou(h,u);f+=`${p.join(r)}
269
- `}return{stdout:f,stderr:"",exitCode:0}}}});var Fi={};O(Fi,{pasteCommand:()=>Fu});function Ti(t,e){if(t.length===0)return"";if(t.length===1)return t[0];let r=t[0];for(let n=1;n<t.length;n++){let s=(n-1)%e.length;r+=e[s]+t[n]}return r}var Lu,Tu,Fu,Mi=N(()=>{"use strict";ae();L();Lu={name:"paste",summary:"merge lines of files",usage:"paste [OPTION]... [FILE]...",description:["Write lines consisting of the sequentially corresponding lines from","each FILE, separated by TABs, to standard output.","","With no FILE, or when FILE is -, read standard input."],options:["-d, --delimiters=LIST reuse characters from LIST instead of TABs","-s, --serial paste one file at a time instead of in parallel"," --help display this help and exit"],examples:["paste file1 file2 Merge file1 and file2 side by side","paste -d, file1 file2 Use comma as delimiter","paste -s file1 Paste all lines of file1 on one line","paste - - < file Paste pairs of lines from file"]},Tu={delimiter:{short:"d",long:"delimiters",type:"string",default:" "},serial:{short:"s",long:"serial",type:"boolean"}},Fu={name:"paste",async execute(t,e){if(C(t))return A(Lu);let r=H("paste",t,Tu);if(!r.ok)return r.error;let n=r.result.flags.delimiter,s=r.result.flags.serial,i=r.result.positional;if(i.length===0)return{stdout:"",stderr:`usage: paste [-s] [-d delimiters] file ...
265
+ `;return{stdout:w,stderr:"",exitCode:0}}}});var Mi={};D(Mi,{cutCommand:()=>Fu});function Tu(t){let e=[],r=t.split(",");for(let n of r)if(n.includes("-")){let[s,i]=n.split("-");e.push({start:s?parseInt(s,10):1,end:i?parseInt(i,10):null})}else{let s=parseInt(n,10);e.push({start:s,end:s})}return e}function Lu(t,e){let r=[];for(let n of e){let s=n.start-1,i=n.end===null?t.length:n.end;for(let a=s;a<i&&a<t.length;a++)a>=0&&!r.includes(t[a])&&r.push(t[a])}return r}var Du,Fu,_i=v(()=>{"use strict";Ke();F();Du={name:"cut",summary:"remove sections from each line of files",usage:"cut [OPTION]... [FILE]...",options:["-c LIST select only these characters","-d DELIM use DELIM instead of TAB for field delimiter","-f LIST select only these fields","-s, --only-delimited do not print lines without delimiters"," --help display this help and exit"]};Fu={name:"cut",async execute(t,e){if(N(t))return C(Du);let r=" ",n=null,s=null,i=!1,a=[];for(let d=0;d<t.length;d++){let h=t[d];if(h==="-d")r=t[++d]||" ";else if(h.startsWith("-d"))r=h.slice(2);else if(h==="-f")n=t[++d];else if(h.startsWith("-f"))n=h.slice(2);else if(h==="-c")s=t[++d];else if(h.startsWith("-c"))s=h.slice(2);else if(h==="-s"||h==="--only-delimited")i=!0;else{if(h.startsWith("--"))return M("cut",h);if(h.startsWith("-")){let p=!1;for(let E of h.slice(1))if(E==="s")i=!0;else if(!"dfc".includes(E)){p=!0;break}if(p)return M("cut",h)}else a.push(h)}}if(!n&&!s)return{stdout:"",stderr:`cut: you must specify a list of bytes, characters, or fields
266
+ `,exitCode:1};let o=await He(e,a,{cmdName:"cut"});if(!o.ok)return o.error;let l=o.content.split(`
267
+ `);l.length>0&&l[l.length-1]===""&&l.pop();let u=Tu(n||s||"1"),f="";for(let d of l)if(s){let h=d.split(""),p=[];for(let E of u){let w=E.start-1,g=E.end===null?h.length:E.end;for(let b=w;b<g&&b<h.length;b++)b>=0&&p.push(h[b])}f+=`${p.join("")}
268
+ `}else{if(i&&!d.includes(r))continue;let h=d.split(r),p=Lu(h,u);f+=`${p.join(r)}
269
+ `}return{stdout:f,stderr:"",exitCode:0}}}});var Bi={};D(Bi,{pasteCommand:()=>Wu});function Wi(t,e){if(t.length===0)return"";if(t.length===1)return t[0];let r=t[0];for(let n=1;n<t.length;n++){let s=(n-1)%e.length;r+=e[s]+t[n]}return r}var Mu,_u,Wu,Hi=v(()=>{"use strict";oe();F();Mu={name:"paste",summary:"merge lines of files",usage:"paste [OPTION]... [FILE]...",description:["Write lines consisting of the sequentially corresponding lines from","each FILE, separated by TABs, to standard output.","","With no FILE, or when FILE is -, read standard input."],options:["-d, --delimiters=LIST reuse characters from LIST instead of TABs","-s, --serial paste one file at a time instead of in parallel"," --help display this help and exit"],examples:["paste file1 file2 Merge file1 and file2 side by side","paste -d, file1 file2 Use comma as delimiter","paste -s file1 Paste all lines of file1 on one line","paste - - < file Paste pairs of lines from file"]},_u={delimiter:{short:"d",long:"delimiters",type:"string",default:" "},serial:{short:"s",long:"serial",type:"boolean"}},Wu={name:"paste",async execute(t,e){if(N(t))return C(Mu);let r=G("paste",t,_u);if(!r.ok)return r.error;let n=r.result.flags.delimiter,s=r.result.flags.serial,i=r.result.positional;if(i.length===0)return{stdout:"",stderr:`usage: paste [-s] [-d delimiters] file ...
270
270
  `,exitCode:1};let a=e.stdin?e.stdin.split(`
271
271
  `):[""];a.length>0&&a[a.length-1]===""&&a.pop();let o=i.filter(f=>f==="-").length,c=[],l=0;for(let f of i)if(f==="-"){let d=[];for(let h=l;h<a.length;h+=o)d.push(a[h]);c.push(d),l++}else{let d=e.fs.resolvePath(e.cwd,f);try{let p=(await e.fs.readFile(d)).split(`
272
272
  `);p.length>0&&p[p.length-1]===""&&p.pop(),c.push(p)}catch{return{stdout:"",stderr:`paste: ${f}: No such file or directory
273
- `,exitCode:1}}}let u="";if(s)for(let f of c)f&&(u+=`${Ti(f,n)}
274
- `);else{let f=Math.max(...c.map(d=>d?.length??0));for(let d=0;d<f;d++){let h=[];for(let p of c)h.push(p?.[d]??"");u+=`${Ti(h,n)}
275
- `}}return{stdout:u,stderr:"",exitCode:0}}}});var Wi={};O(Wi,{trCommand:()=>Bu});function _i(t){let e="",r=0;for(;r<t.length;){if(t[r]==="["&&t[r+1]===":"){let n=!1;for(let[s,i]of Object.entries(_u))if(t.slice(r).startsWith(s)){e+=i,r+=s.length,n=!0;break}if(n)continue}if(t[r]==="\\"&&r+1<t.length){let n=t[r+1];n==="n"?e+=`
276
- `:n==="t"?e+=" ":n==="r"?e+="\r":e+=n,r+=2;continue}if(r+2<t.length&&t[r+1]==="-"){let n=t.charCodeAt(r),s=t.charCodeAt(r+2);for(let i=n;i<=s;i++)e+=String.fromCharCode(i);r+=3;continue}e+=t[r],r++}return e}var Mu,_u,Wu,Bu,Bi=N(()=>{"use strict";ae();L();Mu={name:"tr",summary:"translate or delete characters",usage:"tr [OPTION]... SET1 [SET2]",options:["-c, -C, --complement use the complement of SET1","-d, --delete delete characters in SET1","-s, --squeeze-repeats squeeze repeated characters"," --help display this help and exit"],description:`SET syntax:
273
+ `,exitCode:1}}}let u="";if(s)for(let f of c)f&&(u+=`${Wi(f,n)}
274
+ `);else{let f=Math.max(...c.map(d=>d?.length??0));for(let d=0;d<f;d++){let h=[];for(let p of c)h.push(p?.[d]??"");u+=`${Wi(h,n)}
275
+ `}}return{stdout:u,stderr:"",exitCode:0}}}});var zi={};D(zi,{trCommand:()=>zu});function Ui(t){let e="",r=0;for(;r<t.length;){if(t[r]==="["&&t[r+1]===":"){let n=!1;for(let[s,i]of Object.entries(Hu))if(t.slice(r).startsWith(s)){e+=i,r+=s.length,n=!0;break}if(n)continue}if(t[r]==="\\"&&r+1<t.length){let n=t[r+1];n==="n"?e+=`
276
+ `:n==="t"?e+=" ":n==="r"?e+="\r":e+=n,r+=2;continue}if(r+2<t.length&&t[r+1]==="-"){let n=t.charCodeAt(r),s=t.charCodeAt(r+2);for(let i=n;i<=s;i++)e+=String.fromCharCode(i);r+=3;continue}e+=t[r],r++}return e}var Bu,Hu,Uu,zu,Gi=v(()=>{"use strict";oe();F();Bu={name:"tr",summary:"translate or delete characters",usage:"tr [OPTION]... SET1 [SET2]",options:["-c, -C, --complement use the complement of SET1","-d, --delete delete characters in SET1","-s, --squeeze-repeats squeeze repeated characters"," --help display this help and exit"],description:`SET syntax:
277
277
  a-z character range
278
278
  [:alnum:] all letters and digits
279
279
  [:alpha:] all letters
@@ -287,120 +287,120 @@ Examples:
287
287
  [:graph:] all printable characters except space
288
288
  [:cntrl:] all control characters
289
289
  [:xdigit:] all hexadecimal digits
290
- \\n, \\t, \\r escape sequences`},_u={"[:alnum:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789","[:alpha:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz","[:blank:]":" ","[:cntrl:]":Array.from({length:32},(t,e)=>String.fromCharCode(e)).join("").concat("\x7F"),"[:digit:]":"0123456789","[:graph:]":Array.from({length:94},(t,e)=>String.fromCharCode(33+e)).join(""),"[:lower:]":"abcdefghijklmnopqrstuvwxyz","[:print:]":Array.from({length:95},(t,e)=>String.fromCharCode(32+e)).join(""),"[:punct:]":"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~","[:space:]":`
291
- \r\f\v`,"[:upper:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","[:xdigit:]":"0123456789ABCDEFabcdef"};Wu={complement:{short:"c",long:"complement",type:"boolean"},complementUpper:{short:"C",type:"boolean"},delete:{short:"d",long:"delete",type:"boolean"},squeeze:{short:"s",long:"squeeze-repeats",type:"boolean"}},Bu={name:"tr",async execute(t,e){if(C(t))return A(Mu);let r=H("tr",t,Wu);if(!r.ok)return r.error;let n=r.result.flags.complement||r.result.flags.complementUpper,s=r.result.flags.delete,i=r.result.flags.squeeze,a=r.result.positional;if(a.length<1)return{stdout:"",stderr:`tr: missing operand
290
+ \\n, \\t, \\r escape sequences`},Hu={"[:alnum:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789","[:alpha:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz","[:blank:]":" ","[:cntrl:]":Array.from({length:32},(t,e)=>String.fromCharCode(e)).join("").concat("\x7F"),"[:digit:]":"0123456789","[:graph:]":Array.from({length:94},(t,e)=>String.fromCharCode(33+e)).join(""),"[:lower:]":"abcdefghijklmnopqrstuvwxyz","[:print:]":Array.from({length:95},(t,e)=>String.fromCharCode(32+e)).join(""),"[:punct:]":"!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~","[:space:]":`
291
+ \r\f\v`,"[:upper:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","[:xdigit:]":"0123456789ABCDEFabcdef"};Uu={complement:{short:"c",long:"complement",type:"boolean"},complementUpper:{short:"C",type:"boolean"},delete:{short:"d",long:"delete",type:"boolean"},squeeze:{short:"s",long:"squeeze-repeats",type:"boolean"}},zu={name:"tr",async execute(t,e){if(N(t))return C(Bu);let r=G("tr",t,Uu);if(!r.ok)return r.error;let n=r.result.flags.complement||r.result.flags.complementUpper,s=r.result.flags.delete,i=r.result.flags.squeeze,a=r.result.positional;if(a.length<1)return{stdout:"",stderr:`tr: missing operand
292
292
  `,exitCode:1};if(!s&&!i&&a.length<2)return{stdout:"",stderr:`tr: missing operand after SET1
293
- `,exitCode:1};let o=_i(a[0]),c=a.length>1?_i(a[1]):"",l=e.stdin,u=d=>{let h=o.includes(d);return n?!h:h},f="";if(s)for(let d of l)u(d)||(f+=d);else if(i&&a.length===1){let d="";for(let h of l)u(h)&&h===d||(f+=h,d=h)}else{if(n){let d=c.length>0?c[c.length-1]:"";for(let h of l)o.includes(h)?f+=h:f+=d}else{let d=new Map;for(let h=0;h<o.length;h++){let p=h<c.length?c[h]:c[c.length-1];d.set(o[h],p)}for(let h of l)f+=d.get(h)??h}if(i){let d="",h="";for(let p of f)c.includes(p)&&p===h||(d+=p,h=p);f=d}}return{stdout:f,stderr:"",exitCode:0}}}});var Hi={};O(Hi,{teeCommand:()=>zu});var Hu,Uu,zu,Ui=N(()=>{"use strict";ae();L();Hu={name:"tee",summary:"read from stdin and write to stdout and files",usage:"tee [OPTION]... [FILE]...",options:["-a, --append append to the given FILEs, do not overwrite"," --help display this help and exit"]},Uu={append:{short:"a",long:"append",type:"boolean"}},zu={name:"tee",async execute(t,e){if(C(t))return A(Hu);let r=H("tee",t,Uu);if(!r.ok)return r.error;let{append:n}=r.result.flags,s=r.result.positional,i=e.stdin,a="",o=0;for(let c of s)try{let l=e.fs.resolvePath(e.cwd,c);n?await e.fs.appendFile(l,i):await e.fs.writeFile(l,i)}catch{a+=`tee: ${c}: No such file or directory
294
- `,o=1}return{stdout:i,stderr:a,exitCode:o}}}});function Je(t,e){switch(t.type){case"name":return{matches:be(e.name,t.pattern,t.ignoreCase),pruned:!1,printed:!1};case"path":return{matches:be(e.relativePath,t.pattern,t.ignoreCase),pruned:!1,printed:!1};case"regex":try{let r=t.ignoreCase?"i":"";return{matches:new RegExp(t.pattern,r).test(e.relativePath),pruned:!1,printed:!1}}catch{return{matches:!1,pruned:!1,printed:!1}}case"type":return t.fileType==="f"?{matches:e.isFile,pruned:!1,printed:!1}:t.fileType==="d"?{matches:e.isDirectory,pruned:!1,printed:!1}:{matches:!1,pruned:!1,printed:!1};case"empty":return{matches:e.isEmpty,pruned:!1,printed:!1};case"mtime":{let n=(Date.now()-e.mtime)/(1e3*60*60*24),s;return t.comparison==="more"?s=n>t.days:t.comparison==="less"?s=n<t.days:s=Math.floor(n)===t.days,{matches:s,pruned:!1,printed:!1}}case"newer":{let r=e.newerRefTimes.get(t.refPath);return r===void 0?{matches:!1,pruned:!1,printed:!1}:{matches:e.mtime>r,pruned:!1,printed:!1}}case"size":{let r=t.value;switch(t.unit){case"c":r=t.value;break;case"k":r=t.value*1024;break;case"M":r=t.value*1024*1024;break;case"G":r=t.value*1024*1024*1024;break;case"b":r=t.value*512;break}let n;return t.comparison==="more"?n=e.size>r:t.comparison==="less"?n=e.size<r:t.unit==="b"?n=Math.ceil(e.size/512)===t.value:n=e.size===r,{matches:n,pruned:!1,printed:!1}}case"perm":{let r=e.mode&511,n=t.mode&511,s;return t.matchType==="exact"?s=r===n:t.matchType==="all"?s=(r&n)===n:s=(r&n)!==0,{matches:s,pruned:!1,printed:!1}}case"prune":return{matches:!0,pruned:!0,printed:!1};case"print":return{matches:!0,pruned:!1,printed:!0};case"not":{let r=Je(t.expr,e);return{matches:!r.matches,pruned:r.pruned,printed:!1}}case"and":{let r=Je(t.left,e);if(!r.matches)return{matches:!1,pruned:r.pruned,printed:!1};let n=Je(t.right,e);return{matches:n.matches,pruned:r.pruned||n.pruned,printed:r.printed||n.printed}}case"or":{let r=Je(t.left,e);if(r.matches)return r;let n=Je(t.right,e);return{matches:n.matches,pruned:r.pruned||n.pruned,printed:n.printed}}}}function zi(t){let e=[],r=n=>{n&&(n.type==="newer"?e.push(n.refPath):n.type==="not"?r(n.expr):(n.type==="and"||n.type==="or")&&(r(n.left),r(n.right)))};return r(t),e}var Gi=N(()=>{"use strict";Or()});function ji(t,e){let r=[],n=[],s=e;for(;s<t.length;){let a=t[s];if(a==="("||a==="\\("){r.push({type:"lparen"}),s++;continue}if(a===")"||a==="\\)"){r.push({type:"rparen"}),s++;continue}if(a==="-name"&&s+1<t.length)r.push({type:"expr",expr:{type:"name",pattern:t[++s]}});else if(a==="-iname"&&s+1<t.length)r.push({type:"expr",expr:{type:"name",pattern:t[++s],ignoreCase:!0}});else if(a==="-path"&&s+1<t.length)r.push({type:"expr",expr:{type:"path",pattern:t[++s]}});else if(a==="-ipath"&&s+1<t.length)r.push({type:"expr",expr:{type:"path",pattern:t[++s],ignoreCase:!0}});else if(a==="-regex"&&s+1<t.length)r.push({type:"expr",expr:{type:"regex",pattern:t[++s]}});else if(a==="-iregex"&&s+1<t.length)r.push({type:"expr",expr:{type:"regex",pattern:t[++s],ignoreCase:!0}});else if(a==="-type"&&s+1<t.length){let o=t[++s];if(o==="f"||o==="d")r.push({type:"expr",expr:{type:"type",fileType:o}});else return{expr:null,pathIndex:s,error:`find: Unknown argument to -type: ${o}
295
- `,actions:[]}}else if(a==="-empty")r.push({type:"expr",expr:{type:"empty"}});else if(a==="-mtime"&&s+1<t.length){let o=t[++s],c="exact",l=o;o.startsWith("+")?(c="more",l=o.slice(1)):o.startsWith("-")&&(c="less",l=o.slice(1));let u=parseInt(l,10);Number.isNaN(u)||r.push({type:"expr",expr:{type:"mtime",days:u,comparison:c}})}else if(a==="-newer"&&s+1<t.length){let o=t[++s];r.push({type:"expr",expr:{type:"newer",refPath:o}})}else if(a==="-size"&&s+1<t.length){let o=t[++s],c="exact",l=o;o.startsWith("+")?(c="more",l=o.slice(1)):o.startsWith("-")&&(c="less",l=o.slice(1));let u=l.match(/^(\d+)([ckMGb])?$/);if(u){let f=parseInt(u[1],10),d=u[2]||"b";r.push({type:"expr",expr:{type:"size",value:f,unit:d,comparison:c}})}}else if(a==="-perm"&&s+1<t.length){let o=t[++s],c="exact",l=o;o.startsWith("-")?(c="all",l=o.slice(1)):o.startsWith("/")&&(c="any",l=o.slice(1));let u=parseInt(l,8);Number.isNaN(u)||r.push({type:"expr",expr:{type:"perm",mode:u,matchType:c}})}else if(a==="-prune")r.push({type:"expr",expr:{type:"prune"}});else if(a==="-not"||a==="!")r.push({type:"not"});else if(a==="-o"||a==="-or")r.push({type:"op",op:"or"});else if(a==="-a"||a==="-and")r.push({type:"op",op:"and"});else if(a==="-maxdepth"||a==="-mindepth")s++;else if(a==="-exec"){let o=[];for(s++;s<t.length&&t[s]!==";"&&t[s]!=="+";)o.push(t[s]),s++;if(s>=t.length)return{expr:null,pathIndex:s,error:"find: missing argument to `-exec'\n",actions:[]};let c=t[s]==="+";n.push({type:"exec",command:o,batchMode:c})}else if(a==="-print")r.push({type:"expr",expr:{type:"print"}}),n.push({type:"print"});else if(a==="-print0")n.push({type:"print0"});else if(a==="-delete")n.push({type:"delete"});else{if(a.startsWith("-"))return{expr:null,pathIndex:s,error:`find: unknown predicate '${a}'
296
- `,actions:[]};if(r.length===0){s++;continue}break}s++}if(r.length===0)return{expr:null,pathIndex:s,actions:n};let i=Gu(r);return i.error?{expr:null,pathIndex:s,error:i.error,actions:n}:{expr:i.expr,pathIndex:s,actions:n}}function Gu(t){let e=0;function r(){let o=n();if(!o)return null;for(;e<t.length;){let c=t[e];if(c.type==="op"&&c.op==="or"){e++;let l=n();if(!l)return o;o={type:"or",left:o,right:l}}else break}return o}function n(){let o=s();if(!o)return null;for(;e<t.length;){let c=t[e];if(c.type==="op"&&c.op==="and"){e++;let l=s();if(!l)return o;o={type:"and",left:o,right:l}}else if(c.type==="expr"||c.type==="not"||c.type==="lparen"){let l=s();if(!l)return o;o={type:"and",left:o,right:l}}else break}return o}function s(){if(e<t.length&&t[e].type==="not"){e++;let o=s();return o?{type:"not",expr:o}:null}return i()}function i(){if(e>=t.length)return null;let o=t[e];if(o.type==="lparen"){e++;let c=r();return e<t.length&&t[e].type==="rparen"&&e++,c}return o.type==="expr"?(e++,o.expr):(o.type==="rparen",null)}return{expr:r()}}var qi=N(()=>{"use strict"});var Vi={};O(Vi,{findCommand:()=>Vu});var ju,qu,Vu,Zi=N(()=>{"use strict";L();Gi();qi();ju={name:"find",summary:"search for files in a directory hierarchy",usage:"find [path...] [expression]",options:["-name PATTERN file name matches shell pattern PATTERN","-iname PATTERN like -name but case insensitive","-path PATTERN file path matches shell pattern PATTERN","-ipath PATTERN like -path but case insensitive","-regex PATTERN file path matches regular expression PATTERN","-iregex PATTERN like -regex but case insensitive","-type TYPE file is of type: f (regular file), d (directory)","-empty file is empty or directory is empty","-mtime N file's data was modified N*24 hours ago","-newer FILE file was modified more recently than FILE","-size N[ckMGb] file uses N units of space (c=bytes, k=KB, M=MB, G=GB, b=512B blocks)","-perm MODE file's permission bits are exactly MODE (octal)","-perm -MODE all permission bits MODE are set","-perm /MODE any permission bits MODE are set","-maxdepth LEVELS descend at most LEVELS directories","-mindepth LEVELS do not apply tests at levels less than LEVELS","-prune do not descend into this directory","-not, ! negate the following expression","-a, -and logical AND (default)","-o, -or logical OR","-exec CMD {} ; execute CMD on each file ({} is replaced by filename)","-exec CMD {} + execute CMD with multiple files at once","-print print the full file name (default action)","-print0 print the full file name followed by a null character","-delete delete found files/directories"," --help display this help and exit"]},qu=new Set(["-name","-iname","-path","-ipath","-regex","-iregex","-type","-maxdepth","-mindepth","-mtime","-newer","-size","-perm"]),Vu={name:"find",async execute(t,e){if(C(t))return A(ju);let r=".",n=null,s=null;for(let E=0;E<t.length;E++){let x=t[E];if(x==="-maxdepth"&&E+1<t.length)n=parseInt(t[++E],10);else if(x==="-mindepth"&&E+1<t.length)s=parseInt(t[++E],10);else if(x==="-exec")for(E++;E<t.length&&t[E]!==";"&&t[E]!=="+";)E++;else!x.startsWith("-")&&x!==";"&&x!=="+"&&x!=="("&&x!==")"&&x!=="\\("&&x!=="\\)"?r=x:qu.has(x)&&E++}let{expr:i,error:a,actions:o}=ji(t,0);if(a)return{stdout:"",stderr:a,exitCode:1};let c=o.some(E=>E.type==="print"),l=o.length===0,u=e.fs.resolvePath(e.cwd,r);try{await e.fs.stat(u)}catch{return{stdout:"",stderr:`find: ${r}: No such file or directory
297
- `,exitCode:1}}let f=[],d=zi(i),h=new Map;for(let E of d){let x=e.fs.resolvePath(e.cwd,E);try{let S=await e.fs.stat(x);h.set(E,S.mtime?.getTime()??Date.now())}catch{}}async function p(E,x){if(n!==null&&x>n)return;let S;try{S=await e.fs.stat(E)}catch{return}if(!S)return;let v;E===u?v=r.split("/").pop()||r:v=E.split("/").pop()||"";let R=E===u?r:r==="."?`./${E.slice(u.length+1)}`:r+E.slice(u.length),M=null;S.isDirectory&&(M=await e.fs.readdir(E));let _=S.isFile?S.size===0:M!==null&&M.length===0,K=s===null||x>=s,Ee=!1,ne=!1;if(K&&i!==null){let de={name:v,relativePath:R,isFile:S.isFile,isDirectory:S.isDirectory,isEmpty:_,mtime:S.mtime?.getTime()??Date.now(),size:S.size??0,mode:S.mode??420,newerRefTimes:h},oe=Je(i,de);K=oe.matches,Ee=oe.pruned,c?ne=oe.printed:ne=K}else K&&(ne=!0);if(ne&&f.push(R),M!==null&&!Ee)for(let de of M){let oe=E==="/"?`/${de}`:`${E}/${de}`;await p(oe,x+1)}}await p(u,0);let b="",w="",g=0;if(o.length>0)for(let E of o)switch(E.type){case"print":b+=f.length>0?`${f.join(`
293
+ `,exitCode:1};let o=Ui(a[0]),c=a.length>1?Ui(a[1]):"",l=e.stdin,u=d=>{let h=o.includes(d);return n?!h:h},f="";if(s)for(let d of l)u(d)||(f+=d);else if(i&&a.length===1){let d="";for(let h of l)u(h)&&h===d||(f+=h,d=h)}else{if(n){let d=c.length>0?c[c.length-1]:"";for(let h of l)o.includes(h)?f+=h:f+=d}else{let d=new Map;for(let h=0;h<o.length;h++){let p=h<c.length?c[h]:c[c.length-1];d.set(o[h],p)}for(let h of l)f+=d.get(h)??h}if(i){let d="",h="";for(let p of f)c.includes(p)&&p===h||(d+=p,h=p);f=d}}return{stdout:f,stderr:"",exitCode:0}}}});var ji={};D(ji,{teeCommand:()=>qu});var Gu,ju,qu,qi=v(()=>{"use strict";oe();F();Gu={name:"tee",summary:"read from stdin and write to stdout and files",usage:"tee [OPTION]... [FILE]...",options:["-a, --append append to the given FILEs, do not overwrite"," --help display this help and exit"]},ju={append:{short:"a",long:"append",type:"boolean"}},qu={name:"tee",async execute(t,e){if(N(t))return C(Gu);let r=G("tee",t,ju);if(!r.ok)return r.error;let{append:n}=r.result.flags,s=r.result.positional,i=e.stdin,a="",o=0;for(let c of s)try{let l=e.fs.resolvePath(e.cwd,c);n?await e.fs.appendFile(l,i):await e.fs.writeFile(l,i)}catch{a+=`tee: ${c}: No such file or directory
294
+ `,o=1}return{stdout:i,stderr:a,exitCode:o}}}});function ze(t,e){switch(t.type){case"name":return{matches:xe(e.name,t.pattern,t.ignoreCase),pruned:!1,printed:!1};case"path":return{matches:xe(e.relativePath,t.pattern,t.ignoreCase),pruned:!1,printed:!1};case"regex":try{let r=t.ignoreCase?"i":"";return{matches:new RegExp(t.pattern,r).test(e.relativePath),pruned:!1,printed:!1}}catch{return{matches:!1,pruned:!1,printed:!1}}case"type":return t.fileType==="f"?{matches:e.isFile,pruned:!1,printed:!1}:t.fileType==="d"?{matches:e.isDirectory,pruned:!1,printed:!1}:{matches:!1,pruned:!1,printed:!1};case"empty":return{matches:e.isEmpty,pruned:!1,printed:!1};case"mtime":{let n=(Date.now()-e.mtime)/(1e3*60*60*24),s;return t.comparison==="more"?s=n>t.days:t.comparison==="less"?s=n<t.days:s=Math.floor(n)===t.days,{matches:s,pruned:!1,printed:!1}}case"newer":{let r=e.newerRefTimes.get(t.refPath);return r===void 0?{matches:!1,pruned:!1,printed:!1}:{matches:e.mtime>r,pruned:!1,printed:!1}}case"size":{let r=t.value;switch(t.unit){case"c":r=t.value;break;case"k":r=t.value*1024;break;case"M":r=t.value*1024*1024;break;case"G":r=t.value*1024*1024*1024;break;case"b":r=t.value*512;break}let n;return t.comparison==="more"?n=e.size>r:t.comparison==="less"?n=e.size<r:t.unit==="b"?n=Math.ceil(e.size/512)===t.value:n=e.size===r,{matches:n,pruned:!1,printed:!1}}case"perm":{let r=e.mode&511,n=t.mode&511,s;return t.matchType==="exact"?s=r===n:t.matchType==="all"?s=(r&n)===n:s=(r&n)!==0,{matches:s,pruned:!1,printed:!1}}case"prune":return{matches:!0,pruned:!0,printed:!1};case"print":return{matches:!0,pruned:!1,printed:!0};case"not":{let r=ze(t.expr,e);return{matches:!r.matches,pruned:r.pruned,printed:!1}}case"and":{let r=ze(t.left,e);if(!r.matches)return{matches:!1,pruned:r.pruned,printed:!1};let n=ze(t.right,e);return{matches:n.matches,pruned:r.pruned||n.pruned,printed:r.printed||n.printed}}case"or":{let r=ze(t.left,e);if(r.matches)return r;let n=ze(t.right,e);return{matches:n.matches,pruned:r.pruned||n.pruned,printed:n.printed}}}}function Vi(t){let e=[],r=n=>{n&&(n.type==="newer"?e.push(n.refPath):n.type==="not"?r(n.expr):(n.type==="and"||n.type==="or")&&(r(n.left),r(n.right)))};return r(t),e}var Zi=v(()=>{"use strict";Lr()});function Qi(t,e){let r=[],n=[],s=e;for(;s<t.length;){let a=t[s];if(a==="("||a==="\\("){r.push({type:"lparen"}),s++;continue}if(a===")"||a==="\\)"){r.push({type:"rparen"}),s++;continue}if(a==="-name"&&s+1<t.length)r.push({type:"expr",expr:{type:"name",pattern:t[++s]}});else if(a==="-iname"&&s+1<t.length)r.push({type:"expr",expr:{type:"name",pattern:t[++s],ignoreCase:!0}});else if(a==="-path"&&s+1<t.length)r.push({type:"expr",expr:{type:"path",pattern:t[++s]}});else if(a==="-ipath"&&s+1<t.length)r.push({type:"expr",expr:{type:"path",pattern:t[++s],ignoreCase:!0}});else if(a==="-regex"&&s+1<t.length)r.push({type:"expr",expr:{type:"regex",pattern:t[++s]}});else if(a==="-iregex"&&s+1<t.length)r.push({type:"expr",expr:{type:"regex",pattern:t[++s],ignoreCase:!0}});else if(a==="-type"&&s+1<t.length){let o=t[++s];if(o==="f"||o==="d")r.push({type:"expr",expr:{type:"type",fileType:o}});else return{expr:null,pathIndex:s,error:`find: Unknown argument to -type: ${o}
295
+ `,actions:[]}}else if(a==="-empty")r.push({type:"expr",expr:{type:"empty"}});else if(a==="-mtime"&&s+1<t.length){let o=t[++s],c="exact",l=o;o.startsWith("+")?(c="more",l=o.slice(1)):o.startsWith("-")&&(c="less",l=o.slice(1));let u=parseInt(l,10);Number.isNaN(u)||r.push({type:"expr",expr:{type:"mtime",days:u,comparison:c}})}else if(a==="-newer"&&s+1<t.length){let o=t[++s];r.push({type:"expr",expr:{type:"newer",refPath:o}})}else if(a==="-size"&&s+1<t.length){let o=t[++s],c="exact",l=o;o.startsWith("+")?(c="more",l=o.slice(1)):o.startsWith("-")&&(c="less",l=o.slice(1));let u=l.match(/^(\d+)([ckMGb])?$/);if(u){let f=parseInt(u[1],10),d=u[2]||"b";r.push({type:"expr",expr:{type:"size",value:f,unit:d,comparison:c}})}}else if(a==="-perm"&&s+1<t.length){let o=t[++s],c="exact",l=o;o.startsWith("-")?(c="all",l=o.slice(1)):o.startsWith("/")&&(c="any",l=o.slice(1));let u=parseInt(l,8);Number.isNaN(u)||r.push({type:"expr",expr:{type:"perm",mode:u,matchType:c}})}else if(a==="-prune")r.push({type:"expr",expr:{type:"prune"}});else if(a==="-not"||a==="!")r.push({type:"not"});else if(a==="-o"||a==="-or")r.push({type:"op",op:"or"});else if(a==="-a"||a==="-and")r.push({type:"op",op:"and"});else if(a==="-maxdepth"||a==="-mindepth")s++;else if(a!=="-depth")if(a==="-exec"){let o=[];for(s++;s<t.length&&t[s]!==";"&&t[s]!=="+";)o.push(t[s]),s++;if(s>=t.length)return{expr:null,pathIndex:s,error:"find: missing argument to `-exec'\n",actions:[]};let c=t[s]==="+";n.push({type:"exec",command:o,batchMode:c})}else if(a==="-print")r.push({type:"expr",expr:{type:"print"}}),n.push({type:"print"});else if(a==="-print0")n.push({type:"print0"});else if(a==="-printf"&&s+1<t.length){let o=t[++s];n.push({type:"printf",format:o})}else if(a==="-delete")n.push({type:"delete"});else{if(a.startsWith("-"))return{expr:null,pathIndex:s,error:`find: unknown predicate '${a}'
296
+ `,actions:[]};if(r.length===0){s++;continue}break}s++}if(r.length===0)return{expr:null,pathIndex:s,actions:n};let i=Vu(r);return i.error?{expr:null,pathIndex:s,error:i.error,actions:n}:{expr:i.expr,pathIndex:s,actions:n}}function Vu(t){let e=0;function r(){let o=n();if(!o)return null;for(;e<t.length;){let c=t[e];if(c.type==="op"&&c.op==="or"){e++;let l=n();if(!l)return o;o={type:"or",left:o,right:l}}else break}return o}function n(){let o=s();if(!o)return null;for(;e<t.length;){let c=t[e];if(c.type==="op"&&c.op==="and"){e++;let l=s();if(!l)return o;o={type:"and",left:o,right:l}}else if(c.type==="expr"||c.type==="not"||c.type==="lparen"){let l=s();if(!l)return o;o={type:"and",left:o,right:l}}else break}return o}function s(){if(e<t.length&&t[e].type==="not"){e++;let o=s();return o?{type:"not",expr:o}:null}return i()}function i(){if(e>=t.length)return null;let o=t[e];if(o.type==="lparen"){e++;let c=r();return e<t.length&&t[e].type==="rparen"&&e++,c}return o.type==="expr"?(e++,o.expr):(o.type==="rparen",null)}return{expr:r()}}var Ki=v(()=>{"use strict"});var Xi={};D(Xi,{findCommand:()=>Ku});function Xu(t,e){let r=Wt(t),n="",s=0;for(;s<r.length;)if(r[s]==="%"&&s+1<r.length){if(s++,r[s]==="%"){n+="%",s++;continue}let[i,a,o]=us(r,s);if(s+=o,s>=r.length){n+="%";break}let c=r[s],l;switch(c){case"f":l=e.name,s++;break;case"h":{let u=e.path.lastIndexOf("/");l=u>0?e.path.slice(0,u):".",s++;break}case"p":l=e.path,s++;break;case"P":{let u=e.startingPoint;e.path===u?l="":e.path.startsWith(`${u}/`)?l=e.path.slice(u.length+1):u==="."&&e.path.startsWith("./")?l=e.path.slice(2):l=e.path,s++;break}case"s":l=String(e.size),s++;break;case"d":l=String(e.depth),s++;break;case"m":l=(e.mode&511).toString(8),s++;break;case"M":l=Yu(e.mode,e.isDirectory),s++;break;case"t":{let u=new Date(e.mtime);l=Ju(u),s++;break}case"T":{if(s+1<r.length){let u=r[s+1],f=new Date(e.mtime);l=ef(f,u),s+=2}else l="%T",s++;break}default:n+=`%${i!==0||a!==-1?`${i}.${a}`:""}${c}`,s++;continue}n+=_t(l,i,a)}else n+=r[s],s++;return n}function Yu(t,e){let r=t&511,n=e?"d":"-";return n+=r&256?"r":"-",n+=r&128?"w":"-",n+=r&64?"x":"-",n+=r&32?"r":"-",n+=r&16?"w":"-",n+=r&8?"x":"-",n+=r&4?"r":"-",n+=r&2?"w":"-",n+=r&1?"x":"-",n}function Ju(t){let e=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],r=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],n=e[t.getDay()],s=r[t.getMonth()],i=String(t.getDate()).padStart(2," "),a=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),c=String(t.getSeconds()).padStart(2,"0"),l=t.getFullYear();return`${n} ${s} ${i} ${a}:${o}:${c} ${l}`}function ef(t,e){switch(e){case"@":return String(t.getTime()/1e3);case"Y":return String(t.getFullYear());case"m":return String(t.getMonth()+1).padStart(2,"0");case"d":return String(t.getDate()).padStart(2,"0");case"H":return String(t.getHours()).padStart(2,"0");case"M":return String(t.getMinutes()).padStart(2,"0");case"S":return String(t.getSeconds()).padStart(2,"0");case"T":return`${String(t.getHours()).padStart(2,"0")}:${String(t.getMinutes()).padStart(2,"0")}:${String(t.getSeconds()).padStart(2,"0")}`;case"F":return`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,"0")}-${String(t.getDate()).padStart(2,"0")}`;default:return`%T${e}`}}var Zu,Qu,Ku,Yi=v(()=>{"use strict";F();Or();Zi();Ki();Zu={name:"find",summary:"search for files in a directory hierarchy",usage:"find [path...] [expression]",options:["-name PATTERN file name matches shell pattern PATTERN","-iname PATTERN like -name but case insensitive","-path PATTERN file path matches shell pattern PATTERN","-ipath PATTERN like -path but case insensitive","-regex PATTERN file path matches regular expression PATTERN","-iregex PATTERN like -regex but case insensitive","-type TYPE file is of type: f (regular file), d (directory)","-empty file is empty or directory is empty","-mtime N file's data was modified N*24 hours ago","-newer FILE file was modified more recently than FILE","-size N[ckMGb] file uses N units of space (c=bytes, k=KB, M=MB, G=GB, b=512B blocks)","-perm MODE file's permission bits are exactly MODE (octal)","-perm -MODE all permission bits MODE are set","-perm /MODE any permission bits MODE are set","-maxdepth LEVELS descend at most LEVELS directories","-mindepth LEVELS do not apply tests at levels less than LEVELS","-depth process directory contents before directory itself","-prune do not descend into this directory","-not, ! negate the following expression","-a, -and logical AND (default)","-o, -or logical OR","-exec CMD {} ; execute CMD on each file ({} is replaced by filename)","-exec CMD {} + execute CMD with multiple files at once","-print print the full file name (default action)","-print0 print the full file name followed by a null character","-printf FORMAT print FORMAT with directives: %f %h %p %P %s %d %m %M %t","-delete delete found files/directories"," --help display this help and exit"]},Qu=new Set(["-name","-iname","-path","-ipath","-regex","-iregex","-type","-maxdepth","-mindepth","-mtime","-newer","-size","-perm"]),Ku={name:"find",async execute(t,e){if(N(t))return C(Zu);let r=[],n=null,s=null,i=!1,a=!1;for(let x=0;x<t.length;x++){let A=t[x];if(A==="-maxdepth"&&x+1<t.length)a=!0,n=parseInt(t[++x],10);else if(A==="-mindepth"&&x+1<t.length)a=!0,s=parseInt(t[++x],10);else if(A==="-depth")a=!0,i=!0;else if(A==="-exec")for(a=!0,x++;x<t.length&&t[x]!==";"&&t[x]!=="+";)x++;else!A.startsWith("-")&&A!==";"&&A!=="+"&&A!=="("&&A!==")"&&A!=="\\("&&A!=="\\)"&&A!=="!"?a||r.push(A):Qu.has(A)?(a=!0,x++):(A.startsWith("-")||A==="("||A==="\\("||A==="!")&&(a=!0)}r.length===0&&r.push(".");let{expr:o,error:c,actions:l}=Qi(t,0);if(c)return{stdout:"",stderr:c,exitCode:1};let u=l.some(x=>x.type==="print"),f=l.length===0,d=[],h=l.some(x=>x.type==="printf"),p=[],E="",w=0,g=Vi(o),b=new Map;for(let x of g){let A=e.fs.resolvePath(e.cwd,x);try{let O=await e.fs.stat(A);b.set(x,O.mtime?.getTime()??Date.now())}catch{}}for(let x of r){let A=e.fs.resolvePath(e.cwd,x);try{await e.fs.stat(A)}catch{E+=`find: ${x}: No such file or directory
297
+ `,w=1;continue}async function O(L,R){if(n!==null&&R>n)return;let U;try{U=await e.fs.stat(L)}catch{return}if(!U)return;let Q;L===A?Q=x.split("/").pop()||x:Q=L.split("/").pop()||"";let pe=L===A?x:x==="."?`./${L.slice(A.length+1)}`:x+L.slice(A.length),re=null;U.isDirectory&&(re=await e.fs.readdir(L));let ge=U.isFile?U.size===0:re!==null&&re.length===0,me=()=>{let W=s===null||R>=s,ce=!1;if(W&&o!==null){let Pe={name:Q,relativePath:pe,isFile:U.isFile,isDirectory:U.isDirectory,isEmpty:ge,mtime:U.mtime?.getTime()??Date.now(),size:U.size??0,mode:U.mode??420,newerRefTimes:b},ot=ze(o,Pe);W=ot.matches,u?ce=ot.printed:ce=W}else W&&(ce=!0);ce&&(d.push(pe),h&&p.push({path:pe,name:Q,size:U.size??0,mtime:U.mtime?.getTime()??Date.now(),mode:U.mode??420,isDirectory:U.isDirectory,depth:R,startingPoint:x}))},at=async()=>{if(re!==null)for(let z of re){let W=L==="/"?`/${z}`:`${L}/${z}`;await O(W,R+1)}},Be=!1;if(!i&&o!==null){let z={name:Q,relativePath:pe,isFile:U.isFile,isDirectory:U.isDirectory,isEmpty:ge,mtime:U.mtime?.getTime()??Date.now(),size:U.size??0,mode:U.mode??420,newerRefTimes:b};Be=ze(o,z).pruned}i?(await at(),me()):(me(),Be||await at())}await O(A,0)}let S="";if(l.length>0)for(let x of l)switch(x.type){case"print":S+=d.length>0?`${d.join(`
298
298
  `)}
299
- `:"";break;case"print0":b+=f.length>0?`${f.join("\0")}\0`:"";break;case"delete":{let x=[...f].sort((S,v)=>v.length-S.length);for(let S of x){let v=e.fs.resolvePath(e.cwd,S);try{await e.fs.rm(v,{recursive:!1})}catch(R){let M=R instanceof Error?R.message:String(R);w+=`find: cannot delete '${S}': ${M}
300
- `,g=1}}break}case"exec":if(!e.exec)return{stdout:"",stderr:`find: -exec not supported in this context
301
- `,exitCode:1};if(E.batchMode){let x=[];for(let R of E.command)R==="{}"?x.push(...f):x.push(R);let S=x.map(R=>`"${R}"`).join(" "),v=await e.exec(S,{cwd:e.cwd});b+=v.stdout,w+=v.stderr,v.exitCode!==0&&(g=v.exitCode)}else for(let x of f){let v=E.command.map(M=>M==="{}"?x:M).map(M=>`"${M}"`).join(" "),R=await e.exec(v,{cwd:e.cwd});b+=R.stdout,w+=R.stderr,R.exitCode!==0&&(g=R.exitCode)}break}else l&&(b=f.length>0?`${f.join(`
299
+ `:"";break;case"print0":S+=d.length>0?`${d.join("\0")}\0`:"";break;case"delete":{let A=[...d].sort((O,L)=>L.length-O.length);for(let O of A){let L=e.fs.resolvePath(e.cwd,O);try{await e.fs.rm(L,{recursive:!1})}catch(R){let U=R instanceof Error?R.message:String(R);E+=`find: cannot delete '${O}': ${U}
300
+ `,w=1}}break}case"printf":for(let A of p)S+=Xu(x.format,A);break;case"exec":if(!e.exec)return{stdout:"",stderr:`find: -exec not supported in this context
301
+ `,exitCode:1};if(x.batchMode){let A=[];for(let R of x.command)R==="{}"?A.push(...d):A.push(R);let O=A.map(R=>`"${R}"`).join(" "),L=await e.exec(O,{cwd:e.cwd});S+=L.stdout,E+=L.stderr,L.exitCode!==0&&(w=L.exitCode)}else for(let A of d){let L=x.command.map(U=>U==="{}"?A:U).map(U=>`"${U}"`).join(" "),R=await e.exec(L,{cwd:e.cwd});S+=R.stdout,E+=R.stderr,R.exitCode!==0&&(w=R.exitCode)}break}else f&&(S=d.length>0?`${d.join(`
302
302
  `)}
303
- `:"");return{stdout:b,stderr:w,exitCode:g}}}});var Qi={};O(Qi,{basenameCommand:()=>Qu});var Zu,Qu,Ki=N(()=>{"use strict";L();Zu={name:"basename",summary:"strip directory and suffix from filenames",usage:`basename NAME [SUFFIX]
304
- basename OPTION... NAME...`,options:["-a, --multiple support multiple arguments","-s, --suffix=SUFFIX remove a trailing SUFFIX"," --help display this help and exit"]},Qu={name:"basename",async execute(t,e){if(C(t))return A(Zu);let r=!1,n="",s=[];for(let a=0;a<t.length;a++){let o=t[a];o==="-a"||o==="--multiple"?r=!0:o==="-s"&&a+1<t.length?(n=t[++a],r=!0):o.startsWith("--suffix=")?(n=o.slice(9),r=!0):o.startsWith("-")||s.push(o)}if(s.length===0)return{stdout:"",stderr:`basename: missing operand
303
+ `:"");return{stdout:S,stderr:E,exitCode:w}}}});var Ji={};D(Ji,{basenameCommand:()=>rf});var tf,rf,ea=v(()=>{"use strict";F();tf={name:"basename",summary:"strip directory and suffix from filenames",usage:`basename NAME [SUFFIX]
304
+ basename OPTION... NAME...`,options:["-a, --multiple support multiple arguments","-s, --suffix=SUFFIX remove a trailing SUFFIX"," --help display this help and exit"]},rf={name:"basename",async execute(t,e){if(N(t))return C(tf);let r=!1,n="",s=[];for(let a=0;a<t.length;a++){let o=t[a];o==="-a"||o==="--multiple"?r=!0:o==="-s"&&a+1<t.length?(n=t[++a],r=!0):o.startsWith("--suffix=")?(n=o.slice(9),r=!0):o.startsWith("-")||s.push(o)}if(s.length===0)return{stdout:"",stderr:`basename: missing operand
305
305
  `,exitCode:1};!r&&s.length>=2&&(n=s.pop()??"");let i=[];for(let a of s){let o=a.replace(/\/+$/,""),c=o.split("/").pop()||o;n&&c.endsWith(n)&&(c=c.slice(0,-n.length)),i.push(c)}return{stdout:`${i.join(`
306
306
  `)}
307
- `,stderr:"",exitCode:0}}}});var Xi={};O(Xi,{dirnameCommand:()=>Xu});var Ku,Xu,Yi=N(()=>{"use strict";L();Ku={name:"dirname",summary:"strip last component from file name",usage:"dirname [OPTION] NAME...",options:[" --help display this help and exit"]},Xu={name:"dirname",async execute(t,e){if(C(t))return A(Ku);let r=t.filter(s=>!s.startsWith("-"));if(r.length===0)return{stdout:"",stderr:`dirname: missing operand
307
+ `,stderr:"",exitCode:0}}}});var ta={};D(ta,{dirnameCommand:()=>sf});var nf,sf,ra=v(()=>{"use strict";F();nf={name:"dirname",summary:"strip last component from file name",usage:"dirname [OPTION] NAME...",options:[" --help display this help and exit"]},sf={name:"dirname",async execute(t,e){if(N(t))return C(nf);let r=t.filter(s=>!s.startsWith("-"));if(r.length===0)return{stdout:"",stderr:`dirname: missing operand
308
308
  `,exitCode:1};let n=[];for(let s of r){let i=s.replace(/\/+$/,""),a=i.lastIndexOf("/");a===-1?n.push("."):a===0?n.push("/"):n.push(i.slice(0,a))}return{stdout:`${n.join(`
309
309
  `)}
310
- `,stderr:"",exitCode:0}}}});var ea={};O(ea,{treeCommand:()=>ef});async function tf(t,e,r,n,s){let i={output:"",stderr:"",dirCount:0,fileCount:0},a=t.fs.resolvePath(t.cwd,e);try{if(!(await t.fs.stat(a)).isDirectory)return i.output=`${e}
310
+ `,stderr:"",exitCode:0}}}});var sa={};D(sa,{treeCommand:()=>lf});async function cf(t,e,r,n,s){let i={output:"",stderr:"",dirCount:0,fileCount:0},a=t.fs.resolvePath(t.cwd,e);try{if(!(await t.fs.stat(a)).isDirectory)return i.output=`${e}
311
311
  `,i.fileCount=1,i}catch{return i.stderr=`tree: ${e}: No such file or directory
312
312
  `,i}if(i.output=`${e}
313
313
  `,r.maxDepth!==null&&s>=r.maxDepth)return i;try{let c=(await t.fs.readdir(a)).filter(l=>!(!r.showHidden&&l.startsWith(".")));c.sort();for(let l=0;l<c.length;l++){let u=c[l],f=a==="/"?`/${u}`:`${a}/${u}`,d=l===c.length-1,h=d?"`-- ":"|-- ",p=n+(d?" ":"| ");try{if((await t.fs.stat(f)).isDirectory){i.dirCount++;let w=r.fullPath?f:u;if(i.output+=`${n+h+w}
314
- `,r.maxDepth===null||s+1<r.maxDepth){let g=await Ji(t,f,r,p,s+1);i.output+=g.output,i.dirCount+=g.dirCount,i.fileCount+=g.fileCount}}else if(!r.directoriesOnly){i.fileCount++;let w=r.fullPath?f:u;i.output+=`${n+h+w}
314
+ `,r.maxDepth===null||s+1<r.maxDepth){let g=await na(t,f,r,p,s+1);i.output+=g.output,i.dirCount+=g.dirCount,i.fileCount+=g.fileCount}}else if(!r.directoriesOnly){i.fileCount++;let w=r.fullPath?f:u;i.output+=`${n+h+w}
315
315
  `}}catch{}}}catch{i.stderr=`tree: ${e}: Permission denied
316
- `}return i}async function Ji(t,e,r,n,s){let i={output:"",stderr:"",dirCount:0,fileCount:0};if(r.maxDepth!==null&&s>=r.maxDepth)return i;try{let o=(await t.fs.readdir(e)).filter(c=>!(!r.showHidden&&c.startsWith(".")));o.sort();for(let c=0;c<o.length;c++){let l=o[c],u=e==="/"?`/${l}`:`${e}/${l}`,f=c===o.length-1,d=f?"`-- ":"|-- ",h=n+(f?" ":"| ");try{if((await t.fs.stat(u)).isDirectory){i.dirCount++;let b=r.fullPath?u:l;i.output+=`${n+d+b}
317
- `;let w=await Ji(t,u,r,h,s+1);i.output+=w.output,i.dirCount+=w.dirCount,i.fileCount+=w.fileCount}else if(!r.directoriesOnly){i.fileCount++;let b=r.fullPath?u:l;i.output+=`${n+d+b}
318
- `}}catch{}}}catch{}return i}var Yu,Ju,ef,ta=N(()=>{"use strict";ae();L();Yu={name:"tree",summary:"list contents of directories in a tree-like format",usage:"tree [OPTION]... [DIRECTORY]...",options:["-a include hidden files","-d list directories only","-L LEVEL limit depth of directory tree","-f print full path prefix for each file"," --help display this help and exit"]},Ju={showHidden:{short:"a",type:"boolean"},directoriesOnly:{short:"d",type:"boolean"},fullPath:{short:"f",type:"boolean"},maxDepth:{short:"L",type:"number"}},ef={name:"tree",async execute(t,e){if(C(t))return A(Yu);let r=H("tree",t,Ju);if(!r.ok)return r.error;let n={showHidden:r.result.flags.showHidden,directoriesOnly:r.result.flags.directoriesOnly,maxDepth:r.result.flags.maxDepth??null,fullPath:r.result.flags.fullPath},s=r.result.positional;s.length===0&&s.push(".");let i="",a="",o=0,c=0;for(let l of s){let u=await tf(e,l,n,"",0);i+=u.output,a+=u.stderr,o+=u.dirCount,c+=u.fileCount}return i+=`
316
+ `}return i}async function na(t,e,r,n,s){let i={output:"",stderr:"",dirCount:0,fileCount:0};if(r.maxDepth!==null&&s>=r.maxDepth)return i;try{let o=(await t.fs.readdir(e)).filter(c=>!(!r.showHidden&&c.startsWith(".")));o.sort();for(let c=0;c<o.length;c++){let l=o[c],u=e==="/"?`/${l}`:`${e}/${l}`,f=c===o.length-1,d=f?"`-- ":"|-- ",h=n+(f?" ":"| ");try{if((await t.fs.stat(u)).isDirectory){i.dirCount++;let E=r.fullPath?u:l;i.output+=`${n+d+E}
317
+ `;let w=await na(t,u,r,h,s+1);i.output+=w.output,i.dirCount+=w.dirCount,i.fileCount+=w.fileCount}else if(!r.directoriesOnly){i.fileCount++;let E=r.fullPath?u:l;i.output+=`${n+d+E}
318
+ `}}catch{}}}catch{}return i}var af,of,lf,ia=v(()=>{"use strict";oe();F();af={name:"tree",summary:"list contents of directories in a tree-like format",usage:"tree [OPTION]... [DIRECTORY]...",options:["-a include hidden files","-d list directories only","-L LEVEL limit depth of directory tree","-f print full path prefix for each file"," --help display this help and exit"]},of={showHidden:{short:"a",type:"boolean"},directoriesOnly:{short:"d",type:"boolean"},fullPath:{short:"f",type:"boolean"},maxDepth:{short:"L",type:"number"}},lf={name:"tree",async execute(t,e){if(N(t))return C(af);let r=G("tree",t,of);if(!r.ok)return r.error;let n={showHidden:r.result.flags.showHidden,directoriesOnly:r.result.flags.directoriesOnly,maxDepth:r.result.flags.maxDepth??null,fullPath:r.result.flags.fullPath},s=r.result.positional;s.length===0&&s.push(".");let i="",a="",o=0,c=0;for(let l of s){let u=await cf(e,l,n,"",0);i+=u.output,a+=u.stderr,o+=u.dirCount,c+=u.fileCount}return i+=`
319
319
  ${o} director${o===1?"y":"ies"}`,n.directoriesOnly||(i+=`, ${c} file${c===1?"":"s"}`),i+=`
320
- `,{stdout:i,stderr:a,exitCode:a?1:0}}}});var na={};O(na,{duCommand:()=>sf});async function ra(t,e,r,n,s){let i={output:"",totalSize:0,stderr:""};try{let a=await t.fs.stat(e);if(!a.isDirectory)return i.totalSize=a.size,(n.allFiles||s===0)&&(i.output=Qt(a.size,n.humanReadable)+" "+r+`
321
- `),i;let o=await t.fs.readdir(e),c=0;for(let l of o){let u=e==="/"?`/${l}`:`${e}/${l}`,f=r==="."?l:`${r}/${l}`;try{let d=await t.fs.stat(u);if(d.isDirectory){let h=await ra(t,u,f,n,s+1);c+=h.totalSize,n.summarize||(n.maxDepth===null||s+1<=n.maxDepth?i.output+=h.output:c+=0)}else c+=d.size,n.allFiles&&!n.summarize&&(i.output+=Qt(d.size,n.humanReadable)+" "+f+`
322
- `)}catch{}}i.totalSize=c,(n.summarize||n.maxDepth===null||s<=n.maxDepth)&&(i.output+=`${Qt(c,n.humanReadable)} ${r}
320
+ `,{stdout:i,stderr:a,exitCode:a?1:0}}}});var oa={};D(oa,{duCommand:()=>df});async function aa(t,e,r,n,s){let i={output:"",totalSize:0,stderr:""};try{let a=await t.fs.stat(e);if(!a.isDirectory)return i.totalSize=a.size,(n.allFiles||s===0)&&(i.output=Jt(a.size,n.humanReadable)+" "+r+`
321
+ `),i;let o=await t.fs.readdir(e),c=0;for(let l of o){let u=e==="/"?`/${l}`:`${e}/${l}`,f=r==="."?l:`${r}/${l}`;try{let d=await t.fs.stat(u);if(d.isDirectory){let h=await aa(t,u,f,n,s+1);c+=h.totalSize,n.summarize||(n.maxDepth===null||s+1<=n.maxDepth?i.output+=h.output:c+=0)}else c+=d.size,n.allFiles&&!n.summarize&&(i.output+=Jt(d.size,n.humanReadable)+" "+f+`
322
+ `)}catch{}}i.totalSize=c,(n.summarize||n.maxDepth===null||s<=n.maxDepth)&&(i.output+=`${Jt(c,n.humanReadable)} ${r}
323
323
  `)}catch{i.stderr=`du: cannot read directory '${r}': Permission denied
324
- `}return i}function Qt(t,e){return e?t<1024?`${t}`:t<1024*1024?`${(t/1024).toFixed(1)}K`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)}M`:`${(t/(1024*1024*1024)).toFixed(1)}G`:String(Math.ceil(t/1024)||1)}var rf,nf,sf,sa=N(()=>{"use strict";ae();L();rf={name:"du",summary:"estimate file space usage",usage:"du [OPTION]... [FILE]...",options:["-a write counts for all files, not just directories","-h print sizes in human readable format","-s display only a total for each argument","-c produce a grand total","--max-depth=N print total for directory only if N or fewer levels deep"," --help display this help and exit"]},nf={allFiles:{short:"a",type:"boolean"},humanReadable:{short:"h",type:"boolean"},summarize:{short:"s",type:"boolean"},grandTotal:{short:"c",type:"boolean"},maxDepth:{long:"max-depth",type:"number"}},sf={name:"du",async execute(t,e){if(C(t))return A(rf);let r=H("du",t,nf);if(!r.ok)return r.error;let n={allFiles:r.result.flags.allFiles,humanReadable:r.result.flags.humanReadable,summarize:r.result.flags.summarize,grandTotal:r.result.flags.grandTotal,maxDepth:r.result.flags.maxDepth??null},s=r.result.positional;s.length===0&&s.push(".");let i="",a="",o=0;for(let c of s){let l=e.fs.resolvePath(e.cwd,c);try{await e.fs.stat(l);let u=await ra(e,l,c,n,0);i+=u.output,o+=u.totalSize,a+=u.stderr}catch{a+=`du: cannot access '${c}': No such file or directory
325
- `}}return n.grandTotal&&s.length>0&&(i+=`${Qt(o,n.humanReadable)} total
326
- `),{stdout:i,stderr:a,exitCode:a?1:0}}}});var Zr={};O(Zr,{envCommand:()=>of,printenvCommand:()=>cf});var af,of,lf,cf,Qr=N(()=>{"use strict";L();af={name:"env",summary:"run a program in a modified environment",usage:"env [OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]",options:["-i, --ignore-environment start with an empty environment","-u NAME, --unset=NAME remove NAME from the environment"," --help display this help and exit"]},of={name:"env",async execute(t,e){if(C(t))return A(af);let r=!1,n=[],s={},i=-1;for(let u=0;u<t.length;u++){let f=t[u];if(f==="-i"||f==="--ignore-environment")r=!0;else if(f==="-u"&&u+1<t.length)n.push(t[++u]);else if(f.startsWith("-u"))n.push(f.slice(2));else if(f.startsWith("--unset="))n.push(f.slice(8));else{if(f.startsWith("--")&&f!=="--")return T("env",f);if(f.startsWith("-")&&f!=="-"){for(let d of f.slice(1))if(d!=="i"&&d!=="u")return T("env",`-${d}`);f.includes("i")&&(r=!0)}else if(f.includes("=")&&i===-1){let d=f.indexOf("="),h=f.slice(0,d),p=f.slice(d+1);s[h]=p}else{i=u;break}}}let a;if(r)a={...s};else{a={...e.env};for(let u of n)delete a[u];Object.assign(a,s)}if(i===-1){let u=[];for(let[f,d]of Object.entries(a))u.push(`${f}=${d}`);return{stdout:u.join(`
324
+ `}return i}function Jt(t,e){return e?t<1024?`${t}`:t<1024*1024?`${(t/1024).toFixed(1)}K`:t<1024*1024*1024?`${(t/(1024*1024)).toFixed(1)}M`:`${(t/(1024*1024*1024)).toFixed(1)}G`:String(Math.ceil(t/1024)||1)}var uf,ff,df,la=v(()=>{"use strict";oe();F();uf={name:"du",summary:"estimate file space usage",usage:"du [OPTION]... [FILE]...",options:["-a write counts for all files, not just directories","-h print sizes in human readable format","-s display only a total for each argument","-c produce a grand total","--max-depth=N print total for directory only if N or fewer levels deep"," --help display this help and exit"]},ff={allFiles:{short:"a",type:"boolean"},humanReadable:{short:"h",type:"boolean"},summarize:{short:"s",type:"boolean"},grandTotal:{short:"c",type:"boolean"},maxDepth:{long:"max-depth",type:"number"}},df={name:"du",async execute(t,e){if(N(t))return C(uf);let r=G("du",t,ff);if(!r.ok)return r.error;let n={allFiles:r.result.flags.allFiles,humanReadable:r.result.flags.humanReadable,summarize:r.result.flags.summarize,grandTotal:r.result.flags.grandTotal,maxDepth:r.result.flags.maxDepth??null},s=r.result.positional;s.length===0&&s.push(".");let i="",a="",o=0;for(let c of s){let l=e.fs.resolvePath(e.cwd,c);try{await e.fs.stat(l);let u=await aa(e,l,c,n,0);i+=u.output,o+=u.totalSize,a+=u.stderr}catch{a+=`du: cannot access '${c}': No such file or directory
325
+ `}}return n.grandTotal&&s.length>0&&(i+=`${Jt(o,n.humanReadable)} total
326
+ `),{stdout:i,stderr:a,exitCode:a?1:0}}}});var Xr={};D(Xr,{envCommand:()=>pf,printenvCommand:()=>yf});var hf,pf,mf,yf,Yr=v(()=>{"use strict";F();hf={name:"env",summary:"run a program in a modified environment",usage:"env [OPTION]... [NAME=VALUE]... [COMMAND [ARG]...]",options:["-i, --ignore-environment start with an empty environment","-u NAME, --unset=NAME remove NAME from the environment"," --help display this help and exit"]},pf={name:"env",async execute(t,e){if(N(t))return C(hf);let r=!1,n=[],s={},i=-1;for(let u=0;u<t.length;u++){let f=t[u];if(f==="-i"||f==="--ignore-environment")r=!0;else if(f==="-u"&&u+1<t.length)n.push(t[++u]);else if(f.startsWith("-u"))n.push(f.slice(2));else if(f.startsWith("--unset="))n.push(f.slice(8));else{if(f.startsWith("--")&&f!=="--")return M("env",f);if(f.startsWith("-")&&f!=="-"){for(let d of f.slice(1))if(d!=="i"&&d!=="u")return M("env",`-${d}`);f.includes("i")&&(r=!0)}else if(f.includes("=")&&i===-1){let d=f.indexOf("="),h=f.slice(0,d),p=f.slice(d+1);s[h]=p}else{i=u;break}}}let a;if(r)a={...s};else{a={...e.env};for(let u of n)delete a[u];Object.assign(a,s)}if(i===-1){let u=[];for(let[f,d]of Object.entries(a))u.push(`${f}=${d}`);return{stdout:u.join(`
327
327
  `)+(u.length>0?`
328
328
  `:""),stderr:"",exitCode:0}}if(!e.exec)return{stdout:"",stderr:`env: command execution not supported in this context
329
- `,exitCode:1};let o=t.slice(i).join(" "),c=Object.entries(s).map(([u,f])=>`${u}="${f}"`).join(" "),l=c?`${c} ${o}`:o;return e.exec(l,{cwd:e.cwd})}},lf={name:"printenv",summary:"print all or part of environment",usage:"printenv [OPTION]... [VARIABLE]...",options:[" --help display this help and exit"]},cf={name:"printenv",async execute(t,e){if(C(t))return A(lf);let r=t.filter(i=>!i.startsWith("-"));if(r.length===0){let i=[];for(let[a,o]of Object.entries(e.env))i.push(`${a}=${o}`);return{stdout:i.join(`
329
+ `,exitCode:1};let o=t.slice(i).join(" "),c=Object.entries(s).map(([u,f])=>`${u}="${f}"`).join(" "),l=c?`${c} ${o}`:o;return e.exec(l,{cwd:e.cwd})}},mf={name:"printenv",summary:"print all or part of environment",usage:"printenv [OPTION]... [VARIABLE]...",options:[" --help display this help and exit"]},yf={name:"printenv",async execute(t,e){if(N(t))return C(mf);let r=t.filter(i=>!i.startsWith("-"));if(r.length===0){let i=[];for(let[a,o]of Object.entries(e.env))i.push(`${a}=${o}`);return{stdout:i.join(`
330
330
  `)+(i.length>0?`
331
331
  `:""),stderr:"",exitCode:0}}let n=[],s=0;for(let i of r)i in e.env?n.push(e.env[i]):s=1;return{stdout:n.join(`
332
332
  `)+(n.length>0?`
333
- `:""),stderr:"",exitCode:s}}}});var Kr={};O(Kr,{aliasCommand:()=>ff,unaliasCommand:()=>df});var uf,ft,ff,df,Xr=N(()=>{"use strict";L();uf={name:"alias",summary:"define or display aliases",usage:"alias [name[=value] ...]",options:[" --help display this help and exit"]},ft="BASH_ALIAS_",ff={name:"alias",async execute(t,e){if(C(t))return A(uf);if(t.length===0){let r="";for(let[n,s]of Object.entries(e.env))if(n.startsWith(ft)){let i=n.slice(ft.length);r+=`alias ${i}='${s}'
334
- `}return{stdout:r,stderr:"",exitCode:0}}for(let r of t){let n=r.indexOf("=");if(n===-1){let s=ft+r;return e.env[s]?{stdout:`alias ${r}='${e.env[s]}'
333
+ `:""),stderr:"",exitCode:s}}}});var Jr={};D(Jr,{aliasCommand:()=>wf,unaliasCommand:()=>Ef});var gf,pt,wf,Ef,en=v(()=>{"use strict";F();gf={name:"alias",summary:"define or display aliases",usage:"alias [name[=value] ...]",options:[" --help display this help and exit"]},pt="BASH_ALIAS_",wf={name:"alias",async execute(t,e){if(N(t))return C(gf);if(t.length===0){let r="";for(let[n,s]of Object.entries(e.env))if(n.startsWith(pt)){let i=n.slice(pt.length);r+=`alias ${i}='${s}'
334
+ `}return{stdout:r,stderr:"",exitCode:0}}for(let r of t){let n=r.indexOf("=");if(n===-1){let s=pt+r;return e.env[s]?{stdout:`alias ${r}='${e.env[s]}'
335
335
  `,stderr:"",exitCode:0}:{stdout:"",stderr:`alias: ${r}: not found
336
- `,exitCode:1}}else{let s=r.slice(0,n),i=r.slice(n+1);(i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"'))&&(i=i.slice(1,-1)),e.env[ft+s]=i}}return{stdout:"",stderr:"",exitCode:0}}},df={name:"unalias",async execute(t,e){if(C(t))return A({name:"unalias",summary:"remove alias definitions",usage:"unalias name [name ...]",options:["-a remove all aliases"," --help display this help and exit"]});if(t.length===0)return{stdout:"",stderr:`unalias: usage: unalias [-a] name [name ...]
337
- `,exitCode:1};if(t[0]==="-a"){for(let s of Object.keys(e.env))s.startsWith(ft)&&delete e.env[s];return{stdout:"",stderr:"",exitCode:0}}let r=!1,n="";for(let s of t){let i=ft+s;e.env[i]?delete e.env[i]:(n+=`unalias: ${s}: not found
338
- `,r=!0)}return{stdout:"",stderr:n,exitCode:r?1:0}}}});var aa={};O(aa,{historyCommand:()=>pf});var hf,ia,pf,oa=N(()=>{"use strict";L();hf={name:"history",summary:"display command history",usage:"history [n]",options:["-c clear the history list"," --help display this help and exit"]},ia="BASH_HISTORY",pf={name:"history",async execute(t,e){if(C(t))return A(hf);let r=e.env[ia]||"[]",n;try{n=JSON.parse(r)}catch{n=[]}if(t[0]==="-c")return e.env[ia]="[]",{stdout:"",stderr:"",exitCode:0};let s=n.length;t[0]&&/^\d+$/.test(t[0])&&(s=Math.min(parseInt(t[0],10),n.length));let i=n.length-s,a="";for(let o=i;o<n.length;o++){let c=(o+1).toString().padStart(5," ");a+=`${c} ${n[o]}
339
- `}return{stdout:a,stderr:"",exitCode:0}}}});var la={};O(la,{xargsCommand:()=>yf});var mf,yf,ca=N(()=>{"use strict";L();mf={name:"xargs",summary:"build and execute command lines from standard input",usage:"xargs [OPTION]... [COMMAND [INITIAL-ARGS]]",options:["-I REPLACE replace occurrences of REPLACE with input","-n NUM use at most NUM arguments per command line","-P NUM run at most NUM processes at a time","-0, --null items are separated by null, not whitespace","-t, --verbose print commands before executing","-r, --no-run-if-empty do not run command if input is empty"," --help display this help and exit"]},yf={name:"xargs",async execute(t,e){if(C(t))return A(mf);let r=null,n=null,s=null,i=!1,a=!1,o=!1,c=0;for(let g=0;g<t.length;g++){let E=t[g];if(E==="-I"&&g+1<t.length)r=t[++g],c=g+1;else if(E==="-n"&&g+1<t.length)n=parseInt(t[++g],10),c=g+1;else if(E==="-P"&&g+1<t.length)s=parseInt(t[++g],10),c=g+1;else if(E==="-0"||E==="--null")i=!0,c=g+1;else if(E==="-t"||E==="--verbose")a=!0,c=g+1;else if(E==="-r"||E==="--no-run-if-empty")o=!0,c=g+1;else{if(E.startsWith("--"))return T("xargs",E);if(E.startsWith("-")&&E.length>1){for(let S of E.slice(1))if(!"0trnIP".includes(S))return T("xargs",`-${S}`);E.includes("0")&&(i=!0),E.includes("t")&&(a=!0),E.includes("r")&&(o=!0),c=g+1}else if(!E.startsWith("-")){c=g;break}}}let l=t.slice(c);l.length===0&&l.push("echo");let u=i?"\0":/\s+/,f=e.stdin.split(u).map(g=>g.trim()).filter(g=>g.length>0);if(f.length===0)return o?{stdout:"",stderr:"",exitCode:0}:{stdout:"",stderr:"",exitCode:0};let d="",h="",p=0,b=async g=>{let E=g.join(" ");return a&&(h+=`${E}
340
- `),e.exec?e.exec(E,{cwd:e.cwd}):{stdout:`${E}
341
- `,stderr:"",exitCode:0}},w=async g=>{if(s!==null&&s>1)for(let E=0;E<g.length;E+=s){let x=g.slice(E,E+s),S=await Promise.all(x.map(b));for(let v of S)d+=v.stdout,h+=v.stderr,v.exitCode!==0&&(p=v.exitCode)}else for(let E of g){let x=await b(E);d+=x.stdout,h+=x.stderr,x.exitCode!==0&&(p=x.exitCode)}};if(r!==null){let g=f.map(E=>l.map(x=>x.replaceAll(r,E)));await w(g)}else if(n!==null){let g=[];for(let E=0;E<f.length;E+=n){let x=f.slice(E,E+n);g.push([...l,...x])}await w(g)}else{let g=[...l,...f],E=await b(g);d+=E.stdout,h+=E.stderr,p=E.exitCode}return{stdout:d,stderr:h,exitCode:p}}}});var Yr={};O(Yr,{falseCommand:()=>wf,trueCommand:()=>gf});var gf,wf,Jr=N(()=>{"use strict";gf={name:"true",async execute(){return{stdout:"",stderr:"",exitCode:0}}},wf={name:"false",async execute(){return{stdout:"",stderr:"",exitCode:1}}}});var ua={};O(ua,{clearCommand:()=>bf});var Ef,bf,fa=N(()=>{"use strict";L();Ef={name:"clear",summary:"clear the terminal screen",usage:"clear [OPTIONS]",options:[" --help display this help and exit"]},bf={name:"clear",async execute(t,e){return C(t)?A(Ef):{stdout:"\x1B[2J\x1B[H",stderr:"",exitCode:0}}}});var en={};O(en,{bashCommand:()=>xf,shCommand:()=>Sf});async function Kt(t,e,r,n){if(!n.exec)return{stdout:"",stderr:`bash: internal error: exec function not available
336
+ `,exitCode:1}}else{let s=r.slice(0,n),i=r.slice(n+1);(i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"'))&&(i=i.slice(1,-1)),e.env[pt+s]=i}}return{stdout:"",stderr:"",exitCode:0}}},Ef={name:"unalias",async execute(t,e){if(N(t))return C({name:"unalias",summary:"remove alias definitions",usage:"unalias name [name ...]",options:["-a remove all aliases"," --help display this help and exit"]});if(t.length===0)return{stdout:"",stderr:`unalias: usage: unalias [-a] name [name ...]
337
+ `,exitCode:1};if(t[0]==="-a"){for(let s of Object.keys(e.env))s.startsWith(pt)&&delete e.env[s];return{stdout:"",stderr:"",exitCode:0}}let r=!1,n="";for(let s of t){let i=pt+s;e.env[i]?delete e.env[i]:(n+=`unalias: ${s}: not found
338
+ `,r=!0)}return{stdout:"",stderr:n,exitCode:r?1:0}}}});var ua={};D(ua,{historyCommand:()=>Sf});var bf,ca,Sf,fa=v(()=>{"use strict";F();bf={name:"history",summary:"display command history",usage:"history [n]",options:["-c clear the history list"," --help display this help and exit"]},ca="BASH_HISTORY",Sf={name:"history",async execute(t,e){if(N(t))return C(bf);let r=e.env[ca]||"[]",n;try{n=JSON.parse(r)}catch{n=[]}if(t[0]==="-c")return e.env[ca]="[]",{stdout:"",stderr:"",exitCode:0};let s=n.length;t[0]&&/^\d+$/.test(t[0])&&(s=Math.min(parseInt(t[0],10),n.length));let i=n.length-s,a="";for(let o=i;o<n.length;o++){let c=(o+1).toString().padStart(5," ");a+=`${c} ${n[o]}
339
+ `}return{stdout:a,stderr:"",exitCode:0}}}});var da={};D(da,{xargsCommand:()=>Af});var xf,Af,ha=v(()=>{"use strict";F();xf={name:"xargs",summary:"build and execute command lines from standard input",usage:"xargs [OPTION]... [COMMAND [INITIAL-ARGS]]",options:["-I REPLACE replace occurrences of REPLACE with input","-n NUM use at most NUM arguments per command line","-P NUM run at most NUM processes at a time","-0, --null items are separated by null, not whitespace","-t, --verbose print commands before executing","-r, --no-run-if-empty do not run command if input is empty"," --help display this help and exit"]},Af={name:"xargs",async execute(t,e){if(N(t))return C(xf);let r=null,n=null,s=null,i=!1,a=!1,o=!1,c=0;for(let g=0;g<t.length;g++){let b=t[g];if(b==="-I"&&g+1<t.length)r=t[++g],c=g+1;else if(b==="-n"&&g+1<t.length)n=parseInt(t[++g],10),c=g+1;else if(b==="-P"&&g+1<t.length)s=parseInt(t[++g],10),c=g+1;else if(b==="-0"||b==="--null")i=!0,c=g+1;else if(b==="-t"||b==="--verbose")a=!0,c=g+1;else if(b==="-r"||b==="--no-run-if-empty")o=!0,c=g+1;else{if(b.startsWith("--"))return M("xargs",b);if(b.startsWith("-")&&b.length>1){for(let x of b.slice(1))if(!"0trnIP".includes(x))return M("xargs",`-${x}`);b.includes("0")&&(i=!0),b.includes("t")&&(a=!0),b.includes("r")&&(o=!0),c=g+1}else if(!b.startsWith("-")){c=g;break}}}let l=t.slice(c);l.length===0&&l.push("echo");let u=i?"\0":/\s+/,f=e.stdin.split(u).map(g=>g.trim()).filter(g=>g.length>0);if(f.length===0)return o?{stdout:"",stderr:"",exitCode:0}:{stdout:"",stderr:"",exitCode:0};let d="",h="",p=0,E=async g=>{let b=g.join(" ");return a&&(h+=`${b}
340
+ `),e.exec?e.exec(b,{cwd:e.cwd}):{stdout:`${b}
341
+ `,stderr:"",exitCode:0}},w=async g=>{if(s!==null&&s>1)for(let b=0;b<g.length;b+=s){let S=g.slice(b,b+s),x=await Promise.all(S.map(E));for(let A of x)d+=A.stdout,h+=A.stderr,A.exitCode!==0&&(p=A.exitCode)}else for(let b of g){let S=await E(b);d+=S.stdout,h+=S.stderr,S.exitCode!==0&&(p=S.exitCode)}};if(r!==null){let g=f.map(b=>l.map(S=>S.replaceAll(r,b)));await w(g)}else if(n!==null){let g=[];for(let b=0;b<f.length;b+=n){let S=f.slice(b,b+n);g.push([...l,...S])}await w(g)}else{let g=[...l,...f],b=await E(g);d+=b.stdout,h+=b.stderr,p=b.exitCode}return{stdout:d,stderr:h,exitCode:p}}}});var tn={};D(tn,{falseCommand:()=>Nf,trueCommand:()=>Cf});var Cf,Nf,rn=v(()=>{"use strict";Cf={name:"true",async execute(){return{stdout:"",stderr:"",exitCode:0}}},Nf={name:"false",async execute(){return{stdout:"",stderr:"",exitCode:1}}}});var pa={};D(pa,{clearCommand:()=>kf});var vf,kf,ma=v(()=>{"use strict";F();vf={name:"clear",summary:"clear the terminal screen",usage:"clear [OPTIONS]",options:[" --help display this help and exit"]},kf={name:"clear",async execute(t,e){return N(t)?C(vf):{stdout:"\x1B[2J\x1B[H",stderr:"",exitCode:0}}}});var nn={};D(nn,{bashCommand:()=>If,shCommand:()=>$f});async function er(t,e,r,n){if(!n.exec)return{stdout:"",stderr:`bash: internal error: exec function not available
342
342
  `,exitCode:1};let s={0:e,"#":String(r.length),"@":r.join(" "),"*":r.join(" ")};r.forEach((u,f)=>{s[String(f+1)]=u});let i=t;if(i.startsWith("#!")){let u=i.indexOf(`
343
343
  `);u!==-1&&(i=i.slice(u+1))}let a=i.split(`
344
- `),o=[];for(let u of a){let f=u.trim();f&&!f.startsWith("#")&&o.push(f)}let c=o.join("; ");return await n.exec(c,{env:s,cwd:n.cwd})}var da,xf,Sf,tn=N(()=>{"use strict";L();da={name:"bash",summary:"execute shell commands or scripts",usage:"bash [OPTIONS] [SCRIPT_FILE] [ARGUMENTS...]",options:["-c COMMAND execute COMMAND string"," --help display this help and exit"],notes:["Without -c, reads and executes commands from SCRIPT_FILE.","Arguments are passed as $1, $2, etc. to the script.",'$0 is set to the script name (or "bash" with -c).']},xf={name:"bash",async execute(t,e){if(C(t))return A(da);if(t[0]==="-c"&&t.length>=2){let s=t[1],i=t[2]||"bash",a=t.slice(3);return Kt(s,i,a,e)}if(t.length===0)return{stdout:"",stderr:"",exitCode:0};let r=t[0],n=t.slice(1);try{let s=e.fs.resolvePath(e.cwd,r),i=await e.fs.readFile(s);return Kt(i,r,n,e)}catch{return{stdout:"",stderr:`bash: ${r}: No such file or directory
345
- `,exitCode:127}}}},Sf={name:"sh",async execute(t,e){if(C(t))return A({...da,name:"sh",summary:"execute shell commands or scripts (POSIX shell)"});if(t[0]==="-c"&&t.length>=2){let s=t[1],i=t[2]||"sh",a=t.slice(3);return Kt(s,i,a,e)}if(t.length===0)return{stdout:"",stderr:"",exitCode:0};let r=t[0],n=t.slice(1);try{let s=e.fs.resolvePath(e.cwd,r),i=await e.fs.readFile(s);return Kt(i,r,n,e)}catch{return{stdout:"",stderr:`sh: ${r}: No such file or directory
346
- `,exitCode:127}}}}});var ha={};O(ha,{jqCommand:()=>Cf});function Ct(t,e,r,n=0){if(t===null||t===void 0)return"null";if(typeof t=="boolean"||typeof t=="number")return String(t);if(typeof t=="string")return r?t:JSON.stringify(t);if(Array.isArray(t))return t.length===0?"[]":e?`[${t.map(i=>Ct(i,!0,!1)).join(",")}]`:`[
347
- ${t.map(i=>" ".repeat(n+1)+Ct(i,!1,!1,n+1)).join(`,
344
+ `),o=[];for(let u of a){let f=u.trim();f&&!f.startsWith("#")&&o.push(f)}let c=o.join("; ");return await n.exec(c,{env:s,cwd:n.cwd})}var ya,If,$f,sn=v(()=>{"use strict";F();ya={name:"bash",summary:"execute shell commands or scripts",usage:"bash [OPTIONS] [SCRIPT_FILE] [ARGUMENTS...]",options:["-c COMMAND execute COMMAND string"," --help display this help and exit"],notes:["Without -c, reads and executes commands from SCRIPT_FILE.","Arguments are passed as $1, $2, etc. to the script.",'$0 is set to the script name (or "bash" with -c).']},If={name:"bash",async execute(t,e){if(N(t))return C(ya);if(t[0]==="-c"&&t.length>=2){let s=t[1],i=t[2]||"bash",a=t.slice(3);return er(s,i,a,e)}if(t.length===0)return{stdout:"",stderr:"",exitCode:0};let r=t[0],n=t.slice(1);try{let s=e.fs.resolvePath(e.cwd,r),i=await e.fs.readFile(s);return er(i,r,n,e)}catch{return{stdout:"",stderr:`bash: ${r}: No such file or directory
345
+ `,exitCode:127}}}},$f={name:"sh",async execute(t,e){if(N(t))return C({...ya,name:"sh",summary:"execute shell commands or scripts (POSIX shell)"});if(t[0]==="-c"&&t.length>=2){let s=t[1],i=t[2]||"sh",a=t.slice(3);return er(s,i,a,e)}if(t.length===0)return{stdout:"",stderr:"",exitCode:0};let r=t[0],n=t.slice(1);try{let s=e.fs.resolvePath(e.cwd,r),i=await e.fs.readFile(s);return er(i,r,n,e)}catch{return{stdout:"",stderr:`sh: ${r}: No such file or directory
346
+ `,exitCode:127}}}}});var ga={};D(ga,{jqCommand:()=>Pf});function vt(t,e,r,n=0){if(t===null||t===void 0)return"null";if(typeof t=="boolean"||typeof t=="number")return String(t);if(typeof t=="string")return r?t:JSON.stringify(t);if(Array.isArray(t))return t.length===0?"[]":e?`[${t.map(i=>vt(i,!0,!1)).join(",")}]`:`[
347
+ ${t.map(i=>" ".repeat(n+1)+vt(i,!1,!1,n+1)).join(`,
348
348
  `)}
349
- ${" ".repeat(n)}]`;if(typeof t=="object"){let s=Object.keys(t);return s.length===0?"{}":e?`{${s.map(a=>`${JSON.stringify(a)}:${Ct(t[a],!0,!1)}`).join(",")}}`:`{
350
- ${s.map(a=>{let o=Ct(t[a],!1,!1,n+1);return`${" ".repeat(n+1)}${JSON.stringify(a)}: ${o}`}).join(`,
349
+ ${" ".repeat(n)}]`;if(typeof t=="object"){let s=Object.keys(t);return s.length===0?"{}":e?`{${s.map(a=>`${JSON.stringify(a)}:${vt(t[a],!0,!1)}`).join(",")}}`:`{
350
+ ${s.map(a=>{let o=vt(t[a],!1,!1,n+1);return`${" ".repeat(n+1)}${JSON.stringify(a)}: ${o}`}).join(`,
351
351
  `)}
352
- ${" ".repeat(n)}}`}return String(t)}function Ue(t,e){if(e===""||e===".")return[t];let r=e.startsWith(".")?e.slice(1):e;if(r==="")return[t];if(r.startsWith("[]")){let a=r.slice(2);return Array.isArray(t)?t.flatMap(o=>Ue(o,`.${a}`)):t&&typeof t=="object"?Object.values(t).flatMap(o=>Ue(o,`.${a}`)):[]}let n=r.match(/^\[(-?\d+)\](.*)/);if(n){let a=Number.parseInt(n[1],10),o=n[2];if(Array.isArray(t)){let c=a<0?t.length+a:a;if(c>=0&&c<t.length)return Ue(t[c],`.${o}`)}return[null]}let s=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(.*)/);if(s){let a=s[1],o=s[2];if(t&&typeof t=="object"&&!Array.isArray(t)){let l=t[a];if(o.startsWith("[]"))return o=o.slice(2),Array.isArray(l)?l.flatMap(u=>Ue(u,`.${o}`)):l&&typeof l=="object"?Object.values(l).flatMap(u=>Ue(u,`.${o}`)):[];if(o.startsWith(".")||o.startsWith("[")||o==="")return Ue(l,o||".")}return[null]}let i=r.match(/^\["([^"]+)"\](.*)/);if(i){let a=i[1],o=i[2];return t&&typeof t=="object"&&!Array.isArray(t)?Ue(t[a],`.${o}`):[null]}return[null]}function Nt(t,e){let r=e.trim();if(r.includes("|")){let n=r.split("|").map(i=>i.trim()),s=[t];for(let i of n)s=s.flatMap(a=>Nt(a,i));return s}return r==="keys"?Array.isArray(t)?[t.map((n,s)=>s)]:t&&typeof t=="object"?[Object.keys(t)]:[null]:r==="values"?Array.isArray(t)?[t]:t&&typeof t=="object"?[Object.values(t)]:[null]:r==="length"?typeof t=="string"?[t.length]:Array.isArray(t)?[t.length]:t&&typeof t=="object"?[Object.keys(t).length]:t===null?[0]:[null]:r==="type"?t===null?["null"]:Array.isArray(t)?["array"]:[typeof t]:r==="first"?Array.isArray(t)&&t.length>0?[t[0]]:[null]:r==="last"?Array.isArray(t)&&t.length>0?[t[t.length-1]]:[null]:r==="reverse"?Array.isArray(t)?[[...t].reverse()]:typeof t=="string"?[t.split("").reverse().join("")]:[null]:r==="sort"?Array.isArray(t)?[[...t].sort()]:[null]:r==="unique"?Array.isArray(t)?[[...new Set(t.map(n=>JSON.stringify(n)))].map(n=>JSON.parse(n))]:[null]:r==="flatten"?Array.isArray(t)?[t.flat()]:[null]:r==="add"?Array.isArray(t)?t.length===0?[null]:t.every(n=>typeof n=="number")?[t.reduce((n,s)=>n+s,0)]:t.every(n=>typeof n=="string")?[t.join("")]:t.every(n=>Array.isArray(n))?[t.flat()]:[null]:[null]:r==="min"?Array.isArray(t)&&t.length>0?[Math.min(...t)]:[null]:r==="max"?Array.isArray(t)&&t.length>0?[Math.max(...t)]:[null]:r==="empty"?[]:r==="not"?[!t]:Ue(t,r)}var Af,Cf,pa=N(()=>{"use strict";L();Af={name:"jq",summary:"command-line JSON processor",usage:"jq [OPTIONS] FILTER [FILE]",options:["-r, --raw-output output strings without quotes","-c, --compact compact output (no pretty printing)","-e, --exit-status set exit status based on output","-s, --slurp read entire input into array","-n, --null-input don't read any input"," --help display this help and exit"]};Cf={name:"jq",async execute(t,e){if(C(t))return A(Af);let r=!1,n=!1,s=!1,i=!1,a=!1,o=".",c=!1,l=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-r"||d==="--raw-output")r=!0;else if(d==="-c"||d==="--compact-output")n=!0;else if(d==="-e"||d==="--exit-status")s=!0;else if(d==="-s"||d==="--slurp")i=!0;else if(d==="-n"||d==="--null-input")a=!0;else if(d==="-")l.push("-");else{if(d.startsWith("--"))return T("jq",d);if(d.startsWith("-"))for(let h of d.slice(1))if(h==="r")r=!0;else if(h==="c")n=!0;else if(h==="e")s=!0;else if(h==="s")i=!0;else if(h==="n")a=!0;else return T("jq",`-${h}`);else c?l.push(d):(o=d,c=!0)}}let u;if(a)u="";else if(l.length===0||l.length===1&&l[0]==="-")u=e.stdin;else try{let f=e.fs.resolvePath(e.cwd,l[0]);u=await e.fs.readFile(f)}catch{return{stdout:"",stderr:`jq: ${l[0]}: No such file or directory
353
- `,exitCode:2}}try{let f;if(a)f=Nt(null,o);else if(i){let p=[];for(let b of u.trim().split(`
354
- `))b.trim()&&p.push(JSON.parse(b));f=Nt(p,o)}else{let p=u.trim();if(p.startsWith("{")||p.startsWith("["))f=Nt(JSON.parse(p),o);else{f=[];for(let b of p.split(`
355
- `))b.trim()&&f.push(...Nt(JSON.parse(b),o))}}let d=f.map(p=>Ct(p,n,r)).join(`
352
+ ${" ".repeat(n)}}`}return String(t)}function Ge(t,e){if(e===""||e===".")return[t];let r=e.startsWith(".")?e.slice(1):e;if(r==="")return[t];if(r.startsWith("[]")){let a=r.slice(2);return Array.isArray(t)?t.flatMap(o=>Ge(o,`.${a}`)):t&&typeof t=="object"?Object.values(t).flatMap(o=>Ge(o,`.${a}`)):[]}let n=r.match(/^\[(-?\d+)\](.*)/);if(n){let a=Number.parseInt(n[1],10),o=n[2];if(Array.isArray(t)){let c=a<0?t.length+a:a;if(c>=0&&c<t.length)return Ge(t[c],`.${o}`)}return[null]}let s=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(.*)/);if(s){let a=s[1],o=s[2];if(t&&typeof t=="object"&&!Array.isArray(t)){let l=t[a];if(o.startsWith("[]"))return o=o.slice(2),Array.isArray(l)?l.flatMap(u=>Ge(u,`.${o}`)):l&&typeof l=="object"?Object.values(l).flatMap(u=>Ge(u,`.${o}`)):[];if(o.startsWith(".")||o.startsWith("[")||o==="")return Ge(l,o||".")}return[null]}let i=r.match(/^\["([^"]+)"\](.*)/);if(i){let a=i[1],o=i[2];return t&&typeof t=="object"&&!Array.isArray(t)?Ge(t[a],`.${o}`):[null]}return[null]}function kt(t,e){let r=e.trim();if(r.includes("|")){let n=r.split("|").map(i=>i.trim()),s=[t];for(let i of n)s=s.flatMap(a=>kt(a,i));return s}return r==="keys"?Array.isArray(t)?[t.map((n,s)=>s)]:t&&typeof t=="object"?[Object.keys(t)]:[null]:r==="values"?Array.isArray(t)?[t]:t&&typeof t=="object"?[Object.values(t)]:[null]:r==="length"?typeof t=="string"?[t.length]:Array.isArray(t)?[t.length]:t&&typeof t=="object"?[Object.keys(t).length]:t===null?[0]:[null]:r==="type"?t===null?["null"]:Array.isArray(t)?["array"]:[typeof t]:r==="first"?Array.isArray(t)&&t.length>0?[t[0]]:[null]:r==="last"?Array.isArray(t)&&t.length>0?[t[t.length-1]]:[null]:r==="reverse"?Array.isArray(t)?[[...t].reverse()]:typeof t=="string"?[t.split("").reverse().join("")]:[null]:r==="sort"?Array.isArray(t)?[[...t].sort()]:[null]:r==="unique"?Array.isArray(t)?[[...new Set(t.map(n=>JSON.stringify(n)))].map(n=>JSON.parse(n))]:[null]:r==="flatten"?Array.isArray(t)?[t.flat()]:[null]:r==="add"?Array.isArray(t)?t.length===0?[null]:t.every(n=>typeof n=="number")?[t.reduce((n,s)=>n+s,0)]:t.every(n=>typeof n=="string")?[t.join("")]:t.every(n=>Array.isArray(n))?[t.flat()]:[null]:[null]:r==="min"?Array.isArray(t)&&t.length>0?[Math.min(...t)]:[null]:r==="max"?Array.isArray(t)&&t.length>0?[Math.max(...t)]:[null]:r==="empty"?[]:r==="not"?[!t]:Ge(t,r)}var Rf,Pf,wa=v(()=>{"use strict";F();Rf={name:"jq",summary:"command-line JSON processor",usage:"jq [OPTIONS] FILTER [FILE]",options:["-r, --raw-output output strings without quotes","-c, --compact compact output (no pretty printing)","-e, --exit-status set exit status based on output","-s, --slurp read entire input into array","-n, --null-input don't read any input"," --help display this help and exit"]};Pf={name:"jq",async execute(t,e){if(N(t))return C(Rf);let r=!1,n=!1,s=!1,i=!1,a=!1,o=".",c=!1,l=[];for(let f=0;f<t.length;f++){let d=t[f];if(d==="-r"||d==="--raw-output")r=!0;else if(d==="-c"||d==="--compact-output")n=!0;else if(d==="-e"||d==="--exit-status")s=!0;else if(d==="-s"||d==="--slurp")i=!0;else if(d==="-n"||d==="--null-input")a=!0;else if(d==="-")l.push("-");else{if(d.startsWith("--"))return M("jq",d);if(d.startsWith("-"))for(let h of d.slice(1))if(h==="r")r=!0;else if(h==="c")n=!0;else if(h==="e")s=!0;else if(h==="s")i=!0;else if(h==="n")a=!0;else return M("jq",`-${h}`);else c?l.push(d):(o=d,c=!0)}}let u;if(a)u="";else if(l.length===0||l.length===1&&l[0]==="-")u=e.stdin;else try{let f=e.fs.resolvePath(e.cwd,l[0]);u=await e.fs.readFile(f)}catch{return{stdout:"",stderr:`jq: ${l[0]}: No such file or directory
353
+ `,exitCode:2}}try{let f;if(a)f=kt(null,o);else if(i){let p=[];for(let E of u.trim().split(`
354
+ `))E.trim()&&p.push(JSON.parse(E));f=kt(p,o)}else{let p=u.trim();if(p.startsWith("{")||p.startsWith("["))f=kt(JSON.parse(p),o);else{f=[];for(let E of p.split(`
355
+ `))E.trim()&&f.push(...kt(JSON.parse(E),o))}}let d=f.map(p=>vt(p,n,r)).join(`
356
356
  `),h=s&&(f.length===0||f.every(p=>p==null||p===!1))?1:0;return{stdout:d?`${d}
357
357
  `:"",stderr:"",exitCode:h}}catch(f){return{stdout:"",stderr:`jq: parse error: ${f.message}
358
- `,exitCode:5}}}}});var ma={};O(ma,{base64Command:()=>kf});var Nf,vf,kf,ya=N(()=>{"use strict";ae();Ze();L();Nf={name:"base64",summary:"base64 encode/decode data and print to standard output",usage:"base64 [OPTION]... [FILE]",options:["-d, --decode decode data","-w, --wrap=COLS wrap encoded lines after COLS character (default 76, 0 to disable)"," --help display this help and exit"]},vf={decode:{short:"d",long:"decode",type:"boolean"},wrap:{short:"w",long:"wrap",type:"number",default:76}},kf={name:"base64",async execute(t,e){if(C(t))return A(Nf);let r=H("base64",t,vf);if(!r.ok)return r.error;let n=r.result.flags.decode,s=r.result.flags.wrap,i=r.result.positional,a=await Be(e,i,{cmdName:"base64"});if(!a.ok)return a.error;let o=a.content;try{if(n){let l=o.replace(/\s/g,"");return{stdout:Buffer.from(l,"base64").toString("utf-8"),stderr:"",exitCode:0}}let c=Buffer.from(o).toString("base64");if(s>0){let l=[];for(let u=0;u<c.length;u+=s)l.push(c.slice(u,u+s));c=l.join(`
358
+ `,exitCode:5}}}}});var Ea={};D(Ea,{base64Command:()=>Tf});var Of,Df,Tf,ba=v(()=>{"use strict";oe();Ke();F();Of={name:"base64",summary:"base64 encode/decode data and print to standard output",usage:"base64 [OPTION]... [FILE]",options:["-d, --decode decode data","-w, --wrap=COLS wrap encoded lines after COLS character (default 76, 0 to disable)"," --help display this help and exit"]},Df={decode:{short:"d",long:"decode",type:"boolean"},wrap:{short:"w",long:"wrap",type:"number",default:76}},Tf={name:"base64",async execute(t,e){if(N(t))return C(Of);let r=G("base64",t,Df);if(!r.ok)return r.error;let n=r.result.flags.decode,s=r.result.flags.wrap,i=r.result.positional,a=await He(e,i,{cmdName:"base64"});if(!a.ok)return a.error;let o=a.content;try{if(n){let l=o.replace(/\s/g,"");return{stdout:Buffer.from(l,"base64").toString("utf-8"),stderr:"",exitCode:0}}let c=Buffer.from(o).toString("base64");if(s>0){let l=[];for(let u=0;u<c.length;u+=s)l.push(c.slice(u,u+s));c=l.join(`
359
359
  `)+(c.length>0?`
360
360
  `:"")}return{stdout:c,stderr:"",exitCode:0}}catch{return{stdout:"",stderr:`base64: invalid input
361
- `,exitCode:1}}}}});var wa={};O(wa,{diffCommand:()=>$f});import*as ga from"diff";var If,Rf,$f,Ea=N(()=>{"use strict";ae();L();If={name:"diff",summary:"compare files line by line",usage:"diff [OPTION]... FILE1 FILE2",options:["-u, --unified output unified diff format (default)","-q, --brief report only whether files differ","-s, --report-identical-files report when files are the same","-i, --ignore-case ignore case differences"," --help display this help and exit"]},Rf={unified:{short:"u",long:"unified",type:"boolean"},brief:{short:"q",long:"brief",type:"boolean"},reportSame:{short:"s",long:"report-identical-files",type:"boolean"},ignoreCase:{short:"i",long:"ignore-case",type:"boolean"}},$f={name:"diff",async execute(t,e){if(C(t))return A(If);let r=H("diff",t,Rf);if(!r.ok)return r.error;let n=r.result.flags.brief,s=r.result.flags.reportSame,i=r.result.flags.ignoreCase,a=r.result.positional;if(r.result.flags.unified,a.length<2)return{stdout:"",stderr:`diff: missing operand
361
+ `,exitCode:1}}}}});var xa={};D(xa,{diffCommand:()=>Mf});import*as Sa from"diff";var Lf,Ff,Mf,Aa=v(()=>{"use strict";oe();F();Lf={name:"diff",summary:"compare files line by line",usage:"diff [OPTION]... FILE1 FILE2",options:["-u, --unified output unified diff format (default)","-q, --brief report only whether files differ","-s, --report-identical-files report when files are the same","-i, --ignore-case ignore case differences"," --help display this help and exit"]},Ff={unified:{short:"u",long:"unified",type:"boolean"},brief:{short:"q",long:"brief",type:"boolean"},reportSame:{short:"s",long:"report-identical-files",type:"boolean"},ignoreCase:{short:"i",long:"ignore-case",type:"boolean"}},Mf={name:"diff",async execute(t,e){if(N(t))return C(Lf);let r=G("diff",t,Ff);if(!r.ok)return r.error;let n=r.result.flags.brief,s=r.result.flags.reportSame,i=r.result.flags.ignoreCase,a=r.result.positional;if(r.result.flags.unified,a.length<2)return{stdout:"",stderr:`diff: missing operand
362
362
  `,exitCode:2};let o,c,[l,u]=a;try{o=l==="-"?e.stdin:await e.fs.readFile(e.fs.resolvePath(e.cwd,l))}catch{return{stdout:"",stderr:`diff: ${l}: No such file or directory
363
363
  `,exitCode:2}}try{c=u==="-"?e.stdin:await e.fs.readFile(e.fs.resolvePath(e.cwd,u))}catch{return{stdout:"",stderr:`diff: ${u}: No such file or directory
364
364
  `,exitCode:2}}let f=o,d=c;return i&&(f=f.toLowerCase(),d=d.toLowerCase()),f===d?s?{stdout:`Files ${l} and ${u} are identical
365
365
  `,stderr:"",exitCode:0}:{stdout:"",stderr:"",exitCode:0}:n?{stdout:`Files ${l} and ${u} differ
366
- `,stderr:"",exitCode:1}:{stdout:ga.createTwoFilesPatch(l,u,o,c,"","",{context:3}),stderr:"",exitCode:1}}}});var ba={};O(ba,{dateCommand:()=>Ff});function fe(t,e=2){return String(t).padStart(e,"0")}function Lf(t){let e=-t.getTimezoneOffset();return`${e>=0?"+":"-"}${fe(Math.floor(Math.abs(e)/60))}${fe(Math.abs(e)%60)}`}function Xt(t,e,r){let n=r?{Y:t.getUTCFullYear(),m:t.getUTCMonth(),D:t.getUTCDate(),H:t.getUTCHours(),M:t.getUTCMinutes(),S:t.getUTCSeconds(),w:t.getUTCDay()}:{Y:t.getFullYear(),m:t.getMonth(),D:t.getDate(),H:t.getHours(),M:t.getMinutes(),S:t.getSeconds(),w:t.getDay()},s="",i=0;for(;i<e.length;){if(e[i]==="%"&&i+1<e.length){let a=e[++i];switch(a){case"%":s+="%";break;case"a":s+=Of[n.w];break;case"b":case"h":s+=Df[n.m];break;case"d":s+=fe(n.D);break;case"e":s+=String(n.D).padStart(2," ");break;case"F":s+=`${n.Y}-${fe(n.m+1)}-${fe(n.D)}`;break;case"H":s+=fe(n.H);break;case"I":s+=fe(n.H%12||12);break;case"m":s+=fe(n.m+1);break;case"M":s+=fe(n.M);break;case"n":s+=`
367
- `;break;case"p":s+=n.H<12?"AM":"PM";break;case"P":s+=n.H<12?"am":"pm";break;case"R":s+=`${fe(n.H)}:${fe(n.M)}`;break;case"s":s+=Math.floor(t.getTime()/1e3);break;case"S":s+=fe(n.S);break;case"t":s+=" ";break;case"T":s+=`${fe(n.H)}:${fe(n.M)}:${fe(n.S)}`;break;case"u":s+=n.w||7;break;case"w":s+=n.w;break;case"y":s+=fe(n.Y%100);break;case"Y":s+=n.Y;break;case"z":s+=r?"+0000":Lf(t);break;case"Z":s+=r?"UTC":Intl.DateTimeFormat().resolvedOptions().timeZone;break;default:s+=`%${a}`}}else s+=e[i];i++}return s}function Tf(t){let e=new Date(t);if(!Number.isNaN(e.getTime()))return e;if(/^\d+$/.test(t))return new Date(Number.parseInt(t,10)*1e3);let r=t.toLowerCase();return r==="now"||r==="today"?new Date:r==="yesterday"?new Date(Date.now()-864e5):r==="tomorrow"?new Date(Date.now()+864e5):null}var Pf,Of,Df,Ff,xa=N(()=>{"use strict";L();Pf={name:"date",summary:"display the current time in the given FORMAT",usage:"date [OPTION]... [+FORMAT]",options:["-d, --date=STRING display time described by STRING","-u, --utc print Coordinated Universal Time (UTC)","-I, --iso-8601 output date/time in ISO 8601 format","-R, --rfc-email output RFC 5322 date format"," --help display this help and exit"]},Of=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Df=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];Ff={name:"date",async execute(t,e){if(C(t))return A(Pf);let r=!1,n=null,s=null,i=!1,a=!1;for(let l=0;l<t.length;l++){let u=t[l];if(u==="-u"||u==="--utc")r=!0;else if(u==="-d"||u==="--date")n=t[++l]??"";else if(u.startsWith("--date="))n=u.slice(7);else if(u==="-I"||u==="--iso-8601")i=!0;else if(u==="-R"||u==="--rfc-email")a=!0;else if(u.startsWith("+"))s=u.slice(1);else{if(u.startsWith("--"))return T("date",u);if(u.startsWith("-"))for(let f of u.slice(1))if(f==="u")r=!0;else if(f==="I")i=!0;else if(f==="R")a=!0;else return T("date",`-${f}`)}}let o=n!==null?Tf(n):new Date;if(!o)return{stdout:"",stderr:`date: invalid date '${n}'
368
- `,exitCode:1};let c;return s?c=Xt(o,s,r):i?c=Xt(o,"%Y-%m-%dT%H:%M:%S%z",r):a?c=Xt(o,"%a, %d %b %Y %H:%M:%S %z",r):c=Xt(o,"%a %b %e %H:%M:%S %Z %Y",r),{stdout:`${c}
369
- `,stderr:"",exitCode:0}}}});var Sa={};O(Sa,{sleepCommand:()=>Wf});function _f(t){let e=t.match(/^(\d+\.?\d*)(s|m|h|d)?$/);if(!e)return null;let r=parseFloat(e[1]);switch(e[2]||"s"){case"s":return r*1e3;case"m":return r*60*1e3;case"h":return r*60*60*1e3;case"d":return r*24*60*60*1e3;default:return null}}var Mf,Wf,Aa=N(()=>{"use strict";L();Mf={name:"sleep",summary:"delay for a specified amount of time",usage:"sleep NUMBER[SUFFIX]",description:`Pause for NUMBER seconds. SUFFIX may be:
366
+ `,stderr:"",exitCode:1}:{stdout:Sa.createTwoFilesPatch(l,u,o,c,"","",{context:3}),stderr:"",exitCode:1}}}});var Ca={};D(Ca,{dateCommand:()=>zf});function de(t,e=2){return String(t).padStart(e,"0")}function Hf(t){let e=-t.getTimezoneOffset();return`${e>=0?"+":"-"}${de(Math.floor(Math.abs(e)/60))}${de(Math.abs(e)%60)}`}function tr(t,e,r){let n=r?{Y:t.getUTCFullYear(),m:t.getUTCMonth(),D:t.getUTCDate(),H:t.getUTCHours(),M:t.getUTCMinutes(),S:t.getUTCSeconds(),w:t.getUTCDay()}:{Y:t.getFullYear(),m:t.getMonth(),D:t.getDate(),H:t.getHours(),M:t.getMinutes(),S:t.getSeconds(),w:t.getDay()},s="",i=0;for(;i<e.length;){if(e[i]==="%"&&i+1<e.length){let a=e[++i];switch(a){case"%":s+="%";break;case"a":s+=Wf[n.w];break;case"b":case"h":s+=Bf[n.m];break;case"d":s+=de(n.D);break;case"e":s+=String(n.D).padStart(2," ");break;case"F":s+=`${n.Y}-${de(n.m+1)}-${de(n.D)}`;break;case"H":s+=de(n.H);break;case"I":s+=de(n.H%12||12);break;case"m":s+=de(n.m+1);break;case"M":s+=de(n.M);break;case"n":s+=`
367
+ `;break;case"p":s+=n.H<12?"AM":"PM";break;case"P":s+=n.H<12?"am":"pm";break;case"R":s+=`${de(n.H)}:${de(n.M)}`;break;case"s":s+=Math.floor(t.getTime()/1e3);break;case"S":s+=de(n.S);break;case"t":s+=" ";break;case"T":s+=`${de(n.H)}:${de(n.M)}:${de(n.S)}`;break;case"u":s+=n.w||7;break;case"w":s+=n.w;break;case"y":s+=de(n.Y%100);break;case"Y":s+=n.Y;break;case"z":s+=r?"+0000":Hf(t);break;case"Z":s+=r?"UTC":Intl.DateTimeFormat().resolvedOptions().timeZone;break;default:s+=`%${a}`}}else s+=e[i];i++}return s}function Uf(t){let e=new Date(t);if(!Number.isNaN(e.getTime()))return e;if(/^\d+$/.test(t))return new Date(Number.parseInt(t,10)*1e3);let r=t.toLowerCase();return r==="now"||r==="today"?new Date:r==="yesterday"?new Date(Date.now()-864e5):r==="tomorrow"?new Date(Date.now()+864e5):null}var _f,Wf,Bf,zf,Na=v(()=>{"use strict";F();_f={name:"date",summary:"display the current time in the given FORMAT",usage:"date [OPTION]... [+FORMAT]",options:["-d, --date=STRING display time described by STRING","-u, --utc print Coordinated Universal Time (UTC)","-I, --iso-8601 output date/time in ISO 8601 format","-R, --rfc-email output RFC 5322 date format"," --help display this help and exit"]},Wf=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Bf=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];zf={name:"date",async execute(t,e){if(N(t))return C(_f);let r=!1,n=null,s=null,i=!1,a=!1;for(let l=0;l<t.length;l++){let u=t[l];if(u==="-u"||u==="--utc")r=!0;else if(u==="-d"||u==="--date")n=t[++l]??"";else if(u.startsWith("--date="))n=u.slice(7);else if(u==="-I"||u==="--iso-8601")i=!0;else if(u==="-R"||u==="--rfc-email")a=!0;else if(u.startsWith("+"))s=u.slice(1);else{if(u.startsWith("--"))return M("date",u);if(u.startsWith("-"))for(let f of u.slice(1))if(f==="u")r=!0;else if(f==="I")i=!0;else if(f==="R")a=!0;else return M("date",`-${f}`)}}let o=n!==null?Uf(n):new Date;if(!o)return{stdout:"",stderr:`date: invalid date '${n}'
368
+ `,exitCode:1};let c;return s?c=tr(o,s,r):i?c=tr(o,"%Y-%m-%dT%H:%M:%S%z",r):a?c=tr(o,"%a, %d %b %Y %H:%M:%S %z",r):c=tr(o,"%a %b %e %H:%M:%S %Z %Y",r),{stdout:`${c}
369
+ `,stderr:"",exitCode:0}}}});var va={};D(va,{sleepCommand:()=>qf});function jf(t){let e=t.match(/^(\d+\.?\d*)(s|m|h|d)?$/);if(!e)return null;let r=parseFloat(e[1]);switch(e[2]||"s"){case"s":return r*1e3;case"m":return r*60*1e3;case"h":return r*60*60*1e3;case"d":return r*24*60*60*1e3;default:return null}}var Gf,qf,ka=v(()=>{"use strict";F();Gf={name:"sleep",summary:"delay for a specified amount of time",usage:"sleep NUMBER[SUFFIX]",description:`Pause for NUMBER seconds. SUFFIX may be:
370
370
  s - seconds (default)
371
371
  m - minutes
372
372
  h - hours
373
373
  d - days
374
374
 
375
- NUMBER may be a decimal number.`,options:[" --help display this help and exit"]};Wf={name:"sleep",async execute(t,e){if(C(t))return A(Mf);if(t.length===0)return{stdout:"",stderr:`sleep: missing operand
376
- `,exitCode:1};let r=0;for(let n of t){let s=_f(n);if(s===null)return{stdout:"",stderr:`sleep: invalid time interval '${n}'
377
- `,exitCode:1};r+=s}return e.sleep?await e.sleep(r):await new Promise(n=>setTimeout(n,r)),{stdout:"",stderr:"",exitCode:0}}}});var Ca={};O(Ca,{timeoutCommand:()=>Uf});function Hf(t){let e=t.match(/^(\d+\.?\d*)(s|m|h|d)?$/);if(!e)return null;let r=parseFloat(e[1]);switch(e[2]||"s"){case"s":return r*1e3;case"m":return r*60*1e3;case"h":return r*60*60*1e3;case"d":return r*24*60*60*1e3;default:return null}}var Bf,Uf,Na=N(()=>{"use strict";L();Bf={name:"timeout",summary:"run a command with a time limit",usage:"timeout [OPTION] DURATION COMMAND [ARG]...",description:`Start COMMAND, and kill it if still running after DURATION.
375
+ NUMBER may be a decimal number.`,options:[" --help display this help and exit"]};qf={name:"sleep",async execute(t,e){if(N(t))return C(Gf);if(t.length===0)return{stdout:"",stderr:`sleep: missing operand
376
+ `,exitCode:1};let r=0;for(let n of t){let s=jf(n);if(s===null)return{stdout:"",stderr:`sleep: invalid time interval '${n}'
377
+ `,exitCode:1};r+=s}return e.sleep?await e.sleep(r):await new Promise(n=>setTimeout(n,r)),{stdout:"",stderr:"",exitCode:0}}}});var Ia={};D(Ia,{timeoutCommand:()=>Qf});function Zf(t){let e=t.match(/^(\d+\.?\d*)(s|m|h|d)?$/);if(!e)return null;let r=parseFloat(e[1]);switch(e[2]||"s"){case"s":return r*1e3;case"m":return r*60*1e3;case"h":return r*60*60*1e3;case"d":return r*24*60*60*1e3;default:return null}}var Vf,Qf,$a=v(()=>{"use strict";F();Vf={name:"timeout",summary:"run a command with a time limit",usage:"timeout [OPTION] DURATION COMMAND [ARG]...",description:`Start COMMAND, and kill it if still running after DURATION.
378
378
 
379
379
  DURATION is a number with optional suffix:
380
380
  s - seconds (default)
381
381
  m - minutes
382
382
  h - hours
383
- d - days`,options:["-k, --kill-after=DURATION send KILL signal after DURATION if still running","-s, --signal=SIGNAL specify signal to send (default: TERM)"," --preserve-status exit with same status as COMMAND, even on timeout"," --foreground run command in foreground"," --help display this help and exit"]};Uf={name:"timeout",async execute(t,e){if(C(t))return A(Bf);let r=!1,n=0;for(let d=0;d<t.length;d++){let h=t[d];if(h==="--preserve-status")r=!0,n=d+1;else if(h==="--foreground")n=d+1;else if(h==="-k"||h==="--kill-after")d++,n=d+1;else if(h.startsWith("--kill-after="))n=d+1;else if(h==="-s"||h==="--signal")d++,n=d+1;else if(h.startsWith("--signal="))n=d+1;else{if(h.startsWith("--")&&h!=="--")return T("timeout",h);if(h.startsWith("-")&&h.length>1&&h!=="--")if(h.startsWith("-k"))n=d+1;else if(h.startsWith("-s"))n=d+1;else return T("timeout",h);else{n=d;break}}}let s=t.slice(n);if(s.length===0)return{stdout:"",stderr:`timeout: missing operand
384
- `,exitCode:1};let i=s[0],a=Hf(i);if(a===null)return{stdout:"",stderr:`timeout: invalid time interval '${i}'
383
+ d - days`,options:["-k, --kill-after=DURATION send KILL signal after DURATION if still running","-s, --signal=SIGNAL specify signal to send (default: TERM)"," --preserve-status exit with same status as COMMAND, even on timeout"," --foreground run command in foreground"," --help display this help and exit"]};Qf={name:"timeout",async execute(t,e){if(N(t))return C(Vf);let r=!1,n=0;for(let d=0;d<t.length;d++){let h=t[d];if(h==="--preserve-status")r=!0,n=d+1;else if(h==="--foreground")n=d+1;else if(h==="-k"||h==="--kill-after")d++,n=d+1;else if(h.startsWith("--kill-after="))n=d+1;else if(h==="-s"||h==="--signal")d++,n=d+1;else if(h.startsWith("--signal="))n=d+1;else{if(h.startsWith("--")&&h!=="--")return M("timeout",h);if(h.startsWith("-")&&h.length>1&&h!=="--")if(h.startsWith("-k"))n=d+1;else if(h.startsWith("-s"))n=d+1;else return M("timeout",h);else{n=d;break}}}let s=t.slice(n);if(s.length===0)return{stdout:"",stderr:`timeout: missing operand
384
+ `,exitCode:1};let i=s[0],a=Zf(i);if(a===null)return{stdout:"",stderr:`timeout: invalid time interval '${i}'
385
385
  `,exitCode:1};let o=s.slice(1);if(o.length===0)return{stdout:"",stderr:`timeout: missing operand
386
386
  `,exitCode:1};if(!e.exec)return{stdout:"",stderr:`timeout: exec not available
387
- `,exitCode:1};let c=o.map(d=>d.includes(" ")||d.includes(" ")?`'${d.replace(/'/g,"'\\''")}'`:d).join(" "),l=new Promise(d=>{setTimeout(()=>d({timedOut:!0}),a)}),u=e.exec(c,{cwd:e.cwd}).then(d=>({timedOut:!1,result:d})),f=await Promise.race([l,u]);return f.timedOut?{stdout:"",stderr:"",exitCode:124}:f.result}}});var va={};O(va,{seqCommand:()=>zf});var zf,ka=N(()=>{"use strict";zf={name:"seq",async execute(t){let e=`
387
+ `,exitCode:1};let c=o.map(d=>d.includes(" ")||d.includes(" ")?`'${d.replace(/'/g,"'\\''")}'`:d).join(" "),l=new Promise(d=>{setTimeout(()=>d({timedOut:!0}),a)}),u=e.exec(c,{cwd:e.cwd}).then(d=>({timedOut:!1,result:d})),f=await Promise.race([l,u]);return f.timedOut?{stdout:"",stderr:"",exitCode:124}:f.result}}});var Ra={};D(Ra,{seqCommand:()=>Kf});var Kf,Pa=v(()=>{"use strict";Kf={name:"seq",async execute(t){let e=`
388
388
  `,r=!1,n=[],s=0;for(;s<t.length;){let p=t[s];if(p==="-s"&&s+1<t.length){e=t[s+1],s+=2;continue}if(p==="-w"){r=!0,s++;continue}if(p==="--"){s++;break}if(p.startsWith("-")&&p!=="-"){if(p.startsWith("-s")&&p.length>2){e=p.slice(2),s++;continue}if((p==="-ws"||p==="-sw")&&(r=!0,s+1<t.length)){e=t[s+1],s+=2;continue}}n.push(p),s++}for(;s<t.length;)n.push(t[s]),s++;if(n.length===0)return{stdout:"",stderr:`seq: missing operand
389
- `,exitCode:1};let i=1,a=1,o;if(n.length===1?o=parseFloat(n[0]):n.length===2?(i=parseFloat(n[0]),o=parseFloat(n[1])):(i=parseFloat(n[0]),a=parseFloat(n[1]),o=parseFloat(n[2])),Number.isNaN(i)||Number.isNaN(a)||Number.isNaN(o))return{stdout:"",stderr:`seq: invalid floating point argument: '${n.find(b=>Number.isNaN(parseFloat(b)))}'
389
+ `,exitCode:1};let i=1,a=1,o;if(n.length===1?o=parseFloat(n[0]):n.length===2?(i=parseFloat(n[0]),o=parseFloat(n[1])):(i=parseFloat(n[0]),a=parseFloat(n[1]),o=parseFloat(n[2])),Number.isNaN(i)||Number.isNaN(a)||Number.isNaN(o))return{stdout:"",stderr:`seq: invalid floating point argument: '${n.find(E=>Number.isNaN(parseFloat(E)))}'
390
390
  `,exitCode:1};if(a===0)return{stdout:"",stderr:`seq: invalid Zero increment value: '0'
391
- `,exitCode:1};let c=[],l=p=>{let b=String(p),w=b.indexOf(".");return w===-1?0:b.length-w-1},u=Math.max(l(i),l(a),l(o)),f=1e5,d=0;if(a>0)for(let p=i;p<=o+1e-10&&!(d++>f);p+=a)c.push(u>0?p.toFixed(u):String(Math.round(p)));else for(let p=i;p>=o-1e-10&&!(d++>f);p+=a)c.push(u>0?p.toFixed(u):String(Math.round(p)));if(r&&c.length>0){let p=Math.max(...c.map(b=>b.replace("-","").length));for(let b=0;b<c.length;b++){let w=c[b].startsWith("-"),E=(w?c[b].slice(1):c[b]).padStart(p,"0");c[b]=w?`-${E}`:E}}let h=c.join(e);return{stdout:h?`${h}
392
- `:"",stderr:"",exitCode:0}}}});var Ia={};O(Ia,{exprCommand:()=>Gf});function jf(t){if(t.length===1)return t[0];let e=0;function r(){let l=n();for(;e<t.length&&t[e]==="|";){e++;let u=n();if(l!=="0"&&l!=="")return l;l=u}return l}function n(){let l=s();for(;e<t.length&&t[e]==="&";){e++;let u=s();(l==="0"||l===""||u==="0"||u==="")&&(l="0")}return l}function s(){let l=i();for(;e<t.length;){let u=t[e];if(["=","!=","<",">","<=",">="].includes(u)){e++;let f=i(),d=parseInt(l,10),h=parseInt(f,10),p=!Number.isNaN(d)&&!Number.isNaN(h),b;u==="="?b=p?d===h:l===f:u==="!="?b=p?d!==h:l!==f:u==="<"?b=p?d<h:l<f:u===">"?b=p?d>h:l>f:u==="<="?b=p?d<=h:l<=f:b=p?d>=h:l>=f,l=b?"1":"0"}else break}return l}function i(){let l=a();for(;e<t.length;){let u=t[e];if(u==="+"||u==="-"){e++;let f=a(),d=parseInt(l,10),h=parseInt(f,10);if(Number.isNaN(d)||Number.isNaN(h))throw new Error("non-integer argument");l=String(u==="+"?d+h:d-h)}else break}return l}function a(){let l=o();for(;e<t.length;){let u=t[e];if(u==="*"||u==="/"||u==="%"){e++;let f=o(),d=parseInt(l,10),h=parseInt(f,10);if(Number.isNaN(d)||Number.isNaN(h))throw new Error("non-integer argument");if((u==="/"||u==="%")&&h===0)throw new Error("division by zero");u==="*"?l=String(d*h):u==="/"?l=String(Math.trunc(d/h)):l=String(d%h)}else break}return l}function o(){let l=c();for(;e<t.length&&t[e]===":";){e++;let u=c(),f=new RegExp(`^${u}`),d=l.match(f);d?l=d[1]!==void 0?d[1]:String(d[0].length):l="0"}return l}function c(){if(e>=t.length)throw new Error("syntax error");let l=t[e];if(l==="match"){e++;let u=c(),f=c(),d=new RegExp(f),h=u.match(d);return h?h[1]!==void 0?h[1]:String(h[0].length):"0"}if(l==="substr"){e++;let u=c(),f=parseInt(c(),10),d=parseInt(c(),10);if(Number.isNaN(f)||Number.isNaN(d))throw new Error("non-integer argument");return u.substring(f-1,f-1+d)}if(l==="index"){e++;let u=c(),f=c();for(let d=0;d<u.length;d++)if(f.includes(u[d]))return String(d+1);return"0"}if(l==="length"){e++;let u=c();return String(u.length)}if(l==="("){e++;let u=r();if(e>=t.length||t[e]!==")")throw new Error("syntax error");return e++,u}return e++,l}return r()}var Gf,Ra=N(()=>{"use strict";Gf={name:"expr",async execute(t,e){if(t.length===0)return{stdout:"",stderr:`expr: missing operand
393
- `,exitCode:2};try{let r=jf(t),n=r==="0"||r===""?1:0;return{stdout:`${r}
391
+ `,exitCode:1};let c=[],l=p=>{let E=String(p),w=E.indexOf(".");return w===-1?0:E.length-w-1},u=Math.max(l(i),l(a),l(o)),f=1e5,d=0;if(a>0)for(let p=i;p<=o+1e-10&&!(d++>f);p+=a)c.push(u>0?p.toFixed(u):String(Math.round(p)));else for(let p=i;p>=o-1e-10&&!(d++>f);p+=a)c.push(u>0?p.toFixed(u):String(Math.round(p)));if(r&&c.length>0){let p=Math.max(...c.map(E=>E.replace("-","").length));for(let E=0;E<c.length;E++){let w=c[E].startsWith("-"),b=(w?c[E].slice(1):c[E]).padStart(p,"0");c[E]=w?`-${b}`:b}}let h=c.join(e);return{stdout:h?`${h}
392
+ `:"",stderr:"",exitCode:0}}}});var Oa={};D(Oa,{exprCommand:()=>Xf});function Yf(t){if(t.length===1)return t[0];let e=0;function r(){let l=n();for(;e<t.length&&t[e]==="|";){e++;let u=n();if(l!=="0"&&l!=="")return l;l=u}return l}function n(){let l=s();for(;e<t.length&&t[e]==="&";){e++;let u=s();(l==="0"||l===""||u==="0"||u==="")&&(l="0")}return l}function s(){let l=i();for(;e<t.length;){let u=t[e];if(["=","!=","<",">","<=",">="].includes(u)){e++;let f=i(),d=parseInt(l,10),h=parseInt(f,10),p=!Number.isNaN(d)&&!Number.isNaN(h),E;u==="="?E=p?d===h:l===f:u==="!="?E=p?d!==h:l!==f:u==="<"?E=p?d<h:l<f:u===">"?E=p?d>h:l>f:u==="<="?E=p?d<=h:l<=f:E=p?d>=h:l>=f,l=E?"1":"0"}else break}return l}function i(){let l=a();for(;e<t.length;){let u=t[e];if(u==="+"||u==="-"){e++;let f=a(),d=parseInt(l,10),h=parseInt(f,10);if(Number.isNaN(d)||Number.isNaN(h))throw new Error("non-integer argument");l=String(u==="+"?d+h:d-h)}else break}return l}function a(){let l=o();for(;e<t.length;){let u=t[e];if(u==="*"||u==="/"||u==="%"){e++;let f=o(),d=parseInt(l,10),h=parseInt(f,10);if(Number.isNaN(d)||Number.isNaN(h))throw new Error("non-integer argument");if((u==="/"||u==="%")&&h===0)throw new Error("division by zero");u==="*"?l=String(d*h):u==="/"?l=String(Math.trunc(d/h)):l=String(d%h)}else break}return l}function o(){let l=c();for(;e<t.length&&t[e]===":";){e++;let u=c(),f=new RegExp(`^${u}`),d=l.match(f);d?l=d[1]!==void 0?d[1]:String(d[0].length):l="0"}return l}function c(){if(e>=t.length)throw new Error("syntax error");let l=t[e];if(l==="match"){e++;let u=c(),f=c(),d=new RegExp(f),h=u.match(d);return h?h[1]!==void 0?h[1]:String(h[0].length):"0"}if(l==="substr"){e++;let u=c(),f=parseInt(c(),10),d=parseInt(c(),10);if(Number.isNaN(f)||Number.isNaN(d))throw new Error("non-integer argument");return u.substring(f-1,f-1+d)}if(l==="index"){e++;let u=c(),f=c();for(let d=0;d<u.length;d++)if(f.includes(u[d]))return String(d+1);return"0"}if(l==="length"){e++;let u=c();return String(u.length)}if(l==="("){e++;let u=r();if(e>=t.length||t[e]!==")")throw new Error("syntax error");return e++,u}return e++,l}return r()}var Xf,Da=v(()=>{"use strict";Xf={name:"expr",async execute(t,e){if(t.length===0)return{stdout:"",stderr:`expr: missing operand
393
+ `,exitCode:2};try{let r=Yf(t),n=r==="0"||r===""?1:0;return{stdout:`${r}
394
394
  `,stderr:"",exitCode:n}}catch(r){return{stdout:"",stderr:`expr: ${r.message}
395
- `,exitCode:2}}}}});var $a={};O($a,{htmlToMarkdownCommand:()=>Zf});import qf from"turndown";var Vf,Zf,Pa=N(()=>{"use strict";L();Vf={name:"html-to-markdown",summary:"convert HTML to Markdown (BashEnv extension)",usage:"html-to-markdown [OPTION]... [FILE]",description:["Convert HTML content to Markdown format using the turndown library.","This is a non-standard BashEnv extension command, not available in regular bash.","","Read HTML from FILE or standard input and output Markdown to standard output.","Commonly used with curl to convert web pages:"," curl -s https://example.com | html-to-markdown","","Supported HTML elements:"," - Headings (h1-h6) \u2192 # Markdown headings"," - Paragraphs (p) \u2192 Plain text with blank lines"," - Links (a) \u2192 [text](url)"," - Images (img) \u2192 ![alt](src)"," - Bold/Strong \u2192 **text**"," - Italic/Em \u2192 _text_"," - Code (code, pre) \u2192 `inline` or fenced blocks"," - Lists (ul, ol, li) \u2192 - or 1. items"," - Blockquotes \u2192 > quoted text"," - Horizontal rules (hr) \u2192 ---"],options:["-b, --bullet=CHAR bullet character for unordered lists (-, +, or *)","-c, --code=FENCE fence style for code blocks (``` or ~~~)","-r, --hr=STRING string for horizontal rules (default: ---)"," --heading-style=STYLE"," heading style: 'atx' for # headings (default),"," 'setext' for underlined headings (h1/h2 only)"," --help display this help and exit"],examples:["echo '<h1>Hello</h1><p>World</p>' | html-to-markdown","html-to-markdown page.html","curl -s https://example.com | html-to-markdown > page.md"]},Zf={name:"html-to-markdown",async execute(t,e){if(C(t))return A(Vf);let r="-",n="```",s="---",i="atx",a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="-b"||l==="--bullet")r=t[++c]??"-";else if(l.startsWith("--bullet="))r=l.slice(9);else if(l==="-c"||l==="--code")n=t[++c]??"```";else if(l.startsWith("--code="))n=l.slice(7);else if(l==="-r"||l==="--hr")s=t[++c]??"---";else if(l.startsWith("--hr="))s=l.slice(5);else if(l.startsWith("--heading-style=")){let u=l.slice(16);(u==="setext"||u==="atx")&&(i=u)}else if(l==="-")a.push("-");else{if(l.startsWith("--"))return T("html-to-markdown",l);if(l.startsWith("-"))return T("html-to-markdown",l);a.push(l)}}let o;if(a.length===0||a.length===1&&a[0]==="-")o=e.stdin;else try{let c=e.fs.resolvePath(e.cwd,a[0]);o=await e.fs.readFile(c)}catch{return{stdout:"",stderr:`html-to-markdown: ${a[0]}: No such file or directory
396
- `,exitCode:1}}if(!o.trim())return{stdout:"",stderr:"",exitCode:0};try{let c=new qf({bulletListMarker:r,codeBlockStyle:"fenced",fence:n,hr:s,headingStyle:i});return c.remove(["script","style","footer"]),{stdout:`${c.turndown(o).trim()}
395
+ `,exitCode:2}}}}});var Ta={};D(Ta,{htmlToMarkdownCommand:()=>td});import Jf from"turndown";var ed,td,La=v(()=>{"use strict";F();ed={name:"html-to-markdown",summary:"convert HTML to Markdown (BashEnv extension)",usage:"html-to-markdown [OPTION]... [FILE]",description:["Convert HTML content to Markdown format using the turndown library.","This is a non-standard BashEnv extension command, not available in regular bash.","","Read HTML from FILE or standard input and output Markdown to standard output.","Commonly used with curl to convert web pages:"," curl -s https://example.com | html-to-markdown","","Supported HTML elements:"," - Headings (h1-h6) \u2192 # Markdown headings"," - Paragraphs (p) \u2192 Plain text with blank lines"," - Links (a) \u2192 [text](url)"," - Images (img) \u2192 ![alt](src)"," - Bold/Strong \u2192 **text**"," - Italic/Em \u2192 _text_"," - Code (code, pre) \u2192 `inline` or fenced blocks"," - Lists (ul, ol, li) \u2192 - or 1. items"," - Blockquotes \u2192 > quoted text"," - Horizontal rules (hr) \u2192 ---"],options:["-b, --bullet=CHAR bullet character for unordered lists (-, +, or *)","-c, --code=FENCE fence style for code blocks (``` or ~~~)","-r, --hr=STRING string for horizontal rules (default: ---)"," --heading-style=STYLE"," heading style: 'atx' for # headings (default),"," 'setext' for underlined headings (h1/h2 only)"," --help display this help and exit"],examples:["echo '<h1>Hello</h1><p>World</p>' | html-to-markdown","html-to-markdown page.html","curl -s https://example.com | html-to-markdown > page.md"]},td={name:"html-to-markdown",async execute(t,e){if(N(t))return C(ed);let r="-",n="```",s="---",i="atx",a=[];for(let c=0;c<t.length;c++){let l=t[c];if(l==="-b"||l==="--bullet")r=t[++c]??"-";else if(l.startsWith("--bullet="))r=l.slice(9);else if(l==="-c"||l==="--code")n=t[++c]??"```";else if(l.startsWith("--code="))n=l.slice(7);else if(l==="-r"||l==="--hr")s=t[++c]??"---";else if(l.startsWith("--hr="))s=l.slice(5);else if(l.startsWith("--heading-style=")){let u=l.slice(16);(u==="setext"||u==="atx")&&(i=u)}else if(l==="-")a.push("-");else{if(l.startsWith("--"))return M("html-to-markdown",l);if(l.startsWith("-"))return M("html-to-markdown",l);a.push(l)}}let o;if(a.length===0||a.length===1&&a[0]==="-")o=e.stdin;else try{let c=e.fs.resolvePath(e.cwd,a[0]);o=await e.fs.readFile(c)}catch{return{stdout:"",stderr:`html-to-markdown: ${a[0]}: No such file or directory
396
+ `,exitCode:1}}if(!o.trim())return{stdout:"",stderr:"",exitCode:0};try{let c=new Jf({bulletListMarker:r,codeBlockStyle:"fenced",fence:n,hr:s,headingStyle:i});return c.remove(["script","style","footer"]),{stdout:`${c.turndown(o).trim()}
397
397
  `,stderr:"",exitCode:0}}catch(c){return{stdout:"",stderr:`html-to-markdown: conversion error: ${c.message}
398
- `,exitCode:1}}}}});var Oa={};O(Oa,{helpCommand:()=>Xf});function Kf(t){let e=[],r=new Set(t);e.push(`Available commands:
399
- `);let n=[];for(let[s,i]of Object.entries(Qf)){let a=i.filter(o=>r.has(o));if(a.length>0){e.push(` ${s}:`),e.push(` ${a.join(", ")}
398
+ `,exitCode:1}}}}});var Fa={};D(Fa,{helpCommand:()=>sd});function nd(t){let e=[],r=new Set(t);e.push(`Available commands:
399
+ `);let n=[];for(let[s,i]of Object.entries(rd)){let a=i.filter(o=>r.has(o));if(a.length>0){e.push(` ${s}:`),e.push(` ${a.join(", ")}
400
400
  `);for(let o of a)r.delete(o)}}for(let s of r)n.push(s);return n.length>0&&(e.push(" Other:"),e.push(` ${n.sort().join(", ")}
401
401
  `)),e.push("Use '<command> --help' for details on a specific command."),`${e.join(`
402
402
  `)}
403
- `}var Qf,Xf,Da=N(()=>{"use strict";Qf={"File operations":["ls","cat","head","tail","wc","touch","mkdir","rm","cp","mv","ln","chmod","stat","readlink"],"Text processing":["grep","sed","awk","sort","uniq","cut","tr","tee","diff"],Search:["find"],"Navigation & paths":["pwd","basename","dirname","tree","du"],"Environment & shell":["echo","printf","env","printenv","export","alias","unalias","history","clear","true","false","bash","sh"],"Data processing":["xargs","jq","base64","date"],Network:["curl","html-to-markdown"]};Xf={name:"help",async execute(t,e){if(t.includes("--help")||t.includes("-h"))return{stdout:`help - display available commands
403
+ `}var rd,sd,Ma=v(()=>{"use strict";rd={"File operations":["ls","cat","head","tail","wc","touch","mkdir","rm","cp","mv","ln","chmod","stat","readlink"],"Text processing":["grep","sed","awk","sort","uniq","cut","tr","tee","diff"],Search:["find"],"Navigation & paths":["pwd","basename","dirname","tree","du"],"Environment & shell":["echo","printf","env","printenv","export","alias","unalias","history","clear","true","false","bash","sh"],"Data processing":["xargs","jq","base64","date"],Network:["curl","html-to-markdown"]};sd={name:"help",async execute(t,e){if(t.includes("--help")||t.includes("-h"))return{stdout:`help - display available commands
404
404
 
405
405
  Usage: help [command]
406
406
 
@@ -409,49 +409,49 @@ Options:
409
409
 
410
410
  If a command name is provided, shows help for that command.
411
411
  Otherwise, lists all available commands.
412
- `,stderr:"",exitCode:0};if(t.length>0&&e.exec){let n=t[0];return e.exec(`${n} --help`,{cwd:e.cwd})}let r=e.getRegisteredCommands?.()??[];return{stdout:Kf(r),stderr:"",exitCode:0}}}});var La={};O(La,{whichCommand:()=>ed});var Yf,Jf,ed,Ta=N(()=>{"use strict";ae();L();Yf={name:"which",summary:"locate a command",usage:"which [-as] program ...",options:["-a List all instances of executables found","-s No output, just return 0 if found, 1 if not","--help display this help and exit"]},Jf={showAll:{short:"a",type:"boolean"},silent:{short:"s",type:"boolean"}},ed={name:"which",async execute(t,e){if(C(t))return A(Yf);let r=H("which",t,Jf);if(!r.ok)return r.error;let n=r.result.flags.showAll,s=r.result.flags.silent,i=r.result.positional;if(i.length===0)return{stdout:"",stderr:"",exitCode:1};let o=(e.env.PATH||"/bin:/usr/bin").split(":"),c="",l=!0;for(let u of i){let f=!1;for(let d of o){if(!d)continue;let h=`${d}/${u}`;if(await e.fs.exists(h)&&(f=!0,s||(c+=`${h}
413
- `),!n))break}f||(l=!1)}return{stdout:c,stderr:"",exitCode:l?0:1}}}});function rn(t){let e=t.indexOf("=");if(e>=0){let r=t.slice(0,e),n=t.slice(e+1);return r?`${encodeURIComponent(r)}=${encodeURIComponent(n)}`:encodeURIComponent(n)}return encodeURIComponent(t)}function nn(t){let e=t.indexOf("=");if(e<0)return null;let r=t.slice(0,e),n=t.slice(e+1),s,i,a=n.match(/;type=([^;]+)$/);a&&(i=a[1],n=n.slice(0,-a[0].length));let o=n.match(/;filename=([^;]+)/);return o&&(s=o[1],n=n.replace(o[0],"")),(n.startsWith("@")||n.startsWith("<"))&&(s=s??n.slice(1).split("/").pop()),{name:r,value:n,filename:s,contentType:i}}function Fa(t,e){let r=`----CurlFormBoundary${Date.now().toString(36)}`,n=[];for(let s of t){let i=s.value;if(i.startsWith("@")||i.startsWith("<")){let o=i.slice(1);i=e.get(o)??""}let a=`--${r}\r
412
+ `,stderr:"",exitCode:0};if(t.length>0&&e.exec){let n=t[0];return e.exec(`${n} --help`,{cwd:e.cwd})}let r=e.getRegisteredCommands?.()??[];return{stdout:nd(r),stderr:"",exitCode:0}}}});var _a={};D(_a,{whichCommand:()=>od});var id,ad,od,Wa=v(()=>{"use strict";oe();F();id={name:"which",summary:"locate a command",usage:"which [-as] program ...",options:["-a List all instances of executables found","-s No output, just return 0 if found, 1 if not","--help display this help and exit"]},ad={showAll:{short:"a",type:"boolean"},silent:{short:"s",type:"boolean"}},od={name:"which",async execute(t,e){if(N(t))return C(id);let r=G("which",t,ad);if(!r.ok)return r.error;let n=r.result.flags.showAll,s=r.result.flags.silent,i=r.result.positional;if(i.length===0)return{stdout:"",stderr:"",exitCode:1};let o=(e.env.PATH||"/bin:/usr/bin").split(":"),c="",l=!0;for(let u of i){let f=!1;for(let d of o){if(!d)continue;let h=`${d}/${u}`;if(await e.fs.exists(h)&&(f=!0,s||(c+=`${h}
413
+ `),!n))break}f||(l=!1)}return{stdout:c,stderr:"",exitCode:l?0:1}}}});function an(t){let e=t.indexOf("=");if(e>=0){let r=t.slice(0,e),n=t.slice(e+1);return r?`${encodeURIComponent(r)}=${encodeURIComponent(n)}`:encodeURIComponent(n)}return encodeURIComponent(t)}function on(t){let e=t.indexOf("=");if(e<0)return null;let r=t.slice(0,e),n=t.slice(e+1),s,i,a=n.match(/;type=([^;]+)$/);a&&(i=a[1],n=n.slice(0,-a[0].length));let o=n.match(/;filename=([^;]+)/);return o&&(s=o[1],n=n.replace(o[0],"")),(n.startsWith("@")||n.startsWith("<"))&&(s=s??n.slice(1).split("/").pop()),{name:r,value:n,filename:s,contentType:i}}function Ba(t,e){let r=`----CurlFormBoundary${Date.now().toString(36)}`,n=[];for(let s of t){let i=s.value;if(i.startsWith("@")||i.startsWith("<")){let o=i.slice(1);i=e.get(o)??""}let a=`--${r}\r
414
414
  `;s.filename?(a+=`Content-Disposition: form-data; name="${s.name}"; filename="${s.filename}"\r
415
415
  `,s.contentType&&(a+=`Content-Type: ${s.contentType}\r
416
416
  `)):a+=`Content-Disposition: form-data; name="${s.name}"\r
417
417
  `,a+=`\r
418
418
  ${i}\r
419
419
  `,n.push(a)}return n.push(`--${r}--\r
420
- `),{body:n.join(""),boundary:r}}var sn=N(()=>{"use strict"});var Ma,_a=N(()=>{"use strict";Ma={name:"curl",summary:"transfer a URL",usage:"curl [OPTIONS] URL",options:["-X, --request METHOD HTTP method (GET, POST, PUT, DELETE, etc.)","-H, --header HEADER Add header (can be used multiple times)","-d, --data DATA HTTP POST data"," --data-raw DATA HTTP POST data (no @ interpretation)"," --data-binary DATA HTTP POST binary data"," --data-urlencode DATA URL-encode and POST data","-F, --form NAME=VALUE Multipart form data","-u, --user USER:PASS HTTP authentication","-A, --user-agent STR Set User-Agent header","-e, --referer URL Set Referer header","-b, --cookie DATA Send cookies (name=value or @file)","-c, --cookie-jar FILE Save cookies to file","-T, --upload-file FILE Upload file (PUT)","-o, --output FILE Write output to file","-O, --remote-name Write to file named from URL","-I, --head Show headers only (HEAD request)","-i, --include Include response headers in output","-s, --silent Silent mode (no progress)","-S, --show-error Show errors even when silent","-f, --fail Fail silently on HTTP errors (no output)","-L, --location Follow redirects (default)"," --max-redirs NUM Maximum redirects (default: 20)","-m, --max-time SECS Maximum time for request"," --connect-timeout SECS Connection timeout","-w, --write-out FMT Output format after completion","-v, --verbose Verbose output"," --help Display this help and exit","","Note: Network access must be configured via BashEnv network option."," curl is not available by default for security reasons."]}});function Wa(t){let e={method:"GET",headers:{},dataBinary:!1,formFields:[],useRemoteName:!1,headOnly:!1,includeHeaders:!1,silent:!1,showError:!1,failSilently:!1,followRedirects:!0,verbose:!1};for(let r=0;r<t.length;r++){let n=t[r];if(n==="-X"||n==="--request")e.method=t[++r]??"GET";else if(n.startsWith("-X"))e.method=n.slice(2);else if(n.startsWith("--request="))e.method=n.slice(10);else if(n==="-H"||n==="--header"){let s=t[++r];if(s){let i=s.indexOf(":");if(i>0){let a=s.slice(0,i).trim(),o=s.slice(i+1).trim();e.headers[a]=o}}}else if(n.startsWith("--header=")){let s=n.slice(9),i=s.indexOf(":");if(i>0){let a=s.slice(0,i).trim(),o=s.slice(i+1).trim();e.headers[a]=o}}else if(n==="-d"||n==="--data"||n==="--data-raw")e.data=t[++r]??"",e.method==="GET"&&(e.method="POST");else if(n.startsWith("-d"))e.data=n.slice(2),e.method==="GET"&&(e.method="POST");else if(n.startsWith("--data="))e.data=n.slice(7),e.method==="GET"&&(e.method="POST");else if(n.startsWith("--data-raw="))e.data=n.slice(11),e.method==="GET"&&(e.method="POST");else if(n==="--data-binary")e.data=t[++r]??"",e.dataBinary=!0,e.method==="GET"&&(e.method="POST");else if(n.startsWith("--data-binary="))e.data=n.slice(14),e.dataBinary=!0,e.method==="GET"&&(e.method="POST");else if(n==="--data-urlencode"){let s=t[++r]??"";e.data=(e.data?`${e.data}&`:"")+rn(s),e.method==="GET"&&(e.method="POST")}else if(n.startsWith("--data-urlencode=")){let s=n.slice(17);e.data=(e.data?`${e.data}&`:"")+rn(s),e.method==="GET"&&(e.method="POST")}else if(n==="-F"||n==="--form"){let s=t[++r]??"",i=nn(s);i&&e.formFields.push(i),e.method==="GET"&&(e.method="POST")}else if(n.startsWith("--form=")){let s=n.slice(7),i=nn(s);i&&e.formFields.push(i),e.method==="GET"&&(e.method="POST")}else if(n==="-u"||n==="--user")e.user=t[++r];else if(n.startsWith("-u"))e.user=n.slice(2);else if(n.startsWith("--user="))e.user=n.slice(7);else if(n==="-A"||n==="--user-agent")e.headers["User-Agent"]=t[++r]??"";else if(n.startsWith("-A"))e.headers["User-Agent"]=n.slice(2);else if(n.startsWith("--user-agent="))e.headers["User-Agent"]=n.slice(13);else if(n==="-e"||n==="--referer")e.headers.Referer=t[++r]??"";else if(n.startsWith("-e"))e.headers.Referer=n.slice(2);else if(n.startsWith("--referer="))e.headers.Referer=n.slice(10);else if(n==="-b"||n==="--cookie")e.headers.Cookie=t[++r]??"";else if(n.startsWith("-b"))e.headers.Cookie=n.slice(2);else if(n.startsWith("--cookie="))e.headers.Cookie=n.slice(9);else if(n==="-c"||n==="--cookie-jar")e.cookieJar=t[++r];else if(n.startsWith("--cookie-jar="))e.cookieJar=n.slice(13);else if(n==="-T"||n==="--upload-file")e.uploadFile=t[++r],e.method==="GET"&&(e.method="PUT");else if(n.startsWith("--upload-file="))e.uploadFile=n.slice(14),e.method==="GET"&&(e.method="PUT");else if(n==="-m"||n==="--max-time"){let s=parseFloat(t[++r]??"0");!Number.isNaN(s)&&s>0&&(e.timeoutMs=s*1e3)}else if(n.startsWith("--max-time=")){let s=parseFloat(n.slice(11));!Number.isNaN(s)&&s>0&&(e.timeoutMs=s*1e3)}else if(n==="--connect-timeout"){let s=parseFloat(t[++r]??"0");!Number.isNaN(s)&&s>0&&e.timeoutMs===void 0&&(e.timeoutMs=s*1e3)}else if(n.startsWith("--connect-timeout=")){let s=parseFloat(n.slice(18));!Number.isNaN(s)&&s>0&&e.timeoutMs===void 0&&(e.timeoutMs=s*1e3)}else if(n==="-o"||n==="--output")e.outputFile=t[++r];else if(n.startsWith("--output="))e.outputFile=n.slice(9);else if(n==="-O"||n==="--remote-name")e.useRemoteName=!0;else if(n==="-I"||n==="--head")e.headOnly=!0,e.method="HEAD";else if(n==="-i"||n==="--include")e.includeHeaders=!0;else if(n==="-s"||n==="--silent")e.silent=!0;else if(n==="-S"||n==="--show-error")e.showError=!0;else if(n==="-f"||n==="--fail")e.failSilently=!0;else if(n==="-L"||n==="--location")e.followRedirects=!0;else if(n==="--max-redirs")r++;else if(!n.startsWith("--max-redirs="))if(n==="-w"||n==="--write-out")e.writeOut=t[++r];else if(n.startsWith("--write-out="))e.writeOut=n.slice(12);else if(n==="-v"||n==="--verbose")e.verbose=!0;else{if(n.startsWith("--")&&n!=="--")return T("curl",n);if(n.startsWith("-")&&n!=="-")for(let s of n.slice(1))switch(s){case"s":e.silent=!0;break;case"S":e.showError=!0;break;case"f":e.failSilently=!0;break;case"L":e.followRedirects=!0;break;case"I":e.headOnly=!0,e.method="HEAD";break;case"i":e.includeHeaders=!0;break;case"O":e.useRemoteName=!0;break;case"v":e.verbose=!0;break;default:return T("curl",`-${s}`)}else n.startsWith("-")||(e.url=n)}}return e}var Ba=N(()=>{"use strict";L();sn()});function an(t){return Object.entries(t).map(([e,r])=>`${e}: ${r}`).join(`\r
421
- `)}function Ha(t){try{return new URL(t).pathname.split("/").pop()||"index.html"}catch{return"index.html"}}function on(t,e){let r=t;return r=r.replace(/%\{http_code\}/g,String(e.status)),r=r.replace(/%\{content_type\}/g,e.headers["content-type"]||""),r=r.replace(/%\{url_effective\}/g,e.url),r=r.replace(/%\{size_download\}/g,String(e.bodyLength)),r=r.replace(/\\n/g,`
422
- `),r}var Ua=N(()=>{"use strict"});var za={};O(za,{curlCommand:()=>id});async function td(t,e){if(t.uploadFile){let r=e.fs.resolvePath(e.cwd,t.uploadFile);return{body:await e.fs.readFile(r)}}if(t.formFields.length>0){let r=new Map;for(let i of t.formFields)if(i.value.startsWith("@")||i.value.startsWith("<")){let a=e.fs.resolvePath(e.cwd,i.value.slice(1));try{let o=await e.fs.readFile(a);r.set(i.value.slice(1),o)}catch{r.set(i.value.slice(1),"")}}let{body:n,boundary:s}=Fa(t.formFields,r);return{body:n,contentType:`multipart/form-data; boundary=${s}`}}return t.data!==void 0?{body:t.data}:{}}function rd(t,e){let r={...t.headers};if(t.user){let n=Buffer.from(t.user).toString("base64");r.Authorization=`Basic ${n}`}return e&&!r["Content-Type"]&&(r["Content-Type"]=e),r}async function nd(t,e,r){if(!t.cookieJar)return;let n=e["set-cookie"];if(!n)return;let s=r.fs.resolvePath(r.cwd,t.cookieJar);await r.fs.writeFile(s,n)}function sd(t,e,r){let n="";if(t.verbose){n+=`> ${t.method} ${r}
420
+ `),{body:n.join(""),boundary:r}}var ln=v(()=>{"use strict"});var Ha,Ua=v(()=>{"use strict";Ha={name:"curl",summary:"transfer a URL",usage:"curl [OPTIONS] URL",options:["-X, --request METHOD HTTP method (GET, POST, PUT, DELETE, etc.)","-H, --header HEADER Add header (can be used multiple times)","-d, --data DATA HTTP POST data"," --data-raw DATA HTTP POST data (no @ interpretation)"," --data-binary DATA HTTP POST binary data"," --data-urlencode DATA URL-encode and POST data","-F, --form NAME=VALUE Multipart form data","-u, --user USER:PASS HTTP authentication","-A, --user-agent STR Set User-Agent header","-e, --referer URL Set Referer header","-b, --cookie DATA Send cookies (name=value or @file)","-c, --cookie-jar FILE Save cookies to file","-T, --upload-file FILE Upload file (PUT)","-o, --output FILE Write output to file","-O, --remote-name Write to file named from URL","-I, --head Show headers only (HEAD request)","-i, --include Include response headers in output","-s, --silent Silent mode (no progress)","-S, --show-error Show errors even when silent","-f, --fail Fail silently on HTTP errors (no output)","-L, --location Follow redirects (default)"," --max-redirs NUM Maximum redirects (default: 20)","-m, --max-time SECS Maximum time for request"," --connect-timeout SECS Connection timeout","-w, --write-out FMT Output format after completion","-v, --verbose Verbose output"," --help Display this help and exit","","Note: Network access must be configured via BashEnv network option."," curl is not available by default for security reasons."]}});function za(t){let e={method:"GET",headers:{},dataBinary:!1,formFields:[],useRemoteName:!1,headOnly:!1,includeHeaders:!1,silent:!1,showError:!1,failSilently:!1,followRedirects:!0,verbose:!1};for(let r=0;r<t.length;r++){let n=t[r];if(n==="-X"||n==="--request")e.method=t[++r]??"GET";else if(n.startsWith("-X"))e.method=n.slice(2);else if(n.startsWith("--request="))e.method=n.slice(10);else if(n==="-H"||n==="--header"){let s=t[++r];if(s){let i=s.indexOf(":");if(i>0){let a=s.slice(0,i).trim(),o=s.slice(i+1).trim();e.headers[a]=o}}}else if(n.startsWith("--header=")){let s=n.slice(9),i=s.indexOf(":");if(i>0){let a=s.slice(0,i).trim(),o=s.slice(i+1).trim();e.headers[a]=o}}else if(n==="-d"||n==="--data"||n==="--data-raw")e.data=t[++r]??"",e.method==="GET"&&(e.method="POST");else if(n.startsWith("-d"))e.data=n.slice(2),e.method==="GET"&&(e.method="POST");else if(n.startsWith("--data="))e.data=n.slice(7),e.method==="GET"&&(e.method="POST");else if(n.startsWith("--data-raw="))e.data=n.slice(11),e.method==="GET"&&(e.method="POST");else if(n==="--data-binary")e.data=t[++r]??"",e.dataBinary=!0,e.method==="GET"&&(e.method="POST");else if(n.startsWith("--data-binary="))e.data=n.slice(14),e.dataBinary=!0,e.method==="GET"&&(e.method="POST");else if(n==="--data-urlencode"){let s=t[++r]??"";e.data=(e.data?`${e.data}&`:"")+an(s),e.method==="GET"&&(e.method="POST")}else if(n.startsWith("--data-urlencode=")){let s=n.slice(17);e.data=(e.data?`${e.data}&`:"")+an(s),e.method==="GET"&&(e.method="POST")}else if(n==="-F"||n==="--form"){let s=t[++r]??"",i=on(s);i&&e.formFields.push(i),e.method==="GET"&&(e.method="POST")}else if(n.startsWith("--form=")){let s=n.slice(7),i=on(s);i&&e.formFields.push(i),e.method==="GET"&&(e.method="POST")}else if(n==="-u"||n==="--user")e.user=t[++r];else if(n.startsWith("-u"))e.user=n.slice(2);else if(n.startsWith("--user="))e.user=n.slice(7);else if(n==="-A"||n==="--user-agent")e.headers["User-Agent"]=t[++r]??"";else if(n.startsWith("-A"))e.headers["User-Agent"]=n.slice(2);else if(n.startsWith("--user-agent="))e.headers["User-Agent"]=n.slice(13);else if(n==="-e"||n==="--referer")e.headers.Referer=t[++r]??"";else if(n.startsWith("-e"))e.headers.Referer=n.slice(2);else if(n.startsWith("--referer="))e.headers.Referer=n.slice(10);else if(n==="-b"||n==="--cookie")e.headers.Cookie=t[++r]??"";else if(n.startsWith("-b"))e.headers.Cookie=n.slice(2);else if(n.startsWith("--cookie="))e.headers.Cookie=n.slice(9);else if(n==="-c"||n==="--cookie-jar")e.cookieJar=t[++r];else if(n.startsWith("--cookie-jar="))e.cookieJar=n.slice(13);else if(n==="-T"||n==="--upload-file")e.uploadFile=t[++r],e.method==="GET"&&(e.method="PUT");else if(n.startsWith("--upload-file="))e.uploadFile=n.slice(14),e.method==="GET"&&(e.method="PUT");else if(n==="-m"||n==="--max-time"){let s=parseFloat(t[++r]??"0");!Number.isNaN(s)&&s>0&&(e.timeoutMs=s*1e3)}else if(n.startsWith("--max-time=")){let s=parseFloat(n.slice(11));!Number.isNaN(s)&&s>0&&(e.timeoutMs=s*1e3)}else if(n==="--connect-timeout"){let s=parseFloat(t[++r]??"0");!Number.isNaN(s)&&s>0&&e.timeoutMs===void 0&&(e.timeoutMs=s*1e3)}else if(n.startsWith("--connect-timeout=")){let s=parseFloat(n.slice(18));!Number.isNaN(s)&&s>0&&e.timeoutMs===void 0&&(e.timeoutMs=s*1e3)}else if(n==="-o"||n==="--output")e.outputFile=t[++r];else if(n.startsWith("--output="))e.outputFile=n.slice(9);else if(n==="-O"||n==="--remote-name")e.useRemoteName=!0;else if(n==="-I"||n==="--head")e.headOnly=!0,e.method="HEAD";else if(n==="-i"||n==="--include")e.includeHeaders=!0;else if(n==="-s"||n==="--silent")e.silent=!0;else if(n==="-S"||n==="--show-error")e.showError=!0;else if(n==="-f"||n==="--fail")e.failSilently=!0;else if(n==="-L"||n==="--location")e.followRedirects=!0;else if(n==="--max-redirs")r++;else if(!n.startsWith("--max-redirs="))if(n==="-w"||n==="--write-out")e.writeOut=t[++r];else if(n.startsWith("--write-out="))e.writeOut=n.slice(12);else if(n==="-v"||n==="--verbose")e.verbose=!0;else{if(n.startsWith("--")&&n!=="--")return M("curl",n);if(n.startsWith("-")&&n!=="-")for(let s of n.slice(1))switch(s){case"s":e.silent=!0;break;case"S":e.showError=!0;break;case"f":e.failSilently=!0;break;case"L":e.followRedirects=!0;break;case"I":e.headOnly=!0,e.method="HEAD";break;case"i":e.includeHeaders=!0;break;case"O":e.useRemoteName=!0;break;case"v":e.verbose=!0;break;default:return M("curl",`-${s}`)}else n.startsWith("-")||(e.url=n)}}return e}var Ga=v(()=>{"use strict";F();ln()});function cn(t){return Object.entries(t).map(([e,r])=>`${e}: ${r}`).join(`\r
421
+ `)}function ja(t){try{return new URL(t).pathname.split("/").pop()||"index.html"}catch{return"index.html"}}function un(t,e){let r=t;return r=r.replace(/%\{http_code\}/g,String(e.status)),r=r.replace(/%\{content_type\}/g,e.headers["content-type"]||""),r=r.replace(/%\{url_effective\}/g,e.url),r=r.replace(/%\{size_download\}/g,String(e.bodyLength)),r=r.replace(/\\n/g,`
422
+ `),r}var qa=v(()=>{"use strict"});var Va={};D(Va,{curlCommand:()=>dd});async function ld(t,e){if(t.uploadFile){let r=e.fs.resolvePath(e.cwd,t.uploadFile);return{body:await e.fs.readFile(r)}}if(t.formFields.length>0){let r=new Map;for(let i of t.formFields)if(i.value.startsWith("@")||i.value.startsWith("<")){let a=e.fs.resolvePath(e.cwd,i.value.slice(1));try{let o=await e.fs.readFile(a);r.set(i.value.slice(1),o)}catch{r.set(i.value.slice(1),"")}}let{body:n,boundary:s}=Ba(t.formFields,r);return{body:n,contentType:`multipart/form-data; boundary=${s}`}}return t.data!==void 0?{body:t.data}:{}}function cd(t,e){let r={...t.headers};if(t.user){let n=Buffer.from(t.user).toString("base64");r.Authorization=`Basic ${n}`}return e&&!r["Content-Type"]&&(r["Content-Type"]=e),r}async function ud(t,e,r){if(!t.cookieJar)return;let n=e["set-cookie"];if(!n)return;let s=r.fs.resolvePath(r.cwd,t.cookieJar);await r.fs.writeFile(s,n)}function fd(t,e,r){let n="";if(t.verbose){n+=`> ${t.method} ${r}
423
423
  `;for(let[s,i]of Object.entries(t.headers))n+=`> ${s}: ${i}
424
424
  `;n+=`>
425
425
  `,n+=`< HTTP/1.1 ${e.status} ${e.statusText}
426
426
  `;for(let[s,i]of Object.entries(e.headers))n+=`< ${s}: ${i}
427
427
  `;n+=`<
428
428
  `}return t.includeHeaders&&!t.verbose&&(n+=`HTTP/1.1 ${e.status} ${e.statusText}\r
429
- `,n+=an(e.headers),n+=`\r
429
+ `,n+=cn(e.headers),n+=`\r
430
430
  \r
431
431
  `),t.headOnly?t.includeHeaders||t.verbose||(n+=`HTTP/1.1 ${e.status} ${e.statusText}\r
432
- `,n+=an(e.headers),n+=`\r
433
- `):n+=e.body,t.writeOut&&(n+=on(t.writeOut,{status:e.status,headers:e.headers,url:e.url,bodyLength:e.body.length})),n}var id,Ga=N(()=>{"use strict";ke();L();sn();_a();Ba();Ua();id={name:"curl",async execute(t,e){if(C(t))return A(Ma);let r=Wa(t);if("exitCode"in r)return r;let n=r;if(!n.url)return{stdout:"",stderr:`curl: no URL specified
432
+ `,n+=cn(e.headers),n+=`\r
433
+ `):n+=e.body,t.writeOut&&(n+=un(t.writeOut,{status:e.status,headers:e.headers,url:e.url,bodyLength:e.body.length})),n}var dd,Za=v(()=>{"use strict";Ie();F();ln();Ua();Ga();qa();dd={name:"curl",async execute(t,e){if(N(t))return C(Ha);let r=za(t);if("exitCode"in r)return r;let n=r;if(!n.url)return{stdout:"",stderr:`curl: no URL specified
434
434
  `,exitCode:2};if(!e.fetch)return{stdout:"",stderr:`curl: internal error: fetch not available
435
- `,exitCode:1};let s=n.url;s.match(/^https?:\/\//)||(s=`https://${s}`);try{let{body:i,contentType:a}=await td(n,e),o=rd(n,a),c=await e.fetch(s,{method:n.method,headers:Object.keys(o).length>0?o:void 0,body:i,followRedirects:n.followRedirects,timeoutMs:n.timeoutMs});if(await nd(n,c.headers,e),n.failSilently&&c.status>=400)return{stdout:"",stderr:n.showError||!n.silent?`curl: (22) The requested URL returned error: ${c.status}
436
- `:"",exitCode:22};let l=sd(n,c,s);if(n.outputFile||n.useRemoteName){let u=n.outputFile||Ha(s),f=e.fs.resolvePath(e.cwd,u);await e.fs.writeFile(f,n.headOnly?"":c.body),n.verbose||(l=""),n.writeOut&&(l=on(n.writeOut,{status:c.status,headers:c.headers,url:c.url,bodyLength:c.body.length}))}return{stdout:l,stderr:"",exitCode:0}}catch(i){let a=Y(i),o=1;return a.includes("Network access denied")?o=7:a.includes("HTTP method")&&a.includes("not allowed")?o=3:a.includes("Redirect target not in allow-list")||a.includes("Too many redirects")?o=47:a.includes("aborted")&&(o=28),{stdout:"",stderr:!n.silent||n.showError?`curl: (${o}) ${a}
437
- `:"",exitCode:o}}}}});import{tool as gh,zodSchema as wh}from"ai";import{z as pl}from"zod";var ja=[{name:"echo",load:async()=>(await Promise.resolve().then(()=>(ss(),ns))).echoCommand},{name:"cat",load:async()=>(await Promise.resolve().then(()=>(as(),is))).catCommand},{name:"printf",load:async()=>(await Promise.resolve().then(()=>(cs(),ls))).printfCommand},{name:"ls",load:async()=>(await Promise.resolve().then(()=>(hs(),ds))).lsCommand},{name:"mkdir",load:async()=>(await Promise.resolve().then(()=>(ms(),ps))).mkdirCommand},{name:"touch",load:async()=>(await Promise.resolve().then(()=>(gs(),ys))).touchCommand},{name:"rm",load:async()=>(await Promise.resolve().then(()=>(Es(),ws))).rmCommand},{name:"cp",load:async()=>(await Promise.resolve().then(()=>(xs(),bs))).cpCommand},{name:"mv",load:async()=>(await Promise.resolve().then(()=>(As(),Ss))).mvCommand},{name:"ln",load:async()=>(await Promise.resolve().then(()=>(Ns(),Cs))).lnCommand},{name:"chmod",load:async()=>(await Promise.resolve().then(()=>(Is(),ks))).chmodCommand},{name:"pwd",load:async()=>(await Promise.resolve().then(()=>($s(),Rs))).pwdCommand},{name:"readlink",load:async()=>(await Promise.resolve().then(()=>(Os(),Ps))).readlinkCommand},{name:"head",load:async()=>(await Promise.resolve().then(()=>(Fs(),Ts))).headCommand},{name:"tail",load:async()=>(await Promise.resolve().then(()=>(_s(),Ms))).tailCommand},{name:"wc",load:async()=>(await Promise.resolve().then(()=>(Hs(),Bs))).wcCommand},{name:"stat",load:async()=>(await Promise.resolve().then(()=>(Gs(),zs))).statCommand},{name:"grep",load:async()=>(await Promise.resolve().then(()=>(Ut(),Ht))).grepCommand},{name:"fgrep",load:async()=>(await Promise.resolve().then(()=>(Ut(),Ht))).fgrepCommand},{name:"egrep",load:async()=>(await Promise.resolve().then(()=>(Ut(),Ht))).egrepCommand},{name:"sed",load:async()=>(await Promise.resolve().then(()=>(ti(),ei))).sedCommand},{name:"awk",load:async()=>(await Promise.resolve().then(()=>(Ci(),Ai))).awkCommand2},{name:"sort",load:async()=>(await Promise.resolve().then(()=>($i(),Ri))).sortCommand},{name:"uniq",load:async()=>(await Promise.resolve().then(()=>(Oi(),Pi))).uniqCommand},{name:"cut",load:async()=>(await Promise.resolve().then(()=>(Li(),Di))).cutCommand},{name:"paste",load:async()=>(await Promise.resolve().then(()=>(Mi(),Fi))).pasteCommand},{name:"tr",load:async()=>(await Promise.resolve().then(()=>(Bi(),Wi))).trCommand},{name:"tee",load:async()=>(await Promise.resolve().then(()=>(Ui(),Hi))).teeCommand},{name:"find",load:async()=>(await Promise.resolve().then(()=>(Zi(),Vi))).findCommand},{name:"basename",load:async()=>(await Promise.resolve().then(()=>(Ki(),Qi))).basenameCommand},{name:"dirname",load:async()=>(await Promise.resolve().then(()=>(Yi(),Xi))).dirnameCommand},{name:"tree",load:async()=>(await Promise.resolve().then(()=>(ta(),ea))).treeCommand},{name:"du",load:async()=>(await Promise.resolve().then(()=>(sa(),na))).duCommand},{name:"env",load:async()=>(await Promise.resolve().then(()=>(Qr(),Zr))).envCommand},{name:"printenv",load:async()=>(await Promise.resolve().then(()=>(Qr(),Zr))).printenvCommand},{name:"alias",load:async()=>(await Promise.resolve().then(()=>(Xr(),Kr))).aliasCommand},{name:"unalias",load:async()=>(await Promise.resolve().then(()=>(Xr(),Kr))).unaliasCommand},{name:"history",load:async()=>(await Promise.resolve().then(()=>(oa(),aa))).historyCommand},{name:"xargs",load:async()=>(await Promise.resolve().then(()=>(ca(),la))).xargsCommand},{name:"true",load:async()=>(await Promise.resolve().then(()=>(Jr(),Yr))).trueCommand},{name:"false",load:async()=>(await Promise.resolve().then(()=>(Jr(),Yr))).falseCommand},{name:"clear",load:async()=>(await Promise.resolve().then(()=>(fa(),ua))).clearCommand},{name:"bash",load:async()=>(await Promise.resolve().then(()=>(tn(),en))).bashCommand},{name:"sh",load:async()=>(await Promise.resolve().then(()=>(tn(),en))).shCommand},{name:"jq",load:async()=>(await Promise.resolve().then(()=>(pa(),ha))).jqCommand},{name:"base64",load:async()=>(await Promise.resolve().then(()=>(ya(),ma))).base64Command},{name:"diff",load:async()=>(await Promise.resolve().then(()=>(Ea(),wa))).diffCommand},{name:"date",load:async()=>(await Promise.resolve().then(()=>(xa(),ba))).dateCommand},{name:"sleep",load:async()=>(await Promise.resolve().then(()=>(Aa(),Sa))).sleepCommand},{name:"timeout",load:async()=>(await Promise.resolve().then(()=>(Na(),Ca))).timeoutCommand},{name:"seq",load:async()=>(await Promise.resolve().then(()=>(ka(),va))).seqCommand},{name:"expr",load:async()=>(await Promise.resolve().then(()=>(Ra(),Ia))).exprCommand},{name:"html-to-markdown",load:async()=>(await Promise.resolve().then(()=>(Pa(),$a))).htmlToMarkdownCommand},{name:"help",load:async()=>(await Promise.resolve().then(()=>(Da(),Oa))).helpCommand},{name:"which",load:async()=>(await Promise.resolve().then(()=>(Ta(),La))).whichCommand}],ad=[{name:"curl",load:async()=>(await Promise.resolve().then(()=>(Ga(),za))).curlCommand}],qa=new Map;function Va(t){return{name:t.name,async execute(e,r){let n=qa.get(t.name);return n||(n=await t.load(),qa.set(t.name,n)),n.execute(e,r)}}}function Za(t){return(t?ja.filter(r=>t.includes(r.name)):ja).map(Va)}function Qa(){return ad.map(Va)}function Ka(t){return"load"in t&&typeof t.load=="function"}function Xa(t){let e=null;return{name:t.name,async execute(r,n){return e||(e=await t.load()),e.execute(r,n)}}}var od=new TextEncoder,ld=new TextDecoder;function ln(t,e){if(t instanceof Uint8Array)return t;switch(e){case"base64":return Uint8Array.from(atob(t),r=>r.charCodeAt(0));case"hex":{let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=parseInt(t.slice(n,n+2),16);return r}case"binary":case"latin1":return Uint8Array.from(t,r=>r.charCodeAt(0));default:return od.encode(t)}}function Ya(t,e){switch(e){case"base64":return btoa(String.fromCharCode(...t));case"hex":return Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");case"binary":case"latin1":return String.fromCharCode(...t);default:return ld.decode(t)}}function Yt(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Jt=new TextEncoder;function cd(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var et=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[r,n]of Object.entries(e))cd(n)?this.writeFileSync(r,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(r,n)}normalizePath(e){if(!e||e==="/")return"/";let r=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;r.startsWith("/")||(r=`/${r}`);let n=r.split("/").filter(i=>i&&i!=="."),s=[];for(let i of n)i===".."?s.pop():s.push(i);return`/${s.join("/")}`||"/"}dirname(e){let r=this.normalizePath(e);if(r==="/")return"/";let n=r.lastIndexOf("/");return n===0?"/":r.slice(0,n)}ensureParentDirs(e){let r=this.dirname(e);r!=="/"&&(this.data.has(r)||(this.ensureParentDirs(r),this.data.set(r,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,r,n,s){let i=this.normalizePath(e);this.ensureParentDirs(i);let a=Yt(n),o=ln(r,a);this.data.set(i,{type:"file",content:o,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,r){let n=await this.readFileBuffer(e),s=Yt(r);return Ya(n,s)}async readFileBuffer(e){let r=this.normalizePath(e),n=this.data.get(r),s=r;if(!n)throw new Error(`ENOENT: no such file or directory, open '${e}'`);let i=new Set;for(;n&&n.type==="symlink";){if(i.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);i.add(s),s=this.resolveSymlink(s,n.target),n=this.data.get(s)}if(!n)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return n.content instanceof Uint8Array?n.content:Jt.encode(n.content)}async writeFile(e,r,n){this.writeFileSync(e,r,n)}async appendFile(e,r,n){let s=this.normalizePath(e),i=this.data.get(s);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let a=Yt(n),o=ln(r,a);if(i?.type==="file"){let c=i.content instanceof Uint8Array?i.content:Jt.encode(i.content),l=new Uint8Array(c.length+o.length);l.set(c),l.set(o,c.length),this.data.set(s,{type:"file",content:l,mode:i.mode,mtime:new Date})}else this.writeFileSync(e,r,n)}async exists(e){return this.data.has(this.normalizePath(e))}async stat(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);if(n.type==="symlink"){let i=this.resolveSymlink(r,n.target),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);n=a}let s=0;return n.type==="file"&&n.content&&(n.content instanceof Uint8Array?s=n.content.length:s=Jt.encode(n.content).length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:s,mtime:n.mtime||new Date}}async lstat(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};let s=0;return n.type==="file"&&n.content&&(n.content instanceof Uint8Array?s=n.content.length:s=Jt.encode(n.content).length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:s,mtime:n.mtime||new Date}}resolveSymlink(e,r){if(r.startsWith("/"))return this.normalizePath(r);let n=this.dirname(e);return this.normalizePath(n==="/"?`/${r}`:`${n}/${r}`)}async mkdir(e,r){this.mkdirSync(e,r)}mkdirSync(e,r){let n=this.normalizePath(e);if(this.data.has(n)){if(this.data.get(n)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!r?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let s=this.dirname(n);if(s!=="/"&&!this.data.has(s))if(r?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(n,{type:"directory",mode:493,mtime:new Date})}async readdir(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let s=r==="/"?"/":`${r}/`,i=[];for(let a of this.data.keys())if(a!==r&&a.startsWith(s)){let c=a.slice(s.length).split("/")[0];c&&!i.includes(c)&&i.push(c)}return i.sort()}async rm(e,r){let n=this.normalizePath(e),s=this.data.get(n);if(!s){if(r?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(s.type==="directory"){let i=await this.readdir(n);if(i.length>0){if(!r?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let a of i){let o=n==="/"?`/${a}`:`${n}/${a}`;await this.rm(o,r)}}}this.data.delete(n)}async cp(e,r,n){let s=this.normalizePath(e),i=this.normalizePath(r),a=this.data.get(s);if(!a)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(a.type==="file")this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type==="directory"){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(s);for(let c of o){let l=s==="/"?`/${c}`:`${s}/${c}`,u=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(l,u,n)}}}async mv(e,r){await this.cp(e,r,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,r){if(r.startsWith("/"))return this.normalizePath(r);let n=e==="/"?`/${r}`:`${e}/${r}`;return this.normalizePath(n)}async chmod(e,r){let n=this.normalizePath(e),s=this.data.get(n);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);s.mode=r}async symlink(e,r){let n=this.normalizePath(r);if(this.data.has(n))throw new Error(`EEXIST: file already exists, symlink '${r}'`);this.ensureParentDirs(n),this.data.set(n,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,r){let n=this.normalizePath(e),s=this.normalizePath(r),i=this.data.get(n);if(!i)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${r}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:i.content,mode:i.mode,mtime:i.mtime})}async readlink(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}};X();X();function se(t,e){return{type:"ArithmeticExpression",expression:Le(t,e,0).expr}}function Le(t,e,r){return ud(t,e,r)}function ud(t,e,r){let{expr:n,pos:s}=tr(t,e,r);for(s=J(e,s);e[s]===",";){s++;let{expr:i,pos:a}=tr(t,e,s);n={type:"ArithBinary",operator:",",left:n,right:i},s=J(e,a)}return{expr:n,pos:s}}function tr(t,e,r){let{expr:n,pos:s}=fd(t,e,r);if(s=J(e,s),e[s]==="?"){s++;let{expr:i,pos:a}=Le(t,e,s);if(s=J(e,a),e[s]===":"){s++;let{expr:o,pos:c}=Le(t,e,s);return{expr:{type:"ArithTernary",condition:n,consequent:i,alternate:o},pos:c}}}return{expr:n,pos:s}}function fd(t,e,r){let{expr:n,pos:s}=Ja(t,e,r);for(;s=J(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:i,pos:a}=Ja(t,e,s);n={type:"ArithBinary",operator:"||",left:n,right:i},s=a}return{expr:n,pos:s}}function Ja(t,e,r){let{expr:n,pos:s}=eo(t,e,r);for(;s=J(e,s),e.slice(s,s+2)==="&&";){s+=2;let{expr:i,pos:a}=eo(t,e,s);n={type:"ArithBinary",operator:"&&",left:n,right:i},s=a}return{expr:n,pos:s}}function eo(t,e,r){let{expr:n,pos:s}=to(t,e,r);for(;s=J(e,s),e[s]==="|"&&e[s+1]!=="|";){s++;let{expr:i,pos:a}=to(t,e,s);n={type:"ArithBinary",operator:"|",left:n,right:i},s=a}return{expr:n,pos:s}}function to(t,e,r){let{expr:n,pos:s}=ro(t,e,r);for(;s=J(e,s),e[s]==="^";){s++;let{expr:i,pos:a}=ro(t,e,s);n={type:"ArithBinary",operator:"^",left:n,right:i},s=a}return{expr:n,pos:s}}function ro(t,e,r){let{expr:n,pos:s}=no(t,e,r);for(;s=J(e,s),e[s]==="&"&&e[s+1]!=="&";){s++;let{expr:i,pos:a}=no(t,e,s);n={type:"ArithBinary",operator:"&",left:n,right:i},s=a}return{expr:n,pos:s}}function no(t,e,r){let{expr:n,pos:s}=so(t,e,r);for(;s=J(e,s),e.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let i=e.slice(s,s+2);s+=2;let{expr:a,pos:o}=so(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}return{expr:n,pos:s}}function so(t,e,r){let{expr:n,pos:s}=cn(t,e,r);for(;;)if(s=J(e,s),e.slice(s,s+2)==="<="||e.slice(s,s+2)===">="){let i=e.slice(s,s+2);s+=2;let{expr:a,pos:o}=cn(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}else if(e[s]==="<"||e[s]===">"){let i=e[s];s++;let{expr:a,pos:o}=cn(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}else break;return{expr:n,pos:s}}function cn(t,e,r){let{expr:n,pos:s}=io(t,e,r);for(;s=J(e,s),e.slice(s,s+2)==="<<"||e.slice(s,s+2)===">>";){let i=e.slice(s,s+2);s+=2;let{expr:a,pos:o}=io(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}return{expr:n,pos:s}}function io(t,e,r){let{expr:n,pos:s}=ao(t,e,r);for(;s=J(e,s),(e[s]==="+"||e[s]==="-")&&e[s+1]!==e[s];){let i=e[s];s++;let{expr:a,pos:o}=ao(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}return{expr:n,pos:s}}function ao(t,e,r){let{expr:n,pos:s}=er(t,e,r);for(;;)if(s=J(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:i,pos:a}=er(t,e,s);n={type:"ArithBinary",operator:"*",left:n,right:i},s=a}else if(e[s]==="/"||e[s]==="%"){let i=e[s];s++;let{expr:a,pos:o}=er(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}else break;return{expr:n,pos:s}}function er(t,e,r){let{expr:n,pos:s}=un(t,e,r),i=J(e,s);if(e.slice(i,i+2)==="**"){i+=2;let{expr:a,pos:o}=er(t,e,i);return{expr:{type:"ArithBinary",operator:"**",left:n,right:a},pos:o}}return{expr:n,pos:s}}function un(t,e,r){let n=J(e,r);if(e.slice(n,n+2)==="++"||e.slice(n,n+2)==="--"){let s=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=un(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:a}}if(e[n]==="+"||e[n]==="-"||e[n]==="!"||e[n]==="~"){let s=e[n];n++;let{expr:i,pos:a}=un(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:a}}return hd(t,e,n)}function dd(t,e){let r=t[e];return r==="$"||r==="`"}function hd(t,e,r){let{expr:n,pos:s}=oo(t,e,r),i=[n];for(;dd(e,s);){let{expr:a,pos:o}=oo(t,e,s);i.push(a),s=o}if(i.length>1&&(n={type:"ArithConcat",parts:i}),s=J(e,s),e.slice(s,s+2)==="++"||e.slice(s,s+2)==="--"){let a=e.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:a,operand:n,prefix:!1},pos:s}}return{expr:n,pos:s}}function oo(t,e,r){let n=J(e,r);if(e.slice(n,n+3)==="$(("){n+=3;let s=1,i=n;for(;n<e.length-1&&s>0;)e[n]==="("&&e[n+1]==="("?(s++,n+=2):e[n]===")"&&e[n+1]===")"?(s--,s>0&&(n+=2)):n++;let a=e.slice(i,n),{expr:o}=Le(t,a,0);return n+=2,{expr:{type:"ArithNested",expression:o},pos:n}}if(e.slice(n,n+2)==="$("&&e[n+2]!=="("){n+=2;let s=1,i=n;for(;n<e.length&&s>0;)e[n]==="("?s++:e[n]===")"&&s--,s>0&&n++;let a=e.slice(i,n);return n++,{expr:{type:"ArithCommandSubst",command:a},pos:n}}if(e[n]==="`"){n++;let s=n;for(;n<e.length&&e[n]!=="`";)n++;let i=e.slice(s,n);return e[n]==="`"&&n++,{expr:{type:"ArithCommandSubst",command:i},pos:n}}if(e[n]==="("){n++;let{expr:s,pos:i}=Le(t,e,n);return n=J(e,i),e[n]===")"&&n++,{expr:{type:"ArithGroup",expression:s},pos:n}}if(/[0-9]/.test(e[n])){let s="",i=!1;for(;n<e.length;){let o=e[n];if(i)if(/[0-9a-zA-Z@_]/.test(o))s+=o,n++;else break;else if(o==="#")i=!0,s+=o,n++;else if(/[0-9a-fA-FxX]/.test(o))s+=o,n++;else break}if(e[n]==="."&&/[0-9]/.test(e[n+1]))throw new te(`${s}.${e[n+1]}...: syntax error: invalid arithmetic operator`);if(e[n]==="["){let o=e.slice(n).trim();return{expr:{type:"ArithNumberSubscript",number:s,errorToken:o},pos:e.length}}return{expr:{type:"ArithNumber",value:dt(s)},pos:n}}if(e[n]==="$"&&e[n+1]==="{"){let s=n+2,i=1,a=s;for(;a<e.length&&i>0;)e[a]==="{"?i++:e[a]==="}"&&i--,i>0&&a++;let o=e.slice(s,a),c=a+1;if(e[c]==="#"){let l=c+1;for(;l<e.length&&/[0-9a-zA-Z@_]/.test(e[l]);)l++;let u=e.slice(c+1,l);return{expr:{type:"ArithDynamicBase",baseExpr:o,value:u},pos:l}}if(/[0-9]/.test(e[c])||e[c]==="x"||e[c]==="X"){let l=c;if(e[c]==="x"||e[c]==="X")for(l++;l<e.length&&/[0-9a-fA-F]/.test(e[l]);)l++;else for(;l<e.length&&/[0-9]/.test(e[l]);)l++;let u=e.slice(c,l);return{expr:{type:"ArithDynamicNumber",prefix:o,suffix:u},pos:l}}return n=c,{expr:{type:"ArithBracedExpansion",content:o},pos:n}}if(e[n]==="$"&&n+1<e.length&&/[0-9]/.test(e[n+1])){n++;let s="";for(;n<e.length&&/[0-9]/.test(e[n]);)s+=e[n],n++;return{expr:{type:"ArithVariable",name:s},pos:n}}if(e[n]==="$"&&n+1<e.length&&/[a-zA-Z_]/.test(e[n+1])&&n++,/[a-zA-Z_]/.test(e[n])){let s="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)s+=e[n],n++;if(e[n]==="["){n++;let a;if(e[n]==="'"||e[n]==='"'){let l=e[n];for(n++,a="";n<e.length&&e[n]!==l;)a+=e[n],n++;e[n]===l&&n++,n=J(e,n),e[n]==="]"&&n++}let o;if(a===void 0){let{expr:l,pos:u}=Le(t,e,n);o=l,n=u,e[n]==="]"&&n++}if(n=J(e,n),e[n]==="["&&o)return{expr:{type:"ArithDoubleSubscript",array:s,index:o},pos:n};let c=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let l of c)if(e.slice(n,n+l.length)===l&&e.slice(n,n+l.length+1)!=="=="){n+=l.length;let{expr:u,pos:f}=tr(t,e,n);return{expr:{type:"ArithAssignment",operator:l,variable:s,subscript:o,stringKey:a,value:u},pos:f}}return{expr:{type:"ArithArrayElement",array:s,index:o,stringKey:a},pos:n}}n=J(e,n);let i=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let a of i)if(e.slice(n,n+a.length)===a&&e.slice(n,n+a.length+1)!=="=="){n+=a.length;let{expr:o,pos:c}=tr(t,e,n);return{expr:{type:"ArithAssignment",operator:a,variable:s,value:o},pos:c}}return{expr:{type:"ArithVariable",name:s},pos:n}}return{expr:{type:"ArithNumber",value:0},pos:n}}function dt(t){if(t.includes("#")){let[e,r]=t.split("#"),n=Number.parseInt(e,10);if(n<2||n>64)return Number.NaN;if(n<=36)return Number.parseInt(r,n);let s=0;for(let i of r){let a;if(i>="0"&&i<="9")a=i.charCodeAt(0)-48;else if(i>="a"&&i<="z")a=i.charCodeAt(0)-97+10;else if(i>="A"&&i<="Z")a=i.charCodeAt(0)-65+36;else if(i==="@")a=62;else if(i==="_")a=63;else return Number.NaN;if(a>=n)return Number.NaN;s=s*n+a}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 J(t,e){for(;e<t.length;){if(t[e]==="\\"&&t[e+1]===`
438
- `){e+=2;continue}if(/\s/.test(t[e])){e++;continue}break}return e}var k={script(t){return{type:"Script",statements:t}},statement(t,e=[],r=!1){return{type:"Statement",pipelines:t,operators:e,background:r}},pipeline(t,e=!1){return{type:"Pipeline",commands:t,negated:e}},simpleCommand(t,e=[],r=[],n=[]){return{type:"SimpleCommand",name:t,args:e,assignments:r,redirections:n}},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,r=!1,n=null){return{type:"Assignment",name:t,value:e,append:r,array:n}},redirection(t,e,r=null){return{type:"Redirection",fd:r,operator:t,target:e}},hereDoc(t,e,r=!1,n=!1){return{type:"HereDoc",delimiter:t,content:e,stripTabs:r,quoted:n}},ifNode(t,e=null,r=[]){return{type:"If",clauses:t,elseBody:e,redirections:r}},forNode(t,e,r,n=[]){return{type:"For",variable:t,words:e,body:r,redirections:n}},whileNode(t,e,r=[]){return{type:"While",condition:t,body:e,redirections:r}},untilNode(t,e,r=[]){return{type:"Until",condition:t,body:e,redirections:r}},caseNode(t,e,r=[]){return{type:"Case",word:t,items:e,redirections:r}},caseItem(t,e,r=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:r}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,r=[]){return{type:"FunctionDef",name:t,body:e,redirections:r}},conditionalCommand(t,e=[]){return{type:"ConditionalCommand",expression:t,redirections:e}},arithmeticCommand(t,e=[]){return{type:"ArithmeticCommand",expression:t,redirections:e}}};var m;(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"})(m||(m={}));var rr={if:m.IF,then:m.THEN,else:m.ELSE,elif:m.ELIF,fi:m.FI,for:m.FOR,while:m.WHILE,until:m.UNTIL,do:m.DO,done:m.DONE,case:m.CASE,esac:m.ESAC,in:m.IN,function:m.FUNCTION,select:m.SELECT,time:m.TIME,coproc:m.COPROC};function co(t){let e=t.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!e)return!1;let r=t.slice(e[0].length);if(r===""||r==="+")return!0;if(r[0]==="["){let n=0,s=0;for(;s<r.length;s++)if(r[s]==="[")n++;else if(r[s]==="]"&&(n--,n===0))break;if(n!==0||s>=r.length)return!1;let i=r.slice(s+1);return i===""||i==="+"}return!1}var pd=[[";",";","&",m.SEMI_SEMI_AND],["<","<","<",m.TLESS],["&",">",">",m.AND_DGREAT]],md=[["[","[",m.DBRACK_START],["]","]",m.DBRACK_END],["(","(",m.DPAREN_START],[")",")",m.DPAREN_END],["&","&",m.AND_AND],["|","|",m.OR_OR],[";",";",m.DSEMI],[";","&",m.SEMI_AND],["|","&",m.PIPE_AMP],[">",">",m.DGREAT],["<","&",m.LESSAND],[">","&",m.GREATAND],["<",">",m.LESSGREAT],[">","|",m.CLOBBER],["&",">",m.AND_GREAT]],yd={"|":m.PIPE,"&":m.AMP,";":m.SEMICOLON,"(":m.LPAREN,")":m.RPAREN,"<":m.LESS,">":m.GREAT};function gd(t){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)}var nr=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];constructor(e){this.input=e}tokenize(){let r=this.input.length,n=this.tokens,s=this.pendingHeredocs;for(;this.pos<r&&(this.skipWhitespace(),!(this.pos>=r));){if(s.length>0&&n.length>0&&n[n.length-1].type===m.NEWLINE){this.readHeredocContent();continue}let i=this.nextToken();i&&n.push(i)}return n.push({type:m.EOF,value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),n}skipWhitespace(){let e=this.input,r=e.length,n=this.pos,s=this.column,i=this.line;for(;n<r;){let a=e[n];if(a===" "||a===" ")n++,s++;else if(a==="\\"&&e[n+1]===`
435
+ `,exitCode:1};let s=n.url;s.match(/^https?:\/\//)||(s=`https://${s}`);try{let{body:i,contentType:a}=await ld(n,e),o=cd(n,a),c=await e.fetch(s,{method:n.method,headers:Object.keys(o).length>0?o:void 0,body:i,followRedirects:n.followRedirects,timeoutMs:n.timeoutMs});if(await ud(n,c.headers,e),n.failSilently&&c.status>=400)return{stdout:"",stderr:n.showError||!n.silent?`curl: (22) The requested URL returned error: ${c.status}
436
+ `:"",exitCode:22};let l=fd(n,c,s);if(n.outputFile||n.useRemoteName){let u=n.outputFile||ja(s),f=e.fs.resolvePath(e.cwd,u);await e.fs.writeFile(f,n.headOnly?"":c.body),n.verbose||(l=""),n.writeOut&&(l=un(n.writeOut,{status:c.status,headers:c.headers,url:c.url,bodyLength:c.body.length}))}return{stdout:l,stderr:"",exitCode:0}}catch(i){let a=J(i),o=1;return a.includes("Network access denied")?o=7:a.includes("HTTP method")&&a.includes("not allowed")?o=3:a.includes("Redirect target not in allow-list")||a.includes("Too many redirects")?o=47:a.includes("aborted")&&(o=28),{stdout:"",stderr:!n.silent||n.showError?`curl: (${o}) ${a}
437
+ `:"",exitCode:o}}}}});import{tool as Ch,zodSchema as Nh}from"ai";import{z as wl}from"zod";var Qa=[{name:"echo",load:async()=>(await Promise.resolve().then(()=>(os(),as))).echoCommand},{name:"cat",load:async()=>(await Promise.resolve().then(()=>(cs(),ls))).catCommand},{name:"printf",load:async()=>(await Promise.resolve().then(()=>(hs(),ds))).printfCommand},{name:"ls",load:async()=>(await Promise.resolve().then(()=>(gs(),ys))).lsCommand},{name:"mkdir",load:async()=>(await Promise.resolve().then(()=>(Es(),ws))).mkdirCommand},{name:"touch",load:async()=>(await Promise.resolve().then(()=>(Ss(),bs))).touchCommand},{name:"rm",load:async()=>(await Promise.resolve().then(()=>(As(),xs))).rmCommand},{name:"cp",load:async()=>(await Promise.resolve().then(()=>(Ns(),Cs))).cpCommand},{name:"mv",load:async()=>(await Promise.resolve().then(()=>(ks(),vs))).mvCommand},{name:"ln",load:async()=>(await Promise.resolve().then(()=>($s(),Is))).lnCommand},{name:"chmod",load:async()=>(await Promise.resolve().then(()=>(Os(),Ps))).chmodCommand},{name:"pwd",load:async()=>(await Promise.resolve().then(()=>(Ts(),Ds))).pwdCommand},{name:"readlink",load:async()=>(await Promise.resolve().then(()=>(Fs(),Ls))).readlinkCommand},{name:"head",load:async()=>(await Promise.resolve().then(()=>(Bs(),Ws))).headCommand},{name:"tail",load:async()=>(await Promise.resolve().then(()=>(Us(),Hs))).tailCommand},{name:"wc",load:async()=>(await Promise.resolve().then(()=>(js(),Gs))).wcCommand},{name:"stat",load:async()=>(await Promise.resolve().then(()=>(Zs(),Vs))).statCommand},{name:"grep",load:async()=>(await Promise.resolve().then(()=>(qt(),jt))).grepCommand},{name:"fgrep",load:async()=>(await Promise.resolve().then(()=>(qt(),jt))).fgrepCommand},{name:"egrep",load:async()=>(await Promise.resolve().then(()=>(qt(),jt))).egrepCommand},{name:"sed",load:async()=>(await Promise.resolve().then(()=>(ii(),si))).sedCommand},{name:"awk",load:async()=>(await Promise.resolve().then(()=>(Ii(),ki))).awkCommand2},{name:"sort",load:async()=>(await Promise.resolve().then(()=>(Ti(),Di))).sortCommand},{name:"uniq",load:async()=>(await Promise.resolve().then(()=>(Fi(),Li))).uniqCommand},{name:"cut",load:async()=>(await Promise.resolve().then(()=>(_i(),Mi))).cutCommand},{name:"paste",load:async()=>(await Promise.resolve().then(()=>(Hi(),Bi))).pasteCommand},{name:"tr",load:async()=>(await Promise.resolve().then(()=>(Gi(),zi))).trCommand},{name:"tee",load:async()=>(await Promise.resolve().then(()=>(qi(),ji))).teeCommand},{name:"find",load:async()=>(await Promise.resolve().then(()=>(Yi(),Xi))).findCommand},{name:"basename",load:async()=>(await Promise.resolve().then(()=>(ea(),Ji))).basenameCommand},{name:"dirname",load:async()=>(await Promise.resolve().then(()=>(ra(),ta))).dirnameCommand},{name:"tree",load:async()=>(await Promise.resolve().then(()=>(ia(),sa))).treeCommand},{name:"du",load:async()=>(await Promise.resolve().then(()=>(la(),oa))).duCommand},{name:"env",load:async()=>(await Promise.resolve().then(()=>(Yr(),Xr))).envCommand},{name:"printenv",load:async()=>(await Promise.resolve().then(()=>(Yr(),Xr))).printenvCommand},{name:"alias",load:async()=>(await Promise.resolve().then(()=>(en(),Jr))).aliasCommand},{name:"unalias",load:async()=>(await Promise.resolve().then(()=>(en(),Jr))).unaliasCommand},{name:"history",load:async()=>(await Promise.resolve().then(()=>(fa(),ua))).historyCommand},{name:"xargs",load:async()=>(await Promise.resolve().then(()=>(ha(),da))).xargsCommand},{name:"true",load:async()=>(await Promise.resolve().then(()=>(rn(),tn))).trueCommand},{name:"false",load:async()=>(await Promise.resolve().then(()=>(rn(),tn))).falseCommand},{name:"clear",load:async()=>(await Promise.resolve().then(()=>(ma(),pa))).clearCommand},{name:"bash",load:async()=>(await Promise.resolve().then(()=>(sn(),nn))).bashCommand},{name:"sh",load:async()=>(await Promise.resolve().then(()=>(sn(),nn))).shCommand},{name:"jq",load:async()=>(await Promise.resolve().then(()=>(wa(),ga))).jqCommand},{name:"base64",load:async()=>(await Promise.resolve().then(()=>(ba(),Ea))).base64Command},{name:"diff",load:async()=>(await Promise.resolve().then(()=>(Aa(),xa))).diffCommand},{name:"date",load:async()=>(await Promise.resolve().then(()=>(Na(),Ca))).dateCommand},{name:"sleep",load:async()=>(await Promise.resolve().then(()=>(ka(),va))).sleepCommand},{name:"timeout",load:async()=>(await Promise.resolve().then(()=>($a(),Ia))).timeoutCommand},{name:"seq",load:async()=>(await Promise.resolve().then(()=>(Pa(),Ra))).seqCommand},{name:"expr",load:async()=>(await Promise.resolve().then(()=>(Da(),Oa))).exprCommand},{name:"html-to-markdown",load:async()=>(await Promise.resolve().then(()=>(La(),Ta))).htmlToMarkdownCommand},{name:"help",load:async()=>(await Promise.resolve().then(()=>(Ma(),Fa))).helpCommand},{name:"which",load:async()=>(await Promise.resolve().then(()=>(Wa(),_a))).whichCommand}],hd=[{name:"curl",load:async()=>(await Promise.resolve().then(()=>(Za(),Va))).curlCommand}],Ka=new Map;function Xa(t){return{name:t.name,async execute(e,r){let n=Ka.get(t.name);return n||(n=await t.load(),Ka.set(t.name,n)),n.execute(e,r)}}}function Ya(t){return(t?Qa.filter(r=>t.includes(r.name)):Qa).map(Xa)}function Ja(){return hd.map(Xa)}function eo(t){return"load"in t&&typeof t.load=="function"}function to(t){let e=null;return{name:t.name,async execute(r,n){return e||(e=await t.load()),e.execute(r,n)}}}var pd=new TextEncoder,md=new TextDecoder;function fn(t,e){if(t instanceof Uint8Array)return t;switch(e){case"base64":return Uint8Array.from(atob(t),r=>r.charCodeAt(0));case"hex":{let r=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)r[n/2]=parseInt(t.slice(n,n+2),16);return r}case"binary":case"latin1":return Uint8Array.from(t,r=>r.charCodeAt(0));default:return pd.encode(t)}}function ro(t,e){switch(e){case"base64":return btoa(String.fromCharCode(...t));case"hex":return Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");case"binary":case"latin1":return String.fromCharCode(...t);default:return md.decode(t)}}function rr(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var nr=new TextEncoder;function yd(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var tt=class{data=new Map;constructor(e){if(this.data.set("/",{type:"directory",mode:493,mtime:new Date}),e)for(let[r,n]of Object.entries(e))yd(n)?this.writeFileSync(r,n.content,void 0,{mode:n.mode,mtime:n.mtime}):this.writeFileSync(r,n)}normalizePath(e){if(!e||e==="/")return"/";let r=e.endsWith("/")&&e!=="/"?e.slice(0,-1):e;r.startsWith("/")||(r=`/${r}`);let n=r.split("/").filter(i=>i&&i!=="."),s=[];for(let i of n)i===".."?s.pop():s.push(i);return`/${s.join("/")}`||"/"}dirname(e){let r=this.normalizePath(e);if(r==="/")return"/";let n=r.lastIndexOf("/");return n===0?"/":r.slice(0,n)}ensureParentDirs(e){let r=this.dirname(e);r!=="/"&&(this.data.has(r)||(this.ensureParentDirs(r),this.data.set(r,{type:"directory",mode:493,mtime:new Date})))}writeFileSync(e,r,n,s){let i=this.normalizePath(e);this.ensureParentDirs(i);let a=rr(n),o=fn(r,a);this.data.set(i,{type:"file",content:o,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,r){let n=await this.readFileBuffer(e),s=rr(r);return ro(n,s)}async readFileBuffer(e){let r=this.normalizePath(e),n=this.data.get(r),s=r;if(!n)throw new Error(`ENOENT: no such file or directory, open '${e}'`);let i=new Set;for(;n&&n.type==="symlink";){if(i.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);i.add(s),s=this.resolveSymlink(s,n.target),n=this.data.get(s)}if(!n)throw new Error(`ENOENT: no such file or directory, open '${e}'`);if(n.type!=="file")throw new Error(`EISDIR: illegal operation on a directory, read '${e}'`);return n.content instanceof Uint8Array?n.content:nr.encode(n.content)}async writeFile(e,r,n){this.writeFileSync(e,r,n)}async appendFile(e,r,n){let s=this.normalizePath(e),i=this.data.get(s);if(i&&i.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let a=rr(n),o=fn(r,a);if(i?.type==="file"){let c=i.content instanceof Uint8Array?i.content:nr.encode(i.content),l=new Uint8Array(c.length+o.length);l.set(c),l.set(o,c.length),this.data.set(s,{type:"file",content:l,mode:i.mode,mtime:new Date})}else this.writeFileSync(e,r,n)}async exists(e){return this.data.has(this.normalizePath(e))}async stat(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);if(n.type==="symlink"){let i=this.resolveSymlink(r,n.target),a=this.data.get(i);if(!a)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);n=a}let s=0;return n.type==="file"&&n.content&&(n.content instanceof Uint8Array?s=n.content.length:s=nr.encode(n.content).length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:s,mtime:n.mtime||new Date}}async lstat(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, lstat '${e}'`);if(n.type==="symlink")return{isFile:!1,isDirectory:!1,isSymbolicLink:!0,mode:n.mode,size:n.target.length,mtime:n.mtime||new Date};let s=0;return n.type==="file"&&n.content&&(n.content instanceof Uint8Array?s=n.content.length:s=nr.encode(n.content).length),{isFile:n.type==="file",isDirectory:n.type==="directory",isSymbolicLink:!1,mode:n.mode,size:s,mtime:n.mtime||new Date}}resolveSymlink(e,r){if(r.startsWith("/"))return this.normalizePath(r);let n=this.dirname(e);return this.normalizePath(n==="/"?`/${r}`:`${n}/${r}`)}async mkdir(e,r){this.mkdirSync(e,r)}mkdirSync(e,r){let n=this.normalizePath(e);if(this.data.has(n)){if(this.data.get(n)?.type==="file")throw new Error(`EEXIST: file already exists, mkdir '${e}'`);if(!r?.recursive)throw new Error(`EEXIST: directory already exists, mkdir '${e}'`);return}let s=this.dirname(n);if(s!=="/"&&!this.data.has(s))if(r?.recursive)this.mkdirSync(s,{recursive:!0});else throw new Error(`ENOENT: no such file or directory, mkdir '${e}'`);this.data.set(n,{type:"directory",mode:493,mtime:new Date})}async readdir(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, scandir '${e}'`);if(n.type!=="directory")throw new Error(`ENOTDIR: not a directory, scandir '${e}'`);let s=r==="/"?"/":`${r}/`,i=[];for(let a of this.data.keys())if(a!==r&&a.startsWith(s)){let c=a.slice(s.length).split("/")[0];c&&!i.includes(c)&&i.push(c)}return i.sort()}async rm(e,r){let n=this.normalizePath(e),s=this.data.get(n);if(!s){if(r?.force)return;throw new Error(`ENOENT: no such file or directory, rm '${e}'`)}if(s.type==="directory"){let i=await this.readdir(n);if(i.length>0){if(!r?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let a of i){let o=n==="/"?`/${a}`:`${n}/${a}`;await this.rm(o,r)}}}this.data.delete(n)}async cp(e,r,n){let s=this.normalizePath(e),i=this.normalizePath(r),a=this.data.get(s);if(!a)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(a.type==="file")this.ensureParentDirs(i),this.data.set(i,{...a});else if(a.type==="directory"){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(i,{recursive:!0});let o=await this.readdir(s);for(let c of o){let l=s==="/"?`/${c}`:`${s}/${c}`,u=i==="/"?`/${c}`:`${i}/${c}`;await this.cp(l,u,n)}}}async mv(e,r){await this.cp(e,r,{recursive:!0}),await this.rm(e,{recursive:!0})}getAllPaths(){return Array.from(this.data.keys())}resolvePath(e,r){if(r.startsWith("/"))return this.normalizePath(r);let n=e==="/"?`/${r}`:`${e}/${r}`;return this.normalizePath(n)}async chmod(e,r){let n=this.normalizePath(e),s=this.data.get(n);if(!s)throw new Error(`ENOENT: no such file or directory, chmod '${e}'`);s.mode=r}async symlink(e,r){let n=this.normalizePath(r);if(this.data.has(n))throw new Error(`EEXIST: file already exists, symlink '${r}'`);this.ensureParentDirs(n),this.data.set(n,{type:"symlink",target:e,mode:511,mtime:new Date})}async link(e,r){let n=this.normalizePath(e),s=this.normalizePath(r),i=this.data.get(n);if(!i)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(i.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${r}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:i.content,mode:i.mode,mtime:i.mtime})}async readlink(e){let r=this.normalizePath(e),n=this.data.get(r);if(!n)throw new Error(`ENOENT: no such file or directory, readlink '${e}'`);if(n.type!=="symlink")throw new Error(`EINVAL: invalid argument, readlink '${e}'`);return n.target}};Y();Y();function ie(t,e){return{type:"ArithmeticExpression",expression:Le(t,e,0).expr}}function Le(t,e,r){return gd(t,e,r)}function gd(t,e,r){let{expr:n,pos:s}=ir(t,e,r);for(s=ee(e,s);e[s]===",";){s++;let{expr:i,pos:a}=ir(t,e,s);n={type:"ArithBinary",operator:",",left:n,right:i},s=ee(e,a)}return{expr:n,pos:s}}function ir(t,e,r){let{expr:n,pos:s}=wd(t,e,r);if(s=ee(e,s),e[s]==="?"){s++;let{expr:i,pos:a}=Le(t,e,s);if(s=ee(e,a),e[s]===":"){s++;let{expr:o,pos:c}=Le(t,e,s);return{expr:{type:"ArithTernary",condition:n,consequent:i,alternate:o},pos:c}}}return{expr:n,pos:s}}function wd(t,e,r){let{expr:n,pos:s}=no(t,e,r);for(;s=ee(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:i,pos:a}=no(t,e,s);n={type:"ArithBinary",operator:"||",left:n,right:i},s=a}return{expr:n,pos:s}}function no(t,e,r){let{expr:n,pos:s}=so(t,e,r);for(;s=ee(e,s),e.slice(s,s+2)==="&&";){s+=2;let{expr:i,pos:a}=so(t,e,s);n={type:"ArithBinary",operator:"&&",left:n,right:i},s=a}return{expr:n,pos:s}}function so(t,e,r){let{expr:n,pos:s}=io(t,e,r);for(;s=ee(e,s),e[s]==="|"&&e[s+1]!=="|";){s++;let{expr:i,pos:a}=io(t,e,s);n={type:"ArithBinary",operator:"|",left:n,right:i},s=a}return{expr:n,pos:s}}function io(t,e,r){let{expr:n,pos:s}=ao(t,e,r);for(;s=ee(e,s),e[s]==="^";){s++;let{expr:i,pos:a}=ao(t,e,s);n={type:"ArithBinary",operator:"^",left:n,right:i},s=a}return{expr:n,pos:s}}function ao(t,e,r){let{expr:n,pos:s}=oo(t,e,r);for(;s=ee(e,s),e[s]==="&"&&e[s+1]!=="&";){s++;let{expr:i,pos:a}=oo(t,e,s);n={type:"ArithBinary",operator:"&",left:n,right:i},s=a}return{expr:n,pos:s}}function oo(t,e,r){let{expr:n,pos:s}=lo(t,e,r);for(;s=ee(e,s),e.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let i=e.slice(s,s+2);s+=2;let{expr:a,pos:o}=lo(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}return{expr:n,pos:s}}function lo(t,e,r){let{expr:n,pos:s}=dn(t,e,r);for(;;)if(s=ee(e,s),e.slice(s,s+2)==="<="||e.slice(s,s+2)===">="){let i=e.slice(s,s+2);s+=2;let{expr:a,pos:o}=dn(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}else if(e[s]==="<"||e[s]===">"){let i=e[s];s++;let{expr:a,pos:o}=dn(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}else break;return{expr:n,pos:s}}function dn(t,e,r){let{expr:n,pos:s}=co(t,e,r);for(;s=ee(e,s),e.slice(s,s+2)==="<<"||e.slice(s,s+2)===">>";){let i=e.slice(s,s+2);s+=2;let{expr:a,pos:o}=co(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}return{expr:n,pos:s}}function co(t,e,r){let{expr:n,pos:s}=uo(t,e,r);for(;s=ee(e,s),(e[s]==="+"||e[s]==="-")&&e[s+1]!==e[s];){let i=e[s];s++;let{expr:a,pos:o}=uo(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}return{expr:n,pos:s}}function uo(t,e,r){let{expr:n,pos:s}=sr(t,e,r);for(;;)if(s=ee(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:i,pos:a}=sr(t,e,s);n={type:"ArithBinary",operator:"*",left:n,right:i},s=a}else if(e[s]==="/"||e[s]==="%"){let i=e[s];s++;let{expr:a,pos:o}=sr(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}else break;return{expr:n,pos:s}}function sr(t,e,r){let{expr:n,pos:s}=hn(t,e,r),i=ee(e,s);if(e.slice(i,i+2)==="**"){i+=2;let{expr:a,pos:o}=sr(t,e,i);return{expr:{type:"ArithBinary",operator:"**",left:n,right:a},pos:o}}return{expr:n,pos:s}}function hn(t,e,r){let n=ee(e,r);if(e.slice(n,n+2)==="++"||e.slice(n,n+2)==="--"){let s=e.slice(n,n+2);n+=2;let{expr:i,pos:a}=hn(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:a}}if(e[n]==="+"||e[n]==="-"||e[n]==="!"||e[n]==="~"){let s=e[n];n++;let{expr:i,pos:a}=hn(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:a}}return bd(t,e,n)}function Ed(t,e){let r=t[e];return r==="$"||r==="`"}function bd(t,e,r){let{expr:n,pos:s}=fo(t,e,r),i=[n];for(;Ed(e,s);){let{expr:a,pos:o}=fo(t,e,s);i.push(a),s=o}if(i.length>1&&(n={type:"ArithConcat",parts:i}),s=ee(e,s),e.slice(s,s+2)==="++"||e.slice(s,s+2)==="--"){let a=e.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:a,operand:n,prefix:!1},pos:s}}return{expr:n,pos:s}}function fo(t,e,r){let n=ee(e,r);if(e.slice(n,n+3)==="$(("){n+=3;let s=1,i=n;for(;n<e.length-1&&s>0;)e[n]==="("&&e[n+1]==="("?(s++,n+=2):e[n]===")"&&e[n+1]===")"?(s--,s>0&&(n+=2)):n++;let a=e.slice(i,n),{expr:o}=Le(t,a,0);return n+=2,{expr:{type:"ArithNested",expression:o},pos:n}}if(e.slice(n,n+2)==="$("&&e[n+2]!=="("){n+=2;let s=1,i=n;for(;n<e.length&&s>0;)e[n]==="("?s++:e[n]===")"&&s--,s>0&&n++;let a=e.slice(i,n);return n++,{expr:{type:"ArithCommandSubst",command:a},pos:n}}if(e[n]==="`"){n++;let s=n;for(;n<e.length&&e[n]!=="`";)n++;let i=e.slice(s,n);return e[n]==="`"&&n++,{expr:{type:"ArithCommandSubst",command:i},pos:n}}if(e[n]==="("){n++;let{expr:s,pos:i}=Le(t,e,n);return n=ee(e,i),e[n]===")"&&n++,{expr:{type:"ArithGroup",expression:s},pos:n}}if(/[0-9]/.test(e[n])){let s="",i=!1;for(;n<e.length;){let o=e[n];if(i)if(/[0-9a-zA-Z@_]/.test(o))s+=o,n++;else break;else if(o==="#")i=!0,s+=o,n++;else if(/[0-9a-fA-FxX]/.test(o))s+=o,n++;else break}if(e[n]==="."&&/[0-9]/.test(e[n+1]))throw new ne(`${s}.${e[n+1]}...: syntax error: invalid arithmetic operator`);if(e[n]==="["){let o=e.slice(n).trim();return{expr:{type:"ArithNumberSubscript",number:s,errorToken:o},pos:e.length}}return{expr:{type:"ArithNumber",value:mt(s)},pos:n}}if(e[n]==="$"&&e[n+1]==="{"){let s=n+2,i=1,a=s;for(;a<e.length&&i>0;)e[a]==="{"?i++:e[a]==="}"&&i--,i>0&&a++;let o=e.slice(s,a),c=a+1;if(e[c]==="#"){let l=c+1;for(;l<e.length&&/[0-9a-zA-Z@_]/.test(e[l]);)l++;let u=e.slice(c+1,l);return{expr:{type:"ArithDynamicBase",baseExpr:o,value:u},pos:l}}if(/[0-9]/.test(e[c])||e[c]==="x"||e[c]==="X"){let l=c;if(e[c]==="x"||e[c]==="X")for(l++;l<e.length&&/[0-9a-fA-F]/.test(e[l]);)l++;else for(;l<e.length&&/[0-9]/.test(e[l]);)l++;let u=e.slice(c,l);return{expr:{type:"ArithDynamicNumber",prefix:o,suffix:u},pos:l}}return n=c,{expr:{type:"ArithBracedExpansion",content:o},pos:n}}if(e[n]==="$"&&n+1<e.length&&/[0-9]/.test(e[n+1])){n++;let s="";for(;n<e.length&&/[0-9]/.test(e[n]);)s+=e[n],n++;return{expr:{type:"ArithVariable",name:s},pos:n}}if(e[n]==="$"&&n+1<e.length&&/[a-zA-Z_]/.test(e[n+1])&&n++,/[a-zA-Z_]/.test(e[n])){let s="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)s+=e[n],n++;if(e[n]==="["){n++;let a;if(e[n]==="'"||e[n]==='"'){let l=e[n];for(n++,a="";n<e.length&&e[n]!==l;)a+=e[n],n++;e[n]===l&&n++,n=ee(e,n),e[n]==="]"&&n++}let o;if(a===void 0){let{expr:l,pos:u}=Le(t,e,n);o=l,n=u,e[n]==="]"&&n++}if(n=ee(e,n),e[n]==="["&&o)return{expr:{type:"ArithDoubleSubscript",array:s,index:o},pos:n};let c=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let l of c)if(e.slice(n,n+l.length)===l&&e.slice(n,n+l.length+1)!=="=="){n+=l.length;let{expr:u,pos:f}=ir(t,e,n);return{expr:{type:"ArithAssignment",operator:l,variable:s,subscript:o,stringKey:a,value:u},pos:f}}return{expr:{type:"ArithArrayElement",array:s,index:o,stringKey:a},pos:n}}n=ee(e,n);let i=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let a of i)if(e.slice(n,n+a.length)===a&&e.slice(n,n+a.length+1)!=="=="){n+=a.length;let{expr:o,pos:c}=ir(t,e,n);return{expr:{type:"ArithAssignment",operator:a,variable:s,value:o},pos:c}}return{expr:{type:"ArithVariable",name:s},pos:n}}return{expr:{type:"ArithNumber",value:0},pos:n}}function mt(t){if(t.includes("#")){let[e,r]=t.split("#"),n=Number.parseInt(e,10);if(n<2||n>64)return Number.NaN;if(n<=36)return Number.parseInt(r,n);let s=0;for(let i of r){let a;if(i>="0"&&i<="9")a=i.charCodeAt(0)-48;else if(i>="a"&&i<="z")a=i.charCodeAt(0)-97+10;else if(i>="A"&&i<="Z")a=i.charCodeAt(0)-65+36;else if(i==="@")a=62;else if(i==="_")a=63;else return Number.NaN;if(a>=n)return Number.NaN;s=s*n+a}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 ee(t,e){for(;e<t.length;){if(t[e]==="\\"&&t[e+1]===`
438
+ `){e+=2;continue}if(/\s/.test(t[e])){e++;continue}break}return e}var k={script(t){return{type:"Script",statements:t}},statement(t,e=[],r=!1){return{type:"Statement",pipelines:t,operators:e,background:r}},pipeline(t,e=!1){return{type:"Pipeline",commands:t,negated:e}},simpleCommand(t,e=[],r=[],n=[]){return{type:"SimpleCommand",name:t,args:e,assignments:r,redirections:n}},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,r=!1,n=null){return{type:"Assignment",name:t,value:e,append:r,array:n}},redirection(t,e,r=null){return{type:"Redirection",fd:r,operator:t,target:e}},hereDoc(t,e,r=!1,n=!1){return{type:"HereDoc",delimiter:t,content:e,stripTabs:r,quoted:n}},ifNode(t,e=null,r=[]){return{type:"If",clauses:t,elseBody:e,redirections:r}},forNode(t,e,r,n=[]){return{type:"For",variable:t,words:e,body:r,redirections:n}},whileNode(t,e,r=[]){return{type:"While",condition:t,body:e,redirections:r}},untilNode(t,e,r=[]){return{type:"Until",condition:t,body:e,redirections:r}},caseNode(t,e,r=[]){return{type:"Case",word:t,items:e,redirections:r}},caseItem(t,e,r=";;"){return{type:"CaseItem",patterns:t,body:e,terminator:r}},subshell(t,e=[]){return{type:"Subshell",body:t,redirections:e}},group(t,e=[]){return{type:"Group",body:t,redirections:e}},functionDef(t,e,r=[]){return{type:"FunctionDef",name:t,body:e,redirections:r}},conditionalCommand(t,e=[]){return{type:"ConditionalCommand",expression:t,redirections:e}},arithmeticCommand(t,e=[]){return{type:"ArithmeticCommand",expression:t,redirections:e}}};var m;(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"})(m||(m={}));var ar={if:m.IF,then:m.THEN,else:m.ELSE,elif:m.ELIF,fi:m.FI,for:m.FOR,while:m.WHILE,until:m.UNTIL,do:m.DO,done:m.DONE,case:m.CASE,esac:m.ESAC,in:m.IN,function:m.FUNCTION,select:m.SELECT,time:m.TIME,coproc:m.COPROC};function po(t){let e=t.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);if(!e)return!1;let r=t.slice(e[0].length);if(r===""||r==="+")return!0;if(r[0]==="["){let n=0,s=0;for(;s<r.length;s++)if(r[s]==="[")n++;else if(r[s]==="]"&&(n--,n===0))break;if(n!==0||s>=r.length)return!1;let i=r.slice(s+1);return i===""||i==="+"}return!1}var Sd=[[";",";","&",m.SEMI_SEMI_AND],["<","<","<",m.TLESS],["&",">",">",m.AND_DGREAT]],xd=[["[","[",m.DBRACK_START],["]","]",m.DBRACK_END],["(","(",m.DPAREN_START],[")",")",m.DPAREN_END],["&","&",m.AND_AND],["|","|",m.OR_OR],[";",";",m.DSEMI],[";","&",m.SEMI_AND],["|","&",m.PIPE_AMP],[">",">",m.DGREAT],["<","&",m.LESSAND],[">","&",m.GREATAND],["<",">",m.LESSGREAT],[">","|",m.CLOBBER],["&",">",m.AND_GREAT]],Ad={"|":m.PIPE,"&":m.AMP,";":m.SEMICOLON,"(":m.LPAREN,")":m.RPAREN,"<":m.LESS,">":m.GREAT};function Cd(t){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)}var or=class{input;pos=0;line=1;column=1;tokens=[];pendingHeredocs=[];constructor(e){this.input=e}tokenize(){let r=this.input.length,n=this.tokens,s=this.pendingHeredocs;for(;this.pos<r&&(this.skipWhitespace(),!(this.pos>=r));){if(s.length>0&&n.length>0&&n[n.length-1].type===m.NEWLINE){this.readHeredocContent();continue}let i=this.nextToken();i&&n.push(i)}return n.push({type:m.EOF,value:"",start:this.pos,end:this.pos,line:this.line,column:this.column}),n}skipWhitespace(){let e=this.input,r=e.length,n=this.pos,s=this.column,i=this.line;for(;n<r;){let a=e[n];if(a===" "||a===" ")n++,s++;else if(a==="\\"&&e[n+1]===`
439
439
  `)n+=2,i++,s=1;else break}this.pos=n,this.column=s,this.line=i}nextToken(){let e=this.input,r=this.pos,n=this.line,s=this.column,i=e[r],a=e[r+1],o=e[r+2];if(i==="#")return this.readComment(r,n,s);if(i===`
440
440
  `)return this.pos=r+1,this.line++,this.column=1,{type:m.NEWLINE,value:`
441
- `,start:r,end:r+1,line:n,column:s};if(i==="<"&&a==="<"&&o==="-")return this.pos=r+3,this.column=s+3,this.registerHeredocFromLookahead(!0),this.makeToken(m.DLESSDASH,"<<-",r,n,s);for(let[l,u,f,d]of pd)if(i===l&&a===u&&o===f)return this.pos=r+3,this.column=s+3,this.makeToken(d,l+u+f,r,n,s);if(i==="<"&&a==="<")return this.pos=r+2,this.column=s+2,this.registerHeredocFromLookahead(!1),this.makeToken(m.DLESS,"<<",r,n,s);for(let[l,u,f]of md)if(i===l&&a===u)return this.pos=r+2,this.column=s+2,this.makeToken(f,l+u,r,n,s);let c=yd[i];return c?(this.pos=r+1,this.column=s+1,this.makeToken(c,i,r,n,s)):i==="{"?a==="}"?(this.pos=r+2,this.column=s+2,{type:m.WORD,value:"{}",start:r,end:r+2,line:n,column:s,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(r)!==null?this.readWordWithBraceExpansion(r,n,s):this.scanLiteralBraceWord(r)!==null?this.readWordWithBraceExpansion(r,n,s):a!==void 0&&a!==" "&&a!==" "&&a!==`
441
+ `,start:r,end:r+1,line:n,column:s};if(i==="<"&&a==="<"&&o==="-")return this.pos=r+3,this.column=s+3,this.registerHeredocFromLookahead(!0),this.makeToken(m.DLESSDASH,"<<-",r,n,s);for(let[l,u,f,d]of Sd)if(i===l&&a===u&&o===f)return this.pos=r+3,this.column=s+3,this.makeToken(d,l+u+f,r,n,s);if(i==="<"&&a==="<")return this.pos=r+2,this.column=s+2,this.registerHeredocFromLookahead(!1),this.makeToken(m.DLESS,"<<",r,n,s);for(let[l,u,f]of xd)if(i===l&&a===u)return this.pos=r+2,this.column=s+2,this.makeToken(f,l+u,r,n,s);let c=Ad[i];return c?(this.pos=r+1,this.column=s+1,this.makeToken(c,i,r,n,s)):i==="{"?a==="}"?(this.pos=r+2,this.column=s+2,{type:m.WORD,value:"{}",start:r,end:r+2,line:n,column:s,quoted:!1,singleQuoted:!1}):this.scanBraceExpansion(r)!==null?this.readWordWithBraceExpansion(r,n,s):this.scanLiteralBraceWord(r)!==null?this.readWordWithBraceExpansion(r,n,s):a!==void 0&&a!==" "&&a!==" "&&a!==`
442
442
  `?this.readWord(r,n,s):(this.pos=r+1,this.column=s+1,this.makeToken(m.LBRACE,"{",r,n,s)):i==="}"?this.isWordCharFollowing(r+1)?this.readWord(r,n,s):(this.pos=r+1,this.column=s+1,this.makeToken(m.RBRACE,"}",r,n,s)):i==="!"?a==="="?(this.pos=r+2,this.column=s+2,this.makeToken(m.WORD,"!=",r,n,s)):(this.pos=r+1,this.column=s+1,this.makeToken(m.BANG,"!",r,n,s)):this.readWord(r,n,s)}makeToken(e,r,n,s,i){return{type:e,value:r,start:n,end:this.pos,line:s,column:i}}readComment(e,r,n){let s=this.input,i=s.length,a=this.pos;for(;a<i&&s[a]!==`
443
443
  `;)a++;let o=s.slice(e,a);return this.pos=a,this.column=n+(a-e),{type:m.COMMENT,value:o,start:e,end:a,line:r,column:n}}readWord(e,r,n){let s=this.input,i=s.length,a=this.pos,o=a;for(;a<i;){let w=s[a];if(w===" "||w===" "||w===`
444
444
  `||w===";"||w==="&"||w==="|"||w==="("||w===")"||w==="<"||w===">"||w==="'"||w==='"'||w==="\\"||w==="$"||w==="`"||w==="{"||w==="}"||w==="~"||w==="*"||w==="?"||w==="[")break;a++}if(a>o){let w=s[a];if(a>=i||w===" "||w===" "||w===`
445
- `||w===";"||w==="&"||w==="|"||w==="("||w===")"||w==="<"||w===">"){let g=s.slice(o,a);if(this.pos=a,this.column=n+(a-o),rr[g])return{type:rr[g],value:g,start:e,end:a,line:r,column:n};let E=g.indexOf("=");return E>0&&co(g.slice(0,E))?{type:m.ASSIGNMENT_WORD,value:g,start:e,end:a,line:r,column:n}:/^[0-9]+$/.test(g)?{type:m.NUMBER,value:g,start:e,end:a,line:r,column:n}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g)?{type:m.NAME,value:g,start:e,end:a,line:r,column:n,quoted:!1,singleQuoted:!1}:{type:m.WORD,value:g,start:e,end:a,line:r,column:n,quoted:!1,singleQuoted:!1}}}a=this.pos;let c=this.column,l=this.line,u="",f=!1,d=!1,h=!1,p=!1,b=s[a]==='"'||s[a]==="'";for(;a<i;){let w=s[a];if(!h&&!p&&(w===" "||w===" "||w===`
446
- `||w===";"||w==="&"||w==="|"||w==="("||w===")"||w==="<"||w===">"))break;if(w==="$"&&a+1<i&&s[a+1]==="'"&&!h&&!p){for(u+="$'",a+=2,c+=2;a<i&&s[a]!=="'";)s[a]==="\\"&&a+1<i?(u+=s[a]+s[a+1],a+=2,c+=2):(u+=s[a],a++,c++);a<i&&(u+="'",a++,c++);continue}if(w==="$"&&a+1<i&&s[a+1]==='"'&&!h&&!p){a++,c++,p=!0,f=!0,u===""&&(b=!0),a++,c++;continue}if(w==="'"&&!p){h?(h=!1,b||(u+=w)):(h=!0,b?(d=!0,f=!0):u+=w),a++,c++;continue}if(w==='"'&&!h){p?(p=!1,b||(u+=w)):(p=!0,b?f=!0:u+=w),a++,c++;continue}if(w==="\\"&&!h&&a+1<i){let g=s[a+1];if(g===`
445
+ `||w===";"||w==="&"||w==="|"||w==="("||w===")"||w==="<"||w===">"){let g=s.slice(o,a);if(this.pos=a,this.column=n+(a-o),ar[g])return{type:ar[g],value:g,start:e,end:a,line:r,column:n};let b=g.indexOf("=");return b>0&&po(g.slice(0,b))?{type:m.ASSIGNMENT_WORD,value:g,start:e,end:a,line:r,column:n}:/^[0-9]+$/.test(g)?{type:m.NUMBER,value:g,start:e,end:a,line:r,column:n}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(g)?{type:m.NAME,value:g,start:e,end:a,line:r,column:n,quoted:!1,singleQuoted:!1}:{type:m.WORD,value:g,start:e,end:a,line:r,column:n,quoted:!1,singleQuoted:!1}}}a=this.pos;let c=this.column,l=this.line,u="",f=!1,d=!1,h=!1,p=!1,E=s[a]==='"'||s[a]==="'";for(;a<i;){let w=s[a];if(!h&&!p&&(w===" "||w===" "||w===`
446
+ `||w===";"||w==="&"||w==="|"||w==="("||w===")"||w==="<"||w===">"))break;if(w==="$"&&a+1<i&&s[a+1]==="'"&&!h&&!p){for(u+="$'",a+=2,c+=2;a<i&&s[a]!=="'";)s[a]==="\\"&&a+1<i?(u+=s[a]+s[a+1],a+=2,c+=2):(u+=s[a],a++,c++);a<i&&(u+="'",a++,c++);continue}if(w==="$"&&a+1<i&&s[a+1]==='"'&&!h&&!p){a++,c++,p=!0,f=!0,u===""&&(E=!0),a++,c++;continue}if(w==="'"&&!p){h?(h=!1,E||(u+=w)):(h=!0,E?(d=!0,f=!0):u+=w),a++,c++;continue}if(w==='"'&&!h){p?(p=!1,E||(u+=w)):(p=!0,E?f=!0:u+=w),a++,c++;continue}if(w==="\\"&&!h&&a+1<i){let g=s[a+1];if(g===`
447
447
  `){a+=2,l++,c=1;continue}if(p){if(g==='"'||g==="\\"||g==="$"||g==="`"||g===`
448
- `){g==="$"||g==="`"?u+=w+g:u+=g,a+=2,c+=2;continue}}else{g==='"'||g==="'"?u+=w+g:u+=g,a+=2,c+=2;continue}}if(w==="$"&&a+1<i&&s[a+1]==="("){u+=w,a++,c++,u+=s[a],a++,c++;let g=1,E=!1,x=!1,S=0,v=!1,R="",M=s[a]==="(";for(;g>0&&a<i;){let _=s[a];if(u+=_,E)_==="'"&&(E=!1);else if(x)_==="\\"&&a+1<i?(u+=s[a+1],a++,c++):_==='"'&&(x=!1);else if(_==="'")E=!0,R="";else if(_==='"')x=!0,R="";else if(_==="\\"&&a+1<i)u+=s[a+1],a++,c++,R="";else if(_==="#"&&!M&&(R===""||/\s/.test(s[a-1]||""))){for(;a+1<i&&s[a+1]!==`
449
- `;)a++,c++,u+=s[a];R=""}else/[a-zA-Z_]/.test(_)?R+=_:(R==="case"?(S++,v=!1):R==="in"&&S>0?v=!0:R==="esac"&&S>0&&(S--,v=!1),R="",_==="("?a>0&&s[a-1]==="$"?g++:v||g++:_===")"?v?v=!1:g--:_===";"&&S>0&&a+1<i&&s[a+1]===";"&&(v=!0));_===`
450
- `&&(l++,c=0,R=""),a++,c++}continue}if(w==="$"&&a+1<i&&s[a+1]==="["){u+=w,a++,c++,u+=s[a],a++,c++;let g=1;for(;g>0&&a<i;){let E=s[a];u+=E,E==="["?g++:E==="]"?g--:E===`
451
- `&&(l++,c=0),a++,c++}continue}if(w==="$"&&a+1<i&&s[a+1]==="{"){u+=w,a++,c++,u+=s[a],a++,c++;let g=1;for(;g>0&&a<i;){let E=s[a];u+=E,E==="{"?g++:E==="}"?g--:E===`
448
+ `){g==="$"||g==="`"?u+=w+g:u+=g,a+=2,c+=2;continue}}else{g==='"'||g==="'"?u+=w+g:u+=g,a+=2,c+=2;continue}}if(w==="$"&&a+1<i&&s[a+1]==="("){u+=w,a++,c++,u+=s[a],a++,c++;let g=1,b=!1,S=!1,x=0,A=!1,O="",L=s[a]==="(";for(;g>0&&a<i;){let R=s[a];if(u+=R,b)R==="'"&&(b=!1);else if(S)R==="\\"&&a+1<i?(u+=s[a+1],a++,c++):R==='"'&&(S=!1);else if(R==="'")b=!0,O="";else if(R==='"')S=!0,O="";else if(R==="\\"&&a+1<i)u+=s[a+1],a++,c++,O="";else if(R==="#"&&!L&&(O===""||/\s/.test(s[a-1]||""))){for(;a+1<i&&s[a+1]!==`
449
+ `;)a++,c++,u+=s[a];O=""}else/[a-zA-Z_]/.test(R)?O+=R:(O==="case"?(x++,A=!1):O==="in"&&x>0?A=!0:O==="esac"&&x>0&&(x--,A=!1),O="",R==="("?a>0&&s[a-1]==="$"?g++:A||g++:R===")"?A?A=!1:g--:R===";"&&x>0&&a+1<i&&s[a+1]===";"&&(A=!0));R===`
450
+ `&&(l++,c=0,O=""),a++,c++}continue}if(w==="$"&&a+1<i&&s[a+1]==="["){u+=w,a++,c++,u+=s[a],a++,c++;let g=1;for(;g>0&&a<i;){let b=s[a];u+=b,b==="["?g++:b==="]"?g--:b===`
451
+ `&&(l++,c=0),a++,c++}continue}if(w==="$"&&a+1<i&&s[a+1]==="{"){u+=w,a++,c++,u+=s[a],a++,c++;let g=1;for(;g>0&&a<i;){let b=s[a];u+=b,b==="{"?g++:b==="}"?g--:b===`
452
452
  `&&(l++,c=0),a++,c++}continue}if(w==="$"&&a+1<i){let g=s[a+1];if(g==="#"||g==="?"||g==="$"||g==="!"||g==="@"||g==="*"||g==="-"||g>="0"&&g<="9"){u+=w+g,a+=2,c+=2;continue}}if(w==="`"){for(u+=w,a++,c++;a<i&&s[a]!=="`";){let g=s[a];u+=g,g==="\\"&&a+1<i&&(u+=s[a+1],a++,c++),g===`
453
453
  `&&(l++,c=0),a++,c++}a<i&&(u+=s[a],a++,c++);continue}u+=w,a++,w===`
454
- `?(l++,c=1):c++}if(this.pos=a,this.column=c,this.line=l,u==="")return{type:m.WORD,value:"",start:e,end:a,line:r,column:n,quoted:f,singleQuoted:d};if(!f&&rr[u])return{type:rr[u],value:u,start:e,end:a,line:r,column:n};if(!b){let w=u.indexOf("=");if(w>0&&co(u.slice(0,w)))return{type:m.ASSIGNMENT_WORD,value:u,start:e,end:a,line:r,column:n,quoted:f,singleQuoted:d}}return/^[0-9]+$/.test(u)?{type:m.NUMBER,value:u,start:e,end:a,line:r,column:n}:gd(u)?{type:m.NAME,value:u,start:e,end:a,line:r,column:n,quoted:f,singleQuoted:d}:{type:m.WORD,value:u,start:e,end:a,line:r,column:n,quoted:f,singleQuoted:d}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let e=this.pendingHeredocs.shift();if(!e)break;let r=this.pos,n=this.line,s=this.column,i="";for(;this.pos<this.input.length;){let a=this.pos,o="";for(;this.pos<this.input.length&&this.input[this.pos]!==`
454
+ `?(l++,c=1):c++}if(this.pos=a,this.column=c,this.line=l,u==="")return{type:m.WORD,value:"",start:e,end:a,line:r,column:n,quoted:f,singleQuoted:d};if(!f&&ar[u])return{type:ar[u],value:u,start:e,end:a,line:r,column:n};if(!E){let w=u.indexOf("=");if(w>0&&po(u.slice(0,w)))return{type:m.ASSIGNMENT_WORD,value:u,start:e,end:a,line:r,column:n,quoted:f,singleQuoted:d}}return/^[0-9]+$/.test(u)?{type:m.NUMBER,value:u,start:e,end:a,line:r,column:n}:Cd(u)?{type:m.NAME,value:u,start:e,end:a,line:r,column:n,quoted:f,singleQuoted:d}:{type:m.WORD,value:u,start:e,end:a,line:r,column:n,quoted:f,singleQuoted:d}}readHeredocContent(){for(;this.pendingHeredocs.length>0;){let e=this.pendingHeredocs.shift();if(!e)break;let r=this.pos,n=this.line,s=this.column,i="";for(;this.pos<this.input.length;){let a=this.pos,o="";for(;this.pos<this.input.length&&this.input[this.pos]!==`
455
455
  `;)o+=this.input[this.pos],this.pos++,this.column++;if((e.stripTabs?o.replace(/^\t+/,""):o)===e.delimiter){this.pos<this.input.length&&this.input[this.pos]===`
456
456
  `&&(this.pos++,this.line++,this.column=1);break}i+=o,this.pos<this.input.length&&this.input[this.pos]===`
457
457
  `&&(i+=`
@@ -459,46 +459,46 @@ ${i}\r
459
459
  `||r===";"||r==="&"||r==="|"||r==="("||r===")"||r==="<"||r===">")}readWordWithBraceExpansion(e,r,n){let s=this.input,i=s.length,a=e,o=n;for(;a<i;){let l=s[a];if(l===" "||l===" "||l===`
460
460
  `||l===";"||l==="&"||l==="|"||l==="("||l===")"||l==="<"||l===">")break;if(l==="{"){if(this.scanBraceExpansion(a)!==null){let f=1;for(a++,o++;a<i&&f>0;)s[a]==="{"?f++:s[a]==="}"&&f--,a++,o++;continue}a++,o++;continue}if(l==="}"){a++,o++;continue}if(l==="$"&&a+1<i&&s[a+1]==="("){a++,o++,a++,o++;let u=1;for(;u>0&&a<i;)s[a]==="("?u++:s[a]===")"&&u--,a++,o++;continue}if(l==="$"&&a+1<i&&s[a+1]==="{"){a++,o++,a++,o++;let u=1;for(;u>0&&a<i;)s[a]==="{"?u++:s[a]==="}"&&u--,a++,o++;continue}if(l==="`"){for(a++,o++;a<i&&s[a]!=="`";)s[a]==="\\"&&a+1<i?(a+=2,o+=2):(a++,o++);a<i&&(a++,o++);continue}a++,o++}let c=s.slice(e,a);return this.pos=a,this.column=o,{type:m.WORD,value:c,start:e,end:a,line:r,column:n,quoted:!1,singleQuoted:!1}}scanBraceExpansion(e){let r=this.input,n=r.length,s=e+1,i=1,a=!1,o=!1;for(;s<n&&i>0;){let c=r[s];if(c==="{")i++,s++;else if(c==="}")i--,s++;else if(c===","&&i===1)a=!0,s++;else if(c==="."&&s+1<n&&r[s+1]===".")o=!0,s+=2;else{if(c===" "||c===" "||c===`
461
461
  `||c===";"||c==="&"||c==="|")return null;s++}}return i===0&&(a||o)?r.slice(e,s):null}scanLiteralBraceWord(e){let r=this.input,n=r.length,s=e+1,i=1;for(;s<n&&i>0;){let a=r[s];if(a==="{")i++,s++;else if(a==="}"){if(i--,i===0)return r.slice(e,s+1);s++}else{if(a===" "||a===" "||a===`
462
- `||a===";"||a==="&"||a==="|")return null;s++}}return null}};var fn=1e6,dn=1e5,uo=1e6,fo=new Set([m.LESS,m.GREAT,m.DLESS,m.DGREAT,m.LESSAND,m.GREATAND,m.LESSGREAT,m.DLESSDASH,m.CLOBBER,m.TLESS,m.AND_GREAT,m.AND_DGREAT]),ho=new Set([m.LESS,m.GREAT,m.DLESS,m.DGREAT,m.LESSAND,m.GREATAND,m.LESSGREAT,m.DLESSDASH,m.CLOBBER,m.TLESS]),Te=class extends Error{line;column;token;constructor(e,r,n,s=void 0){super(`Parse error at ${r}:${n}: ${e}`),this.line=r,this.column=n,this.token=s,this.name="ParseException"}};function mo(t,e,r){let n=r+1;for(;n<e.length&&/[a-zA-Z0-9_-]/.test(e[n]);)n++;return n}function hn(t,e,r,n,s){let i=1,a=r+1;for(;a<e.length&&i>0;)e[a]===n?i++:e[a]===s&&i--,i>0&&a++;return i===0?a:-1}function tt(t,e,r){let n=r,s=1;for(;n<e.length&&s>0;){let i=e[n];if(i==="\\"&&n+1<e.length){n+=2;continue}if(i==="'"){let a=e.indexOf("'",n+1);if(a!==-1){n=a+1;continue}}if(i==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?n+=2:n++;n<e.length&&n++;continue}i==="{"?s++:i==="}"&&s--,s>0&&n++}return n}function yo(t,e,r){let n=r,s=!1;for(;n<e.length;){let i=e[n];if(i==="/"&&s||i==="}")break;if(i==="'"){let a=e.indexOf("'",n+1);if(a!==-1){n=a+1,s=!0;continue}}if(i==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?n+=2:n++;n<e.length&&n++,s=!0;continue}i==="\\"?(n+=2,s=!0):(n++,s=!0)}return n}function go(t,e,r){let n=r,s="";for(;n<e.length;){let i=e[n];if(i==="*"||i==="?")s+=i,n++;else if(i==="["){let a=wd(e,n);a===-1?(s+=i,n++):(s+=e.slice(n,a+1),n=a+1)}else break}return{pattern:s,endIndex:n}}function wd(t,e){let r=e+1;for(r<t.length&&t[r]==="^"&&r++,r<t.length&&t[r]==="]"&&r++;r<t.length;){let n=t[r];if(n==="\\"&&r+1<t.length){r+=2;continue}if(n==="]")return r;if(n==='"'||n==="$"||n==="`")return-1;if(n==="'"){let s=t.indexOf("'",r+1);if(s!==-1){r=s+1;continue}}if(n==="["&&r+1<t.length&&t[r+1]===":"){let s=t.indexOf(":]",r+2);if(s!==-1){r=s+2;continue}}if(n==="["&&r+1<t.length&&(t[r+1]==="."||t[r+1]==="=")){let i=`${t[r+1]}]`,a=t.indexOf(i,r+2);if(a!==-1){r=a+2;continue}}r++}return-1}function wo(t,e,r){let n="",s=r;for(;s<e.length&&e[s]!=="'";){let i=e[s];if(i==="\\"&&s+1<e.length)switch(e[s+1]){case"n":n+=`
463
- `,s+=2;break;case"t":n+=" ",s+=2;break;case"r":n+="\r",s+=2;break;case"\\":n+="\\",s+=2;break;case"'":n+="'",s+=2;break;case'"':n+='"',s+=2;break;case"a":n+="\x07",s+=2;break;case"b":n+="\b",s+=2;break;case"e":case"E":n+="\x1B",s+=2;break;case"f":n+="\f",s+=2;break;case"v":n+="\v",s+=2;break;case"x":{let o=e.slice(s+2,s+4),c=parseInt(o,16);Number.isNaN(c)?(n+="\\x",s+=2):(n+=String.fromCharCode(c),s+=4);break}case"u":{let o=e.slice(s+2,s+6),c=parseInt(o,16);Number.isNaN(c)?(n+="\\u",s+=2):(n+=String.fromCharCode(c),s+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let o="",c=s+1;for(;c<e.length&&c<s+4&&/[0-7]/.test(e[c]);)o+=e[c],c++;let l=parseInt(o,8);n+=String.fromCharCode(l),s=c;break}default:n+=i,s++}else n+=i,s++}return s<e.length&&e[s]==="'"&&s++,{part:k.literal(n),endIndex:s}}function pn(t,e){let r=e.trim();return r===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:se(t,r)}function po(t){let e=[],r="",n=0;for(let s=0;s<t.length;s++){let i=t[s];i==="{"?(n++,r+=i):i==="}"?(n--,r+=i):i===","&&n===0?(e.push(r),r=""):r+=i}return e.push(r),e}function Eo(t,e,r,n){let s=hn(t,e,r,"{","}");if(s===-1)return null;let i=e.slice(r+1,s),a=i.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(a)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(a[1],10),end:Number.parseInt(a[2],10),step:a[3]?Number.parseInt(a[3],10):void 0,startStr:a[1],endStr:a[2]}]},endIndex:s+1};let o=i.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return o?{part:{type:"BraceExpansion",items:[{type:"Range",start:o[1],end:o[2],step:o[3]?Number.parseInt(o[3],10):void 0}]},endIndex:s+1}:i.includes(",")&&n?{part:{type:"BraceExpansion",items:po(i).map(u=>({type:"Word",word:k.word(n(t,u,!1,!1,!1))}))},endIndex:s+1}:i.includes(",")?{part:{type:"BraceExpansion",items:po(i).map(u=>({type:"Word",word:k.word([k.literal(u)])}))},endIndex:s+1}:null}function bo(t,e){let r="";for(let n of e.parts)switch(n.type){case"Literal":case"SingleQuoted":case"Escaped":r+=n.value;break;case"DoubleQuoted":r+='"';for(let s of n.parts)s.type==="Literal"||s.type==="Escaped"?r+=s.value:s.type==="ParameterExpansion"&&(r+=`\${${s.parameter}}`);r+='"';break;case"ParameterExpansion":r+=`\${${n.parameter}}`;break;case"Glob":r+=n.pattern;break;default:r+=n.type}return r}function xo(t,e){return{[m.LESS]:"<",[m.GREAT]:">",[m.DGREAT]:">>",[m.LESSAND]:"<&",[m.GREATAND]:">&",[m.LESSGREAT]:"<>",[m.CLOBBER]:">|",[m.TLESS]:"<<<",[m.AND_GREAT]:"&>",[m.AND_DGREAT]:"&>>",[m.DLESS]:"<",[m.DLESSDASH]:"<"}[e]||">"}function sr(t){let e=t.current(),r=e.type;if(r===m.NUMBER){let n=t.peek(1);return e.end!==n.start?!1:ho.has(n.type)}return fo.has(r)}function ir(t){let e=null;t.check(m.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let r=t.advance(),n=xo(t,r.type);if(r.type===m.DLESS||r.type===m.DLESSDASH)return Ed(t,n,e,r.type===m.DLESSDASH);t.isWord()||t.error("Expected redirection target");let s=t.parseWord();return k.redirection(n,s,e)}function Ed(t,e,r,n){t.isWord()||t.error("Expected here-document delimiter");let s=t.advance(),i=s.value,a=s.quoted||!1;(i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"'))&&(i=i.slice(1,-1));let o=k.redirection(n?"<<-":"<<",k.hereDoc(i,k.word([]),n,a),r);return t.addPendingHeredoc(o,i,n,a),o}function Ao(t){let e=[],r=null,n=[],s=[];for(;t.check(m.ASSIGNMENT_WORD);)t.checkIterationLimit(),e.push(bd(t));for(;sr(t);)t.checkIterationLimit(),s.push(ir(t));for(t.isWord()&&(r=t.parseWord());(!t.isStatementEnd()||t.check(m.RBRACE))&&!t.check(m.PIPE,m.PIPE_AMP);)if(t.checkIterationLimit(),sr(t))s.push(ir(t));else if(t.check(m.RBRACE)){let i=t.advance();n.push(t.parseWordFromString(i.value,!1,!1))}else if(t.isWord())n.push(t.parseWord());else if(t.check(m.ASSIGNMENT_WORD)){let i=t.advance(),a=i.value,o=a.endsWith("="),c=a.endsWith("=(");if((o||c)&&(c||t.check(m.LPAREN))){let l=c?a.slice(0,-2):a.slice(0,-1);c||t.expect(m.LPAREN);let u=mn(t);t.expect(m.RPAREN);let f=u.map(h=>bo(t,h)),d=`${l}=(${f.join(" ")})`;n.push(t.parseWordFromString(d,!1,!1))}else n.push(t.parseWordFromString(a,i.quoted,i.singleQuoted))}else if(t.check(m.LPAREN))t.error("syntax error near unexpected token `('");else break;return k.simpleCommand(r,n,e,s)}function bd(t){let e=t.expect(m.ASSIGNMENT_WORD),r=e.value,n=r.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);n||t.error(`Invalid assignment: ${r}`);let s=n[0],i,a=s.length;if(r[a]==="["){let f=0,d=a+1;for(;a<r.length;a++)if(r[a]==="[")f++;else if(r[a]==="]"&&(f--,f===0))break;f!==0&&t.error(`Invalid assignment: ${r}`),i=r.slice(d,a),a++}let o=r[a]==="+";o&&a++,r[a]!=="="&&t.error(`Invalid assignment: ${r}`),a++;let c=r.slice(a);if(c==="("){let f=mn(t);t.expect(m.RPAREN);let d=i!==void 0?`${s}[${i}]`:s;return k.assignment(d,null,o,f)}if(c===""&&t.check(m.LPAREN)){let f=t.current();if(e.end===f.start){t.advance();let d=mn(t);t.expect(m.RPAREN);let h=i!==void 0?`${s}[${i}]`:s;return k.assignment(h,null,o,d)}}let l=c?t.parseWordFromString(c,e.quoted,e.singleQuoted,!0):null,u=i!==void 0?`${s}[${i}]`:s;return k.assignment(u,l,o,null)}function mn(t){let e=[];for(t.skipNewlines();!t.check(m.RPAREN,m.EOF);)t.checkIterationLimit(),t.isWord()?e.push(t.parseWord()):t.advance(),t.skipNewlines();return e}function yn(t){t.expect(m.IF);let e=[],r=t.parseCompoundList();t.expect(m.THEN);let n=t.parseCompoundList();if(n.length===0){let a=t.check(m.FI)?"fi":t.check(m.ELSE)?"else":t.check(m.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${a}'`)}for(e.push({condition:r,body:n});t.check(m.ELIF);){t.advance();let a=t.parseCompoundList();t.expect(m.THEN);let o=t.parseCompoundList();if(o.length===0){let c=t.check(m.FI)?"fi":t.check(m.ELSE)?"else":t.check(m.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${c}'`)}e.push({condition:a,body:o})}let s=null;t.check(m.ELSE)&&(t.advance(),s=t.parseCompoundList(),s.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(m.FI);let i=t.parseOptionalRedirections();return k.ifNode(e,s,i)}function gn(t){if(t.expect(m.FOR),t.check(m.DPAREN_START))return Sd(t);t.isWord()||t.error("Expected variable name in for loop");let r=t.advance().value,n=null;if(t.skipNewlines(),t.check(m.IN))for(t.advance(),n=[];!t.check(m.SEMICOLON,m.NEWLINE,m.DO,m.EOF)&&t.isWord();)n.push(t.parseWord());t.check(m.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(m.DO);let s=t.parseCompoundList();t.expect(m.DONE);let i=t.parseOptionalRedirections();return k.forNode(r,n,s,i)}function Sd(t){t.expect(m.DPAREN_START);let e=null,r=null,n=null,s=["","",""],i=0,a=0;for(;!t.check(m.DPAREN_END,m.EOF);){let l=t.advance();if(l.type===m.SEMICOLON&&a===0){if(i++,i>2)break}else l.value==="("&&a++,l.value===")"&&a--,s[i]+=l.value}t.expect(m.DPAREN_END),s[0].trim()&&(e=se(t,s[0].trim())),s[1].trim()&&(r=se(t,s[1].trim())),s[2].trim()&&(n=se(t,s[2].trim())),t.skipNewlines(),t.check(m.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(m.DO);let o=t.parseCompoundList();t.expect(m.DONE);let c=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:r,update:n,body:o,redirections:c}}function wn(t){t.expect(m.WHILE);let e=t.parseCompoundList();t.expect(m.DO);let r=t.parseCompoundList();r.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(m.DONE);let n=t.parseOptionalRedirections();return k.whileNode(e,r,n)}function En(t){t.expect(m.UNTIL);let e=t.parseCompoundList();t.expect(m.DO);let r=t.parseCompoundList();r.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(m.DONE);let n=t.parseOptionalRedirections();return k.untilNode(e,r,n)}function bn(t){t.expect(m.CASE),t.isWord()||t.error("Expected word after 'case'");let e=t.parseWord();t.skipNewlines(),t.expect(m.IN),t.skipNewlines();let r=[];for(;!t.check(m.ESAC,m.EOF);){t.checkIterationLimit();let s=t.getPos(),i=Ad(t);if(i&&r.push(i),t.skipNewlines(),t.getPos()===s&&!i)break}t.expect(m.ESAC);let n=t.parseOptionalRedirections();return k.caseNode(e,r,n)}function Ad(t){t.check(m.LPAREN)&&t.advance();let e=[];for(;t.isWord()&&(e.push(t.parseWord()),t.check(m.PIPE));)t.advance();if(e.length===0)return null;t.expect(m.RPAREN),t.skipNewlines();let r=[];for(;!t.check(m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND,m.ESAC,m.EOF);){t.checkIterationLimit(),t.isWord()&&t.peek(1).type===m.RPAREN&&t.error("syntax error near unexpected token `)'"),t.check(m.LPAREN)&&t.peek(1).type===m.WORD&&t.error(`syntax error near unexpected token \`${t.peek(1).value}'`);let s=t.getPos(),i=t.parseStatement();if(i&&r.push(i),t.skipSeparators(!1),t.getPos()===s&&!i)break}let n=";;";return t.check(m.DSEMI)?(t.advance(),n=";;"):t.check(m.SEMI_AND)?(t.advance(),n=";&"):t.check(m.SEMI_SEMI_AND)&&(t.advance(),n=";;&"),k.caseItem(e,r,n)}function xn(t){t.peek(1).type,m.LPAREN,t.expect(m.LPAREN),t.check(m.LPAREN)&&t.advance();let e=t.parseCompoundList();t.expect(m.RPAREN);let r=t.parseOptionalRedirections();return k.subshell(e,r)}function Sn(t){t.expect(m.LBRACE);let e=t.parseCompoundList();t.expect(m.RBRACE);let r=t.parseOptionalRedirections();return k.group(e,r)}var Nd=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],vd=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function Cn(t){return t.skipNewlines(),kd(t)}function kd(t){let e=Co(t);for(t.skipNewlines();t.check(m.OR_OR);){t.advance(),t.skipNewlines();let r=Co(t);e={type:"CondOr",left:e,right:r},t.skipNewlines()}return e}function Co(t){let e=An(t);for(t.skipNewlines();t.check(m.AND_AND);){t.advance(),t.skipNewlines();let r=An(t);e={type:"CondAnd",left:e,right:r},t.skipNewlines()}return e}function An(t){return t.skipNewlines(),t.check(m.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:An(t)}):Id(t)}function Id(t){if(t.check(m.LPAREN)){t.advance();let e=Cn(t);return t.expect(m.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),r=e.value;if(Nd.includes(r)&&!e.quoted&&(t.advance(),t.check(m.DBRACK_END)&&t.error(`Expected operand after ${r}`),t.isWord())){let s=t.parseWord();return{type:"CondUnary",operator:r,operand:s}}let n=t.parseWord();if(t.isWord()&&vd.includes(t.current().value)){let s=t.advance().value,i=t.parseWord();return{type:"CondBinary",operator:s,left:n,right:i}}if(t.check(m.LESS)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"<",left:n,right:s}}if(t.check(m.GREAT)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:">",left:n,right:s}}if(t.isWord()&&t.current().value==="="){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"==",left:n,right:s}}return{type:"CondWord",word:n}}t.error("Expected conditional expression")}function $d(t,e,r){let n=r+1,s=e[n];if("@*#?$!-0123456789".includes(s))return{part:k.parameterExpansion(s),endIndex:n+1};let i="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)i+=e[n],n++;return{part:k.parameterExpansion(i),endIndex:n}}function Pd(t,e,r,n=!1){let s=r+2,i=!1;e[s]==="!"&&(i=!0,s++);let a=!1;e[s]==="#"&&!/[}:#%/^,]/.test(e[s+1]||"}")&&(a=!0,s++);let o="",c=e[s];if(/[@*#?$!-]/.test(c)&&!/[a-zA-Z0-9_]/.test(e[s+1]||""))o=c,s++;else for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)o+=e[s],s++;if(e[s]==="["){let u=hn(t,e,s,"[","]");o+=e.slice(s,u+1),s=u+1}o===""&&!i&&!a&&e[s]!=="}"&&t.error(`\${${e[s]}}: bad substitution`);let l=null;if(i){let u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)l={type:"ArrayKeys",array:u[1],star:u[2]==="*"},o="";else if(e[s]==="*"||e[s]==="@"){let f=e[s];s++,l={type:"VarNamePrefix",prefix:o,star:f==="*"},o=""}else l={type:"Indirection"}}else if(a)if(e[s]===":")for(l={type:"LengthSliceError"};s<e.length&&e[s]!=="}";)s++;else e[s]!=="}"&&/[-+=?]/.test(e[s])?t.error(`\${#${o}${e.slice(s,e.indexOf("}",s))}}: bad substitution`):l={type:"Length"};if(!l&&s<e.length&&e[s]!=="}"){let u=Od(t,e,s,o,n);l=u.operation,s=u.endIndex}if(s<e.length&&e[s]!=="}"){let u=e[s];if(!/[:\-+=?#%/^,@[]/.test(u)){let f=s;for(;f<e.length&&e[f]!=="}";)f++;let d=e.slice(r,f+1);t.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;s<e.length&&e[s]!=="}";)s++;return{part:k.parameterExpansion(o,l),endIndex:s+1}}function Od(t,e,r,n,s=!1){let i=r,a=e[i],o=e[i+1]||"";if(a===":"){let c=o;if("-=?+".includes(c)){i+=2;let g=tt(t,e,i),E=e.slice(i,g),x=ze(t,E,!1,!1,!0,!1,s),S=k.word(x.length>0?x:[k.literal("")]);if(c==="-")return{operation:{type:"DefaultValue",word:S,checkEmpty:!0},endIndex:g};if(c==="=")return{operation:{type:"AssignDefault",word:S,checkEmpty:!0},endIndex:g};if(c==="?")return{operation:{type:"ErrorIfUnset",word:S,checkEmpty:!0},endIndex:g};if(c==="+")return{operation:{type:"UseAlternative",word:S,checkEmpty:!0},endIndex:g}}i++;let l=tt(t,e,i),u=e.slice(i,l),f=-1,d=0,h=0;for(let w=0;w<u.length;w++){let g=u[w];if(g==="("||g==="[")d++;else if(g===")"||g==="]")d--;else if(g==="?"&&d===0)h++;else if(g===":"&&d===0)if(h>0)h--;else{f=w;break}}let p=f>=0?u.slice(0,f):u,b=f>=0?u.slice(f+1):null;return{operation:{type:"Substring",offset:pn(t,p),length:b?pn(t,b):null},endIndex:l}}if("-=?+".includes(a)){i++;let c=tt(t,e,i),l=e.slice(i,c),u=ze(t,l,!1,!1,!0,!1,s),f=k.word(u.length>0?u:[k.literal("")]);if(a==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:c};if(a==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:c};if(a==="?")return{operation:{type:"ErrorIfUnset",word:l?f:null,checkEmpty:!1},endIndex:c};if(a==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:c}}if(a==="#"||a==="%"){let c=o===a,l=a==="#"?"prefix":"suffix";i+=c?2:1;let u=tt(t,e,i),f=e.slice(i,u),d=ze(t,f,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:k.word(d.length>0?d:[k.literal("")]),side:l,greedy:c},endIndex:u}}if(a==="/"){let c=o==="/";i+=c?2:1;let l=null;e[i]==="#"?(l="start",i++):e[i]==="%"&&(l="end",i++);let u=yo(t,e,i),f=e.slice(i,u),d=ze(t,f,!1,!1,!1),h=k.word(d.length>0?d:[k.literal("")]),p=null,b=u;if(e[u]==="/"){let w=u+1,g=tt(t,e,w),E=e.slice(w,g),x=ze(t,E,!1,!1,!1);p=k.word(x.length>0?x:[k.literal("")]),b=g}return{operation:{type:"PatternReplacement",pattern:h,replacement:p,all:c,anchor:l},endIndex:b}}if(a==="^"||a===","){let c=o===a,l=a==="^"?"upper":"lower";i+=c?2:1;let u=tt(t,e,i),f=e.slice(i,u),d=f?k.word([k.literal(f)]):null;return{operation:{type:"CaseModification",direction:l,all:c,pattern:d},endIndex:u}}return a==="@"&&/[QPaAEK]/.test(o)?{operation:{type:"Transform",operator:o},endIndex:i+2}:{operation:null,endIndex:i}}function Nn(t,e,r,n=!1){let s=r+1;if(s>=e.length)return{part:k.literal("$"),endIndex:s};let i=e[s];if(i==="("&&e[s+1]==="(")return t.parseArithmeticExpansion(e,r);if(i==="["){let a=1,o=s+1;for(;o<e.length&&a>0;)e[o]==="["?a++:e[o]==="]"&&a--,a>0&&o++;if(a===0){let c=e.slice(s+1,o),l=se(t,c);return{part:k.arithmeticExpansion(l),endIndex:o+1}}}return i==="("?t.parseCommandSubstitution(e,r):i==="{"?Pd(t,e,r,n):/[a-zA-Z_0-9@*#?$!-]/.test(i)?$d(t,e,r):{part:k.literal("$"),endIndex:s}}function Dd(t,e){let r=[],n=0,s="",i=()=>{s&&(r.push(k.literal(s)),s="")};for(;n<e.length;){let a=e[n];if(a==="\\"&&n+1<e.length){let o=e[n+1];if(o==="$"||o==="`"){s+=o,n+=2;continue}s+=a,n++;continue}if(a==="$"){i();let{part:o,endIndex:c}=Nn(t,e,n,!0);o&&r.push(o),n=c;continue}if(a==="`"){i();let{part:o,endIndex:c}=t.parseBacktickSubstitution(e,n,!0);r.push(o),n=c;continue}s+=a,n++}return i(),r}function Ld(t,e,r){let n=[],s=r,i="",a=()=>{i&&(n.push(k.literal(i)),i="")};for(;s<e.length&&e[s]!=='"';){let o=e[s];if(o==="\\"&&s+1<e.length){let c=e[s+1];if('"\\$`\n'.includes(c)){i+=c,s+=2;continue}i+=o,s++;continue}if(o==="$"){a();let{part:c,endIndex:l}=Nn(t,e,s,!0);c&&n.push(c),s=l;continue}if(o==="`"){a();let{part:c,endIndex:l}=t.parseBacktickSubstitution(e,s,!0);n.push(c),s=l;continue}i+=o,s++}return a(),{part:k.doubleQuoted(n),endIndex:s}}function ze(t,e,r=!1,n=!1,s=!1,i=!1,a=!1){if(n)return[k.singleQuoted(e)];if(r){let f=Dd(t,e);return[k.doubleQuoted(f)]}let o=[],c=0,l="",u=()=>{l&&(o.push(k.literal(l)),l="")};for(;c<e.length;){let f=e[c];if(f==="\\"&&c+1<e.length){let d=e[c+1];(i?d==="$"||d==="`"||d==="\\"||d===`
462
+ `||a===";"||a==="&"||a==="|")return null;s++}}return null}};var pn=1e6,mn=1e5,mo=1e6,yo=new Set([m.LESS,m.GREAT,m.DLESS,m.DGREAT,m.LESSAND,m.GREATAND,m.LESSGREAT,m.DLESSDASH,m.CLOBBER,m.TLESS,m.AND_GREAT,m.AND_DGREAT]),go=new Set([m.LESS,m.GREAT,m.DLESS,m.DGREAT,m.LESSAND,m.GREATAND,m.LESSGREAT,m.DLESSDASH,m.CLOBBER,m.TLESS]),Fe=class extends Error{line;column;token;constructor(e,r,n,s=void 0){super(`Parse error at ${r}:${n}: ${e}`),this.line=r,this.column=n,this.token=s,this.name="ParseException"}};function Eo(t,e,r){let n=r+1;for(;n<e.length&&/[a-zA-Z0-9_-]/.test(e[n]);)n++;return n}function yn(t,e,r,n,s){let i=1,a=r+1;for(;a<e.length&&i>0;)e[a]===n?i++:e[a]===s&&i--,i>0&&a++;return i===0?a:-1}function rt(t,e,r){let n=r,s=1;for(;n<e.length&&s>0;){let i=e[n];if(i==="\\"&&n+1<e.length){n+=2;continue}if(i==="'"){let a=e.indexOf("'",n+1);if(a!==-1){n=a+1;continue}}if(i==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?n+=2:n++;n<e.length&&n++;continue}i==="{"?s++:i==="}"&&s--,s>0&&n++}return n}function bo(t,e,r){let n=r,s=!1;for(;n<e.length;){let i=e[n];if(i==="/"&&s||i==="}")break;if(i==="'"){let a=e.indexOf("'",n+1);if(a!==-1){n=a+1,s=!0;continue}}if(i==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?n+=2:n++;n<e.length&&n++,s=!0;continue}i==="\\"?(n+=2,s=!0):(n++,s=!0)}return n}function So(t,e,r){let n=r,s="";for(;n<e.length;){let i=e[n];if(i==="*"||i==="?")s+=i,n++;else if(i==="["){let a=Nd(e,n);a===-1?(s+=i,n++):(s+=e.slice(n,a+1),n=a+1)}else break}return{pattern:s,endIndex:n}}function Nd(t,e){let r=e+1;for(r<t.length&&t[r]==="^"&&r++,r<t.length&&t[r]==="]"&&r++;r<t.length;){let n=t[r];if(n==="\\"&&r+1<t.length){r+=2;continue}if(n==="]")return r;if(n==='"'||n==="$"||n==="`")return-1;if(n==="'"){let s=t.indexOf("'",r+1);if(s!==-1){r=s+1;continue}}if(n==="["&&r+1<t.length&&t[r+1]===":"){let s=t.indexOf(":]",r+2);if(s!==-1){r=s+2;continue}}if(n==="["&&r+1<t.length&&(t[r+1]==="."||t[r+1]==="=")){let i=`${t[r+1]}]`,a=t.indexOf(i,r+2);if(a!==-1){r=a+2;continue}}r++}return-1}function xo(t,e,r){let n="",s=r;for(;s<e.length&&e[s]!=="'";){let i=e[s];if(i==="\\"&&s+1<e.length)switch(e[s+1]){case"n":n+=`
463
+ `,s+=2;break;case"t":n+=" ",s+=2;break;case"r":n+="\r",s+=2;break;case"\\":n+="\\",s+=2;break;case"'":n+="'",s+=2;break;case'"':n+='"',s+=2;break;case"a":n+="\x07",s+=2;break;case"b":n+="\b",s+=2;break;case"e":case"E":n+="\x1B",s+=2;break;case"f":n+="\f",s+=2;break;case"v":n+="\v",s+=2;break;case"x":{let o=e.slice(s+2,s+4),c=parseInt(o,16);Number.isNaN(c)?(n+="\\x",s+=2):(n+=String.fromCharCode(c),s+=4);break}case"u":{let o=e.slice(s+2,s+6),c=parseInt(o,16);Number.isNaN(c)?(n+="\\u",s+=2):(n+=String.fromCharCode(c),s+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let o="",c=s+1;for(;c<e.length&&c<s+4&&/[0-7]/.test(e[c]);)o+=e[c],c++;let l=parseInt(o,8);n+=String.fromCharCode(l),s=c;break}default:n+=i,s++}else n+=i,s++}return s<e.length&&e[s]==="'"&&s++,{part:k.literal(n),endIndex:s}}function gn(t,e){let r=e.trim();return r===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:ie(t,r)}function wo(t){let e=[],r="",n=0;for(let s=0;s<t.length;s++){let i=t[s];i==="{"?(n++,r+=i):i==="}"?(n--,r+=i):i===","&&n===0?(e.push(r),r=""):r+=i}return e.push(r),e}function Ao(t,e,r,n){let s=yn(t,e,r,"{","}");if(s===-1)return null;let i=e.slice(r+1,s),a=i.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(a)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(a[1],10),end:Number.parseInt(a[2],10),step:a[3]?Number.parseInt(a[3],10):void 0,startStr:a[1],endStr:a[2]}]},endIndex:s+1};let o=i.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return o?{part:{type:"BraceExpansion",items:[{type:"Range",start:o[1],end:o[2],step:o[3]?Number.parseInt(o[3],10):void 0}]},endIndex:s+1}:i.includes(",")&&n?{part:{type:"BraceExpansion",items:wo(i).map(u=>({type:"Word",word:k.word(n(t,u,!1,!1,!1))}))},endIndex:s+1}:i.includes(",")?{part:{type:"BraceExpansion",items:wo(i).map(u=>({type:"Word",word:k.word([k.literal(u)])}))},endIndex:s+1}:null}function Co(t,e){let r="";for(let n of e.parts)switch(n.type){case"Literal":case"SingleQuoted":case"Escaped":r+=n.value;break;case"DoubleQuoted":r+='"';for(let s of n.parts)s.type==="Literal"||s.type==="Escaped"?r+=s.value:s.type==="ParameterExpansion"&&(r+=`\${${s.parameter}}`);r+='"';break;case"ParameterExpansion":r+=`\${${n.parameter}}`;break;case"Glob":r+=n.pattern;break;default:r+=n.type}return r}function No(t,e){return{[m.LESS]:"<",[m.GREAT]:">",[m.DGREAT]:">>",[m.LESSAND]:"<&",[m.GREATAND]:">&",[m.LESSGREAT]:"<>",[m.CLOBBER]:">|",[m.TLESS]:"<<<",[m.AND_GREAT]:"&>",[m.AND_DGREAT]:"&>>",[m.DLESS]:"<",[m.DLESSDASH]:"<"}[e]||">"}function lr(t){let e=t.current(),r=e.type;if(r===m.NUMBER){let n=t.peek(1);return e.end!==n.start?!1:go.has(n.type)}return yo.has(r)}function cr(t){let e=null;t.check(m.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let r=t.advance(),n=No(t,r.type);if(r.type===m.DLESS||r.type===m.DLESSDASH)return vd(t,n,e,r.type===m.DLESSDASH);t.isWord()||t.error("Expected redirection target");let s=t.parseWord();return k.redirection(n,s,e)}function vd(t,e,r,n){t.isWord()||t.error("Expected here-document delimiter");let s=t.advance(),i=s.value,a=s.quoted||!1;(i.startsWith("'")&&i.endsWith("'")||i.startsWith('"')&&i.endsWith('"'))&&(i=i.slice(1,-1));let o=k.redirection(n?"<<-":"<<",k.hereDoc(i,k.word([]),n,a),r);return t.addPendingHeredoc(o,i,n,a),o}function ko(t){let e=[],r=null,n=[],s=[];for(;t.check(m.ASSIGNMENT_WORD);)t.checkIterationLimit(),e.push(kd(t));for(;lr(t);)t.checkIterationLimit(),s.push(cr(t));for(t.isWord()&&(r=t.parseWord());(!t.isStatementEnd()||t.check(m.RBRACE))&&!t.check(m.PIPE,m.PIPE_AMP);)if(t.checkIterationLimit(),lr(t))s.push(cr(t));else if(t.check(m.RBRACE)){let i=t.advance();n.push(t.parseWordFromString(i.value,!1,!1))}else if(t.isWord())n.push(t.parseWord());else if(t.check(m.ASSIGNMENT_WORD)){let i=t.advance(),a=i.value,o=a.endsWith("="),c=a.endsWith("=(");if((o||c)&&(c||t.check(m.LPAREN))){let l=c?a.slice(0,-2):a.slice(0,-1);c||t.expect(m.LPAREN);let u=wn(t);t.expect(m.RPAREN);let f=u.map(h=>Co(t,h)),d=`${l}=(${f.join(" ")})`;n.push(t.parseWordFromString(d,!1,!1))}else n.push(t.parseWordFromString(a,i.quoted,i.singleQuoted))}else if(t.check(m.LPAREN))t.error("syntax error near unexpected token `('");else break;return k.simpleCommand(r,n,e,s)}function kd(t){let e=t.expect(m.ASSIGNMENT_WORD),r=e.value,n=r.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);n||t.error(`Invalid assignment: ${r}`);let s=n[0],i,a=s.length;if(r[a]==="["){let f=0,d=a+1;for(;a<r.length;a++)if(r[a]==="[")f++;else if(r[a]==="]"&&(f--,f===0))break;f!==0&&t.error(`Invalid assignment: ${r}`),i=r.slice(d,a),a++}let o=r[a]==="+";o&&a++,r[a]!=="="&&t.error(`Invalid assignment: ${r}`),a++;let c=r.slice(a);if(c==="("){let f=wn(t);t.expect(m.RPAREN);let d=i!==void 0?`${s}[${i}]`:s;return k.assignment(d,null,o,f)}if(c===""&&t.check(m.LPAREN)){let f=t.current();if(e.end===f.start){t.advance();let d=wn(t);t.expect(m.RPAREN);let h=i!==void 0?`${s}[${i}]`:s;return k.assignment(h,null,o,d)}}let l=c?t.parseWordFromString(c,e.quoted,e.singleQuoted,!0):null,u=i!==void 0?`${s}[${i}]`:s;return k.assignment(u,l,o,null)}function wn(t){let e=[];for(t.skipNewlines();!t.check(m.RPAREN,m.EOF);)t.checkIterationLimit(),t.isWord()?e.push(t.parseWord()):t.advance(),t.skipNewlines();return e}function En(t){t.expect(m.IF);let e=[],r=t.parseCompoundList();t.expect(m.THEN);let n=t.parseCompoundList();if(n.length===0){let a=t.check(m.FI)?"fi":t.check(m.ELSE)?"else":t.check(m.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${a}'`)}for(e.push({condition:r,body:n});t.check(m.ELIF);){t.advance();let a=t.parseCompoundList();t.expect(m.THEN);let o=t.parseCompoundList();if(o.length===0){let c=t.check(m.FI)?"fi":t.check(m.ELSE)?"else":t.check(m.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${c}'`)}e.push({condition:a,body:o})}let s=null;t.check(m.ELSE)&&(t.advance(),s=t.parseCompoundList(),s.length===0&&t.error("syntax error near unexpected token `fi'")),t.expect(m.FI);let i=t.parseOptionalRedirections();return k.ifNode(e,s,i)}function bn(t){if(t.expect(m.FOR),t.check(m.DPAREN_START))return $d(t);t.isWord()||t.error("Expected variable name in for loop");let r=t.advance().value,n=null;if(t.skipNewlines(),t.check(m.IN))for(t.advance(),n=[];!t.check(m.SEMICOLON,m.NEWLINE,m.DO,m.EOF)&&t.isWord();)n.push(t.parseWord());t.check(m.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(m.DO);let s=t.parseCompoundList();t.expect(m.DONE);let i=t.parseOptionalRedirections();return k.forNode(r,n,s,i)}function $d(t){t.expect(m.DPAREN_START);let e=null,r=null,n=null,s=["","",""],i=0,a=0;for(;!t.check(m.DPAREN_END,m.EOF);){let l=t.advance();if(l.type===m.SEMICOLON&&a===0){if(i++,i>2)break}else l.value==="("&&a++,l.value===")"&&a--,s[i]+=l.value}t.expect(m.DPAREN_END),s[0].trim()&&(e=ie(t,s[0].trim())),s[1].trim()&&(r=ie(t,s[1].trim())),s[2].trim()&&(n=ie(t,s[2].trim())),t.skipNewlines(),t.check(m.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(m.DO);let o=t.parseCompoundList();t.expect(m.DONE);let c=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:r,update:n,body:o,redirections:c}}function Sn(t){t.expect(m.WHILE);let e=t.parseCompoundList();t.expect(m.DO);let r=t.parseCompoundList();r.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(m.DONE);let n=t.parseOptionalRedirections();return k.whileNode(e,r,n)}function xn(t){t.expect(m.UNTIL);let e=t.parseCompoundList();t.expect(m.DO);let r=t.parseCompoundList();r.length===0&&t.error("syntax error near unexpected token `done'"),t.expect(m.DONE);let n=t.parseOptionalRedirections();return k.untilNode(e,r,n)}function An(t){t.expect(m.CASE),t.isWord()||t.error("Expected word after 'case'");let e=t.parseWord();t.skipNewlines(),t.expect(m.IN),t.skipNewlines();let r=[];for(;!t.check(m.ESAC,m.EOF);){t.checkIterationLimit();let s=t.getPos(),i=Rd(t);if(i&&r.push(i),t.skipNewlines(),t.getPos()===s&&!i)break}t.expect(m.ESAC);let n=t.parseOptionalRedirections();return k.caseNode(e,r,n)}function Rd(t){t.check(m.LPAREN)&&t.advance();let e=[];for(;t.isWord()&&(e.push(t.parseWord()),t.check(m.PIPE));)t.advance();if(e.length===0)return null;t.expect(m.RPAREN),t.skipNewlines();let r=[];for(;!t.check(m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND,m.ESAC,m.EOF);){t.checkIterationLimit(),t.isWord()&&t.peek(1).type===m.RPAREN&&t.error("syntax error near unexpected token `)'"),t.check(m.LPAREN)&&t.peek(1).type===m.WORD&&t.error(`syntax error near unexpected token \`${t.peek(1).value}'`);let s=t.getPos(),i=t.parseStatement();if(i&&r.push(i),t.skipSeparators(!1),t.getPos()===s&&!i)break}let n=";;";return t.check(m.DSEMI)?(t.advance(),n=";;"):t.check(m.SEMI_AND)?(t.advance(),n=";&"):t.check(m.SEMI_SEMI_AND)&&(t.advance(),n=";;&"),k.caseItem(e,r,n)}function Cn(t){t.peek(1).type,m.LPAREN,t.expect(m.LPAREN),t.check(m.LPAREN)&&t.advance();let e=t.parseCompoundList();t.expect(m.RPAREN);let r=t.parseOptionalRedirections();return k.subshell(e,r)}function Nn(t){t.expect(m.LBRACE);let e=t.parseCompoundList();t.expect(m.RBRACE);let r=t.parseOptionalRedirections();return k.group(e,r)}var Od=["-a","-b","-c","-d","-e","-f","-g","-h","-k","-p","-r","-s","-t","-u","-w","-x","-G","-L","-N","-O","-S","-z","-n","-o","-v","-R"],Dd=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function kn(t){return t.skipNewlines(),Td(t)}function Td(t){let e=Io(t);for(t.skipNewlines();t.check(m.OR_OR);){t.advance(),t.skipNewlines();let r=Io(t);e={type:"CondOr",left:e,right:r},t.skipNewlines()}return e}function Io(t){let e=vn(t);for(t.skipNewlines();t.check(m.AND_AND);){t.advance(),t.skipNewlines();let r=vn(t);e={type:"CondAnd",left:e,right:r},t.skipNewlines()}return e}function vn(t){return t.skipNewlines(),t.check(m.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:vn(t)}):Ld(t)}function Ld(t){if(t.check(m.LPAREN)){t.advance();let e=kn(t);return t.expect(m.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),r=e.value;if(Od.includes(r)&&!e.quoted&&(t.advance(),t.check(m.DBRACK_END)&&t.error(`Expected operand after ${r}`),t.isWord())){let s=t.parseWord();return{type:"CondUnary",operator:r,operand:s}}let n=t.parseWord();if(t.isWord()&&Dd.includes(t.current().value)){let s=t.advance().value,i=t.parseWord();return{type:"CondBinary",operator:s,left:n,right:i}}if(t.check(m.LESS)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"<",left:n,right:s}}if(t.check(m.GREAT)){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:">",left:n,right:s}}if(t.isWord()&&t.current().value==="="){t.advance();let s=t.parseWord();return{type:"CondBinary",operator:"==",left:n,right:s}}return{type:"CondWord",word:n}}t.error("Expected conditional expression")}function Md(t,e,r){let n=r+1,s=e[n];if("@*#?$!-0123456789".includes(s))return{part:k.parameterExpansion(s),endIndex:n+1};let i="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)i+=e[n],n++;return{part:k.parameterExpansion(i),endIndex:n}}function _d(t,e,r,n=!1){let s=r+2,i=!1;e[s]==="!"&&(i=!0,s++);let a=!1;e[s]==="#"&&!/[}:#%/^,]/.test(e[s+1]||"}")&&(a=!0,s++);let o="",c=e[s];if(/[@*#?$!-]/.test(c)&&!/[a-zA-Z0-9_]/.test(e[s+1]||""))o=c,s++;else for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)o+=e[s],s++;if(e[s]==="["){let u=yn(t,e,s,"[","]");o+=e.slice(s,u+1),s=u+1}o===""&&!i&&!a&&e[s]!=="}"&&t.error(`\${${e[s]}}: bad substitution`);let l=null;if(i){let u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)l={type:"ArrayKeys",array:u[1],star:u[2]==="*"},o="";else if(e[s]==="*"||e[s]==="@"){let f=e[s];s++,l={type:"VarNamePrefix",prefix:o,star:f==="*"},o=""}else l={type:"Indirection"}}else if(a)if(e[s]===":")for(l={type:"LengthSliceError"};s<e.length&&e[s]!=="}";)s++;else e[s]!=="}"&&/[-+=?]/.test(e[s])?t.error(`\${#${o}${e.slice(s,e.indexOf("}",s))}}: bad substitution`):l={type:"Length"};if(!l&&s<e.length&&e[s]!=="}"){let u=Wd(t,e,s,o,n);l=u.operation,s=u.endIndex}if(s<e.length&&e[s]!=="}"){let u=e[s];if(!/[:\-+=?#%/^,@[]/.test(u)){let f=s;for(;f<e.length&&e[f]!=="}";)f++;let d=e.slice(r,f+1);t.error(`\${${d.slice(2,-1)}}: bad substitution`)}}for(;s<e.length&&e[s]!=="}";)s++;return{part:k.parameterExpansion(o,l),endIndex:s+1}}function Wd(t,e,r,n,s=!1){let i=r,a=e[i],o=e[i+1]||"";if(a===":"){let c=o;if("-=?+".includes(c)){i+=2;let g=rt(t,e,i),b=e.slice(i,g),S=je(t,b,!1,!1,!0,!1,s),x=k.word(S.length>0?S:[k.literal("")]);if(c==="-")return{operation:{type:"DefaultValue",word:x,checkEmpty:!0},endIndex:g};if(c==="=")return{operation:{type:"AssignDefault",word:x,checkEmpty:!0},endIndex:g};if(c==="?")return{operation:{type:"ErrorIfUnset",word:x,checkEmpty:!0},endIndex:g};if(c==="+")return{operation:{type:"UseAlternative",word:x,checkEmpty:!0},endIndex:g}}i++;let l=rt(t,e,i),u=e.slice(i,l),f=-1,d=0,h=0;for(let w=0;w<u.length;w++){let g=u[w];if(g==="("||g==="[")d++;else if(g===")"||g==="]")d--;else if(g==="?"&&d===0)h++;else if(g===":"&&d===0)if(h>0)h--;else{f=w;break}}let p=f>=0?u.slice(0,f):u,E=f>=0?u.slice(f+1):null;return{operation:{type:"Substring",offset:gn(t,p),length:E?gn(t,E):null},endIndex:l}}if("-=?+".includes(a)){i++;let c=rt(t,e,i),l=e.slice(i,c),u=je(t,l,!1,!1,!0,!1,s),f=k.word(u.length>0?u:[k.literal("")]);if(a==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:c};if(a==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:c};if(a==="?")return{operation:{type:"ErrorIfUnset",word:l?f:null,checkEmpty:!1},endIndex:c};if(a==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:c}}if(a==="#"||a==="%"){let c=o===a,l=a==="#"?"prefix":"suffix";i+=c?2:1;let u=rt(t,e,i),f=e.slice(i,u),d=je(t,f,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:k.word(d.length>0?d:[k.literal("")]),side:l,greedy:c},endIndex:u}}if(a==="/"){let c=o==="/";i+=c?2:1;let l=null;e[i]==="#"?(l="start",i++):e[i]==="%"&&(l="end",i++);let u=bo(t,e,i),f=e.slice(i,u),d=je(t,f,!1,!1,!1),h=k.word(d.length>0?d:[k.literal("")]),p=null,E=u;if(e[u]==="/"){let w=u+1,g=rt(t,e,w),b=e.slice(w,g),S=je(t,b,!1,!1,!1);p=k.word(S.length>0?S:[k.literal("")]),E=g}return{operation:{type:"PatternReplacement",pattern:h,replacement:p,all:c,anchor:l},endIndex:E}}if(a==="^"||a===","){let c=o===a,l=a==="^"?"upper":"lower";i+=c?2:1;let u=rt(t,e,i),f=e.slice(i,u),d=f?k.word([k.literal(f)]):null;return{operation:{type:"CaseModification",direction:l,all:c,pattern:d},endIndex:u}}return a==="@"&&/[QPaAEK]/.test(o)?{operation:{type:"Transform",operator:o},endIndex:i+2}:{operation:null,endIndex:i}}function In(t,e,r,n=!1){let s=r+1;if(s>=e.length)return{part:k.literal("$"),endIndex:s};let i=e[s];if(i==="("&&e[s+1]==="(")return t.parseArithmeticExpansion(e,r);if(i==="["){let a=1,o=s+1;for(;o<e.length&&a>0;)e[o]==="["?a++:e[o]==="]"&&a--,a>0&&o++;if(a===0){let c=e.slice(s+1,o),l=ie(t,c);return{part:k.arithmeticExpansion(l),endIndex:o+1}}}return i==="("?t.parseCommandSubstitution(e,r):i==="{"?_d(t,e,r,n):/[a-zA-Z_0-9@*#?$!-]/.test(i)?Md(t,e,r):{part:k.literal("$"),endIndex:s}}function Bd(t,e){let r=[],n=0,s="",i=()=>{s&&(r.push(k.literal(s)),s="")};for(;n<e.length;){let a=e[n];if(a==="\\"&&n+1<e.length){let o=e[n+1];if(o==="$"||o==="`"){s+=o,n+=2;continue}s+=a,n++;continue}if(a==="$"){i();let{part:o,endIndex:c}=In(t,e,n,!0);o&&r.push(o),n=c;continue}if(a==="`"){i();let{part:o,endIndex:c}=t.parseBacktickSubstitution(e,n,!0);r.push(o),n=c;continue}s+=a,n++}return i(),r}function Hd(t,e,r){let n=[],s=r,i="",a=()=>{i&&(n.push(k.literal(i)),i="")};for(;s<e.length&&e[s]!=='"';){let o=e[s];if(o==="\\"&&s+1<e.length){let c=e[s+1];if('"\\$`\n'.includes(c)){i+=c,s+=2;continue}i+=o,s++;continue}if(o==="$"){a();let{part:c,endIndex:l}=In(t,e,s,!0);c&&n.push(c),s=l;continue}if(o==="`"){a();let{part:c,endIndex:l}=t.parseBacktickSubstitution(e,s,!0);n.push(c),s=l;continue}i+=o,s++}return a(),{part:k.doubleQuoted(n),endIndex:s}}function je(t,e,r=!1,n=!1,s=!1,i=!1,a=!1){if(n)return[k.singleQuoted(e)];if(r){let f=Bd(t,e);return[k.doubleQuoted(f)]}let o=[],c=0,l="",u=()=>{l&&(o.push(k.literal(l)),l="")};for(;c<e.length;){let f=e[c];if(f==="\\"&&c+1<e.length){let d=e[c+1];(i?d==="$"||d==="`"||d==="\\"||d===`
464
464
  `:d==="$"||d==="`"||d==="\\"||d==='"'||d===`
465
- `)?l+=d:l+=`\\${d}`,c+=2;continue}if(f==="'"&&!a){u();let d=e.indexOf("'",c+1);if(d===-1){l+=e.slice(c);break}o.push(k.singleQuoted(e.slice(c+1,d))),c=d+1;continue}if(f==='"'){u();let{part:d,endIndex:h}=Ld(t,e,c+1);o.push(d),c=h+1;continue}if(f==="$"&&e[c+1]==="'"){u();let{part:d,endIndex:h}=wo(t,e,c+2);o.push(d),c=h;continue}if(f==="$"){u();let{part:d,endIndex:h}=Nn(t,e,c);d&&o.push(d),c=h;continue}if(f==="`"){u();let{part:d,endIndex:h}=t.parseBacktickSubstitution(e,c);o.push(d),c=h;continue}if(f==="~"){let d=c>0?e[c-1]:"";if(c===0||d==="="||s&&d===":"){let p=mo(t,e,c),b=e[p];if(b===void 0||b==="/"||b===":"){u();let w=e.slice(c+1,p)||null;o.push({type:"TildeExpansion",user:w}),c=p;continue}}}if(f==="*"||f==="?"||f==="["){u();let{pattern:d,endIndex:h}=go(t,e,c);o.push({type:"Glob",pattern:d}),c=h;continue}if(f==="{"&&!s){let d=Eo(t,e,c,ze);if(d){u(),o.push(d.part),c=d.endIndex;continue}}l+=f,c++}return u(),o}var le=class t{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;checkIterationLimit(){if(this.parseIterations++,this.parseIterations>uo)throw new Te("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}parse(e){if(e.length>fn)throw new Te(`Input too large: ${e.length} bytes exceeds limit of ${fn}`,1,1);let r=new nr(e);if(this.tokens=r.tokenize(),this.tokens.length>dn)throw new Te(`Too many tokens: ${this.tokens.length} exceeds limit of ${dn}`,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,r,n,s,...i){let a=this.tokens[this.pos]?.type;return a===e||r!==void 0&&a===r||n!==void 0&&a===n||s!==void 0&&a===s?!0:i.length>0?i.includes(a):!1}expect(e,r){if(this.check(e))return this.advance();let n=this.current();throw new Te(r||`Expected ${e}, got ${n.type}`,n.line,n.column,n)}error(e){let r=this.current();throw new Te(e,r.line,r.column,r)}skipNewlines(){for(;this.check(m.NEWLINE,m.COMMENT);)this.check(m.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(e=!0){for(;;){if(this.check(m.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(m.SEMICOLON,m.COMMENT)){this.advance();continue}if(e&&this.check(m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(e,r,n,s){this.pendingHeredocs.push({redirect:e,delimiter:r,stripTabs:n,quoted:s})}processHeredocs(){for(let e of this.pendingHeredocs)if(this.check(m.HEREDOC_CONTENT)){let r=this.advance(),n;e.quoted?n=k.word([k.literal(r.value)]):n=this.parseWordFromString(r.value,!1,!1,!1,!0),e.redirect.target=k.hereDoc(e.delimiter,n,e.stripTabs,e.quoted)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(m.EOF,m.NEWLINE,m.SEMICOLON,m.AMP,m.AND_AND,m.OR_OR,m.RPAREN,m.RBRACE,m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)}isCommandStart(){let e=this.current().type;return e===m.WORD||e===m.NAME||e===m.NUMBER||e===m.ASSIGNMENT_WORD||e===m.IF||e===m.FOR||e===m.WHILE||e===m.UNTIL||e===m.CASE||e===m.LPAREN||e===m.LBRACE||e===m.DPAREN_START||e===m.DBRACK_START||e===m.FUNCTION||e===m.BANG||e===m.IN}parseScript(){let e=[],n=0;for(this.skipNewlines();!this.check(m.EOF);){n++,n>1e4&&this.error("Parser stuck: too many iterations (>10000)"),this.checkUnexpectedToken();let s=this.pos,i=this.parseStatement();i&&e.push(i),this.skipSeparators(!1),this.check(m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===s&&!this.check(m.EOF)&&this.advance()}return k.script(e)}checkUnexpectedToken(){let e=this.current().type,r=this.current().value;(e===m.DO||e===m.DONE||e===m.THEN||e===m.ELSE||e===m.ELIF||e===m.FI||e===m.ESAC)&&this.error(`syntax error near unexpected token \`${r}'`),(e===m.RBRACE||e===m.RPAREN)&&this.error(`syntax error near unexpected token \`${r}'`),(e===m.DSEMI||e===m.SEMI_AND||e===m.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${r}'`),e===m.SEMICOLON&&this.error(`syntax error near unexpected token \`${r}'`)}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let e=[],r=[],n=!1,s=this.parsePipeline();for(e.push(s);this.check(m.AND_AND,m.OR_OR);){let i=this.advance();r.push(i.type===m.AND_AND?"&&":"||"),this.skipNewlines();let a=this.parsePipeline();e.push(a)}return this.check(m.AMP)&&(this.advance(),n=!0),k.statement(e,r,n)}parsePipeline(){let e=0;for(;this.check(m.BANG);)this.advance(),e++;let r=e%2===1,n=[],s=this.parseCommand();for(n.push(s);this.check(m.PIPE,m.PIPE_AMP);){let i=this.advance();this.skipNewlines();let a=this.parseCommand();i.type===m.PIPE_AMP&&a.type==="SimpleCommand"&&a.redirections.unshift(k.redirection(">&",k.word([k.literal("1")]),2)),n.push(a)}return k.pipeline(n,r)}parseCommand(){return this.check(m.IF)?yn(this):this.check(m.FOR)?gn(this):this.check(m.WHILE)?wn(this):this.check(m.UNTIL)?En(this):this.check(m.CASE)?bn(this):this.check(m.LPAREN)?xn(this):this.check(m.LBRACE)?Sn(this):this.check(m.DPAREN_START)?this.parseArithmeticCommand():this.check(m.DBRACK_START)?this.parseConditionalCommand():this.check(m.FUNCTION)?this.parseFunctionDef():this.check(m.NAME,m.WORD)&&this.peek(1).type===m.LPAREN&&this.peek(2).type===m.RPAREN?this.parseFunctionDef():Ao(this)}isWord(){let e=this.current().type;return e===m.WORD||e===m.NAME||e===m.NUMBER||e===m.IF||e===m.FOR||e===m.WHILE||e===m.UNTIL||e===m.CASE||e===m.FUNCTION||e===m.ELSE||e===m.ELIF||e===m.FI||e===m.THEN||e===m.DO||e===m.DONE||e===m.ESAC||e===m.IN||e===m.BANG}parseWord(){let e=this.advance();return this.parseWordFromString(e.value,e.quoted,e.singleQuoted)}parseWordFromString(e,r=!1,n=!1,s=!1,i=!1){let a=ze(this,e,r,n,s,i);return k.word(a)}parseCommandSubstitution(e,r){let n=r+2,s=1,i=n,a=!1,o=!1,c=0,l=!1,u="";for(;i<e.length&&s>0;){let p=e[i];a?p==="'"&&(a=!1):o?p==="\\"&&i+1<e.length?i++:p==='"'&&(o=!1):p==="'"?(a=!0,u=""):p==='"'?(o=!0,u=""):p==="\\"&&i+1<e.length?(i++,u=""):/[a-zA-Z_]/.test(p)?u+=p:(u==="case"?(c++,l=!1):u==="in"&&c>0?l=!0:u==="esac"&&c>0&&(c--,l=!1),u="",p==="("?i>0&&e[i-1]==="$"?s++:l||s++:p===")"?l?l=!1:s--:p===";"&&c>0&&i+1<e.length&&e[i+1]===";"&&(l=!0)),s>0&&i++}s>0&&this.error("unexpected EOF while looking for matching `)'");let f=e.slice(n,i),h=new t().parse(f);return{part:k.commandSubstitution(h,!1),endIndex:i+1}}parseBacktickSubstitution(e,r,n=!1){let i=r+1,a="";for(;i<e.length&&e[i]!=="`";)if(e[i]==="\\"){let l=e[i+1];l==="$"||l==="`"||l==="\\"||l===`
465
+ `)?l+=d:l+=`\\${d}`,c+=2;continue}if(f==="'"&&!a){u();let d=e.indexOf("'",c+1);if(d===-1){l+=e.slice(c);break}o.push(k.singleQuoted(e.slice(c+1,d))),c=d+1;continue}if(f==='"'){u();let{part:d,endIndex:h}=Hd(t,e,c+1);o.push(d),c=h+1;continue}if(f==="$"&&e[c+1]==="'"){u();let{part:d,endIndex:h}=xo(t,e,c+2);o.push(d),c=h;continue}if(f==="$"){u();let{part:d,endIndex:h}=In(t,e,c);d&&o.push(d),c=h;continue}if(f==="`"){u();let{part:d,endIndex:h}=t.parseBacktickSubstitution(e,c);o.push(d),c=h;continue}if(f==="~"){let d=c>0?e[c-1]:"";if(c===0||d==="="||s&&d===":"){let p=Eo(t,e,c),E=e[p];if(E===void 0||E==="/"||E===":"){u();let w=e.slice(c+1,p)||null;o.push({type:"TildeExpansion",user:w}),c=p;continue}}}if(f==="*"||f==="?"||f==="["){u();let{pattern:d,endIndex:h}=So(t,e,c);o.push({type:"Glob",pattern:d}),c=h;continue}if(f==="{"&&!s){let d=Ao(t,e,c,je);if(d){u(),o.push(d.part),c=d.endIndex;continue}}l+=f,c++}return u(),o}var le=class t{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;checkIterationLimit(){if(this.parseIterations++,this.parseIterations>mo)throw new Fe("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}parse(e){if(e.length>pn)throw new Fe(`Input too large: ${e.length} bytes exceeds limit of ${pn}`,1,1);let r=new or(e);if(this.tokens=r.tokenize(),this.tokens.length>mn)throw new Fe(`Too many tokens: ${this.tokens.length} exceeds limit of ${mn}`,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,r,n,s,...i){let a=this.tokens[this.pos]?.type;return a===e||r!==void 0&&a===r||n!==void 0&&a===n||s!==void 0&&a===s?!0:i.length>0?i.includes(a):!1}expect(e,r){if(this.check(e))return this.advance();let n=this.current();throw new Fe(r||`Expected ${e}, got ${n.type}`,n.line,n.column,n)}error(e){let r=this.current();throw new Fe(e,r.line,r.column,r)}skipNewlines(){for(;this.check(m.NEWLINE,m.COMMENT);)this.check(m.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(e=!0){for(;;){if(this.check(m.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(m.SEMICOLON,m.COMMENT)){this.advance();continue}if(e&&this.check(m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(e,r,n,s){this.pendingHeredocs.push({redirect:e,delimiter:r,stripTabs:n,quoted:s})}processHeredocs(){for(let e of this.pendingHeredocs)if(this.check(m.HEREDOC_CONTENT)){let r=this.advance(),n;e.quoted?n=k.word([k.literal(r.value)]):n=this.parseWordFromString(r.value,!1,!1,!1,!0),e.redirect.target=k.hereDoc(e.delimiter,n,e.stripTabs,e.quoted)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(m.EOF,m.NEWLINE,m.SEMICOLON,m.AMP,m.AND_AND,m.OR_OR,m.RPAREN,m.RBRACE,m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)}isCommandStart(){let e=this.current().type;return e===m.WORD||e===m.NAME||e===m.NUMBER||e===m.ASSIGNMENT_WORD||e===m.IF||e===m.FOR||e===m.WHILE||e===m.UNTIL||e===m.CASE||e===m.LPAREN||e===m.LBRACE||e===m.DPAREN_START||e===m.DBRACK_START||e===m.FUNCTION||e===m.BANG||e===m.IN}parseScript(){let e=[],n=0;for(this.skipNewlines();!this.check(m.EOF);){n++,n>1e4&&this.error("Parser stuck: too many iterations (>10000)"),this.checkUnexpectedToken();let s=this.pos,i=this.parseStatement();i&&e.push(i),this.skipSeparators(!1),this.check(m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===s&&!this.check(m.EOF)&&this.advance()}return k.script(e)}checkUnexpectedToken(){let e=this.current().type,r=this.current().value;(e===m.DO||e===m.DONE||e===m.THEN||e===m.ELSE||e===m.ELIF||e===m.FI||e===m.ESAC)&&this.error(`syntax error near unexpected token \`${r}'`),(e===m.RBRACE||e===m.RPAREN)&&this.error(`syntax error near unexpected token \`${r}'`),(e===m.DSEMI||e===m.SEMI_AND||e===m.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${r}'`),e===m.SEMICOLON&&this.error(`syntax error near unexpected token \`${r}'`)}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let e=[],r=[],n=!1,s=this.parsePipeline();for(e.push(s);this.check(m.AND_AND,m.OR_OR);){let i=this.advance();r.push(i.type===m.AND_AND?"&&":"||"),this.skipNewlines();let a=this.parsePipeline();e.push(a)}return this.check(m.AMP)&&(this.advance(),n=!0),k.statement(e,r,n)}parsePipeline(){let e=0;for(;this.check(m.BANG);)this.advance(),e++;let r=e%2===1,n=[],s=this.parseCommand();for(n.push(s);this.check(m.PIPE,m.PIPE_AMP);){let i=this.advance();this.skipNewlines();let a=this.parseCommand();i.type===m.PIPE_AMP&&a.type==="SimpleCommand"&&a.redirections.unshift(k.redirection(">&",k.word([k.literal("1")]),2)),n.push(a)}return k.pipeline(n,r)}parseCommand(){return this.check(m.IF)?En(this):this.check(m.FOR)?bn(this):this.check(m.WHILE)?Sn(this):this.check(m.UNTIL)?xn(this):this.check(m.CASE)?An(this):this.check(m.LPAREN)?Cn(this):this.check(m.LBRACE)?Nn(this):this.check(m.DPAREN_START)?this.parseArithmeticCommand():this.check(m.DBRACK_START)?this.parseConditionalCommand():this.check(m.FUNCTION)?this.parseFunctionDef():this.check(m.NAME,m.WORD)&&this.peek(1).type===m.LPAREN&&this.peek(2).type===m.RPAREN?this.parseFunctionDef():ko(this)}isWord(){let e=this.current().type;return e===m.WORD||e===m.NAME||e===m.NUMBER||e===m.IF||e===m.FOR||e===m.WHILE||e===m.UNTIL||e===m.CASE||e===m.FUNCTION||e===m.ELSE||e===m.ELIF||e===m.FI||e===m.THEN||e===m.DO||e===m.DONE||e===m.ESAC||e===m.IN||e===m.BANG}parseWord(){let e=this.advance();return this.parseWordFromString(e.value,e.quoted,e.singleQuoted)}parseWordFromString(e,r=!1,n=!1,s=!1,i=!1){let a=je(this,e,r,n,s,i);return k.word(a)}parseCommandSubstitution(e,r){let n=r+2,s=1,i=n,a=!1,o=!1,c=0,l=!1,u="";for(;i<e.length&&s>0;){let p=e[i];a?p==="'"&&(a=!1):o?p==="\\"&&i+1<e.length?i++:p==='"'&&(o=!1):p==="'"?(a=!0,u=""):p==='"'?(o=!0,u=""):p==="\\"&&i+1<e.length?(i++,u=""):/[a-zA-Z_]/.test(p)?u+=p:(u==="case"?(c++,l=!1):u==="in"&&c>0?l=!0:u==="esac"&&c>0&&(c--,l=!1),u="",p==="("?i>0&&e[i-1]==="$"?s++:l||s++:p===")"?l?l=!1:s--:p===";"&&c>0&&i+1<e.length&&e[i+1]===";"&&(l=!0)),s>0&&i++}s>0&&this.error("unexpected EOF while looking for matching `)'");let f=e.slice(n,i),h=new t().parse(f);return{part:k.commandSubstitution(h,!1),endIndex:i+1}}parseBacktickSubstitution(e,r,n=!1){let i=r+1,a="";for(;i<e.length&&e[i]!=="`";)if(e[i]==="\\"){let l=e[i+1];l==="$"||l==="`"||l==="\\"||l===`
466
466
  `||n&&l==='"'?(l!==`
467
- `&&(a+=l),i+=2):(a+=e[i],i++)}else a+=e[i],i++;i>=e.length&&this.error("unexpected EOF while looking for matching ``'");let c=new t().parse(a);return{part:k.commandSubstitution(c,!0),endIndex:i+1}}parseArithmeticExpansion(e,r){let n=r+3,s=1,i=0,a=n;for(;a<e.length-1&&s>0;)e[a]==="$"&&e[a+1]==="("?e[a+2]==="("?(s++,a+=3):(i++,a+=2):e[a]==="("&&e[a+1]==="("?(s++,a+=2):e[a]===")"&&e[a+1]===")"?i>0?(i--,a++):(s--,s>0&&(a+=2)):e[a]==="("?(i++,a++):(e[a]===")"&&i>0&&i--,a++);let o=e.slice(n,a),c=this.parseArithmeticExpression(o);return{part:k.arithmeticExpansion(c),endIndex:a+2}}parseArithmeticCommand(){this.expect(m.DPAREN_START);let e="",r=1,n=0,s=!1,i=!1;for(;r>0&&!this.check(m.EOF);){if(s){if(s=!1,n>0){n--,e+=")";continue}if(this.check(m.RPAREN)){r--,i=!0,this.advance();continue}if(this.check(m.DPAREN_END)){r--,i=!0;continue}e+=")";continue}this.check(m.DPAREN_START)?(r++,e+="((",this.advance()):this.check(m.DPAREN_END)?n>=2?(n-=2,e+="))",this.advance()):n===1?(n--,e+=")",s=!0,this.advance()):(r--,i=!0,r>0&&(e+="))"),this.advance()):this.check(m.LPAREN)?(n++,e+="(",this.advance()):this.check(m.RPAREN)?(n>0&&n--,e+=")",this.advance()):(e+=this.current().value,this.advance())}i||this.expect(m.DPAREN_END);let a=this.parseArithmeticExpression(e.trim()),o=this.parseOptionalRedirections();return k.arithmeticCommand(a,o)}parseConditionalCommand(){this.expect(m.DBRACK_START);let e=Cn(this);this.expect(m.DBRACK_END);let r=this.parseOptionalRedirections();return k.conditionalCommand(e,r)}parseFunctionDef(){let e;this.check(m.FUNCTION)?(this.advance(),e=this.expect(m.NAME,"Expected function name").value,this.check(m.LPAREN)&&(this.advance(),this.expect(m.RPAREN))):(e=this.advance().value,this.expect(m.LPAREN),this.expect(m.RPAREN)),this.skipNewlines();let r=this.parseCompoundCommandBody(),n=this.parseOptionalRedirections();return k.functionDef(e,r,n)}parseCompoundCommandBody(){if(this.check(m.LBRACE))return Sn(this);if(this.check(m.LPAREN))return xn(this);if(this.check(m.IF))return yn(this);if(this.check(m.FOR))return gn(this);if(this.check(m.WHILE))return wn(this);if(this.check(m.UNTIL))return En(this);if(this.check(m.CASE))return bn(this);this.error("Expected compound command for function body")}parseCompoundList(){let e=[];for(this.skipNewlines();!this.check(m.EOF,m.FI,m.ELSE,m.ELIF,m.THEN,m.DO,m.DONE,m.ESAC,m.RPAREN,m.RBRACE,m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let r=this.pos,n=this.parseStatement();if(n&&e.push(n),this.skipSeparators(),this.pos===r&&!n)break}return e}parseOptionalRedirections(){let e=[];for(;sr(this);){this.checkIterationLimit();let r=this.pos;if(e.push(ir(this)),this.pos===r)break}return e}parseArithmeticExpression(e){return se(this,e)}};function Ge(t){return new le().parse(t)}X();var ht=class{fs;cwd;constructor(e,r){this.fs=e,this.cwd=r}isGlobPattern(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandArgs(e,r){let n=[];for(let s=0;s<e.length;s++){let i=e[s];if((r?.[s]??!1)||!this.isGlobPattern(i))n.push(i);else{let o=await this.expand(i);o.length>0?n.push(...o):n.push(i)}}return n}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}async expandSimple(e){let r=[],n=e.lastIndexOf("/"),s,i;n===-1?(s=this.cwd,i=e):(s=e.slice(0,n)||"/",i=e.slice(n+1));let a=this.fs.resolvePath(this.cwd,s);try{let o=await this.fs.readdir(a);for(let c of o)if(this.matchPattern(c,i)){let l=n===-1?c:`${s}/${c}`;r.push(l)}}catch{}return r.sort()}async expandRecursive(e){let r=[],n=e.indexOf("**"),s=e.slice(0,n).replace(/\/$/,"")||".",a=e.slice(n+2).replace(/^\//,"");return await this.walkDirectory(s,a,r),r.sort()}async walkDirectory(e,r,n){let s=this.fs.resolvePath(this.cwd,e);try{let i=await this.fs.readdir(s);for(let a of i){let o=e==="."?a:`${e}/${a}`,c=this.fs.resolvePath(this.cwd,o);try{(await this.fs.stat(c)).isDirectory?await this.walkDirectory(o,r,n):r&&this.matchPattern(a,r)&&n.push(o)}catch{}}}catch{}}matchPattern(e,r){return this.patternToRegex(r).test(e)}patternToRegex(e){let r="^";for(let n=0;n<e.length;n++){let s=e[n];if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let i=n+1,a="[";for(i<e.length&&(e[i]==="^"||e[i]==="!")&&(a+="^",i++),i<e.length&&e[i]==="]"&&(a+="\\]",i++);i<e.length&&e[i]!=="]";){if(e[i]==="["&&i+1<e.length&&e[i+1]===":"){let o=e.indexOf(":]",i+2);if(o!==-1){let c=e.slice(i+2,o),l=this.posixClassToRegex(c);a+=l,i=o+2;continue}}if(e[i]==="\\"&&i+1<e.length){a+=`\\${e[i+1]}`,i+=2;continue}e[i]==="-"?a+="\\-":a+=e[i],i++}a+="]",r+=a,n=i}else if(s==="\\"&&n+1<e.length){let i=e[n+1];/[.+^${}()|\\*?[\]]/.test(i)?r+=`\\${i}`:r+=i,n++}else/[.+^${}()|]/.test(s)?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r)}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]||""}};X();function Ae(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return Ae(t.expression);case"ArithBinary":return Ae(t.left)||Ae(t.right);case"ArithUnary":return Ae(t.operand);case"ArithTernary":return Ae(t.condition)||Ae(t.consequent)||Ae(t.alternate);case"ArithAssignment":return Ae(t.value);case"ArithGroup":return Ae(t.expression);case"ArithArrayElement":return t.index?Ae(t.index):!1;case"ArithConcat":return t.parts.some(Ae);default:return!1}}function vn(t){let e=t.operation;return e?!!("word"in e&&e.word&&Fe(e.word)||e.type==="PatternReplacement"&&(e.pattern&&Fe(e.pattern)||e.replacement&&Fe(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&Fe(e.pattern)):!1}function ar(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return Ae(t.expression.expression);case"DoubleQuoted":return t.parts.some(ar);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&Fe(e.word));case"ParameterExpansion":return vn(t);default:return!1}}function Fe(t){return t.parts.some(ar)}function kn(t){if(!t.operation)return!1;let e=t.operation,r;if((e.type==="DefaultValue"||e.type==="AssignDefault"||e.type==="UseAlternative"||e.type==="ErrorIfUnset")&&(r=e.word?.parts),!r)return!1;for(let n of r)if(n.type==="DoubleQuoted"||n.type==="SingleQuoted")return!0;return!1}function No(t){let e=!1,r=!1,n=!1,s=!1,i=!1;for(let a of t){if((a.type==="SingleQuoted"||a.type==="DoubleQuoted")&&(e=!0,a.type==="DoubleQuoted"))for(let o of a.parts)o.type==="ParameterExpansion"&&o.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&!o.operation&&(s=!0);a.type==="CommandSubstitution"&&(r=!0),a.type==="ParameterExpansion"&&(i=!0,(a.parameter==="@"||a.parameter==="*")&&(n=!0),kn(a)&&(e=!0))}return{hasQuoted:e,hasCommandSub:r,hasArrayVar:n,hasArrayAtExpansion:s,hasParamExpansion:i}}function Fd(t,e,r,n,s){let i=r??1;i===0&&(i=1);let a=Math.abs(i),o=[],c=0;n?.match(/^-?0\d/)&&(c=Math.max(c,n.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(c=Math.max(c,s.replace(/^-/,"").length));let l=u=>{if(c>0){let f=u<0,d=String(Math.abs(u)).padStart(c,"0");return f?`-${d}`:d}return String(u)};if(t<=e)for(let u=t,f=0;u<=e&&f<1e4;u+=a,f++)o.push(l(u));else for(let u=t,f=0;u>=e&&f<1e4;u-=a,f++)o.push(l(u));return o}function Md(t,e,r){let n=r??1;n===0&&(n=1);let s=t.charCodeAt(0),i=e.charCodeAt(0),a=Math.abs(n),o=t>="A"&&t<="Z",c=t>="a"&&t<="z",l=e>="A"&&e<="Z",u=e>="a"&&e<="z";if(o&&u||c&&l)return null;let f=[];if(s<=i)for(let d=s,h=0;d<=i&&h<1e4;d+=a,h++)f.push(String.fromCharCode(d));else for(let d=s,h=0;d>=i&&h<1e4;d-=a,h++)f.push(String.fromCharCode(d));return f}function vt(t,e,r,n,s){let i=r!==void 0?`..${r}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:Fd(t,e,r,n,s),literal:`{${t}..${e}${i}}`}:typeof t=="string"&&typeof e=="string"?{expanded:Md(t,e,r),literal:`{${t}..${e}${i}}`}:{expanded:null,literal:`{${t}..${e}${i}}`}}function ye(t,e){let r="",n=0;for(;n<t.length;){let s=t[n];if(s==="\\")if(n+1<t.length){let i=t[n+1];/[\\^$.|+(){}[\]*?]/.test(i)?r+=`\\${i}`:r+=i,n+=2}else r+="\\\\",n++;else if(s==="*")r+=e?".*":".*?",n++;else if(s==="?")r+=".",n++;else if(s==="["){let i=_d(t,n);if(i===-1)r+="\\[",n++;else{let a=t.slice(n+1,i);r+=Wd(a),n=i+1}}else/[\^$.|+(){}]/.test(s)?(r+=`\\${s}`,n++):(r+=s,n++)}return r}function _d(t,e){let r=e+1;for(r<t.length&&t[r]==="^"&&r++,r<t.length&&t[r]==="]"&&r++;r<t.length;){if(t[r]==="\\"&&r+1<t.length){r+=2;continue}if(t[r]==="]")return r;if(t[r]==="'"){let n=t.indexOf("'",r+1);if(n!==-1){r=n+1;continue}}if(t[r]==="["&&r+1<t.length&&t[r+1]===":"){let n=t.indexOf(":]",r+2);if(n!==-1){r=n+2;continue}}r++}return-1}function Wd(t){let e="[",r=0;for((t[0]==="^"||t[0]==="!")&&(e+="^",r++);r<t.length;){if(t[r]==="'"){let s=t.indexOf("'",r+1);if(s!==-1){let i=t.slice(r+1,s);for(let a of i)a==="\\"?e+="\\\\":a==="]"?e+="\\]":a==="^"&&e==="["?e+="\\^":e+=a;r=s+1;continue}}if(t[r]==="["&&r+1<t.length&&t[r+1]===":"){let s=t.indexOf(":]",r+2);if(s!==-1){let i=t.slice(r+2,s);e+=Hd(i),r=s+2;continue}}let n=t[r];n==="\\"?r+1<t.length?(e+=`\\${t[r+1]}`,r+=2):(e+="\\\\",r++):n==="-"&&r>0&&r<t.length-1?(e+="-",r++):n==="^"&&r===0?(e+="^",r++):(n==="]"&&r===0?e+="\\]":e+=n,r++)}return e+="]",e}var Bd={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 Hd(t){return Bd[t]??""}X();function kt(t,e){let r=`${e}_`,n=[];for(let s of Object.keys(t.state.env))if(s.startsWith(r)){let i=s.slice(r.length),a=Number.parseInt(i,10);!Number.isNaN(a)&&String(a)===i&&n.push(a)}return n.sort((s,i)=>s-i)}function In(t,e){let r=`${e}_`;for(let n of Object.keys(t.state.env))n.startsWith(r)&&delete t.state.env[n]}function Rn(t,e){let r=`${e}_`,n=[];for(let s of Object.keys(t.state.env))if(s.startsWith(r)&&!s.includes("__")){let i=s.slice(r.length);n.push(i)}return n.sort()}function vo(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function or(t){return t.IFS??`
468
- `}function ko(t){return t.IFS===""}function It(t){return t.split("").map(e=>/[\\^$.*+?()[\]{}|-]/.test(e)?`\\${e}`:e===" "?"\\t":e===`
469
- `?"\\n":e).join("")}function Ud(t,e){let r=It(t);return new RegExp(`[${r}]+`,e)}function zd(t){let e=It(t);return new RegExp(`^[${e}]+`)}function Gd(t){let e=It(t);return new RegExp(`[${e}]+$`)}function Rt(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function Io(t,e){if(e==="")return{words:[t],wordStarts:[0]};let r=[],n=[],s=Ud(e,"g"),i=0,a=t.match(zd(e));a&&(i=a[0].length),s.lastIndex=i;let o=s.exec(t);for(;o!==null;)o.index>i&&(n.push(i),r.push(t.substring(i,o.index))),i=s.lastIndex,o=s.exec(t);return i<t.length&&(n.push(i),r.push(t.substring(i))),{words:r,wordStarts:n}}function Ro(t,e){return e===""?t:t.replace(Gd(e),"")}function ie(t,e){return t.state.associativeArrays?.has(e)?Rn(t,e).map(i=>[i,t.state.env[`${e}_${i}`]]):kt(t,e).map(s=>[s,t.state.env[`${e}_${s}`]])}function $o(t,e){return t.state.associativeArrays?.has(e)?Rn(t,e).length>0:kt(t,e).length>0}function Ce(t,e,r=!0,n=!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 a="";return t.state.options.errexit&&(a+="e"),t.state.options.nounset&&(a+="u"),t.state.options.verbose&&(a+="v"),t.state.options.xtrace&&(a+="x"),t.state.options.pipefail&&(a+="p"),a}case"*":{let a=Number.parseInt(t.state.env["#"]||"0",10);if(a===0)return"";let o=[];for(let c=1;c<=a;c++)o.push(t.state.env[String(c)]||"");return o.join(Rt(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:""}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(e))throw new De(`\${${e}}`);let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let a=s[1],o=s[2];if(o==="@"||o==="*"){let f=ie(t,a);if(f.length>0)return f.map(([,h])=>h).join(" ");let d=t.state.env[a];return d!==void 0?d:""}if(t.state.associativeArrays?.has(a)){let f=vo(o),d=t.state.env[`${a}_${f}`];if(d===void 0&&r&&t.state.options.nounset)throw new Se(`${a}[${o}]`);return d||""}let l;if(/^-?\d+$/.test(o))l=Number.parseInt(o,10);else try{let f=new le,d=se(f,o);l=j(t,d.expression)}catch{let f=t.state.env[o];l=f?Number.parseInt(f,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let f=ie(t,a);if(f.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${a}: bad array subscript
470
- `,"";let h=Math.max(...f.map(([b])=>typeof b=="number"?b:0))+1+l;return h<0?(t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${a}: bad array subscript
471
- `,""):t.state.env[`${a}_${h}`]||""}let u=t.state.env[`${a}_${l}`];if(u===void 0&&r&&t.state.options.nounset)throw new Se(`${a}[${l}]`);return u||""}if(/^[1-9][0-9]*$/.test(e)){let a=t.state.env[e];if(a===void 0&&r&&t.state.options.nounset)throw new Se(e);return a||""}let i=t.state.env[e];if(i===void 0&&r&&t.state.options.nounset)throw new Se(e);return i||""}async function Po(t,e,r,n,s){let i=[];for(let u of e){let f=u.type==="ParameterExpansion"||u.type==="CommandSubstitution"||u.type==="ArithmeticExpansion";if(u.type==="ParameterExpansion"&&kn(u)){let d=await s(t,u);i.push({value:d,splittable:!1})}else{let d=await s(t,u);i.push({value:d,splittable:f})}}if(!i.some(u=>u.splittable&&new RegExp(`[${n}]`).test(u.value))){let u=i.map(f=>f.value).join("");return u?[u]:[]}let o=new RegExp(`[${n}]+`),c=[],l="";for(let u=0;u<i.length;u++){let f=i[u];if(!f.splittable)l+=f.value;else{let d=f.value.split(o);for(let h=0;h<d.length;h++)h===0?l+=d[h]:(l!==""&&c.push(l),l=d[h])}}return l!==""&&c.push(l),c}function ge(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oo(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function Do(t){switch(t.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return t.value==="";default:return!1}}function $n(t){if(t==="")return"''";if(!/['\\\n\r\t\x00-\x1f\x7f]/.test(t))return`'${t}'`;let e="$'";for(let r of t)switch(r){case"'":e+="\\'";break;case"\\":e+="\\\\";break;case`
472
- `:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let n=r.charCodeAt(0);n<32||n===127?e+=`\\x${n.toString(16).padStart(2,"0")}`:e+=r}}return`${e}'`}function rt(t,e,r=!1){return e.map(n=>Me(t,n,r)).join("")}async function nt(t,e,r=!1){let n=[];for(let s of e)n.push(await Pe(t,s));return n.join("")}function jd(t){return Do(t)}function Lo(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!jd(e))return!1;return!0}function To(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function Fo(t,e,r=!1){let n=Oo(e);if(n!==null)return n;switch(e.type){case"ParameterExpansion":return Ho(t,e,r);case"TildeExpansion":return r?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 Me(t,e,r=!1){let n=Fo(t,e,r);if(n!==null)return n;switch(e.type){case"DoubleQuoted":{let s=[];for(let i of e.parts)s.push(Me(t,i,!0));return s.join("")}case"ArithmeticExpansion":return String(j(t,e.expression.expression));case"BraceExpansion":{let s=[];for(let i of e.items)if(i.type==="Range"){let a=vt(i.start,i.end,i.step,i.startStr,i.endStr);if(a.expanded)s.push(...a.expanded);else return a.literal}else s.push(lr(t,i.word));return s.join(" ")}default:return""}}function lr(t,e){let r=e.parts,n=r.length;if(n===1)return Me(t,r[0]);let s=[];for(let i=0;i<n;i++)s.push(Me(t,r[i]));return s.join("")}async function Q(t,e){return Fe(e)?Bo(t,e):lr(t,e)}function cr(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&cr(e.parts))return!0;return!1}function qd(t){for(let e of t){if(e.type==="BraceExpansion"){for(let r of e.items)if(r.type==="Word"&&Fe(r.word))return!0}if(ar(e))return!0}return!1}var Mo=1e4,pt=1e5;function _o(t,e,r={count:0}){if(r.count>pt)return[[]];let n=[[]];for(let s of e)if(s.type==="BraceExpansion"){let i=[],a=!1,o="";for(let u of s.items)if(u.type==="Range"){let f=vt(u.start,u.end,u.step,u.startStr,u.endStr);if(f.expanded)for(let d of f.expanded)r.count++,i.push(d);else{a=!0,o=f.literal;break}}else{let f=_o(t,u.word.parts,r);for(let d of f)r.count++,i.push(d.join(""))}if(a){for(let u of n)r.count++,u.push(o);continue}if(n.length*i.length>Mo||r.count>pt)return n;let l=[];for(let u of n)for(let f of i){if(r.count++,r.count>pt)return l.length>0?l:n;l.push([...u,f])}n=l}else{let i=Me(t,s);for(let a of n)r.count++,a.push(i)}return n}function Vd(t,e){let r=e.parts;return cr(r)?_o(t,r).map(s=>s.join("")):[lr(t,e)]}async function Wo(t,e,r={count:0}){if(r.count>pt)return[[]];let n=[[]];for(let s of e)if(s.type==="BraceExpansion"){let i=[],a=!1,o="";for(let u of s.items)if(u.type==="Range"){let f=vt(u.start,u.end,u.step,u.startStr,u.endStr);if(f.expanded)for(let d of f.expanded)r.count++,i.push(d);else{a=!0,o=f.literal;break}}else{let f=await Wo(t,u.word.parts,r);for(let d of f)r.count++,i.push(d.join(""))}if(a){for(let u of n)r.count++,u.push(o);continue}if(n.length*i.length>Mo||r.count>pt)return n;let l=[];for(let u of n)for(let f of i){if(r.count++,r.count>pt)return l.length>0?l:n;l.push([...u,f])}n=l}else{let i=await Pe(t,s);for(let a of n)r.count++,a.push(i)}return n}async function Zd(t,e){let r=e.parts;return cr(r)?(await Wo(t,r)).map(s=>s.join("")):[await Q(t,e)]}async function $t(t,e){let r=e.parts,{hasQuoted:n,hasCommandSub:s,hasArrayVar:i,hasArrayAtExpansion:a,hasParamExpansion:o}=No(r),l=cr(r)?qd(r)?await Zd(t,e):Vd(t,e):null;if(l&&l.length>1){let d=[];for(let h of l)if(!n&&/[*?[]/.test(h)){let b=await new ht(t.fs,t.state.cwd).expand(h);b.length>0?d.push(...b):d.push(h)}else d.push(h);return{values:d,quoted:!1}}if(a&&r.length===1&&r[0].type==="DoubleQuoted"){let d=r[0];if(d.parts.length===1&&d.parts[0].type==="ParameterExpansion"){let p=d.parts[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@]\]$/);if(p){let b=p[1],w=ie(t,b);if(w.length>0)return{values:w.map(([,E])=>E),quoted:!0};let g=t.state.env[b];return g!==void 0?{values:[g],quoted:!0}:{values:[],quoted:!0}}}}if(!n&&i&&r.length===1&&r[0].type==="ParameterExpansion"){let d=r[0].parameter;if(d==="@"||d==="*"){let h=Number.parseInt(t.state.env["#"]||"0",10);if(h===0)return{values:[],quoted:!1};let p=[];for(let b=1;b<=h;b++)p.push(t.state.env[String(b)]||"");return{values:p,quoted:!1}}}if(!n&&(s||i||o)&&!ko(t.state.env)){let d=or(t.state.env),h=It(d),p=await Po(t,r,d,h,Pe),b=[],w=new ht(t.fs,t.state.cwd);for(let g of p)if(/[*?[]/.test(g)){let E=await w.expand(g);E.length>0?b.push(...E):b.push(g)}else b.push(g);return{values:b,quoted:!1}}let f=Fe(e)?await Bo(t,e):lr(t,e);if(!n&&/[*?[]/.test(f)){let h=await new ht(t.fs,t.state.cwd).expand(f);if(h.length>0)return{values:h,quoted:!1}}return f===""&&!n?{values:[],quoted:!1}:{values:[f],quoted:n}}async function Bo(t,e){let r=e.parts,n=r.length;if(n===1)return Pe(t,r[0]);let s=[];for(let i=0;i<n;i++)s.push(await Pe(t,r[i]));return s.join("")}async function Pe(t,e){if(e.type==="ParameterExpansion"&&vn(e))return Qd(t,e);let r=Fo(t,e);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let n=[];for(let s of e.parts)n.push(await Pe(t,s));return n.join("")}case"CommandSubstitution":try{let n=await t.executeScript(e.body);return t.state.lastExitCode=n.exitCode,t.state.env["?"]=String(n.exitCode),n.stdout.replace(/\n+$/,"")}catch(n){if(n instanceof W)throw n;if(n instanceof Z)return t.state.lastExitCode=n.exitCode,t.state.env["?"]=String(n.exitCode),n.stdout.replace(/\n+$/,"");throw n}case"ArithmeticExpansion":return String(await q(t,e.expression.expression));case"BraceExpansion":{let n=[];for(let s of e.items)if(s.type==="Range"){let i=vt(s.start,s.end,s.step,s.startStr,s.endStr);if(i.expanded)n.push(...i.expanded);else return i.literal}else n.push(await Q(t,s.word));return n.join(" ")}default:return""}}function Ho(t,e,r=!1){let{parameter:n,operation:s}=e,i=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),a=Ce(t,n,!i);if(!s)return a;let o=!(n in t.state.env),c=a==="";switch(s.type){case"DefaultValue":return(o||s.checkEmpty&&c)&&s.word?rt(t,s.word.parts,r):a;case"AssignDefault":{if((o||s.checkEmpty&&c)&&s.word){let u=rt(t,s.word.parts,r),f=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(f){let[,d,h]=f,p;if(/^\d+$/.test(h))p=Number.parseInt(h,10);else{try{let w=new le,g=se(w,h);p=j(t,g.expression)}catch{let w=t.state.env[h];p=w?Number.parseInt(w,10):0}Number.isNaN(p)&&(p=0)}t.state.env[`${d}_${p}`]=u;let b=Number.parseInt(t.state.env[`${d}__length`]||"0",10);p>=b&&(t.state.env[`${d}__length`]=String(p+1))}else t.state.env[n]=u;return u}return a}case"ErrorIfUnset":{if(o||s.checkEmpty&&c){let u=s.word?rt(t,s.word.parts,r):`${n}: parameter null or not set`;throw new Z(1,"",`bash: ${u}
473
- `)}return a}case"UseAlternative":return!(o||s.checkEmpty&&c)&&s.word?rt(t,s.word.parts,r):"";case"Length":{let l=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l){let u=ie(t,l[1]);return String(u.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&$o(t,n)){let u=t.state.env[`${n}_0`]||"";return String(u.length)}return String(a.length)}case"LengthSliceError":throw new De(n);case"Substring":{let l=s.offset?j(t,s.offset.expression):0,u=s.length?j(t,s.length.expression):void 0;if(n==="@"||n==="*"){let p=(t.state.env["@"]||"").split(" ").filter(E=>E),b=t.state.env[0]||"bash",w=l===0?[b,...p]:p,g=l===0?0:l-1;if(g<0||g>=w.length)return"";if(u!==void 0){let E=u<0?w.length+u:g+u;return w.slice(g,Math.max(g,E)).join(" ")}return w.slice(g).join(" ")}let f=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(f){let b=ie(t,f[1]).map(([,g])=>g),w=l;if(w<0&&(w=b.length+w,w<0))return"";if(u!==void 0){if(u<0){let g=b.length+u;return b.slice(w,Math.max(w,g)).join(" ")}return b.slice(w,w+u).join(" ")}return b.slice(w).join(" ")}let d=[...a],h=l;if(h<0&&(h=Math.max(0,d.length+h)),u!==void 0){if(u<0){let p=d.length+u;return d.slice(h,Math.max(h,p)).join("")}return d.slice(h,h+u).join("")}return d.slice(h).join("")}case"PatternRemoval":{let l="";if(s.pattern)for(let f of s.pattern.parts)if(f.type==="Glob")l+=ye(f.pattern,s.greedy);else if(f.type==="Literal")l+=ye(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")l+=ge(f.value);else if(f.type==="DoubleQuoted"){let d=rt(t,f.parts);l+=ge(d)}else if(f.type==="ParameterExpansion"){let d=Me(t,f);l+=ye(d,s.greedy)}else{let d=Me(t,f);l+=ge(d)}if(s.side==="prefix")return a.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return a.replace(u,"");for(let f=a.length;f>=0;f--){let d=a.slice(f);if(u.test(d))return a.slice(0,f)}return a}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=ye(d.pattern,!0);else if(d.type==="Literal")l+=ye(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=ge(d.value);else if(d.type==="DoubleQuoted"){let h=rt(t,d.parts);l+=ge(h)}else if(d.type==="ParameterExpansion"){let h=Me(t,d);l+=ye(h,!0)}else{let h=Me(t,d);l+=ge(h)}let u=s.replacement?rt(t,s.replacement.parts):"";if(l==="")return a;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let f=s.all?"g":"";try{let d=new RegExp(l,f);if(s.all){let h="",p=0,b=d.exec(a);for(;b!==null&&!(b[0].length===0&&b.index===a.length);)h+=a.slice(p,b.index)+u,p=b.index+b[0].length,b[0].length===0&&p++,b=d.exec(a);return h+=a.slice(p),h}return a.replace(d,u)}catch{return a}}case"CaseModification":return s.direction==="upper"?s.all?a.toUpperCase():a.charAt(0).toUpperCase()+a.slice(1):s.all?a.toLowerCase():a.charAt(0).toLowerCase()+a.slice(1);case"Transform":{let l=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l&&s.operator==="Q")return ie(t,l[1]).map(([,d])=>$n(d)).join(" ");switch(s.operator){case"Q":return $n(a);case"P":return a;case"a":return"";case"A":return`${n}=${$n(a)}`;case"E":return a.replace(/\\([\\abefnrtv'"?])/g,(u,f)=>{switch(f){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
474
- `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return f}});case"K":return"";default:return a}}case"Indirection":return Ce(t,a);case"ArrayKeys":{let u=ie(t,s.array).map(([f])=>String(f));return s.star?u.join(Rt(t.state.env)):u.join(" ")}case"VarNamePrefix":{let l=Object.keys(t.state.env).filter(u=>u.startsWith(s.prefix)&&!u.includes("__")).sort();return s.star?l.join(Rt(t.state.env)):l.join(" ")}default:return a}}async function Qd(t,e,r=!1){let{parameter:n,operation:s}=e,i=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),a=Ce(t,n,!i);if(!s)return a;let o=!(n in t.state.env),c=a==="";switch(s.type){case"DefaultValue":return(o||s.checkEmpty&&c)&&s.word?nt(t,s.word.parts,r):a;case"AssignDefault":{if((o||s.checkEmpty&&c)&&s.word){let u=await nt(t,s.word.parts,r),f=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(f){let[,d,h]=f,p;if(/^\d+$/.test(h))p=Number.parseInt(h,10);else{try{let w=new le,g=se(w,h);p=await q(t,g.expression)}catch{let w=t.state.env[h];p=w?Number.parseInt(w,10):0}Number.isNaN(p)&&(p=0)}t.state.env[`${d}_${p}`]=u;let b=Number.parseInt(t.state.env[`${d}__length`]||"0",10);p>=b&&(t.state.env[`${d}__length`]=String(p+1))}else t.state.env[n]=u;return u}return a}case"ErrorIfUnset":{if(o||s.checkEmpty&&c){let u=s.word?await nt(t,s.word.parts,r):`${n}: parameter null or not set`;throw new Z(1,"",`bash: ${u}
475
- `)}return a}case"UseAlternative":return!(o||s.checkEmpty&&c)&&s.word?nt(t,s.word.parts,r):"";case"PatternRemoval":{let l="";if(s.pattern)for(let f of s.pattern.parts)if(f.type==="Glob")l+=ye(f.pattern,s.greedy);else if(f.type==="Literal")l+=ye(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")l+=ge(f.value);else if(f.type==="DoubleQuoted"){let d=await nt(t,f.parts);l+=ge(d)}else if(f.type==="ParameterExpansion"){let d=await Pe(t,f);l+=ye(d,s.greedy)}else{let d=await Pe(t,f);l+=ge(d)}if(s.side==="prefix")return a.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return a.replace(u,"");for(let f=a.length;f>=0;f--){let d=a.slice(f);if(u.test(d))return a.slice(0,f)}return a}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=ye(d.pattern,!0);else if(d.type==="Literal")l+=ye(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=ge(d.value);else if(d.type==="DoubleQuoted"){let h=await nt(t,d.parts);l+=ge(h)}else if(d.type==="ParameterExpansion"){let h=await Pe(t,d);l+=ye(h,!0)}else{let h=await Pe(t,d);l+=ge(h)}let u=s.replacement?await nt(t,s.replacement.parts):"";if(l==="")return a;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let f=s.all?"g":"";try{let d=new RegExp(l,f);if(s.all){let h="",p=0,b=d.exec(a);for(;b!==null&&!(b[0].length===0&&b.index===a.length);)h+=a.slice(p,b.index)+u,p=b.index+b[0].length,b[0].length===0&&p++,b=d.exec(a);return h+=a.slice(p),h}return a.replace(d,u)}catch{return a}}default:return Ho(t,e,r)}}function Pn(t,e,r){switch(r){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 te("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 Uo(t,e,r){switch(r){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 On(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function Kd(t,e){let r=t.state.env[e];if(r!==void 0)return r;let n=t.state.env[`${e}_0`];return n!==void 0?n:Ce(t,e)}function mt(t){if(!t)return 0;let e=Number.parseInt(t,10);if(!Number.isNaN(e)&&/^-?\d+$/.test(t.trim()))return e;let r=t.trim();if(!r)return 0;try{let n=new le,{expr:s,pos:i}=Le(n,r,0);if(i<r.length){let a=r.slice(i).trim().split(/\s+/)[0];throw new te(`${r}: syntax error in expression (error token is "${a}")`)}return s.type==="ArithNumber"?s.value:e||0}catch(n){if(n instanceof te)throw n;let s=r.split(/\s+/).slice(1)[0]||r;throw new te(`${r}: syntax error in expression (error token is "${s}")`)}}function ur(t,e,r=new Set){if(r.has(e))return 0;r.add(e);let n=Kd(t,e);if(!n)return 0;let s=Number.parseInt(n,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(n.trim()))return s;let i=n.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return ur(t,i,r);try{let a=new le,{expr:o}=Le(a,i,0);return Ne(t,o,r)}catch{return 0}}function Ne(t,e,r){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new te("value too great for base");return e.value;case"ArithVariable":return ur(t,e.name,r);case"ArithBinary":{if(e.operator==="||")return Ne(t,e.left,r)||Ne(t,e.right,r)?1:0;if(e.operator==="&&")return Ne(t,e.left,r)&&Ne(t,e.right,r)?1:0;let n=Ne(t,e.left,r),s=Ne(t,e.right,r);return Pn(n,s,e.operator)}case"ArithUnary":{let n=Ne(t,e.operand,r);return On(n,e.operator)}case"ArithTernary":return Ne(t,e.condition,r)?Ne(t,e.consequent,r):Ne(t,e.alternate,r);case"ArithGroup":return Ne(t,e.expression,r);default:return j(t,e)}}function je(t,e){if(e.startsWith("#")){let f=e.slice(1),d=t.state.env[f]||"";return String(d.length)}if(e.startsWith("!")){let f=e.slice(1),d=t.state.env[f]||"";return t.state.env[d]||""}let r=[":-",":=",":?",":+","-","=","?","+"],n=-1,s="";for(let f of r){let d=e.indexOf(f);d>0&&(n===-1||d<n)&&(n=d,s=f)}if(n===-1)return Ce(t,e);let i=e.slice(0,n),a=e.slice(n+s.length),o=t.state.env[i],c=o===void 0,l=o==="",u=s.startsWith(":");switch(s){case":-":case"-":return c||u&&l?a:o||"";case":=":case"=":return c||u&&l?(t.state.env[i]=a,a):o||"";case":+":case"+":return!(c||u&&l)?a:"";case":?":case"?":{if(c||u&&l)throw new Error(a||`${i}: parameter null or not set`);return o||""}default:return o||""}}function j(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new te("value too great for base");return e.value;case"ArithVariable":return ur(t,e.name);case"ArithNested":return j(t,e.expression);case"ArithCommandSubst":return 0;case"ArithBracedExpansion":{let r=je(t,e.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=je(t,e.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)return 0;let s=`${n}#${e.value}`;return dt(s)}case"ArithDynamicNumber":{let n=je(t,e.prefix)+e.suffix;return dt(n)}case"ArithArrayElement":{let r=t.state.associativeArrays?.has(e.array),n;if(e.stringKey!==void 0)n=`${e.array}_${e.stringKey}`;else if(r&&e.index?.type==="ArithVariable")n=`${e.array}_${e.index.name}`;else if(e.index){let i=j(t,e.index);if(i<0){let o=ie(t,e.array);if(o.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
467
+ `&&(a+=l),i+=2):(a+=e[i],i++)}else a+=e[i],i++;i>=e.length&&this.error("unexpected EOF while looking for matching ``'");let c=new t().parse(a);return{part:k.commandSubstitution(c,!0),endIndex:i+1}}parseArithmeticExpansion(e,r){let n=r+3,s=1,i=0,a=n;for(;a<e.length-1&&s>0;)e[a]==="$"&&e[a+1]==="("?e[a+2]==="("?(s++,a+=3):(i++,a+=2):e[a]==="("&&e[a+1]==="("?(s++,a+=2):e[a]===")"&&e[a+1]===")"?i>0?(i--,a++):(s--,s>0&&(a+=2)):e[a]==="("?(i++,a++):(e[a]===")"&&i>0&&i--,a++);let o=e.slice(n,a),c=this.parseArithmeticExpression(o);return{part:k.arithmeticExpansion(c),endIndex:a+2}}parseArithmeticCommand(){this.expect(m.DPAREN_START);let e="",r=1,n=0,s=!1,i=!1;for(;r>0&&!this.check(m.EOF);){if(s){if(s=!1,n>0){n--,e+=")";continue}if(this.check(m.RPAREN)){r--,i=!0,this.advance();continue}if(this.check(m.DPAREN_END)){r--,i=!0;continue}e+=")";continue}this.check(m.DPAREN_START)?(r++,e+="((",this.advance()):this.check(m.DPAREN_END)?n>=2?(n-=2,e+="))",this.advance()):n===1?(n--,e+=")",s=!0,this.advance()):(r--,i=!0,r>0&&(e+="))"),this.advance()):this.check(m.LPAREN)?(n++,e+="(",this.advance()):this.check(m.RPAREN)?(n>0&&n--,e+=")",this.advance()):(e+=this.current().value,this.advance())}i||this.expect(m.DPAREN_END);let a=this.parseArithmeticExpression(e.trim()),o=this.parseOptionalRedirections();return k.arithmeticCommand(a,o)}parseConditionalCommand(){this.expect(m.DBRACK_START);let e=kn(this);this.expect(m.DBRACK_END);let r=this.parseOptionalRedirections();return k.conditionalCommand(e,r)}parseFunctionDef(){let e;this.check(m.FUNCTION)?(this.advance(),e=this.expect(m.NAME,"Expected function name").value,this.check(m.LPAREN)&&(this.advance(),this.expect(m.RPAREN))):(e=this.advance().value,this.expect(m.LPAREN),this.expect(m.RPAREN)),this.skipNewlines();let r=this.parseCompoundCommandBody(),n=this.parseOptionalRedirections();return k.functionDef(e,r,n)}parseCompoundCommandBody(){if(this.check(m.LBRACE))return Nn(this);if(this.check(m.LPAREN))return Cn(this);if(this.check(m.IF))return En(this);if(this.check(m.FOR))return bn(this);if(this.check(m.WHILE))return Sn(this);if(this.check(m.UNTIL))return xn(this);if(this.check(m.CASE))return An(this);this.error("Expected compound command for function body")}parseCompoundList(){let e=[];for(this.skipNewlines();!this.check(m.EOF,m.FI,m.ELSE,m.ELIF,m.THEN,m.DO,m.DONE,m.ESAC,m.RPAREN,m.RBRACE,m.DSEMI,m.SEMI_AND,m.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let r=this.pos,n=this.parseStatement();if(n&&e.push(n),this.skipSeparators(),this.pos===r&&!n)break}return e}parseOptionalRedirections(){let e=[];for(;lr(this);){this.checkIterationLimit();let r=this.pos;if(e.push(cr(this)),this.pos===r)break}return e}parseArithmeticExpression(e){return ie(this,e)}};function qe(t){return new le().parse(t)}Y();var yt=class{fs;cwd;constructor(e,r){this.fs=e,this.cwd=r}isGlobPattern(e){return e.includes("*")||e.includes("?")||/\[.*\]/.test(e)}async expandArgs(e,r){let n=[];for(let s=0;s<e.length;s++){let i=e[s];if((r?.[s]??!1)||!this.isGlobPattern(i))n.push(i);else{let o=await this.expand(i);o.length>0?n.push(...o):n.push(i)}}return n}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}async expandSimple(e){let r=[],n=e.lastIndexOf("/"),s,i;n===-1?(s=this.cwd,i=e):(s=e.slice(0,n)||"/",i=e.slice(n+1));let a=this.fs.resolvePath(this.cwd,s);try{let o=await this.fs.readdir(a);for(let c of o)if(this.matchPattern(c,i)){let l=n===-1?c:`${s}/${c}`;r.push(l)}}catch{}return r.sort()}async expandRecursive(e){let r=[],n=e.indexOf("**"),s=e.slice(0,n).replace(/\/$/,"")||".",a=e.slice(n+2).replace(/^\//,"");return await this.walkDirectory(s,a,r),r.sort()}async walkDirectory(e,r,n){let s=this.fs.resolvePath(this.cwd,e);try{let i=await this.fs.readdir(s);for(let a of i){let o=e==="."?a:`${e}/${a}`,c=this.fs.resolvePath(this.cwd,o);try{(await this.fs.stat(c)).isDirectory?await this.walkDirectory(o,r,n):r&&this.matchPattern(a,r)&&n.push(o)}catch{}}}catch{}}matchPattern(e,r){return this.patternToRegex(r).test(e)}patternToRegex(e){let r="^";for(let n=0;n<e.length;n++){let s=e[n];if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let i=n+1,a="[";for(i<e.length&&(e[i]==="^"||e[i]==="!")&&(a+="^",i++),i<e.length&&e[i]==="]"&&(a+="\\]",i++);i<e.length&&e[i]!=="]";){if(e[i]==="["&&i+1<e.length&&e[i+1]===":"){let o=e.indexOf(":]",i+2);if(o!==-1){let c=e.slice(i+2,o),l=this.posixClassToRegex(c);a+=l,i=o+2;continue}}if(e[i]==="\\"&&i+1<e.length){a+=`\\${e[i+1]}`,i+=2;continue}e[i]==="-"?a+="\\-":a+=e[i],i++}a+="]",r+=a,n=i}else if(s==="\\"&&n+1<e.length){let i=e[n+1];/[.+^${}()|\\*?[\]]/.test(i)?r+=`\\${i}`:r+=i,n++}else/[.+^${}()|]/.test(s)?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r)}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]||""}};Y();function Ne(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return Ne(t.expression);case"ArithBinary":return Ne(t.left)||Ne(t.right);case"ArithUnary":return Ne(t.operand);case"ArithTernary":return Ne(t.condition)||Ne(t.consequent)||Ne(t.alternate);case"ArithAssignment":return Ne(t.value);case"ArithGroup":return Ne(t.expression);case"ArithArrayElement":return t.index?Ne(t.index):!1;case"ArithConcat":return t.parts.some(Ne);default:return!1}}function $n(t){let e=t.operation;return e?!!("word"in e&&e.word&&Me(e.word)||e.type==="PatternReplacement"&&(e.pattern&&Me(e.pattern)||e.replacement&&Me(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&Me(e.pattern)):!1}function ur(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return Ne(t.expression.expression);case"DoubleQuoted":return t.parts.some(ur);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&Me(e.word));case"ParameterExpansion":return $n(t);default:return!1}}function Me(t){return t.parts.some(ur)}function Rn(t){if(!t.operation)return!1;let e=t.operation,r;if((e.type==="DefaultValue"||e.type==="AssignDefault"||e.type==="UseAlternative"||e.type==="ErrorIfUnset")&&(r=e.word?.parts),!r)return!1;for(let n of r)if(n.type==="DoubleQuoted"||n.type==="SingleQuoted")return!0;return!1}function $o(t){let e=!1,r=!1,n=!1,s=!1,i=!1;for(let a of t){if((a.type==="SingleQuoted"||a.type==="DoubleQuoted")&&(e=!0,a.type==="DoubleQuoted"))for(let o of a.parts)o.type==="ParameterExpansion"&&o.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&!o.operation&&(s=!0);a.type==="CommandSubstitution"&&(r=!0),a.type==="ParameterExpansion"&&(i=!0,(a.parameter==="@"||a.parameter==="*")&&(n=!0),Rn(a)&&(e=!0))}return{hasQuoted:e,hasCommandSub:r,hasArrayVar:n,hasArrayAtExpansion:s,hasParamExpansion:i}}function zd(t,e,r,n,s){let i=r??1;i===0&&(i=1);let a=Math.abs(i),o=[],c=0;n?.match(/^-?0\d/)&&(c=Math.max(c,n.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(c=Math.max(c,s.replace(/^-/,"").length));let l=u=>{if(c>0){let f=u<0,d=String(Math.abs(u)).padStart(c,"0");return f?`-${d}`:d}return String(u)};if(t<=e)for(let u=t,f=0;u<=e&&f<1e4;u+=a,f++)o.push(l(u));else for(let u=t,f=0;u>=e&&f<1e4;u-=a,f++)o.push(l(u));return o}function Gd(t,e,r){let n=r??1;n===0&&(n=1);let s=t.charCodeAt(0),i=e.charCodeAt(0),a=Math.abs(n),o=t>="A"&&t<="Z",c=t>="a"&&t<="z",l=e>="A"&&e<="Z",u=e>="a"&&e<="z";if(o&&u||c&&l)return null;let f=[];if(s<=i)for(let d=s,h=0;d<=i&&h<1e4;d+=a,h++)f.push(String.fromCharCode(d));else for(let d=s,h=0;d>=i&&h<1e4;d-=a,h++)f.push(String.fromCharCode(d));return f}function It(t,e,r,n,s){let i=r!==void 0?`..${r}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:zd(t,e,r,n,s),literal:`{${t}..${e}${i}}`}:typeof t=="string"&&typeof e=="string"?{expanded:Gd(t,e,r),literal:`{${t}..${e}${i}}`}:{expanded:null,literal:`{${t}..${e}${i}}`}}function Ee(t,e){let r="",n=0;for(;n<t.length;){let s=t[n];if(s==="\\")if(n+1<t.length){let i=t[n+1];/[\\^$.|+(){}[\]*?]/.test(i)?r+=`\\${i}`:r+=i,n+=2}else r+="\\\\",n++;else if(s==="*")r+=e?".*":".*?",n++;else if(s==="?")r+=".",n++;else if(s==="["){let i=jd(t,n);if(i===-1)r+="\\[",n++;else{let a=t.slice(n+1,i);r+=qd(a),n=i+1}}else/[\^$.|+(){}]/.test(s)?(r+=`\\${s}`,n++):(r+=s,n++)}return r}function jd(t,e){let r=e+1;for(r<t.length&&t[r]==="^"&&r++,r<t.length&&t[r]==="]"&&r++;r<t.length;){if(t[r]==="\\"&&r+1<t.length){r+=2;continue}if(t[r]==="]")return r;if(t[r]==="'"){let n=t.indexOf("'",r+1);if(n!==-1){r=n+1;continue}}if(t[r]==="["&&r+1<t.length&&t[r+1]===":"){let n=t.indexOf(":]",r+2);if(n!==-1){r=n+2;continue}}r++}return-1}function qd(t){let e="[",r=0;for((t[0]==="^"||t[0]==="!")&&(e+="^",r++);r<t.length;){if(t[r]==="'"){let s=t.indexOf("'",r+1);if(s!==-1){let i=t.slice(r+1,s);for(let a of i)a==="\\"?e+="\\\\":a==="]"?e+="\\]":a==="^"&&e==="["?e+="\\^":e+=a;r=s+1;continue}}if(t[r]==="["&&r+1<t.length&&t[r+1]===":"){let s=t.indexOf(":]",r+2);if(s!==-1){let i=t.slice(r+2,s);e+=Zd(i),r=s+2;continue}}let n=t[r];n==="\\"?r+1<t.length?(e+=`\\${t[r+1]}`,r+=2):(e+="\\\\",r++):n==="-"&&r>0&&r<t.length-1?(e+="-",r++):n==="^"&&r===0?(e+="^",r++):(n==="]"&&r===0?e+="\\]":e+=n,r++)}return e+="]",e}var Vd={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 Zd(t){return Vd[t]??""}Y();function $t(t,e){let r=`${e}_`,n=[];for(let s of Object.keys(t.state.env))if(s.startsWith(r)){let i=s.slice(r.length),a=Number.parseInt(i,10);!Number.isNaN(a)&&String(a)===i&&n.push(a)}return n.sort((s,i)=>s-i)}function Pn(t,e){let r=`${e}_`;for(let n of Object.keys(t.state.env))n.startsWith(r)&&delete t.state.env[n]}function On(t,e){let r=`${e}_`,n=[];for(let s of Object.keys(t.state.env))if(s.startsWith(r)&&!s.includes("__")){let i=s.slice(r.length);n.push(i)}return n.sort()}function Ro(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function fr(t){return t.IFS??`
468
+ `}function Po(t){return t.IFS===""}function Rt(t){return t.split("").map(e=>/[\\^$.*+?()[\]{}|-]/.test(e)?`\\${e}`:e===" "?"\\t":e===`
469
+ `?"\\n":e).join("")}function Qd(t,e){let r=Rt(t);return new RegExp(`[${r}]+`,e)}function Kd(t){let e=Rt(t);return new RegExp(`^[${e}]+`)}function Xd(t){let e=Rt(t);return new RegExp(`[${e}]+$`)}function Pt(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function Oo(t,e){if(e==="")return{words:[t],wordStarts:[0]};let r=[],n=[],s=Qd(e,"g"),i=0,a=t.match(Kd(e));a&&(i=a[0].length),s.lastIndex=i;let o=s.exec(t);for(;o!==null;)o.index>i&&(n.push(i),r.push(t.substring(i,o.index))),i=s.lastIndex,o=s.exec(t);return i<t.length&&(n.push(i),r.push(t.substring(i))),{words:r,wordStarts:n}}function Do(t,e){return e===""?t:t.replace(Xd(e),"")}function ae(t,e){return t.state.associativeArrays?.has(e)?On(t,e).map(i=>[i,t.state.env[`${e}_${i}`]]):$t(t,e).map(s=>[s,t.state.env[`${e}_${s}`]])}function To(t,e){return t.state.associativeArrays?.has(e)?On(t,e).length>0:$t(t,e).length>0}function ve(t,e,r=!0,n=!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 a="";return t.state.options.errexit&&(a+="e"),t.state.options.nounset&&(a+="u"),t.state.options.verbose&&(a+="v"),t.state.options.xtrace&&(a+="x"),t.state.options.pipefail&&(a+="p"),a}case"*":{let a=Number.parseInt(t.state.env["#"]||"0",10);if(a===0)return"";let o=[];for(let c=1;c<=a;c++)o.push(t.state.env[String(c)]||"");return o.join(Pt(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:""}if(/^[a-zA-Z_][a-zA-Z0-9_]*\[\]$/.test(e))throw new Te(`\${${e}}`);let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let a=s[1],o=s[2];if(o==="@"||o==="*"){let f=ae(t,a);if(f.length>0)return f.map(([,h])=>h).join(" ");let d=t.state.env[a];return d!==void 0?d:""}if(t.state.associativeArrays?.has(a)){let f=Ro(o),d=t.state.env[`${a}_${f}`];if(d===void 0&&r&&t.state.options.nounset)throw new Ce(`${a}[${o}]`);return d||""}let l;if(/^-?\d+$/.test(o))l=Number.parseInt(o,10);else try{let f=new le,d=ie(f,o);l=V(t,d.expression)}catch{let f=t.state.env[o];l=f?Number.parseInt(f,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let f=ae(t,a);if(f.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${a}: bad array subscript
470
+ `,"";let h=Math.max(...f.map(([E])=>typeof E=="number"?E:0))+1+l;return h<0?(t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${a}: bad array subscript
471
+ `,""):t.state.env[`${a}_${h}`]||""}let u=t.state.env[`${a}_${l}`];if(u===void 0&&r&&t.state.options.nounset)throw new Ce(`${a}[${l}]`);return u||""}if(/^[1-9][0-9]*$/.test(e)){let a=t.state.env[e];if(a===void 0&&r&&t.state.options.nounset)throw new Ce(e);return a||""}let i=t.state.env[e];if(i===void 0&&r&&t.state.options.nounset)throw new Ce(e);return i||""}async function Lo(t,e,r,n,s){let i=[];for(let u of e){let f=u.type==="ParameterExpansion"||u.type==="CommandSubstitution"||u.type==="ArithmeticExpansion";if(u.type==="ParameterExpansion"&&Rn(u)){let d=await s(t,u);i.push({value:d,splittable:!1})}else{let d=await s(t,u);i.push({value:d,splittable:f})}}if(!i.some(u=>u.splittable&&new RegExp(`[${n}]`).test(u.value))){let u=i.map(f=>f.value).join("");return u?[u]:[]}let o=new RegExp(`[${n}]+`),c=[],l="";for(let u=0;u<i.length;u++){let f=i[u];if(!f.splittable)l+=f.value;else{let d=f.value.split(o);for(let h=0;h<d.length;h++)h===0?l+=d[h]:(l!==""&&c.push(l),l=d[h])}}return l!==""&&c.push(l),c}function be(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Fo(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function Mo(t){switch(t.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return t.value==="";default:return!1}}function Dn(t){if(t==="")return"''";if(!/['\\\n\r\t\x00-\x1f\x7f]/.test(t))return`'${t}'`;let e="$'";for(let r of t)switch(r){case"'":e+="\\'";break;case"\\":e+="\\\\";break;case`
472
+ `:e+="\\n";break;case"\r":e+="\\r";break;case" ":e+="\\t";break;default:{let n=r.charCodeAt(0);n<32||n===127?e+=`\\x${n.toString(16).padStart(2,"0")}`:e+=r}}return`${e}'`}function nt(t,e,r=!1){return e.map(n=>_e(t,n,r)).join("")}async function st(t,e,r=!1){let n=[];for(let s of e)n.push(await De(t,s));return n.join("")}function Yd(t){return Mo(t)}function _o(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!Yd(e))return!1;return!0}function Wo(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function Bo(t,e,r=!1){let n=Fo(e);if(n!==null)return n;switch(e.type){case"ParameterExpansion":return jo(t,e,r);case"TildeExpansion":return r?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 _e(t,e,r=!1){let n=Bo(t,e,r);if(n!==null)return n;switch(e.type){case"DoubleQuoted":{let s=[];for(let i of e.parts)s.push(_e(t,i,!0));return s.join("")}case"ArithmeticExpansion":return String(V(t,e.expression.expression));case"BraceExpansion":{let s=[];for(let i of e.items)if(i.type==="Range"){let a=It(i.start,i.end,i.step,i.startStr,i.endStr);if(a.expanded)s.push(...a.expanded);else return a.literal}else s.push(dr(t,i.word));return s.join(" ")}default:return""}}function dr(t,e){let r=e.parts,n=r.length;if(n===1)return _e(t,r[0]);let s=[];for(let i=0;i<n;i++)s.push(_e(t,r[i]));return s.join("")}async function X(t,e){return Me(e)?Go(t,e):dr(t,e)}function hr(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&hr(e.parts))return!0;return!1}function Jd(t){for(let e of t){if(e.type==="BraceExpansion"){for(let r of e.items)if(r.type==="Word"&&Me(r.word))return!0}if(ur(e))return!0}return!1}var Ho=1e4,gt=1e5;function Uo(t,e,r={count:0}){if(r.count>gt)return[[]];let n=[[]];for(let s of e)if(s.type==="BraceExpansion"){let i=[],a=!1,o="";for(let u of s.items)if(u.type==="Range"){let f=It(u.start,u.end,u.step,u.startStr,u.endStr);if(f.expanded)for(let d of f.expanded)r.count++,i.push(d);else{a=!0,o=f.literal;break}}else{let f=Uo(t,u.word.parts,r);for(let d of f)r.count++,i.push(d.join(""))}if(a){for(let u of n)r.count++,u.push(o);continue}if(n.length*i.length>Ho||r.count>gt)return n;let l=[];for(let u of n)for(let f of i){if(r.count++,r.count>gt)return l.length>0?l:n;l.push([...u,f])}n=l}else{let i=_e(t,s);for(let a of n)r.count++,a.push(i)}return n}function eh(t,e){let r=e.parts;return hr(r)?Uo(t,r).map(s=>s.join("")):[dr(t,e)]}async function zo(t,e,r={count:0}){if(r.count>gt)return[[]];let n=[[]];for(let s of e)if(s.type==="BraceExpansion"){let i=[],a=!1,o="";for(let u of s.items)if(u.type==="Range"){let f=It(u.start,u.end,u.step,u.startStr,u.endStr);if(f.expanded)for(let d of f.expanded)r.count++,i.push(d);else{a=!0,o=f.literal;break}}else{let f=await zo(t,u.word.parts,r);for(let d of f)r.count++,i.push(d.join(""))}if(a){for(let u of n)r.count++,u.push(o);continue}if(n.length*i.length>Ho||r.count>gt)return n;let l=[];for(let u of n)for(let f of i){if(r.count++,r.count>gt)return l.length>0?l:n;l.push([...u,f])}n=l}else{let i=await De(t,s);for(let a of n)r.count++,a.push(i)}return n}async function th(t,e){let r=e.parts;return hr(r)?(await zo(t,r)).map(s=>s.join("")):[await X(t,e)]}async function Ot(t,e){let r=e.parts,{hasQuoted:n,hasCommandSub:s,hasArrayVar:i,hasArrayAtExpansion:a,hasParamExpansion:o}=$o(r),l=hr(r)?Jd(r)?await th(t,e):eh(t,e):null;if(l&&l.length>1){let d=[];for(let h of l)if(!n&&/[*?[]/.test(h)){let E=await new yt(t.fs,t.state.cwd).expand(h);E.length>0?d.push(...E):d.push(h)}else d.push(h);return{values:d,quoted:!1}}if(a&&r.length===1&&r[0].type==="DoubleQuoted"){let d=r[0];if(d.parts.length===1&&d.parts[0].type==="ParameterExpansion"){let p=d.parts[0].parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@]\]$/);if(p){let E=p[1],w=ae(t,E);if(w.length>0)return{values:w.map(([,b])=>b),quoted:!0};let g=t.state.env[E];return g!==void 0?{values:[g],quoted:!0}:{values:[],quoted:!0}}}}if(!n&&i&&r.length===1&&r[0].type==="ParameterExpansion"){let d=r[0].parameter;if(d==="@"||d==="*"){let h=Number.parseInt(t.state.env["#"]||"0",10);if(h===0)return{values:[],quoted:!1};let p=[];for(let E=1;E<=h;E++)p.push(t.state.env[String(E)]||"");return{values:p,quoted:!1}}}if(!n&&(s||i||o)&&!Po(t.state.env)){let d=fr(t.state.env),h=Rt(d),p=await Lo(t,r,d,h,De),E=[],w=new yt(t.fs,t.state.cwd);for(let g of p)if(/[*?[]/.test(g)){let b=await w.expand(g);b.length>0?E.push(...b):E.push(g)}else E.push(g);return{values:E,quoted:!1}}let f=Me(e)?await Go(t,e):dr(t,e);if(!n&&/[*?[]/.test(f)){let h=await new yt(t.fs,t.state.cwd).expand(f);if(h.length>0)return{values:h,quoted:!1}}return f===""&&!n?{values:[],quoted:!1}:{values:[f],quoted:n}}async function Go(t,e){let r=e.parts,n=r.length;if(n===1)return De(t,r[0]);let s=[];for(let i=0;i<n;i++)s.push(await De(t,r[i]));return s.join("")}async function De(t,e){if(e.type==="ParameterExpansion"&&$n(e))return rh(t,e);let r=Bo(t,e);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let n=[];for(let s of e.parts)n.push(await De(t,s));return n.join("")}case"CommandSubstitution":try{let n=await t.executeScript(e.body);return t.state.lastExitCode=n.exitCode,t.state.env["?"]=String(n.exitCode),n.stdout.replace(/\n+$/,"")}catch(n){if(n instanceof B)throw n;if(n instanceof K)return t.state.lastExitCode=n.exitCode,t.state.env["?"]=String(n.exitCode),n.stdout.replace(/\n+$/,"");throw n}case"ArithmeticExpansion":return String(await Z(t,e.expression.expression));case"BraceExpansion":{let n=[];for(let s of e.items)if(s.type==="Range"){let i=It(s.start,s.end,s.step,s.startStr,s.endStr);if(i.expanded)n.push(...i.expanded);else return i.literal}else n.push(await X(t,s.word));return n.join(" ")}default:return""}}function jo(t,e,r=!1){let{parameter:n,operation:s}=e,i=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),a=ve(t,n,!i);if(!s)return a;let o=!(n in t.state.env),c=a==="";switch(s.type){case"DefaultValue":return(o||s.checkEmpty&&c)&&s.word?nt(t,s.word.parts,r):a;case"AssignDefault":{if((o||s.checkEmpty&&c)&&s.word){let u=nt(t,s.word.parts,r),f=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(f){let[,d,h]=f,p;if(/^\d+$/.test(h))p=Number.parseInt(h,10);else{try{let w=new le,g=ie(w,h);p=V(t,g.expression)}catch{let w=t.state.env[h];p=w?Number.parseInt(w,10):0}Number.isNaN(p)&&(p=0)}t.state.env[`${d}_${p}`]=u;let E=Number.parseInt(t.state.env[`${d}__length`]||"0",10);p>=E&&(t.state.env[`${d}__length`]=String(p+1))}else t.state.env[n]=u;return u}return a}case"ErrorIfUnset":{if(o||s.checkEmpty&&c){let u=s.word?nt(t,s.word.parts,r):`${n}: parameter null or not set`;throw new K(1,"",`bash: ${u}
473
+ `)}return a}case"UseAlternative":return!(o||s.checkEmpty&&c)&&s.word?nt(t,s.word.parts,r):"";case"Length":{let l=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l){let u=ae(t,l[1]);return String(u.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&To(t,n)){let u=t.state.env[`${n}_0`]||"";return String(u.length)}return String(a.length)}case"LengthSliceError":throw new Te(n);case"Substring":{let l=s.offset?V(t,s.offset.expression):0,u=s.length?V(t,s.length.expression):void 0;if(n==="@"||n==="*"){let p=(t.state.env["@"]||"").split(" ").filter(b=>b),E=t.state.env[0]||"bash",w=l===0?[E,...p]:p,g=l===0?0:l-1;if(g<0||g>=w.length)return"";if(u!==void 0){let b=u<0?w.length+u:g+u;return w.slice(g,Math.max(g,b)).join(" ")}return w.slice(g).join(" ")}let f=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(f){let E=ae(t,f[1]).map(([,g])=>g),w=l;if(w<0&&(w=E.length+w,w<0))return"";if(u!==void 0){if(u<0){let g=E.length+u;return E.slice(w,Math.max(w,g)).join(" ")}return E.slice(w,w+u).join(" ")}return E.slice(w).join(" ")}let d=[...a],h=l;if(h<0&&(h=Math.max(0,d.length+h)),u!==void 0){if(u<0){let p=d.length+u;return d.slice(h,Math.max(h,p)).join("")}return d.slice(h,h+u).join("")}return d.slice(h).join("")}case"PatternRemoval":{let l="";if(s.pattern)for(let f of s.pattern.parts)if(f.type==="Glob")l+=Ee(f.pattern,s.greedy);else if(f.type==="Literal")l+=Ee(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")l+=be(f.value);else if(f.type==="DoubleQuoted"){let d=nt(t,f.parts);l+=be(d)}else if(f.type==="ParameterExpansion"){let d=_e(t,f);l+=Ee(d,s.greedy)}else{let d=_e(t,f);l+=be(d)}if(s.side==="prefix")return a.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return a.replace(u,"");for(let f=a.length;f>=0;f--){let d=a.slice(f);if(u.test(d))return a.slice(0,f)}return a}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=Ee(d.pattern,!0);else if(d.type==="Literal")l+=Ee(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=be(d.value);else if(d.type==="DoubleQuoted"){let h=nt(t,d.parts);l+=be(h)}else if(d.type==="ParameterExpansion"){let h=_e(t,d);l+=Ee(h,!0)}else{let h=_e(t,d);l+=be(h)}let u=s.replacement?nt(t,s.replacement.parts):"";if(l==="")return a;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let f=s.all?"g":"";try{let d=new RegExp(l,f);if(s.all){let h="",p=0,E=d.exec(a);for(;E!==null&&!(E[0].length===0&&E.index===a.length);)h+=a.slice(p,E.index)+u,p=E.index+E[0].length,E[0].length===0&&p++,E=d.exec(a);return h+=a.slice(p),h}return a.replace(d,u)}catch{return a}}case"CaseModification":return s.direction==="upper"?s.all?a.toUpperCase():a.charAt(0).toUpperCase()+a.slice(1):s.all?a.toLowerCase():a.charAt(0).toLowerCase()+a.slice(1);case"Transform":{let l=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l&&s.operator==="Q")return ae(t,l[1]).map(([,d])=>Dn(d)).join(" ");switch(s.operator){case"Q":return Dn(a);case"P":return a;case"a":return"";case"A":return`${n}=${Dn(a)}`;case"E":return a.replace(/\\([\\abefnrtv'"?])/g,(u,f)=>{switch(f){case"\\":return"\\";case"a":return"\x07";case"b":return"\b";case"e":return"\x1B";case"f":return"\f";case"n":return`
474
+ `;case"r":return"\r";case"t":return" ";case"v":return"\v";case"'":return"'";case'"':return'"';case"?":return"?";default:return f}});case"K":return"";default:return a}}case"Indirection":return ve(t,a);case"ArrayKeys":{let u=ae(t,s.array).map(([f])=>String(f));return s.star?u.join(Pt(t.state.env)):u.join(" ")}case"VarNamePrefix":{let l=Object.keys(t.state.env).filter(u=>u.startsWith(s.prefix)&&!u.includes("__")).sort();return s.star?l.join(Pt(t.state.env)):l.join(" ")}default:return a}}async function rh(t,e,r=!1){let{parameter:n,operation:s}=e,i=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),a=ve(t,n,!i);if(!s)return a;let o=!(n in t.state.env),c=a==="";switch(s.type){case"DefaultValue":return(o||s.checkEmpty&&c)&&s.word?st(t,s.word.parts,r):a;case"AssignDefault":{if((o||s.checkEmpty&&c)&&s.word){let u=await st(t,s.word.parts,r),f=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(f){let[,d,h]=f,p;if(/^\d+$/.test(h))p=Number.parseInt(h,10);else{try{let w=new le,g=ie(w,h);p=await Z(t,g.expression)}catch{let w=t.state.env[h];p=w?Number.parseInt(w,10):0}Number.isNaN(p)&&(p=0)}t.state.env[`${d}_${p}`]=u;let E=Number.parseInt(t.state.env[`${d}__length`]||"0",10);p>=E&&(t.state.env[`${d}__length`]=String(p+1))}else t.state.env[n]=u;return u}return a}case"ErrorIfUnset":{if(o||s.checkEmpty&&c){let u=s.word?await st(t,s.word.parts,r):`${n}: parameter null or not set`;throw new K(1,"",`bash: ${u}
475
+ `)}return a}case"UseAlternative":return!(o||s.checkEmpty&&c)&&s.word?st(t,s.word.parts,r):"";case"PatternRemoval":{let l="";if(s.pattern)for(let f of s.pattern.parts)if(f.type==="Glob")l+=Ee(f.pattern,s.greedy);else if(f.type==="Literal")l+=Ee(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")l+=be(f.value);else if(f.type==="DoubleQuoted"){let d=await st(t,f.parts);l+=be(d)}else if(f.type==="ParameterExpansion"){let d=await De(t,f);l+=Ee(d,s.greedy)}else{let d=await De(t,f);l+=be(d)}if(s.side==="prefix")return a.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return a.replace(u,"");for(let f=a.length;f>=0;f--){let d=a.slice(f);if(u.test(d))return a.slice(0,f)}return a}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=Ee(d.pattern,!0);else if(d.type==="Literal")l+=Ee(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=be(d.value);else if(d.type==="DoubleQuoted"){let h=await st(t,d.parts);l+=be(h)}else if(d.type==="ParameterExpansion"){let h=await De(t,d);l+=Ee(h,!0)}else{let h=await De(t,d);l+=be(h)}let u=s.replacement?await st(t,s.replacement.parts):"";if(l==="")return a;s.anchor==="start"?l=`^${l}`:s.anchor==="end"&&(l=`${l}$`);let f=s.all?"g":"";try{let d=new RegExp(l,f);if(s.all){let h="",p=0,E=d.exec(a);for(;E!==null&&!(E[0].length===0&&E.index===a.length);)h+=a.slice(p,E.index)+u,p=E.index+E[0].length,E[0].length===0&&p++,E=d.exec(a);return h+=a.slice(p),h}return a.replace(d,u)}catch{return a}}default:return jo(t,e,r)}}function Tn(t,e,r){switch(r){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 ne("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 qo(t,e,r){switch(r){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 Ln(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function nh(t,e){let r=t.state.env[e];if(r!==void 0)return r;let n=t.state.env[`${e}_0`];return n!==void 0?n:ve(t,e)}function wt(t){if(!t)return 0;let e=Number.parseInt(t,10);if(!Number.isNaN(e)&&/^-?\d+$/.test(t.trim()))return e;let r=t.trim();if(!r)return 0;try{let n=new le,{expr:s,pos:i}=Le(n,r,0);if(i<r.length){let a=r.slice(i).trim().split(/\s+/)[0];throw new ne(`${r}: syntax error in expression (error token is "${a}")`)}return s.type==="ArithNumber"?s.value:e||0}catch(n){if(n instanceof ne)throw n;let s=r.split(/\s+/).slice(1)[0]||r;throw new ne(`${r}: syntax error in expression (error token is "${s}")`)}}function pr(t,e,r=new Set){if(r.has(e))return 0;r.add(e);let n=nh(t,e);if(!n)return 0;let s=Number.parseInt(n,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(n.trim()))return s;let i=n.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return pr(t,i,r);try{let a=new le,{expr:o}=Le(a,i,0);return ke(t,o,r)}catch{return 0}}function ke(t,e,r){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new ne("value too great for base");return e.value;case"ArithVariable":return pr(t,e.name,r);case"ArithBinary":{if(e.operator==="||")return ke(t,e.left,r)||ke(t,e.right,r)?1:0;if(e.operator==="&&")return ke(t,e.left,r)&&ke(t,e.right,r)?1:0;let n=ke(t,e.left,r),s=ke(t,e.right,r);return Tn(n,s,e.operator)}case"ArithUnary":{let n=ke(t,e.operand,r);return Ln(n,e.operator)}case"ArithTernary":return ke(t,e.condition,r)?ke(t,e.consequent,r):ke(t,e.alternate,r);case"ArithGroup":return ke(t,e.expression,r);default:return V(t,e)}}function Ve(t,e){if(e.startsWith("#")){let f=e.slice(1),d=t.state.env[f]||"";return String(d.length)}if(e.startsWith("!")){let f=e.slice(1),d=t.state.env[f]||"";return t.state.env[d]||""}let r=[":-",":=",":?",":+","-","=","?","+"],n=-1,s="";for(let f of r){let d=e.indexOf(f);d>0&&(n===-1||d<n)&&(n=d,s=f)}if(n===-1)return ve(t,e);let i=e.slice(0,n),a=e.slice(n+s.length),o=t.state.env[i],c=o===void 0,l=o==="",u=s.startsWith(":");switch(s){case":-":case"-":return c||u&&l?a:o||"";case":=":case"=":return c||u&&l?(t.state.env[i]=a,a):o||"";case":+":case"+":return!(c||u&&l)?a:"";case":?":case"?":{if(c||u&&l)throw new Error(a||`${i}: parameter null or not set`);return o||""}default:return o||""}}function V(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new ne("value too great for base");return e.value;case"ArithVariable":return pr(t,e.name);case"ArithNested":return V(t,e.expression);case"ArithCommandSubst":return 0;case"ArithBracedExpansion":{let r=Ve(t,e.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=Ve(t,e.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)return 0;let s=`${n}#${e.value}`;return mt(s)}case"ArithDynamicNumber":{let n=Ve(t,e.prefix)+e.suffix;return mt(n)}case"ArithArrayElement":{let r=t.state.associativeArrays?.has(e.array),n;if(e.stringKey!==void 0)n=`${e.array}_${e.stringKey}`;else if(r&&e.index?.type==="ArithVariable")n=`${e.array}_${e.index.name}`;else if(e.index){let i=V(t,e.index);if(i<0){let o=ae(t,e.array);if(o.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
476
476
  `,0;let l=Math.max(...o.map(([u])=>typeof u=="number"?u:0))+1+i;if(l<0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
477
- `,0;i=l}n=`${e.array}_${i}`;let a=t.state.env[n];if(a!==void 0)return mt(a);if(i===0){let o=t.state.env[e.array];if(o!==void 0)return mt(o)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new Se(`${e.array}[${i}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?mt(s):0}case"ArithDoubleSubscript":throw new te("double subscript","","");case"ArithNumberSubscript":throw new te(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return j(t,e.left)||j(t,e.right)?1:0;if(e.operator==="&&")return j(t,e.left)&&j(t,e.right)?1:0;let r=j(t,e.left),n=j(t,e.right);return Pn(r,n,e.operator)}case"ArithUnary":{let r=j(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let n=e.operand.name,s=Number.parseInt(Ce(t,n),10)||0,i=e.operator==="++"?s+1:s-1;return t.state.env[n]=String(i),e.prefix?i:s}if(e.operand.type==="ArithArrayElement"){let n=e.operand.array,s=t.state.associativeArrays?.has(n),i;if(e.operand.stringKey!==void 0)i=`${n}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")i=`${n}_${e.operand.index.name}`;else if(e.operand.index){let c=j(t,e.operand.index);i=`${n}_${c}`}else return r;let a=Number.parseInt(t.state.env[i]||"0",10)||0,o=e.operator==="++"?a+1:a-1;return t.state.env[i]=String(o),e.prefix?o:a}return r}return On(r,e.operator)}case"ArithTernary":return j(t,e.condition)?j(t,e.consequent):j(t,e.alternate);case"ArithAssignment":{let r=e.variable,n=r;if(e.stringKey!==void 0)n=`${r}_${e.stringKey}`;else if(e.subscript){let o=t.state.associativeArrays?.has(r);if(o&&e.subscript.type==="ArithVariable")n=`${r}_${e.subscript.name}`;else if(o){let c=j(t,e.subscript);n=`${r}_${c}`}else{let c=j(t,e.subscript);if(c<0){let l=ie(t,r);l.length>0&&(c=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+c)}n=`${r}_${c}`}}let s=Number.parseInt(t.state.env[n]||"0",10)||0,i=j(t,e.value),a=Uo(s,i,e.operator);return t.state.env[n]=String(a),a}case"ArithGroup":return j(t,e.expression);case"ArithConcat":{let r="";for(let n of e.parts)r+=zo(t,n);return Number.parseInt(r,10)||0}default:return 0}}function zo(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return Ce(t,e.name);case"ArithBracedExpansion":return je(t,e.content);case"ArithCommandSubst":return"0";case"ArithConcat":{let r="";for(let n of e.parts)r+=zo(t,n);return r}default:return String(j(t,e))}}async function q(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new te("value too great for base");return e.value;case"ArithVariable":return ur(t,e.name);case"ArithNested":return q(t,e.expression);case"ArithCommandSubst":{if(t.execFn){let n=(await t.execFn(e.command)).stdout.trim();return Number.parseInt(n,10)||0}return 0}case"ArithBracedExpansion":{let r=je(t,e.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=je(t,e.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)return 0;let s=`${n}#${e.value}`;return dt(s)}case"ArithDynamicNumber":{let n=je(t,e.prefix)+e.suffix;return dt(n)}case"ArithArrayElement":{let r=t.state.associativeArrays?.has(e.array),n;if(e.stringKey!==void 0)n=`${e.array}_${e.stringKey}`;else if(r&&e.index?.type==="ArithVariable")n=`${e.array}_${e.index.name}`;else if(e.index){let i=await q(t,e.index);n=`${e.array}_${i}`;let a=t.state.env[n];if(a!==void 0)return mt(a);if(i===0){let o=t.state.env[e.array];if(o!==void 0)return mt(o)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new Se(`${e.array}[${i}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?mt(s):0}case"ArithDoubleSubscript":throw new te("double subscript","","");case"ArithNumberSubscript":throw new te(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return await q(t,e.left)||await q(t,e.right)?1:0;if(e.operator==="&&")return await q(t,e.left)&&await q(t,e.right)?1:0;let r=await q(t,e.left),n=await q(t,e.right);return Pn(r,n,e.operator)}case"ArithUnary":{let r=await q(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let n=e.operand.name,s=Number.parseInt(Ce(t,n),10)||0,i=e.operator==="++"?s+1:s-1;return t.state.env[n]=String(i),e.prefix?i:s}if(e.operand.type==="ArithArrayElement"){let n=e.operand.array,s=t.state.associativeArrays?.has(n),i;if(e.operand.stringKey!==void 0)i=`${n}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")i=`${n}_${e.operand.index.name}`;else if(e.operand.index){let c=await q(t,e.operand.index);i=`${n}_${c}`}else return r;let a=Number.parseInt(t.state.env[i]||"0",10)||0,o=e.operator==="++"?a+1:a-1;return t.state.env[i]=String(o),e.prefix?o:a}return r}return On(r,e.operator)}case"ArithTernary":return await q(t,e.condition)?await q(t,e.consequent):await q(t,e.alternate);case"ArithAssignment":{let r=e.variable,n=r;if(e.stringKey!==void 0)n=`${r}_${e.stringKey}`;else if(e.subscript){let o=t.state.associativeArrays?.has(r);if(o&&e.subscript.type==="ArithVariable")n=`${r}_${e.subscript.name}`;else if(o){let c=await q(t,e.subscript);n=`${r}_${c}`}else{let c=await q(t,e.subscript);if(c<0){let l=ie(t,r);l.length>0&&(c=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+c)}n=`${r}_${c}`}}let s=Number.parseInt(t.state.env[n]||"0",10)||0,i=await q(t,e.value),a=Uo(s,i,e.operator);return t.state.env[n]=String(a),a}case"ArithGroup":return await q(t,e.expression);case"ArithConcat":{let r="";for(let n of e.parts)r+=await Go(t,n);return Number.parseInt(r,10)||0}default:return 0}}async function Go(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return Ce(t,e.name);case"ArithBracedExpansion":return je(t,e.content);case"ArithCommandSubst":return t.execFn?(await t.execFn(e.command)).stdout.trim():"0";case"ArithConcat":{let r="";for(let n of e.parts)r+=await Go(t,n);return r}default:return String(await q(t,e))}}X();X();var G=Object.freeze({stdout:"",stderr:"",exitCode:0});function we(t=""){return{stdout:t,stderr:"",exitCode:0}}function F(t,e=1){return{stdout:"",stderr:t,exitCode:e}}function $(t,e,r){return{stdout:t,stderr:e,exitCode:r}}function re(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function _e(t,e,r="",n=""){throw new W(t,e,r,n)}function Dn(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new $e;return G}let r=1;if(e.length>0){let n=Number.parseInt(e[0],10);if(Number.isNaN(n)||n<1)throw new Z(128,"",`bash: break: ${e[0]}: numeric argument required
478
- `);r=n}throw new ce(r)}async function Ln(t,e){let r,n=!1,s=!1,i=0;for(;i<e.length;)if(e[i]==="--"){i++;break}else if(e[i]==="-L")s=!1,i++;else if(e[i]==="-P")s=!0,i++;else if(e[i].startsWith("-")&&e[i]!=="-")i++;else break;let a=e.slice(i);if(a.length===0||a[0]==="~"?r=t.state.env.HOME||"/":a[0]==="-"?(r=t.state.previousDir,n=!0):r=a[0],!r.startsWith("/")&&!r.startsWith("./")&&!r.startsWith("../")&&r!=="."&&r!==".."){let f=t.state.env.CDPATH;if(f){let d=f.split(":").filter(h=>h);for(let h of d){let p=h.startsWith("/")?`${h}/${r}`:`${t.state.cwd}/${h}/${r}`;try{if((await t.fs.stat(p)).isDirectory){r=p,n=!0;break}}catch{}}}}let c=(r.startsWith("/")?r:`${t.state.cwd}/${r}`).split("/").filter(f=>f&&f!=="."),l="";for(let f of c)if(f==="..")l=l.split("/").slice(0,-1).join("/")||"/";else{l=l?`${l}/${f}`:`/${f}`;try{if(!(await t.fs.stat(l)).isDirectory)return F(`bash: cd: ${r}: Not a directory
479
- `)}catch{return F(`bash: cd: ${r}: No such file or directory
480
- `)}}let u=l||"/";return t.state.previousDir=t.state.cwd,t.state.cwd=u,t.state.env.PWD=t.state.cwd,t.state.env.OLDPWD=t.state.previousDir,we(n?`${u}
481
- `:"")}X();function Tn(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new $e;return G}if(e.length>1)throw new ce(1);let r=1;if(e.length>0){let n=Number.parseInt(e[0],10);if(Number.isNaN(n)||n<1)return F(`bash: continue: ${e[0]}: numeric argument required
482
- `);r=n}throw new pe(r)}function st(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function Xd(t,e){return t.state.readonlyVars?.has(e)??!1}function qe(t,e,r="bash"){return Xd(t,e)?F(`${r}: ${e}: readonly variable
483
- `):null}function jo(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(e)return{name:e[1],isArray:!0,arrayElements:Fn(e[2])};if(t.includes("=")){let r=t.indexOf("=");return{name:t.slice(0,r),isArray:!1,value:t.slice(r+1)}}return{name:t,isArray:!1}}function qo(t,e,r={}){let{name:n,isArray:s,arrayElements:i,value:a}=e,{makeReadonly:o=!1,checkReadonly:c=!0}=r;if(c){let l=qe(t,n);if(l)return l}if(s&&i){for(let l=0;l<i.length;l++)t.state.env[`${n}_${l}`]=i[l];t.state.env[`${n}__length`]=String(i.length)}else a!==void 0&&(t.state.env[n]=a);return o&&st(t,n),null}function Mn(t,e){let r=!1,n=!1,s=!1,i=!1,a=!1,o=[];for(let c=0;c<e.length;c++){let l=e[c];if(l==="-a")r=!0;else if(l==="-A")n=!0;else if(l==="-r")s=!0;else if(l==="-x")i=!0;else if(l==="-p")a=!0;else if(l==="--"){o.push(...e.slice(c+1));break}else if(l.startsWith("-"))for(let u of l.slice(1))u==="a"?r=!0:u==="A"?n=!0:u==="r"?s=!0:u==="x"?i=!0:u==="p"&&(a=!0);else o.push(l)}if(a&&o.length>0){let c="";for(let l of o){let u=t.state.env[l];if(u!==void 0){let f=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');c+=`declare -- ${l}="${f}"
484
- `}}return we(c)}if(o.length===0&&!a){let c="",l=Object.entries(t.state.env).filter(([u])=>!u.startsWith("BASH_")).sort(([u],[f])=>u.localeCompare(f));for(let[u,f]of l){let d=f.replace(/'/g,"'\\''");c+=`declare -- ${u}='${d}'
485
- `}return we(c)}for(let c of o){let l=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(l){let u=l[1],f=l[2];if(n&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(u)),n&&f.includes("[")){let d=Yd(f);for(let[h,p]of d)t.state.env[`${u}_${h}`]=p}else{let d=Fn(f);for(let h=0;h<d.length;h++)t.state.env[`${u}_${h}`]=d[h];t.state.env[`${u}__length`]=String(d.length)}s&&st(t,u);continue}if(c.includes("=")){let u=c.indexOf("="),f=c.slice(0,u),d=c.slice(u+1),h=qe(t,f);if(h)return h;t.state.env[f]=d,s&&st(t,f)}else{let u=c;n&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(u));let f=Object.keys(t.state.env).some(d=>d.startsWith(`${u}_`)&&!d.startsWith(`${u}__length`));!(u in t.state.env)&&!f&&(r||n?t.state.env[`${u}__length`]="0":t.state.env[u]=""),s&&st(t,u)}}return G}function Fn(t){let e=[],r="",n=!1,s=!1,i=!1;for(let a of t){if(i){r+=a,i=!1;continue}if(a==="\\"){i=!0;continue}if(a==="'"&&!s){n=!n;continue}if(a==='"'&&!n){s=!s;continue}if((a===" "||a===" "||a===`
486
- `)&&!n&&!s){r&&(e.push(r),r="");continue}r+=a}return r&&e.push(r),e}function Yd(t){let e=[],r=0;for(;r<t.length;){for(;r<t.length&&/\s/.test(t[r]);)r++;if(r>=t.length)break;if(t[r]!=="["){r++;continue}r++;let n="";if(t[r]==="'"||t[r]==='"'){let i=t[r];for(r++;r<t.length&&t[r]!==i;)n+=t[r],r++;t[r]===i&&r++}else for(;r<t.length&&t[r]!=="]"&&t[r]!=="=";)n+=t[r],r++;for(;r<t.length&&t[r]!=="]";)r++;if(t[r]==="]"&&r++,t[r]!=="=")continue;r++;let s="";if(t[r]==="'"||t[r]==='"'){let i=t[r];for(r++;r<t.length&&t[r]!==i;)t[r]==="\\"&&r+1<t.length&&r++,s+=t[r],r++;t[r]===i&&r++}else for(;r<t.length&&!/\s/.test(t[r]);)s+=t[r],r++;e.push([n,s])}return e}function _n(t,e){let r=!1,n=!1,s=[];for(let i=0;i<e.length;i++){let a=e[i];if(a==="-a")r=!0;else if(a==="-A")n=!0;else if(a==="-p"){if(e.length===1){let o="";for(let c of t.state.readonlyVars||[]){let l=t.state.env[c];l!==void 0&&(o+=`declare -r ${c}="${l}"
487
- `)}return we(o)}}else if(a==="--"){s.push(...e.slice(i+1));break}else a.startsWith("-")||s.push(a)}for(let i of s){let a=jo(i);if(a.value===void 0&&!a.isArray){st(t,a.name);continue}let o=qo(t,a,{makeReadonly:!0});if(o)return o}return G}X();async function Wn(t,e){let r=e;if(r.length>0){let s=r[0];if(s==="--")r=r.slice(1);else if(s.startsWith("-")&&s!=="-"&&s.length>1)return F(`bash: eval: ${s}: invalid option
477
+ `,0;i=l}n=`${e.array}_${i}`;let a=t.state.env[n];if(a!==void 0)return wt(a);if(i===0){let o=t.state.env[e.array];if(o!==void 0)return wt(o)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new Ce(`${e.array}[${i}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?wt(s):0}case"ArithDoubleSubscript":throw new ne("double subscript","","");case"ArithNumberSubscript":throw new ne(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return V(t,e.left)||V(t,e.right)?1:0;if(e.operator==="&&")return V(t,e.left)&&V(t,e.right)?1:0;let r=V(t,e.left),n=V(t,e.right);return Tn(r,n,e.operator)}case"ArithUnary":{let r=V(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let n=e.operand.name,s=Number.parseInt(ve(t,n),10)||0,i=e.operator==="++"?s+1:s-1;return t.state.env[n]=String(i),e.prefix?i:s}if(e.operand.type==="ArithArrayElement"){let n=e.operand.array,s=t.state.associativeArrays?.has(n),i;if(e.operand.stringKey!==void 0)i=`${n}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")i=`${n}_${e.operand.index.name}`;else if(e.operand.index){let c=V(t,e.operand.index);i=`${n}_${c}`}else return r;let a=Number.parseInt(t.state.env[i]||"0",10)||0,o=e.operator==="++"?a+1:a-1;return t.state.env[i]=String(o),e.prefix?o:a}return r}return Ln(r,e.operator)}case"ArithTernary":return V(t,e.condition)?V(t,e.consequent):V(t,e.alternate);case"ArithAssignment":{let r=e.variable,n=r;if(e.stringKey!==void 0)n=`${r}_${e.stringKey}`;else if(e.subscript){let o=t.state.associativeArrays?.has(r);if(o&&e.subscript.type==="ArithVariable")n=`${r}_${e.subscript.name}`;else if(o){let c=V(t,e.subscript);n=`${r}_${c}`}else{let c=V(t,e.subscript);if(c<0){let l=ae(t,r);l.length>0&&(c=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+c)}n=`${r}_${c}`}}let s=Number.parseInt(t.state.env[n]||"0",10)||0,i=V(t,e.value),a=qo(s,i,e.operator);return t.state.env[n]=String(a),a}case"ArithGroup":return V(t,e.expression);case"ArithConcat":{let r="";for(let n of e.parts)r+=Vo(t,n);return Number.parseInt(r,10)||0}default:return 0}}function Vo(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return ve(t,e.name);case"ArithBracedExpansion":return Ve(t,e.content);case"ArithCommandSubst":return"0";case"ArithConcat":{let r="";for(let n of e.parts)r+=Vo(t,n);return r}default:return String(V(t,e))}}async function Z(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new ne("value too great for base");return e.value;case"ArithVariable":return pr(t,e.name);case"ArithNested":return Z(t,e.expression);case"ArithCommandSubst":{if(t.execFn){let n=(await t.execFn(e.command)).stdout.trim();return Number.parseInt(n,10)||0}return 0}case"ArithBracedExpansion":{let r=Ve(t,e.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=Ve(t,e.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)return 0;let s=`${n}#${e.value}`;return mt(s)}case"ArithDynamicNumber":{let n=Ve(t,e.prefix)+e.suffix;return mt(n)}case"ArithArrayElement":{let r=t.state.associativeArrays?.has(e.array),n;if(e.stringKey!==void 0)n=`${e.array}_${e.stringKey}`;else if(r&&e.index?.type==="ArithVariable")n=`${e.array}_${e.index.name}`;else if(e.index){let i=await Z(t,e.index);n=`${e.array}_${i}`;let a=t.state.env[n];if(a!==void 0)return wt(a);if(i===0){let o=t.state.env[e.array];if(o!==void 0)return wt(o)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new Ce(`${e.array}[${i}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?wt(s):0}case"ArithDoubleSubscript":throw new ne("double subscript","","");case"ArithNumberSubscript":throw new ne(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return await Z(t,e.left)||await Z(t,e.right)?1:0;if(e.operator==="&&")return await Z(t,e.left)&&await Z(t,e.right)?1:0;let r=await Z(t,e.left),n=await Z(t,e.right);return Tn(r,n,e.operator)}case"ArithUnary":{let r=await Z(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let n=e.operand.name,s=Number.parseInt(ve(t,n),10)||0,i=e.operator==="++"?s+1:s-1;return t.state.env[n]=String(i),e.prefix?i:s}if(e.operand.type==="ArithArrayElement"){let n=e.operand.array,s=t.state.associativeArrays?.has(n),i;if(e.operand.stringKey!==void 0)i=`${n}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")i=`${n}_${e.operand.index.name}`;else if(e.operand.index){let c=await Z(t,e.operand.index);i=`${n}_${c}`}else return r;let a=Number.parseInt(t.state.env[i]||"0",10)||0,o=e.operator==="++"?a+1:a-1;return t.state.env[i]=String(o),e.prefix?o:a}return r}return Ln(r,e.operator)}case"ArithTernary":return await Z(t,e.condition)?await Z(t,e.consequent):await Z(t,e.alternate);case"ArithAssignment":{let r=e.variable,n=r;if(e.stringKey!==void 0)n=`${r}_${e.stringKey}`;else if(e.subscript){let o=t.state.associativeArrays?.has(r);if(o&&e.subscript.type==="ArithVariable")n=`${r}_${e.subscript.name}`;else if(o){let c=await Z(t,e.subscript);n=`${r}_${c}`}else{let c=await Z(t,e.subscript);if(c<0){let l=ae(t,r);l.length>0&&(c=Math.max(...l.map(([f])=>typeof f=="number"?f:0))+1+c)}n=`${r}_${c}`}}let s=Number.parseInt(t.state.env[n]||"0",10)||0,i=await Z(t,e.value),a=qo(s,i,e.operator);return t.state.env[n]=String(a),a}case"ArithGroup":return await Z(t,e.expression);case"ArithConcat":{let r="";for(let n of e.parts)r+=await Zo(t,n);return Number.parseInt(r,10)||0}default:return 0}}async function Zo(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return ve(t,e.name);case"ArithBracedExpansion":return Ve(t,e.content);case"ArithCommandSubst":return t.execFn?(await t.execFn(e.command)).stdout.trim():"0";case"ArithConcat":{let r="";for(let n of e.parts)r+=await Zo(t,n);return r}default:return String(await Z(t,e))}}Y();Y();var q=Object.freeze({stdout:"",stderr:"",exitCode:0});function Se(t=""){return{stdout:t,stderr:"",exitCode:0}}function _(t,e=1){return{stdout:"",stderr:t,exitCode:e}}function $(t,e,r){return{stdout:t,stderr:e,exitCode:r}}function se(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function We(t,e,r="",n=""){throw new B(t,e,r,n)}function Fn(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new Oe;return q}let r=1;if(e.length>0){let n=Number.parseInt(e[0],10);if(Number.isNaN(n)||n<1)throw new K(128,"",`bash: break: ${e[0]}: numeric argument required
478
+ `);r=n}throw new ue(r)}async function Mn(t,e){let r,n=!1,s=!1,i=0;for(;i<e.length;)if(e[i]==="--"){i++;break}else if(e[i]==="-L")s=!1,i++;else if(e[i]==="-P")s=!0,i++;else if(e[i].startsWith("-")&&e[i]!=="-")i++;else break;let a=e.slice(i);if(a.length===0||a[0]==="~"?r=t.state.env.HOME||"/":a[0]==="-"?(r=t.state.previousDir,n=!0):r=a[0],!r.startsWith("/")&&!r.startsWith("./")&&!r.startsWith("../")&&r!=="."&&r!==".."){let f=t.state.env.CDPATH;if(f){let d=f.split(":").filter(h=>h);for(let h of d){let p=h.startsWith("/")?`${h}/${r}`:`${t.state.cwd}/${h}/${r}`;try{if((await t.fs.stat(p)).isDirectory){r=p,n=!0;break}}catch{}}}}let c=(r.startsWith("/")?r:`${t.state.cwd}/${r}`).split("/").filter(f=>f&&f!=="."),l="";for(let f of c)if(f==="..")l=l.split("/").slice(0,-1).join("/")||"/";else{l=l?`${l}/${f}`:`/${f}`;try{if(!(await t.fs.stat(l)).isDirectory)return _(`bash: cd: ${r}: Not a directory
479
+ `)}catch{return _(`bash: cd: ${r}: No such file or directory
480
+ `)}}let u=l||"/";return t.state.previousDir=t.state.cwd,t.state.cwd=u,t.state.env.PWD=t.state.cwd,t.state.env.OLDPWD=t.state.previousDir,Se(n?`${u}
481
+ `:"")}Y();function _n(t,e){if(t.state.loopDepth===0){if(t.state.parentHasLoopContext)throw new Oe;return q}if(e.length>1)throw new ue(1);let r=1;if(e.length>0){let n=Number.parseInt(e[0],10);if(Number.isNaN(n)||n<1)return _(`bash: continue: ${e[0]}: numeric argument required
482
+ `);r=n}throw new ye(r)}function it(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function sh(t,e){return t.state.readonlyVars?.has(e)??!1}function Ze(t,e,r="bash"){return sh(t,e)?_(`${r}: ${e}: readonly variable
483
+ `):null}function Qo(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(e)return{name:e[1],isArray:!0,arrayElements:Wn(e[2])};if(t.includes("=")){let r=t.indexOf("=");return{name:t.slice(0,r),isArray:!1,value:t.slice(r+1)}}return{name:t,isArray:!1}}function Ko(t,e,r={}){let{name:n,isArray:s,arrayElements:i,value:a}=e,{makeReadonly:o=!1,checkReadonly:c=!0}=r;if(c){let l=Ze(t,n);if(l)return l}if(s&&i){for(let l=0;l<i.length;l++)t.state.env[`${n}_${l}`]=i[l];t.state.env[`${n}__length`]=String(i.length)}else a!==void 0&&(t.state.env[n]=a);return o&&it(t,n),null}function Bn(t,e){let r=!1,n=!1,s=!1,i=!1,a=!1,o=[];for(let c=0;c<e.length;c++){let l=e[c];if(l==="-a")r=!0;else if(l==="-A")n=!0;else if(l==="-r")s=!0;else if(l==="-x")i=!0;else if(l==="-p")a=!0;else if(l==="--"){o.push(...e.slice(c+1));break}else if(l.startsWith("-"))for(let u of l.slice(1))u==="a"?r=!0:u==="A"?n=!0:u==="r"?s=!0:u==="x"?i=!0:u==="p"&&(a=!0);else o.push(l)}if(a&&o.length>0){let c="";for(let l of o){let u=t.state.env[l];if(u!==void 0){let f=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');c+=`declare -- ${l}="${f}"
484
+ `}}return Se(c)}if(o.length===0&&!a){let c="",l=Object.entries(t.state.env).filter(([u])=>!u.startsWith("BASH_")).sort(([u],[f])=>u.localeCompare(f));for(let[u,f]of l){let d=f.replace(/'/g,"'\\''");c+=`declare -- ${u}='${d}'
485
+ `}return Se(c)}for(let c of o){let l=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(l){let u=l[1],f=l[2];if(n&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(u)),n&&f.includes("[")){let d=ih(f);for(let[h,p]of d)t.state.env[`${u}_${h}`]=p}else{let d=Wn(f);for(let h=0;h<d.length;h++)t.state.env[`${u}_${h}`]=d[h];t.state.env[`${u}__length`]=String(d.length)}s&&it(t,u);continue}if(c.includes("=")){let u=c.indexOf("="),f=c.slice(0,u),d=c.slice(u+1),h=Ze(t,f);if(h)return h;t.state.env[f]=d,s&&it(t,f)}else{let u=c;n&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(u));let f=Object.keys(t.state.env).some(d=>d.startsWith(`${u}_`)&&!d.startsWith(`${u}__length`));!(u in t.state.env)&&!f&&(r||n?t.state.env[`${u}__length`]="0":t.state.env[u]=""),s&&it(t,u)}}return q}function Wn(t){let e=[],r="",n=!1,s=!1,i=!1;for(let a of t){if(i){r+=a,i=!1;continue}if(a==="\\"){i=!0;continue}if(a==="'"&&!s){n=!n;continue}if(a==='"'&&!n){s=!s;continue}if((a===" "||a===" "||a===`
486
+ `)&&!n&&!s){r&&(e.push(r),r="");continue}r+=a}return r&&e.push(r),e}function ih(t){let e=[],r=0;for(;r<t.length;){for(;r<t.length&&/\s/.test(t[r]);)r++;if(r>=t.length)break;if(t[r]!=="["){r++;continue}r++;let n="";if(t[r]==="'"||t[r]==='"'){let i=t[r];for(r++;r<t.length&&t[r]!==i;)n+=t[r],r++;t[r]===i&&r++}else for(;r<t.length&&t[r]!=="]"&&t[r]!=="=";)n+=t[r],r++;for(;r<t.length&&t[r]!=="]";)r++;if(t[r]==="]"&&r++,t[r]!=="=")continue;r++;let s="";if(t[r]==="'"||t[r]==='"'){let i=t[r];for(r++;r<t.length&&t[r]!==i;)t[r]==="\\"&&r+1<t.length&&r++,s+=t[r],r++;t[r]===i&&r++}else for(;r<t.length&&!/\s/.test(t[r]);)s+=t[r],r++;e.push([n,s])}return e}function Hn(t,e){let r=!1,n=!1,s=[];for(let i=0;i<e.length;i++){let a=e[i];if(a==="-a")r=!0;else if(a==="-A")n=!0;else if(a==="-p"){if(e.length===1){let o="";for(let c of t.state.readonlyVars||[]){let l=t.state.env[c];l!==void 0&&(o+=`declare -r ${c}="${l}"
487
+ `)}return Se(o)}}else if(a==="--"){s.push(...e.slice(i+1));break}else a.startsWith("-")||s.push(a)}for(let i of s){let a=Qo(i);if(a.value===void 0&&!a.isArray){it(t,a.name);continue}let o=Ko(t,a,{makeReadonly:!0});if(o)return o}return q}Y();async function Un(t,e){let r=e;if(r.length>0){let s=r[0];if(s==="--")r=r.slice(1);else if(s.startsWith("-")&&s!=="-"&&s.length>1)return _(`bash: eval: ${s}: invalid option
488
488
  eval: usage: eval [arg ...]
489
- `,2)}if(r.length===0)return G;let n=r.join(" ");if(n.trim()==="")return G;try{let s=Ge(n);return t.executeScript(s)}catch(s){if(s instanceof ce||s instanceof pe||s instanceof ue||s instanceof Z)throw s;if(s.name==="ParseException")return F(`bash: eval: ${s.message}
490
- `);throw s}}X();function Bn(t,e){let r,n="";if(e.length===0)r=t.state.lastExitCode;else{let s=e[0],i=Number.parseInt(s,10);s===""||Number.isNaN(i)||!/^-?\d+$/.test(s)?(n=`bash: exit: ${s}: numeric argument required
491
- `,r=2):r=(i%256+256)%256}throw new Z(r,"",n)}function Hn(t,e){let r=!1,n=[];for(let a of e)a==="-n"?r=!0:a==="-p"||a==="--"||n.push(a);if(n.length===0&&!r){let a="",o=Object.entries(t.state.env).filter(([c])=>!c.startsWith("BASH_ALIAS_")).sort(([c],[l])=>c.localeCompare(l));for(let[c,l]of o){let u=l.replace(/'/g,"'\\''");a+=`declare -x ${c}='${u}'
492
- `}return we(a)}if(r){for(let a of n){let o=a.split("=")[0];delete t.state.env[o]}return G}let s="",i=0;for(let a of n){let o,c;if(a.includes("=")){let l=a.indexOf("=");o=a.slice(0,l),c=a.slice(l+1)}else o=a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){s+=`bash: export: \`${a}': not a valid identifier
493
- `,i=1;continue}c!==void 0?t.state.env[o]=c:o in t.state.env||(t.state.env[o]="")}return $("",s,i)}function Jd(t){let e=[],r="",n=0;for(let s of t){for(let i of s)i==="("?n++:i===")"&&n--;r?r+=` ${s}`:r=s,n===0&&(e.push(r),r="")}return r&&e.push(r),e}async function Un(t,e){if(e.length===0)return F(`bash: let: expression expected
494
- `);let r=Jd(e),n=0;for(let s of r)try{let a=Ge(`(( ${s} ))`).statements[0];if(a&&a.pipelines.length>0&&a.pipelines[0].commands.length>0){let o=a.pipelines[0].commands[0];o.type==="ArithmeticCommand"&&(n=await q(t,o.expression.expression))}}catch(i){return F(`bash: let: ${s}: ${i.message}
495
- `)}return $("","",n===0?1:0)}function eh(t,e){let r=t.state.env.HOME||"/home/user";return e.split(":").map(i=>i==="~"?r:i==="~root"?"/root":i.startsWith("~/")?r+i.slice(1):i.startsWith("~root/")?`/root${i.slice(5)}`:i).join(":")}function zn(t,e){if(t.state.localScopes.length===0)return F(`bash: local: can only be used in a function
496
- `);let r=t.state.localScopes[t.state.localScopes.length-1],n="",s=0;for(let i of e){let a,o;if(i.includes("=")){let c=i.indexOf("=");a=i.slice(0,c),o=eh(t,i.slice(c+1))}else a=i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){n+=`bash: local: \`${i}': not a valid identifier
497
- `,s=1;continue}r.has(a)||r.set(a,t.state.env[a]),o!==void 0&&(t.state.env[a]=o)}return $("",n,s)}function Gn(t,e,r){let n=!1,s=`
498
- `,i="",a=-1,o=null,c=[],l=0,u=!1;for(;l<e.length;){let E=e[l];E==="-r"?n=!0:E==="-d"&&l+1<e.length?(s=e[l+1],l++):E==="-p"&&l+1<e.length?(i=e[l+1],l++):E==="-n"&&l+1<e.length?(a=Number.parseInt(e[l+1],10),(Number.isNaN(a)||a<0)&&(u=!0,a=0),l++):E==="-a"&&l+1<e.length?(o=e[l+1],l++):E==="-t"?l+1<e.length&&!e[l+1].startsWith("-")&&l++:E==="-s"||E.startsWith("-")||c.push(E),l++}if(u)return $("","",1);c.length===0&&o===null&&c.push("REPLY");let f=r;!f&&t.state.groupStdin!==void 0&&(f=t.state.groupStdin);let d="",h=0,p=!0;if(a>=0){for(let E=0;E<f.length&&E<a;E++){let x=f[E];if(x===s){h=E+1;break}d+=x,h=E+1}t.state.groupStdin!==void 0&&!r&&(t.state.groupStdin=f.substring(h))}else{let E=f;for(h=0;;){let x=E.indexOf(s);if(x!==-1){let S=E.substring(0,x);if(h+=x+s.length,E=E.substring(x+s.length),!n&&S.endsWith("\\")){d+=S.slice(0,-1);continue}d+=S,p=!0;break}else if(E.length>0){d+=E,h+=E.length,p=!1,E="";break}else{if(d.length===0){for(let S of c)t.state.env[S]="";return o&&In(t,o),$("","",1)}p=!1;break}}t.state.groupStdin!==void 0&&!r&&(t.state.groupStdin=f.substring(h))}if(s===`
489
+ `,2)}if(r.length===0)return q;let n=r.join(" ");if(n.trim()==="")return q;try{let s=qe(n);return t.executeScript(s)}catch(s){if(s instanceof ue||s instanceof ye||s instanceof fe||s instanceof K)throw s;if(s.name==="ParseException")return _(`bash: eval: ${s.message}
490
+ `);throw s}}Y();function zn(t,e){let r,n="";if(e.length===0)r=t.state.lastExitCode;else{let s=e[0],i=Number.parseInt(s,10);s===""||Number.isNaN(i)||!/^-?\d+$/.test(s)?(n=`bash: exit: ${s}: numeric argument required
491
+ `,r=2):r=(i%256+256)%256}throw new K(r,"",n)}function Gn(t,e){let r=!1,n=[];for(let a of e)a==="-n"?r=!0:a==="-p"||a==="--"||n.push(a);if(n.length===0&&!r){let a="",o=Object.entries(t.state.env).filter(([c])=>!c.startsWith("BASH_ALIAS_")).sort(([c],[l])=>c.localeCompare(l));for(let[c,l]of o){let u=l.replace(/'/g,"'\\''");a+=`declare -x ${c}='${u}'
492
+ `}return Se(a)}if(r){for(let a of n){let o=a.split("=")[0];delete t.state.env[o]}return q}let s="",i=0;for(let a of n){let o,c;if(a.includes("=")){let l=a.indexOf("=");o=a.slice(0,l),c=a.slice(l+1)}else o=a;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o)){s+=`bash: export: \`${a}': not a valid identifier
493
+ `,i=1;continue}c!==void 0?t.state.env[o]=c:o in t.state.env||(t.state.env[o]="")}return $("",s,i)}function ah(t){let e=[],r="",n=0;for(let s of t){for(let i of s)i==="("?n++:i===")"&&n--;r?r+=` ${s}`:r=s,n===0&&(e.push(r),r="")}return r&&e.push(r),e}async function jn(t,e){if(e.length===0)return _(`bash: let: expression expected
494
+ `);let r=ah(e),n=0;for(let s of r)try{let a=qe(`(( ${s} ))`).statements[0];if(a&&a.pipelines.length>0&&a.pipelines[0].commands.length>0){let o=a.pipelines[0].commands[0];o.type==="ArithmeticCommand"&&(n=await Z(t,o.expression.expression))}}catch(i){return _(`bash: let: ${s}: ${i.message}
495
+ `)}return $("","",n===0?1:0)}function oh(t,e){let r=t.state.env.HOME||"/home/user";return e.split(":").map(i=>i==="~"?r:i==="~root"?"/root":i.startsWith("~/")?r+i.slice(1):i.startsWith("~root/")?`/root${i.slice(5)}`:i).join(":")}function qn(t,e){if(t.state.localScopes.length===0)return _(`bash: local: can only be used in a function
496
+ `);let r=t.state.localScopes[t.state.localScopes.length-1],n="",s=0;for(let i of e){let a,o;if(i.includes("=")){let c=i.indexOf("=");a=i.slice(0,c),o=oh(t,i.slice(c+1))}else a=i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){n+=`bash: local: \`${i}': not a valid identifier
497
+ `,s=1;continue}r.has(a)||r.set(a,t.state.env[a]),o!==void 0&&(t.state.env[a]=o)}return $("",n,s)}function Vn(t,e,r){let n=!1,s=`
498
+ `,i="",a=-1,o=null,c=[],l=0,u=!1;for(;l<e.length;){let b=e[l];b==="-r"?n=!0:b==="-d"&&l+1<e.length?(s=e[l+1],l++):b==="-p"&&l+1<e.length?(i=e[l+1],l++):b==="-n"&&l+1<e.length?(a=Number.parseInt(e[l+1],10),(Number.isNaN(a)||a<0)&&(u=!0,a=0),l++):b==="-a"&&l+1<e.length?(o=e[l+1],l++):b==="-t"?l+1<e.length&&!e[l+1].startsWith("-")&&l++:b==="-s"||b.startsWith("-")||c.push(b),l++}if(u)return $("","",1);c.length===0&&o===null&&c.push("REPLY");let f=r;!f&&t.state.groupStdin!==void 0&&(f=t.state.groupStdin);let d="",h=0,p=!0;if(a>=0){for(let b=0;b<f.length&&b<a;b++){let S=f[b];if(S===s){h=b+1;break}d+=S,h=b+1}t.state.groupStdin!==void 0&&!r&&(t.state.groupStdin=f.substring(h))}else{let b=f;for(h=0;;){let S=b.indexOf(s);if(S!==-1){let x=b.substring(0,S);if(h+=S+s.length,b=b.substring(S+s.length),!n&&x.endsWith("\\")){d+=x.slice(0,-1);continue}d+=x,p=!0;break}else if(b.length>0){d+=b,h+=b.length,p=!1,b="";break}else{if(d.length===0){for(let x of c)t.state.env[x]="";return o&&Pn(t,o),$("","",1)}p=!1;break}}t.state.groupStdin!==void 0&&!r&&(t.state.groupStdin=f.substring(h))}if(s===`
499
499
  `&&d.endsWith(`
500
- `)&&(d=d.slice(0,-1)),n||(d=d.replace(/\\(.)/g,"$1")),c.length===1&&c[0]==="REPLY")return t.state.env.REPLY=d,$("","",p?0:1);let b=or(t.state.env),{words:w,wordStarts:g}=Io(d,b);if(o){In(t,o);for(let E=0;E<w.length;E++)t.state.env[`${o}_${E}`]=w[E];return $("","",p?0:1)}for(let E=0;E<c.length;E++){let x=c[E];if(E<c.length-1)t.state.env[x]=w[E]??"";else if(E<g.length){let S=Ro(d.substring(g[E]),b);t.state.env[x]=S}else t.state.env[x]=""}return $("","",p?0:1)}X();function jn(t,e){if(t.state.callDepth===0&&t.state.sourceDepth===0)return F("bash: return: can only `return' from a function or sourced script\n");let r=t.state.lastExitCode;if(e.length>0){let n=e[0],s=Number.parseInt(n,10);if(n===""||Number.isNaN(s)||!/^-?\d+$/.test(n))return F(`bash: return: ${n}: numeric argument required
501
- `,2);r=(s%256+256)%256}throw new ue(r)}function th(t){return/^[a-zA-Z0-9_/.:-]*$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var fr=`set: usage: set [-eux] [+eux] [-o option] [+o option]
500
+ `)&&(d=d.slice(0,-1)),n||(d=d.replace(/\\(.)/g,"$1")),c.length===1&&c[0]==="REPLY")return t.state.env.REPLY=d,$("","",p?0:1);let E=fr(t.state.env),{words:w,wordStarts:g}=Oo(d,E);if(o){Pn(t,o);for(let b=0;b<w.length;b++)t.state.env[`${o}_${b}`]=w[b];return $("","",p?0:1)}for(let b=0;b<c.length;b++){let S=c[b];if(b<c.length-1)t.state.env[S]=w[b]??"";else if(b<g.length){let x=Do(d.substring(g[b]),E);t.state.env[S]=x}else t.state.env[S]=""}return $("","",p?0:1)}Y();function Zn(t,e){if(t.state.callDepth===0&&t.state.sourceDepth===0)return _("bash: return: can only `return' from a function or sourced script\n");let r=t.state.lastExitCode;if(e.length>0){let n=e[0],s=Number.parseInt(n,10);if(n===""||Number.isNaN(s)||!/^-?\d+$/.test(n))return _(`bash: return: ${n}: numeric argument required
501
+ `,2);r=(s%256+256)%256}throw new fe(r)}function lh(t){return/^[a-zA-Z0-9_/.:-]*$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var mr=`set: usage: set [-eux] [+eux] [-o option] [+o option]
502
502
  Options:
503
503
  -e Exit immediately if a command exits with non-zero status
504
504
  +e Disable -e
@@ -514,65 +514,65 @@ Options:
514
514
  +o pipefail Disable pipefail
515
515
  -o xtrace Same as -x
516
516
  +o xtrace Disable xtrace
517
- `,Vo={e:"errexit",u:"nounset",x:"xtrace",v:"verbose",f:null,h:null,C:null,n:null,a:null,b:null,m:null,B:null,H:null,P:null,T:null,E:null,p:null},Zo={errexit:"errexit",pipefail:"pipefail",nounset:"nounset",xtrace:"xtrace",verbose:"verbose",noclobber:null,noglob:null,noexec:null,allexport:null,notify:null,monitor:null,braceexpand:null,histexpand:null,physical:null,functrace:null,errtrace:null,privileged:null,hashall:null,posix:null,vi:null,emacs:null,ignoreeof:null,"interactive-comments":null,keyword:null,onecmd:null},Qo=["errexit","nounset","pipefail","verbose","xtrace"],Ko=["allexport","braceexpand","emacs","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","noclobber","noexec","noglob","nolog","notify","onecmd","physical","posix","privileged","vi"];function Xo(t,e,r){e!==null&&(t.state.options[e]=r)}function rh(t,e){return e+1<t.length&&!t[e+1].startsWith("-")&&!t[e+1].startsWith("+")}function Vn(t,e){if(e.includes("--help"))return we(fr);if(e.length===0){let n=Object.entries(t.state.env).filter(([s])=>/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${s}=${th(i)}`).join(`
518
- `);return we(n?`${n}
519
- `:"")}let r=0;for(;r<e.length;){let n=e[r];if((n==="-o"||n==="+o")&&rh(e,r)){let s=e[r+1];if(!(s in Zo))return F(`bash: set: ${s}: invalid option name
520
- ${fr}`);Xo(t,Zo[s],n==="-o"),r+=2;continue}if(n==="-o"){let s=Qo.map(o=>`${o.padEnd(16)}${t.state.options[o]?"on":"off"}`),i=Ko.map(o=>`${o.padEnd(16)}off`),a=[...s,...i].sort();return we(`${a.join(`
517
+ `,Xo={e:"errexit",u:"nounset",x:"xtrace",v:"verbose",f:null,h:null,C:null,n:null,a:null,b:null,m:null,B:null,H:null,P:null,T:null,E:null,p:null},Yo={errexit:"errexit",pipefail:"pipefail",nounset:"nounset",xtrace:"xtrace",verbose:"verbose",noclobber:null,noglob:null,noexec:null,allexport:null,notify:null,monitor:null,braceexpand:null,histexpand:null,physical:null,functrace:null,errtrace:null,privileged:null,hashall:null,posix:null,vi:null,emacs:null,ignoreeof:null,"interactive-comments":null,keyword:null,onecmd:null},Jo=["errexit","nounset","pipefail","verbose","xtrace"],el=["allexport","braceexpand","emacs","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","noclobber","noexec","noglob","nolog","notify","onecmd","physical","posix","privileged","vi"];function tl(t,e,r){e!==null&&(t.state.options[e]=r)}function ch(t,e){return e+1<t.length&&!t[e+1].startsWith("-")&&!t[e+1].startsWith("+")}function Kn(t,e){if(e.includes("--help"))return Se(mr);if(e.length===0){let n=Object.entries(t.state.env).filter(([s])=>/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)).sort(([s],[i])=>s.localeCompare(i)).map(([s,i])=>`${s}=${lh(i)}`).join(`
518
+ `);return Se(n?`${n}
519
+ `:"")}let r=0;for(;r<e.length;){let n=e[r];if((n==="-o"||n==="+o")&&ch(e,r)){let s=e[r+1];if(!(s in Yo))return _(`bash: set: ${s}: invalid option name
520
+ ${mr}`);tl(t,Yo[s],n==="-o"),r+=2;continue}if(n==="-o"){let s=Jo.map(o=>`${o.padEnd(16)}${t.state.options[o]?"on":"off"}`),i=el.map(o=>`${o.padEnd(16)}off`),a=[...s,...i].sort();return Se(`${a.join(`
521
521
  `)}
522
- `)}if(n==="+o"){let s=Qo.map(o=>`set ${t.state.options[o]?"-o":"+o"} ${o}`),i=Ko.map(o=>`set +o ${o}`),a=[...s,...i].sort();return we(`${a.join(`
522
+ `)}if(n==="+o"){let s=Jo.map(o=>`set ${t.state.options[o]?"-o":"+o"} ${o}`),i=el.map(o=>`set +o ${o}`),a=[...s,...i].sort();return Se(`${a.join(`
523
523
  `)}
524
- `)}if(n.length>1&&(n[0]==="-"||n[0]==="+")&&n[1]!=="-"){let s=n[0]==="-";for(let i=1;i<n.length;i++){let a=n[i];if(!(a in Vo))return F(`bash: set: ${n[0]}${a}: invalid option
525
- ${fr}`);Xo(t,Vo[a],s)}r++;continue}if(n==="--")return qn(t,e.slice(r+1)),G;if(n==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,r+1<e.length)return qn(t,e.slice(r+1)),G;r++;continue}if(n==="+"){r++;continue}return n.startsWith("-")||n.startsWith("+")?F(`bash: set: ${n}: invalid option
526
- ${fr}`):(qn(t,e.slice(r)),G)}return G}function qn(t,e){let r=1;for(;t.state.env[String(r)]!==void 0;)delete t.state.env[String(r)],r++;for(let n=0;n<e.length;n++)t.state.env[String(n+1)]=e[n];t.state.env["#"]=String(e.length),t.state.env["@"]=e.join(" "),t.state.env["*"]=e.join(" ")}function Zn(t,e){let r=1;if(e.length>0){let a=Number.parseInt(e[0],10);if(Number.isNaN(a)||a<0)return F(`bash: shift: ${e[0]}: numeric argument required
527
- `);r=a}let n=Number.parseInt(t.state.env["#"]||"0",10);if(r>n)return F(`bash: shift: shift count out of range
528
- `);if(r===0)return G;let s=[];for(let a=1;a<=n;a++)s.push(t.state.env[String(a)]||"");let i=s.slice(r);for(let a=1;a<=n;a++)delete t.state.env[String(a)];for(let a=0;a<i.length;a++)t.state.env[String(a+1)]=i[a];return t.state.env["#"]=String(i.length),t.state.env["@"]=i.join(" "),G}X();async function Qn(t,e){let r=e;if(r.length>0&&r[0]==="--"&&(r=r.slice(1)),r.length===0)return $("",`bash: source: filename argument required
529
- `,2);let n=r[0],s=null,i=null;if(n.includes("/")){let c=t.fs.resolvePath(t.state.cwd,n);try{i=await t.fs.readFile(c),s=c}catch{}}else{let l=(t.state.env.PATH||"").split(":").filter(u=>u);for(let u of l){let f=t.fs.resolvePath(t.state.cwd,`${u}/${n}`);try{if((await t.fs.stat(f)).isDirectory)continue;i=await t.fs.readFile(f),s=f;break}catch{}}if(i===null){let u=t.fs.resolvePath(t.state.cwd,n);try{i=await t.fs.readFile(u),s=u}catch{}}}if(i===null)return F(`bash: ${n}: No such file or directory
530
- `);let a={};if(r.length>1){for(let l=1;l<=9;l++)a[String(l)]=t.state.env[String(l)];a["#"]=t.state.env["#"],a["@"]=t.state.env["@"];let c=r.slice(1);t.state.env["#"]=String(c.length),t.state.env["@"]=c.join(" ");for(let l=0;l<c.length&&l<9;l++)t.state.env[String(l+1)]=c[l];for(let l=c.length+1;l<=9;l++)delete t.state.env[String(l)]}let o=()=>{if(t.state.sourceDepth--,r.length>1)for(let[c,l]of Object.entries(a))l===void 0?delete t.state.env[c]:t.state.env[c]=l};t.state.sourceDepth++;try{let c=Ge(i),l=await t.executeScript(c);return o(),l}catch(c){if(o(),c instanceof Z)throw c;if(c instanceof ue)return $(c.stdout,c.stderr,c.exitCode);if(c.name==="ParseException")return F(`bash: ${n}: ${c.message}
531
- `);throw c}}function Kn(t,e){let r="variable",n="",s=0;for(let i of e){if(i==="-v"){r="variable";continue}if(i==="-f"){r="function";continue}if(r==="function"){t.state.functions.delete(i);continue}let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let o=a[1],c=a[2];if(c==="@"||c==="*"){let u=ie(t,o);for(let[f]of u)delete t.state.env[`${o}_${f}`];delete t.state.env[o];continue}let l;if(/^-?\d+$/.test(c))l=Number.parseInt(c,10);else{let u=t.state.env[c];l=u?Number.parseInt(u,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let u=ie(t,o),f=u.length;if(f===0){n+=`bash: unset: [${l}]: bad array subscript
524
+ `)}if(n.length>1&&(n[0]==="-"||n[0]==="+")&&n[1]!=="-"){let s=n[0]==="-";for(let i=1;i<n.length;i++){let a=n[i];if(!(a in Xo))return _(`bash: set: ${n[0]}${a}: invalid option
525
+ ${mr}`);tl(t,Xo[a],s)}r++;continue}if(n==="--")return Qn(t,e.slice(r+1)),q;if(n==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,r+1<e.length)return Qn(t,e.slice(r+1)),q;r++;continue}if(n==="+"){r++;continue}return n.startsWith("-")||n.startsWith("+")?_(`bash: set: ${n}: invalid option
526
+ ${mr}`):(Qn(t,e.slice(r)),q)}return q}function Qn(t,e){let r=1;for(;t.state.env[String(r)]!==void 0;)delete t.state.env[String(r)],r++;for(let n=0;n<e.length;n++)t.state.env[String(n+1)]=e[n];t.state.env["#"]=String(e.length),t.state.env["@"]=e.join(" "),t.state.env["*"]=e.join(" ")}function Xn(t,e){let r=1;if(e.length>0){let a=Number.parseInt(e[0],10);if(Number.isNaN(a)||a<0)return _(`bash: shift: ${e[0]}: numeric argument required
527
+ `);r=a}let n=Number.parseInt(t.state.env["#"]||"0",10);if(r>n)return _(`bash: shift: shift count out of range
528
+ `);if(r===0)return q;let s=[];for(let a=1;a<=n;a++)s.push(t.state.env[String(a)]||"");let i=s.slice(r);for(let a=1;a<=n;a++)delete t.state.env[String(a)];for(let a=0;a<i.length;a++)t.state.env[String(a+1)]=i[a];return t.state.env["#"]=String(i.length),t.state.env["@"]=i.join(" "),q}Y();async function Yn(t,e){let r=e;if(r.length>0&&r[0]==="--"&&(r=r.slice(1)),r.length===0)return $("",`bash: source: filename argument required
529
+ `,2);let n=r[0],s=null,i=null;if(n.includes("/")){let c=t.fs.resolvePath(t.state.cwd,n);try{i=await t.fs.readFile(c),s=c}catch{}}else{let l=(t.state.env.PATH||"").split(":").filter(u=>u);for(let u of l){let f=t.fs.resolvePath(t.state.cwd,`${u}/${n}`);try{if((await t.fs.stat(f)).isDirectory)continue;i=await t.fs.readFile(f),s=f;break}catch{}}if(i===null){let u=t.fs.resolvePath(t.state.cwd,n);try{i=await t.fs.readFile(u),s=u}catch{}}}if(i===null)return _(`bash: ${n}: No such file or directory
530
+ `);let a={};if(r.length>1){for(let l=1;l<=9;l++)a[String(l)]=t.state.env[String(l)];a["#"]=t.state.env["#"],a["@"]=t.state.env["@"];let c=r.slice(1);t.state.env["#"]=String(c.length),t.state.env["@"]=c.join(" ");for(let l=0;l<c.length&&l<9;l++)t.state.env[String(l+1)]=c[l];for(let l=c.length+1;l<=9;l++)delete t.state.env[String(l)]}let o=()=>{if(t.state.sourceDepth--,r.length>1)for(let[c,l]of Object.entries(a))l===void 0?delete t.state.env[c]:t.state.env[c]=l};t.state.sourceDepth++;try{let c=qe(i),l=await t.executeScript(c);return o(),l}catch(c){if(o(),c instanceof K)throw c;if(c instanceof fe)return $(c.stdout,c.stderr,c.exitCode);if(c.name==="ParseException")return _(`bash: ${n}: ${c.message}
531
+ `);throw c}}function Jn(t,e){let r="variable",n="",s=0;for(let i of e){if(i==="-v"){r="variable";continue}if(i==="-f"){r="function";continue}if(r==="function"){t.state.functions.delete(i);continue}let a=i.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(a){let o=a[1],c=a[2];if(c==="@"||c==="*"){let u=ae(t,o);for(let[f]of u)delete t.state.env[`${o}_${f}`];delete t.state.env[o];continue}let l;if(/^-?\d+$/.test(c))l=Number.parseInt(c,10);else{let u=t.state.env[c];l=u?Number.parseInt(u,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let u=ae(t,o),f=u.length;if(f===0){n+=`bash: unset: [${l}]: bad array subscript
532
532
  `,s=1;continue}let d=f+l;if(d<0){n+=`bash: unset: [${l}]: bad array subscript
533
- `,s=1;continue}let h=u[d][0];delete t.state.env[`${o}_${h}`];continue}delete t.state.env[`${o}_${l}`];continue}delete t.state.env[i],t.state.functions.delete(i)}return $("",n,s)}function Xn(t,e){return t.fs.resolvePath(t.state.cwd,e)}var nh=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function dr(t){return nh.includes(t)}async function hr(t,e,r){let n=Xn(t,r);switch(e){case"-e":case"-a":return t.fs.exists(n);case"-f":return await t.fs.exists(n)?(await t.fs.stat(n)).isFile:!1;case"-d":return await t.fs.exists(n)?(await t.fs.stat(n)).isDirectory:!1;case"-r":case"-w":case"-x":return t.fs.exists(n);case"-s":return await t.fs.exists(n)?(await t.fs.stat(n)).size>0:!1;case"-L":case"-h":try{return(await t.fs.lstat(n)).isSymbolicLink}catch{return!1}case"-k":return await t.fs.exists(n)?((await t.fs.stat(n)).mode&512)!==0:!1;case"-g":return await t.fs.exists(n)?((await t.fs.stat(n)).mode&1024)!==0:!1;case"-u":return await t.fs.exists(n)?((await t.fs.stat(n)).mode&2048)!==0:!1;case"-G":case"-O":return t.fs.exists(n);case"-b":return!1;case"-c":return["/dev/null","/dev/zero","/dev/random","/dev/urandom","/dev/tty","/dev/stdin","/dev/stdout","/dev/stderr"].some(i=>n===i||n.endsWith(i));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return t.fs.exists(n);default:return!1}}var sh=["-nt","-ot","-ef"];function pr(t){return sh.includes(t)}async function mr(t,e,r,n){let s=Xn(t,r),i=Xn(t,n);switch(e){case"-nt":try{let a=await t.fs.stat(s),o=await t.fs.stat(i);return a.mtime>o.mtime}catch{return!1}case"-ot":try{let a=await t.fs.stat(s),o=await t.fs.stat(i);return a.mtime<o.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(s)||!await t.fs.exists(i))return!1;let a=t.fs.resolvePath(t.state.cwd,s),o=t.fs.resolvePath(t.state.cwd,i);return a===o}catch{return!1}default:return!1}}var ih=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function yr(t){return ih.has(t)}function gr(t,e,r){switch(t){case"-eq":return e===r;case"-ne":return e!==r;case"-lt":return e<r;case"-le":return e<=r;case"-gt":return e>r;case"-ge":return e>=r}}function wr(t){return t==="="||t==="=="||t==="!="}function Er(t,e,r,n=!1){let s=n?br(e,r):e===r;return t==="!="?!s:s}var ah=new Set(["-z","-n"]);function xr(t){return ah.has(t)}function Sr(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function Ar(t,e){let r=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(r){let n=r[1],s=r[2];s=s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(a,o)=>t.state.env[o]||"");let i;if(/^-?\d+$/.test(s))i=Number.parseInt(s,10);else try{let a=Function(`"use strict"; return (${s})`)();i=typeof a=="number"?Math.floor(a):0}catch{let a=t.state.env[s];i=a?Number.parseInt(a,10):0}if(i<0){let a=kt(t,n);if(a.length===0||(i=Math.max(...a)+1+i,i<0))return!1}return`${n}_${i}`in t.state.env}return e in t.state.env}async function Ve(t,e){switch(e.type){case"CondBinary":{let r=await Q(t,e.left),n=await Q(t,e.right),s=e.right.parts.length>0&&e.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped");if(wr(e.operator))return Er(e.operator,r,n,!s);if(yr(e.operator))return gr(e.operator,Jo(t,r),Jo(t,n));if(pr(e.operator))return mr(t,e.operator,r,n);switch(e.operator){case"=~":try{let i=new RegExp(n),a=r.match(i);if(a){t.state.env.BASH_REMATCH=a[0];for(let o=1;o<a.length;o++)t.state.env[`BASH_REMATCH_${o}`]=a[o]||""}return a!==null}catch{throw new Error("syntax error in regular expression")}case"<":return r<n;case">":return r>n;default:return!1}}case"CondUnary":{let r=await Q(t,e.operand);return dr(e.operator)?hr(t,e.operator,r):xr(e.operator)?Sr(e.operator,r):e.operator==="-v"?Ar(t,r):e.operator==="-o"?Jn(t,r):!1}case"CondNot":return!await Ve(t,e.operand);case"CondAnd":return await Ve(t,e.left)?await Ve(t,e.right):!1;case"CondOr":return await Ve(t,e.left)?!0:await Ve(t,e.right);case"CondGroup":return await Ve(t,e.expression);case"CondWord":return await Q(t,e.word)!=="";default:return!1}}async function yt(t,e){if(e.length===0)return $("","",1);if(e.length===1)return re(!!e[0]);if(e.length===2){let n=e[0],s=e[1];return n==="("?F(`test: '(' without matching ')'
534
- `,2):dr(n)?re(await hr(t,n,s)):xr(n)?re(Sr(n,s)):n==="!"?re(!s):n==="-v"?re(Ar(t,s)):n==="-o"?re(Jn(t,s)):n==="="||n==="=="||n==="!="||n==="<"||n===">"||n==="-eq"||n==="-ne"||n==="-lt"||n==="-le"||n==="-gt"||n==="-ge"||n==="-nt"||n==="-ot"||n==="-ef"?F(`test: ${n}: unary operator expected
535
- `,2):$("","",1)}if(e.length===3){let n=e[0],s=e[1],i=e[2];if(wr(s))return re(Er(s,n,i));if(yr(s)){let a=Cr(n),o=Cr(i);return!a.valid||!o.valid?$("","",2):re(gr(s,a.value,o.value))}if(pr(s))return re(await mr(t,s,n,i));switch(s){case"-a":return re(n!==""&&i!=="");case"-o":return re(n!==""||i!=="");case">":return re(n>i);case"<":return re(n<i)}if(n==="!"){let a=await yt(t,[s,i]);return $("",a.stderr,a.exitCode===0?1:a.exitCode===1?0:a.exitCode)}if(n==="("&&i===")")return re(s!=="")}if(e.length===4){if(e[0]==="!"){let n=await yt(t,e.slice(1));return $("",n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(e[0]==="("&&e[3]===")")return yt(t,[e[1],e[2]])}let r=await tl(t,e,0);return r.pos<e.length?F(`test: too many arguments
536
- `,2):re(r.value)}async function tl(t,e,r){return oh(t,e,r)}async function oh(t,e,r){let{value:n,pos:s}=await Yo(t,e,r);for(;e[s]==="-o";){let i=await Yo(t,e,s+1);n=n||i.value,s=i.pos}return{value:n,pos:s}}async function Yo(t,e,r){let{value:n,pos:s}=await Yn(t,e,r);for(;e[s]==="-a";){let i=await Yn(t,e,s+1);n=n&&i.value,s=i.pos}return{value:n,pos:s}}async function Yn(t,e,r){if(e[r]==="!"){let{value:n,pos:s}=await Yn(t,e,r+1);return{value:!n,pos:s}}return lh(t,e,r)}async function lh(t,e,r){let n=e[r];if(n==="("){let{value:i,pos:a}=await tl(t,e,r+1);return{value:i,pos:e[a]===")"?a+1:a}}if(dr(n)){let i=e[r+1]??"";return{value:await hr(t,n,i),pos:r+2}}if(xr(n)){let i=e[r+1]??"";return{value:Sr(n,i),pos:r+2}}if(n==="-v"){let i=e[r+1]??"";return{value:Ar(t,i),pos:r+2}}if(n==="-o"){let i=e[r+1]??"";return{value:Jn(t,i),pos:r+2}}let s=e[r+1];if(wr(s)){let i=n,a=e[r+2]??"";return{value:Er(s,i,a),pos:r+3}}if(yr(s)){let i=Cr(n),a=Cr(e[r+2]??"0");return!i.valid||!a.valid?{value:!1,pos:r+3}:{value:gr(s,i.value,a.value),pos:r+3}}if(pr(s)){let i=n,a=e[r+2]??"";return{value:await mr(t,s,i,a),pos:r+3}}return{value:n!==void 0&&n!=="",pos:r+1}}function br(t,e){let r="^";for(let n=0;n<e.length;n++){let s=e[n];if(s==="\\")if(n+1<e.length){let i=e[n+1];/[\\^$.|+(){}[\]*?]/.test(i)?r+=`\\${i}`:r+=i,n++}else r+="\\\\";else if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let i=e.indexOf("]",n+1);i!==-1?(r+=e.slice(n,i+1),n=i):r+="\\["}else/[\\^$.|+(){}]/.test(s)?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r).test(t)}function Jn(t,e){let n={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 n?n():!1}function Jo(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 el(e);try{let r=new le,n=se(r,e);return j(t,n.expression)}catch{return el(e)}}function ch(t,e){let r=0;for(let n of t){let s;if(n>="0"&&n<="9")s=n.charCodeAt(0)-48;else if(n>="a"&&n<="z")s=n.charCodeAt(0)-97+10;else if(n>="A"&&n<="Z")s=n.charCodeAt(0)-65+36;else if(n==="@")s=62;else if(n==="_")s=63;else return Number.NaN;if(s>=e)return Number.NaN;r=r*e+s}return r}function el(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 r,n=t.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(n){let s=Number.parseInt(n[1],10);s>=2&&s<=64?r=ch(n[2],s):r=0}else/^0[xX][0-9a-fA-F]+$/.test(t)?r=Number.parseInt(t,16):/^0[0-7]+$/.test(t)?r=Number.parseInt(t,8):r=Number.parseInt(t,10);return Number.isNaN(r)&&(r=0),e?-r:r}function Cr(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 r=Number.parseInt(t,10);return Number.isNaN(r)?{value:0,valid:!1}:{value:e?-r:r,valid:!0}}X();async function es(t,e){let r=t.state.inCondition;t.state.inCondition=!0;let n="",s="",i=0;try{for(let a of e){let o=await t.executeStatement(a);n+=o.stdout,s+=o.stderr,i=o.exitCode}}finally{t.state.inCondition=r}return{stdout:n,stderr:s,exitCode:i}}X();ke();function Pt(t,e,r,n){if(t instanceof ce)return e+=t.stdout,r+=t.stderr,t.levels>1&&n>1?(t.levels--,t.stdout=e,t.stderr=r,{action:"rethrow",stdout:e,stderr:r,error:t}):{action:"break",stdout:e,stderr:r};if(t instanceof pe)return e+=t.stdout,r+=t.stderr,t.levels>1&&n>1?(t.levels--,t.stdout=e,t.stderr=r,{action:"rethrow",stdout:e,stderr:r,error:t}):{action:"continue",stdout:e,stderr:r};if(t instanceof ue||t instanceof Re||t instanceof Z||t instanceof W)return t.prependOutput(e,r),{action:"rethrow",stdout:e,stderr:r,error:t};let s=Y(t);return{action:"error",stdout:e,stderr:`${r}${s}
537
- `,exitCode:1}}X();ke();async function Nr(t,e,r="",n=""){let s=r,i=n,a=0;try{for(let o of e){let c=await t.executeStatement(o);s+=c.stdout,i+=c.stderr,a=c.exitCode}}catch(o){if(zt(o)||o instanceof Re||o instanceof Z||o instanceof W||o instanceof $e)throw o.prependOutput(s,i),o;return{stdout:s,stderr:`${i}${Y(o)}
538
- `,exitCode:1}}return{stdout:s,stderr:i,exitCode:a}}async function rl(t,e){let r="",n="";for(let s of e.clauses){let i=await es(t,s.condition);if(r+=i.stdout,n+=i.stderr,i.exitCode===0)return Nr(t,s.body,r,n)}return e.elseBody?Nr(t,e.elseBody,r,n):$(r,n,0)}async function nl(t,e){let r="",n="",s=0,i=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return F(`bash: \`${e.variable}': not a valid identifier
539
- `);let a=[];if(e.words===null)a=(t.state.env["@"]||"").split(" ").filter(Boolean);else if(e.words.length===0)a=[];else for(let o of e.words){let c=await $t(t,o);a.push(...c.values)}t.state.loopDepth++;try{for(let o of a){i++,i>t.limits.maxLoopIterations&&_e(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),t.state.env[e.variable]=o;try{for(let c of e.body){let l=await t.executeStatement(c);r+=l.stdout,n+=l.stderr,s=l.exitCode}}catch(c){let l=Pt(c,r,n,t.state.loopDepth);if(r=l.stdout,n=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return $(r,n,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return $(r,n,s)}async function sl(t,e){let r="",n="",s=0,i=0;e.init&&await q(t,e.init.expression),t.state.loopDepth++;try{for(;i++,i>t.limits.maxLoopIterations&&_e(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),!(e.condition&&await q(t,e.condition.expression)===0);){try{for(let a of e.body){let o=await t.executeStatement(a);r+=o.stdout,n+=o.stderr,s=o.exitCode}}catch(a){let o=Pt(a,r,n,t.state.loopDepth);if(r=o.stdout,n=o.stderr,o.action==="break")break;if(o.action==="continue"){e.update&&await q(t,e.update.expression);continue}if(o.action==="error")return $(r,n,o.exitCode??1);throw o.error}e.update&&await q(t,e.update.expression)}}finally{t.state.loopDepth--}return $(r,n,s)}async function il(t,e,r=""){let n="",s="",i=0,a=0,o=r;for(let l of e.redirections)if((l.operator==="<<"||l.operator==="<<-")&&l.target.type==="HereDoc"){let u=l.target,f=await Q(t,u.content);u.stripTabs&&(f=f.split(`
533
+ `,s=1;continue}let h=u[d][0];delete t.state.env[`${o}_${h}`];continue}delete t.state.env[`${o}_${l}`];continue}delete t.state.env[i],t.state.functions.delete(i)}return $("",n,s)}function es(t,e){return t.fs.resolvePath(t.state.cwd,e)}var uh=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function yr(t){return uh.includes(t)}async function gr(t,e,r){let n=es(t,r);switch(e){case"-e":case"-a":return t.fs.exists(n);case"-f":return await t.fs.exists(n)?(await t.fs.stat(n)).isFile:!1;case"-d":return await t.fs.exists(n)?(await t.fs.stat(n)).isDirectory:!1;case"-r":case"-w":case"-x":return t.fs.exists(n);case"-s":return await t.fs.exists(n)?(await t.fs.stat(n)).size>0:!1;case"-L":case"-h":try{return(await t.fs.lstat(n)).isSymbolicLink}catch{return!1}case"-k":return await t.fs.exists(n)?((await t.fs.stat(n)).mode&512)!==0:!1;case"-g":return await t.fs.exists(n)?((await t.fs.stat(n)).mode&1024)!==0:!1;case"-u":return await t.fs.exists(n)?((await t.fs.stat(n)).mode&2048)!==0:!1;case"-G":case"-O":return t.fs.exists(n);case"-b":return!1;case"-c":return["/dev/null","/dev/zero","/dev/random","/dev/urandom","/dev/tty","/dev/stdin","/dev/stdout","/dev/stderr"].some(i=>n===i||n.endsWith(i));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return t.fs.exists(n);default:return!1}}var fh=["-nt","-ot","-ef"];function wr(t){return fh.includes(t)}async function Er(t,e,r,n){let s=es(t,r),i=es(t,n);switch(e){case"-nt":try{let a=await t.fs.stat(s),o=await t.fs.stat(i);return a.mtime>o.mtime}catch{return!1}case"-ot":try{let a=await t.fs.stat(s),o=await t.fs.stat(i);return a.mtime<o.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(s)||!await t.fs.exists(i))return!1;let a=t.fs.resolvePath(t.state.cwd,s),o=t.fs.resolvePath(t.state.cwd,i);return a===o}catch{return!1}default:return!1}}var dh=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function br(t){return dh.has(t)}function Sr(t,e,r){switch(t){case"-eq":return e===r;case"-ne":return e!==r;case"-lt":return e<r;case"-le":return e<=r;case"-gt":return e>r;case"-ge":return e>=r}}function xr(t){return t==="="||t==="=="||t==="!="}function Ar(t,e,r,n=!1){let s=n?Cr(e,r):e===r;return t==="!="?!s:s}var hh=new Set(["-z","-n"]);function Nr(t){return hh.has(t)}function vr(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function kr(t,e){let r=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(r){let n=r[1],s=r[2];s=s.replace(/\$([a-zA-Z_][a-zA-Z0-9_]*)/g,(a,o)=>t.state.env[o]||"");let i;if(/^-?\d+$/.test(s))i=Number.parseInt(s,10);else try{let a=Function(`"use strict"; return (${s})`)();i=typeof a=="number"?Math.floor(a):0}catch{let a=t.state.env[s];i=a?Number.parseInt(a,10):0}if(i<0){let a=$t(t,n);if(a.length===0||(i=Math.max(...a)+1+i,i<0))return!1}return`${n}_${i}`in t.state.env}return e in t.state.env}async function Qe(t,e){switch(e.type){case"CondBinary":{let r=await X(t,e.left),n=await X(t,e.right),s=e.right.parts.length>0&&e.right.parts.every(i=>i.type==="SingleQuoted"||i.type==="DoubleQuoted"||i.type==="Escaped");if(xr(e.operator))return Ar(e.operator,r,n,!s);if(br(e.operator))return Sr(e.operator,nl(t,r),nl(t,n));if(wr(e.operator))return Er(t,e.operator,r,n);switch(e.operator){case"=~":try{let i=new RegExp(n),a=r.match(i);if(a){t.state.env.BASH_REMATCH=a[0];for(let o=1;o<a.length;o++)t.state.env[`BASH_REMATCH_${o}`]=a[o]||""}return a!==null}catch{throw new Error("syntax error in regular expression")}case"<":return r<n;case">":return r>n;default:return!1}}case"CondUnary":{let r=await X(t,e.operand);return yr(e.operator)?gr(t,e.operator,r):Nr(e.operator)?vr(e.operator,r):e.operator==="-v"?kr(t,r):e.operator==="-o"?rs(t,r):!1}case"CondNot":return!await Qe(t,e.operand);case"CondAnd":return await Qe(t,e.left)?await Qe(t,e.right):!1;case"CondOr":return await Qe(t,e.left)?!0:await Qe(t,e.right);case"CondGroup":return await Qe(t,e.expression);case"CondWord":return await X(t,e.word)!=="";default:return!1}}async function Et(t,e){if(e.length===0)return $("","",1);if(e.length===1)return se(!!e[0]);if(e.length===2){let n=e[0],s=e[1];return n==="("?_(`test: '(' without matching ')'
534
+ `,2):yr(n)?se(await gr(t,n,s)):Nr(n)?se(vr(n,s)):n==="!"?se(!s):n==="-v"?se(kr(t,s)):n==="-o"?se(rs(t,s)):n==="="||n==="=="||n==="!="||n==="<"||n===">"||n==="-eq"||n==="-ne"||n==="-lt"||n==="-le"||n==="-gt"||n==="-ge"||n==="-nt"||n==="-ot"||n==="-ef"?_(`test: ${n}: unary operator expected
535
+ `,2):$("","",1)}if(e.length===3){let n=e[0],s=e[1],i=e[2];if(xr(s))return se(Ar(s,n,i));if(br(s)){let a=Ir(n),o=Ir(i);return!a.valid||!o.valid?$("","",2):se(Sr(s,a.value,o.value))}if(wr(s))return se(await Er(t,s,n,i));switch(s){case"-a":return se(n!==""&&i!=="");case"-o":return se(n!==""||i!=="");case">":return se(n>i);case"<":return se(n<i)}if(n==="!"){let a=await Et(t,[s,i]);return $("",a.stderr,a.exitCode===0?1:a.exitCode===1?0:a.exitCode)}if(n==="("&&i===")")return se(s!=="")}if(e.length===4){if(e[0]==="!"){let n=await Et(t,e.slice(1));return $("",n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(e[0]==="("&&e[3]===")")return Et(t,[e[1],e[2]])}let r=await il(t,e,0);return r.pos<e.length?_(`test: too many arguments
536
+ `,2):se(r.value)}async function il(t,e,r){return ph(t,e,r)}async function ph(t,e,r){let{value:n,pos:s}=await rl(t,e,r);for(;e[s]==="-o";){let i=await rl(t,e,s+1);n=n||i.value,s=i.pos}return{value:n,pos:s}}async function rl(t,e,r){let{value:n,pos:s}=await ts(t,e,r);for(;e[s]==="-a";){let i=await ts(t,e,s+1);n=n&&i.value,s=i.pos}return{value:n,pos:s}}async function ts(t,e,r){if(e[r]==="!"){let{value:n,pos:s}=await ts(t,e,r+1);return{value:!n,pos:s}}return mh(t,e,r)}async function mh(t,e,r){let n=e[r];if(n==="("){let{value:i,pos:a}=await il(t,e,r+1);return{value:i,pos:e[a]===")"?a+1:a}}if(yr(n)){let i=e[r+1]??"";return{value:await gr(t,n,i),pos:r+2}}if(Nr(n)){let i=e[r+1]??"";return{value:vr(n,i),pos:r+2}}if(n==="-v"){let i=e[r+1]??"";return{value:kr(t,i),pos:r+2}}if(n==="-o"){let i=e[r+1]??"";return{value:rs(t,i),pos:r+2}}let s=e[r+1];if(xr(s)){let i=n,a=e[r+2]??"";return{value:Ar(s,i,a),pos:r+3}}if(br(s)){let i=Ir(n),a=Ir(e[r+2]??"0");return!i.valid||!a.valid?{value:!1,pos:r+3}:{value:Sr(s,i.value,a.value),pos:r+3}}if(wr(s)){let i=n,a=e[r+2]??"";return{value:await Er(t,s,i,a),pos:r+3}}return{value:n!==void 0&&n!=="",pos:r+1}}function Cr(t,e){let r="^";for(let n=0;n<e.length;n++){let s=e[n];if(s==="\\")if(n+1<e.length){let i=e[n+1];/[\\^$.|+(){}[\]*?]/.test(i)?r+=`\\${i}`:r+=i,n++}else r+="\\\\";else if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let i=e.indexOf("]",n+1);i!==-1?(r+=e.slice(n,i+1),n=i):r+="\\["}else/[\\^$.|+(){}]/.test(s)?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r).test(t)}function rs(t,e){let n={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 n?n():!1}function nl(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 sl(e);try{let r=new le,n=ie(r,e);return V(t,n.expression)}catch{return sl(e)}}function yh(t,e){let r=0;for(let n of t){let s;if(n>="0"&&n<="9")s=n.charCodeAt(0)-48;else if(n>="a"&&n<="z")s=n.charCodeAt(0)-97+10;else if(n>="A"&&n<="Z")s=n.charCodeAt(0)-65+36;else if(n==="@")s=62;else if(n==="_")s=63;else return Number.NaN;if(s>=e)return Number.NaN;r=r*e+s}return r}function sl(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 r,n=t.match(/^(\d+)#([a-zA-Z0-9@_]+)$/);if(n){let s=Number.parseInt(n[1],10);s>=2&&s<=64?r=yh(n[2],s):r=0}else/^0[xX][0-9a-fA-F]+$/.test(t)?r=Number.parseInt(t,16):/^0[0-7]+$/.test(t)?r=Number.parseInt(t,8):r=Number.parseInt(t,10);return Number.isNaN(r)&&(r=0),e?-r:r}function Ir(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 r=Number.parseInt(t,10);return Number.isNaN(r)?{value:0,valid:!1}:{value:e?-r:r,valid:!0}}Y();async function ns(t,e){let r=t.state.inCondition;t.state.inCondition=!0;let n="",s="",i=0;try{for(let a of e){let o=await t.executeStatement(a);n+=o.stdout,s+=o.stderr,i=o.exitCode}}finally{t.state.inCondition=r}return{stdout:n,stderr:s,exitCode:i}}Y();Ie();function Dt(t,e,r,n){if(t instanceof ue)return e+=t.stdout,r+=t.stderr,t.levels>1&&n>1?(t.levels--,t.stdout=e,t.stderr=r,{action:"rethrow",stdout:e,stderr:r,error:t}):{action:"break",stdout:e,stderr:r};if(t instanceof ye)return e+=t.stdout,r+=t.stderr,t.levels>1&&n>1?(t.levels--,t.stdout=e,t.stderr=r,{action:"rethrow",stdout:e,stderr:r,error:t}):{action:"continue",stdout:e,stderr:r};if(t instanceof fe||t instanceof Re||t instanceof K||t instanceof B)return t.prependOutput(e,r),{action:"rethrow",stdout:e,stderr:r,error:t};let s=J(t);return{action:"error",stdout:e,stderr:`${r}${s}
537
+ `,exitCode:1}}Y();Ie();async function $r(t,e,r="",n=""){let s=r,i=n,a=0;try{for(let o of e){let c=await t.executeStatement(o);s+=c.stdout,i+=c.stderr,a=c.exitCode}}catch(o){if(Vt(o)||o instanceof Re||o instanceof K||o instanceof B||o instanceof Oe)throw o.prependOutput(s,i),o;return{stdout:s,stderr:`${i}${J(o)}
538
+ `,exitCode:1}}return{stdout:s,stderr:i,exitCode:a}}async function al(t,e){let r="",n="";for(let s of e.clauses){let i=await ns(t,s.condition);if(r+=i.stdout,n+=i.stderr,i.exitCode===0)return $r(t,s.body,r,n)}return e.elseBody?$r(t,e.elseBody,r,n):$(r,n,0)}async function ol(t,e){let r="",n="",s=0,i=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return _(`bash: \`${e.variable}': not a valid identifier
539
+ `);let a=[];if(e.words===null)a=(t.state.env["@"]||"").split(" ").filter(Boolean);else if(e.words.length===0)a=[];else for(let o of e.words){let c=await Ot(t,o);a.push(...c.values)}t.state.loopDepth++;try{for(let o of a){i++,i>t.limits.maxLoopIterations&&We(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),t.state.env[e.variable]=o;try{for(let c of e.body){let l=await t.executeStatement(c);r+=l.stdout,n+=l.stderr,s=l.exitCode}}catch(c){let l=Dt(c,r,n,t.state.loopDepth);if(r=l.stdout,n=l.stderr,l.action==="break")break;if(l.action==="continue")continue;if(l.action==="error")return $(r,n,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return $(r,n,s)}async function ll(t,e){let r="",n="",s=0,i=0;e.init&&await Z(t,e.init.expression),t.state.loopDepth++;try{for(;i++,i>t.limits.maxLoopIterations&&We(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),!(e.condition&&await Z(t,e.condition.expression)===0);){try{for(let a of e.body){let o=await t.executeStatement(a);r+=o.stdout,n+=o.stderr,s=o.exitCode}}catch(a){let o=Dt(a,r,n,t.state.loopDepth);if(r=o.stdout,n=o.stderr,o.action==="break")break;if(o.action==="continue"){e.update&&await Z(t,e.update.expression);continue}if(o.action==="error")return $(r,n,o.exitCode??1);throw o.error}e.update&&await Z(t,e.update.expression)}}finally{t.state.loopDepth--}return $(r,n,s)}async function cl(t,e,r=""){let n="",s="",i=0,a=0,o=r;for(let l of e.redirections)if((l.operator==="<<"||l.operator==="<<-")&&l.target.type==="HereDoc"){let u=l.target,f=await X(t,u.content);u.stripTabs&&(f=f.split(`
540
540
  `).map(d=>d.replace(/^\t+/,"")).join(`
541
- `)),o=f}else if(l.operator==="<<<"&&l.target.type==="Word")o=`${await Q(t,l.target)}
542
- `;else if(l.operator==="<"&&l.target.type==="Word")try{let u=await Q(t,l.target),f=t.fs.resolvePath(t.state.cwd,u);o=await t.fs.readFile(f)}catch{let u=await Q(t,l.target);return F(`bash: ${u}: No such file or directory
543
- `)}let c=t.state.groupStdin;o&&(t.state.groupStdin=o),t.state.loopDepth++;try{for(;;){a++,a>t.limits.maxLoopIterations&&_e(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,s);let l=0,u=!1,f=!1,d=t.state.inCondition;t.state.inCondition=!0;try{for(let h of e.condition){let p=await t.executeStatement(h);n+=p.stdout,s+=p.stderr,l=p.exitCode}}catch(h){if(h instanceof ce){if(n+=h.stdout,s+=h.stderr,h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=n,h.stderr=s,t.state.inCondition=d,h;u=!0}else if(h instanceof pe){if(n+=h.stdout,s+=h.stderr,h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=n,h.stderr=s,t.state.inCondition=d,h;f=!0}else throw t.state.inCondition=d,h}finally{t.state.inCondition=d}if(u)break;if(!f){if(l!==0)break;try{for(let h of e.body){let p=await t.executeStatement(h);n+=p.stdout,s+=p.stderr,i=p.exitCode}}catch(h){let p=Pt(h,n,s,t.state.loopDepth);if(n=p.stdout,s=p.stderr,p.action==="break")break;if(p.action==="continue")continue;if(p.action==="error")return $(n,s,p.exitCode??1);throw p.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=c}return $(n,s,i)}async function al(t,e){let r="",n="",s=0,i=0;t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&_e(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let a=await es(t,e.condition);if(r+=a.stdout,n+=a.stderr,a.exitCode===0)break;try{for(let o of e.body){let c=await t.executeStatement(o);r+=c.stdout,n+=c.stderr,s=c.exitCode}}catch(o){let c=Pt(o,r,n,t.state.loopDepth);if(r=c.stdout,n=c.stderr,c.action==="break")break;if(c.action==="continue")continue;if(c.action==="error")return $(r,n,c.exitCode??1);throw c.error}}}finally{t.state.loopDepth--}return $(r,n,s)}async function ol(t,e){let r="",n="",s=0,i=await Q(t,e.word),a=!1;for(let o=0;o<e.items.length;o++){let c=e.items[o],l=a;if(!a)for(let u of c.patterns){let f=await Q(t,u);if(Lo(u)&&(f=To(f)),br(i,f)){l=!0;break}}if(l){let u=await Nr(t,c.body,r,n);if(r=u.stdout,n=u.stderr,s=u.exitCode,c.terminator===";;")break;c.terminator===";&"?a=!0:a=!1}else a=!1}return $(r,n,s)}X();X();function ll(t,e){return t.state.functions.set(e.name,e),G}async function cl(t,e,r){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,_e(`${e.name}: maximum recursion depth (${t.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),t.state.localScopes.push(new Map);let n={};for(let i=0;i<r.length;i++)n[String(i+1)]=t.state.env[String(i+1)],t.state.env[String(i+1)]=r[i];n["@"]=t.state.env["@"],n["#"]=t.state.env["#"],t.state.env["@"]=r.join(" "),t.state.env["#"]=String(r.length);let s=()=>{let i=t.state.localScopes.pop();if(i)for(let[a,o]of i)o===void 0?delete t.state.env[a]:t.state.env[a]=o;for(let[a,o]of Object.entries(n))o===void 0?delete t.state.env[a]:t.state.env[a]=o;t.state.callDepth--};try{let i=await t.executeCommand(e.body,"");return s(),i}catch(i){if(s(),i instanceof ue)return $(i.stdout,i.stderr,i.exitCode);throw i}}ke();async function ul(t,e,r){let{stdout:n,stderr:s,exitCode:i}=e;for(let a of r){if(a.target.type==="HereDoc")continue;let o=await Q(t,a.target);switch(a.operator){case">":{let c=a.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${o}: Is a directory
541
+ `)),o=f}else if(l.operator==="<<<"&&l.target.type==="Word")o=`${await X(t,l.target)}
542
+ `;else if(l.operator==="<"&&l.target.type==="Word")try{let u=await X(t,l.target),f=t.fs.resolvePath(t.state.cwd,u);o=await t.fs.readFile(f)}catch{let u=await X(t,l.target);return _(`bash: ${u}: No such file or directory
543
+ `)}let c=t.state.groupStdin;o&&(t.state.groupStdin=o),t.state.loopDepth++;try{for(;;){a++,a>t.limits.maxLoopIterations&&We(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,s);let l=0,u=!1,f=!1,d=t.state.inCondition;t.state.inCondition=!0;try{for(let h of e.condition){let p=await t.executeStatement(h);n+=p.stdout,s+=p.stderr,l=p.exitCode}}catch(h){if(h instanceof ue){if(n+=h.stdout,s+=h.stderr,h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=n,h.stderr=s,t.state.inCondition=d,h;u=!0}else if(h instanceof ye){if(n+=h.stdout,s+=h.stderr,h.levels>1&&t.state.loopDepth>1)throw h.levels--,h.stdout=n,h.stderr=s,t.state.inCondition=d,h;f=!0}else throw t.state.inCondition=d,h}finally{t.state.inCondition=d}if(u)break;if(!f){if(l!==0)break;try{for(let h of e.body){let p=await t.executeStatement(h);n+=p.stdout,s+=p.stderr,i=p.exitCode}}catch(h){let p=Dt(h,n,s,t.state.loopDepth);if(n=p.stdout,s=p.stderr,p.action==="break")break;if(p.action==="continue")continue;if(p.action==="error")return $(n,s,p.exitCode??1);throw p.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=c}return $(n,s,i)}async function ul(t,e){let r="",n="",s=0,i=0;t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&We(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let a=await ns(t,e.condition);if(r+=a.stdout,n+=a.stderr,a.exitCode===0)break;try{for(let o of e.body){let c=await t.executeStatement(o);r+=c.stdout,n+=c.stderr,s=c.exitCode}}catch(o){let c=Dt(o,r,n,t.state.loopDepth);if(r=c.stdout,n=c.stderr,c.action==="break")break;if(c.action==="continue")continue;if(c.action==="error")return $(r,n,c.exitCode??1);throw c.error}}}finally{t.state.loopDepth--}return $(r,n,s)}async function fl(t,e){let r="",n="",s=0,i=await X(t,e.word),a=!1;for(let o=0;o<e.items.length;o++){let c=e.items[o],l=a;if(!a)for(let u of c.patterns){let f=await X(t,u);if(_o(u)&&(f=Wo(f)),Cr(i,f)){l=!0;break}}if(l){let u=await $r(t,c.body,r,n);if(r=u.stdout,n=u.stderr,s=u.exitCode,c.terminator===";;")break;c.terminator===";&"?a=!0:a=!1}else a=!1}return $(r,n,s)}Y();Y();function dl(t,e){return t.state.functions.set(e.name,e),q}async function hl(t,e,r){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,We(`${e.name}: maximum recursion depth (${t.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),t.state.localScopes.push(new Map);let n={};for(let i=0;i<r.length;i++)n[String(i+1)]=t.state.env[String(i+1)],t.state.env[String(i+1)]=r[i];n["@"]=t.state.env["@"],n["#"]=t.state.env["#"],t.state.env["@"]=r.join(" "),t.state.env["#"]=String(r.length);let s=()=>{let i=t.state.localScopes.pop();if(i)for(let[a,o]of i)o===void 0?delete t.state.env[a]:t.state.env[a]=o;for(let[a,o]of Object.entries(n))o===void 0?delete t.state.env[a]:t.state.env[a]=o;t.state.callDepth--};try{let i=await t.executeCommand(e.body,"");return s(),i}catch(i){if(s(),i instanceof fe)return $(i.stdout,i.stderr,i.exitCode);throw i}}Ie();async function pl(t,e,r){let{stdout:n,stderr:s,exitCode:i}=e;for(let a of r){if(a.target.type==="HereDoc")continue;let o=await X(t,a.target);switch(a.operator){case">":{let c=a.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${o}: Is a directory
544
544
  `,i=1,n="";break}}catch{}await t.fs.writeFile(l,n),n=""}else if(c===2)if(o==="/dev/null")s="";else{let l=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${o}: Is a directory
545
545
  `,i=1;break}}catch{}await t.fs.writeFile(l,s),s=""}break}case">>":{let c=a.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${o}: Is a directory
546
546
  `,i=1,n="";break}}catch{}await t.fs.appendFile(l,n),n=""}else if(c===2){let l=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${o}: Is a directory
547
547
  `,i=1;break}}catch{}await t.fs.appendFile(l,s),s=""}break}case">&":{let c=a.fd??1;o==="2"||o==="&2"?c===1&&(s+=n,n=""):(o==="1"||o==="&1")&&(n+=s,s="");break}case"&>":{let c=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(c)).isDirectory){s=`bash: ${o}: Is a directory
548
548
  `,i=1,n="";break}}catch{}await t.fs.writeFile(c,n+s),n="",s="";break}case"&>>":{let c=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(c)).isDirectory){s=`bash: ${o}: Is a directory
549
- `,i=1,n="";break}}catch{}await t.fs.appendFile(c,n+s),n="",s="";break}}}return $(n,s,i)}var Ot=class{ctx;constructor(e,r){this.ctx={state:r,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep}}async executeScript(e){let r="",n="",s=0;for(let i of e.statements)try{let a=await this.executeStatement(i);r+=a.stdout,n+=a.stderr,s=a.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}catch(a){if(a instanceof Z)throw a.prependOutput(r,n),a;if(a instanceof W)throw a;if(a instanceof Re)return r+=a.stdout,n+=a.stderr,s=a.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}};if(a instanceof Se)return r+=a.stdout,n+=a.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}};if(a instanceof De)return r+=a.stdout,n+=a.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}};if(a instanceof ce||a instanceof pe){if(this.ctx.state.loopDepth>0)throw a.prependOutput(r,n),a;r+=a.stdout,n+=a.stderr;continue}throw a instanceof ue&&a.prependOutput(r,n),a}return{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&_e(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let r="",n="",s=0,i=-1,a=!1;for(let o=0;o<e.pipelines.length;o++){let c=e.pipelines[o],l=o>0?e.operators[o-1]:null;if(l==="&&"&&s!==0||l==="||"&&s===0)continue;let u=await this.executePipeline(c);r+=u.stdout,n+=u.stderr,s=u.exitCode,i=o,a=c.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}if(this.ctx.state.options.errexit&&s!==0&&i===e.pipelines.length-1&&!a&&!this.ctx.state.inCondition)throw new Re(s,r,n);return $(r,n,s)}async executePipeline(e){let r="",n=G,s=0,i=[];for(let a=0;a<e.commands.length;a++){let o=e.commands[a],c=a===e.commands.length-1,l;try{l=await this.executeCommand(o,r)}catch(u){if(u instanceof De)l={stdout:u.stdout,stderr:u.stderr,exitCode:1};else if(u instanceof Z&&e.commands.length>1)l={stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode};else throw u}i.push(l.exitCode),l.exitCode!==0&&(s=l.exitCode),c?n=l:(r=l.stdout,n={stdout:"",stderr:l.stderr,exitCode:l.exitCode})}for(let a of Object.keys(this.ctx.state.env))a.startsWith("PIPESTATUS_")&&delete this.ctx.state.env[a];for(let a=0;a<i.length;a++)this.ctx.state.env[`PIPESTATUS_${a}`]=String(i[a]);return this.ctx.state.env.PIPESTATUS__length=String(i.length),this.ctx.state.options.pipefail&&s!==0&&(n={...n,exitCode:s}),e.negated&&(n={...n,exitCode:n.exitCode===0?1:0}),n}async executeCommand(e,r){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,r);case"If":return rl(this.ctx,e);case"For":return nl(this.ctx,e);case"CStyleFor":return sl(this.ctx,e);case"While":return il(this.ctx,e,r);case"Until":return al(this.ctx,e);case"Case":return ol(this.ctx,e);case"Subshell":return this.executeSubshell(e,r);case"Group":return this.executeGroup(e,r);case"FunctionDef":return ll(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return G}}async executeSimpleCommand(e,r){try{return await this.executeSimpleCommandInner(e,r)}catch(n){if(n instanceof te)return F(n.stderr);throw n}}async executeSimpleCommandInner(e,r){this.ctx.state.expansionStderr="";let n={};for(let c of e.assignments){let l=c.name;if(c.array){if(/\[.+\]$/.test(l))return $("",`bash: ${l}: cannot assign list to array member
550
- `,1);let b=qe(this.ctx,l);if(b)return b;let w=[];for(let E of c.array){let x=await $t(this.ctx,E);w.push(...x.values)}let g=0;if(c.append){let E=ie(this.ctx,l);E.length>0&&(g=Math.max(...E.map(([S])=>typeof S=="number"?S:0))+1)}else{let E=`${l}_`;for(let x of Object.keys(this.ctx.state.env))x.startsWith(E)&&!x.includes("__")&&delete this.ctx.state.env[x]}for(let E=0;E<w.length;E++)this.ctx.state.env[`${l}_${g+E}`]=w[E];c.append||(this.ctx.state.env[`${l}__length`]=String(w.length));continue}let u=c.value?await Q(this.ctx,c.value):"";if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return $("",`bash: ${l}: bad array subscript
551
- `,1);let d=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let b=d[1],w=d[2],g=qe(this.ctx,b);if(g)return g;let E=this.ctx.state.associativeArrays?.has(b),x;if(E){let v;if(w.startsWith("'")&&w.endsWith("'"))v=w.slice(1,-1);else if(w.startsWith('"')&&w.endsWith('"')){let R=w.slice(1,-1),_=new le().parseWordFromString(R,!0,!1);v=await Q(this.ctx,_)}else if(w.includes("$")){let M=new le().parseWordFromString(w,!1,!1);v=await Q(this.ctx,M)}else v=w;x=`${b}_${v}`}else{let v;if(/^-?\d+$/.test(w))v=Number.parseInt(w,10);else{try{let R=new le,M=se(R,w);v=j(this.ctx,M.expression)}catch{let R=this.ctx.state.env[w];v=R?Number.parseInt(R,10):0}Number.isNaN(v)&&(v=0)}if(v<0){let R=ie(this.ctx,b);if(R.length===0)return $("",`bash: ${b}[${w}]: bad array subscript
552
- `,1);if(v=Math.max(...R.map(([_])=>typeof _=="number"?_:0))+1+v,v<0)return $("",`bash: ${b}[${w}]: bad array subscript
553
- `,1)}x=`${b}_${v}`}let S=c.append?(this.ctx.state.env[x]||"")+u:u;e.name?(n[x]=this.ctx.state.env[x],this.ctx.state.env[x]=S):this.ctx.state.env[x]=S;continue}let h=qe(this.ctx,l);if(h)return h;let p=c.append?(this.ctx.state.env[l]||"")+u:u;e.name?(n[l]=this.ctx.state.env[l],this.ctx.state.env[l]=p):this.ctx.state.env[l]=p}if(!e.name)return $("","",this.ctx.state.lastExitCode);for(let c of e.redirections){if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let l=c.target,u=await Q(this.ctx,l.content);l.stripTabs&&(u=u.split(`
549
+ `,i=1,n="";break}}catch{}await t.fs.appendFile(c,n+s),n="",s="";break}}}return $(n,s,i)}var Tt=class{ctx;constructor(e,r){this.ctx={state:r,fs:e.fs,commands:e.commands,limits:e.limits,execFn:e.exec,executeScript:this.executeScript.bind(this),executeStatement:this.executeStatement.bind(this),executeCommand:this.executeCommand.bind(this),fetch:e.fetch,sleep:e.sleep}}async executeScript(e){let r="",n="",s=0;for(let i of e.statements)try{let a=await this.executeStatement(i);r+=a.stdout,n+=a.stderr,s=a.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}catch(a){if(a instanceof K)throw a.prependOutput(r,n),a;if(a instanceof B)throw a;if(a instanceof Re)return r+=a.stdout,n+=a.stderr,s=a.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}};if(a instanceof Ce)return r+=a.stdout,n+=a.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}};if(a instanceof Te)return r+=a.stdout,n+=a.stderr,s=1,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}};if(a instanceof ue||a instanceof ye){if(this.ctx.state.loopDepth>0)throw a.prependOutput(r,n),a;r+=a.stdout,n+=a.stderr;continue}throw a instanceof fe&&a.prependOutput(r,n),a}return{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}}}async executeStatement(e){this.ctx.state.commandCount++,this.ctx.state.commandCount>this.ctx.limits.maxCommandCount&&We(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let r="",n="",s=0,i=-1,a=!1;for(let o=0;o<e.pipelines.length;o++){let c=e.pipelines[o],l=o>0?e.operators[o-1]:null;if(l==="&&"&&s!==0||l==="||"&&s===0)continue;let u=await this.executePipeline(c);r+=u.stdout,n+=u.stderr,s=u.exitCode,i=o,a=c.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}if(this.ctx.state.options.errexit&&s!==0&&i===e.pipelines.length-1&&!a&&!this.ctx.state.inCondition)throw new Re(s,r,n);return $(r,n,s)}async executePipeline(e){let r="",n=q,s=0,i=[];for(let a=0;a<e.commands.length;a++){let o=e.commands[a],c=a===e.commands.length-1,l;try{l=await this.executeCommand(o,r)}catch(u){if(u instanceof Te)l={stdout:u.stdout,stderr:u.stderr,exitCode:1};else if(u instanceof K&&e.commands.length>1)l={stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode};else throw u}i.push(l.exitCode),l.exitCode!==0&&(s=l.exitCode),c?n=l:(r=l.stdout,n={stdout:"",stderr:l.stderr,exitCode:l.exitCode})}for(let a of Object.keys(this.ctx.state.env))a.startsWith("PIPESTATUS_")&&delete this.ctx.state.env[a];for(let a=0;a<i.length;a++)this.ctx.state.env[`PIPESTATUS_${a}`]=String(i[a]);return this.ctx.state.env.PIPESTATUS__length=String(i.length),this.ctx.state.options.pipefail&&s!==0&&(n={...n,exitCode:s}),e.negated&&(n={...n,exitCode:n.exitCode===0?1:0}),n}async executeCommand(e,r){switch(e.type){case"SimpleCommand":return this.executeSimpleCommand(e,r);case"If":return al(this.ctx,e);case"For":return ol(this.ctx,e);case"CStyleFor":return ll(this.ctx,e);case"While":return cl(this.ctx,e,r);case"Until":return ul(this.ctx,e);case"Case":return fl(this.ctx,e);case"Subshell":return this.executeSubshell(e,r);case"Group":return this.executeGroup(e,r);case"FunctionDef":return dl(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return q}}async executeSimpleCommand(e,r){try{return await this.executeSimpleCommandInner(e,r)}catch(n){if(n instanceof ne)return _(n.stderr);throw n}}async executeSimpleCommandInner(e,r){this.ctx.state.expansionStderr="";let n={};for(let c of e.assignments){let l=c.name;if(c.array){if(/\[.+\]$/.test(l))return $("",`bash: ${l}: cannot assign list to array member
550
+ `,1);let E=Ze(this.ctx,l);if(E)return E;let w=[];for(let b of c.array){let S=await Ot(this.ctx,b);w.push(...S.values)}let g=0;if(c.append){let b=ae(this.ctx,l);b.length>0&&(g=Math.max(...b.map(([x])=>typeof x=="number"?x:0))+1)}else{let b=`${l}_`;for(let S of Object.keys(this.ctx.state.env))S.startsWith(b)&&!S.includes("__")&&delete this.ctx.state.env[S]}for(let b=0;b<w.length;b++)this.ctx.state.env[`${l}_${g+b}`]=w[b];c.append||(this.ctx.state.env[`${l}__length`]=String(w.length));continue}let u=c.value?await X(this.ctx,c.value):"";if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return $("",`bash: ${l}: bad array subscript
551
+ `,1);let d=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let E=d[1],w=d[2],g=Ze(this.ctx,E);if(g)return g;let b=this.ctx.state.associativeArrays?.has(E),S;if(b){let A;if(w.startsWith("'")&&w.endsWith("'"))A=w.slice(1,-1);else if(w.startsWith('"')&&w.endsWith('"')){let O=w.slice(1,-1),R=new le().parseWordFromString(O,!0,!1);A=await X(this.ctx,R)}else if(w.includes("$")){let L=new le().parseWordFromString(w,!1,!1);A=await X(this.ctx,L)}else A=w;S=`${E}_${A}`}else{let A;if(/^-?\d+$/.test(w))A=Number.parseInt(w,10);else{try{let O=new le,L=ie(O,w);A=V(this.ctx,L.expression)}catch{let O=this.ctx.state.env[w];A=O?Number.parseInt(O,10):0}Number.isNaN(A)&&(A=0)}if(A<0){let O=ae(this.ctx,E);if(O.length===0)return $("",`bash: ${E}[${w}]: bad array subscript
552
+ `,1);if(A=Math.max(...O.map(([R])=>typeof R=="number"?R:0))+1+A,A<0)return $("",`bash: ${E}[${w}]: bad array subscript
553
+ `,1)}S=`${E}_${A}`}let x=c.append?(this.ctx.state.env[S]||"")+u:u;e.name?(n[S]=this.ctx.state.env[S],this.ctx.state.env[S]=x):this.ctx.state.env[S]=x;continue}let h=Ze(this.ctx,l);if(h)return h;let p=c.append?(this.ctx.state.env[l]||"")+u:u;e.name?(n[l]=this.ctx.state.env[l],this.ctx.state.env[l]=p):this.ctx.state.env[l]=p}if(!e.name)return $("","",this.ctx.state.lastExitCode);for(let c of e.redirections){if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let l=c.target,u=await X(this.ctx,l.content);l.stripTabs&&(u=u.split(`
554
554
  `).map(f=>f.replace(/^\t+/,"")).join(`
555
- `)),r=u;continue}if(c.operator==="<<<"&&c.target.type==="Word"){r=`${await Q(this.ctx,c.target)}
556
- `;continue}if(c.operator==="<"&&c.target.type==="Word")try{let l=await Q(this.ctx,c.target),u=this.ctx.fs.resolvePath(this.ctx.state.cwd,l);r=await this.ctx.fs.readFile(u)}catch{let l=await Q(this.ctx,c.target);for(let[u,f]of Object.entries(n))f===void 0?delete this.ctx.state.env[u]:this.ctx.state.env[u]=f;return F(`bash: ${l}: No such file or directory
557
- `)}}let s=await Q(this.ctx,e.name),i=[],a=[];for(let c of e.args){let l=await $t(this.ctx,c);for(let u of l.values)i.push(u),a.push(l.quoted)}if(!s){if(e.name.parts.every(l=>l.type==="CommandSubstitution"||l.type==="ParameterExpansion"||l.type==="ArithmeticExpansion")){if(i.length>0){let l=i.shift();return a.shift(),await this.runCommand(l,i,a,r)}return $("","",this.ctx.state.lastExitCode)}return F(`bash: : command not found
558
- `,127)}let o=await this.runCommand(s,i,a,r);o=await ul(this.ctx,o,e.redirections),this.ctx.state.lastArg=i.length>0?i[i.length-1]:s;for(let[c,l]of Object.entries(n))l===void 0?delete this.ctx.state.env[c]:this.ctx.state.env[c]=l;return this.ctx.state.expansionStderr&&(o={...o,stderr:this.ctx.state.expansionStderr+o.stderr},this.ctx.state.expansionStderr=""),o}async runCommand(e,r,n,s,i=!1){if(e==="cd")return await Ln(this.ctx,r);if(e==="export")return Hn(this.ctx,r);if(e==="unset")return Kn(this.ctx,r);if(e==="exit")return Bn(this.ctx,r);if(e==="local")return zn(this.ctx,r);if(e==="set")return Vn(this.ctx,r);if(e==="break")return Dn(this.ctx,r);if(e==="continue")return Tn(this.ctx,r);if(e==="return")return jn(this.ctx,r);if(e==="eval")return Wn(this.ctx,r);if(e==="shift")return Zn(this.ctx,r);if(e==="source"||e===".")return Qn(this.ctx,r);if(e==="read")return Gn(this.ctx,r,s);if(e==="declare"||e==="typeset")return Mn(this.ctx,r);if(e==="readonly")return _n(this.ctx,r);if(!i){let u=this.ctx.state.functions.get(e);if(u)return cl(this.ctx,u,r)}if(e===":"||e==="true")return G;if(e==="false")return re(!1);if(e==="let")return Un(this.ctx,r);if(e==="command"){if(r.length===0)return G;let u=r;for(;u.length>0&&u[0].startsWith("-");)u=u.slice(1);if(u.length===0)return G;let[f,...d]=u;return this.runCommand(f,d,[],s,!0)}if(e==="builtin"){if(r.length===0)return G;let[u,...f]=r;return this.runCommand(u,f,[],s)}if(e==="shopt")return G;if(e==="exec"){if(r.length===0)return G;let[u,...f]=r;return this.runCommand(u,f,[],s)}if(e==="wait")return G;if(e==="type")return this.handleType(r);if(e==="[["){let u=r.lastIndexOf("]]");if(u!==-1){let f=r.slice(0,u);return yt(this.ctx,f)}return F("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let u=r;if(e==="["){if(r[r.length-1]!=="]")return F("[: missing `]'\n",2);u=r.slice(0,-1)}return yt(this.ctx,u)}let a=await this.resolveCommand(e);if(!a)return F(`bash: ${e}: command not found
559
- `,127);let{cmd:o,path:c}=a,l={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:s,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep};try{return await o.execute(r,l)}catch(u){return F(`${e}: ${Y(u)}
555
+ `)),r=u;continue}if(c.operator==="<<<"&&c.target.type==="Word"){r=`${await X(this.ctx,c.target)}
556
+ `;continue}if(c.operator==="<"&&c.target.type==="Word")try{let l=await X(this.ctx,c.target),u=this.ctx.fs.resolvePath(this.ctx.state.cwd,l);r=await this.ctx.fs.readFile(u)}catch{let l=await X(this.ctx,c.target);for(let[u,f]of Object.entries(n))f===void 0?delete this.ctx.state.env[u]:this.ctx.state.env[u]=f;return _(`bash: ${l}: No such file or directory
557
+ `)}}let s=await X(this.ctx,e.name),i=[],a=[];for(let c of e.args){let l=await Ot(this.ctx,c);for(let u of l.values)i.push(u),a.push(l.quoted)}if(!s){if(e.name.parts.every(l=>l.type==="CommandSubstitution"||l.type==="ParameterExpansion"||l.type==="ArithmeticExpansion")){if(i.length>0){let l=i.shift();return a.shift(),await this.runCommand(l,i,a,r)}return $("","",this.ctx.state.lastExitCode)}return _(`bash: : command not found
558
+ `,127)}let o=await this.runCommand(s,i,a,r);o=await pl(this.ctx,o,e.redirections),this.ctx.state.lastArg=i.length>0?i[i.length-1]:s;for(let[c,l]of Object.entries(n))l===void 0?delete this.ctx.state.env[c]:this.ctx.state.env[c]=l;return this.ctx.state.expansionStderr&&(o={...o,stderr:this.ctx.state.expansionStderr+o.stderr},this.ctx.state.expansionStderr=""),o}async runCommand(e,r,n,s,i=!1){if(e==="cd")return await Mn(this.ctx,r);if(e==="export")return Gn(this.ctx,r);if(e==="unset")return Jn(this.ctx,r);if(e==="exit")return zn(this.ctx,r);if(e==="local")return qn(this.ctx,r);if(e==="set")return Kn(this.ctx,r);if(e==="break")return Fn(this.ctx,r);if(e==="continue")return _n(this.ctx,r);if(e==="return")return Zn(this.ctx,r);if(e==="eval")return Un(this.ctx,r);if(e==="shift")return Xn(this.ctx,r);if(e==="source"||e===".")return Yn(this.ctx,r);if(e==="read")return Vn(this.ctx,r,s);if(e==="declare"||e==="typeset")return Bn(this.ctx,r);if(e==="readonly")return Hn(this.ctx,r);if(!i){let u=this.ctx.state.functions.get(e);if(u)return hl(this.ctx,u,r)}if(e===":"||e==="true")return q;if(e==="false")return se(!1);if(e==="let")return jn(this.ctx,r);if(e==="command"){if(r.length===0)return q;let u=r;for(;u.length>0&&u[0].startsWith("-");)u=u.slice(1);if(u.length===0)return q;let[f,...d]=u;return this.runCommand(f,d,[],s,!0)}if(e==="builtin"){if(r.length===0)return q;let[u,...f]=r;return this.runCommand(u,f,[],s)}if(e==="shopt")return q;if(e==="exec"){if(r.length===0)return q;let[u,...f]=r;return this.runCommand(u,f,[],s)}if(e==="wait")return q;if(e==="type")return this.handleType(r);if(e==="[["){let u=r.lastIndexOf("]]");if(u!==-1){let f=r.slice(0,u);return Et(this.ctx,f)}return _("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let u=r;if(e==="["){if(r[r.length-1]!=="]")return _("[: missing `]'\n",2);u=r.slice(0,-1)}return Et(this.ctx,u)}let a=await this.resolveCommand(e);if(!a)return _(`bash: ${e}: command not found
559
+ `,127);let{cmd:o,path:c}=a,l={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:s,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep};try{return await o.execute(r,l)}catch(u){return _(`${e}: ${J(u)}
560
560
  `)}}async resolveCommand(e){if(e.includes("/")){let i=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);if(!await this.ctx.fs.exists(i))return null;let a=i.split("/").pop()||e,o=this.ctx.commands.get(a);return o?{cmd:o,path:i}:null}let n=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let i of n){if(!i)continue;let a=`${i}/${e}`;if(await this.ctx.fs.exists(a)){let o=this.ctx.commands.get(e);if(o)return{cmd:o,path:a}}}if(!await this.ctx.fs.exists("/bin")){let i=this.ctx.commands.get(e);if(i)return{cmd:i,path:`/bin/${e}`}}return null}async findCommandInPath(e){let r=[],s=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let i of s){if(!i)continue;let a=`${i}/${e}`;await this.ctx.fs.exists(a)&&r.push(a)}return r}handleType(e){let r=new Set(["if","then","else","elif","fi","case","esac","for","select","while","until","do","done","in","function","{","}","time","[[","]]","!"]),n=new Set(["cd","export","unset","exit","local","set","break","continue","return","eval","shift","source",".","read","declare","typeset","readonly",":","true","false","let","command","builtin","shopt","exec","wait","type","[","test"]),s="",i="",a=0;for(let o of e)r.has(o)?s+=`${o} is a shell keyword
561
561
  `:n.has(o)?s+=`${o} is a shell builtin
562
562
  `:this.ctx.state.functions.has(o)?s+=`${o} is a function
563
563
  `:this.ctx.commands.has(o)?s+=`${o} is /bin/${o}
564
564
  `:(i+=`bash: type: ${o}: not found
565
- `,a=1);return $(s,i,a)}async executeSubshell(e,r=""){let n={...this.ctx.state.env},s=this.ctx.state.cwd,i=this.ctx.state.loopDepth,a=this.ctx.state.parentHasLoopContext;this.ctx.state.parentHasLoopContext=i>0,this.ctx.state.loopDepth=0;let o=this.ctx.state.groupStdin;r&&(this.ctx.state.groupStdin=r);let c="",l="",u=0;try{for(let f of e.body){let d=await this.executeStatement(f);c+=d.stdout,l+=d.stderr,u=d.exitCode}}catch(f){if(this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=i,this.ctx.state.parentHasLoopContext=a,this.ctx.state.groupStdin=o,f instanceof W)throw f;if(f instanceof $e)return c+=f.stdout,l+=f.stderr,$(c,l,0);if(f instanceof ce||f instanceof pe)return c+=f.stdout,l+=f.stderr,$(c,l,0);if(f instanceof Z)return c+=f.stdout,l+=f.stderr,$(c,l,f.exitCode);if(f instanceof ue)return c+=f.stdout,l+=f.stderr,$(c,l,f.exitCode);if(f instanceof Re)throw f.stdout=c+f.stdout,f.stderr=l+f.stderr,f;return $(c,`${l}${Y(f)}
566
- `,1)}return this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=i,this.ctx.state.parentHasLoopContext=a,this.ctx.state.groupStdin=o,$(c,l,u)}async executeGroup(e,r=""){let n="",s="",i=0,a=this.ctx.state.groupStdin;r&&(this.ctx.state.groupStdin=r);try{for(let o of e.body){let c=await this.executeStatement(o);n+=c.stdout,s+=c.stderr,i=c.exitCode}}catch(o){if(this.ctx.state.groupStdin=a,o instanceof W)throw o;if(zt(o)||o instanceof Re||o instanceof Z)throw o.prependOutput(n,s),o;return $(n,`${s}${Y(o)}
567
- `,1)}return this.ctx.state.groupStdin=a,$(n,s,i)}async executeArithmeticCommand(e){try{let r=await q(this.ctx,e.expression.expression);return re(r!==0)}catch(r){return F(`bash: arithmetic expression: ${r.message}
568
- `)}}async executeConditionalCommand(e){try{let r=await Ve(this.ctx,e.expression);return re(r)}catch(r){return F(`bash: conditional expression: ${r.message}
569
- `,2)}}};var gt={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4};function fl(t){return t?{maxCallDepth:t.maxCallDepth??gt.maxCallDepth,maxCommandCount:t.maxCommandCount??gt.maxCommandCount,maxLoopIterations:t.maxLoopIterations??gt.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??gt.maxAwkIterations,maxSedIterations:t.maxSedIterations??gt.maxSedIterations}:{...gt}}function dl(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function uh(t){let e=dl(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function fh(t,e){let r=dl(t);if(!r)return!1;let n=uh(e);return!n||r.origin!==n.origin?!1:n.pathPrefix==="/"||n.pathPrefix===""?!0:r.pathname.startsWith(n.pathPrefix)}function ts(t,e){return!e||e.length===0?!1:e.some(r=>fh(t,r))}var Dt=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},Lt=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},Tt=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},vr=class extends Error{constructor(e,r){super(`HTTP method '${e}' not allowed. Allowed methods: ${r.join(", ")}`),this.name="MethodNotAllowedError"}};var dh=20,hh=3e4,ph=["GET","HEAD"],mh=new Set(["GET","HEAD","OPTIONS"]),yh=new Set([301,302,303,307,308]);function rs(t){let e=t.maxRedirects??dh,r=t.timeoutMs??hh,n=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??ph;function s(o){if(!t.dangerouslyAllowFullInternetAccess&&!ts(o,t.allowedUrlPrefixes??[]))throw new Dt(o)}function i(o){if(t.dangerouslyAllowFullInternetAccess)return;let c=o.toUpperCase();if(!n.includes(c))throw new vr(c,n)}async function a(o,c={}){let l=c.method?.toUpperCase()??"GET";s(o),i(l);let u=o,f=0,d=c.followRedirects??!0,h=c.timeoutMs!==void 0?Math.min(c.timeoutMs,r):r;for(;;){let p=new AbortController,b=setTimeout(()=>p.abort(),h);try{let w={method:l,headers:c.headers,signal:p.signal,redirect:"manual"};c.body&&!mh.has(l)&&(w.body=c.body);let g=await fetch(u,w);if(yh.has(g.status)&&d){let E=g.headers.get("location");if(!E)return await hl(g,u);let x=new URL(E,u).href;if(!t.dangerouslyAllowFullInternetAccess&&!ts(x,t.allowedUrlPrefixes??[]))throw new Tt(x);if(f++,f>e)throw new Lt(e);u=x;continue}return await hl(g,u)}finally{clearTimeout(b)}}}return a}async function hl(t,e){let r={};return t.headers.forEach((n,s)=>{r[s.toLowerCase()]=n}),{status:t.status,statusText:t.statusText,headers:r,body:await t.text(),url:e}}var kr=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;logger;state;constructor(e={}){let r=e.fs??new et(e.files);this.fs=r,this.useDefaultLayout=!e.cwd&&!e.files;let n=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s={HOME:this.useDefaultLayout?"/home/user":"/",PATH:"/bin:/usr/bin",IFS:`
570
- `,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:n,OLDPWD:n,...e.env};if(this.limits=fl({...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=rs(e.network)),this.sleepFn=e.sleep,this.logger=e.logger,this.state={env:s,cwd:n,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1},inCondition:!1,loopDepth:0},r instanceof et)try{r.mkdirSync("/bin",{recursive:!0}),r.mkdirSync("/usr/bin",{recursive:!0}),this.useDefaultLayout&&(r.mkdirSync("/home/user",{recursive:!0}),r.mkdirSync("/tmp",{recursive:!0}))}catch{}if(n!=="/"&&r instanceof et)try{r.mkdirSync(n,{recursive:!0})}catch{}for(let i of Za(e.commands))this.registerCommand(i);if(e.network)for(let i of Qa())this.registerCommand(i);if(e.customCommands)for(let i of e.customCommands)Ka(i)?this.registerCommand(Xa(i)):this.registerCommand(i)}registerCommand(e){if(this.commands.set(e.name,e),this.fs instanceof et)try{this.fs.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
565
+ `,a=1);return $(s,i,a)}async executeSubshell(e,r=""){let n={...this.ctx.state.env},s=this.ctx.state.cwd,i=this.ctx.state.loopDepth,a=this.ctx.state.parentHasLoopContext;this.ctx.state.parentHasLoopContext=i>0,this.ctx.state.loopDepth=0;let o=this.ctx.state.groupStdin;r&&(this.ctx.state.groupStdin=r);let c="",l="",u=0;try{for(let f of e.body){let d=await this.executeStatement(f);c+=d.stdout,l+=d.stderr,u=d.exitCode}}catch(f){if(this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=i,this.ctx.state.parentHasLoopContext=a,this.ctx.state.groupStdin=o,f instanceof B)throw f;if(f instanceof Oe)return c+=f.stdout,l+=f.stderr,$(c,l,0);if(f instanceof ue||f instanceof ye)return c+=f.stdout,l+=f.stderr,$(c,l,0);if(f instanceof K)return c+=f.stdout,l+=f.stderr,$(c,l,f.exitCode);if(f instanceof fe)return c+=f.stdout,l+=f.stderr,$(c,l,f.exitCode);if(f instanceof Re)throw f.stdout=c+f.stdout,f.stderr=l+f.stderr,f;return $(c,`${l}${J(f)}
566
+ `,1)}return this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=i,this.ctx.state.parentHasLoopContext=a,this.ctx.state.groupStdin=o,$(c,l,u)}async executeGroup(e,r=""){let n="",s="",i=0,a=this.ctx.state.groupStdin;r&&(this.ctx.state.groupStdin=r);try{for(let o of e.body){let c=await this.executeStatement(o);n+=c.stdout,s+=c.stderr,i=c.exitCode}}catch(o){if(this.ctx.state.groupStdin=a,o instanceof B)throw o;if(Vt(o)||o instanceof Re||o instanceof K)throw o.prependOutput(n,s),o;return $(n,`${s}${J(o)}
567
+ `,1)}return this.ctx.state.groupStdin=a,$(n,s,i)}async executeArithmeticCommand(e){try{let r=await Z(this.ctx,e.expression.expression);return se(r!==0)}catch(r){return _(`bash: arithmetic expression: ${r.message}
568
+ `)}}async executeConditionalCommand(e){try{let r=await Qe(this.ctx,e.expression);return se(r)}catch(r){return _(`bash: conditional expression: ${r.message}
569
+ `,2)}}};var bt={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4};function ml(t){return t?{maxCallDepth:t.maxCallDepth??bt.maxCallDepth,maxCommandCount:t.maxCommandCount??bt.maxCommandCount,maxLoopIterations:t.maxLoopIterations??bt.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??bt.maxAwkIterations,maxSedIterations:t.maxSedIterations??bt.maxSedIterations}:{...bt}}function yl(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function gh(t){let e=yl(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function wh(t,e){let r=yl(t);if(!r)return!1;let n=gh(e);return!n||r.origin!==n.origin?!1:n.pathPrefix==="/"||n.pathPrefix===""?!0:r.pathname.startsWith(n.pathPrefix)}function ss(t,e){return!e||e.length===0?!1:e.some(r=>wh(t,r))}var Lt=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},Ft=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},Mt=class extends Error{constructor(e){super(`Redirect target not in allow-list: ${e}`),this.name="RedirectNotAllowedError"}},Rr=class extends Error{constructor(e,r){super(`HTTP method '${e}' not allowed. Allowed methods: ${r.join(", ")}`),this.name="MethodNotAllowedError"}};var Eh=20,bh=3e4,Sh=["GET","HEAD"],xh=new Set(["GET","HEAD","OPTIONS"]),Ah=new Set([301,302,303,307,308]);function is(t){let e=t.maxRedirects??Eh,r=t.timeoutMs??bh,n=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??Sh;function s(o){if(!t.dangerouslyAllowFullInternetAccess&&!ss(o,t.allowedUrlPrefixes??[]))throw new Lt(o)}function i(o){if(t.dangerouslyAllowFullInternetAccess)return;let c=o.toUpperCase();if(!n.includes(c))throw new Rr(c,n)}async function a(o,c={}){let l=c.method?.toUpperCase()??"GET";s(o),i(l);let u=o,f=0,d=c.followRedirects??!0,h=c.timeoutMs!==void 0?Math.min(c.timeoutMs,r):r;for(;;){let p=new AbortController,E=setTimeout(()=>p.abort(),h);try{let w={method:l,headers:c.headers,signal:p.signal,redirect:"manual"};c.body&&!xh.has(l)&&(w.body=c.body);let g=await fetch(u,w);if(Ah.has(g.status)&&d){let b=g.headers.get("location");if(!b)return await gl(g,u);let S=new URL(b,u).href;if(!t.dangerouslyAllowFullInternetAccess&&!ss(S,t.allowedUrlPrefixes??[]))throw new Mt(S);if(f++,f>e)throw new Ft(e);u=S;continue}return await gl(g,u)}finally{clearTimeout(E)}}}return a}async function gl(t,e){let r={};return t.headers.forEach((n,s)=>{r[s.toLowerCase()]=n}),{status:t.status,statusText:t.statusText,headers:r,body:await t.text(),url:e}}var Pr=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;logger;state;constructor(e={}){let r=e.fs??new tt(e.files);this.fs=r,this.useDefaultLayout=!e.cwd&&!e.files;let n=e.cwd||(this.useDefaultLayout?"/home/user":"/"),s={HOME:this.useDefaultLayout?"/home/user":"/",PATH:"/bin:/usr/bin",IFS:`
570
+ `,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:n,OLDPWD:n,...e.env};if(this.limits=ml({...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=is(e.network)),this.sleepFn=e.sleep,this.logger=e.logger,this.state={env:s,cwd:n,previousDir:"/home/user",functions:new Map,localScopes:[],callDepth:0,sourceDepth:0,commandCount:0,lastExitCode:0,lastArg:"",options:{errexit:!1,pipefail:!1,nounset:!1,xtrace:!1,verbose:!1},inCondition:!1,loopDepth:0},r instanceof tt)try{r.mkdirSync("/bin",{recursive:!0}),r.mkdirSync("/usr/bin",{recursive:!0}),this.useDefaultLayout&&(r.mkdirSync("/home/user",{recursive:!0}),r.mkdirSync("/tmp",{recursive:!0}))}catch{}if(n!=="/"&&r instanceof tt)try{r.mkdirSync(n,{recursive:!0})}catch{}for(let i of Ya(e.commands))this.registerCommand(i);if(e.network)for(let i of Ja())this.registerCommand(i);if(e.customCommands)for(let i of e.customCommands)eo(i)?this.registerCommand(to(i)):this.registerCommand(i)}registerCommand(e){if(this.commands.set(e.name,e),this.fs instanceof tt)try{this.fs.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
571
571
  # Built-in command: ${e.name}
572
572
  `)}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,r){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.
573
573
  `,exitCode:1,env:{...this.state.env,...r?.env}};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:{...this.state.env,...r?.env}};this.logger?.info("exec",{command:e});let n=r?.cwd??this.state.cwd,s={...this.state,env:{...this.state.env,...r?.env,...r?.cwd?{PWD:r.cwd}:{}},cwd:n,functions:new Map(this.state.functions),localScopes:[...this.state.localScopes],options:{...this.state.options}},i=e;r?.rawScript||(i=e.split(`
574
574
  `).map(o=>o.trimStart()).join(`
575
- `));try{let a=Ge(i),o={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn},l=await new Ot(o,s).executeScript(a);return this.logResult(l)}catch(a){if(a instanceof Z)return this.logResult({stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,env:{...this.state.env,...r?.env}});if(a instanceof te)return this.logResult({stdout:a.stdout,stderr:a.stderr,exitCode:1,env:{...this.state.env,...r?.env}});if(a instanceof W)return this.logResult({stdout:a.stdout,stderr:a.stderr,exitCode:W.EXIT_CODE,env:{...this.state.env,...r?.env}});if(a.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${a.message}
575
+ `));try{let a=qe(i),o={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn},l=await new Tt(o,s).executeScript(a);return this.logResult(l)}catch(a){if(a instanceof K)return this.logResult({stdout:a.stdout,stderr:a.stderr,exitCode:a.exitCode,env:{...this.state.env,...r?.env}});if(a instanceof ne)return this.logResult({stdout:a.stdout,stderr:a.stderr,exitCode:1,env:{...this.state.env,...r?.env}});if(a instanceof B)return this.logResult({stdout:a.stdout,stderr:a.stderr,exitCode:B.EXIT_CODE,env:{...this.state.env,...r?.env}});if(a.name==="ParseException")return this.logResult({stdout:"",stderr:`bash: syntax error: ${a.message}
576
576
  `,exitCode:2,env:{...this.state.env,...r?.env}});if(a instanceof RangeError)return this.logResult({stdout:"",stderr:`bash: ${a.message}
577
- `,exitCode:1,env:{...this.state.env,...r?.env}});throw a}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,r){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),r)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};function Eh(t){let e=["Execute bash commands in a virtual environment.","","This is a simulated bash environment with a virtual filesystem. Commands run in isolation without access to the host system.",""];if(t.files&&Object.keys(t.files).length>0){let r=Object.keys(t.files),n=r.slice(0,5);e.push("Available files:");for(let s of n)e.push(` ${s}`);r.length>5&&e.push(` ... and ${r.length-5} more`),e.push(""),e.push("Common operations:"),e.push(" ls -la # List files with details"),e.push(" find . -name '*.ts' # Find files by pattern"),e.push(" grep -r 'pattern' . # Search file contents"),e.push(" cat <file> # View file contents"),e.push("")}return e.push("To discover commands and their options:"),e.push(" help # List all available commands"),e.push(" <command> --help # Show options for a specific command"),e.push(""),t.commands?.length&&(e.push(`Available commands: ${t.commands.join(", ")}`),e.push("")),t.network&&(e.push("Network access via curl is enabled for this environment."),e.push("")),t.extraInstructions&&e.push(t.extraInstructions),e.join(`
578
- `).trim()}var bh=pl.object({command:pl.string().describe("The bash command to execute")});function t0(t={}){let e=new kr({fs:t.fs,files:t.fs?void 0:t.files,env:t.env,cwd:t.cwd,network:t.network,commands:t.commands,logger:t.logger});return gh({description:Eh(t),inputSchema:wh(bh),execute:async({command:r})=>{t.onCall?.(r);let n=await e.exec(r);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}})}export{t0 as createBashTool};
577
+ `,exitCode:1,env:{...this.state.env,...r?.env}});throw a}}async readFile(e){return this.fs.readFile(this.fs.resolvePath(this.state.cwd,e))}async writeFile(e,r){return this.fs.writeFile(this.fs.resolvePath(this.state.cwd,e),r)}getCwd(){return this.state.cwd}getEnv(){return{...this.state.env}}};function vh(t){let e=["Execute bash commands in a virtual environment.","","This is a simulated bash environment with a virtual filesystem. Commands run in isolation without access to the host system.",""];if(t.files&&Object.keys(t.files).length>0){let r=Object.keys(t.files),n=r.slice(0,5);e.push("Available files:");for(let s of n)e.push(` ${s}`);r.length>5&&e.push(` ... and ${r.length-5} more`),e.push(""),e.push("Common operations:"),e.push(" ls -la # List files with details"),e.push(" find . -name '*.ts' # Find files by pattern"),e.push(" grep -r 'pattern' . # Search file contents"),e.push(" cat <file> # View file contents"),e.push("")}return e.push("To discover commands and their options:"),e.push(" help # List all available commands"),e.push(" <command> --help # Show options for a specific command"),e.push(""),t.commands?.length&&(e.push(`Available commands: ${t.commands.join(", ")}`),e.push("")),t.network&&(e.push("Network access via curl is enabled for this environment."),e.push("")),t.extraInstructions&&e.push(t.extraInstructions),e.join(`
578
+ `).trim()}var kh=wl.object({command:wl.string().describe("The bash command to execute")});function f0(t={}){let e=new Pr({fs:t.fs,files:t.fs?void 0:t.files,env:t.env,cwd:t.cwd,network:t.network,commands:t.commands,logger:t.logger});return Ch({description:vh(t),inputSchema:Nh(kh),execute:async({command:r})=>{t.onCall?.(r);let n=await e.exec(r);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}})}export{f0 as createBashTool};