just-bash 1.1.0 → 1.2.0

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.
Files changed (71) hide show
  1. package/dist/Bash.d.ts +18 -0
  2. package/dist/ai/index.d.ts +6 -1
  3. package/dist/bin/chunks/awk2-6XCE67AX.js +20 -0
  4. package/dist/bin/chunks/awk2-DKAZ7LPG.js +20 -0
  5. package/dist/bin/chunks/awk2-GAJ72X3Z.js +20 -0
  6. package/dist/bin/chunks/awk2-HJAPWU2N.js +18 -0
  7. package/dist/bin/chunks/awk2-LVXC5OAC.js +20 -0
  8. package/dist/bin/chunks/awk2-T6HR4EYO.js +20 -0
  9. package/dist/bin/chunks/awk2-UYU2UYZ2.js +20 -0
  10. package/dist/bin/chunks/awk2-W64AZN7P.js +20 -0
  11. package/dist/bin/chunks/find-7BUNQZX4.js +11 -0
  12. package/dist/bin/chunks/find-YATLECXJ.js +11 -0
  13. package/dist/bin/chunks/grep-PHBFGJCV.js +15 -0
  14. package/dist/bin/chunks/sed-B6FXUN7R.js +80 -0
  15. package/dist/bin/chunks/sed-RHLDIXPL.js +76 -0
  16. package/dist/bin/chunks/sed-SYSATJXR.js +75 -0
  17. package/dist/bin/just-bash.js +102 -102
  18. package/dist/bin/shell/chunks/awk2-6XCE67AX.js +20 -0
  19. package/dist/bin/shell/chunks/awk2-DKAZ7LPG.js +20 -0
  20. package/dist/bin/shell/chunks/awk2-GAJ72X3Z.js +20 -0
  21. package/dist/bin/shell/chunks/awk2-HJAPWU2N.js +18 -0
  22. package/dist/bin/shell/chunks/awk2-LVXC5OAC.js +20 -0
  23. package/dist/bin/shell/chunks/awk2-T6HR4EYO.js +20 -0
  24. package/dist/bin/shell/chunks/awk2-UYU2UYZ2.js +20 -0
  25. package/dist/bin/shell/chunks/awk2-W64AZN7P.js +20 -0
  26. package/dist/bin/shell/chunks/find-7BUNQZX4.js +11 -0
  27. package/dist/bin/shell/chunks/find-YATLECXJ.js +11 -0
  28. package/dist/bin/shell/chunks/grep-PHBFGJCV.js +15 -0
  29. package/dist/bin/shell/chunks/sed-B6FXUN7R.js +80 -0
  30. package/dist/bin/shell/chunks/sed-RHLDIXPL.js +76 -0
  31. package/dist/bin/shell/chunks/sed-SYSATJXR.js +75 -0
  32. package/dist/bin/shell/shell.js +124 -128
  33. package/dist/bundle/ai/index.js +423 -386
  34. package/dist/bundle/chunks/awk2-365HINHI.js +19 -0
  35. package/dist/bundle/chunks/awk2-7YCFY7D2.js +19 -0
  36. package/dist/bundle/chunks/awk2-7YL3P4KU.js +19 -0
  37. package/dist/bundle/chunks/awk2-ETXZHQQ4.js +19 -0
  38. package/dist/bundle/chunks/awk2-FMEL7ESV.js +19 -0
  39. package/dist/bundle/chunks/awk2-LE4QUFGK.js +19 -0
  40. package/dist/bundle/chunks/awk2-MGHA6JPJ.js +17 -0
  41. package/dist/bundle/chunks/awk2-XEAK5PBN.js +19 -0
  42. package/dist/bundle/chunks/find-KP4M5DWC.js +10 -0
  43. package/dist/bundle/chunks/find-WM6ZETA7.js +10 -0
  44. package/dist/bundle/chunks/grep-CZTYKNEE.js +14 -0
  45. package/dist/bundle/chunks/sed-2WWCANZT.js +79 -0
  46. package/dist/bundle/chunks/sed-5LZHAGFR.js +74 -0
  47. package/dist/bundle/chunks/sed-V7XSBPTD.js +75 -0
  48. package/dist/bundle/index.js +8 -8
  49. package/dist/commands/awk/ast.d.ts +201 -0
  50. package/dist/commands/awk/awk2.d.ts +7 -0
  51. package/dist/commands/awk/builtins.d.ts +17 -0
  52. package/dist/commands/awk/interpreter/context.d.ts +53 -0
  53. package/dist/commands/awk/interpreter/expressions.d.ts +17 -0
  54. package/dist/commands/awk/interpreter/fields.d.ts +25 -0
  55. package/dist/commands/awk/interpreter/helpers.d.ts +29 -0
  56. package/dist/commands/awk/interpreter/index.d.ts +8 -0
  57. package/dist/commands/awk/interpreter/interpreter.d.ts +50 -0
  58. package/dist/commands/awk/interpreter/statements.d.ts +11 -0
  59. package/dist/commands/awk/interpreter/types.d.ts +13 -0
  60. package/dist/commands/awk/interpreter/variables.d.ts +35 -0
  61. package/dist/commands/awk/interpreter2.d.ts +90 -0
  62. package/dist/commands/awk/lexer.d.ts +100 -0
  63. package/dist/commands/awk/parser2.d.ts +73 -0
  64. package/dist/commands/find/matcher.d.ts +6 -2
  65. package/dist/commands/find/types.d.ts +13 -0
  66. package/dist/commands/sed/executor.d.ts +1 -1
  67. package/dist/commands/sed/lexer.d.ts +74 -0
  68. package/dist/commands/sed/parser.d.ts +4 -0
  69. package/dist/commands/sed/types.d.ts +66 -2
  70. package/dist/index.d.ts +1 -1
  71. package/package.json +1 -1
@@ -1,6 +1,6 @@
1
- var Ga=Object.defineProperty;var C=(t,e)=>()=>(t&&(e=t(t=0)),e);var I=(t,e)=>{for(var r in e)Ga(t,r,{get:e[r],enumerable:!0})};var Nn={};I(Nn,{echoCommand:()=>Za});function Va(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="",o=r+2;for(;o<t.length&&o<r+5&&/[0-7]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\0";else{let i=parseInt(s,8)%256;e+=String.fromCharCode(i)}r=o;break}case"x":{let s="",o=r+2;for(;o<t.length&&o<r+4&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\\x",r+=2;else{let i=parseInt(s,16);e+=String.fromCharCode(i),r=o}break}case"u":{let s="",o=r+2;for(;o<t.length&&o<r+6&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\\u",r+=2;else{let i=parseInt(s,16);e+=String.fromCodePoint(i),r=o}break}case"U":{let s="",o=r+2;for(;o<t.length&&o<r+10&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;if(s.length===0)e+="\\U",r+=2;else{let i=parseInt(s,16);try{e+=String.fromCodePoint(i)}catch{e+=`\\U${s}`}r=o}break}default:e+=`\\${n}`,r+=2}}else e+=t[r],r++;return{output:e,stop:!1}}var Za,vn=C(()=>{"use strict";Za={name:"echo",async execute(t,e){let r=!1,n=!1,s=0;for(;s<t.length;){let i=t[s];if(i==="-n")r=!0,s++;else if(i==="-e")n=!0,s++;else if(i==="-E")n=!1,s++;else if(i==="-ne"||i==="-en")r=!0,n=!0,s++;else break}let o=t.slice(s).join(" ");if(n){let i=Va(o);if(o=i.output,i.stop)return{stdout:o,stderr:"",exitCode:0}}return r||(o+=`
3
- `),{stdout:o,stderr:"",exitCode:0}}}});function x(t){let e=`${t.name} - ${t.summary}
1
+ var pl=Object.defineProperty;var N=(t,e)=>()=>(t&&(e=t(t=0)),e);var O=(t,e)=>{for(var r in e)pl(t,r,{get:e[r],enumerable:!0})};var rs={};O(rs,{echoCommand:()=>yl});function ml(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 yl,ns=N(()=>{"use strict";yl={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=ml(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}
4
4
 
5
5
  `;if(e+=`Usage: ${t.usage}
6
6
  `,t.description){if(e+=`
@@ -19,152 +19,176 @@ 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 S(t){return t.includes("--help")}function O(t,e){return{stdout:"",stderr:e.startsWith("--")?`${t}: unrecognized option '${e}'
22
+ `}return{stdout:e,stderr:"",exitCode:0}}function C(t){return t.includes("--help")}function L(t,e){return{stdout:"",stderr:e.startsWith("--")?`${t}: unrecognized option '${e}'
23
23
  `:`${t}: invalid option -- '${e.replace(/^-/,"")}'
24
- `,exitCode:1}}var R=C(()=>{"use strict"});function M(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 o={};for(let[c,l]of Object.entries(r))l.default!==void 0?o[c]=l.default:l.type==="boolean"&&(o[c]=!1);let i=[],a=!1;for(let c=0;c<e.length;c++){let l=e[c];if(a||!l.startsWith("-")||l==="-"){i.push(l);continue}if(l==="--"){a=!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:O(t,l)};let{name:p,type:b}=h;if(b==="boolean")o[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]}o[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:O(t,`-${d}`)};let{name:p,type:b}=h;if(b==="boolean")o[p]=!0;else{let g;if(f+1<u.length)g=u.slice(f+1);else if(c+1<e.length)g=e[++c];else return{ok:!1,error:{stdout:"",stderr:`${t}: option requires an argument -- '${d}'
26
- `,exitCode:1}};o[p]=b==="number"?parseInt(g,10):g;break}}}}return{ok:!0,result:{flags:o,positional:i}}}var Y=C(()=>{"use strict";R()});async function tt(t,e,r){let{cmdName:n,allowStdinMarker:s=!0,stopOnError:o=!1}=r;if(e.length===0)return{files:[{filename:"",content:t.stdin}],stderr:"",exitCode:0};let i=[],a="",c=0;for(let l of e){if(s&&l==="-"){i.push({filename:"-",content:t.stdin});continue}try{let u=t.fs.resolvePath(t.cwd,l),f=await t.fs.readFile(u);i.push({filename:l,content:f})}catch{if(a+=`${n}: ${l}: No such file or directory
27
- `,c=1,o)return{files:i,stderr:a,exitCode:c}}}return{files:i,stderr:a,exitCode:c}}async function Ie(t,e,r){let n=await tt(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(o=>o.content).join("")}}var Le=C(()=>{"use strict"});var kn={};I(kn,{catCommand:()=>Xa});function Ya(t,e){let r=t.split(`
24
+ `,exitCode:1}}var T=N(()=>{"use strict"});function H(t,e,r){let n=new Map,s=new Map;for(let[l,c]of Object.entries(r)){let u={name:l,type:c.type};c.short&&n.set(c.short,u),c.long&&s.set(c.long,u)}let i={};for(let[l,c]of Object.entries(r))c.default!==void 0?i[l]=c.default:c.type==="boolean"&&(i[l]=!1);let a=[],o=!1;for(let l=0;l<e.length;l++){let c=e[l];if(o||!c.startsWith("-")||c==="-"){a.push(c);continue}if(c==="--"){o=!0;continue}if(c.startsWith("--")){let u=c.indexOf("="),f,d;u!==-1?(f=c.slice(2,u),d=c.slice(u+1)):f=c.slice(2);let h=s.get(f);if(!h)return{ok:!1,error:L(t,c)};let{name:p,type:b}=h;if(b==="boolean")i[p]=!0;else{if(d===void 0){if(l+1>=e.length)return{ok:!1,error:{stdout:"",stderr:`${t}: option '--${f}' requires an argument
25
+ `,exitCode:1}};d=e[++l]}i[p]=b==="number"?parseInt(d,10):d}}else{let u=c.slice(1);for(let f=0;f<u.length;f++){let d=u[f],h=n.get(d);if(!h)return{ok:!1,error:L(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(l+1<e.length)w=e[++l];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";T()});async function wt(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="",l=0;for(let c of e){if(s&&c==="-"){a.push({filename:"-",content:t.stdin});continue}try{let u=t.fs.resolvePath(t.cwd,c),f=await t.fs.readFile(u);a.push({filename:c,content:f})}catch{if(o+=`${n}: ${c}: No such file or directory
27
+ `,l=1,i)return{files:a,stderr:o,exitCode:l}}}return{files:a,stderr:o,exitCode:l}}async function We(t,e,r){let n=await wt(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 Ve=N(()=>{"use strict"});var ss={};O(ss,{catCommand:()=>El});function bl(t,e){let r=t.split(`
28
28
  `),n=t.endsWith(`
29
- `),s=n?r.slice(0,-1):r;return{content:s.map((i,a)=>`${String(e+a).padStart(6," ")} ${i}`).join(`
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 Qa,Ka,Xa,In=C(()=>{"use strict";Y();Le();R();Qa={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"]},Ka={number:{short:"n",long:"number",type:"boolean"}},Xa={name:"cat",async execute(t,e){if(S(t))return x(Qa);let r=M("cat",t,Ka);if(!r.ok)return r.error;let n=r.result.flags.number,s=r.result.positional,o=await tt(e,s,{cmdName:"cat",allowStdinMarker:!0,stopOnError:!1}),i="",a=1;for(let{content:c}of o.files)if(n){let l=Ya(c,a);i+=l.content,a=l.nextLineNumber}else i+=c;return{stdout:i,stderr:o.stderr,exitCode:o.exitCode}}}});function q(t){return t instanceof Error?t.message:String(t)}var ye=C(()=>{"use strict"});var Rn={};I(Rn,{printfCommand:()=>el});import{sprintf as qe}from"sprintf-js";function tl(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="",o=r+1;for(;o<t.length&&o<r+4&&/[0-7]/.test(t[o]);)s+=t[o],o++;e+=String.fromCharCode(parseInt(s,8)),r=o;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 rl(t,e,r){let n="",s=0,o=0,i=!1,a="";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 E=parseInt(e[r+o]||"0",10);o++,h=h.replace("*",String(E))}if(u){let E=parseInt(e[r+o]||"0",10);o++,h=h.replace(".*",`.${E}`)}let p=e[r+o]||"";o++;let{value:b,parseError:g,parseErrMsg:y,stopped:w}=nl(h,f,p);if(n+=b,g&&(i=!0,y&&(a=y)),w)return{result:n,argsConsumed:o,error:i,errMsg:a,stopped:!0}}else n+=t[s],s++;return{result:n,argsConsumed:o,error:i,errMsg:a,stopped:!1}}function nl(t,e,r){let n=!1,s="";switch(e){case"d":case"i":{let o=gt(r);return n=we,n&&(s=`printf: ${r}: invalid number
33
- `),{value:Pn(t,o),parseError:n,parseErrMsg:s}}case"o":{let o=gt(r);return n=we,n&&(s=`printf: ${r}: invalid number
34
- `),{value:sl(t,o),parseError:n,parseErrMsg:s}}case"u":{let o=gt(r);n=we,n&&(s=`printf: ${r}: invalid number
35
- `);let i=o<0?o>>>0:o;return{value:Pn(t.replace("u","d"),i),parseError:n,parseErrMsg:s}}case"x":case"X":{let o=gt(r);return n=we,n&&(s=`printf: ${r}: invalid number
36
- `),{value:il(t,o),parseError:n,parseErrMsg:s}}case"e":case"E":case"f":case"F":case"g":case"G":{let o=parseFloat(r)||0;return{value:cl(t,e,o),parseError:!1,parseErrMsg:""}}case"c":return{value:r.charAt(0)||"",parseError:!1,parseErrMsg:""};case"s":return{value:al(t,r),parseError:!1,parseErrMsg:""};case"q":return{value:ll(t,r),parseError:!1,parseErrMsg:""};case"b":{let o=ul(r);return{value:o.value,parseError:!1,parseErrMsg:"",stopped:o.stopped}}default:try{return{value:qe(t,r),parseError:!1,parseErrMsg:""}}catch{return{value:"",parseError:!0,parseErrMsg:`printf: [sprintf] unexpected placeholder
37
- `}}}}function gt(t){we=!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)?(we=!0,0):(r&&(we=!0),n)}if(t.startsWith("0")&&t.length>1&&/^-?0[0-7]+$/.test(t))return r&&(we=!0),parseInt(t,8)||0;if(/^\d+#/.test(t)){we=!0;let n=t.match(/^(\d+)#/);return n?parseInt(n[1],10):0}if(t!==""&&!/^-?\d+$/.test(t)){we=!0;let n=parseInt(t,10);return Number.isNaN(n)?0:n}return r&&(we=!0),parseInt(t,10)||0}function Pn(t,e){let r=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[diu]$/);if(!r)return qe(t.replace(/\.\d*/,""),e);let n=r[1]||"",s=r[2]?parseInt(r[2],10):0,o=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,i=e<0,a=Math.abs(e),c=String(a);o>=0&&(c=c.padStart(o,"0"));let l="";i?l="-":n.includes("+")?l="+":n.includes(" ")&&(l=" ");let u=l+c;return s>u.length&&(n.includes("-")?u=u.padEnd(s," "):n.includes("0")&&o<0?u=l+c.padStart(s-l.length,"0"):u=u.padStart(s," ")),u}function sl(t,e){let r=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?o$/);if(!r)return qe(t,e);let n=r[1]||"",s=r[2]?parseInt(r[2],10):0,o=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,i=Math.abs(e).toString(8);o>=0&&(i=i.padStart(o,"0")),n.includes("#")&&!i.startsWith("0")&&(i=`0${i}`);let a=i;return s>a.length&&(n.includes("-")?a=a.padEnd(s," "):n.includes("0")&&o<0?a=a.padStart(s,"0"):a=a.padStart(s," ")),a}function il(t,e){let r=t.includes("X"),n=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[xX]$/);if(!n)return qe(t,e);let s=n[1]||"",o=n[2]?parseInt(n[2],10):0,i=n[3]!==void 0?n[4]?parseInt(n[4],10):0:-1,a=Math.abs(e).toString(16);r&&(a=a.toUpperCase()),i>=0&&(a=a.padStart(i,"0"));let c="";s.includes("#")&&e!==0&&(c=r?"0X":"0x");let l=c+a;return o>l.length&&(s.includes("-")?l=l.padEnd(o," "):s.includes("0")&&i<0?l=c+a.padStart(o-c.length,"0"):l=l.padStart(o," ")),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 o=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":o<32||o>126?n+=`\\x${o.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 al(t,e){let r=t.match(/^%(-?)(\d*)(\.(\d*))?s$/);if(!r)return qe(t.replace(/0+(?=\d)/,""),e);let n=r[1]==="-",s=r[2]?parseInt(r[2],10):0,o=r[3]!==void 0?r[4]?parseInt(r[4],10):0:-1,i=e;return o>=0&&i.length>o&&(i=i.slice(0,o)),s>i.length&&(n?i=i.padEnd(s," "):i=i.padStart(s," ")),i}function ll(t,e){let r=ol(e),n=t.match(/^%(-?)(\d*)q$/);if(!n)return r;let s=n[1]==="-",o=n[2]?parseInt(n[2],10):0,i=r;return o>i.length&&(s?i=i.padEnd(o," "):i=i.padStart(o," ")),i}function cl(t,e,r){let n=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[eEfFgG]$/);if(!n)return qe(t,r);let s=n[1]||"",o=n[2]?parseInt(n[2],10):0,i=n[3]!==void 0?n[4]?parseInt(n[4],10):0:6,a,c=e.toLowerCase();if(c==="e"?(a=r.toExponential(i),a=a.replace(/e([+-])(\d)$/,"e$10$2"),e==="E"&&(a=a.toUpperCase())):c==="f"?(a=r.toFixed(i),s.includes("#")&&i===0&&!a.includes(".")&&(a+=".")):c==="g"?(a=r.toPrecision(i||1),s.includes("#")||(a=a.replace(/\.?0+$/,""),a=a.replace(/\.?0+e/,"e")),a=a.replace(/e([+-])(\d)$/,"e$10$2"),e==="G"&&(a=a.toUpperCase())):a=r.toString(),r>=0&&(s.includes("+")?a=`+${a}`:s.includes(" ")&&(a=` ${a}`)),o>a.length)if(s.includes("-"))a=a.padEnd(o," ");else if(s.includes("0")){let l=a.match(/^[+ -]/)?.[0]||"",u=l?a.slice(1):a;a=l+u.padStart(o-l.length,"0")}else a=a.padStart(o," ");return a}function ul(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="",o=r+2;for(;o<t.length&&o<r+4&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;s?(e+=String.fromCharCode(parseInt(s,16)),r=o):(e+="\\x",r+=2);break}case"u":{let s="",o=r+2;for(;o<t.length&&o<r+6&&/[0-9a-fA-F]/.test(t[o]);)s+=t[o],o++;s?(e+=String.fromCodePoint(parseInt(s,16)),r=o):(e+="\\u",r+=2);break}case"0":{let s="",o=r+2;for(;o<t.length&&o<r+5&&/[0-7]/.test(t[o]);)s+=t[o],o++;s?e+=String.fromCharCode(parseInt(s,8)):e+="\0",r=o;break}case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let s="",o=r+1;for(;o<t.length&&o<r+4&&/[0-7]/.test(t[o]);)s+=t[o],o++;e+=String.fromCharCode(parseInt(s,8)),r=o;break}default:e+=t[r],r++}else e+=t[r],r++;return{value:e,stopped:!1}}var Ja,el,we,On=C(()=>{"use strict";ye();R();Ja={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)"]},el={name:"printf",async execute(t,e){if(S(t))return x(Ja);if(t.length===0)return{stdout:"",stderr:`printf: usage: printf format [arguments]
40
- `,exitCode:2};let r=null,n=0;for(;n<t.length;){let i=t[n];if(i==="--"){n++;break}if(i==="-v"){if(n+1>=t.length)return{stdout:"",stderr:`printf: -v: option requires an argument
31
+ `:""),nextLineNumber:e+s.length}}var gl,wl,El,is=N(()=>{"use strict";ae();Ve();T();gl={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"]},wl={number:{short:"n",long:"number",type:"boolean"}},El={name:"cat",async execute(t,e){if(C(t))return A(gl);let r=H("cat",t,wl);if(!r.ok)return r.error;let n=r.result.flags.number,s=r.result.positional,i=await wt(e,s,{cmdName:"cat",allowStdinMarker:!0,stopOnError:!1}),a="",o=1;for(let{content:l}of i.files)if(n){let c=bl(l,o);a+=c.content,o=c.nextLineNumber}else a+=l;return{stdout:a,stderr:i.stderr,exitCode:i.exitCode}}}});function Y(t){return t instanceof Error?t.message:String(t)}var ve=N(()=>{"use strict"});var os={};O(os,{printfCommand:()=>Sl});import{sprintf as st}from"sprintf-js";function Al(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 Cl(t,e,r){let n="",s=0,i=0,a=!1,o="";for(;s<t.length;)if(t[s]==="%"&&s+1<t.length){let l=s;if(s++,t[s]==="%"){n+="%",s++;continue}for(;s<t.length&&"+-0 #'".includes(t[s]);)s++;let c=!1;if(t[s]==="*")c=!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(l,s);if(c){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}=Nl(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 Nl(t,e,r){let n=!1,s="";switch(e){case"d":case"i":{let i=Lt(r);return n=ke,n&&(s=`printf: ${r}: invalid number
33
+ `),{value:as(t,i),parseError:n,parseErrMsg:s}}case"o":{let i=Lt(r);return n=ke,n&&(s=`printf: ${r}: invalid number
34
+ `),{value:vl(t,i),parseError:n,parseErrMsg:s}}case"u":{let i=Lt(r);n=ke,n&&(s=`printf: ${r}: invalid number
35
+ `);let a=i<0?i>>>0:i;return{value:as(t.replace("u","d"),a),parseError:n,parseErrMsg:s}}case"x":case"X":{let i=Lt(r);return n=ke,n&&(s=`printf: ${r}: invalid number
36
+ `),{value:kl(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:Pl(t,e,i),parseError:!1,parseErrMsg:""}}case"c":return{value:r.charAt(0)||"",parseError:!1,parseErrMsg:""};case"s":return{value:Rl(t,r),parseError:!1,parseErrMsg:""};case"q":return{value:$l(t,r),parseError:!1,parseErrMsg:""};case"b":{let i=Ol(r);return{value:i.value,parseError:!1,parseErrMsg:"",stopped:i.stopped}}default:try{return{value:st(t,r),parseError:!1,parseErrMsg:""}}catch{return{value:"",parseError:!0,parseErrMsg:`printf: [sprintf] unexpected placeholder
37
+ `}}}}function Lt(t){ke=!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)?(ke=!0,0):(r&&(ke=!0),n)}if(t.startsWith("0")&&t.length>1&&/^-?0[0-7]+$/.test(t))return r&&(ke=!0),parseInt(t,8)||0;if(/^\d+#/.test(t)){ke=!0;let n=t.match(/^(\d+)#/);return n?parseInt(n[1],10):0}if(t!==""&&!/^-?\d+$/.test(t)){ke=!0;let n=parseInt(t,10);return Number.isNaN(n)?0:n}return r&&(ke=!0),parseInt(t,10)||0}function as(t,e){let r=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[diu]$/);if(!r)return st(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),l=String(o);i>=0&&(l=l.padStart(i,"0"));let c="";a?c="-":n.includes("+")?c="+":n.includes(" ")&&(c=" ");let u=c+l;return s>u.length&&(n.includes("-")?u=u.padEnd(s," "):n.includes("0")&&i<0?u=c+l.padStart(s-c.length,"0"):u=u.padStart(s," ")),u}function vl(t,e){let r=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?o$/);if(!r)return st(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 kl(t,e){let r=t.includes("X"),n=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[xX]$/);if(!n)return st(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 l="";s.includes("#")&&e!==0&&(l=r?"0X":"0x");let c=l+o;return i>c.length&&(s.includes("-")?c=c.padEnd(i," "):s.includes("0")&&a<0?c=l+o.padStart(i-l.length,"0"):c=c.padStart(i," ")),c}function Il(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 Rl(t,e){let r=t.match(/^%(-?)(\d*)(\.(\d*))?s$/);if(!r)return st(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 $l(t,e){let r=Il(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 Pl(t,e,r){let n=t.match(/^%([- +#0']*)(\d*)(\.(\d*))?[eEfFgG]$/);if(!n)return st(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,l=e.toLowerCase();if(l==="e"?(o=r.toExponential(a),o=o.replace(/e([+-])(\d)$/,"e$10$2"),e==="E"&&(o=o.toUpperCase())):l==="f"?(o=r.toFixed(a),s.includes("#")&&a===0&&!o.includes(".")&&(o+=".")):l==="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 c=o.match(/^[+ -]/)?.[0]||"",u=c?o.slice(1):o;o=c+u.padStart(i-c.length,"0")}else o=o.padStart(i," ");return o}function Ol(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 xl,Sl,ke,ls=N(()=>{"use strict";ve();T();xl={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)"]},Sl={name:"printf",async execute(t,e){if(C(t))return A(xl);if(t.length===0)return{stdout:"",stderr:`printf: usage: printf format [arguments]
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
- `,exitCode:2};n+=2}else{if(i.startsWith("-")&&i!=="-")break;break}}if(n>=t.length)return{stdout:"",stderr:`printf: usage: printf format [arguments]
43
- `,exitCode:1};let s=t[n],o=t.slice(n+1);try{let i=tl(s),a="",c=0,l=!1,u="";do{let{result:f,argsConsumed:d,error:h,errMsg:p,stopped:b}=rl(i,o,c);if(a+=f,c+=d,h&&(l=!0,p&&(u=p)),b)break}while(c<o.length&&c>0);return c===0&&o.length>0,r?(e.env[r]=a,{stdout:"",stderr:u,exitCode:l?1:0}):{stdout:a,stderr:u,exitCode:l?1:0}}catch(i){return{stdout:"",stderr:`printf: ${q(i)}
44
- `,exitCode:1}}}};we=!1});var Mn={};I(Mn,{lsCommand:()=>hl});import{minimatch as Dn}from"minimatch";function yt(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 wt(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,o=new Date(s.getTime()-4320*60*60*1e3);if(t>o){let a=String(t.getHours()).padStart(2,"0"),c=String(t.getMinutes()).padStart(2,"0");return`${r} ${n} ${a}:${c}`}let i=t.getFullYear();return`${r} ${n} ${i}`}async function pl(t,e,r,n,s,o=!1,i=!1,a=!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(Dn(h,t)||Dn(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(a){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(o&&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),g=b.isDirectory?"drwxr-xr-x":"-rw-r--r--",y=b.isDirectory?"/":"",w=b.size??0,E=i?yt(w).padStart(5):String(w).padStart(5),$=b.mtime??new Date(0),A=wt($);d.push(`${g} 1 user user ${E} ${A} ${h}${y}`)}catch{d.push(`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${h}`)}}return{stdout:`${d.join(`
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=Al(s),o="",l=0,c=!1,u="";do{let{result:f,argsConsumed:d,error:h,errMsg:p,stopped:b}=Cl(a,i,l);if(o+=f,l+=d,h&&(c=!0,p&&(u=p)),b)break}while(l<i.length&&l>0);return l===0&&i.length>0,r?(e.env[r]=o,{stdout:"",stderr:u,exitCode:c?1:0}):{stdout:o,stderr:u,exitCode:c?1:0}}catch(a){return{stdout:"",stderr:`printf: ${Y(a)}
44
+ `,exitCode:1}}}};ke=!1});var fs={};O(fs,{lsCommand:()=>Ll});import{minimatch as cs}from"minimatch";function Ft(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 Mt(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"),l=String(t.getMinutes()).padStart(2,"0");return`${r} ${n} ${o}:${l}`}let a=t.getFullYear();return`${r} ${n} ${a}`}async function Fl(t,e,r,n,s,i=!1,a=!1,o=!1){let l=r||n,c=e.fs.getAllPaths(),u=e.fs.resolvePath(e.cwd,"."),f=[];for(let d of c){let h=d.startsWith(u)&&d.slice(u.length+1)||d;if(cs(h,t)||cs(d,t)){let p=h.split("/").pop()||h;if(!l&&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?Ft(E).padStart(5):String(E).padStart(5),S=b.mtime??new Date(0),v=Mt(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(`
46
46
  `)}
47
47
  `,stderr:"",exitCode:0}}return{stdout:`${f.join(`
48
48
  `)}
49
- `,stderr:"",exitCode:0}}async function Tn(t,e,r,n,s,o,i,a=!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 g=h.size??0,y=c?yt(g).padStart(5):String(g).padStart(5),w=h.mtime??new Date(0),E=wt(w);return{stdout:`-rw-r--r-- 1 user user ${y} ${E} ${t}
49
+ `,stderr:"",exitCode:0}}async function us(t,e,r,n,s,i,a,o=!1,l=!1,c=!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=l?Ft(w).padStart(5):String(w).padStart(5),E=h.mtime??new Date(0),x=Mt(E);return{stdout:`-rw-r--r-- 1 user user ${g} ${x} ${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(g=>!g.startsWith("."))),l){let g=[];for(let y of p){let w=d==="/"?`/${y}`:`${d}/${y}`;try{let E=await e.fs.stat(w);g.push({name:y,size:E.size??0})}catch{g.push({name:y,size:0})}}g.sort((y,w)=>w.size-y.size),p=g.map(y=>y.name)}else p.sort();r&&(p=[".","..",...p]),a&&p.reverse();let b="";if((o||i)&&(b+=`${t}:
51
+ `,stderr:"",exitCode:0}}let p=await e.fs.readdir(d);if(f||(p=p.filter(w=>!w.startsWith("."))),c){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
52
  `),s){b+=`total ${p.length}
53
- `;for(let g of p){if(g==="."||g===".."){b+=`drwxr-xr-x 1 user user 0 Jan 1 00:00 ${g}
54
- `;continue}let y=d==="/"?`/${g}`:`${d}/${g}`;try{let w=await e.fs.stat(y),E=w.isDirectory?"drwxr-xr-x":"-rw-r--r--",$=w.isDirectory?"/":"",A=w.size??0,P=c?yt(A).padStart(5):String(A).padStart(5),J=w.mtime??new Date(0),L=wt(J);b+=`${E} 1 user user ${P} ${L} ${g}${$}
55
- `}catch{b+=`-rw-r--r-- 1 user user 0 Jan 1 00:00 ${g}
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=l?Ft(v).padStart(5):String(v).padStart(5),M=E.mtime??new Date(0),_=Mt(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
56
  `}}}else b+=p.join(`
57
57
  `)+(p.length?`
58
- `:"");if(o)for(let g of p){if(g==="."||g==="..")continue;let y=d==="/"?`/${g}`:`${d}/${g}`;try{if((await e.fs.stat(y)).isDirectory){b+=`
59
- `;let E=t==="."?`./${g}`:`${t}/${g}`,$=await Tn(E,e,r,n,s,o,!1,a,c,l,!0);b+=$.stdout}}catch{}}return{stdout:b,stderr:"",exitCode:0}}catch{return{stdout:"",stderr:`ls: ${t}: No such file or directory
60
- `,exitCode:2}}}var fl,dl,hl,Fn=C(()=>{"use strict";Y();R();fl={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"]},dl={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"}},hl={name:"ls",async execute(t,e){if(S(t))return x(fl);let r=M("ls",t,dl);if(!r.ok)return r.error;let n=r.result.flags.showAll,s=r.result.flags.showAlmostAll,o=r.result.flags.longFormat,i=r.result.flags.humanReadable,a=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 g=0;g<d.length;g++){let y=d[g];if(g>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){b+=`
59
+ `;let x=t==="."?`./${w}`:`${t}/${w}`,S=await us(x,e,r,n,s,i,!1,o,l,c,!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 Dl,Tl,Ll,ds=N(()=>{"use strict";ae();T();Dl={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"}},Ll={name:"ls",async execute(t,e){if(C(t))return A(Dl);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,l=r.result.flags.reverse,c=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(`
61
61
 
62
62
  `)&&(h+=`
63
- `),u){let w=e.fs.resolvePath(e.cwd,y);try{let E=await e.fs.stat(w);if(o){let $=E.isDirectory?"drwxr-xr-x":"-rw-r--r--",A=E.isDirectory?"/":"",P=E.size??0,J=i?yt(P).padStart(5):String(P).padStart(5),L=E.mtime??new Date(0),Se=wt(L);h+=`${$} 1 user user ${J} ${Se} ${y}${A}
64
- `}else h+=`${y}
65
- `}catch{p+=`ls: cannot access '${y}': No such file or directory
66
- `,b=2}continue}if(y.includes("*")||y.includes("?")||y.includes("[")){let w=await pl(y,e,n,s,o,c,i,l);h+=w.stdout,p+=w.stderr,w.exitCode!==0&&(b=w.exitCode)}else{let w=await Tn(y,e,n,s,o,a,d.length>1,c,i,l);h+=w.stdout,p+=w.stderr,w.exitCode!==0&&(b=w.exitCode)}}return{stdout:h,stderr:p,exitCode:b}}}});var Ln={};I(Ln,{mkdirCommand:()=>gl});var ml,gl,Wn=C(()=>{"use strict";ye();Y();ml={recursive:{short:"p",long:"parents",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},gl={name:"mkdir",async execute(t,e){let r=M("mkdir",t,ml);if(!r.ok)return r.error;let n=r.result.flags.recursive,s=r.result.flags.verbose,o=r.result.positional;if(o.length===0)return{stdout:"",stderr:`mkdir: missing operand
67
- `,exitCode:1};let i="",a="",c=0;for(let l of o)try{let u=e.fs.resolvePath(e.cwd,l);await e.fs.mkdir(u,{recursive:n}),s&&(i+=`mkdir: created directory '${l}'
68
- `)}catch(u){let f=q(u);f.includes("ENOENT")||f.includes("no such file")?a+=`mkdir: cannot create directory '${l}': No such file or directory
69
- `:f.includes("EEXIST")||f.includes("already exists")?a+=`mkdir: cannot create directory '${l}': File exists
70
- `:a+=`mkdir: cannot create directory '${l}': ${f}
71
- `,c=1}return{stdout:i,stderr:a,exitCode:c}}}});var _n={};I(_n,{touchCommand:()=>yl});var yl,Hn=C(()=>{"use strict";ye();R();yl={name:"touch",async execute(t,e){let r=[];for(let o of t){if(o.startsWith("--"))return O("touch",o);if(o.startsWith("-")&&o.length>1)return O("touch",o);r.push(o)}if(r.length===0)return{stdout:"",stderr:`touch: missing file operand
72
- `,exitCode:1};let n="",s=0;for(let o of r)try{let i=e.fs.resolvePath(e.cwd,o);await e.fs.exists(i)||await e.fs.writeFile(i,"")}catch(i){n+=`touch: cannot touch '${o}': ${q(i)}
73
- `,s=1}return{stdout:"",stderr:n,exitCode:s}}}});var Bn={};I(Bn,{rmCommand:()=>bl});var wl,bl,zn=C(()=>{"use strict";ye();Y();wl={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"}},bl={name:"rm",async execute(t,e){let r=M("rm",t,wl);if(!r.ok)return r.error;let n=r.result.flags.recursive||r.result.flags.recursiveUpper,s=r.result.flags.force,o=r.result.flags.verbose,i=r.result.positional;if(i.length===0)return s?{stdout:"",stderr:"",exitCode:0}:{stdout:"",stderr:`rm: missing operand
74
- `,exitCode:1};let a="",c="",l=0;for(let u of i)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
- `,l=1;continue}await e.fs.rm(f,{recursive:n,force:s}),o&&(a+=`removed '${u}'
76
- `)}catch(f){if(!s){let d=q(f);d.includes("ENOENT")||d.includes("no such file")?c+=`rm: cannot remove '${u}': No such file or directory
77
- `:d.includes("ENOTEMPTY")||d.includes("not empty")?c+=`rm: cannot remove '${u}': Directory not empty
78
- `:c+=`rm: cannot remove '${u}': ${d}
79
- `,l=1}}return{stdout:a,stderr:c,exitCode:l}}}});var Un={};I(Un,{cpCommand:()=>Sl});var El,xl,Sl,jn=C(()=>{"use strict";ye();Y();R();El={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"]},xl={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"}},Sl={name:"cp",async execute(t,e){if(S(t))return x(El);let r=M("cp",t,xl);if(!r.ok)return r.error;let n=r.result.flags.recursive||r.result.flags.recursiveUpper,s=r.result.flags.noClobber,o=r.result.flags.preserve,i=r.result.flags.verbose,a=r.result.positional;if(a.length<2)return{stdout:"",stderr:`cp: missing destination file operand
80
- `,exitCode:1};let c=a.pop()??"",l=a,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 g=e.fs.resolvePath(e.cwd,b),y=await e.fs.stat(g),w=u;if(p){let E=b.split("/").pop()||b;w=u==="/"?`/${E}`:`${u}/${E}`}if(y.isDirectory&&!n){d+=`cp: -r not specified; omitting directory '${b}'
82
- `,h=1;continue}if(s)try{await e.fs.stat(w);continue}catch{}await e.fs.cp(g,w,{recursive:n}),i&&(f+=`'${b}' -> '${w}'
83
- `)}catch(g){let y=q(g);y.includes("ENOENT")||y.includes("no such file")?d+=`cp: cannot stat '${b}': No such file or directory
84
- `:d+=`cp: cannot copy '${b}': ${y}
85
- `,h=1}return{stdout:f,stderr:d,exitCode:h}}}});var qn={};I(qn,{mvCommand:()=>$l});var Cl,Al,$l,Gn=C(()=>{"use strict";ye();Y();R();Cl={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"]},Al={force:{short:"f",long:"force",type:"boolean"},noClobber:{short:"n",long:"no-clobber",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},$l={name:"mv",async execute(t,e){if(S(t))return x(Cl);let r=M("mv",t,Al);if(!r.ok)return r.error;let n=r.result.flags.force,s=r.result.flags.noClobber,o=r.result.flags.verbose,i=r.result.positional;if(s&&(n=!1),i.length<2)return{stdout:"",stderr:`mv: missing destination file operand
86
- `,exitCode:1};let a=i.pop()??"",c=i,l=e.fs.resolvePath(e.cwd,a),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 '${a}' is not a directory
87
- `,exitCode:1};for(let p of c)try{let b=e.fs.resolvePath(e.cwd,p),g=l;if(h){let y=p.split("/").pop()||p;g=l==="/"?`/${y}`:`${l}/${y}`}if(s)try{await e.fs.stat(g);continue}catch{}if(await e.fs.mv(b,g),o){let y=h?`${a}/${p.split("/").pop()||p}`:a;u+=`renamed '${p}' -> '${y}'
88
- `}}catch(b){let g=q(b);g.includes("ENOENT")||g.includes("no such file")?f+=`mv: cannot stat '${p}': No such file or directory
89
- `:f+=`mv: cannot move '${p}': ${g}
90
- `,d=1}return{stdout:u,stderr:f,exitCode:d}}}});var Vn={};I(Vn,{lnCommand:()=>vl});var Nl,vl,Zn=C(()=>{"use strict";R();Nl={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"]},vl={name:"ln",async execute(t,e){if(S(t))return x(Nl);let r=!1,n=!1,s=!1,o=0;for(;o<t.length&&t[o].startsWith("-");){let f=t[o];if(f==="-s"||f==="--symbolic")r=!0,o++;else if(f==="-f"||f==="--force")n=!0,o++;else if(f==="-v"||f==="--verbose")s=!0,o++;else if(f==="-n"||f==="--no-dereference")o++;else if(/^-[sfvn]+$/.test(f))f.includes("s")&&(r=!0),f.includes("f")&&(n=!0),f.includes("v")&&(s=!0),o++;else if(f==="--"){o++;break}else return{stdout:"",stderr:`ln: invalid option -- '${f.slice(1)}'
91
- `,exitCode:1}}let i=t.slice(o);if(i.length<2)return{stdout:"",stderr:`ln: missing file operand
92
- `,exitCode:1};let a=i[0],c=i[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
- `,exitCode:1}}else return{stdout:"",stderr:`ln: failed to create ${r?"symbolic ":""}link '${c}': File exists
94
- `,exitCode:1};try{if(r)await e.fs.symlink(a,l);else{let f=e.fs.resolvePath(e.cwd,a);if(!await e.fs.exists(f))return{stdout:"",stderr:`ln: failed to access '${a}': No such file or directory
95
- `,exitCode:1};await e.fs.link(f,l)}}catch(f){let d=f;return d.message.includes("EPERM")?{stdout:"",stderr:`ln: '${a}': hard link not allowed for directory
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?Ft(R).padStart(5):String(R).padStart(5),_=x.mtime??new Date(0),Pe=Mt(_);h+=`${S} 1 user user ${M} ${Pe} ${g}${v}
64
+ `}else h+=`${g}
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 Fl(g,e,n,s,i,l,a,c);h+=E.stdout,p+=E.stderr,E.exitCode!==0&&(b=E.exitCode)}else{let E=await us(g,e,n,s,i,o,d.length>1,l,a,c);h+=E.stdout,p+=E.stderr,E.exitCode!==0&&(b=E.exitCode)}}return{stdout:h,stderr:p,exitCode:b}}}});var hs={};O(hs,{mkdirCommand:()=>_l});var Ml,_l,ps=N(()=>{"use strict";ve();ae();Ml={recursive:{short:"p",long:"parents",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},_l={name:"mkdir",async execute(t,e){let r=H("mkdir",t,Ml);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
+ `,exitCode:1};let a="",o="",l=0;for(let c of i)try{let u=e.fs.resolvePath(e.cwd,c);await e.fs.mkdir(u,{recursive:n}),s&&(a+=`mkdir: created directory '${c}'
68
+ `)}catch(u){let f=Y(u);f.includes("ENOENT")||f.includes("no such file")?o+=`mkdir: cannot create directory '${c}': No such file or directory
69
+ `:f.includes("EEXIST")||f.includes("already exists")?o+=`mkdir: cannot create directory '${c}': File exists
70
+ `:o+=`mkdir: cannot create directory '${c}': ${f}
71
+ `,l=1}return{stdout:a,stderr:o,exitCode:l}}}});var ms={};O(ms,{touchCommand:()=>Wl});var Wl,ys=N(()=>{"use strict";ve();T();Wl={name:"touch",async execute(t,e){let r=[];for(let i of t){if(i.startsWith("--"))return L("touch",i);if(i.startsWith("-")&&i.length>1)return L("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 gs={};O(gs,{rmCommand:()=>Hl});var Bl,Hl,ws=N(()=>{"use strict";ve();ae();Bl={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"}},Hl={name:"rm",async execute(t,e){let r=H("rm",t,Bl);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
+ `,exitCode:1};let o="",l="",c=0;for(let u of a)try{let f=e.fs.resolvePath(e.cwd,u);if((await e.fs.stat(f)).isDirectory&&!n){l+=`rm: cannot remove '${u}': Is a directory
75
+ `,c=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")?l+=`rm: cannot remove '${u}': No such file or directory
77
+ `:d.includes("ENOTEMPTY")||d.includes("not empty")?l+=`rm: cannot remove '${u}': Directory not empty
78
+ `:l+=`rm: cannot remove '${u}': ${d}
79
+ `,c=1}}return{stdout:o,stderr:l,exitCode:c}}}});var Es={};O(Es,{cpCommand:()=>Gl});var Ul,zl,Gl,bs=N(()=>{"use strict";ve();ae();T();Ul={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"]},zl={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"}},Gl={name:"cp",async execute(t,e){if(C(t))return A(Ul);let r=H("cp",t,zl);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
+ `,exitCode:1};let l=o.pop()??"",c=o,u=e.fs.resolvePath(e.cwd,l),f="",d="",h=0,p=!1;try{p=(await e.fs.stat(u)).isDirectory}catch{}if(c.length>1&&!p)return{stdout:"",stderr:`cp: target '${l}' is not a directory
81
+ `,exitCode:1};for(let b of c)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 xs={};O(xs,{mvCommand:()=>Vl});var jl,ql,Vl,Ss=N(()=>{"use strict";ve();ae();T();jl={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"]},ql={force:{short:"f",long:"force",type:"boolean"},noClobber:{short:"n",long:"no-clobber",type:"boolean"},verbose:{short:"v",long:"verbose",type:"boolean"}},Vl={name:"mv",async execute(t,e){if(C(t))return A(jl);let r=H("mv",t,ql);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
+ `,exitCode:1};let o=a.pop()??"",l=a,c=e.fs.resolvePath(e.cwd,o),u="",f="",d=0,h=!1;try{h=(await e.fs.stat(c)).isDirectory}catch{}if(l.length>1&&!h)return{stdout:"",stderr:`mv: target '${o}' is not a directory
87
+ `,exitCode:1};for(let p of l)try{let b=e.fs.resolvePath(e.cwd,p),w=c;if(h){let g=p.split("/").pop()||p;w=c==="/"?`/${g}`:`${c}/${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
89
+ `:f+=`mv: cannot move '${p}': ${w}
90
+ `,d=1}return{stdout:u,stderr:f,exitCode:d}}}});var As={};O(As,{lnCommand:()=>Ql});var Zl,Ql,Cs=N(()=>{"use strict";T();Zl={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"]},Ql={name:"ln",async execute(t,e){if(C(t))return A(Zl);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
+ `,exitCode:1}}let a=t.slice(i);if(a.length<2)return{stdout:"",stderr:`ln: missing file operand
92
+ `,exitCode:1};let o=a[0],l=a[1],c=e.fs.resolvePath(e.cwd,l);if(await e.fs.exists(c))if(n)try{await e.fs.rm(c,{force:!0})}catch{return{stdout:"",stderr:`ln: cannot remove '${l}': Permission denied
93
+ `,exitCode:1}}else return{stdout:"",stderr:`ln: failed to create ${r?"symbolic ":""}link '${l}': File exists
94
+ `,exitCode:1};try{if(r)await e.fs.symlink(o,c);else{let f=e.fs.resolvePath(e.cwd,o);if(!await e.fs.exists(f))return{stdout:"",stderr:`ln: failed to access '${o}': No such file or directory
95
+ `,exitCode:1};await e.fs.link(f,c)}}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
- `,exitCode:1}}let u="";return s&&(u=`'${c}' -> '${a}'
98
- `),{stdout:u,stderr:"",exitCode:0}}}});var Kn={};I(Kn,{chmodCommand:()=>Il});async function Qn(t,e,r,n){let s="",o=await t.fs.readdir(e);for(let i of o){let a=e==="/"?`/${i}`:`${e}/${i}`;await t.fs.chmod(a,r),n&&(s+=`mode of '${a}' changed to ${r.toString(8).padStart(4,"0")}
99
- `),(await t.fs.stat(a)).isDirectory&&(s+=await Qn(t,a,r,n))}return s}function Pl(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 o=s[1]||"a",i=s[2],a=s[3];(o==="a"||o==="")&&(o="ugo");let c=0;a.includes("r")&&(c|=4),a.includes("w")&&(c|=2),(a.includes("x")||a.includes("X"))&&(c|=1);for(let l of o){let u=0;l==="u"?u=6:l==="g"?u=3:l==="o"&&(u=0);let f=c<<u;i==="+"?e|=f:i==="-"?e&=~f:i==="="&&(e&=~(7<<u),e|=f)}}return e}var kl,Il,Xn=C(()=>{"use strict";R();kl={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"]},Il={name:"chmod",async execute(t,e){if(S(t))return x(kl);if(t.length<2)return{stdout:"",stderr:`chmod: missing operand
97
+ `,exitCode:1}}let u="";return s&&(u=`'${l}' -> '${o}'
98
+ `),{stdout:u,stderr:"",exitCode:0}}}});var vs={};O(vs,{chmodCommand:()=>Xl});async function Ns(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 Ns(t,o,r,n))}return s}function Yl(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 l=0;o.includes("r")&&(l|=4),o.includes("w")&&(l|=2),(o.includes("x")||o.includes("X"))&&(l|=1);for(let c of i){let u=0;c==="u"?u=6:c==="g"?u=3:c==="o"&&(u=0);let f=l<<u;a==="+"?e|=f:a==="-"?e&=~f:a==="="&&(e&=~(7<<u),e|=f)}}return e}var Kl,Xl,ks=N(()=>{"use strict";T();Kl={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"]},Xl={name:"chmod",async execute(t,e){if(C(t))return A(Kl);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 o=t[s],i=t.slice(s+1),a;try{a=Pl(o)}catch{return{stdout:"",stderr:`chmod: invalid mode: '${o}'
103
- `,exitCode:1}}let c="",l="",u=!1;for(let f of i){let d=e.fs.resolvePath(e.cwd,f);try{if(await e.fs.chmod(d,a),n&&(c+=`mode of '${f}' changed to ${a.toString(8).padStart(4,"0")}
104
- `),r&&(await e.fs.stat(d)).isDirectory){let p=await Qn(e,d,a,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 Yn={};I(Yn,{pwdCommand:()=>Rl});var Rl,Jn=C(()=>{"use strict";Rl={name:"pwd",async execute(t,e){return{stdout:`${e.cwd}
106
- `,stderr:"",exitCode:0}}}});var es={};I(es,{readlinkCommand:()=>Dl});var Ol,Dl,ts=C(()=>{"use strict";R();Ol={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"]},Dl={name:"readlink",async execute(t,e){if(S(t))return x(Ol);let r=!1,n=0;for(;n<t.length&&t[n].startsWith("-");){let a=t[n];if(a==="-f"||a==="--canonicalize")r=!0,n++;else if(a==="--"){n++;break}else return{stdout:"",stderr:`readlink: invalid option -- '${a.slice(1)}'
102
+ `,exitCode:1};let i=t[s],a=t.slice(s+1),o;try{o=Yl(i)}catch{return{stdout:"",stderr:`chmod: invalid mode: '${i}'
103
+ `,exitCode:1}}let l="",c="",u=!1;for(let f of a){let d=e.fs.resolvePath(e.cwd,f);try{if(await e.fs.chmod(d,o),n&&(l+=`mode of '${f}' changed to ${o.toString(8).padStart(4,"0")}
104
+ `),r&&(await e.fs.stat(d)).isDirectory){let p=await Ns(e,d,o,n);l+=p}}catch{c+=`chmod: cannot access '${f}': No such file or directory
105
+ `,u=!0}}return{stdout:l,stderr:c,exitCode:u?1:0}}}});var Is={};O(Is,{pwdCommand:()=>Jl});var Jl,Rs=N(()=>{"use strict";Jl={name:"pwd",async execute(t,e){return{stdout:`${e.cwd}
106
+ `,stderr:"",exitCode:0}}}});var $s={};O($s,{readlinkCommand:()=>tc});var ec,tc,Ps=N(()=>{"use strict";T();ec={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"]},tc={name:"readlink",async execute(t,e){if(C(t))return A(ec);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
- `,exitCode:1};let o="",i=!1;for(let a of s){let c=e.fs.resolvePath(e.cwd,a);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}}o+=`${l}
109
- `}else{let l=await e.fs.readlink(c);o+=`${l}
110
- `}}catch{r?o+=`${c}
111
- `:i=!0}}return{stdout:o,stderr:"",exitCode:i?1:0}}}});function bt(t,e){let r=10,n=null,s=!1,o=!1,i=!1,a=[];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("+")?(i=!0,r=parseInt(u.slice(1),10)):r=parseInt(u,10)}else if(e==="tail"&&l.startsWith("-n+"))i=!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")o=!0;else if(l.match(/^-\d+$/))r=parseInt(l.slice(1),10);else{if(l.startsWith("--"))return{ok:!1,error:O(e,l)};if(l.startsWith("-")&&l!=="-")return{ok:!1,error:O(e,l)};a.push(l)}}return n!==null&&(Number.isNaN(n)||n<0)?{ok:!1,error:{stdout:"",stderr:`${e}: invalid number of bytes
108
+ `,exitCode:1};let i="",a=!1;for(let o of s){let l=e.fs.resolvePath(e.cwd,o);try{if(r){let c=l,u=new Set;for(;!u.has(c);){u.add(c);try{let f=await e.fs.readlink(c);if(f.startsWith("/"))c=f;else{let d=c.substring(0,c.lastIndexOf("/"))||"/";c=e.fs.resolvePath(d,f)}}catch{break}}i+=`${c}
109
+ `}else{let c=await e.fs.readlink(l);i+=`${c}
110
+ `}}catch{r?i+=`${l}
111
+ `:a=!0}}return{stdout:i,stderr:"",exitCode:a?1:0}}}});function _t(t,e){let r=10,n=null,s=!1,i=!1,a=!1,o=[];for(let l=0;l<t.length;l++){let c=t[l];if(c==="-n"&&l+1<t.length){let u=t[++l];e==="tail"&&u.startsWith("+")?(a=!0,r=parseInt(u.slice(1),10)):r=parseInt(u,10)}else if(e==="tail"&&c.startsWith("-n+"))a=!0,r=parseInt(c.slice(3),10);else if(c.startsWith("-n"))r=parseInt(c.slice(2),10);else if(c==="-c"&&l+1<t.length)n=parseInt(t[++l],10);else if(c.startsWith("-c"))n=parseInt(c.slice(2),10);else if(c.startsWith("--bytes="))n=parseInt(c.slice(8),10);else if(c.startsWith("--lines="))r=parseInt(c.slice(8),10);else if(c==="-q"||c==="--quiet"||c==="--silent")s=!0;else if(c==="-v"||c==="--verbose")i=!0;else if(c.match(/^-\d+$/))r=parseInt(c.slice(1),10);else{if(c.startsWith("--"))return{ok:!1,error:L(e,c)};if(c.startsWith("-")&&c!=="-")return{ok:!1,error:L(e,c)};o.push(c)}}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:o,files:a,fromLine:i}}}async function Et(t,e,r,n){let{quiet:s,verbose:o,files:i}=e;if(i.length===0)return{stdout:n(t.stdin),stderr:"",exitCode:0};let a="",c="",l=0,u=o||!s&&i.length>1;for(let f=0;f<i.length;f++){let d=i[f];u&&(f>0&&(a+=`
114
- `),a+=`==> ${d} <==
115
- `);try{let h=t.fs.resolvePath(t.cwd,d),p=await t.fs.readFile(h);a+=n(p)}catch{c+=`${r}: ${d}: No such file or directory
116
- `,l=1}}return{stdout:a,stderr:c,exitCode:l}}function rs(t,e,r){if(r!==null)return t.slice(0,r);if(e===0)return"";let n=0,s=0,o=t.length;for(;n<o&&s<e;){let i=t.indexOf(`
117
- `,n);if(i===-1)return`${t}
118
- `;s++,n=i+1}return n>0?t.slice(0,n):""}function ns(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
- `,c);if(f===-1)break;l++,c=f+1}let u=t.slice(c);return u.endsWith(`
113
+ `,exitCode:1}}:{ok:!0,options:{lines:r,bytes:n,quiet:s,verbose:i,files:o,fromLine:a}}}async function Wt(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="",l="",c=0,u=i||!s&&a.length>1;for(let f=0;f<a.length;f++){let d=a[f];u&&(f>0&&(o+=`
114
+ `),o+=`==> ${d} <==
115
+ `);try{let h=t.fs.resolvePath(t.cwd,d),p=await t.fs.readFile(h);o+=n(p)}catch{l+=`${r}: ${d}: No such file or directory
116
+ `,c=1}}return{stdout:o,stderr:l,exitCode:c}}function Os(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
+ `,n);if(a===-1)return`${t}
118
+ `;s++,n=a+1}return n>0?t.slice(0,n):""}function Ds(t,e,r,n){if(r!==null)return t.slice(-r);let s=t.length;if(s===0)return"";if(n){let l=0,c=1;for(;l<s&&c<e;){let f=t.indexOf(`
119
+ `,l);if(f===-1)break;c++,l=f+1}let u=t.slice(l);return u.endsWith(`
120
120
  `)?u:`${u}
121
- `}if(e===0)return"";let o=s-1;t[o]===`
122
- `&&o--;let i=0;for(;o>=0&&i<e;){if(t[o]===`
123
- `&&(i++,i===e)){o++;break}o--}o<0&&(o=0);let a=t.slice(o);return t[s-1]===`
124
- `?a:`${a}
125
- `}var ir=C(()=>{"use strict";R()});var ss={};I(ss,{headCommand:()=>Ml});var Tl,Ml,is=C(()=>{"use strict";R();ir();Tl={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"]},Ml={name:"head",async execute(t,e){if(S(t))return x(Tl);let r=bt(t,"head");if(!r.ok)return r.error;let{lines:n,bytes:s}=r.options;return Et(e,r.options,"head",o=>rs(o,n,s))}}});var os={};I(os,{tailCommand:()=>Ll});var Fl,Ll,as=C(()=>{"use strict";ir();R();Fl={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"]},Ll={name:"tail",async execute(t,e){if(S(t))return x(Fl);let r=bt(t,"tail");if(!r.ok)return r.error;let{lines:n,bytes:s,fromLine:o}=r.options;return Et(e,r.options,"tail",i=>ns(i,n,s,o??!1))}}});var cs={};I(cs,{wcCommand:()=>Hl});function ls(t){let e=t.length,r=0,n=0,s=!1;for(let o=0;o<e;o++){let i=t[o];i===`
126
- `?(r++,s&&(n++,s=!1)):i===" "||i===" "||i==="\r"?s&&(n++,s=!1):s=!0}return s&&n++,{lines:r,words:n,chars:e}}function or(t,e,r,n,s){let o=[];e&&o.push(String(t.lines)),r&&o.push(String(t.words)),n&&o.push(String(t.chars));let i=o.join(" ");return s&&(i+=` ${s}`),i}var Wl,_l,Hl,us=C(()=>{"use strict";Y();Le();R();Wl={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"]},_l={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"}},Hl={name:"wc",async execute(t,e){if(S(t))return x(Wl);let r=M("wc",t,_l);if(!r.ok)return r.error;let{lines:n,words:s}=r.result.flags,o=r.result.flags.bytes||r.result.flags.chars,i=r.result.positional;!n&&!s&&!o&&(n=s=o=!0);let a=await tt(e,i,{cmdName:"wc",stopOnError:!1});if(i.length===0){let d=ls(a.files[0].content);return{stdout:`${or(d,n,s,o,"")}
127
- `,stderr:"",exitCode:0}}let c="",l=0,u=0,f=0;for(let{filename:d,content:h}of a.files){let p=ls(h);l+=p.lines,u+=p.words,f+=p.chars,c+=`${or(p,n,s,o,d)}
128
- `}return i.length>1&&(c+=`${or({lines:l,words:u,chars:f},n,s,o,"total")}
129
- `),{stdout:c,stderr:a.stderr,exitCode:a.exitCode}}}});var ds={};I(ds,{statCommand:()=>Ul});function fs(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 Bl,zl,Ul,hs=C(()=>{"use strict";Y();R();Bl={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"]},zl={format:{short:"c",type:"string"}},Ul={name:"stat",async execute(t,e){if(S(t))return x(Bl);let r=M("stat",t,zl);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 o="",i="",a=!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=fs(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"),o+=`${f}
131
- `}else{let f=u.mode.toString(8).padStart(4,"0"),d=fs(u.mode,u.isDirectory);o+=` File: ${c}
132
- `,o+=` Size: ${u.size} Blocks: ${Math.ceil(u.size/512)}
133
- `,o+=`Access: (${f}/${d})
134
- `,o+=`Modify: ${u.mtime.toISOString()}
135
- `}}catch{i+=`stat: cannot stat '${c}': No such file or directory
136
- `,a=!0}}return{stdout:o,stderr:i,exitCode:a?1:0}}}});function ue(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 o=n.ignoreCase?`i:${s}`:s,i=ps.get(o);return i||(i=jl(s,n.ignoreCase),ps.set(o,i)),i.test(t)}function jl(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 o=n+1;for(;o<t.length&&t[o]!=="]";)o++;r+=t.slice(n,o+1),n=o}else s==="."||s==="+"||s==="^"||s==="$"||s==="{"||s==="}"||s==="("||s===")"||s==="|"||s==="\\"?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r,e?"i":"")}var ps,ar=C(()=>{"use strict";ps=new Map});var xt={};I(xt,{egrepCommand:()=>Ql,fgrepCommand:()=>Zl,grepCommand:()=>cr});function Gl(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 ms(t,e,r,n,s,o,i=!1,a=0,c=0){let l=t.split(`
137
- `),u=l.length,f=u>0&&l[u-1]===""?u-1:u;if(s){let g=0;for(let w=0;w<f;w++)e.lastIndex=0,e.test(l[w])!==r&&g++;return{output:`${o?`${o}:${g}`:String(g)}
138
- `,matched:g>0}}if(a===0&&c===0){let g=[],y=!1;for(let w=0;w<f;w++){let E=l[w];if(e.lastIndex=0,e.test(E)!==r)if(y=!0,i){e.lastIndex=0;for(let A=e.exec(E);A!==null;A=e.exec(E))g.push(o?`${o}:${A[0]}`:A[0]),A[0].length===0&&e.lastIndex++}else n?g.push(o?`${o}:${w+1}:${E}`:`${w+1}:${E}`):g.push(o?`${o}:${E}`:E)}return{output:g.length>0?`${g.join(`
121
+ `}if(e===0)return"";let i=s-1;t[i]===`
122
+ `&&i--;let a=0;for(;i>=0&&a<e;){if(t[i]===`
123
+ `&&(a++,a===e)){i++;break}i--}i<0&&(i=0);let o=t.slice(i);return t[s-1]===`
124
+ `?o:`${o}
125
+ `}var Rr=N(()=>{"use strict";T()});var Ts={};O(Ts,{headCommand:()=>nc});var rc,nc,Ls=N(()=>{"use strict";T();Rr();rc={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"]},nc={name:"head",async execute(t,e){if(C(t))return A(rc);let r=_t(t,"head");if(!r.ok)return r.error;let{lines:n,bytes:s}=r.options;return Wt(e,r.options,"head",i=>Os(i,n,s))}}});var Fs={};O(Fs,{tailCommand:()=>ic});var sc,ic,Ms=N(()=>{"use strict";Rr();T();sc={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"]},ic={name:"tail",async execute(t,e){if(C(t))return A(sc);let r=_t(t,"tail");if(!r.ok)return r.error;let{lines:n,bytes:s,fromLine:i}=r.options;return Wt(e,r.options,"tail",a=>Ds(a,n,s,i??!1))}}});var Ws={};O(Ws,{wcCommand:()=>lc});function _s(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 $r(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 ac,oc,lc,Bs=N(()=>{"use strict";ae();Ve();T();ac={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"]},oc={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"}},lc={name:"wc",async execute(t,e){if(C(t))return A(ac);let r=H("wc",t,oc);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 wt(e,a,{cmdName:"wc",stopOnError:!1});if(a.length===0){let d=_s(o.files[0].content);return{stdout:`${$r(d,n,s,i,"")}
127
+ `,stderr:"",exitCode:0}}let l="",c=0,u=0,f=0;for(let{filename:d,content:h}of o.files){let p=_s(h);c+=p.lines,u+=p.words,f+=p.chars,l+=`${$r(p,n,s,i,d)}
128
+ `}return a.length>1&&(l+=`${$r({lines:c,words:u,chars:f},n,s,i,"total")}
129
+ `),{stdout:l,stderr:o.stderr,exitCode:o.exitCode}}}});var Us={};O(Us,{statCommand:()=>fc});function Hs(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 cc,uc,fc,zs=N(()=>{"use strict";ae();T();cc={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"]},uc={format:{short:"c",type:"string"}},fc={name:"stat",async execute(t,e){if(C(t))return A(cc);let r=H("stat",t,uc);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 l of s){let c=e.fs.resolvePath(e.cwd,l);try{let u=await e.fs.stat(c);if(n){let f=n,d=u.mode.toString(8),h=Hs(u.mode,u.isDirectory);f=f.replace(/%n/g,l),f=f.replace(/%N/g,`'${l}'`),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=Hs(u.mode,u.isDirectory);i+=` File: ${l}
132
+ `,i+=` Size: ${u.size} Blocks: ${Math.ceil(u.size/512)}
133
+ `,i+=`Access: (${f}/${d})
134
+ `,i+=`Modify: ${u.mtime.toISOString()}
135
+ `}}catch{a+=`stat: cannot stat '${l}': 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=Gs.get(i);return a||(a=dc(s,n.ignoreCase),Gs.set(i,a)),a.test(t)}function dc(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 Gs,Pr=N(()=>{"use strict";Gs=new Map});var Bt={};O(Bt,{egrepCommand:()=>gc,fgrepCommand:()=>yc,grepCommand:()=>Dr});function pc(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 js(t,e,r,n,s,i,a=!1,o=0,l=0,c=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&&l===0){let g=[],E=!1,x=0;for(let S=0;S<d&&!(c>0&&x>=c);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(`
139
139
  `)}
140
- `:"",matched:y}}let d=[],h=0,p=new Set,b=[];for(let g=0;g<f;g++)e.lastIndex=0,e.test(l[g])!==r&&(b.push(g),h++);for(let g of b){for(let w=Math.max(0,g-a);w<g;w++)if(!p.has(w)){p.add(w);let E=l[w];n&&(E=`${w+1}-${E}`),o&&(E=`${o}-${E}`),d.push(E)}if(!p.has(g)){p.add(g);let w=l[g];if(i){e.lastIndex=0;for(let E=e.exec(w);E!==null;E=e.exec(w))d.push(o?`${o}:${E[0]}`:E[0]),E[0].length===0&&e.lastIndex++}else{let E=w;n&&(E=`${g+1}:${E}`),o&&(E=`${o}:${E}`),d.push(E)}}let y=Math.min(f-1,g+c);for(let w=g+1;w<=y;w++)if(!p.has(w)){p.add(w);let E=l[w];n&&(E=`${w+1}-${E}`),o&&(E=`${o}-${E}`),d.push(E)}}return{output:d.length>0?`${d.join(`
140
+ `:"",matched:E}}let h=[],p=0,b=new Set,w=[];for(let g=0;g<d&&!(c>0&&p>=c);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+l);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(`
141
141
  `)}
142
- `:"",matched:h>0}}async function lr(t,e,r=[],n=[],s=[]){let o=e.fs.resolvePath(e.cwd,t),i=[];try{if(!(await e.fs.stat(o)).isDirectory){let u=t.split("/").pop()||t;return n.length>0&&n.some(f=>ue(u,f,{stripQuotes:!0}))?[]:r.length>0&&!r.some(f=>ue(u,f,{stripQuotes:!0}))?[]:[t]}let c=t.split("/").pop()||t;if(s.length>0&&s.some(u=>ue(c,u,{stripQuotes:!0})))return[];let l=await e.fs.readdir(o);for(let u of l){if(u.startsWith("."))continue;let f=t==="."?u:`${t}/${u}`,d=await lr(f,e,r,n,s);i.push(...d)}}catch{}return i}async function Vl(t,e){let r=[],n=t.lastIndexOf("/"),s,o;if(n===-1?(s=e.cwd,o=t):(s=t.slice(0,n)||"/",o=t.slice(n+1)),t.includes("**")){let a=t.split("**"),c=a[0].replace(/\/$/,"")||".",l=a[1]||"";return await gs(c,l,e,r),r}let i=e.fs.resolvePath(e.cwd,s);try{let a=await e.fs.readdir(i);for(let c of a)if(ue(c,o,{stripQuotes:!0})){let l=n===-1?c:`${s}/${c}`;r.push(l)}}catch{}return r.sort()}async function gs(t,e,r,n){let s=r.fs.resolvePath(r.cwd,t);try{if(!(await r.fs.stat(s)).isDirectory){let a=t.split("/").pop()||"";if(e){let c=e.replace(/^\//,"");ue(a,c,{stripQuotes:!0})&&n.push(t)}return}let i=await r.fs.readdir(s);for(let a of i){let c=t==="."?a:`${t}/${a}`,l=r.fs.resolvePath(r.cwd,c);if((await r.fs.stat(l)).isDirectory)await gs(c,e,r,n);else if(e){let f=e.replace(/^\//,"");ue(a,f,{stripQuotes:!0})&&n.push(c)}}}catch{}}var ql,cr,Zl,Ql,St=C(()=>{"use strict";ar();R();ql={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","-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","-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"]},cr={name:"grep",async execute(t,e){if(S(t))return x(ql);let r=!1,n=!1,s=!1,o=!1,i=!1,a=!1,c=!1,l=!1,u=!1,f=!1,d=!1,h=!1,p=!1,b=0,g=0,y=[],w=[],E=[],$=null,A=[];for(let B=0;B<t.length;B++){let H=t[B];if(H.startsWith("-")&&H!=="-"){if(H==="-e"&&B+1<t.length){$=t[++B];continue}if(H.startsWith("--include=")){y.push(H.slice(10));continue}if(H.startsWith("--exclude=")){w.push(H.slice(10));continue}if(H.startsWith("--exclude-dir=")){E.push(H.slice(14));continue}let se=H.match(/^-([ABC])(\d+)$/);if(se){let T=parseInt(se[2],10);se[1]==="A"?g=T:se[1]==="B"?b=T:se[1]==="C"&&(b=T,g=T);continue}if((H==="-A"||H==="-B"||H==="-C")&&B+1<t.length){let T=parseInt(t[++B],10);H==="-A"?g=T:H==="-B"?b=T:(b=T,g=T);continue}let mt=H.startsWith("--")?[H]:H.slice(1).split("");for(let T of mt)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")o=!0;else if(T==="l"||T==="--files-with-matches")i=!0;else if(T==="L"||T==="--files-without-match")a=!0;else if(T==="r"||T==="R"||T==="--recursive")c=!0;else if(T==="w"||T==="--word-regexp")l=!0;else if(T==="E"||T==="--extended-regexp")u=!0;else if(T==="F"||T==="--fixed-strings")f=!0;else if(T==="o"||T==="--only-matching")d=!0;else if(T==="h"||T==="--no-filename")h=!0;else if(T==="q"||T==="--quiet"||T==="--silent")p=!0;else{if(T.startsWith("--"))return O("grep",T);if(T.length===1)return O("grep",`-${T}`)}}else $===null?$=H:A.push(H)}if($===null)return{stdout:"",stderr:`grep: missing pattern
143
- `,exitCode:2};let P;f?P=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"):u?P=$:P=Gl($),l&&(P=`\\b${P}\\b`);let J;try{J=new RegExp(P,r?"gi":"g")}catch{return{stdout:"",stderr:`grep: invalid regular expression: ${$}
144
- `,exitCode:2}}if(A.length===0&&e.stdin){let B=ms(e.stdin,J,s,n,o,"",d,b,g);return p?{stdout:"",stderr:"",exitCode:B.matched?0:1}:{stdout:B.output,stderr:"",exitCode:B.matched?0:1}}if(A.length===0)return{stdout:"",stderr:`grep: no input files
145
- `,exitCode:2};let L="",Se="",Fe=!1,pt=!1,je=[];for(let B of A)if(B.includes("*")||B.includes("?")||B.includes("[")){let H=await Vl(B,e);if(c)for(let se of H){let mt=await lr(se,e,y,w,E);je.push(...mt)}else je.push(...H)}else if(c){let H=await lr(B,e,y,w,E);je.push(...H)}else je.push(B);let qa=(je.length>1||c)&&!h;for(let B of je){let H=B.split("/").pop()||B;if(!(w.length>0&&!c&&w.some(se=>ue(H,se,{stripQuotes:!0})))&&!(y.length>0&&!c&&!y.some(se=>ue(H,se,{stripQuotes:!0}))))try{let se=e.fs.resolvePath(e.cwd,B);if((await e.fs.stat(se)).isDirectory){c||(Se+=`grep: ${B}: Is a directory
146
- `);continue}let T=await e.fs.readFile(se),sr=ms(T,J,s,n,o,qa?B:"",d,b,g);if(sr.matched){if(Fe=!0,p)return{stdout:"",stderr:"",exitCode:0};i?L+=`${B}
147
- `:a||(L+=sr.output)}else a?L+=`${B}
148
- `:o&&!i&&(L+=sr.output)}catch{Se+=`grep: ${B}: No such file or directory
149
- `,pt=!0}}let et;return pt?et=2:a?et=L.length>0?0:1:et=Fe?0:1,p?{stdout:"",stderr:"",exitCode:et}:{stdout:L,stderr:Se,exitCode:et}}};Zl={name:"fgrep",async execute(t,e){return cr.execute(["-F",...t],e)}},Ql={name:"egrep",async execute(t,e){return cr.execute(["-E",...t],e)}}});function Ct(t){return t instanceof te||t instanceof ie||t instanceof re}var be,te,ie,re,Ee,fe,z,V,Ce,j,Z=C(()=>{"use strict";be=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}},te=class extends be{levels;name="BreakError";constructor(e=1,r="",n=""){super("break",r,n),this.levels=e}},ie=class extends be{levels;name="ContinueError";constructor(e=1,r="",n=""){super("continue",r,n),this.levels=e}},re=class extends be{exitCode;name="ReturnError";constructor(e=0,r="",n=""){super("return",r,n),this.exitCode=e}},Ee=class extends be{exitCode;name="ErrexitError";constructor(e,r="",n=""){super(`errexit: command exited with status ${e}`,r,n),this.exitCode=e}},fe=class extends be{varName;name="NounsetError";constructor(e,r=""){super(`${e}: unbound variable`,r,`bash: ${e}: unbound variable
150
- `),this.varName=e}},z=class extends be{exitCode;name="ExitError";constructor(e,r="",n=""){super("exit",r,n),this.exitCode=e}},V=class extends be{name="ArithmeticError";constructor(e,r="",n=""){super(e,r,n),this.stderr=n||`bash: ${e}
151
- `}},Ce=class extends be{name="BadSubstitutionError";constructor(e,r="",n=""){super(e,r,n),this.stderr=n||`bash: ${e}: bad substitution
152
- `}},j=class extends be{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
- `}}});function bs(t){return{patternSpace:"",holdSpace:"",lineNumber:0,totalLines:t,deleted:!1,printed:!1,quit:!1,appendBuffer:[],substitutionMade:!1,lineNumberOutput:[],restartCycle:!1}}function Xl(t){return typeof t=="object"&&"first"in t&&"step"in t}function ys(t,e,r,n){if(t==="$")return e===r;if(typeof t=="number")return e===t;if(Xl(t)){let{first:s,step:o}=t;return o===0?e===s:(e-s)%o===0&&e>=s}if(typeof t=="object"&&"pattern"in t)try{return new RegExp(t.pattern).test(n)}catch{return!1}return!1}function Ge(t,e,r,n){if(!t||!t.start&&!t.end)return!0;let s=t.start,o=t.end;if(s!==void 0&&o===void 0)return ys(s,e,r,n);if(s!==void 0&&o!==void 0){let i=typeof s=="number"?s:s==="$"?r:1,a=typeof o=="number"?o:r;return typeof s=="object"&&"pattern"in s&&ys(s,e,r,n)?!0:e>=i&&e<=a}return!0}function ws(t,e,r){let n="",s=0;for(;s<t.length;){if(t[s]==="\\"&&s+1<t.length){let o=t[s+1];if(o==="&"){n+="&",s+=2;continue}if(o==="n"){n+=`
154
- `,s+=2;continue}if(o==="t"){n+=" ",s+=2;continue}let i=parseInt(o,10);if(i>=1&&i<=9){n+=r[i-1]||"",s+=2;continue}n+=o,s+=2;continue}if(t[s]==="&"){n+=e,s++;continue}n+=t[s],s++}return n}function Yl(t,e){let{lineNumber:r,totalLines:n,patternSpace:s}=e;if(t.type!=="label"&&Ge(t.address,r,n,s))switch(t.type){case"substitute":{let o=t,i="";o.global&&(i+="g"),o.ignoreCase&&(i+="i");try{let a=new RegExp(o.pattern,i),c=e.patternSpace;if(o.nthOccurrence&&o.nthOccurrence>0&&!o.global){let u=0,f=o.nthOccurrence;e.patternSpace=e.patternSpace.replace(new RegExp(o.pattern,`g${o.ignoreCase?"i":""}`),(d,...h)=>{if(u++,u===f){let p=h.slice(0,-2);return ws(o.replacement,d,p)}return d})}else e.patternSpace=e.patternSpace.replace(a,(u,...f)=>{let d=f.slice(0,-2);return ws(o.replacement,u,d)});c!==e.patternSpace&&(e.substitutionMade=!0,o.printOnMatch&&(e.printed=!0))}catch{}break}case"print":e.printed=!0;break;case"printFirstLine":{let o=e.patternSpace.indexOf(`
155
- `);o!==-1?e.lineNumberOutput.push(e.patternSpace.slice(0,o)):e.lineNumberOutput.push(e.patternSpace);break}case"delete":e.deleted=!0;break;case"deleteFirstLine":{let o=e.patternSpace.indexOf(`
156
- `);o!==-1?(e.patternSpace=e.patternSpace.slice(o+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+=`
142
+ `:"",matched:p>0}}async function Or(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 l=t.split("/").pop()||t;if(s.length>0&&s.some(u=>be(l,u,{stripQuotes:!0})))return[];let c=await e.fs.readdir(i);for(let u of c){if(u.startsWith("."))continue;let f=t==="."?u:`${t}/${u}`,d=await Or(f,e,r,n,s);a.push(...d)}}catch{}return a}async function mc(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("**"),l=o[0].replace(/\/$/,"")||".",c=o[1]||"";return await qs(l,c,e,r),r}let a=e.fs.resolvePath(e.cwd,s);try{let o=await e.fs.readdir(a);for(let l of o)if(be(l,i,{stripQuotes:!0})){let c=n===-1?l:`${s}/${l}`;r.push(c)}}catch{}return r.sort()}async function qs(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 l=e.replace(/^\//,"");be(o,l,{stripQuotes:!0})&&n.push(t)}return}let a=await r.fs.readdir(s);for(let o of a){let l=t==="."?o:`${t}/${o}`,c=r.fs.resolvePath(r.cwd,l);if((await r.fs.stat(c)).isDirectory)await qs(l,e,r,n);else if(e){let f=e.replace(/^\//,"");be(o,f,{stripQuotes:!0})&&n.push(l)}}}catch{}}var hc,Dr,yc,gc,Ht=N(()=>{"use strict";Pr();T();hc={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"]},Dr={name:"grep",async execute(t,e){if(C(t))return A(hc);let r=!1,n=!1,s=!1,i=!1,a=!1,o=!1,l=!1,c=!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 Ne=z.match(/^-m(\d+)$/);if(Ne){w=parseInt(Ne[1],10);continue}if(z==="-m"&&V+1<t.length){w=parseInt(t[++V],10);continue}let _e=z.match(/^-([ABC])(\d+)$/);if(_e){let D=parseInt(_e[2],10);_e[1]==="A"?E=D:_e[1]==="B"?g=D:_e[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 Ir=z.startsWith("--")?[z]:z.slice(1).split("");for(let D of Ir)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")l=!0;else if(D==="w"||D==="--word-regexp")c=!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 L("grep",D);if(D.length===1)return L("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:_=pc(R),c&&(_=`\\b${_}\\b`),u&&(_=`^${_}$`);let Pe;try{Pe=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=js(e.stdin,Pe,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 mc(V,e);if(l)for(let Ne of z){let _e=await Or(Ne,e,x,S,v);oe.push(..._e)}else oe.push(...z)}else if(l){let z=await Or(V,e,x,S,v);oe.push(...z)}else oe.push(V);let kr=(oe.length>1||l)&&!p;for(let V of oe){let z=V.split("/").pop()||V;if(!(S.length>0&&!l&&S.some(Ne=>be(z,Ne,{stripQuotes:!0})))&&!(x.length>0&&!l&&!x.some(Ne=>be(z,Ne,{stripQuotes:!0}))))try{let Ne=e.fs.resolvePath(e.cwd,V);if((await e.fs.stat(Ne)).isDirectory){l||(Ee+=`grep: ${V}: Is a directory
146
+ `);continue}let Ir=await e.fs.readFile(Ne),D=js(Ir,Pe,s,n,i,kr?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 gt;return de?gt=2:o?gt=K.length>0?0:1:gt=ne?0:1,b?{stdout:"",stderr:"",exitCode:gt}:{stdout:K,stderr:Ee,exitCode:gt}}};yc={name:"fgrep",async execute(t,e){return Dr.execute(["-F",...t],e)}},gc={name:"egrep",async execute(t,e){return Dr.execute(["-E",...t],e)}}});function Ut(t){return t instanceof ce||t instanceof pe||t instanceof ue}var Ie,ce,pe,ue,Re,xe,Z,te,Oe,W,X=N(()=>{"use strict";Ie=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 Ie{levels;name="BreakError";constructor(e=1,r="",n=""){super("break",r,n),this.levels=e}},pe=class extends Ie{levels;name="ContinueError";constructor(e=1,r="",n=""){super("continue",r,n),this.levels=e}},ue=class extends Ie{exitCode;name="ReturnError";constructor(e=0,r="",n=""){super("return",r,n),this.exitCode=e}},Re=class extends Ie{exitCode;name="ErrexitError";constructor(e,r="",n=""){super(`errexit: command exited with status ${e}`,r,n),this.exitCode=e}},xe=class extends Ie{varName;name="NounsetError";constructor(e,r=""){super(`${e}: unbound variable`,r,`bash: ${e}: unbound variable
150
+ `),this.varName=e}},Z=class extends Ie{exitCode;name="ExitError";constructor(e,r="",n=""){super("exit",r,n),this.exitCode=e}},te=class extends Ie{name="ArithmeticError";constructor(e,r="",n=""){super(e,r,n),this.stderr=n||`bash: ${e}
151
+ `}},Oe=class extends Ie{name="BadSubstitutionError";constructor(e,r="",n=""){super(e,r,n),this.stderr=n||`bash: ${e}: bad substitution
152
+ `}},W=class extends Ie{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
+ `}}});function Zs(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 Ec(t){return typeof t=="object"&&"first"in t&&"step"in t}function Et(t,e,r,n){if(t==="$")return e===r;if(typeof t=="number")return e===t;if(Ec(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 bc(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 it(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 Et(i,e,r,n);if(i!==void 0&&a!==void 0){let o=typeof i=="object"&&"pattern"in i,l=typeof a=="object"&&"pattern"in a;if(!o&&!l){let u=typeof i=="number"?i:i==="$"?r:1,f=typeof a=="number"?a:r;return e>=u&&e<=f}if(s){let u=bc(t),f=s.get(u);return f||(f={active:!1},s.set(u,f)),f.active?(Et(a,e,r,n)&&(f.active=!1,s.set(u,f)),!0):Et(i,e,r,n)?(f.active=!0,f.startLine=e,s.set(u,f),Et(a,e,r,n)&&(f.active=!1,s.set(u,f)),!0):!1}return Et(i,e,r,n)}return!0}function xc(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 Sc(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
+ `?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 Vs(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 Ac(t,e){let{lineNumber:r,totalLines:n,patternSpace:s}=e;if(t.type!=="label"&&it(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:xc(i.pattern);try{let l=new RegExp(o,a),c=l.test(e.patternSpace);if(l.lastIndex=0,c){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 Vs(i.replacement,d,p)}return d})}else e.patternSpace=e.patternSpace.replace(l,(u,...f)=>{let d=f.slice(0,-2);return Vs(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
+ `);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
+ `);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+=`
157
159
  ${e.patternSpace}`:e.holdSpace=e.patternSpace;break;case"get":e.patternSpace=e.holdSpace;break;case"getAppend":e.patternSpace+=`
158
- ${e.holdSpace}`;break;case"exchange":{let o=e.patternSpace;e.patternSpace=e.holdSpace,e.holdSpace=o;break}case"next":e.printed=!0;break;case"quit":e.quit=!0;break;case"transliterate":e.patternSpace=Jl(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 Jl(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 ur(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 o=n?.maxIterations??Kl,i=0,a=0,c=0;for(;c<t.length;){if(i++,i>o)throw new j(`sed: command execution exceeded maximum iterations (${o})`,"iterations");if(e.deleted||e.quit||e.restartCycle)break;let l=t[c];if(l.type==="nextAppend"){if(Ge(l.address,e.lineNumber,e.totalLines,e.patternSpace))if(r&&r.currentLineIndex+a+1<r.lines.length){a++;let u=r.lines[r.currentLineIndex+a];e.patternSpace+=`
159
- ${u}`,e.lineNumber=r.currentLineIndex+a+1}else{e.quit=!0,e.deleted=!0;break}c++;continue}if(l.type==="branch"){let u=l;if(Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)){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(Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)&&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(Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)&&!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;Ge(u.address,e.lineNumber,e.totalLines,e.patternSpace)&&ur(u.commands,e,r,n),c++;continue}Yl(l,e),c++}return a}var Kl,Es=C(()=>{"use strict";Z();Kl=1e4});function fr(t){if(t==="$")return"$";let e=t.match(/^(\d+)~(\d+)$/);if(e)return{first:parseInt(e[1],10),step:parseInt(e[2],10)};let r=parseInt(t,10);if(!Number.isNaN(r))return r;if(t.startsWith("/")&&t.endsWith("/"))return{pattern:t.slice(1,-1)}}function ec(t){let e=t,r,n,s=e.match(/^(\d+)~(\d+)/);if(s)return r={first:parseInt(s[1],10),step:parseInt(s[2],10)},e=e.slice(s[0].length),{range:{start:r,end:void 0},rest:e};if(e.startsWith("$")){if(r="$",e=e.slice(1),e.startsWith(",")){e=e.slice(1);let i=e.match(/^(\d+|\$)/);i&&(n=fr(i[1]),e=e.slice(i[0].length))}return{range:{start:r,end:n},rest:e}}let o=e.match(/^(\d+)/);if(o){if(r=parseInt(o[1],10),e=e.slice(o[0].length),e.startsWith(",")){e=e.slice(1);let i=e.match(/^(\d+|\$)/);i&&(n=fr(i[1]),e=e.slice(i[0].length))}return{range:{start:r,end:n},rest:e}}if(e.startsWith("/")){let i=1;for(;i<e.length&&e[i]!=="/";)e[i]==="\\"&&i+1<e.length?i+=2:i++;if(i<e.length){if(r={pattern:e.slice(1,i)},e=e.slice(i+1),e.startsWith(","))if(e=e.slice(1),e.startsWith("/")){let a=1;for(;a<e.length&&e[a]!=="/";)e[a]==="\\"&&a+1<e.length?a+=2:a++;a<e.length&&(n={pattern:e.slice(1,a)},e=e.slice(a+1))}else{let a=e.match(/^(\d+|\$)/);a&&(n=fr(a[1]),e=e.slice(a[0].length))}return{range:{start:r,end:n},rest:e}}}return{rest:e}}function Cs(t){let e=t.trim();if(!e)return{command:null};let{range:r,rest:n}=ec(e),s=n.trim();if(!s&&r)return{command:{type:"print",address:r}};let o=s[0];switch(o){case"p":return{command:{type:"print",address:r}};case"d":return{command:{type:"delete",address:r}};case"h":return{command:{type:"hold",address:r}};case"H":return{command:{type:"holdAppend",address:r}};case"g":if(s.length===1||/^\s/.test(s[1]))return{command:{type:"get",address:r}};break;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"P":return{command:{type:"printFirstLine",address:r}};case"D":return{command:{type:"deleteFirstLine",address:r}};case"q":return{command:{type:"quit",address:r}};case"z":return{command:{type:"zap",address:r}};case"=":return{command:{type:"lineNumber",address:r}};case"y":return tc(s,r);case"b":{let i=s.slice(1).trim();return{command:{type:"branch",address:r,label:i||void 0}}}case"t":{let i=s.slice(1).trim();return{command:{type:"branchOnSubst",address:r,label:i||void 0}}}case"T":{let i=s.slice(1).trim();return{command:{type:"branchOnNoSubst",address:r,label:i||void 0}}}case"{":return rc(s,r);case":":{let i=s.slice(1).trim();return i?{command:{type:"label",name:i}}:{command:null,error:"missing label name"}}case"a":if(s[1]==="\\"||s[1]===" "){let i=s.slice(2).replace(/^[\s]*/,"");return{command:{type:"append",address:r,text:i}}}break;case"i":if(s[1]==="\\"||s[1]===" "){let i=s.slice(2).replace(/^[\s]*/,"");return{command:{type:"insert",address:r,text:i}}}break;case"c":if(s[1]==="\\"||s[1]===" "){let i=s.slice(2).replace(/^[\s]*/,"");return{command:{type:"change",address:r,text:i}}}break;case"s":return Ss(s,r)}return s.startsWith("s")?Ss(s,r):o&&xs[o]?{command:null,error:`unsupported command: ${xs[o]}`}:{command:null,error:`invalid command: ${t}`}}function tc(t,e){if(!t.startsWith("y")||t.length<4)return{command:null,error:"invalid transliteration"};let r=t[1],n=2,s="",o="";for(;n<t.length&&t[n]!==r;)if(t[n]==="\\"&&n+1<t.length){let i=t[n+1];i==="n"?s+=`
160
- `:i==="t"?s+=" ":s+=i,n+=2}else s+=t[n],n++;if(n>=t.length)return{command:null,error:"unterminated transliteration source"};for(n++;n<t.length&&t[n]!==r;)if(t[n]==="\\"&&n+1<t.length){let i=t[n+1];i==="n"?o+=`
161
- `:i==="t"?o+=" ":o+=i,n+=2}else o+=t[n],n++;return s.length!==o.length?{command:null,error:"transliteration sets must have same length"}:{command:{type:"transliterate",address:e,source:s,dest:o}}}function Ss(t,e){if(!t.startsWith("s")||t.length<4)return{command:null,error:"invalid substitution"};let r=t[1],n="",s="",o="",i=2;for(;i<t.length&&t[i]!==r;)t[i]==="\\"&&i+1<t.length?(n+=t[i]+t[i+1],i+=2):(n+=t[i],i++);if(i>=t.length)return{command:null,error:"unterminated substitution pattern"};for(i++;i<t.length&&t[i]!==r;)t[i]==="\\"&&i+1<t.length?(s+=t[i]+t[i+1],i+=2):(s+=t[i],i++);i<t.length&&(i++,o=t.slice(i));let a,c=o.match(/(\d+)/);return c&&(a=parseInt(c[1],10)),{command:{type:"substitute",address:e,pattern:n,replacement:s,global:o.includes("g"),ignoreCase:o.includes("i"),printOnMatch:o.includes("p"),nthOccurrence:a}}}function rc(t,e){let r=1,n=1,s=!1,o="",i=0;for(;n<t.length&&r>0;){let u=t[n];if(u==="\\"&&n+1<t.length){n+=2;continue}if(!s&&u==="s"&&n+1<t.length&&/[^a-zA-Z0-9]/.test(t[n+1])){s=!0,o=t[n+1],i=0,n++;continue}if(s&&u===o){i++,i>=3&&(s=!1),n++;continue}s||(u==="{"?r++:u==="}"&&r--),n++}if(r!==0)return{command:null,error:"unmatched brace in grouped commands"};let a=t.slice(1,n-1).trim(),c=$s(a),l=[];for(let u of c){let f=Cs(u);if(f.error)return{command:null,error:f.error};f.command&&l.push(f.command)}return{command:{type:"group",address:e,commands:l}}}function As(t,e=!1){let r=[];for(let n of t){let s=$s(n);for(let o of s){let i=Cs(o);if(i.error)return{commands:[],error:i.error};i.command&&(i.command.type==="substitute"&&e&&(i.command.extendedRegex=!0),r.push(i.command))}}return{commands:r}}function $s(t){let e=[],r="",n=!1,s="",o=0,i=0,a=0;for(;a<t.length;){let c=t[a];if(c==="\\"&&a+1<t.length){r+=c+t[a+1],a+=2;continue}if(!n){if(c==="{"){i++,r+=c,a++;continue}if(c==="}"){i--,r+=c,a++;continue}}if(!n&&c==="s"&&a+1<t.length&&/[^a-zA-Z0-9]/.test(t[a+1])){s=t[a+1],o=0,n=!0,r+=c,a++;continue}if(n&&c===s){o++,r+=c,o>=3&&(n=!1),a++;continue}if(!n&&i===0&&c===";"){r.trim()&&e.push(r.trim()),r="",a++;continue}r+=c,a++}return r.trim()&&e.push(r.trim()),e}var xs,Ns=C(()=>{"use strict";xs={r:"r (read file) - file operations not supported",R:"R (read line from file) - file operations not supported",w:"w (write to file) - file operations not supported",W:"W (write first line to file) - file operations not supported",e:"e (execute shell command) - shell execution not supported",l:"l (list/escape special chars) - not implemented",F:"F (print filename) - not implemented",Q:"Q (quit without printing) - use 'q' instead",v:"v (version check) - not implemented"}});var vs={};I(vs,{sedCommand:()=>sc});function dr(t,e,r,n){let s=t.split(`
162
- `);s.length>0&&s[s.length-1]===""&&s.pop();let o=s.length,i="",a="",c=!1,l=n?{maxIterations:n.maxSedIterations}:void 0;for(let u=0;u<s.length;u++){let f={...bs(o),patternSpace:s[u],holdSpace:a,lineNumber:u+1,totalLines:o,substitutionMade:!1},d={lines:s,currentLineIndex:u},h=0,p=1e4,b=0;do{if(h++,h>p)break;f.restartCycle=!1;let w=ur(e,f,d,l);b+=w,d.currentLineIndex+=w}while(f.restartCycle&&!f.deleted&&!f.quit);u+=b,a=f.holdSpace,c=f.substitutionMade;for(let w of f.lineNumberOutput)i+=`${w}
163
- `;let g=[],y=[];for(let w of f.appendBuffer)w.startsWith("__INSERT__")?g.push(w.slice(10)):y.push(w);for(let w of g)i+=`${w}
164
- `;f.deleted||(r?f.printed&&(i+=`${f.patternSpace}
165
- `):i+=`${f.patternSpace}
166
- `);for(let w of y)i+=`${w}
167
- `;if(f.quit)break}return i}var nc,sc,ks=C(()=>{"use strict";R();Es();Ns();nc={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:
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=Sc(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
+ `});break;case"writeFirstLine":{let i=e.patternSpace.indexOf(`
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=Cc(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 Cc(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 c=0;c<t.length;c++){let u=t[c];u.type==="label"&&s.set(u.name,c)}let i=n?.maxIterations??wc,a=0,o=0,l=0;for(;l<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 c=t[l];if(c.type==="nextAppend"){if(it(c.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}l++;continue}if(c.type==="branch"){let u=c;if(it(u.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates)){if(u.label){let f=s.get(u.label);if(f!==void 0){l=f;continue}}break}l++;continue}if(c.type==="branchOnSubst"){let u=c;if(it(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){l=f;continue}}break}l++;continue}if(c.type==="branchOnNoSubst"){let u=c;if(it(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){l=f;continue}}break}l++;continue}if(c.type==="group"){let u=c;it(u.address,e.lineNumber,e.totalLines,e.patternSpace,e.rangeStates)&&Tr(u.commands,e,r,n),l++;continue}Ac(c,e),l++}return o}var wc,Qs=N(()=>{"use strict";X();wc=1e4});var I,zt,Ks=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={}));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
+ `?(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
+ `;)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
+ `?(this.advance(),{type:I.NEWLINE,value:`
168
+ `,line:e,column:r}):n===";"?(this.advance(),{type:I.SEMICOLON,value:";",line:e,column:r}):n==="{"?(this.advance(),{type:I.LBRACE,value:"{",line:e,column:r}):n==="}"?(this.advance(),{type:I.RBRACE,value:"}",line:e,column:r}):n===","?(this.advance(),{type:I.COMMA,value:",",line:e,column:r}):n==="$"?(this.advance(),{type:I.DOLLAR,value:"$",line:e,column:r}):this.isDigit(n)?this.readNumber():n==="/"?this.readPattern():n===":"?this.readLabelDef():this.readCommand()}readNumber(){let e=this.line,r=this.column,n="";for(;this.isDigit(this.peek());)n+=this.advance();if(this.peek()==="~"){this.advance();let s="";for(;this.isDigit(this.peek());)s+=this.advance();let i=parseInt(n,10),a=parseInt(s,10)||0;return{type:I.STEP,value:`${i}~${a}`,first:i,step:a,line:e,column:r}}return{type:I.NUMBER,value:parseInt(n,10),line:e,column:r}}readPattern(){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()===`
169
+ `)break;n+=this.advance()}return this.peek()==="/"&&this.advance(),{type:I.PATTERN,value:n,pattern:n,line:e,column:r}}readLabelDef(){let e=this.line,r=this.column;this.advance();let n="";for(;this.pos<this.input.length;){let s=this.peek();if(s===" "||s===" "||s===`
170
+ `||s===";"||s==="}"||s==="{")break;n+=this.advance()}return{type:I.LABEL_DEF,value:n,label:n,line:e,column:r}}readCommand(){let e=this.line,r=this.column,n=this.advance();switch(n){case"s":return this.readSubstitute(e,r);case"y":return this.readTransliterate(e,r);case"a":case"i":case"c":return this.readTextCommand(n,e,r);case"b":return this.readBranch(I.BRANCH,"b",e,r);case"t":return this.readBranch(I.BRANCH_ON_SUBST,"t",e,r);case"T":return this.readBranch(I.BRANCH_ON_NO_SUBST,"T",e,r);case"r":return this.readFileCommand(I.FILE_READ,"r",e,r);case"R":return this.readFileCommand(I.FILE_READ_LINE,"R",e,r);case"w":return this.readFileCommand(I.FILE_WRITE,"w",e,r);case"W":return this.readFileCommand(I.FILE_WRITE_LINE,"W",e,r);case"e":return this.readExecute(e,r);case"p":case"P":case"d":case"D":case"h":case"H":case"g":case"G":case"x":case"n":case"N":case"q":case"Q":case"z":case"=":case"l":case"F":case"v":return{type:I.COMMAND,value:n,line:e,column:r};default:return{type:I.ERROR,value:n,line:e,column:r}}}readSubstitute(e,r){let n=this.advance();if(!n||n===`
171
+ `)return{type:I.ERROR,value:"s",line:e,column:r};let s="";for(;this.pos<this.input.length&&this.peek()!==n;)if(this.peek()==="\\")s+=this.advance(),this.pos<this.input.length&&this.peek()!==`
172
+ `&&(s+=this.advance());else{if(this.peek()===`
173
+ `)break;s+=this.advance()}if(this.peek()!==n)return{type:I.ERROR,value:"unterminated substitution pattern",line:e,column:r};this.advance();let i="";for(;this.pos<this.input.length&&this.peek()!==n;)if(this.peek()==="\\")i+=this.advance(),this.pos<this.input.length&&this.peek()!==`
174
+ `&&(i+=this.advance());else{if(this.peek()===`
175
+ `)break;i+=this.advance()}this.peek()===n&&this.advance();let a="";for(;this.pos<this.input.length;){let o=this.peek();if(o==="g"||o==="i"||o==="p"||o==="I"||this.isDigit(o))a+=this.advance();else break}return{type:I.SUBSTITUTE,value:`s${n}${s}${n}${i}${n}${a}`,pattern:s,replacement:i,flags:a,line:e,column:r}}readTransliterate(e,r){let n=this.advance();if(!n||n===`
176
+ `)return{type:I.ERROR,value:"y",line:e,column:r};let s="";for(;this.pos<this.input.length&&this.peek()!==n;)if(this.peek()==="\\"){this.advance();let a=this.advance();a==="n"?s+=`
177
+ `:a==="t"?s+=" ":s+=a}else{if(this.peek()===`
178
+ `)break;s+=this.advance()}if(this.peek()!==n)return{type:I.ERROR,value:"unterminated transliteration source",line:e,column:r};this.advance();let i="";for(;this.pos<this.input.length&&this.peek()!==n;)if(this.peek()==="\\"){this.advance();let a=this.advance();a==="n"?i+=`
179
+ `:a==="t"?i+=" ":i+=a}else{if(this.peek()===`
180
+ `)break;i+=this.advance()}return this.peek()===n&&this.advance(),{type:I.TRANSLITERATE,value:`y${n}${s}${n}${i}${n}`,source:s,dest:i,line:e,column:r}}readTextCommand(e,r,n){this.peek()==="\\"&&this.advance(),this.peek()===" "&&this.advance();let s="";for(;this.pos<this.input.length&&this.peek()!==`
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
+ `||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
+ `||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 Xs(t,e=!1){return new Lr(t,e).parse()}var Lr,Ys=N(()=>{"use strict";Ks();Lr=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 Js={};O(Js,{sedCommand:()=>vc});async function Fr(t,e,r,n={}){let{limits:s,filename:i,fs:a,cwd:o}=n,l=t.split(`
185
+ `);l.length>0&&l[l.length-1]===""&&l.pop();let c=l.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<l.length;E++){let x={...Zs(c,i,h),patternSpace:l[E],holdSpace:d,lineNumber:E+1,totalLines:c,substitutionMade:!1},S={lines:l,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 kr=await a.readFile(ne);p.set(ne,kr.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 _=[],Pe=[];for(let K of x.appendBuffer)K.startsWith("__INSERT__")?_.push(K.slice(10)):Pe.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 Pe)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 Nc,vc,ei=N(()=>{"use strict";X();T();Qs();Ys();Nc={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:
168
192
  s/regexp/replacement/[flags] substitute
169
193
  d delete pattern space
170
194
  p print pattern space
@@ -180,36 +204,49 @@ ${u}`,e.lineNumber=r.currentLineIndex+a+1}else{e.quit=!0,e.deleted=!0;break}c++;
180
204
  N append next line to pattern space
181
205
  y/source/dest/ transliterate characters
182
206
  = print line number
207
+ l list pattern space (escape special chars)
183
208
  b [label] branch to label
184
209
  t [label] branch on substitution
210
+ T [label] branch if no substitution
185
211
  :label define label
186
212
  q quit
213
+ Q quit without printing
187
214
 
188
215
  Addresses:
189
216
  N line number
190
217
  $ last line
191
218
  /regexp/ lines matching regexp
192
- N,M range from line N to M`};sc={name:"sed",async execute(t,e){if(S(t))return x(nc);let r=[],n=[],s=!1,o=!1,i=!1,a=[];for(let d=0;d<t.length;d++){let h=t[d];if(h==="-n"||h==="--quiet"||h==="--silent")s=!0;else if(h==="-i"||h==="--in-place")o=!0;else if(h.startsWith("-i"))o=!0;else if(h==="-E"||h==="-r"||h==="--regexp-extended")i=!0;else if(h==="-e")d+1<t.length&&r.push(t[++d]);else if(h==="-f")d+1<t.length&&n.push(t[++d]);else{if(h.startsWith("--"))return O("sed",h);if(h.startsWith("-")&&h.length>1){for(let p of h.slice(1))if(p!=="n"&&p!=="e"&&p!=="f"&&p!=="i"&&p!=="E"&&p!=="r")return O("sed",`-${p}`);h.includes("n")&&(s=!0),h.includes("i")&&(o=!0),(h.includes("E")||h.includes("r"))&&(i=!0),h.includes("e")&&!h.includes("n")&&!h.includes("i")&&d+1<t.length&&r.push(t[++d]),h.includes("f")&&!h.includes("e")&&d+1<t.length&&n.push(t[++d])}else!h.startsWith("-")&&r.length===0&&n.length===0?r.push(h):h.startsWith("-")||a.push(h)}}for(let d of n){let h=e.fs.resolvePath(e.cwd,d);try{let p=await e.fs.readFile(h);for(let b of p.split(`
193
- `)){let g=b.trim();g&&!g.startsWith("#")&&r.push(g)}}catch{return{stdout:"",stderr:`sed: couldn't open file ${d}: No such file or directory
219
+ N,M range from line N to M
220
+ first~step every step-th line starting at first`};vc={name:"sed",async execute(t,e){if(C(t))return A(Nc);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 L("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 L("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
194
222
  `,exitCode:1}}}if(r.length===0)return{stdout:"",stderr:`sed: no script specified
195
- `,exitCode:1};let{commands:c,error:l}=As(r,i);if(l)return{stdout:"",stderr:`sed: ${l}
196
- `,exitCode:1};if(c.length===0)return{stdout:"",stderr:`sed: no valid commands
197
- `,exitCode:1};let u="";if(a.length===0)return u=e.stdin,{stdout:dr(u,c,s,e.limits),stderr:"",exitCode:0};if(o){for(let d of a){let h=e.fs.resolvePath(e.cwd,d);try{let p=await e.fs.readFile(h),b=dr(p,c,s,e.limits);await e.fs.writeFile(h,b)}catch{return{stdout:"",stderr:`sed: ${d}: No such file or directory
198
- `,exitCode:1}}}return{stdout:"",stderr:"",exitCode:0}}for(let d of a){let h=e.fs.resolvePath(e.cwd,d);try{u+=await e.fs.readFile(h)}catch{return{stdout:"",stderr:`sed: ${d}: No such file or directory
199
- `,exitCode:1}}}return{stdout:dr(u,c,s,e.limits),stderr:"",exitCode:0}}}});function Ps(t,e,r){if(t.length<2)return e.RSTART=0,e.RLENGTH=-1,0;let n=String(r(t[0],e)),s=t[1].trim();s.startsWith("/")&&s.endsWith("/")&&(s=s.slice(1,-1));try{let i=new RegExp(s).exec(n);if(i)return e.RSTART=i.index+1,e.RLENGTH=i[0].length,e.RSTART}catch{}return e.RSTART=0,e.RLENGTH=-1,0}function Rs(t,e,r){if(t.length<3)return"";let n=String(r(t[0],e)),s=String(r(t[1],e)),o=String(r(t[2],e)),i=t.length>=4?String(r(t[3],e)):e.line;n.startsWith("/")&&n.endsWith("/")&&(n=n.slice(1,-1));try{let a=o.toLowerCase()==="g",c=a?0:parseInt(o,10)||1;if(a){let l=new RegExp(n,"g");return i.replace(l,(u,...f)=>Is(s,u,f.slice(0,-2)))}else{let l=0,u=new RegExp(n,"g");return i.replace(u,(f,...d)=>(l++,l===c?Is(s,f,d.slice(0,-2)):f))}}catch{return i}}function Is(t,e,r){let n="",s=0;for(;s<t.length;)if(t[s]==="\\"&&s+1<t.length){let o=t[s+1];if(o==="&")n+="&",s+=2;else if(o==="0")n+=e,s+=2;else if(o>="1"&&o<="9"){let i=parseInt(o,10)-1;n+=r[i]||"",s+=2}else o==="n"?(n+=`
200
- `,s+=2):o==="t"?(n+=" ",s+=2):(n+=o,s+=2)}else t[s]==="&"?(n+=e,s++):(n+=t[s],s++);return n}function Os(t,e,r){return t.length===0?e.line.length:String(r(t[0],e)).length}function Ds(t,e,r){if(t.length<2)return"";let n=String(r(t[0],e)),s=Number(r(t[1],e))-1;if(t.length>=3){let o=Number(r(t[2],e));return n.substr(Math.max(0,s),o)}return n.substr(Math.max(0,s))}function Ts(t,e,r){if(t.length<2)return 0;let n=String(r(t[0],e)),s=String(r(t[1],e)),o=n.indexOf(s);return o===-1?0:o+1}function Ms(t,e,r){if(t.length<2)return 0;let n=String(r(t[0],e)),s=t[1].trim(),o=t.length>=3?String(r(t[2],e)):e.FS,i=n.split(o===" "?/\s+/:o);e.arrays[s]||(e.arrays[s]={}),e.arrays[s]={};for(let a=0;a<i.length;a++)e.arrays[s][String(a+1)]=i[a];return i.length}function Fs(t,e,r){if(t.length<2)return 0;let n=String(r(t[0],e)),s=String(r(t[1],e)),o=t.length>=3?t[2].trim():"$0",i;if(o==="$0")i=e.line;else if(o.startsWith("$")){let u=parseInt(o.slice(1),10)-1;i=e.fields[u]||""}else i=String(e.vars[o]??"");let a=new RegExp(n),c=i.replace(a,s),l=c!==i?1:0;if(o==="$0")e.line=c;else if(o.startsWith("$")){let u=parseInt(o.slice(1),10)-1;e.fields[u]=c}else e.vars[o]=c;return l}function Ls(t,e,r){if(t.length<2)return 0;let n=String(r(t[0],e)),s=String(r(t[1],e)),o=t.length>=3?t[2].trim():"$0",i;if(o==="$0")i=e.line;else if(o.startsWith("$")){let f=parseInt(o.slice(1),10)-1;i=e.fields[f]||""}else i=String(e.vars[o]??"");let a=new RegExp(n,"g"),c=i.match(a),l=c?c.length:0,u=i.replace(a,s);if(o==="$0")e.line=u;else if(o.startsWith("$")){let f=parseInt(o.slice(1),10)-1;e.fields[f]=u}else e.vars[o]=u;return l}function Ws(t,e,r){return t.length===0?"":String(r(t[0],e)).toLowerCase()}function _s(t,e,r){return t.length===0?"":String(r(t[0],e)).toUpperCase()}function Hs(t,e,r){if(t.length===0)return"";let n=String(r(t[0],e)),s=t.slice(1),o=0,i="",a=0;for(;a<n.length;)if(n[a]==="%"&&a+1<n.length){let c=a+1;for(;c<n.length&&/[-+ #0]/.test(n[c]);)c++;for(;c<n.length&&/\d/.test(n[c]);)c++;if(n[c]===".")for(c++;c<n.length&&/\d/.test(n[c]);)c++;let l=n[c];if(l==="s"||l==="d"||l==="i"||l==="f"){let u=s[o]?r(s[o],e):"";i+=String(u),o++,a=c+1}else l==="%"?(i+="%",a=c+1):i+=n[a++]}else if(n[a]==="\\"&&a+1<n.length){let c=n[a+1];c==="n"?i+=`
201
- `:c==="t"?i+=" ":c==="r"?i+="\r":i+=c,a+=2}else i+=n[a++];return i}var Bs=C(()=>{"use strict"});function v(t,e){if(t=t.trim(),t.startsWith('"')&&t.endsWith('"'))return oc(t.slice(1,-1));let r=t.match(/^(\w+)\s*\((.*)\)$/);if(r){let c=r[1],l=r[2],u=ic(l);switch(c){case"length":return Os(u,e,v);case"substr":return Ds(u,e,v);case"index":return Ts(u,e,v);case"split":return Ms(u,e,v);case"sub":return Fs(u,e,v);case"gsub":return Ls(u,e,v);case"match":return Ps(u,e,v);case"gensub":return Rs(u,e,v);case"tolower":return Ws(u,e,v);case"toupper":return _s(u,e,v);case"sprintf":return Hs(u,e,v);case"int":return Math.floor(Number(v(u[0]||"0",e)));case"sqrt":return Math.sqrt(Number(v(u[0]||"0",e)));case"sin":return Math.sin(Number(v(u[0]||"0",e)));case"cos":return Math.cos(Number(v(u[0]||"0",e)));case"log":return Math.log(Number(v(u[0]||"0",e)));case"exp":return Math.exp(Number(v(u[0]||"0",e)));case"atan2":{let f=Number(v(u[0]||"0",e)),d=Number(v(u[1]||"0",e));return Math.atan2(f,d)}case"rand":return e.random?e.random():Math.random();case"srand":{let f=u.length>0?Number(v(u[0],e)):Date.now();return e.vars._srand_seed=f,f}case"systime":case"mktime":case"strftime":throw new Error(`function '${c}()' is not implemented`);case"system":throw new Error("system() is not supported - shell execution not allowed in sandboxed environment");case"close":throw new Error("close() is not supported - file operations not allowed");case"fflush":throw new Error("fflush() is not supported - file operations not allowed");case"nextfile":throw new Error("nextfile is not supported - use 'next' instead")}if(e.functions?.[c])return lc(c,u,e)}let n=t.match(/^(\w+)\[(.+)\]$/);if(n){let c=n[1],l=n[2],u=String(v(l,e));return e.arrays[c]?e.arrays[c][u]??"":""}if(t.startsWith("$")){if(t.startsWith("$(")){let l=t.slice(2,-1),u=Number(v(l,e));return u===0?e.line:e.fields[u-1]||""}let c=t.match(/^\$(\d+)$/);if(c){let l=parseInt(c[1],10);return l===0?e.line:e.fields[l-1]||""}}if(t==="NR")return e.NR;if(t==="NF")return e.NF;if(t==="FNR")return e.FNR;if(t==="FS")return e.FS;if(t==="OFS")return e.OFS;if(t==="FILENAME")return e.FILENAME;if(t==="RSTART")return e.RSTART;if(t==="RLENGTH")return e.RLENGTH;if(e.vars[t]!==void 0)return e.vars[t];let s=t.match(/^(.+?)\s*\?\s*(.+?)\s*:\s*(.+)$/);if(s){let c=de(s[1].trim(),e);return v(c?s[2].trim():s[3].trim(),e)}let o=t.match(/^(.+?)\s*(\^|\*\*)\s*(.+)$/);if(o){let c=Number(v(o[1],e)),l=Number(v(o[3],e));return c**l}let i=t.match(/^(.+?)\s+([+\-*/%])\s+(.+)$/);if(i){let c=Number(v(i[1],e)),l=Number(v(i[3],e));switch(i[2]){case"+":return c+l;case"-":return c-l;case"*":return c*l;case"/":return l!==0?c/l:0;case"%":return c%l}}let a=t.match(/^([a-zA-Z_]\w*|\$\d+|\d+(?:\.\d+)?)\s*([+\-*/%])\s*(.+)$/);if(a){let c=Number(v(a[1],e)),l=Number(v(a[3],e));switch(a[2]){case"+":return c+l;case"-":return c-l;case"*":return c*l;case"/":return l!==0?c/l:0;case"%":return c%l}}return t.includes("$")||t.includes('"')?ac(t,e):/^-?\d+(\.\d+)?$/.test(t)?parseFloat(t):/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)?"":t}function ic(t){let e=[],r="",n=0,s=!1;for(let o=0;o<t.length;o++){let i=t[o];i==='"'&&t[o-1]!=="\\"?(s=!s,r+=i):!s&&i==="("?(n++,r+=i):!s&&i===")"?(n--,r+=i):!s&&i===","&&n===0?(e.push(r.trim()),r=""):r+=i}return r.trim()&&e.push(r.trim()),e}function oc(t){return t.replace(/\\n/g,`
202
- `).replace(/\\t/g," ").replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function ac(t,e){let r="",n=0;for(;n<t.length;){for(;n<t.length&&/\s/.test(t[n]);)n++;if(n>=t.length)break;if(t[n]==='"'){let s="";for(n++;n<t.length&&t[n]!=='"';)if(t[n]==="\\"&&n+1<t.length){let o=t[n+1];o==="n"?s+=`
203
- `:o==="t"?s+=" ":o==="r"?s+="\r":s+=o,n+=2}else s+=t[n++];n++,r+=s}else if(t[n]==="$"){n++;let s="";for(;n<t.length&&/\d/.test(t[n]);)s+=t[n++];let o=parseInt(s,10);r+=o===0?e.line:e.fields[o-1]||""}else{let s="";for(;n<t.length&&!/[\s$"]/.test(t[n]);)s+=t[n++];s==="NR"?r+=e.NR:s==="NF"?r+=e.NF:e.vars[s]!==void 0?r+=e.vars[s]:r+=s}}return r}function de(t,e){if(t=t.trim(),t.includes("&&"))return zs(t,"&&").every(l=>de(l,e));if(t.includes("||"))return zs(t,"||").some(l=>de(l,e));if(t.startsWith("!"))return!de(t.slice(1).trim(),e);if(t.startsWith("(")&&t.endsWith(")"))return de(t.slice(1,-1),e);if(t.startsWith("/")&&t.endsWith("/"))return new RegExp(t.slice(1,-1)).test(e.line);let r=t.match(/^(.+)\s+in\s+(\w+)$/);if(r){let c=String(v(r[1].trim(),e)),l=r[2];return!!(e.arrays[l]&&e.arrays[l][c]!==void 0)}let n=t.match(/^NR\s*(==|!=|>|<|>=|<=)\s*(\d+)$/);if(n){let c=n[1],l=parseInt(n[2],10);return Us(e.NR,c,l)}let s=t.match(/^\$(\d+)\s*~\s*\/([^/]+)\/$/);if(s){let c=parseInt(s[1],10),l=s[2],u=c===0?e.line:e.fields[c-1]||"";return new RegExp(l).test(u)}let o=t.match(/^\$(\d+)\s*!~\s*\/([^/]+)\/$/);if(o){let c=parseInt(o[1],10),l=o[2],u=c===0?e.line:e.fields[c-1]||"";return!new RegExp(l).test(u)}let i=t.match(/^(.+?)\s*(==|!=|>=|<=|>|<)\s*(.+)$/);if(i){let c=i[1].trim(),l=i[2],u=i[3].trim(),f=v(c,e),d=v(u,e);return Us(f,l,d)}let a=v(t,e);return typeof a=="number"?a!==0:typeof a=="string"?a!=="":!!a}function zs(t,e){let r=[],n="",s=0,o=!1;for(let i=0;i<t.length;i++){if(t[i]==='"'&&t[i-1]!=="\\"&&(o=!o),!o){if(t[i]==="(")s++;else if(t[i]===")")s--;else if(s===0&&t.slice(i,i+e.length)===e){r.push(n.trim()),n="",i+=e.length-1;continue}}n+=t[i]}return n.trim()&&r.push(n.trim()),r}function Us(t,e,r){let n=typeof t=="number"?t:parseFloat(String(t)),s=typeof r=="number"?r:parseFloat(String(r));if(!Number.isNaN(n)&&!Number.isNaN(s))switch(e){case"==":return n===s;case"!=":return n!==s;case">":return n>s;case"<":return n<s;case">=":return n>=s;case"<=":return n<=s}else{let i=String(t),a=String(r);switch(e){case"==":return i===a;case"!=":return i!==a;case">":return i>a;case"<":return i<a;case">=":return i>=a;case"<=":return i<=a}}return!1}function lc(t,e,r){let n=r.functions[t];if(!n)throw new Error(`awk: undefined function '${t}'`);let s="__func_depth__",o=r.vars[s]||0;if(o>=js)throw new Error(`awk: function '${t}' exceeded maximum recursion depth (${js})`);r.vars[s]=o+1;let i={};for(let c of n.params)i[c]=r.vars[c];for(let c=0;c<n.params.length;c++)c<e.length?r.vars[n.params[c]]=v(e[c],r):r.vars[n.params[c]]="";let a="";try{let c=n.body.match(/return\s+(.+)/);c&&(a=v(c[1].trim(),r))}finally{for(let c of n.params){let l=i[c];l!==void 0?r.vars[c]=l:delete r.vars[c]}r.vars[s]=o}return a}var js,qs=C(()=>{"use strict";Bs();js=100});function Gs(t){let e={begin:null,main:[],end:null,functions:{}},r=t.trim(),n=/function\s+(\w+)\s*\(([^)]*)\)\s*\{/g;for(let i=n.exec(r);i!==null;i=n.exec(r)){let a=i[1],c=i[2],l=i.index,u=i.index+i[0].length-1,f=oe(r,u);if(f!==-1){let d=c.split(",").map(p=>p.trim()).filter(p=>p.length>0),h=r.slice(u+1,f).trim();e.functions[a]={params:d,body:h},r=r.slice(0,l)+r.slice(f+1),r=r.trim(),n.lastIndex=0}}let s=r.match(/\bBEGIN\s*\{/);if(s&&s.index!==void 0){let i=s.index,a=r.slice(i+5).trim();if(a.startsWith("{")){let c=oe(a,0);c!==-1&&(e.begin=a.slice(1,c).trim(),r=r.slice(0,i)+a.slice(c+1),r=r.trim())}}let o=r.match(/\bEND\s*\{/);if(o&&o.index!==void 0){let i=o.index,a=r.slice(i+3).trim();if(a.startsWith("{")){let c=oe(a,0);c!==-1&&(e.end=a.slice(1,c).trim(),r=r.slice(0,i).trim())}}for(;r&&(r=r.trim(),!!r);){let i=!1;if(r.startsWith("{")){let a=oe(r,0);a!==-1&&(e.main.push({pattern:null,action:r.slice(1,a).trim()}),r=r.slice(a+1).trim(),i=!0)}if(!i){let a=r.match(/^\/([^/]*)\/\s*,\s*\/([^/]*)\/\s*\{/);if(a){let c=r.indexOf("{"),l=oe(r,c);l!==-1&&(e.main.push({pattern:null,range:{start:a[1],end:a[2]},action:r.slice(c+1,l).trim()}),r=r.slice(l+1).trim(),i=!0)}}if(!i){let a=r.match(/^\/([^/]*)\/\s*\{/);if(a){let c=r.indexOf("{"),l=oe(r,c);l!==-1&&(e.main.push({pattern:a[1],action:r.slice(c+1,l).trim()}),r=r.slice(l+1).trim(),i=!0)}}if(!i){let a=r.match(/^\/([^/]*)\/\s*,\s*\/([^/]*)\//);a&&(e.main.push({pattern:null,range:{start:a[1],end:a[2]},action:"print"}),r=r.slice(a[0].length).trim(),i=!0)}if(!i){let a=r.match(/^\/([^/]*)\//);a&&(e.main.push({pattern:a[1],action:"print"}),r=r.slice(a[0].length).trim(),i=!0)}if(!i&&r.includes("{")){let a=r.indexOf("{"),c=oe(r,a);c!==-1&&(e.main.push({pattern:r.slice(0,a).trim()||null,action:r.slice(a+1,c).trim()}),r=r.slice(c+1).trim(),i=!0)}i||(r.startsWith("print")||r.startsWith("printf")?(e.main.push({pattern:null,action:r}),r=""):(e.main.push({pattern:r,action:"print"}),r=""))}return e.main.length===0&&!e.begin&&!e.end&&e.main.push({pattern:null,action:"print"}),e}function oe(t,e){if(t[e]!=="{")return-1;let r=1,n=!1,s="";for(let o=e+1;o<t.length;o++){let i=t[o],a=t[o-1];if(n)i===s&&a!=="\\"&&(n=!1);else if(i==='"'||i==="'")n=!0,s=i;else if(i==="{")r++;else if(i==="}"&&(r--,r===0))return o}return-1}var hr=C(()=>{"use strict"});function he(t,e){let r="",n=cc(t);for(let s of n)if(r+=pr(s,e),e.shouldNext||e.shouldExit||e.loopBreak||e.loopContinue)break;return r}function cc(t){let e=[],r="",n=0,s=0,o=!1;for(let i=0;i<t.length;i++){let a=t[i];if(a==='"'&&t[i-1]!=="\\"&&(o=!o),!o){if(a==="{")n++;else if(a==="}")n--;else if(a==="(")s++;else if(a===")")s--;else if((a===";"||a===`
204
- `)&&n===0&&s===0){r.trim()&&e.push(r.trim()),r="";continue}}r+=a}return r.trim()&&e.push(r.trim()),e}function pr(t,e){if(t=t.trim(),!t)return"";if(t.startsWith("if"))return uc(t,e);if(t.startsWith("while"))return fc(t,e);if(t.startsWith("do"))return dc(t,e);if(t.startsWith("for"))return hc(t,e);if(t==="print"||t==="print $0")return`${e.line}
205
- `;if(t.startsWith("print ")){let i=t.slice(6).trim();return`${pc(i,e)}
206
- `}if(t.startsWith("printf ")){let i=t.slice(7).trim();return mc(i,e)}if(t==="next")return e.shouldNext=!0,"";if(t==="exit"||t.startsWith("exit ")){if(e.shouldExit=!0,t.startsWith("exit ")){let i=t.slice(5).trim();e.exitCode=Number(v(i,e))||0}else e.exitCode=0;return""}if(t==="break")return e.loopBreak=!0,"";if(t==="continue")return e.loopContinue=!0,"";if(t==="getline"||t.startsWith("getline "))return gc(t,e);let r=t.match(/^delete\s+(\w+)\[(.+)\]$/);if(r){let i=r[1],a=r[2],c=String(v(a,e));return e.arrays[i]&&delete e.arrays[i][c],""}let n=t.match(/^(\w+)\[(.+)\]\s*=\s*(.+)$/);if(n){let i=n[1],a=n[2],c=n[3];e.arrays[i]||(e.arrays[i]={});let l=String(v(a,e)),u=v(c,e);return e.arrays[i][l]=u,""}if(t.match(/^(\w+)\+\+$/)){let i=t.slice(0,-2),a=Number(e.vars[i])||0;return e.vars[i]=a+1,""}if(t.match(/^(\w+)--$/)){let i=t.slice(0,-2),a=Number(e.vars[i])||0;return e.vars[i]=a-1,""}if(t.match(/^\+\+(\w+)$/)){let i=t.slice(2),a=Number(e.vars[i])||0;return e.vars[i]=a+1,""}if(t.match(/^--(\w+)$/)){let i=t.slice(2),a=Number(e.vars[i])||0;return e.vars[i]=a-1,""}let s=t.match(/^(\w+)\[(.+)\]\+\+$/);if(s){let i=s[1],a=s[2];e.arrays[i]||(e.arrays[i]={});let c=String(v(a,e)),l=Number(e.arrays[i][c])||0;return e.arrays[i][c]=l+1,""}if(t.includes("+=")){let i=t.indexOf("+="),a=t.slice(0,i).trim(),c=t.slice(i+2).trim(),l=Number(v(c,e))||0,u=a.match(/^(\w+)\[(.+)\]$/);if(u){let f=u[1],d=u[2];e.arrays[f]||(e.arrays[f]={});let h=String(v(d,e)),p=Number(e.arrays[f][h])||0;e.arrays[f][h]=p+l}else{let f=Number(e.vars[a])||0;e.vars[a]=f+l}return""}if(t.includes("-=")){let i=t.indexOf("-="),a=t.slice(0,i).trim(),c=t.slice(i+2).trim(),l=Number(e.vars[a])||0,u=Number(v(c,e))||0;return e.vars[a]=l-u,""}if(t.includes("*=")){let i=t.indexOf("*="),a=t.slice(0,i).trim(),c=t.slice(i+2).trim(),l=Number(e.vars[a])||0,u=Number(v(c,e))||0;return e.vars[a]=l*u,""}if(t.includes("/=")){let i=t.indexOf("/="),a=t.slice(0,i).trim(),c=t.slice(i+2).trim(),l=Number(e.vars[a])||0,u=Number(v(c,e))||0;return e.vars[a]=u!==0?l/u:0,""}if(t.includes("=")&&!t.includes("==")&&!t.includes("!=")&&!t.includes(">=")&&!t.includes("<=")){let i=t.indexOf("="),a=t.slice(0,i).trim(),c=t.slice(i+1).trim();return e.vars[a]=v(c,e),""}return t.match(/^(\w+)\s*\((.+)\)$/)&&v(t,e),""}function uc(t,e){let r=t.indexOf("(");if(r===-1)return"";let n=1,s=r+1;for(;s<t.length&&n>0;)t[s]==="("?n++:t[s]===")"&&n--,s++;s--;let o=t.slice(r+1,s).trim(),i=t.slice(s+1).trim(),a,c=null,l;if(i.startsWith("{")){let u=oe(i,0);a=i.slice(1,u).trim(),l=i.slice(u+1).trim()}else{let u=i.indexOf(";");if(u!==-1)a=i.slice(0,u).trim(),l=i.slice(u+1).trim();else{let f=i.indexOf(" else ");f!==-1?(a=i.slice(0,f).trim(),l=i.slice(f+1).trim()):(a=i,l="")}}if(l.startsWith("else")){let u=l.slice(4).trim();if(u.startsWith("{")){let f=oe(u,0);c=u.slice(1,f).trim()}else if(u.startsWith("if"))c=u;else{let f=u.indexOf(";");c=f!==-1?u.slice(0,f).trim():u}}return de(o,e)?he(a,e):c?he(c,e):""}function fc(t,e){let r=t.indexOf("(");if(r===-1)return"";let n=1,s=r+1;for(;s<t.length&&n>0;)t[s]==="("?n++:t[s]===")"&&n--,s++;s--;let o=t.slice(r+1,s).trim(),i=t.slice(s+1).trim(),a;if(i.startsWith("{")){let f=oe(i,0);a=i.slice(1,f).trim()}else a=i;let c="",l=0,u=e.maxIterations??mr;for(;de(o,e);){if(l++,l>u)throw new j(`awk: while loop exceeded maximum iterations (${u})`,"iterations",c);if(e.loopContinue=!1,c+=he(a,e),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext)break}return c}function dc(t,e){if(!t.match(/^do\s*\{/))return"";let n=t.indexOf("{"),s=oe(t,n);if(s===-1)return"";let o=t.slice(n+1,s).trim(),a=t.slice(s+1).trim().match(/^while\s*\((.+)\)\s*;?$/);if(!a)return"";let c=a[1].trim(),l="",u=0,f=e.maxIterations??mr;do{if(u++,u>f)throw new j(`awk: do-while loop exceeded maximum iterations (${f})`,"iterations",l);if(e.loopContinue=!1,l+=he(o,e),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext)break}while(de(c,e));return l}function hc(t,e){let r=t.indexOf("(");if(r===-1)return"";let n=1,s=r+1;for(;s<t.length&&n>0;)t[s]==="("?n++:t[s]===")"&&n--,s++;s--;let o=t.slice(r+1,s).trim(),i=t.slice(s+1).trim(),a;if(i.startsWith("{")){let g=oe(i,0);a=i.slice(1,g).trim()}else a=i;let c=o.match(/^(\w+)\s+in\s+(\w+)$/);if(c){let g=c[1],y=c[2],w="";if(e.arrays[y])for(let E of Object.keys(e.arrays[y])){if(e.vars[g]=E,e.loopContinue=!1,w+=he(a,e),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext)break}return w}let l=o.split(";").map(g=>g.trim());if(l.length!==3)return"";let[u,f,d]=l;u&&pr(u,e);let h="",p=0,b=e.maxIterations??mr;for(;!f||de(f,e);){if(p++,p>b)throw new j(`awk: for loop exceeded maximum iterations (${b})`,"iterations",h);if(e.loopContinue=!1,h+=he(a,e),e.loopBreak){e.loopBreak=!1;break}if(e.shouldExit||e.shouldNext)break;d&&pr(d,e)}return h}function pc(t,e){let r=[],n=Vs(t);for(let s of n)r.push(String(v(s.trim(),e)));return r.join(e.OFS)}function Vs(t){let e=[],r="",n=!1,s=0;for(let o=0;o<t.length;o++){let i=t[o];i==='"'&&t[o-1]!=="\\"?(n=!n,r+=i):i==="("&&!n?(s++,r+=i):i===")"&&!n?(s--,r+=i):i===","&&!n&&s===0?(e.push(r),r=""):r+=i}return r&&e.push(r),e}function mc(t,e){let r=t.match(/^"([^"]*)"(.*)$/);if(!r)return"";let n=r[1],s=r[2].trim(),o=s?Vs(s.replace(/^,\s*/,"")):[],i=0,a="",c=0;for(;c<n.length;)if(n[c]==="%"&&c+1<n.length){let l=c+1,u="",f="";for(;l<n.length&&/[-+ #0]/.test(n[l]);)l++;for(;l<n.length&&/\d/.test(n[l]);)u+=n[l++];if(n[l]===".")for(l++;l<n.length&&/\d/.test(n[l]);)f+=n[l++];let d=n[l];if(d==="s"){let h=o[i]?String(v(o[i],e)):"";u&&(h=h.padStart(parseInt(u,10))),a+=h,i++,c=l+1}else if(d==="d"||d==="i"){let h=o[i]?Math.floor(Number(v(o[i],e))):0,p=String(h);u&&(p=p.padStart(parseInt(u,10))),a+=p,i++,c=l+1}else if(d==="f"){let h=o[i]?Number(v(o[i],e)):0,p=f?parseInt(f,10):6,b=h.toFixed(p);u&&(b=b.padStart(parseInt(u,10))),a+=b,i++,c=l+1}else if(d==="x"||d==="X"){let h=o[i]?Math.floor(Number(v(o[i],e))):0,p=Math.abs(h).toString(16);d==="X"&&(p=p.toUpperCase()),u&&(p=p.padStart(parseInt(u,10),"0")),a+=h<0?`-${p}`:p,i++,c=l+1}else if(d==="o"){let h=o[i]?Math.floor(Number(v(o[i],e))):0,p=Math.abs(h).toString(8);u&&(p=p.padStart(parseInt(u,10),"0")),a+=h<0?`-${p}`:p,i++,c=l+1}else if(d==="c"){let h=o[i]?v(o[i],e):"";typeof h=="number"?a+=String.fromCharCode(h):a+=String(h).charAt(0)||"",i++,c=l+1}else if(d==="e"||d==="E"){let h=o[i]?Number(v(o[i],e)):0,p=f?parseInt(f,10):6,b=h.toExponential(p);d==="E"&&(b=b.toUpperCase()),u&&(b=b.padStart(parseInt(u,10))),a+=b,i++,c=l+1}else if(d==="g"||d==="G"){let h=o[i]?Number(v(o[i],e)):0,p=f?parseInt(f,10):6,b=Math.floor(Math.log10(Math.abs(h))),g;h===0?g="0":b<-4||b>=p?(g=h.toExponential(p-1),d==="G"&&(g=g.toUpperCase())):g=h.toPrecision(p),g=g.replace(/\.?0+$/,"").replace(/\.?0+e/,"e"),u&&(g=g.padStart(parseInt(u,10))),a+=g,i++,c=l+1}else d==="%"?(a+="%",c=l+1):a+=n[c++]}else if(n[c]==="\\"&&c+1<n.length){let l=n[c+1];l==="n"?a+=`
207
- `:l==="t"?a+=" ":l==="r"?a+="\r":a+=l,c+=2}else a+=n[c++];return a}function gc(t,e){if(!e.lines||e.lineIndex===void 0)return"";let r=e.lineIndex+1;if(r>=e.lines.length)return"";let n=e.lines[r];if(t==="getline")e.line=n,e.fields=e.fieldSep?n.split(e.fieldSep):n.split(/\s+/),e.NF=e.fields.length,e.NR++,e.lineIndex=r;else{let s=t.slice(8).trim();s&&!s.startsWith("<")&&(e.vars[s]=n,e.NR++,e.lineIndex=r)}return""}function Zs(t,e){if(t===null)return!0;if(t.startsWith("/")&&t.endsWith("/"))return new RegExp(t.slice(1,-1)).test(e.line);if(/^(NR|NF|\$\d+)\s*(==|!=|>|<|>=|<=|~)/.test(t)||/\s*(==|!=|>|<|>=|<=)\s*/.test(t))return de(t,e);try{return new RegExp(t).test(e.line)}catch{return de(t,e)}}var mr,Qs=C(()=>{"use strict";Z();qs();hr();mr=1e4});var Js={};I(Js,{awkCommand:()=>wc});function Ks(t){return t.replace(/\\t/g," ").replace(/\\n/g,`
208
- `).replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function Xs(t){if(t===" ")return/\s+/;if(/[[\](){}.*+?^$|\\]/.test(t))try{return new RegExp(t)}catch{return new RegExp(Ys(t))}return new RegExp(Ys(t))}function Ys(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var yc,wc,ei=C(()=>{"use strict";R();Qs();hr();yc={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"]},wc={name:"awk",async execute(t,e){if(S(t))return x(yc);let r=/\s+/,n=" ",s={},o=0;for(let g=0;g<t.length;g++){let y=t[g];if(y==="-F"&&g+1<t.length)n=Ks(t[++g]),r=Xs(n),o=g+1;else if(y.startsWith("-F"))n=Ks(y.slice(2)),r=Xs(n),o=g+1;else if(y==="-v"&&g+1<t.length){let w=t[++g],E=w.indexOf("=");if(E>0){let $=w.slice(0,E),A=w.slice(E+1);s[$]=A}o=g+1}else{if(y.startsWith("--"))return O("awk",y);if(y.startsWith("-")&&y.length>1){let w=y[1];if(w!=="F"&&w!=="v")return O("awk",`-${w}`);o=g+1}else if(!y.startsWith("-")){o=g;break}}}if(o>=t.length)return{stdout:"",stderr:`awk: missing program
209
- `,exitCode:1};let i=t[o],a=t.slice(o+1),{begin:c,main:l,end:u,functions:f}=Gs(i),d={FS:n,OFS:" ",NR:0,NF:0,FNR:0,FILENAME:"",RSTART:0,RLENGTH:-1,fields:[],line:"",vars:s,arrays:{},functions:f||{},fieldSep:r,maxIterations:e.limits?.maxAwkIterations},h="";if(c&&(h+=he(c,d),d.shouldExit))return{stdout:h,stderr:"",exitCode:d.exitCode||0};let p=[];if(a.length>0)for(let g of a)try{let y=e.fs.resolvePath(e.cwd,g),E=(await e.fs.readFile(y)).split(`
210
- `);E.length>0&&E[E.length-1]===""&&E.pop(),p.push({filename:g,lines:E})}catch{return{stdout:"",stderr:`awk: ${g}: No such file or directory
211
- `,exitCode:1}}else{let g=e.stdin.split(`
212
- `);g.length>0&&g[g.length-1]===""&&g.pop(),p.push({filename:"",lines:g})}let b=l.map(()=>!1);for(let g of p){for(d.FILENAME=g.filename,d.FNR=0,d.lines=g.lines,d.lineIndex=-1;d.lineIndex<g.lines.length-1;){d.lineIndex++;let y=g.lines[d.lineIndex];d.NR++,d.FNR++,d.line=y,d.fields=y.split(r),d.NF=d.fields.length,d.shouldNext=!1;for(let w=0;w<l.length&&!(d.shouldExit||d.shouldNext);w++){let E=l[w];if(E.range){let $=new RegExp(E.range.start),A=new RegExp(E.range.end);b[w]?(h+=he(E.action,d),A.test(y)&&(b[w]=!1)):$.test(y)&&(b[w]=!0,h+=he(E.action,d),A.test(y)&&(b[w]=!1))}else Zs(E.pattern,d)&&(h+=he(E.action,d))}if(d.shouldExit)break}if(d.shouldExit)break}return u&&!d.shouldExit&&(h+=he(u,d)),{stdout:h,stderr:"",exitCode:d.exitCode||0}}}});function gr(t,e,r){let n=r!==null?r:/\s+/,s=t.split(n),o=e.startField-1;if(o>=s.length)return"";if(e.endField===void 0){let c=s[o]||"";return e.startChar!==void 0&&(c=c.slice(e.startChar-1)),e.ignoreLeading&&(c=c.trimStart()),c}let i=Math.min(e.endField-1,s.length-1),a="";for(let c=o;c<=i&&c<s.length;c++){let l=s[c]||"";if(c===o&&e.startChar!==void 0&&(l=l.slice(e.startChar-1)),c===i&&e.endChar!==void 0){let u=c===o&&e.startChar!==void 0?e.endChar-e.startChar+1:e.endChar;l=l.slice(0,u)}c>o&&(a+=r||" "),a+=l}return e.ignoreLeading&&(a=a.trimStart()),a}function bc(t,e,r,n){if(r){let i=parseFloat(t)||0,a=parseFloat(e)||0;return i-a}let s=t,o=e;return n&&(s=s.toLowerCase(),o=o.toLowerCase()),s.localeCompare(o)}function ti(t){let{keys:e,fieldDelimiter:r,numeric:n,ignoreCase:s,reverse:o}=t;return(i,a)=>{if(e.length===0){let l=i,u=a;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 o?-p:p}}else f=l.localeCompare(u);return o?-f:f}for(let l of e){let u=gr(i,l,r),f=gr(a,l,r),d=l.numeric??n,h=l.ignoreCase??s,p=l.reverse??o,b=bc(u,f,d,h);if(b!==0)return p?-b:b}let c=i.localeCompare(a);return o?-c:c}}function ri(t,e){if(e.keys.length===0){if(e.ignoreCase){let s=new Set;return t.filter(o=>{let i=o.toLowerCase();return s.has(i)?!1:(s.add(i),!0)})}return[...new Set(t)]}let r=e.keys[0],n=new Set;return t.filter(s=>{let o=gr(s,r,e.fieldDelimiter);return(r.ignoreCase??e.ignoreCase)&&(o=o.toLowerCase()),n.has(o)?!1:(n.add(o),!0)})}var ni=C(()=>{"use strict"});function At(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 o=n.split(",");if(o.length===0||o[0]==="")return null;let i=o[0].split("."),a=parseInt(i[0],10);if(Number.isNaN(a)||a<1)return null;if(e.startField=a,i.length>1&&i[1]){let c=parseInt(i[1],10);!Number.isNaN(c)&&c>=1&&(e.startChar=c)}if(o.length>1&&o[1]){let c=o[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 si=C(()=>{"use strict"});var ii={};I(ii,{sortCommand:()=>xc});var Ec,xc,oi=C(()=>{"use strict";Le();R();ni();si();Ec={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]]
223
+ `,exitCode:1};let{commands:l,error:c}=Xs(r,a);if(c)return{stdout:"",stderr:`sed: ${c}
224
+ `,exitCode:1};if(l.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 Fr(u,l,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 Fr(h,l,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 Fr(u,l,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 Mr(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 ti=N(()=>{"use strict"});function ri(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 ni=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 kc(t,e,r){return t.length===0?e.line.length:ee(await r.evalExpr(t[0])).length}async function Ic(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 Rc(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 $c(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 l=ee(await r.evalExpr(t[2]));a=l===" "?/\s+/:l}else e.FS===" "&&(a=/\s+/);let o=n.split(a);e.arrays[i]={};for(let l=0;l<o.length;l++)e.arrays[i][String(l+1)]=o[l];return o.length}async function Pc(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),l=a.replace(o,ii(s)),c=l!==a?1:0;if(i==="$0")e.line=l,e.fields=e.FS===" "?l.trim().split(/\s+/).filter(Boolean):l.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]=l,e.NF=e.fields.length,e.line=e.fields.join(e.OFS)}else e.vars[i]=l;return c}catch{return 0}}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,"g"),l=a.match(o),c=l?l.length:0,u=a.replace(o,ii(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 c}catch{return 0}}function ii(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 Dc(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",l=o?0:parseInt(i,10)||1;if(o){let c=new RegExp(n,"g");return a.replace(c,(u,...f)=>si(s,u,f.slice(0,-2)))}else{let c=0,u=new RegExp(n,"g");return a.replace(u,(f,...d)=>(c++,c===l?si(s,f,d.slice(0,-2)):f))}}catch{return a}}function si(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 Lc(t,e,r){return t.length===0?"":ee(await r.evalExpr(t[0])).toLowerCase()}async function Fc(t,e,r){return t.length===0?"":ee(await r.evalExpr(t[0])).toUpperCase()}async function Mc(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 Br(n,s)}async function _c(t,e,r){return t.length===0?0:Math.floor(me(await r.evalExpr(t[0])))}async function Wc(t,e,r){return t.length===0?0:Math.sqrt(me(await r.evalExpr(t[0])))}async function Bc(t,e,r){return t.length===0?0:Math.sin(me(await r.evalExpr(t[0])))}async function Hc(t,e,r){return t.length===0?0:Math.cos(me(await r.evalExpr(t[0])))}async function Uc(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 zc(t,e,r){return t.length===0?0:Math.log(me(await r.evalExpr(t[0])))}async function Gc(t,e,r){return t.length===0?1:Math.exp(me(await r.evalExpr(t[0])))}function jc(t,e,r){return e.random?e.random():Math.random()}async function qc(t,e,r){let n=t.length>0?me(await r.evalExpr(t[0])):Date.now();return e.vars._srand_seed=n,n}function _r(t,e){return()=>{throw new Error(`${t}() is not supported - ${e}`)}}function Wr(t){return()=>{throw new Error(`function '${t}()' is not implemented`)}}function Br(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="",l="";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]);)l+=t[i++];let c=t[i],u=e[r];switch(c){case"s":{let f=u!==void 0?String(u):"";if(l&&(f=f.substring(0,parseInt(l,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=l?parseInt(l,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=l?parseInt(l,10):6,h=f.toExponential(d);if(c==="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=l?parseInt(l,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),c==="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(c==="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 ai,Hr=N(()=>{"use strict";ai={length:kc,substr:Ic,index:Rc,split:$c,sub:Pc,gsub:Oc,match:Dc,gensub:Tc,tolower:Lc,toupper:Fc,sprintf:Mc,int:_c,sqrt:Wc,sin:Bc,cos:Hc,atan2:Uc,log:zc,exp:Gc,rand:jc,srand:qc,system:_r("system","shell execution not allowed in sandboxed environment"),close:_r("close","file operations not allowed"),fflush:_r("fflush","file operations not allowed"),systime:Wr("systime"),mktime:Wr("mktime"),strftime:Wr("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 Ur(t){if(typeof t=="number")return!0;let e=String(t).trim();return e===""?!1:!Number.isNaN(Number(e))}function bt(t,e){try{return new RegExp(t).test(e)}catch{return!1}}var at=N(()=>{"use strict"});function oi(t,e){return t.FS===" "?e.trim().split(/\s+/).filter(Boolean):e.split(t.fieldSep)}function Ze(t,e){return e===0?t.line:e<0||e>t.fields.length?"":t.fields[e-1]??""}function ot(t,e,r){if(e===0)t.line=U(r),t.fields=oi(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 xt(t,e){t.line=e,t.fields=oi(t,e),t.NF=t.fields.length}function li(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 Gt=N(()=>{"use strict";at()});function Qe(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 Be(t,e,r){switch(e){case"FS":li(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 Ke(t,e,r){return e==="ARGV"?t.ARGV[r]??"":t.arrays[e]?.[r]??""}function lt(t,e,r,n){t.arrays[e]||(t.arrays[e]={}),t.arrays[e][r]=n}function ci(t,e,r){return e==="ARGV"?t.ARGV[r]!==void 0:t.arrays[e]?.[r]!==void 0}function ui(t,e,r){t.arrays[e]&&delete t.arrays[e][r]}function fi(t,e){delete t.arrays[e]}var zr=N(()=>{"use strict";Gt();at()});function di(t){Gr=t}async function $(t,e){switch(e.type){case"number":return e.value;case"string":return e.value;case"regex":return bt(e.pattern,t.line)?1:0;case"field":return Vc(t,e);case"variable":return Qe(t,e.name);case"array_access":return Zc(t,e);case"binary":return Qc(t,e);case"unary":return Yc(t,e);case"ternary":return he(await $(t,e.condition))?$(t,e.consequent):$(t,e.alternate);case"call":return Jc(t,e.name,e.args);case"assignment":return tu(t,e);case"pre_increment":return ru(t,e.operand);case"pre_decrement":return nu(t,e.operand);case"post_increment":return su(t,e.operand);case"post_decrement":return iu(t,e.operand);case"in":return au(t,e.key,e.array);case"getline":return ou(t,e.variable,e.file);case"tuple":return cu(t,e.elements);default:return""}}async function Vc(t,e){let r=Math.floor(B(await $(t,e.index)));return Ze(t,r)}async function Zc(t,e){let r=U(await $(t,e.key));return Ke(t,e.array,r)}async function Qc(t,e){let r=e.operator;if(r==="||")return he(await $(t,e.left))||he(await $(t,e.right))?1:0;if(r==="&&")return he(await $(t,e.left))&&he(await $(t,e.right))?1:0;if(r==="~"){let o=await $(t,e.left),l=e.right.type==="regex"?e.right.pattern:U(await $(t,e.right));try{return new RegExp(l).test(U(o))?1:0}catch{return 0}}if(r==="!~"){let o=await $(t,e.left),l=e.right.type==="regex"?e.right.pattern:U(await $(t,e.right));try{return new RegExp(l).test(U(o))?0:1}catch{return 1}}let n=await $(t,e.left),s=await $(t,e.right);if(r===" ")return U(n)+U(s);if(Kc(r))return Xc(n,s,r);let i=B(n),a=B(s);return ri(i,a,r)}function Kc(t){return["<","<=",">",">=","==","!="].includes(t)}function Xc(t,e,r){let n=Ur(t),s=Ur(e);if(n&&s){let o=B(t),l=B(e);switch(r){case"<":return o<l?1:0;case"<=":return o<=l?1:0;case">":return o>l?1:0;case">=":return o>=l?1:0;case"==":return o===l?1:0;case"!=":return o!==l?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 Yc(t,e){let r=await $(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 Jc(t,e,r){let n=ai[e];if(n)return n(r,t,{evalExpr:i=>$(t,i)});let s=t.functions.get(e);return s?eu(t,s,r):""}async function eu(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 $(t,r[i]):"";t.vars[a]=o}t.hasReturn=!1,t.returnValue=void 0,Gr&&await Gr(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 tu(t,e){let r=await $(t,e.value),n=e.target,s=e.operator,i;if(s==="=")i=r;else{let a;if(n.type==="field"){let c=Math.floor(B(await $(t,n.index)));a=Ze(t,c)}else if(n.type==="variable")a=Qe(t,n.name);else{let c=U(await $(t,n.key));a=Ke(t,n.array,c)}let o=B(a),l=B(r);switch(s){case"+=":i=o+l;break;case"-=":i=o-l;break;case"*=":i=o*l;break;case"/=":i=l!==0?o/l:0;break;case"%=":i=l!==0?o%l:0;break;case"^=":i=o**l;break;default:i=r}}if(n.type==="field"){let a=Math.floor(B(await $(t,n.index)));ot(t,a,i)}else if(n.type==="variable")Be(t,n.name,i);else{let a=U(await $(t,n.key));lt(t,n.array,a,i)}return i}async function ru(t,e){let r;if(e.type==="field"){let n=Math.floor(B(await $(t,e.index)));r=B(Ze(t,n))+1,ot(t,n,r)}else if(e.type==="variable")r=B(Qe(t,e.name))+1,Be(t,e.name,r);else{let n=U(await $(t,e.key));r=B(Ke(t,e.array,n))+1,lt(t,e.array,n,r)}return r}async function nu(t,e){let r;if(e.type==="field"){let n=Math.floor(B(await $(t,e.index)));r=B(Ze(t,n))-1,ot(t,n,r)}else if(e.type==="variable")r=B(Qe(t,e.name))-1,Be(t,e.name,r);else{let n=U(await $(t,e.key));r=B(Ke(t,e.array,n))-1,lt(t,e.array,n,r)}return r}async function su(t,e){let r;if(e.type==="field"){let n=Math.floor(B(await $(t,e.index)));r=B(Ze(t,n)),ot(t,n,r+1)}else if(e.type==="variable")r=B(Qe(t,e.name)),Be(t,e.name,r+1);else{let n=U(await $(t,e.key));r=B(Ke(t,e.array,n)),lt(t,e.array,n,r+1)}return r}async function iu(t,e){let r;if(e.type==="field"){let n=Math.floor(B(await $(t,e.index)));r=B(Ze(t,n)),ot(t,n,r-1)}else if(e.type==="variable")r=B(Qe(t,e.name)),Be(t,e.name,r-1);else{let n=U(await $(t,e.key));r=B(Ke(t,e.array,n)),lt(t,e.array,n,r-1)}return r}async function au(t,e,r){let n;if(e.type==="tuple"){let s=[];for(let i of e.elements)s.push(U(await $(t,i)));n=s.join(t.SUBSEP)}else n=U(await $(t,e));return ci(t,r,n)?1:0}async function ou(t,e,r){if(r)return lu(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?Be(t,e,s):xt(t,s),t.NR++,t.lineIndex=n,1}async function lu(t,e,r){if(!t.fs||!t.cwd)return-1;let n=U(await $(t,r)),s=t.fs.resolvePath(t.cwd,n),i=`__fc_${s}`,a=`__fi_${s}`,o,l;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,l=-1}catch{return-1}else o=JSON.parse(t.vars[i]),l=t.vars[a];let c=l+1;if(c>=o.length)return 0;let u=o[c];return t.vars[a]=c,e?Be(t,e,u):xt(t,u),1}async function cu(t,e){if(e.length===0)return"";for(let r=0;r<e.length-1;r++)await $(t,e[r]);return $(t,e[e.length-1])}var Gr,jr=N(()=>{"use strict";X();ni();Hr();Gt();at();zr();Gr=null});async function ct(t,e){for(let r of e)if(await Xe(t,r),uu(t))break}function uu(t){return t.shouldExit||t.shouldNext||t.shouldNextFile||t.loopBreak||t.loopContinue||t.hasReturn}async function Xe(t,e){switch(e.type){case"block":await ct(t,e.statements);break;case"expr_stmt":await $(t,e.expression);break;case"print":await fu(t,e.args,e.output);break;case"printf":await du(t,e.format,e.args,e.output);break;case"if":await hu(t,e);break;case"while":await pu(t,e);break;case"do_while":await mu(t,e);break;case"for":await yu(t,e);break;case"for_in":await gu(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 $(t,e.code))):0;break;case"return":t.hasReturn=!0,t.returnValue=e.value?await $(t,e.value):"";break;case"delete":await wu(t,e.target);break}}async function fu(t,e,r){let n=[];for(let i of e)n.push(U(await $(t,i)));let s=n.join(t.OFS)+t.ORS;r?await hi(t,r.redirect,r.file,s):t.output+=s}async function du(t,e,r,n){let s=U(await $(t,e)),i=[];for(let o of r)i.push(await $(t,o));let a=Br(s,i);n?await hi(t,n.redirect,n.file,a):t.output+=a}async function hi(t,e,r,n){if(!t.fs||!t.cwd){t.output+=n;return}let s=U(await $(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 hu(t,e){he(await $(t,e.condition))?await Xe(t,e.consequent):e.alternate&&await Xe(t,e.alternate)}async function pu(t,e){let r=0;for(;he(await $(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 Xe(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break}}async function mu(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 Xe(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break}while(he(await $(t,e.condition)))}async function yu(t,e){e.init&&await $(t,e.init);let r=0;for(;!e.condition||he(await $(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 Xe(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break;e.update&&await $(t,e.update)}}async function gu(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 Xe(t,e.body),t.loopBreak){t.loopBreak=!1;break}if(t.shouldExit||t.shouldNext||t.hasReturn)break}}async function wu(t,e){if(e.type==="array_access"){let r=U(await $(t,e.key));ui(t,e.array,r)}else e.type==="variable"&&fi(t,e.name)}var pi=N(()=>{"use strict";X();Hr();jr();at();zr();di(ct)});var St,mi=N(()=>{"use strict";jr();Gt();at();pi();St=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 ct(this.ctx,e.action.statements),this.ctx.shouldExit))break}}async executeLine(e){if(!(!this.program||this.ctx.shouldExit)){xt(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 ct(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 ct(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 bt(n.pattern,this.ctx.line);case"expr_pattern":return he(await $(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 bt(e.pattern,this.ctx.line);case"expr_pattern":return he(await $(this.ctx,e.expression));default:return!1}}}});var yi=N(()=>{"use strict";ti();mi()});function bu(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,Eu,jt,gi=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={}));Eu={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};jt=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
+ `?(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
+ `)this.advance(),this.advance();else break;else if(e==="#")for(;this.pos<this.input.length&&this.peek()!==`
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
+ `?(this.advance(),{type:y.NEWLINE,value:`
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
+ `;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=bu(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=Eu[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 qt,wi=N(()=>{"use strict";gi();qt=class{tokens=[];pos=0;parse(e){let r=new jt(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 Si={};O(Si,{awkCommand2:()=>Su});function Ei(t){return t.replace(/\\t/g," ").replace(/\\n/g,`
243
+ `).replace(/\\r/g,"\r").replace(/\\\\/g,"\\")}function bi(t){if(t===" ")return/\s+/;if(/[[\](){}.*+?^$|\\]/.test(t))try{return new RegExp(t)}catch{return new RegExp(xi(t))}return new RegExp(xi(t))}function xi(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}var xu,Su,Ai=N(()=>{"use strict";X();T();yi();wi();xu={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"]},Su={name:"awk",async execute(t,e){if(C(t))return A(xu);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=Ei(t[++h]),r=bi(n),i=h+1;else if(p.startsWith("-F"))n=Ei(p.slice(2)),r=bi(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 L("awk",p);if(p.startsWith("-")&&p.length>1){let b=p[1];if(b!=="F"&&b!=="v")return L("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),l=new qt,c;try{c=l.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=Mr({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 St(f);d.execute(c);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(`
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
+ `,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 qr(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 l=s[i]||"";return e.startChar!==void 0&&(l=l.slice(e.startChar-1)),e.ignoreLeading&&(l=l.trimStart()),l}let a=Math.min(e.endField-1,s.length-1),o="";for(let l=i;l<=a&&l<s.length;l++){let c=s[l]||"";if(l===i&&e.startChar!==void 0&&(c=c.slice(e.startChar-1)),l===a&&e.endChar!==void 0){let u=l===i&&e.startChar!==void 0?e.endChar-e.startChar+1:e.endChar;c=c.slice(0,u)}l>i&&(o+=r||" "),o+=c}return e.ignoreLeading&&(o=o.trimStart()),o}function Au(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 Ci(t){let{keys:e,fieldDelimiter:r,numeric:n,ignoreCase:s,reverse:i}=t;return(a,o)=>{if(e.length===0){let c=a,u=o;s&&(c=c.toLowerCase(),u=u.toLowerCase());let f;if(n){let d=parseFloat(c)||0,h=parseFloat(u)||0;if(f=d-h,f===0){let p=c.localeCompare(u);return i?-p:p}}else f=c.localeCompare(u);return i?-f:f}for(let c of e){let u=qr(a,c,r),f=qr(o,c,r),d=c.numeric??n,h=c.ignoreCase??s,p=c.reverse??i,b=Au(u,f,d,h);if(b!==0)return p?-b:b}let l=a.localeCompare(o);return i?-l:l}}function Ni(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=qr(s,r,e.fieldDelimiter);return(r.ignoreCase??e.ignoreCase)&&(i=i.toLowerCase()),n.has(i)?!1:(n.add(i),!0)})}var vi=N(()=>{"use strict"});function Vt(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 l=parseInt(a[1],10);!Number.isNaN(l)&&l>=1&&(e.startChar=l)}if(i.length>1&&i[1]){let l=i[1],c=l.match(/([nrfb]+)$/i);if(c){let f=c[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),l=l.slice(0,-f.length)}let u=l.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 ki=N(()=>{"use strict"});var Ii={};O(Ii,{sortCommand:()=>Nu});var Cu,Nu,Ri=N(()=>{"use strict";Ve();T();vi();ki();Cu={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]]
213
250
  F is a field number (1-indexed)
214
251
  C is a character position within the field (1-indexed)
215
252
  OPTS can be: n (numeric), r (reverse), f (fold case), b (ignore blanks)
@@ -219,24 +256,24 @@ Examples:
219
256
  -k2,2 sort by second field only
220
257
  -k1.3 sort by first field starting at 3rd character
221
258
  -k1,2n sort by fields 1-2 numerically
222
- -k2 -k1 sort by field 2, then by field 1`},xc={name:"sort",async execute(t,e){if(S(t))return x(Ec);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=At(f);d&&r.keys.push(d)}}else if(u.startsWith("-k")){let f=At(u.slice(2));f&&r.keys.push(f)}else if(u.startsWith("--key=")){let f=At(u.slice(6));f&&r.keys.push(f)}else{if(u.startsWith("--"))return O("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 O("sort",u)}else n.push(u)}}let s=await Ie(e,n,{cmdName:"sort"});if(!s.ok)return s.error;let i=s.content.split(`
223
- `);i.length>0&&i[i.length-1]===""&&i.pop();let a=ti(r);return i.sort(a),r.unique&&(i=ri(i,r)),{stdout:i.length>0?`${i.join(`
259
+ -k2 -k1 sort by field 2, then by field 1`},Nu={name:"sort",async execute(t,e){if(C(t))return A(Cu);let r={reverse:!1,numeric:!1,unique:!1,ignoreCase:!1,keys:[],fieldDelimiter:null},n=[];for(let c=0;c<t.length;c++){let u=t[c];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[++c]||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[++c];if(f){let d=Vt(f);d&&r.keys.push(d)}}else if(u.startsWith("-k")){let f=Vt(u.slice(2));f&&r.keys.push(f)}else if(u.startsWith("--key=")){let f=Vt(u.slice(6));f&&r.keys.push(f)}else{if(u.startsWith("--"))return L("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 L("sort",u)}else n.push(u)}}let s=await We(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=Ci(r);return a.sort(o),r.unique&&(a=Ni(a,r)),{stdout:a.length>0?`${a.join(`
224
261
  `)}
225
- `:"",stderr:"",exitCode:0}}}});var ai={};I(ai,{uniqCommand:()=>Ac});var Sc,Cc,Ac,li=C(()=>{"use strict";Y();Le();R();Sc={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"]},Cc={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"}},Ac={name:"uniq",async execute(t,e){if(S(t))return x(Sc);let r=M("uniq",t,Cc);if(!r.ok)return r.error;let{count:n,duplicatesOnly:s,uniqueOnly:o,ignoreCase:i}=r.result.flags,a=r.result.positional,c=await Ie(e,a,{cmdName:"uniq"});if(!c.ok)return c.error;let u=c.content.split(`
226
- `);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=(y,w)=>i?y.toLowerCase()===w.toLowerCase():y===w;for(let y=1;y<u.length;y++)p(u[y],d)?h++:(f.push({line:d,count:h}),d=u[y],h=1);f.push({line:d,count:h});let b=f;s?b=f.filter(y=>y.count>1):o&&(b=f.filter(y=>y.count===1));let g="";for(let{line:y,count:w}of b)n?g+=`${String(w).padStart(4)} ${y}
227
- `:g+=`${y}
228
- `;return{stdout:g,stderr:"",exitCode:0}}}});var ci={};I(ci,{cutCommand:()=>kc});function Nc(t){let e=[],r=t.split(",");for(let n of r)if(n.includes("-")){let[s,o]=n.split("-");e.push({start:s?parseInt(s,10):1,end:o?parseInt(o,10):null})}else{let s=parseInt(n,10);e.push({start:s,end:s})}return e}function vc(t,e){let r=[];for(let n of e){let s=n.start-1,o=n.end===null?t.length:n.end;for(let i=s;i<o&&i<t.length;i++)i>=0&&!r.includes(t[i])&&r.push(t[i])}return r}var $c,kc,ui=C(()=>{"use strict";Le();R();$c={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"]};kc={name:"cut",async execute(t,e){if(S(t))return x($c);let r=" ",n=null,s=null,o=!1,i=[];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")o=!0;else{if(h.startsWith("--"))return O("cut",h);if(h.startsWith("-")){let p=!1;for(let b of h.slice(1))if(b==="s")o=!0;else if(!"dfc".includes(b)){p=!0;break}if(p)return O("cut",h)}else i.push(h)}}if(!n&&!s)return{stdout:"",stderr:`cut: you must specify a list of bytes, characters, or fields
229
- `,exitCode:1};let a=await Ie(e,i,{cmdName:"cut"});if(!a.ok)return a.error;let l=a.content.split(`
230
- `);l.length>0&&l[l.length-1]===""&&l.pop();let u=Nc(n||s||"1"),f="";for(let d of l)if(s){let h=d.split(""),p=[];for(let b of u){let g=b.start-1,y=b.end===null?h.length:b.end;for(let w=g;w<y&&w<h.length;w++)w>=0&&p.push(h[w])}f+=`${p.join("")}
231
- `}else{if(o&&!d.includes(r))continue;let h=d.split(r),p=vc(h,u);f+=`${p.join(r)}
232
- `}return{stdout:f,stderr:"",exitCode:0}}}});var di={};I(di,{pasteCommand:()=>Rc});function fi(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 Ic,Pc,Rc,hi=C(()=>{"use strict";Y();R();Ic={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"]},Pc={delimiter:{short:"d",long:"delimiters",type:"string",default:" "},serial:{short:"s",long:"serial",type:"boolean"}},Rc={name:"paste",async execute(t,e){if(S(t))return x(Ic);let r=M("paste",t,Pc);if(!r.ok)return r.error;let n=r.result.flags.delimiter,s=r.result.flags.serial,o=r.result.positional;if(o.length===0)return{stdout:"",stderr:`usage: paste [-s] [-d delimiters] file ...
233
- `,exitCode:1};let i=e.stdin?e.stdin.split(`
234
- `):[""];i.length>0&&i[i.length-1]===""&&i.pop();let a=o.filter(f=>f==="-").length,c=[],l=0;for(let f of o)if(f==="-"){let d=[];for(let h=l;h<i.length;h+=a)d.push(i[h]);c.push(d),l++}else{let d=e.fs.resolvePath(e.cwd,f);try{let p=(await e.fs.readFile(d)).split(`
235
- `);p.length>0&&p[p.length-1]===""&&p.pop(),c.push(p)}catch{return{stdout:"",stderr:`paste: ${f}: No such file or directory
236
- `,exitCode:1}}}let u="";if(s)for(let f of c)f&&(u+=`${fi(f,n)}
237
- `);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+=`${fi(h,n)}
238
- `}}return{stdout:u,stderr:"",exitCode:0}}}});var mi={};I(mi,{trCommand:()=>Mc});function pi(t){let e="",r=0;for(;r<t.length;){if(t[r]==="["&&t[r+1]===":"){let n=!1;for(let[s,o]of Object.entries(Dc))if(t.slice(r).startsWith(s)){e+=o,r+=s.length,n=!0;break}if(n)continue}if(t[r]==="\\"&&r+1<t.length){let n=t[r+1];n==="n"?e+=`
239
- `: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 o=n;o<=s;o++)e+=String.fromCharCode(o);r+=3;continue}e+=t[r],r++}return e}var Oc,Dc,Tc,Mc,gi=C(()=>{"use strict";Y();R();Oc={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:
262
+ `:"",stderr:"",exitCode:0}}}});var $i={};O($i,{uniqCommand:()=>Iu});var vu,ku,Iu,Pi=N(()=>{"use strict";ae();Ve();T();vu={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"]},ku={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"}},Iu={name:"uniq",async execute(t,e){if(C(t))return A(vu);let r=H("uniq",t,ku);if(!r.ok)return r.error;let{count:n,duplicatesOnly:s,uniqueOnly:i,ignoreCase:a}=r.result.flags,o=r.result.positional,l=await We(e,o,{cmdName:"uniq"});if(!l.ok)return l.error;let u=l.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}
264
+ `:w+=`${g}
265
+ `;return{stdout:w,stderr:"",exitCode:0}}}});var Oi={};O(Oi,{cutCommand:()=>Ou});function $u(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 Pu(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 Ru,Ou,Di=N(()=>{"use strict";Ve();T();Ru={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"]};Ou={name:"cut",async execute(t,e){if(C(t))return A(Ru);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 L("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 L("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 We(e,a,{cmdName:"cut"});if(!o.ok)return o.error;let c=o.content.split(`
267
+ `);c.length>0&&c[c.length-1]===""&&c.pop();let u=$u(n||s||"1"),f="";for(let d of c)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=Pu(h,u);f+=`${p.join(r)}
269
+ `}return{stdout:f,stderr:"",exitCode:0}}}});var Li={};O(Li,{pasteCommand:()=>Lu});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 Du,Tu,Lu,Fi=N(()=>{"use strict";ae();T();Du={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"}},Lu={name:"paste",async execute(t,e){if(C(t))return A(Du);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 ...
270
+ `,exitCode:1};let a=e.stdin?e.stdin.split(`
271
+ `):[""];a.length>0&&a[a.length-1]===""&&a.pop();let o=i.filter(f=>f==="-").length,l=[],c=0;for(let f of i)if(f==="-"){let d=[];for(let h=c;h<a.length;h+=o)d.push(a[h]);l.push(d),c++}else{let d=e.fs.resolvePath(e.cwd,f);try{let p=(await e.fs.readFile(d)).split(`
272
+ `);p.length>0&&p[p.length-1]===""&&p.pop(),l.push(p)}catch{return{stdout:"",stderr:`paste: ${f}: No such file or directory
273
+ `,exitCode:1}}}let u="";if(s)for(let f of l)f&&(u+=`${Ti(f,n)}
274
+ `);else{let f=Math.max(...l.map(d=>d?.length??0));for(let d=0;d<f;d++){let h=[];for(let p of l)h.push(p?.[d]??"");u+=`${Ti(h,n)}
275
+ `}}return{stdout:u,stderr:"",exitCode:0}}}});var _i={};O(_i,{trCommand:()=>Wu});function Mi(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(Mu))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 Fu,Mu,_u,Wu,Wi=N(()=>{"use strict";ae();T();Fu={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:
240
277
  a-z character range
241
278
  [:alnum:] all letters and digits
242
279
  [:alpha:] all letters
@@ -250,120 +287,120 @@ Examples:
250
287
  [:graph:] all printable characters except space
251
288
  [:cntrl:] all control characters
252
289
  [:xdigit:] all hexadecimal digits
253
- \\n, \\t, \\r escape sequences`},Dc={"[: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:]":`
254
- \r\f\v`,"[:upper:]":"ABCDEFGHIJKLMNOPQRSTUVWXYZ","[:xdigit:]":"0123456789ABCDEFabcdef"};Tc={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"}},Mc={name:"tr",async execute(t,e){if(S(t))return x(Oc);let r=M("tr",t,Tc);if(!r.ok)return r.error;let n=r.result.flags.complement||r.result.flags.complementUpper,s=r.result.flags.delete,o=r.result.flags.squeeze,i=r.result.positional;if(i.length<1)return{stdout:"",stderr:`tr: missing operand
255
- `,exitCode:1};if(!s&&!o&&i.length<2)return{stdout:"",stderr:`tr: missing operand after SET1
256
- `,exitCode:1};let a=pi(i[0]),c=i.length>1?pi(i[1]):"",l=e.stdin,u=d=>{let h=a.includes(d);return n?!h:h},f="";if(s)for(let d of l)u(d)||(f+=d);else if(o&&i.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)a.includes(h)?f+=h:f+=d}else{let d=new Map;for(let h=0;h<a.length;h++){let p=h<c.length?c[h]:c[c.length-1];d.set(a[h],p)}for(let h of l)f+=d.get(h)??h}if(o){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 yi={};I(yi,{teeCommand:()=>Wc});var Fc,Lc,Wc,wi=C(()=>{"use strict";Y();R();Fc={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"]},Lc={append:{short:"a",long:"append",type:"boolean"}},Wc={name:"tee",async execute(t,e){if(S(t))return x(Fc);let r=M("tee",t,Lc);if(!r.ok)return r.error;let{append:n}=r.result.flags,s=r.result.positional,o=e.stdin,i="",a=0;for(let c of s)try{let l=e.fs.resolvePath(e.cwd,c);n?await e.fs.appendFile(l,o):await e.fs.writeFile(l,o)}catch{i+=`tee: ${c}: No such file or directory
257
- `,a=1}return{stdout:o,stderr:i,exitCode:a}}}});function We(t,e){switch(t.type){case"name":return ue(e.name,t.pattern,t.ignoreCase);case"path":return ue(e.relativePath,t.pattern,t.ignoreCase);case"type":return t.fileType==="f"?e.isFile:t.fileType==="d"?e.isDirectory:!1;case"empty":return e.isEmpty;case"mtime":{let n=(Date.now()-e.mtime)/(1e3*60*60*24);return t.comparison==="more"?n>t.days:t.comparison==="less"?n<t.days:Math.floor(n)===t.days}case"newer":{let r=e.newerRefTimes.get(t.refPath);return r===void 0?!1:e.mtime>r}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}return t.comparison==="more"?e.size>r:t.comparison==="less"?e.size<r:t.unit==="b"?Math.ceil(e.size/512)===t.value:e.size===r}case"perm":{let r=e.mode&511,n=t.mode&511;return t.matchType==="exact"?r===n:t.matchType==="all"?(r&n)===n:(r&n)!==0}case"not":return!We(t.expr,e);case"and":return We(t.left,e)&&We(t.right,e);case"or":return We(t.left,e)||We(t.right,e)}}function bi(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 Ei=C(()=>{"use strict";ar()});function xi(t,e){let r=[],n=[],s=e;for(;s<t.length;){let l=t[s];if(l==="-name"&&s+1<t.length)r.push({type:"expr",expr:{type:"name",pattern:t[++s]}});else if(l==="-iname"&&s+1<t.length)r.push({type:"expr",expr:{type:"name",pattern:t[++s],ignoreCase:!0}});else if(l==="-path"&&s+1<t.length)r.push({type:"expr",expr:{type:"path",pattern:t[++s]}});else if(l==="-ipath"&&s+1<t.length)r.push({type:"expr",expr:{type:"path",pattern:t[++s],ignoreCase:!0}});else if(l==="-type"&&s+1<t.length){let u=t[++s];if(u==="f"||u==="d")r.push({type:"expr",expr:{type:"type",fileType:u}});else return{expr:null,pathIndex:s,error:`find: Unknown argument to -type: ${u}
258
- `,actions:[]}}else if(l==="-empty")r.push({type:"expr",expr:{type:"empty"}});else if(l==="-mtime"&&s+1<t.length){let u=t[++s],f="exact",d=u;u.startsWith("+")?(f="more",d=u.slice(1)):u.startsWith("-")&&(f="less",d=u.slice(1));let h=parseInt(d,10);Number.isNaN(h)||r.push({type:"expr",expr:{type:"mtime",days:h,comparison:f}})}else if(l==="-newer"&&s+1<t.length){let u=t[++s];r.push({type:"expr",expr:{type:"newer",refPath:u}})}else if(l==="-size"&&s+1<t.length){let u=t[++s],f="exact",d=u;u.startsWith("+")?(f="more",d=u.slice(1)):u.startsWith("-")&&(f="less",d=u.slice(1));let h=d.match(/^(\d+)([ckMGb])?$/);if(h){let p=parseInt(h[1],10),b=h[2]||"b";r.push({type:"expr",expr:{type:"size",value:p,unit:b,comparison:f}})}}else if(l==="-perm"&&s+1<t.length){let u=t[++s],f="exact",d=u;u.startsWith("-")?(f="all",d=u.slice(1)):u.startsWith("/")&&(f="any",d=u.slice(1));let h=parseInt(d,8);Number.isNaN(h)||r.push({type:"expr",expr:{type:"perm",mode:h,matchType:f}})}else if(l==="-not"||l==="!")r.push({type:"not"});else if(l==="-o"||l==="-or")r.push({type:"op",op:"or"});else if(l==="-a"||l==="-and")r.push({type:"op",op:"and"});else if(l==="-maxdepth"||l==="-mindepth")s++;else if(l==="-exec"){let u=[];for(s++;s<t.length&&t[s]!==";"&&t[s]!=="+";)u.push(t[s]),s++;if(s>=t.length)return{expr:null,pathIndex:s,error:"find: missing argument to `-exec'\n",actions:[]};let f=t[s]==="+";n.push({type:"exec",command:u,batchMode:f})}else if(l==="-print")n.push({type:"print"});else if(l==="-print0")n.push({type:"print0"});else if(l==="-delete")n.push({type:"delete"});else{if(l.startsWith("-"))return{expr:null,pathIndex:s,error:`find: unknown predicate '${l}'
259
- `,actions:[]};if(r.length===0){s++;continue}break}s++}if(r.length===0)return{expr:null,pathIndex:s,actions:n};let o=[];for(let l=0;l<r.length;l++){let u=r[l];if(u.type==="not"){if(l+1<r.length&&r[l+1].type==="expr"){let f=r[l+1].expr;o.push({type:"expr",expr:{type:"not",expr:f}}),l++}}else(u.type==="expr"||u.type==="op")&&o.push(u)}let i=[[]];for(let l of o)l.type==="op"&&l.op==="or"?i.push([]):l.type==="expr"&&i[i.length-1].push(l.expr);let a=[];for(let l of i){if(l.length===0)continue;let u=l[0];for(let f=1;f<l.length;f++)u={type:"and",left:u,right:l[f]};a.push(u)}if(a.length===0)return{expr:null,pathIndex:s,actions:n};let c=a[0];for(let l=1;l<a.length;l++)c={type:"or",left:c,right:a[l]};return{expr:c,pathIndex:s,actions:n}}var Si=C(()=>{"use strict"});var Ci={};I(Ci,{findCommand:()=>Bc});var _c,Hc,Bc,Ai=C(()=>{"use strict";R();Ei();Si();_c={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","-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","-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"]},Hc=new Set(["-name","-iname","-path","-ipath","-type","-maxdepth","-mindepth","-mtime","-newer","-size","-perm"]),Bc={name:"find",async execute(t,e){if(S(t))return x(_c);let r=".",n=null,s=null;for(let y=0;y<t.length;y++){let w=t[y];if(w==="-maxdepth"&&y+1<t.length)n=parseInt(t[++y],10);else if(w==="-mindepth"&&y+1<t.length)s=parseInt(t[++y],10);else if(w==="-exec")for(y++;y<t.length&&t[y]!==";"&&t[y]!=="+";)y++;else!w.startsWith("-")&&w!==";"&&w!=="+"?r=w:Hc.has(w)&&y++}let{expr:o,error:i,actions:a}=xi(t,0);if(i)return{stdout:"",stderr:i,exitCode:1};let c=a.length===0,l=e.fs.resolvePath(e.cwd,r);try{await e.fs.stat(l)}catch{return{stdout:"",stderr:`find: ${r}: No such file or directory
260
- `,exitCode:1}}let u=[],f=bi(o),d=new Map;for(let y of f){let w=e.fs.resolvePath(e.cwd,y);try{let E=await e.fs.stat(w);d.set(y,E.mtime?.getTime()??Date.now())}catch{}}async function h(y,w){if(n!==null&&w>n)return;let E;try{E=await e.fs.stat(y)}catch{return}if(!E)return;let $;y===l?$=r.split("/").pop()||r:$=y.split("/").pop()||"";let A=y===l?r:r==="."?`./${y.slice(l.length+1)}`:r+y.slice(l.length),P=null;E.isDirectory&&(P=await e.fs.readdir(y));let J=E.isFile?E.size===0:P!==null&&P.length===0,Se=s===null||w>=s;if(Se&&o!==null){let Fe={name:$,relativePath:A,isFile:E.isFile,isDirectory:E.isDirectory,isEmpty:J,mtime:E.mtime?.getTime()??Date.now(),size:E.size??0,mode:E.mode??420,newerRefTimes:d};Se=We(o,Fe)}if(Se&&u.push(A),P!==null)for(let Fe of P){let pt=y==="/"?`/${Fe}`:`${y}/${Fe}`;await h(pt,w+1)}}await h(l,0);let p="",b="",g=0;if(a.length>0)for(let y of a)switch(y.type){case"print":p+=u.length>0?`${u.join(`
290
+ \\n, \\t, \\r escape sequences`},Mu={"[: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"};_u={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"}},Wu={name:"tr",async execute(t,e){if(C(t))return A(Fu);let r=H("tr",t,_u);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
+ `,exitCode:1};if(!s&&!i&&a.length<2)return{stdout:"",stderr:`tr: missing operand after SET1
293
+ `,exitCode:1};let o=Mi(a[0]),l=a.length>1?Mi(a[1]):"",c=e.stdin,u=d=>{let h=o.includes(d);return n?!h:h},f="";if(s)for(let d of c)u(d)||(f+=d);else if(i&&a.length===1){let d="";for(let h of c)u(h)&&h===d||(f+=h,d=h)}else{if(n){let d=l.length>0?l[l.length-1]:"";for(let h of c)o.includes(h)?f+=h:f+=d}else{let d=new Map;for(let h=0;h<o.length;h++){let p=h<l.length?l[h]:l[l.length-1];d.set(o[h],p)}for(let h of c)f+=d.get(h)??h}if(i){let d="",h="";for(let p of f)l.includes(p)&&p===h||(d+=p,h=p);f=d}}return{stdout:f,stderr:"",exitCode:0}}}});var Bi={};O(Bi,{teeCommand:()=>Uu});var Bu,Hu,Uu,Hi=N(()=>{"use strict";ae();T();Bu={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"]},Hu={append:{short:"a",long:"append",type:"boolean"}},Uu={name:"tee",async execute(t,e){if(C(t))return A(Bu);let r=H("tee",t,Hu);if(!r.ok)return r.error;let{append:n}=r.result.flags,s=r.result.positional,i=e.stdin,a="",o=0;for(let l of s)try{let c=e.fs.resolvePath(e.cwd,l);n?await e.fs.appendFile(c,i):await e.fs.writeFile(c,i)}catch{a+=`tee: ${l}: No such file or directory
294
+ `,o=1}return{stdout:i,stderr:a,exitCode:o}}}});function Ye(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=Ye(t.expr,e);return{matches:!r.matches,pruned:r.pruned,printed:!1}}case"and":{let r=Ye(t.left,e);if(!r.matches)return{matches:!1,pruned:r.pruned,printed:!1};let n=Ye(t.right,e);return{matches:n.matches,pruned:r.pruned||n.pruned,printed:r.printed||n.printed}}case"or":{let r=Ye(t.left,e);if(r.matches)return r;let n=Ye(t.right,e);return{matches:n.matches,pruned:r.pruned||n.pruned,printed:n.printed}}}}function Ui(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=N(()=>{"use strict";Pr()});function Gi(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],l="exact",c=o;o.startsWith("+")?(l="more",c=o.slice(1)):o.startsWith("-")&&(l="less",c=o.slice(1));let u=parseInt(c,10);Number.isNaN(u)||r.push({type:"expr",expr:{type:"mtime",days:u,comparison:l}})}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],l="exact",c=o;o.startsWith("+")?(l="more",c=o.slice(1)):o.startsWith("-")&&(l="less",c=o.slice(1));let u=c.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:l}})}}else if(a==="-perm"&&s+1<t.length){let o=t[++s],l="exact",c=o;o.startsWith("-")?(l="all",c=o.slice(1)):o.startsWith("/")&&(l="any",c=o.slice(1));let u=parseInt(c,8);Number.isNaN(u)||r.push({type:"expr",expr:{type:"perm",mode:u,matchType:l}})}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 l=t[s]==="+";n.push({type:"exec",command:o,batchMode:l})}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=zu(r);return i.error?{expr:null,pathIndex:s,error:i.error,actions:n}:{expr:i.expr,pathIndex:s,actions:n}}function zu(t){let e=0;function r(){let o=n();if(!o)return null;for(;e<t.length;){let l=t[e];if(l.type==="op"&&l.op==="or"){e++;let c=n();if(!c)return o;o={type:"or",left:o,right:c}}else break}return o}function n(){let o=s();if(!o)return null;for(;e<t.length;){let l=t[e];if(l.type==="op"&&l.op==="and"){e++;let c=s();if(!c)return o;o={type:"and",left:o,right:c}}else if(l.type==="expr"||l.type==="not"||l.type==="lparen"){let c=s();if(!c)return o;o={type:"and",left:o,right:c}}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 l=r();return e<t.length&&t[e].type==="rparen"&&e++,l}return o.type==="expr"?(e++,o.expr):(o.type==="rparen",null)}return{expr:r()}}var ji=N(()=>{"use strict"});var qi={};O(qi,{findCommand:()=>qu});var Gu,ju,qu,Vi=N(()=>{"use strict";T();zi();ji();Gu={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"]},ju=new Set(["-name","-iname","-path","-ipath","-regex","-iregex","-type","-maxdepth","-mindepth","-mtime","-newer","-size","-perm"]),qu={name:"find",async execute(t,e){if(C(t))return A(Gu);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:ju.has(x)&&E++}let{expr:i,error:a,actions:o}=Gi(t,0);if(a)return{stdout:"",stderr:a,exitCode:1};let l=o.some(E=>E.type==="print"),c=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=Ui(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=Ye(i,de);K=oe.matches,Ee=oe.pruned,l?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(`
261
298
  `)}
262
- `:"";break;case"print0":p+=u.length>0?`${u.join("\0")}\0`:"";break;case"delete":{let w=[...u].sort((E,$)=>$.length-E.length);for(let E of w){let $=e.fs.resolvePath(e.cwd,E);try{await e.fs.rm($,{recursive:!1})}catch(A){let P=A instanceof Error?A.message:String(A);b+=`find: cannot delete '${E}': ${P}
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}
263
300
  `,g=1}}break}case"exec":if(!e.exec)return{stdout:"",stderr:`find: -exec not supported in this context
264
- `,exitCode:1};if(y.batchMode){let w=[];for(let A of y.command)A==="{}"?w.push(...u):w.push(A);let E=w.map(A=>`"${A}"`).join(" "),$=await e.exec(E);p+=$.stdout,b+=$.stderr,$.exitCode!==0&&(g=$.exitCode)}else for(let w of u){let $=y.command.map(P=>P==="{}"?w:P).map(P=>`"${P}"`).join(" "),A=await e.exec($);p+=A.stdout,b+=A.stderr,A.exitCode!==0&&(g=A.exitCode)}break}else c&&(p=u.length>0?`${u.join(`
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);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);b+=R.stdout,w+=R.stderr,R.exitCode!==0&&(g=R.exitCode)}break}else c&&(b=f.length>0?`${f.join(`
265
302
  `)}
266
- `:"");return{stdout:p,stderr:b,exitCode:g}}}});var $i={};I($i,{basenameCommand:()=>Uc});var zc,Uc,Ni=C(()=>{"use strict";R();zc={name:"basename",summary:"strip directory and suffix from filenames",usage:`basename NAME [SUFFIX]
267
- basename OPTION... NAME...`,options:["-a, --multiple support multiple arguments","-s, --suffix=SUFFIX remove a trailing SUFFIX"," --help display this help and exit"]},Uc={name:"basename",async execute(t,e){if(S(t))return x(zc);let r=!1,n="",s=[];for(let i=0;i<t.length;i++){let a=t[i];a==="-a"||a==="--multiple"?r=!0:a==="-s"&&i+1<t.length?(n=t[++i],r=!0):a.startsWith("--suffix=")?(n=a.slice(9),r=!0):a.startsWith("-")||s.push(a)}if(s.length===0)return{stdout:"",stderr:`basename: missing operand
268
- `,exitCode:1};!r&&s.length>=2&&(n=s.pop()??"");let o=[];for(let i of s){let a=i.replace(/\/+$/,""),c=a.split("/").pop()||a;n&&c.endsWith(n)&&(c=c.slice(0,-n.length)),o.push(c)}return{stdout:`${o.join(`
303
+ `:"");return{stdout:b,stderr:w,exitCode:g}}}});var Zi={};O(Zi,{basenameCommand:()=>Zu});var Vu,Zu,Qi=N(()=>{"use strict";T();Vu={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"]},Zu={name:"basename",async execute(t,e){if(C(t))return A(Vu);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
+ `,exitCode:1};!r&&s.length>=2&&(n=s.pop()??"");let i=[];for(let a of s){let o=a.replace(/\/+$/,""),l=o.split("/").pop()||o;n&&l.endsWith(n)&&(l=l.slice(0,-n.length)),i.push(l)}return{stdout:`${i.join(`
269
306
  `)}
270
- `,stderr:"",exitCode:0}}}});var vi={};I(vi,{dirnameCommand:()=>qc});var jc,qc,ki=C(()=>{"use strict";R();jc={name:"dirname",summary:"strip last component from file name",usage:"dirname [OPTION] NAME...",options:[" --help display this help and exit"]},qc={name:"dirname",async execute(t,e){if(S(t))return x(jc);let r=t.filter(s=>!s.startsWith("-"));if(r.length===0)return{stdout:"",stderr:`dirname: missing operand
271
- `,exitCode:1};let n=[];for(let s of r){let o=s.replace(/\/+$/,""),i=o.lastIndexOf("/");i===-1?n.push("."):i===0?n.push("/"):n.push(o.slice(0,i))}return{stdout:`${n.join(`
307
+ `,stderr:"",exitCode:0}}}});var Ki={};O(Ki,{dirnameCommand:()=>Ku});var Qu,Ku,Xi=N(()=>{"use strict";T();Qu={name:"dirname",summary:"strip last component from file name",usage:"dirname [OPTION] NAME...",options:[" --help display this help and exit"]},Ku={name:"dirname",async execute(t,e){if(C(t))return A(Qu);let r=t.filter(s=>!s.startsWith("-"));if(r.length===0)return{stdout:"",stderr:`dirname: missing operand
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(`
272
309
  `)}
273
- `,stderr:"",exitCode:0}}}});var Pi={};I(Pi,{treeCommand:()=>Zc});async function Qc(t,e,r,n,s){let o={output:"",stderr:"",dirCount:0,fileCount:0},i=t.fs.resolvePath(t.cwd,e);try{if(!(await t.fs.stat(i)).isDirectory)return o.output=`${e}
274
- `,o.fileCount=1,o}catch{return o.stderr=`tree: ${e}: No such file or directory
275
- `,o}if(o.output=`${e}
276
- `,r.maxDepth!==null&&s>=r.maxDepth)return o;try{let c=(await t.fs.readdir(i)).filter(l=>!(!r.showHidden&&l.startsWith(".")));c.sort();for(let l=0;l<c.length;l++){let u=c[l],f=i==="/"?`/${u}`:`${i}/${u}`,d=l===c.length-1,h=d?"`-- ":"|-- ",p=n+(d?" ":"| ");try{if((await t.fs.stat(f)).isDirectory){o.dirCount++;let g=r.fullPath?f:u;if(o.output+=`${n+h+g}
277
- `,r.maxDepth===null||s+1<r.maxDepth){let y=await Ii(t,f,r,p,s+1);o.output+=y.output,o.dirCount+=y.dirCount,o.fileCount+=y.fileCount}}else if(!r.directoriesOnly){o.fileCount++;let g=r.fullPath?f:u;o.output+=`${n+h+g}
278
- `}}catch{}}}catch{o.stderr=`tree: ${e}: Permission denied
279
- `}return o}async function Ii(t,e,r,n,s){let o={output:"",stderr:"",dirCount:0,fileCount:0};if(r.maxDepth!==null&&s>=r.maxDepth)return o;try{let a=(await t.fs.readdir(e)).filter(c=>!(!r.showHidden&&c.startsWith(".")));a.sort();for(let c=0;c<a.length;c++){let l=a[c],u=e==="/"?`/${l}`:`${e}/${l}`,f=c===a.length-1,d=f?"`-- ":"|-- ",h=n+(f?" ":"| ");try{if((await t.fs.stat(u)).isDirectory){o.dirCount++;let b=r.fullPath?u:l;o.output+=`${n+d+b}
280
- `;let g=await Ii(t,u,r,h,s+1);o.output+=g.output,o.dirCount+=g.dirCount,o.fileCount+=g.fileCount}else if(!r.directoriesOnly){o.fileCount++;let b=r.fullPath?u:l;o.output+=`${n+d+b}
281
- `}}catch{}}}catch{}return o}var Gc,Vc,Zc,Ri=C(()=>{"use strict";Y();R();Gc={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"]},Vc={showHidden:{short:"a",type:"boolean"},directoriesOnly:{short:"d",type:"boolean"},fullPath:{short:"f",type:"boolean"},maxDepth:{short:"L",type:"number"}},Zc={name:"tree",async execute(t,e){if(S(t))return x(Gc);let r=M("tree",t,Vc);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 o="",i="",a=0,c=0;for(let l of s){let u=await Qc(e,l,n,"",0);o+=u.output,i+=u.stderr,a+=u.dirCount,c+=u.fileCount}return o+=`
282
- ${a} director${a===1?"y":"ies"}`,n.directoriesOnly||(o+=`, ${c} file${c===1?"":"s"}`),o+=`
283
- `,{stdout:o,stderr:i,exitCode:i?1:0}}}});var Di={};I(Di,{duCommand:()=>Yc});async function Oi(t,e,r,n,s){let o={output:"",totalSize:0,stderr:""};try{let i=await t.fs.stat(e);if(!i.isDirectory)return o.totalSize=i.size,(n.allFiles||s===0)&&(o.output=$t(i.size,n.humanReadable)+" "+r+`
284
- `),o;let a=await t.fs.readdir(e),c=0;for(let l of a){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 Oi(t,u,f,n,s+1);c+=h.totalSize,n.summarize||(n.maxDepth===null||s+1<=n.maxDepth?o.output+=h.output:c+=0)}else c+=d.size,n.allFiles&&!n.summarize&&(o.output+=$t(d.size,n.humanReadable)+" "+f+`
285
- `)}catch{}}o.totalSize=c,(n.summarize||n.maxDepth===null||s<=n.maxDepth)&&(o.output+=`${$t(c,n.humanReadable)} ${r}
286
- `)}catch{o.stderr=`du: cannot read directory '${r}': Permission denied
287
- `}return o}function $t(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 Kc,Xc,Yc,Ti=C(()=>{"use strict";Y();R();Kc={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"]},Xc={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"}},Yc={name:"du",async execute(t,e){if(S(t))return x(Kc);let r=M("du",t,Xc);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 o="",i="",a=0;for(let c of s){let l=e.fs.resolvePath(e.cwd,c);try{await e.fs.stat(l);let u=await Oi(e,l,c,n,0);o+=u.output,a+=u.totalSize,i+=u.stderr}catch{i+=`du: cannot access '${c}': No such file or directory
288
- `}}return n.grandTotal&&s.length>0&&(o+=`${$t(a,n.humanReadable)} total
289
- `),{stdout:o,stderr:i,exitCode:i?1:0}}}});var yr={};I(yr,{envCommand:()=>eu,printenvCommand:()=>ru});var Jc,eu,tu,ru,wr=C(()=>{"use strict";R();Jc={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"]},eu={name:"env",async execute(t,e){if(S(t))return x(Jc);let r=!1,n=[],s={},o=-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 O("env",f);if(f.startsWith("-")&&f!=="-"){for(let d of f.slice(1))if(d!=="i"&&d!=="u")return O("env",`-${d}`);f.includes("i")&&(r=!0)}else if(f.includes("=")&&o===-1){let d=f.indexOf("="),h=f.slice(0,d),p=f.slice(d+1);s[h]=p}else{o=u;break}}}let i;if(r)i={...s};else{i={...e.env};for(let u of n)delete i[u];Object.assign(i,s)}if(o===-1){let u=[];for(let[f,d]of Object.entries(i))u.push(`${f}=${d}`);return{stdout:u.join(`
310
+ `,stderr:"",exitCode:0}}}});var Ji={};O(Ji,{treeCommand:()=>Ju});async function ef(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
+ `,i.fileCount=1,i}catch{return i.stderr=`tree: ${e}: No such file or directory
312
+ `,i}if(i.output=`${e}
313
+ `,r.maxDepth!==null&&s>=r.maxDepth)return i;try{let l=(await t.fs.readdir(a)).filter(c=>!(!r.showHidden&&c.startsWith(".")));l.sort();for(let c=0;c<l.length;c++){let u=l[c],f=a==="/"?`/${u}`:`${a}/${u}`,d=c===l.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 Yi(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
+ `}}catch{}}}catch{i.stderr=`tree: ${e}: Permission denied
316
+ `}return i}async function Yi(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(l=>!(!r.showHidden&&l.startsWith(".")));o.sort();for(let l=0;l<o.length;l++){let c=o[l],u=e==="/"?`/${c}`:`${e}/${c}`,f=l===o.length-1,d=f?"`-- ":"|-- ",h=n+(f?" ":"| ");try{if((await t.fs.stat(u)).isDirectory){i.dirCount++;let b=r.fullPath?u:c;i.output+=`${n+d+b}
317
+ `;let w=await Yi(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:c;i.output+=`${n+d+b}
318
+ `}}catch{}}}catch{}return i}var Xu,Yu,Ju,ea=N(()=>{"use strict";ae();T();Xu={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"]},Yu={showHidden:{short:"a",type:"boolean"},directoriesOnly:{short:"d",type:"boolean"},fullPath:{short:"f",type:"boolean"},maxDepth:{short:"L",type:"number"}},Ju={name:"tree",async execute(t,e){if(C(t))return A(Xu);let r=H("tree",t,Yu);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,l=0;for(let c of s){let u=await ef(e,c,n,"",0);i+=u.output,a+=u.stderr,o+=u.dirCount,l+=u.fileCount}return i+=`
319
+ ${o} director${o===1?"y":"ies"}`,n.directoriesOnly||(i+=`, ${l} file${l===1?"":"s"}`),i+=`
320
+ `,{stdout:i,stderr:a,exitCode:a?1:0}}}});var ra={};O(ra,{duCommand:()=>nf});async function ta(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=Zt(a.size,n.humanReadable)+" "+r+`
321
+ `),i;let o=await t.fs.readdir(e),l=0;for(let c of o){let u=e==="/"?`/${c}`:`${e}/${c}`,f=r==="."?c:`${r}/${c}`;try{let d=await t.fs.stat(u);if(d.isDirectory){let h=await ta(t,u,f,n,s+1);l+=h.totalSize,n.summarize||(n.maxDepth===null||s+1<=n.maxDepth?i.output+=h.output:l+=0)}else l+=d.size,n.allFiles&&!n.summarize&&(i.output+=Zt(d.size,n.humanReadable)+" "+f+`
322
+ `)}catch{}}i.totalSize=l,(n.summarize||n.maxDepth===null||s<=n.maxDepth)&&(i.output+=`${Zt(l,n.humanReadable)} ${r}
323
+ `)}catch{i.stderr=`du: cannot read directory '${r}': Permission denied
324
+ `}return i}function Zt(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 tf,rf,nf,na=N(()=>{"use strict";ae();T();tf={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"]},rf={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"}},nf={name:"du",async execute(t,e){if(C(t))return A(tf);let r=H("du",t,rf);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 l of s){let c=e.fs.resolvePath(e.cwd,l);try{await e.fs.stat(c);let u=await ta(e,c,l,n,0);i+=u.output,o+=u.totalSize,a+=u.stderr}catch{a+=`du: cannot access '${l}': No such file or directory
325
+ `}}return n.grandTotal&&s.length>0&&(i+=`${Zt(o,n.humanReadable)} total
326
+ `),{stdout:i,stderr:a,exitCode:a?1:0}}}});var Vr={};O(Vr,{envCommand:()=>af,printenvCommand:()=>lf});var sf,af,of,lf,Zr=N(()=>{"use strict";T();sf={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"]},af={name:"env",async execute(t,e){if(C(t))return A(sf);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 L("env",f);if(f.startsWith("-")&&f!=="-"){for(let d of f.slice(1))if(d!=="i"&&d!=="u")return L("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(`
290
327
  `)+(u.length>0?`
291
328
  `:""),stderr:"",exitCode:0}}if(!e.exec)return{stdout:"",stderr:`env: command execution not supported in this context
292
- `,exitCode:1};let a=t.slice(o).join(" "),c=Object.entries(s).map(([u,f])=>`${u}="${f}"`).join(" "),l=c?`${c} ${a}`:a;return e.exec(l)}},tu={name:"printenv",summary:"print all or part of environment",usage:"printenv [OPTION]... [VARIABLE]...",options:[" --help display this help and exit"]},ru={name:"printenv",async execute(t,e){if(S(t))return x(tu);let r=t.filter(o=>!o.startsWith("-"));if(r.length===0){let o=[];for(let[i,a]of Object.entries(e.env))o.push(`${i}=${a}`);return{stdout:o.join(`
293
- `)+(o.length>0?`
294
- `:""),stderr:"",exitCode:0}}let n=[],s=0;for(let o of r)o in e.env?n.push(e.env[o]):s=1;return{stdout:n.join(`
329
+ `,exitCode:1};let o=t.slice(i).join(" "),l=Object.entries(s).map(([u,f])=>`${u}="${f}"`).join(" "),c=l?`${l} ${o}`:o;return e.exec(c)}},of={name:"printenv",summary:"print all or part of environment",usage:"printenv [OPTION]... [VARIABLE]...",options:[" --help display this help and exit"]},lf={name:"printenv",async execute(t,e){if(C(t))return A(of);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
+ `)+(i.length>0?`
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(`
295
332
  `)+(n.length>0?`
296
- `:""),stderr:"",exitCode:s}}}});var br={};I(br,{aliasCommand:()=>su,unaliasCommand:()=>iu});var nu,Ve,su,iu,Er=C(()=>{"use strict";R();nu={name:"alias",summary:"define or display aliases",usage:"alias [name[=value] ...]",options:[" --help display this help and exit"]},Ve="BASH_ALIAS_",su={name:"alias",async execute(t,e){if(S(t))return x(nu);if(t.length===0){let r="";for(let[n,s]of Object.entries(e.env))if(n.startsWith(Ve)){let o=n.slice(Ve.length);r+=`alias ${o}='${s}'
297
- `}return{stdout:r,stderr:"",exitCode:0}}for(let r of t){let n=r.indexOf("=");if(n===-1){let s=Ve+r;return e.env[s]?{stdout:`alias ${r}='${e.env[s]}'
333
+ `:""),stderr:"",exitCode:s}}}});var Qr={};O(Qr,{aliasCommand:()=>uf,unaliasCommand:()=>ff});var cf,ut,uf,ff,Kr=N(()=>{"use strict";T();cf={name:"alias",summary:"define or display aliases",usage:"alias [name[=value] ...]",options:[" --help display this help and exit"]},ut="BASH_ALIAS_",uf={name:"alias",async execute(t,e){if(C(t))return A(cf);if(t.length===0){let r="";for(let[n,s]of Object.entries(e.env))if(n.startsWith(ut)){let i=n.slice(ut.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=ut+r;return e.env[s]?{stdout:`alias ${r}='${e.env[s]}'
298
335
  `,stderr:"",exitCode:0}:{stdout:"",stderr:`alias: ${r}: not found
299
- `,exitCode:1}}else{let s=r.slice(0,n),o=r.slice(n+1);(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1)),e.env[Ve+s]=o}}return{stdout:"",stderr:"",exitCode:0}}},iu={name:"unalias",async execute(t,e){if(S(t))return x({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 ...]
300
- `,exitCode:1};if(t[0]==="-a"){for(let s of Object.keys(e.env))s.startsWith(Ve)&&delete e.env[s];return{stdout:"",stderr:"",exitCode:0}}let r=!1,n="";for(let s of t){let o=Ve+s;e.env[o]?delete e.env[o]:(n+=`unalias: ${s}: not found
301
- `,r=!0)}return{stdout:"",stderr:n,exitCode:r?1:0}}}});var Fi={};I(Fi,{historyCommand:()=>au});var ou,Mi,au,Li=C(()=>{"use strict";R();ou={name:"history",summary:"display command history",usage:"history [n]",options:["-c clear the history list"," --help display this help and exit"]},Mi="BASH_HISTORY",au={name:"history",async execute(t,e){if(S(t))return x(ou);let r=e.env[Mi]||"[]",n;try{n=JSON.parse(r)}catch{n=[]}if(t[0]==="-c")return e.env[Mi]="[]",{stdout:"",stderr:"",exitCode:0};let s=n.length;t[0]&&/^\d+$/.test(t[0])&&(s=Math.min(parseInt(t[0],10),n.length));let o=n.length-s,i="";for(let a=o;a<n.length;a++){let c=(a+1).toString().padStart(5," ");i+=`${c} ${n[a]}
302
- `}return{stdout:i,stderr:"",exitCode:0}}}});var Wi={};I(Wi,{xargsCommand:()=>cu});var lu,cu,_i=C(()=>{"use strict";R();lu={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"]},cu={name:"xargs",async execute(t,e){if(S(t))return x(lu);let r=null,n=null,s=null,o=!1,i=!1,a=!1,c=0;for(let y=0;y<t.length;y++){let w=t[y];if(w==="-I"&&y+1<t.length)r=t[++y],c=y+1;else if(w==="-n"&&y+1<t.length)n=parseInt(t[++y],10),c=y+1;else if(w==="-P"&&y+1<t.length)s=parseInt(t[++y],10),c=y+1;else if(w==="-0"||w==="--null")o=!0,c=y+1;else if(w==="-t"||w==="--verbose")i=!0,c=y+1;else if(w==="-r"||w==="--no-run-if-empty")a=!0,c=y+1;else{if(w.startsWith("--"))return O("xargs",w);if(w.startsWith("-")&&w.length>1){for(let $ of w.slice(1))if(!"0trnIP".includes($))return O("xargs",`-${$}`);w.includes("0")&&(o=!0),w.includes("t")&&(i=!0),w.includes("r")&&(a=!0),c=y+1}else if(!w.startsWith("-")){c=y;break}}}let l=t.slice(c);l.length===0&&l.push("echo");let u=o?"\0":/\s+/,f=e.stdin.split(u).map(y=>y.trim()).filter(y=>y.length>0);if(f.length===0)return a?{stdout:"",stderr:"",exitCode:0}:{stdout:"",stderr:"",exitCode:0};let d="",h="",p=0,b=async y=>{let w=y.join(" ");return i&&(h+=`${w}
303
- `),e.exec?e.exec(w):{stdout:`${w}
304
- `,stderr:"",exitCode:0}},g=async y=>{if(s!==null&&s>1)for(let w=0;w<y.length;w+=s){let E=y.slice(w,w+s),$=await Promise.all(E.map(b));for(let A of $)d+=A.stdout,h+=A.stderr,A.exitCode!==0&&(p=A.exitCode)}else for(let w of y){let E=await b(w);d+=E.stdout,h+=E.stderr,E.exitCode!==0&&(p=E.exitCode)}};if(r!==null){let y=f.map(w=>l.map(E=>E.replaceAll(r,w)));await g(y)}else if(n!==null){let y=[];for(let w=0;w<f.length;w+=n){let E=f.slice(w,w+n);y.push([...l,...E])}await g(y)}else{let y=[...l,...f],w=await b(y);d+=w.stdout,h+=w.stderr,p=w.exitCode}return{stdout:d,stderr:h,exitCode:p}}}});var xr={};I(xr,{falseCommand:()=>fu,trueCommand:()=>uu});var uu,fu,Sr=C(()=>{"use strict";uu={name:"true",async execute(){return{stdout:"",stderr:"",exitCode:0}}},fu={name:"false",async execute(){return{stdout:"",stderr:"",exitCode:1}}}});var Hi={};I(Hi,{clearCommand:()=>hu});var du,hu,Bi=C(()=>{"use strict";R();du={name:"clear",summary:"clear the terminal screen",usage:"clear [OPTIONS]",options:[" --help display this help and exit"]},hu={name:"clear",async execute(t,e){return S(t)?x(du):{stdout:"\x1B[2J\x1B[H",stderr:"",exitCode:0}}}});var Cr={};I(Cr,{bashCommand:()=>pu,shCommand:()=>mu});async function Nt(t,e,r,n){if(!n.exec)return{stdout:"",stderr:`bash: internal error: exec function not available
305
- `,exitCode:1};let s={0:e,"#":String(r.length),"@":r.join(" "),"*":r.join(" ")};r.forEach((u,f)=>{s[String(f+1)]=u});let o=t;if(o.startsWith("#!")){let u=o.indexOf(`
306
- `);u!==-1&&(o=o.slice(u+1))}let i=o.split(`
307
- `),a=[];for(let u of i){let f=u.trim();f&&!f.startsWith("#")&&a.push(f)}let c=a.join("; ");return await n.exec(c,{env:s})}var zi,pu,mu,Ar=C(()=>{"use strict";R();zi={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).']},pu={name:"bash",async execute(t,e){if(S(t))return x(zi);if(t[0]==="-c"&&t.length>=2){let s=t[1],o=t[2]||"bash",i=t.slice(3);return Nt(s,o,i,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),o=await e.fs.readFile(s);return Nt(o,r,n,e)}catch{return{stdout:"",stderr:`bash: ${r}: No such file or directory
308
- `,exitCode:127}}}},mu={name:"sh",async execute(t,e){if(S(t))return x({...zi,name:"sh",summary:"execute shell commands or scripts (POSIX shell)"});if(t[0]==="-c"&&t.length>=2){let s=t[1],o=t[2]||"sh",i=t.slice(3);return Nt(s,o,i,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),o=await e.fs.readFile(s);return Nt(o,r,n,e)}catch{return{stdout:"",stderr:`sh: ${r}: No such file or directory
309
- `,exitCode:127}}}}});var Ui={};I(Ui,{jqCommand:()=>yu});function rt(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(o=>rt(o,!0,!1)).join(",")}]`:`[
310
- ${t.map(o=>" ".repeat(n+1)+rt(o,!1,!1,n+1)).join(`,
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[ut+s]=i}}return{stdout:"",stderr:"",exitCode:0}}},ff={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(ut)&&delete e.env[s];return{stdout:"",stderr:"",exitCode:0}}let r=!1,n="";for(let s of t){let i=ut+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 ia={};O(ia,{historyCommand:()=>hf});var df,sa,hf,aa=N(()=>{"use strict";T();df={name:"history",summary:"display command history",usage:"history [n]",options:["-c clear the history list"," --help display this help and exit"]},sa="BASH_HISTORY",hf={name:"history",async execute(t,e){if(C(t))return A(df);let r=e.env[sa]||"[]",n;try{n=JSON.parse(r)}catch{n=[]}if(t[0]==="-c")return e.env[sa]="[]",{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 l=(o+1).toString().padStart(5," ");a+=`${l} ${n[o]}
339
+ `}return{stdout:a,stderr:"",exitCode:0}}}});var oa={};O(oa,{xargsCommand:()=>mf});var pf,mf,la=N(()=>{"use strict";T();pf={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"]},mf={name:"xargs",async execute(t,e){if(C(t))return A(pf);let r=null,n=null,s=null,i=!1,a=!1,o=!1,l=0;for(let g=0;g<t.length;g++){let E=t[g];if(E==="-I"&&g+1<t.length)r=t[++g],l=g+1;else if(E==="-n"&&g+1<t.length)n=parseInt(t[++g],10),l=g+1;else if(E==="-P"&&g+1<t.length)s=parseInt(t[++g],10),l=g+1;else if(E==="-0"||E==="--null")i=!0,l=g+1;else if(E==="-t"||E==="--verbose")a=!0,l=g+1;else if(E==="-r"||E==="--no-run-if-empty")o=!0,l=g+1;else{if(E.startsWith("--"))return L("xargs",E);if(E.startsWith("-")&&E.length>1){for(let S of E.slice(1))if(!"0trnIP".includes(S))return L("xargs",`-${S}`);E.includes("0")&&(i=!0),E.includes("t")&&(a=!0),E.includes("r")&&(o=!0),l=g+1}else if(!E.startsWith("-")){l=g;break}}}let c=t.slice(l);c.length===0&&c.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):{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=>c.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([...c,...x])}await w(g)}else{let g=[...c,...f],E=await b(g);d+=E.stdout,h+=E.stderr,p=E.exitCode}return{stdout:d,stderr:h,exitCode:p}}}});var Xr={};O(Xr,{falseCommand:()=>gf,trueCommand:()=>yf});var yf,gf,Yr=N(()=>{"use strict";yf={name:"true",async execute(){return{stdout:"",stderr:"",exitCode:0}}},gf={name:"false",async execute(){return{stdout:"",stderr:"",exitCode:1}}}});var ca={};O(ca,{clearCommand:()=>Ef});var wf,Ef,ua=N(()=>{"use strict";T();wf={name:"clear",summary:"clear the terminal screen",usage:"clear [OPTIONS]",options:[" --help display this help and exit"]},Ef={name:"clear",async execute(t,e){return C(t)?A(wf):{stdout:"\x1B[2J\x1B[H",stderr:"",exitCode:0}}}});var Jr={};O(Jr,{bashCommand:()=>bf,shCommand:()=>xf});async function Qt(t,e,r,n){if(!n.exec)return{stdout:"",stderr:`bash: internal error: exec function not available
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
+ `);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 l=o.join("; ");return await n.exec(l,{env:s})}var fa,bf,xf,en=N(()=>{"use strict";T();fa={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).']},bf={name:"bash",async execute(t,e){if(C(t))return A(fa);if(t[0]==="-c"&&t.length>=2){let s=t[1],i=t[2]||"bash",a=t.slice(3);return Qt(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 Qt(i,r,n,e)}catch{return{stdout:"",stderr:`bash: ${r}: No such file or directory
345
+ `,exitCode:127}}}},xf={name:"sh",async execute(t,e){if(C(t))return A({...fa,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 Qt(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 Qt(i,r,n,e)}catch{return{stdout:"",stderr:`sh: ${r}: No such file or directory
346
+ `,exitCode:127}}}}});var da={};O(da,{jqCommand:()=>Af});function At(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=>At(i,!0,!1)).join(",")}]`:`[
347
+ ${t.map(i=>" ".repeat(n+1)+At(i,!1,!1,n+1)).join(`,
311
348
  `)}
312
- ${" ".repeat(n)}]`;if(typeof t=="object"){let s=Object.keys(t);return s.length===0?"{}":e?`{${s.map(i=>`${JSON.stringify(i)}:${rt(t[i],!0,!1)}`).join(",")}}`:`{
313
- ${s.map(i=>{let a=rt(t[i],!1,!1,n+1);return`${" ".repeat(n+1)}${JSON.stringify(i)}: ${a}`}).join(`,
349
+ ${" ".repeat(n)}]`;if(typeof t=="object"){let s=Object.keys(t);return s.length===0?"{}":e?`{${s.map(a=>`${JSON.stringify(a)}:${At(t[a],!0,!1)}`).join(",")}}`:`{
350
+ ${s.map(a=>{let o=At(t[a],!1,!1,n+1);return`${" ".repeat(n+1)}${JSON.stringify(a)}: ${o}`}).join(`,
314
351
  `)}
315
- ${" ".repeat(n)}}`}return String(t)}function Pe(t,e){if(e===""||e===".")return[t];let r=e.startsWith(".")?e.slice(1):e;if(r==="")return[t];if(r.startsWith("[]")){let i=r.slice(2);return Array.isArray(t)?t.flatMap(a=>Pe(a,`.${i}`)):t&&typeof t=="object"?Object.values(t).flatMap(a=>Pe(a,`.${i}`)):[]}let n=r.match(/^\[(-?\d+)\](.*)/);if(n){let i=Number.parseInt(n[1],10),a=n[2];if(Array.isArray(t)){let c=i<0?t.length+i:i;if(c>=0&&c<t.length)return Pe(t[c],`.${a}`)}return[null]}let s=r.match(/^([a-zA-Z_][a-zA-Z0-9_]*)(.*)/);if(s){let i=s[1],a=s[2];if(t&&typeof t=="object"&&!Array.isArray(t)){let l=t[i];if(a.startsWith("[]"))return a=a.slice(2),Array.isArray(l)?l.flatMap(u=>Pe(u,`.${a}`)):l&&typeof l=="object"?Object.values(l).flatMap(u=>Pe(u,`.${a}`)):[];if(a.startsWith(".")||a.startsWith("[")||a==="")return Pe(l,a||".")}return[null]}let o=r.match(/^\["([^"]+)"\](.*)/);if(o){let i=o[1],a=o[2];return t&&typeof t=="object"&&!Array.isArray(t)?Pe(t[i],`.${a}`):[null]}return[null]}function nt(t,e){let r=e.trim();if(r.includes("|")){let n=r.split("|").map(o=>o.trim()),s=[t];for(let o of n)s=s.flatMap(i=>nt(i,o));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]:Pe(t,r)}var gu,yu,ji=C(()=>{"use strict";R();gu={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"]};yu={name:"jq",async execute(t,e){if(S(t))return x(gu);let r=!1,n=!1,s=!1,o=!1,i=!1,a=".",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")o=!0;else if(d==="-n"||d==="--null-input")i=!0;else if(d==="-")l.push("-");else{if(d.startsWith("--"))return O("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")o=!0;else if(h==="n")i=!0;else return O("jq",`-${h}`);else c?l.push(d):(a=d,c=!0)}}let u;if(i)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
316
- `,exitCode:2}}try{let f;if(i)f=nt(null,a);else if(o){let p=[];for(let b of u.trim().split(`
317
- `))b.trim()&&p.push(JSON.parse(b));f=nt(p,a)}else{let p=u.trim();if(p.startsWith("{")||p.startsWith("["))f=nt(JSON.parse(p),a);else{f=[];for(let b of p.split(`
318
- `))b.trim()&&f.push(...nt(JSON.parse(b),a))}}let d=f.map(p=>rt(p,n,r)).join(`
352
+ ${" ".repeat(n)}}`}return String(t)}function He(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=>He(o,`.${a}`)):t&&typeof t=="object"?Object.values(t).flatMap(o=>He(o,`.${a}`)):[]}let n=r.match(/^\[(-?\d+)\](.*)/);if(n){let a=Number.parseInt(n[1],10),o=n[2];if(Array.isArray(t)){let l=a<0?t.length+a:a;if(l>=0&&l<t.length)return He(t[l],`.${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 c=t[a];if(o.startsWith("[]"))return o=o.slice(2),Array.isArray(c)?c.flatMap(u=>He(u,`.${o}`)):c&&typeof c=="object"?Object.values(c).flatMap(u=>He(u,`.${o}`)):[];if(o.startsWith(".")||o.startsWith("[")||o==="")return He(c,o||".")}return[null]}let i=r.match(/^\["([^"]+)"\](.*)/);if(i){let a=i[1],o=i[2];return t&&typeof t=="object"&&!Array.isArray(t)?He(t[a],`.${o}`):[null]}return[null]}function Ct(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=>Ct(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]:He(t,r)}var Sf,Af,ha=N(()=>{"use strict";T();Sf={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"]};Af={name:"jq",async execute(t,e){if(C(t))return A(Sf);let r=!1,n=!1,s=!1,i=!1,a=!1,o=".",l=!1,c=[];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==="-")c.push("-");else{if(d.startsWith("--"))return L("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 L("jq",`-${h}`);else l?c.push(d):(o=d,l=!0)}}let u;if(a)u="";else if(c.length===0||c.length===1&&c[0]==="-")u=e.stdin;else try{let f=e.fs.resolvePath(e.cwd,c[0]);u=await e.fs.readFile(f)}catch{return{stdout:"",stderr:`jq: ${c[0]}: No such file or directory
353
+ `,exitCode:2}}try{let f;if(a)f=Ct(null,o);else if(i){let p=[];for(let b of u.trim().split(`
354
+ `))b.trim()&&p.push(JSON.parse(b));f=Ct(p,o)}else{let p=u.trim();if(p.startsWith("{")||p.startsWith("["))f=Ct(JSON.parse(p),o);else{f=[];for(let b of p.split(`
355
+ `))b.trim()&&f.push(...Ct(JSON.parse(b),o))}}let d=f.map(p=>At(p,n,r)).join(`
319
356
  `),h=s&&(f.length===0||f.every(p=>p==null||p===!1))?1:0;return{stdout:d?`${d}
320
357
  `:"",stderr:"",exitCode:h}}catch(f){return{stdout:"",stderr:`jq: parse error: ${f.message}
321
- `,exitCode:5}}}}});var qi={};I(qi,{base64Command:()=>Eu});var wu,bu,Eu,Gi=C(()=>{"use strict";Y();Le();R();wu={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"]},bu={decode:{short:"d",long:"decode",type:"boolean"},wrap:{short:"w",long:"wrap",type:"number",default:76}},Eu={name:"base64",async execute(t,e){if(S(t))return x(wu);let r=M("base64",t,bu);if(!r.ok)return r.error;let n=r.result.flags.decode,s=r.result.flags.wrap,o=r.result.positional,i=await Ie(e,o,{cmdName:"base64"});if(!i.ok)return i.error;let a=i.content;try{if(n){let l=a.replace(/\s/g,"");return{stdout:Buffer.from(l,"base64").toString("utf-8"),stderr:"",exitCode:0}}let c=Buffer.from(a).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(`
322
- `)+(c.length>0?`
323
- `:"")}return{stdout:c,stderr:"",exitCode:0}}catch{return{stdout:"",stderr:`base64: invalid input
324
- `,exitCode:1}}}}});var Zi={};I(Zi,{diffCommand:()=>Cu});import*as Vi from"diff";var xu,Su,Cu,Qi=C(()=>{"use strict";Y();R();xu={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"]},Su={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"}},Cu={name:"diff",async execute(t,e){if(S(t))return x(xu);let r=M("diff",t,Su);if(!r.ok)return r.error;let n=r.result.flags.brief,s=r.result.flags.reportSame,o=r.result.flags.ignoreCase,i=r.result.positional;if(r.result.flags.unified,i.length<2)return{stdout:"",stderr:`diff: missing operand
325
- `,exitCode:2};let a,c,[l,u]=i;try{a=l==="-"?e.stdin:await e.fs.readFile(e.fs.resolvePath(e.cwd,l))}catch{return{stdout:"",stderr:`diff: ${l}: No such file or directory
326
- `,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
327
- `,exitCode:2}}let f=a,d=c;return o&&(f=f.toLowerCase(),d=d.toLowerCase()),f===d?s?{stdout:`Files ${l} and ${u} are identical
328
- `,stderr:"",exitCode:0}:{stdout:"",stderr:"",exitCode:0}:n?{stdout:`Files ${l} and ${u} differ
329
- `,stderr:"",exitCode:1}:{stdout:Vi.createTwoFilesPatch(l,u,a,c,"","",{context:3}),stderr:"",exitCode:1}}}});var Ki={};I(Ki,{dateCommand:()=>Iu});function ne(t,e=2){return String(t).padStart(e,"0")}function vu(t){let e=-t.getTimezoneOffset();return`${e>=0?"+":"-"}${ne(Math.floor(Math.abs(e)/60))}${ne(Math.abs(e)%60)}`}function vt(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="",o=0;for(;o<e.length;){if(e[o]==="%"&&o+1<e.length){let i=e[++o];switch(i){case"%":s+="%";break;case"a":s+=$u[n.w];break;case"b":case"h":s+=Nu[n.m];break;case"d":s+=ne(n.D);break;case"e":s+=String(n.D).padStart(2," ");break;case"F":s+=`${n.Y}-${ne(n.m+1)}-${ne(n.D)}`;break;case"H":s+=ne(n.H);break;case"I":s+=ne(n.H%12||12);break;case"m":s+=ne(n.m+1);break;case"M":s+=ne(n.M);break;case"n":s+=`
330
- `;break;case"p":s+=n.H<12?"AM":"PM";break;case"P":s+=n.H<12?"am":"pm";break;case"R":s+=`${ne(n.H)}:${ne(n.M)}`;break;case"s":s+=Math.floor(t.getTime()/1e3);break;case"S":s+=ne(n.S);break;case"t":s+=" ";break;case"T":s+=`${ne(n.H)}:${ne(n.M)}:${ne(n.S)}`;break;case"u":s+=n.w||7;break;case"w":s+=n.w;break;case"y":s+=ne(n.Y%100);break;case"Y":s+=n.Y;break;case"z":s+=r?"+0000":vu(t);break;case"Z":s+=r?"UTC":Intl.DateTimeFormat().resolvedOptions().timeZone;break;default:s+=`%${i}`}}else s+=e[o];o++}return s}function ku(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 Au,$u,Nu,Iu,Xi=C(()=>{"use strict";R();Au={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"]},$u=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Nu=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];Iu={name:"date",async execute(t,e){if(S(t))return x(Au);let r=!1,n=null,s=null,o=!1,i=!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")o=!0;else if(u==="-R"||u==="--rfc-email")i=!0;else if(u.startsWith("+"))s=u.slice(1);else{if(u.startsWith("--"))return O("date",u);if(u.startsWith("-"))for(let f of u.slice(1))if(f==="u")r=!0;else if(f==="I")o=!0;else if(f==="R")i=!0;else return O("date",`-${f}`)}}let a=n!==null?ku(n):new Date;if(!a)return{stdout:"",stderr:`date: invalid date '${n}'
331
- `,exitCode:1};let c;return s?c=vt(a,s,r):o?c=vt(a,"%Y-%m-%dT%H:%M:%S%z",r):i?c=vt(a,"%a, %d %b %Y %H:%M:%S %z",r):c=vt(a,"%a %b %e %H:%M:%S %Z %Y",r),{stdout:`${c}
332
- `,stderr:"",exitCode:0}}}});var Yi={};I(Yi,{sleepCommand:()=>Ou});function Ru(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 Pu,Ou,Ji=C(()=>{"use strict";R();Pu={name:"sleep",summary:"delay for a specified amount of time",usage:"sleep NUMBER[SUFFIX]",description:`Pause for NUMBER seconds. SUFFIX may be:
358
+ `,exitCode:5}}}}});var pa={};O(pa,{base64Command:()=>vf});var Cf,Nf,vf,ma=N(()=>{"use strict";ae();Ve();T();Cf={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"]},Nf={decode:{short:"d",long:"decode",type:"boolean"},wrap:{short:"w",long:"wrap",type:"number",default:76}},vf={name:"base64",async execute(t,e){if(C(t))return A(Cf);let r=H("base64",t,Nf);if(!r.ok)return r.error;let n=r.result.flags.decode,s=r.result.flags.wrap,i=r.result.positional,a=await We(e,i,{cmdName:"base64"});if(!a.ok)return a.error;let o=a.content;try{if(n){let c=o.replace(/\s/g,"");return{stdout:Buffer.from(c,"base64").toString("utf-8"),stderr:"",exitCode:0}}let l=Buffer.from(o).toString("base64");if(s>0){let c=[];for(let u=0;u<l.length;u+=s)c.push(l.slice(u,u+s));l=c.join(`
359
+ `)+(l.length>0?`
360
+ `:"")}return{stdout:l,stderr:"",exitCode:0}}catch{return{stdout:"",stderr:`base64: invalid input
361
+ `,exitCode:1}}}}});var ga={};O(ga,{diffCommand:()=>Rf});import*as ya from"diff";var kf,If,Rf,wa=N(()=>{"use strict";ae();T();kf={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"]},If={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"}},Rf={name:"diff",async execute(t,e){if(C(t))return A(kf);let r=H("diff",t,If);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
+ `,exitCode:2};let o,l,[c,u]=a;try{o=c==="-"?e.stdin:await e.fs.readFile(e.fs.resolvePath(e.cwd,c))}catch{return{stdout:"",stderr:`diff: ${c}: No such file or directory
363
+ `,exitCode:2}}try{l=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
+ `,exitCode:2}}let f=o,d=l;return i&&(f=f.toLowerCase(),d=d.toLowerCase()),f===d?s?{stdout:`Files ${c} and ${u} are identical
365
+ `,stderr:"",exitCode:0}:{stdout:"",stderr:"",exitCode:0}:n?{stdout:`Files ${c} and ${u} differ
366
+ `,stderr:"",exitCode:1}:{stdout:ya.createTwoFilesPatch(c,u,o,l,"","",{context:3}),stderr:"",exitCode:1}}}});var Ea={};O(Ea,{dateCommand:()=>Lf});function fe(t,e=2){return String(t).padStart(e,"0")}function Df(t){let e=-t.getTimezoneOffset();return`${e>=0?"+":"-"}${fe(Math.floor(Math.abs(e)/60))}${fe(Math.abs(e)%60)}`}function Kt(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+=Pf[n.w];break;case"b":case"h":s+=Of[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":Df(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 $f,Pf,Of,Lf,ba=N(()=>{"use strict";T();$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"]},Pf=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],Of=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];Lf={name:"date",async execute(t,e){if(C(t))return A($f);let r=!1,n=null,s=null,i=!1,a=!1;for(let c=0;c<t.length;c++){let u=t[c];if(u==="-u"||u==="--utc")r=!0;else if(u==="-d"||u==="--date")n=t[++c]??"";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 L("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 L("date",`-${f}`)}}let o=n!==null?Tf(n):new Date;if(!o)return{stdout:"",stderr:`date: invalid date '${n}'
368
+ `,exitCode:1};let l;return s?l=Kt(o,s,r):i?l=Kt(o,"%Y-%m-%dT%H:%M:%S%z",r):a?l=Kt(o,"%a, %d %b %Y %H:%M:%S %z",r):l=Kt(o,"%a %b %e %H:%M:%S %Z %Y",r),{stdout:`${l}
369
+ `,stderr:"",exitCode:0}}}});var xa={};O(xa,{sleepCommand:()=>_f});function Mf(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 Ff,_f,Sa=N(()=>{"use strict";T();Ff={name:"sleep",summary:"delay for a specified amount of time",usage:"sleep NUMBER[SUFFIX]",description:`Pause for NUMBER seconds. SUFFIX may be:
333
370
  s - seconds (default)
334
371
  m - minutes
335
372
  h - hours
336
373
  d - days
337
374
 
338
- NUMBER may be a decimal number.`,options:[" --help display this help and exit"]};Ou={name:"sleep",async execute(t,e){if(S(t))return x(Pu);if(t.length===0)return{stdout:"",stderr:`sleep: missing operand
339
- `,exitCode:1};let r=0;for(let n of t){let s=Ru(n);if(s===null)return{stdout:"",stderr:`sleep: invalid time interval '${n}'
340
- `,exitCode:1};r+=s}return e.sleep?await e.sleep(r):await new Promise(n=>setTimeout(n,r)),{stdout:"",stderr:"",exitCode:0}}}});var eo={};I(eo,{timeoutCommand:()=>Mu});function Tu(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 Du,Mu,to=C(()=>{"use strict";R();Du={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"]};_f={name:"sleep",async execute(t,e){if(C(t))return A(Ff);if(t.length===0)return{stdout:"",stderr:`sleep: missing operand
376
+ `,exitCode:1};let r=0;for(let n of t){let s=Mf(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 Aa={};O(Aa,{timeoutCommand:()=>Hf});function Bf(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 Wf,Hf,Ca=N(()=>{"use strict";T();Wf={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.
341
378
 
342
379
  DURATION is a number with optional suffix:
343
380
  s - seconds (default)
344
381
  m - minutes
345
382
  h - hours
346
- 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"]};Mu={name:"timeout",async execute(t,e){if(S(t))return x(Du);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 O("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 O("timeout",h);else{n=d;break}}}let s=t.slice(n);if(s.length===0)return{stdout:"",stderr:`timeout: missing operand
347
- `,exitCode:1};let o=s[0],i=Tu(o);if(i===null)return{stdout:"",stderr:`timeout: invalid time interval '${o}'
348
- `,exitCode:1};let a=s.slice(1);if(a.length===0)return{stdout:"",stderr:`timeout: missing operand
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"]};Hf={name:"timeout",async execute(t,e){if(C(t))return A(Wf);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 L("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 L("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=Bf(i);if(a===null)return{stdout:"",stderr:`timeout: invalid time interval '${i}'
385
+ `,exitCode:1};let o=s.slice(1);if(o.length===0)return{stdout:"",stderr:`timeout: missing operand
349
386
  `,exitCode:1};if(!e.exec)return{stdout:"",stderr:`timeout: exec not available
350
- `,exitCode:1};let c=a.map(d=>d.includes(" ")||d.includes(" ")?`'${d.replace(/'/g,"'\\''")}'`:d).join(" "),l=new Promise(d=>{setTimeout(()=>d({timedOut:!0}),i)}),u=e.exec(c).then(d=>({timedOut:!1,result:d})),f=await Promise.race([l,u]);return f.timedOut?{stdout:"",stderr:"",exitCode:124}:f.result}}});var ro={};I(ro,{seqCommand:()=>Fu});var Fu,no=C(()=>{"use strict";Fu={name:"seq",async execute(t){let e=`
387
+ `,exitCode:1};let l=o.map(d=>d.includes(" ")||d.includes(" ")?`'${d.replace(/'/g,"'\\''")}'`:d).join(" "),c=new Promise(d=>{setTimeout(()=>d({timedOut:!0}),a)}),u=e.exec(l).then(d=>({timedOut:!1,result:d})),f=await Promise.race([c,u]);return f.timedOut?{stdout:"",stderr:"",exitCode:124}:f.result}}});var Na={};O(Na,{seqCommand:()=>Uf});var Uf,va=N(()=>{"use strict";Uf={name:"seq",async execute(t){let e=`
351
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
352
- `,exitCode:1};let o=1,i=1,a;if(n.length===1?a=parseFloat(n[0]):n.length===2?(o=parseFloat(n[0]),a=parseFloat(n[1])):(o=parseFloat(n[0]),i=parseFloat(n[1]),a=parseFloat(n[2])),Number.isNaN(o)||Number.isNaN(i)||Number.isNaN(a))return{stdout:"",stderr:`seq: invalid floating point argument: '${n.find(b=>Number.isNaN(parseFloat(b)))}'
353
- `,exitCode:1};if(i===0)return{stdout:"",stderr:`seq: invalid Zero increment value: '0'
354
- `,exitCode:1};let c=[],l=p=>{let b=String(p),g=b.indexOf(".");return g===-1?0:b.length-g-1},u=Math.max(l(o),l(i),l(a)),f=1e5,d=0;if(i>0)for(let p=o;p<=a+1e-10&&!(d++>f);p+=i)c.push(u>0?p.toFixed(u):String(Math.round(p)));else for(let p=o;p>=a-1e-10&&!(d++>f);p+=i)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 g=c[b].startsWith("-"),w=(g?c[b].slice(1):c[b]).padStart(p,"0");c[b]=g?`-${w}`:w}}let h=c.join(e);return{stdout:h?`${h}
355
- `:"",stderr:"",exitCode:0}}}});var so={};I(so,{exprCommand:()=>Lu});function Wu(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=o();for(;e<t.length;){let u=t[e];if(["=","!=","<",">","<=",">="].includes(u)){e++;let f=o(),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 o(){let l=i();for(;e<t.length;){let u=t[e];if(u==="+"||u==="-"){e++;let f=i(),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 i(){let l=a();for(;e<t.length;){let u=t[e];if(u==="*"||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");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 a(){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 Lu,io=C(()=>{"use strict";Lu={name:"expr",async execute(t,e){if(t.length===0)return{stdout:"",stderr:`expr: missing operand
356
- `,exitCode:2};try{let r=Wu(t),n=r==="0"||r===""?1:0;return{stdout:`${r}
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)))}'
390
+ `,exitCode:1};if(a===0)return{stdout:"",stderr:`seq: invalid Zero increment value: '0'
391
+ `,exitCode:1};let l=[],c=p=>{let b=String(p),w=b.indexOf(".");return w===-1?0:b.length-w-1},u=Math.max(c(i),c(a),c(o)),f=1e5,d=0;if(a>0)for(let p=i;p<=o+1e-10&&!(d++>f);p+=a)l.push(u>0?p.toFixed(u):String(Math.round(p)));else for(let p=i;p>=o-1e-10&&!(d++>f);p+=a)l.push(u>0?p.toFixed(u):String(Math.round(p)));if(r&&l.length>0){let p=Math.max(...l.map(b=>b.replace("-","").length));for(let b=0;b<l.length;b++){let w=l[b].startsWith("-"),E=(w?l[b].slice(1):l[b]).padStart(p,"0");l[b]=w?`-${E}`:E}}let h=l.join(e);return{stdout:h?`${h}
392
+ `:"",stderr:"",exitCode:0}}}});var ka={};O(ka,{exprCommand:()=>zf});function Gf(t){if(t.length===1)return t[0];let e=0;function r(){let c=n();for(;e<t.length&&t[e]==="|";){e++;let u=n();if(c!=="0"&&c!=="")return c;c=u}return c}function n(){let c=s();for(;e<t.length&&t[e]==="&";){e++;let u=s();(c==="0"||c===""||u==="0"||u==="")&&(c="0")}return c}function s(){let c=i();for(;e<t.length;){let u=t[e];if(["=","!=","<",">","<=",">="].includes(u)){e++;let f=i(),d=parseInt(c,10),h=parseInt(f,10),p=!Number.isNaN(d)&&!Number.isNaN(h),b;u==="="?b=p?d===h:c===f:u==="!="?b=p?d!==h:c!==f:u==="<"?b=p?d<h:c<f:u===">"?b=p?d>h:c>f:u==="<="?b=p?d<=h:c<=f:b=p?d>=h:c>=f,c=b?"1":"0"}else break}return c}function i(){let c=a();for(;e<t.length;){let u=t[e];if(u==="+"||u==="-"){e++;let f=a(),d=parseInt(c,10),h=parseInt(f,10);if(Number.isNaN(d)||Number.isNaN(h))throw new Error("non-integer argument");c=String(u==="+"?d+h:d-h)}else break}return c}function a(){let c=o();for(;e<t.length;){let u=t[e];if(u==="*"||u==="/"||u==="%"){e++;let f=o(),d=parseInt(c,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==="*"?c=String(d*h):u==="/"?c=String(Math.trunc(d/h)):c=String(d%h)}else break}return c}function o(){let c=l();for(;e<t.length&&t[e]===":";){e++;let u=l(),f=new RegExp(`^${u}`),d=c.match(f);d?c=d[1]!==void 0?d[1]:String(d[0].length):c="0"}return c}function l(){if(e>=t.length)throw new Error("syntax error");let c=t[e];if(c==="match"){e++;let u=l(),f=l(),d=new RegExp(f),h=u.match(d);return h?h[1]!==void 0?h[1]:String(h[0].length):"0"}if(c==="substr"){e++;let u=l(),f=parseInt(l(),10),d=parseInt(l(),10);if(Number.isNaN(f)||Number.isNaN(d))throw new Error("non-integer argument");return u.substring(f-1,f-1+d)}if(c==="index"){e++;let u=l(),f=l();for(let d=0;d<u.length;d++)if(f.includes(u[d]))return String(d+1);return"0"}if(c==="length"){e++;let u=l();return String(u.length)}if(c==="("){e++;let u=r();if(e>=t.length||t[e]!==")")throw new Error("syntax error");return e++,u}return e++,c}return r()}var zf,Ia=N(()=>{"use strict";zf={name:"expr",async execute(t,e){if(t.length===0)return{stdout:"",stderr:`expr: missing operand
393
+ `,exitCode:2};try{let r=Gf(t),n=r==="0"||r===""?1:0;return{stdout:`${r}
357
394
  `,stderr:"",exitCode:n}}catch(r){return{stdout:"",stderr:`expr: ${r.message}
358
- `,exitCode:2}}}}});var oo={};I(oo,{htmlToMarkdownCommand:()=>Bu});import _u from"turndown";var Hu,Bu,ao=C(()=>{"use strict";R();Hu={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"]},Bu={name:"html-to-markdown",async execute(t,e){if(S(t))return x(Hu);let r="-",n="```",s="---",o="atx",i=[];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")&&(o=u)}else if(l==="-")i.push("-");else{if(l.startsWith("--"))return O("html-to-markdown",l);if(l.startsWith("-"))return O("html-to-markdown",l);i.push(l)}}let a;if(i.length===0||i.length===1&&i[0]==="-")a=e.stdin;else try{let c=e.fs.resolvePath(e.cwd,i[0]);a=await e.fs.readFile(c)}catch{return{stdout:"",stderr:`html-to-markdown: ${i[0]}: No such file or directory
359
- `,exitCode:1}}if(!a.trim())return{stdout:"",stderr:"",exitCode:0};try{let c=new _u({bulletListMarker:r,codeBlockStyle:"fenced",fence:n,hr:s,headingStyle:o});return c.remove(["script","style","footer"]),{stdout:`${c.turndown(a).trim()}
360
- `,stderr:"",exitCode:0}}catch(c){return{stdout:"",stderr:`html-to-markdown: conversion error: ${c.message}
361
- `,exitCode:1}}}}});var lo={};I(lo,{helpCommand:()=>ju});function Uu(t){let e=[],r=new Set(t);e.push(`Available commands:
362
- `);let n=[];for(let[s,o]of Object.entries(zu)){let i=o.filter(a=>r.has(a));if(i.length>0){e.push(` ${s}:`),e.push(` ${i.join(", ")}
363
- `);for(let a of i)r.delete(a)}}for(let s of r)n.push(s);return n.length>0&&(e.push(" Other:"),e.push(` ${n.sort().join(", ")}
395
+ `,exitCode:2}}}}});var Ra={};O(Ra,{htmlToMarkdownCommand:()=>Vf});import jf from"turndown";var qf,Vf,$a=N(()=>{"use strict";T();qf={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"]},Vf={name:"html-to-markdown",async execute(t,e){if(C(t))return A(qf);let r="-",n="```",s="---",i="atx",a=[];for(let l=0;l<t.length;l++){let c=t[l];if(c==="-b"||c==="--bullet")r=t[++l]??"-";else if(c.startsWith("--bullet="))r=c.slice(9);else if(c==="-c"||c==="--code")n=t[++l]??"```";else if(c.startsWith("--code="))n=c.slice(7);else if(c==="-r"||c==="--hr")s=t[++l]??"---";else if(c.startsWith("--hr="))s=c.slice(5);else if(c.startsWith("--heading-style=")){let u=c.slice(16);(u==="setext"||u==="atx")&&(i=u)}else if(c==="-")a.push("-");else{if(c.startsWith("--"))return L("html-to-markdown",c);if(c.startsWith("-"))return L("html-to-markdown",c);a.push(c)}}let o;if(a.length===0||a.length===1&&a[0]==="-")o=e.stdin;else try{let l=e.fs.resolvePath(e.cwd,a[0]);o=await e.fs.readFile(l)}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 l=new jf({bulletListMarker:r,codeBlockStyle:"fenced",fence:n,hr:s,headingStyle:i});return l.remove(["script","style","footer"]),{stdout:`${l.turndown(o).trim()}
397
+ `,stderr:"",exitCode:0}}catch(l){return{stdout:"",stderr:`html-to-markdown: conversion error: ${l.message}
398
+ `,exitCode:1}}}}});var Pa={};O(Pa,{helpCommand:()=>Kf});function Qf(t){let e=[],r=new Set(t);e.push(`Available commands:
399
+ `);let n=[];for(let[s,i]of Object.entries(Zf)){let a=i.filter(o=>r.has(o));if(a.length>0){e.push(` ${s}:`),e.push(` ${a.join(", ")}
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(", ")}
364
401
  `)),e.push("Use '<command> --help' for details on a specific command."),`${e.join(`
365
402
  `)}
366
- `}var zu,ju,co=C(()=>{"use strict";zu={"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"]};ju={name:"help",async execute(t,e){if(t.includes("--help")||t.includes("-h"))return{stdout:`help - display available commands
403
+ `}var Zf,Kf,Oa=N(()=>{"use strict";Zf={"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"]};Kf={name:"help",async execute(t,e){if(t.includes("--help")||t.includes("-h"))return{stdout:`help - display available commands
367
404
 
368
405
  Usage: help [command]
369
406
 
@@ -372,96 +409,96 @@ Options:
372
409
 
373
410
  If a command name is provided, shows help for that command.
374
411
  Otherwise, lists all available commands.
375
- `,stderr:"",exitCode:0};if(t.length>0&&e.exec){let n=t[0];return e.exec(`${n} --help`)}let r=e.getRegisteredCommands?.()??[];return{stdout:Uu(r),stderr:"",exitCode:0}}}});var uo={};I(uo,{whichCommand:()=>Vu});var qu,Gu,Vu,fo=C(()=>{"use strict";Y();R();qu={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"]},Gu={showAll:{short:"a",type:"boolean"},silent:{short:"s",type:"boolean"}},Vu={name:"which",async execute(t,e){if(S(t))return x(qu);let r=M("which",t,Gu);if(!r.ok)return r.error;let n=r.result.flags.showAll,s=r.result.flags.silent,o=r.result.positional;if(o.length===0)return{stdout:"",stderr:"",exitCode:1};let a=(e.env.PATH||"/bin:/usr/bin").split(":"),c="",l=!0;for(let u of o){let f=!1;for(let d of a){if(!d)continue;let h=`${d}/${u}`;if(await e.fs.exists(h)&&(f=!0,s||(c+=`${h}
376
- `),!n))break}f||(l=!1)}return{stdout:c,stderr:"",exitCode:l?0:1}}}});function $r(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 Nr(t){let e=t.indexOf("=");if(e<0)return null;let r=t.slice(0,e),n=t.slice(e+1),s,o,i=n.match(/;type=([^;]+)$/);i&&(o=i[1],n=n.slice(0,-i[0].length));let a=n.match(/;filename=([^;]+)/);return a&&(s=a[1],n=n.replace(a[0],"")),(n.startsWith("@")||n.startsWith("<"))&&(s=s??n.slice(1).split("/").pop()),{name:r,value:n,filename:s,contentType:o}}function ho(t,e){let r=`----CurlFormBoundary${Date.now().toString(36)}`,n=[];for(let s of t){let o=s.value;if(o.startsWith("@")||o.startsWith("<")){let a=o.slice(1);o=e.get(a)??""}let i=`--${r}\r
377
- `;s.filename?(i+=`Content-Disposition: form-data; name="${s.name}"; filename="${s.filename}"\r
378
- `,s.contentType&&(i+=`Content-Type: ${s.contentType}\r
379
- `)):i+=`Content-Disposition: form-data; name="${s.name}"\r
380
- `,i+=`\r
381
- ${o}\r
382
- `,n.push(i)}return n.push(`--${r}--\r
383
- `),{body:n.join(""),boundary:r}}var vr=C(()=>{"use strict"});var po,mo=C(()=>{"use strict";po={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 go(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 o=s.indexOf(":");if(o>0){let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();e.headers[i]=a}}}else if(n.startsWith("--header=")){let s=n.slice(9),o=s.indexOf(":");if(o>0){let i=s.slice(0,o).trim(),a=s.slice(o+1).trim();e.headers[i]=a}}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}&`:"")+$r(s),e.method==="GET"&&(e.method="POST")}else if(n.startsWith("--data-urlencode=")){let s=n.slice(17);e.data=(e.data?`${e.data}&`:"")+$r(s),e.method==="GET"&&(e.method="POST")}else if(n==="-F"||n==="--form"){let s=t[++r]??"",o=Nr(s);o&&e.formFields.push(o),e.method==="GET"&&(e.method="POST")}else if(n.startsWith("--form=")){let s=n.slice(7),o=Nr(s);o&&e.formFields.push(o),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 O("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 O("curl",`-${s}`)}else n.startsWith("-")||(e.url=n)}}return e}var yo=C(()=>{"use strict";R();vr()});function kr(t){return Object.entries(t).map(([e,r])=>`${e}: ${r}`).join(`\r
384
- `)}function wo(t){try{return new URL(t).pathname.split("/").pop()||"index.html"}catch{return"index.html"}}function Ir(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,`
385
- `),r}var bo=C(()=>{"use strict"});var Eo={};I(Eo,{curlCommand:()=>Yu});async function Zu(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 o of t.formFields)if(o.value.startsWith("@")||o.value.startsWith("<")){let i=e.fs.resolvePath(e.cwd,o.value.slice(1));try{let a=await e.fs.readFile(i);r.set(o.value.slice(1),a)}catch{r.set(o.value.slice(1),"")}}let{body:n,boundary:s}=ho(t.formFields,r);return{body:n,contentType:`multipart/form-data; boundary=${s}`}}return t.data!==void 0?{body:t.data}:{}}function Qu(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 Ku(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 Xu(t,e,r){let n="";if(t.verbose){n+=`> ${t.method} ${r}
386
- `;for(let[s,o]of Object.entries(t.headers))n+=`> ${s}: ${o}
412
+ `,stderr:"",exitCode:0};if(t.length>0&&e.exec){let n=t[0];return e.exec(`${n} --help`)}let r=e.getRegisteredCommands?.()??[];return{stdout:Qf(r),stderr:"",exitCode:0}}}});var Da={};O(Da,{whichCommand:()=>Jf});var Xf,Yf,Jf,Ta=N(()=>{"use strict";ae();T();Xf={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"]},Yf={showAll:{short:"a",type:"boolean"},silent:{short:"s",type:"boolean"}},Jf={name:"which",async execute(t,e){if(C(t))return A(Xf);let r=H("which",t,Yf);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(":"),l="",c=!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||(l+=`${h}
413
+ `),!n))break}f||(c=!1)}return{stdout:l,stderr:"",exitCode:c?0:1}}}});function tn(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 rn(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 La(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
+ `;s.filename?(a+=`Content-Disposition: form-data; name="${s.name}"; filename="${s.filename}"\r
415
+ `,s.contentType&&(a+=`Content-Type: ${s.contentType}\r
416
+ `)):a+=`Content-Disposition: form-data; name="${s.name}"\r
417
+ `,a+=`\r
418
+ ${i}\r
419
+ `,n.push(a)}return n.push(`--${r}--\r
420
+ `),{body:n.join(""),boundary:r}}var nn=N(()=>{"use strict"});var Fa,Ma=N(()=>{"use strict";Fa={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 _a(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}&`:"")+tn(s),e.method==="GET"&&(e.method="POST")}else if(n.startsWith("--data-urlencode=")){let s=n.slice(17);e.data=(e.data?`${e.data}&`:"")+tn(s),e.method==="GET"&&(e.method="POST")}else if(n==="-F"||n==="--form"){let s=t[++r]??"",i=rn(s);i&&e.formFields.push(i),e.method==="GET"&&(e.method="POST")}else if(n.startsWith("--form=")){let s=n.slice(7),i=rn(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 L("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 L("curl",`-${s}`)}else n.startsWith("-")||(e.url=n)}}return e}var Wa=N(()=>{"use strict";T();nn()});function sn(t){return Object.entries(t).map(([e,r])=>`${e}: ${r}`).join(`\r
421
+ `)}function Ba(t){try{return new URL(t).pathname.split("/").pop()||"index.html"}catch{return"index.html"}}function an(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 Ha=N(()=>{"use strict"});var Ua={};O(Ua,{curlCommand:()=>sd});async function ed(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}=La(t.formFields,r);return{body:n,contentType:`multipart/form-data; boundary=${s}`}}return t.data!==void 0?{body:t.data}:{}}function td(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 rd(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 nd(t,e,r){let n="";if(t.verbose){n+=`> ${t.method} ${r}
423
+ `;for(let[s,i]of Object.entries(t.headers))n+=`> ${s}: ${i}
387
424
  `;n+=`>
388
425
  `,n+=`< HTTP/1.1 ${e.status} ${e.statusText}
389
- `;for(let[s,o]of Object.entries(e.headers))n+=`< ${s}: ${o}
426
+ `;for(let[s,i]of Object.entries(e.headers))n+=`< ${s}: ${i}
390
427
  `;n+=`<
391
428
  `}return t.includeHeaders&&!t.verbose&&(n+=`HTTP/1.1 ${e.status} ${e.statusText}\r
392
- `,n+=kr(e.headers),n+=`\r
429
+ `,n+=sn(e.headers),n+=`\r
393
430
  \r
394
431
  `),t.headOnly?t.includeHeaders||t.verbose||(n+=`HTTP/1.1 ${e.status} ${e.statusText}\r
395
- `,n+=kr(e.headers),n+=`\r
396
- `):n+=e.body,t.writeOut&&(n+=Ir(t.writeOut,{status:e.status,headers:e.headers,url:e.url,bodyLength:e.body.length})),n}var Yu,xo=C(()=>{"use strict";ye();R();vr();mo();yo();bo();Yu={name:"curl",async execute(t,e){if(S(t))return x(po);let r=go(t);if("exitCode"in r)return r;let n=r;if(!n.url)return{stdout:"",stderr:`curl: no URL specified
432
+ `,n+=sn(e.headers),n+=`\r
433
+ `):n+=e.body,t.writeOut&&(n+=an(t.writeOut,{status:e.status,headers:e.headers,url:e.url,bodyLength:e.body.length})),n}var sd,za=N(()=>{"use strict";ve();T();nn();Ma();Wa();Ha();sd={name:"curl",async execute(t,e){if(C(t))return A(Fa);let r=_a(t);if("exitCode"in r)return r;let n=r;if(!n.url)return{stdout:"",stderr:`curl: no URL specified
397
434
  `,exitCode:2};if(!e.fetch)return{stdout:"",stderr:`curl: internal error: fetch not available
398
- `,exitCode:1};let s=n.url;s.match(/^https?:\/\//)||(s=`https://${s}`);try{let{body:o,contentType:i}=await Zu(n,e),a=Qu(n,i),c=await e.fetch(s,{method:n.method,headers:Object.keys(a).length>0?a:void 0,body:o,followRedirects:n.followRedirects,timeoutMs:n.timeoutMs});if(await Ku(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}
399
- `:"",exitCode:22};let l=Xu(n,c,s);if(n.outputFile||n.useRemoteName){let u=n.outputFile||wo(s),f=e.fs.resolvePath(e.cwd,u);await e.fs.writeFile(f,n.headOnly?"":c.body),n.verbose||(l=""),n.writeOut&&(l=Ir(n.writeOut,{status:c.status,headers:c.headers,url:c.url,bodyLength:c.body.length}))}return{stdout:l,stderr:"",exitCode:0}}catch(o){let i=q(o),a=1;return i.includes("Network access denied")?a=7:i.includes("HTTP method")&&i.includes("not allowed")?a=3:i.includes("Redirect target not in allow-list")||i.includes("Too many redirects")?a=47:i.includes("aborted")&&(a=28),{stdout:"",stderr:!n.silent||n.showError?`curl: (${a}) ${i}
400
- `:"",exitCode:a}}}}});import{tool as fd,zodSchema as dd}from"ai";import{z as ja}from"zod";var So=[{name:"echo",load:async()=>(await Promise.resolve().then(()=>(vn(),Nn))).echoCommand},{name:"cat",load:async()=>(await Promise.resolve().then(()=>(In(),kn))).catCommand},{name:"printf",load:async()=>(await Promise.resolve().then(()=>(On(),Rn))).printfCommand},{name:"ls",load:async()=>(await Promise.resolve().then(()=>(Fn(),Mn))).lsCommand},{name:"mkdir",load:async()=>(await Promise.resolve().then(()=>(Wn(),Ln))).mkdirCommand},{name:"touch",load:async()=>(await Promise.resolve().then(()=>(Hn(),_n))).touchCommand},{name:"rm",load:async()=>(await Promise.resolve().then(()=>(zn(),Bn))).rmCommand},{name:"cp",load:async()=>(await Promise.resolve().then(()=>(jn(),Un))).cpCommand},{name:"mv",load:async()=>(await Promise.resolve().then(()=>(Gn(),qn))).mvCommand},{name:"ln",load:async()=>(await Promise.resolve().then(()=>(Zn(),Vn))).lnCommand},{name:"chmod",load:async()=>(await Promise.resolve().then(()=>(Xn(),Kn))).chmodCommand},{name:"pwd",load:async()=>(await Promise.resolve().then(()=>(Jn(),Yn))).pwdCommand},{name:"readlink",load:async()=>(await Promise.resolve().then(()=>(ts(),es))).readlinkCommand},{name:"head",load:async()=>(await Promise.resolve().then(()=>(is(),ss))).headCommand},{name:"tail",load:async()=>(await Promise.resolve().then(()=>(as(),os))).tailCommand},{name:"wc",load:async()=>(await Promise.resolve().then(()=>(us(),cs))).wcCommand},{name:"stat",load:async()=>(await Promise.resolve().then(()=>(hs(),ds))).statCommand},{name:"grep",load:async()=>(await Promise.resolve().then(()=>(St(),xt))).grepCommand},{name:"fgrep",load:async()=>(await Promise.resolve().then(()=>(St(),xt))).fgrepCommand},{name:"egrep",load:async()=>(await Promise.resolve().then(()=>(St(),xt))).egrepCommand},{name:"sed",load:async()=>(await Promise.resolve().then(()=>(ks(),vs))).sedCommand},{name:"awk",load:async()=>(await Promise.resolve().then(()=>(ei(),Js))).awkCommand},{name:"sort",load:async()=>(await Promise.resolve().then(()=>(oi(),ii))).sortCommand},{name:"uniq",load:async()=>(await Promise.resolve().then(()=>(li(),ai))).uniqCommand},{name:"cut",load:async()=>(await Promise.resolve().then(()=>(ui(),ci))).cutCommand},{name:"paste",load:async()=>(await Promise.resolve().then(()=>(hi(),di))).pasteCommand},{name:"tr",load:async()=>(await Promise.resolve().then(()=>(gi(),mi))).trCommand},{name:"tee",load:async()=>(await Promise.resolve().then(()=>(wi(),yi))).teeCommand},{name:"find",load:async()=>(await Promise.resolve().then(()=>(Ai(),Ci))).findCommand},{name:"basename",load:async()=>(await Promise.resolve().then(()=>(Ni(),$i))).basenameCommand},{name:"dirname",load:async()=>(await Promise.resolve().then(()=>(ki(),vi))).dirnameCommand},{name:"tree",load:async()=>(await Promise.resolve().then(()=>(Ri(),Pi))).treeCommand},{name:"du",load:async()=>(await Promise.resolve().then(()=>(Ti(),Di))).duCommand},{name:"env",load:async()=>(await Promise.resolve().then(()=>(wr(),yr))).envCommand},{name:"printenv",load:async()=>(await Promise.resolve().then(()=>(wr(),yr))).printenvCommand},{name:"alias",load:async()=>(await Promise.resolve().then(()=>(Er(),br))).aliasCommand},{name:"unalias",load:async()=>(await Promise.resolve().then(()=>(Er(),br))).unaliasCommand},{name:"history",load:async()=>(await Promise.resolve().then(()=>(Li(),Fi))).historyCommand},{name:"xargs",load:async()=>(await Promise.resolve().then(()=>(_i(),Wi))).xargsCommand},{name:"true",load:async()=>(await Promise.resolve().then(()=>(Sr(),xr))).trueCommand},{name:"false",load:async()=>(await Promise.resolve().then(()=>(Sr(),xr))).falseCommand},{name:"clear",load:async()=>(await Promise.resolve().then(()=>(Bi(),Hi))).clearCommand},{name:"bash",load:async()=>(await Promise.resolve().then(()=>(Ar(),Cr))).bashCommand},{name:"sh",load:async()=>(await Promise.resolve().then(()=>(Ar(),Cr))).shCommand},{name:"jq",load:async()=>(await Promise.resolve().then(()=>(ji(),Ui))).jqCommand},{name:"base64",load:async()=>(await Promise.resolve().then(()=>(Gi(),qi))).base64Command},{name:"diff",load:async()=>(await Promise.resolve().then(()=>(Qi(),Zi))).diffCommand},{name:"date",load:async()=>(await Promise.resolve().then(()=>(Xi(),Ki))).dateCommand},{name:"sleep",load:async()=>(await Promise.resolve().then(()=>(Ji(),Yi))).sleepCommand},{name:"timeout",load:async()=>(await Promise.resolve().then(()=>(to(),eo))).timeoutCommand},{name:"seq",load:async()=>(await Promise.resolve().then(()=>(no(),ro))).seqCommand},{name:"expr",load:async()=>(await Promise.resolve().then(()=>(io(),so))).exprCommand},{name:"html-to-markdown",load:async()=>(await Promise.resolve().then(()=>(ao(),oo))).htmlToMarkdownCommand},{name:"help",load:async()=>(await Promise.resolve().then(()=>(co(),lo))).helpCommand},{name:"which",load:async()=>(await Promise.resolve().then(()=>(fo(),uo))).whichCommand}],Ju=[{name:"curl",load:async()=>(await Promise.resolve().then(()=>(xo(),Eo))).curlCommand}],Co=new Map;function Ao(t){return{name:t.name,async execute(e,r){let n=Co.get(t.name);return n||(n=await t.load(),Co.set(t.name,n)),n.execute(e,r)}}}function $o(t){return(t?So.filter(r=>t.includes(r.name)):So).map(Ao)}function No(){return Ju.map(Ao)}function vo(t){return"load"in t&&typeof t.load=="function"}function ko(t){let e=null;return{name:t.name,async execute(r,n){return e||(e=await t.load()),e.execute(r,n)}}}var ef=new TextEncoder,tf=new TextDecoder;function Pr(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 ef.encode(t)}}function Io(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 tf.decode(t)}}function kt(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var It=new TextEncoder;function rf(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var _e=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))rf(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(o=>o&&o!=="."),s=[];for(let o of n)o===".."?s.pop():s.push(o);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 o=this.normalizePath(e);this.ensureParentDirs(o);let i=kt(n),a=Pr(r,i);this.data.set(o,{type:"file",content:a,mode:s?.mode??420,mtime:s?.mtime??new Date})}async readFile(e,r){let n=await this.readFileBuffer(e),s=kt(r);return Io(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 o=new Set;for(;n&&n.type==="symlink";){if(o.has(s))throw new Error(`ELOOP: too many levels of symbolic links, open '${e}'`);o.add(s),s=this.resolveSymlink(s,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:It.encode(n.content)}async writeFile(e,r,n){this.writeFileSync(e,r,n)}async appendFile(e,r,n){let s=this.normalizePath(e),o=this.data.get(s);if(o&&o.type==="directory")throw new Error(`EISDIR: illegal operation on a directory, write '${e}'`);let i=kt(n),a=Pr(r,i);if(o?.type==="file"){let c=o.content instanceof Uint8Array?o.content:It.encode(o.content),l=new Uint8Array(c.length+a.length);l.set(c),l.set(a,c.length),this.data.set(s,{type:"file",content:l,mode:o.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 o=this.resolveSymlink(r,n.target),i=this.data.get(o);if(!i)throw new Error(`ENOENT: no such file or directory, stat '${e}'`);n=i}let s=0;return n.type==="file"&&n.content&&(n.content instanceof Uint8Array?s=n.content.length:s=It.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=It.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}/`,o=[];for(let i of this.data.keys())if(i!==r&&i.startsWith(s)){let c=i.slice(s.length).split("/")[0];c&&!o.includes(c)&&o.push(c)}return o.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 o=await this.readdir(n);if(o.length>0){if(!r?.recursive)throw new Error(`ENOTEMPTY: directory not empty, rm '${e}'`);for(let i of o){let a=n==="/"?`/${i}`:`${n}/${i}`;await this.rm(a,r)}}}this.data.delete(n)}async cp(e,r,n){let s=this.normalizePath(e),o=this.normalizePath(r),i=this.data.get(s);if(!i)throw new Error(`ENOENT: no such file or directory, cp '${e}'`);if(i.type==="file")this.ensureParentDirs(o),this.data.set(o,{...i});else if(i.type==="directory"){if(!n?.recursive)throw new Error(`EISDIR: is a directory, cp '${e}'`);await this.mkdir(o,{recursive:!0});let a=await this.readdir(s);for(let c of a){let l=s==="/"?`/${c}`:`${s}/${c}`,u=o==="/"?`/${c}`:`${o}/${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),o=this.data.get(n);if(!o)throw new Error(`ENOENT: no such file or directory, link '${e}'`);if(o.type!=="file")throw new Error(`EPERM: operation not permitted, link '${e}'`);if(this.data.has(s))throw new Error(`EEXIST: file already exists, link '${r}'`);this.ensureParentDirs(s),this.data.set(s,{type:"file",content:o.content,mode:o.mode,mtime:o.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}};Z();Z();function K(t,e){return{type:"ArithmeticExpression",expression:Ae(t,e,0).expr}}function Ae(t,e,r){return nf(t,e,r)}function nf(t,e,r){let{expr:n,pos:s}=Rt(t,e,r);for(s=G(e,s);e[s]===",";){s++;let{expr:o,pos:i}=Rt(t,e,s);n={type:"ArithBinary",operator:",",left:n,right:o},s=G(e,i)}return{expr:n,pos:s}}function Rt(t,e,r){let{expr:n,pos:s}=sf(t,e,r);if(s=G(e,s),e[s]==="?"){s++;let{expr:o,pos:i}=Ae(t,e,s);if(s=G(e,i),e[s]===":"){s++;let{expr:a,pos:c}=Ae(t,e,s);return{expr:{type:"ArithTernary",condition:n,consequent:o,alternate:a},pos:c}}}return{expr:n,pos:s}}function sf(t,e,r){let{expr:n,pos:s}=Po(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:o,pos:i}=Po(t,e,s);n={type:"ArithBinary",operator:"||",left:n,right:o},s=i}return{expr:n,pos:s}}function Po(t,e,r){let{expr:n,pos:s}=Ro(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="&&";){s+=2;let{expr:o,pos:i}=Ro(t,e,s);n={type:"ArithBinary",operator:"&&",left:n,right:o},s=i}return{expr:n,pos:s}}function Ro(t,e,r){let{expr:n,pos:s}=Oo(t,e,r);for(;s=G(e,s),e[s]==="|"&&e[s+1]!=="|";){s++;let{expr:o,pos:i}=Oo(t,e,s);n={type:"ArithBinary",operator:"|",left:n,right:o},s=i}return{expr:n,pos:s}}function Oo(t,e,r){let{expr:n,pos:s}=Do(t,e,r);for(;s=G(e,s),e[s]==="^";){s++;let{expr:o,pos:i}=Do(t,e,s);n={type:"ArithBinary",operator:"^",left:n,right:o},s=i}return{expr:n,pos:s}}function Do(t,e,r){let{expr:n,pos:s}=To(t,e,r);for(;s=G(e,s),e[s]==="&"&&e[s+1]!=="&";){s++;let{expr:o,pos:i}=To(t,e,s);n={type:"ArithBinary",operator:"&",left:n,right:o},s=i}return{expr:n,pos:s}}function To(t,e,r){let{expr:n,pos:s}=Mo(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Mo(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}return{expr:n,pos:s}}function Mo(t,e,r){let{expr:n,pos:s}=Rr(t,e,r);for(;;)if(s=G(e,s),e.slice(s,s+2)==="<="||e.slice(s,s+2)===">="){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Rr(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}else if(e[s]==="<"||e[s]===">"){let o=e[s];s++;let{expr:i,pos:a}=Rr(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}else break;return{expr:n,pos:s}}function Rr(t,e,r){let{expr:n,pos:s}=Fo(t,e,r);for(;s=G(e,s),e.slice(s,s+2)==="<<"||e.slice(s,s+2)===">>";){let o=e.slice(s,s+2);s+=2;let{expr:i,pos:a}=Fo(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}return{expr:n,pos:s}}function Fo(t,e,r){let{expr:n,pos:s}=Lo(t,e,r);for(;s=G(e,s),(e[s]==="+"||e[s]==="-")&&e[s+1]!==e[s];){let o=e[s];s++;let{expr:i,pos:a}=Lo(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}return{expr:n,pos:s}}function Lo(t,e,r){let{expr:n,pos:s}=Pt(t,e,r);for(;;)if(s=G(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:o,pos:i}=Pt(t,e,s);n={type:"ArithBinary",operator:"*",left:n,right:o},s=i}else if(e[s]==="/"||e[s]==="%"){let o=e[s];s++;let{expr:i,pos:a}=Pt(t,e,s);n={type:"ArithBinary",operator:o,left:n,right:i},s=a}else break;return{expr:n,pos:s}}function Pt(t,e,r){let{expr:n,pos:s}=Or(t,e,r),o=G(e,s);if(e.slice(o,o+2)==="**"){o+=2;let{expr:i,pos:a}=Pt(t,e,o);return{expr:{type:"ArithBinary",operator:"**",left:n,right:i},pos:a}}return{expr:n,pos:s}}function Or(t,e,r){let n=G(e,r);if(e.slice(n,n+2)==="++"||e.slice(n,n+2)==="--"){let s=e.slice(n,n+2);n+=2;let{expr:o,pos:i}=Or(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}if(e[n]==="+"||e[n]==="-"||e[n]==="!"||e[n]==="~"){let s=e[n];n++;let{expr:o,pos:i}=Or(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:o,prefix:!0},pos:i}}return af(t,e,n)}function of(t,e){let r=t[e];return r==="$"||r==="`"}function af(t,e,r){let{expr:n,pos:s}=Wo(t,e,r),o=[n];for(;of(e,s);){let{expr:i,pos:a}=Wo(t,e,s);o.push(i),s=a}if(o.length>1&&(n={type:"ArithConcat",parts:o}),s=G(e,s),e.slice(s,s+2)==="++"||e.slice(s,s+2)==="--"){let i=e.slice(s,s+2);return s+=2,{expr:{type:"ArithUnary",operator:i,operand:n,prefix:!1},pos:s}}return{expr:n,pos:s}}function Wo(t,e,r){let n=G(e,r);if(e.slice(n,n+3)==="$(("){n+=3;let s=1,o=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 i=e.slice(o,n),{expr:a}=Ae(t,i,0);return n+=2,{expr:{type:"ArithNested",expression:a},pos:n}}if(e.slice(n,n+2)==="$("&&e[n+2]!=="("){n+=2;let s=1,o=n;for(;n<e.length&&s>0;)e[n]==="("?s++:e[n]===")"&&s--,s>0&&n++;let i=e.slice(o,n);return n++,{expr:{type:"ArithCommandSubst",command:i},pos:n}}if(e[n]==="`"){n++;let s=n;for(;n<e.length&&e[n]!=="`";)n++;let o=e.slice(s,n);return e[n]==="`"&&n++,{expr:{type:"ArithCommandSubst",command:o},pos:n}}if(e[n]==="("){n++;let{expr:s,pos:o}=Ae(t,e,n);return n=G(e,o),e[n]===")"&&n++,{expr:{type:"ArithGroup",expression:s},pos:n}}if(/[0-9]/.test(e[n])){let s="",o=!1;for(;n<e.length;){let a=e[n];if(o)if(/[0-9a-zA-Z@_]/.test(a))s+=a,n++;else break;else if(a==="#")o=!0,s+=a,n++;else if(/[0-9a-fA-FxX]/.test(a))s+=a,n++;else break}if(e[n]==="."&&/[0-9]/.test(e[n+1]))throw new V(`${s}.${e[n+1]}...: syntax error: invalid arithmetic operator`);if(e[n]==="["){let a=e.slice(n).trim();return{expr:{type:"ArithNumberSubscript",number:s,errorToken:a},pos:e.length}}return{expr:{type:"ArithNumber",value:Ze(s)},pos:n}}if(e[n]==="$"&&e[n+1]==="{"){let s=n+2,o=1,i=s;for(;i<e.length&&o>0;)e[i]==="{"?o++:e[i]==="}"&&o--,o>0&&i++;let a=e.slice(s,i),c=i+1;if(e[c]==="#"){let l=c+1;for(;l<e.length&&/[0-9a-zA-Z@_]/.test(e[l]);)l++;let u=e.slice(c+1,l);return{expr:{type:"ArithDynamicBase",baseExpr:a,value:u},pos:l}}if(/[0-9]/.test(e[c])||e[c]==="x"||e[c]==="X"){let l=c;if(e[c]==="x"||e[c]==="X")for(l++;l<e.length&&/[0-9a-fA-F]/.test(e[l]);)l++;else for(;l<e.length&&/[0-9]/.test(e[l]);)l++;let u=e.slice(c,l);return{expr:{type:"ArithDynamicNumber",prefix:a,suffix:u},pos:l}}return n=c,{expr:{type:"ArithBracedExpansion",content:a},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 i;if(e[n]==="'"||e[n]==='"'){let l=e[n];for(n++,i="";n<e.length&&e[n]!==l;)i+=e[n],n++;e[n]===l&&n++,n=G(e,n),e[n]==="]"&&n++}let a;if(i===void 0){let{expr:l,pos:u}=Ae(t,e,n);a=l,n=u,e[n]==="]"&&n++}if(n=G(e,n),e[n]==="["&&a)return{expr:{type:"ArithDoubleSubscript",array:s,index:a},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}=Rt(t,e,n);return{expr:{type:"ArithAssignment",operator:l,variable:s,subscript:a,stringKey:i,value:u},pos:f}}return{expr:{type:"ArithArrayElement",array:s,index:a,stringKey:i},pos:n}}n=G(e,n);let o=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let i of o)if(e.slice(n,n+i.length)===i&&e.slice(n,n+i.length+1)!=="=="){n+=i.length;let{expr:a,pos:c}=Rt(t,e,n);return{expr:{type:"ArithAssignment",operator:i,variable:s,value:a},pos:c}}return{expr:{type:"ArithVariable",name:s},pos:n}}return{expr:{type:"ArithNumber",value:0},pos:n}}function Ze(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 o of r){let i;if(o>="0"&&o<="9")i=o.charCodeAt(0)-48;else if(o>="a"&&o<="z")i=o.charCodeAt(0)-97+10;else if(o>="A"&&o<="Z")i=o.charCodeAt(0)-65+36;else if(o==="@")i=62;else if(o==="_")i=63;else return Number.NaN;if(i>=n)return Number.NaN;s=s*n+i}return s}return t.startsWith("0x")||t.startsWith("0X")?Number.parseInt(t.slice(2),16):t.startsWith("0")&&t.length>1&&/^[0-9]+$/.test(t)?/[89]/.test(t)?Number.NaN:Number.parseInt(t,8):Number.parseInt(t,10)}function G(t,e){for(;e<t.length;){if(t[e]==="\\"&&t[e+1]===`
401
- `){e+=2;continue}if(/\s/.test(t[e])){e++;continue}break}return e}var N={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 Ot={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 Ho(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 o=r.slice(s+1);return o===""||o==="+"}return!1}var lf=[[";",";","&",m.SEMI_SEMI_AND],["<","<","<",m.TLESS],["&",">",">",m.AND_DGREAT]],cf=[["[","[",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]],uf={"|":m.PIPE,"&":m.AMP,";":m.SEMICOLON,"(":m.LPAREN,")":m.RPAREN,"<":m.LESS,">":m.GREAT};function ff(t){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)}var Dt=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 o=this.nextToken();o&&n.push(o)}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,o=this.line;for(;n<r;){let i=e[n];if(i===" "||i===" ")n++,s++;else if(i==="\\"&&e[n+1]===`
402
- `)n+=2,o++,s=1;else break}this.pos=n,this.column=s,this.line=o}nextToken(){let e=this.input,r=this.pos,n=this.line,s=this.column,o=e[r],i=e[r+1],a=e[r+2];if(o==="#")return this.readComment(r,n,s);if(o===`
435
+ `,exitCode:1};let s=n.url;s.match(/^https?:\/\//)||(s=`https://${s}`);try{let{body:i,contentType:a}=await ed(n,e),o=td(n,a),l=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 rd(n,l.headers,e),n.failSilently&&l.status>=400)return{stdout:"",stderr:n.showError||!n.silent?`curl: (22) The requested URL returned error: ${l.status}
436
+ `:"",exitCode:22};let c=nd(n,l,s);if(n.outputFile||n.useRemoteName){let u=n.outputFile||Ba(s),f=e.fs.resolvePath(e.cwd,u);await e.fs.writeFile(f,n.headOnly?"":l.body),n.verbose||(c=""),n.writeOut&&(c=an(n.writeOut,{status:l.status,headers:l.headers,url:l.url,bodyLength:l.body.length}))}return{stdout:c,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 yh,zodSchema as gh}from"ai";import{z as hl}from"zod";var Ga=[{name:"echo",load:async()=>(await Promise.resolve().then(()=>(ns(),rs))).echoCommand},{name:"cat",load:async()=>(await Promise.resolve().then(()=>(is(),ss))).catCommand},{name:"printf",load:async()=>(await Promise.resolve().then(()=>(ls(),os))).printfCommand},{name:"ls",load:async()=>(await Promise.resolve().then(()=>(ds(),fs))).lsCommand},{name:"mkdir",load:async()=>(await Promise.resolve().then(()=>(ps(),hs))).mkdirCommand},{name:"touch",load:async()=>(await Promise.resolve().then(()=>(ys(),ms))).touchCommand},{name:"rm",load:async()=>(await Promise.resolve().then(()=>(ws(),gs))).rmCommand},{name:"cp",load:async()=>(await Promise.resolve().then(()=>(bs(),Es))).cpCommand},{name:"mv",load:async()=>(await Promise.resolve().then(()=>(Ss(),xs))).mvCommand},{name:"ln",load:async()=>(await Promise.resolve().then(()=>(Cs(),As))).lnCommand},{name:"chmod",load:async()=>(await Promise.resolve().then(()=>(ks(),vs))).chmodCommand},{name:"pwd",load:async()=>(await Promise.resolve().then(()=>(Rs(),Is))).pwdCommand},{name:"readlink",load:async()=>(await Promise.resolve().then(()=>(Ps(),$s))).readlinkCommand},{name:"head",load:async()=>(await Promise.resolve().then(()=>(Ls(),Ts))).headCommand},{name:"tail",load:async()=>(await Promise.resolve().then(()=>(Ms(),Fs))).tailCommand},{name:"wc",load:async()=>(await Promise.resolve().then(()=>(Bs(),Ws))).wcCommand},{name:"stat",load:async()=>(await Promise.resolve().then(()=>(zs(),Us))).statCommand},{name:"grep",load:async()=>(await Promise.resolve().then(()=>(Ht(),Bt))).grepCommand},{name:"fgrep",load:async()=>(await Promise.resolve().then(()=>(Ht(),Bt))).fgrepCommand},{name:"egrep",load:async()=>(await Promise.resolve().then(()=>(Ht(),Bt))).egrepCommand},{name:"sed",load:async()=>(await Promise.resolve().then(()=>(ei(),Js))).sedCommand},{name:"awk",load:async()=>(await Promise.resolve().then(()=>(Ai(),Si))).awkCommand2},{name:"sort",load:async()=>(await Promise.resolve().then(()=>(Ri(),Ii))).sortCommand},{name:"uniq",load:async()=>(await Promise.resolve().then(()=>(Pi(),$i))).uniqCommand},{name:"cut",load:async()=>(await Promise.resolve().then(()=>(Di(),Oi))).cutCommand},{name:"paste",load:async()=>(await Promise.resolve().then(()=>(Fi(),Li))).pasteCommand},{name:"tr",load:async()=>(await Promise.resolve().then(()=>(Wi(),_i))).trCommand},{name:"tee",load:async()=>(await Promise.resolve().then(()=>(Hi(),Bi))).teeCommand},{name:"find",load:async()=>(await Promise.resolve().then(()=>(Vi(),qi))).findCommand},{name:"basename",load:async()=>(await Promise.resolve().then(()=>(Qi(),Zi))).basenameCommand},{name:"dirname",load:async()=>(await Promise.resolve().then(()=>(Xi(),Ki))).dirnameCommand},{name:"tree",load:async()=>(await Promise.resolve().then(()=>(ea(),Ji))).treeCommand},{name:"du",load:async()=>(await Promise.resolve().then(()=>(na(),ra))).duCommand},{name:"env",load:async()=>(await Promise.resolve().then(()=>(Zr(),Vr))).envCommand},{name:"printenv",load:async()=>(await Promise.resolve().then(()=>(Zr(),Vr))).printenvCommand},{name:"alias",load:async()=>(await Promise.resolve().then(()=>(Kr(),Qr))).aliasCommand},{name:"unalias",load:async()=>(await Promise.resolve().then(()=>(Kr(),Qr))).unaliasCommand},{name:"history",load:async()=>(await Promise.resolve().then(()=>(aa(),ia))).historyCommand},{name:"xargs",load:async()=>(await Promise.resolve().then(()=>(la(),oa))).xargsCommand},{name:"true",load:async()=>(await Promise.resolve().then(()=>(Yr(),Xr))).trueCommand},{name:"false",load:async()=>(await Promise.resolve().then(()=>(Yr(),Xr))).falseCommand},{name:"clear",load:async()=>(await Promise.resolve().then(()=>(ua(),ca))).clearCommand},{name:"bash",load:async()=>(await Promise.resolve().then(()=>(en(),Jr))).bashCommand},{name:"sh",load:async()=>(await Promise.resolve().then(()=>(en(),Jr))).shCommand},{name:"jq",load:async()=>(await Promise.resolve().then(()=>(ha(),da))).jqCommand},{name:"base64",load:async()=>(await Promise.resolve().then(()=>(ma(),pa))).base64Command},{name:"diff",load:async()=>(await Promise.resolve().then(()=>(wa(),ga))).diffCommand},{name:"date",load:async()=>(await Promise.resolve().then(()=>(ba(),Ea))).dateCommand},{name:"sleep",load:async()=>(await Promise.resolve().then(()=>(Sa(),xa))).sleepCommand},{name:"timeout",load:async()=>(await Promise.resolve().then(()=>(Ca(),Aa))).timeoutCommand},{name:"seq",load:async()=>(await Promise.resolve().then(()=>(va(),Na))).seqCommand},{name:"expr",load:async()=>(await Promise.resolve().then(()=>(Ia(),ka))).exprCommand},{name:"html-to-markdown",load:async()=>(await Promise.resolve().then(()=>($a(),Ra))).htmlToMarkdownCommand},{name:"help",load:async()=>(await Promise.resolve().then(()=>(Oa(),Pa))).helpCommand},{name:"which",load:async()=>(await Promise.resolve().then(()=>(Ta(),Da))).whichCommand}],id=[{name:"curl",load:async()=>(await Promise.resolve().then(()=>(za(),Ua))).curlCommand}],ja=new Map;function qa(t){return{name:t.name,async execute(e,r){let n=ja.get(t.name);return n||(n=await t.load(),ja.set(t.name,n)),n.execute(e,r)}}}function Va(t){return(t?Ga.filter(r=>t.includes(r.name)):Ga).map(qa)}function Za(){return id.map(qa)}function Qa(t){return"load"in t&&typeof t.load=="function"}function Ka(t){let e=null;return{name:t.name,async execute(r,n){return e||(e=await t.load()),e.execute(r,n)}}}var ad=new TextEncoder,od=new TextDecoder;function on(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 ad.encode(t)}}function Xa(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 od.decode(t)}}function Xt(t){if(t!=null)return typeof t=="string"?t:t.encoding??void 0}var Yt=new TextEncoder;function ld(t){return typeof t=="object"&&t!==null&&!(t instanceof Uint8Array)&&"content"in t}var Je=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))ld(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=Xt(n),o=on(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=Xt(r);return Xa(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:Yt.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=Xt(n),o=on(r,a);if(i?.type==="file"){let l=i.content instanceof Uint8Array?i.content:Yt.encode(i.content),c=new Uint8Array(l.length+o.length);c.set(l),c.set(o,l.length),this.data.set(s,{type:"file",content:c,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=Yt.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=Yt.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 l=a.slice(s.length).split("/")[0];l&&!i.includes(l)&&i.push(l)}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 l of o){let c=s==="/"?`/${l}`:`${s}/${l}`,u=i==="/"?`/${l}`:`${i}/${l}`;await this.cp(c,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:De(t,e,0).expr}}function De(t,e,r){return cd(t,e,r)}function cd(t,e,r){let{expr:n,pos:s}=er(t,e,r);for(s=J(e,s);e[s]===",";){s++;let{expr:i,pos:a}=er(t,e,s);n={type:"ArithBinary",operator:",",left:n,right:i},s=J(e,a)}return{expr:n,pos:s}}function er(t,e,r){let{expr:n,pos:s}=ud(t,e,r);if(s=J(e,s),e[s]==="?"){s++;let{expr:i,pos:a}=De(t,e,s);if(s=J(e,a),e[s]===":"){s++;let{expr:o,pos:l}=De(t,e,s);return{expr:{type:"ArithTernary",condition:n,consequent:i,alternate:o},pos:l}}}return{expr:n,pos:s}}function ud(t,e,r){let{expr:n,pos:s}=Ya(t,e,r);for(;s=J(e,s),e.slice(s,s+2)==="||";){s+=2;let{expr:i,pos:a}=Ya(t,e,s);n={type:"ArithBinary",operator:"||",left:n,right:i},s=a}return{expr:n,pos:s}}function Ya(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[s]==="|"&&e[s+1]!=="|";){s++;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]==="^";){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]==="&"&&e[s+1]!=="&";){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.slice(s,s+2)==="=="||e.slice(s,s+2)==="!=";){let i=e.slice(s,s+2);s+=2;let{expr:a,pos:o}=no(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}return{expr:n,pos:s}}function no(t,e,r){let{expr:n,pos:s}=ln(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}=ln(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}=ln(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}else break;return{expr:n,pos:s}}function ln(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}=io(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}=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}=Jt(t,e,r);for(;;)if(s=J(e,s),e[s]==="*"&&e[s+1]!=="*"){s++;let{expr:i,pos:a}=Jt(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}=Jt(t,e,s);n={type:"ArithBinary",operator:i,left:n,right:a},s=o}else break;return{expr:n,pos:s}}function Jt(t,e,r){let{expr:n,pos:s}=cn(t,e,r),i=J(e,s);if(e.slice(i,i+2)==="**"){i+=2;let{expr:a,pos:o}=Jt(t,e,i);return{expr:{type:"ArithBinary",operator:"**",left:n,right:a},pos:o}}return{expr:n,pos:s}}function cn(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}=cn(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}=cn(t,e,n);return{expr:{type:"ArithUnary",operator:s,operand:i,prefix:!0},pos:a}}return dd(t,e,n)}function fd(t,e){let r=t[e];return r==="$"||r==="`"}function dd(t,e,r){let{expr:n,pos:s}=ao(t,e,r),i=[n];for(;fd(e,s);){let{expr:a,pos:o}=ao(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 ao(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}=De(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}=De(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:ft(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),l=a+1;if(e[l]==="#"){let c=l+1;for(;c<e.length&&/[0-9a-zA-Z@_]/.test(e[c]);)c++;let u=e.slice(l+1,c);return{expr:{type:"ArithDynamicBase",baseExpr:o,value:u},pos:c}}if(/[0-9]/.test(e[l])||e[l]==="x"||e[l]==="X"){let c=l;if(e[l]==="x"||e[l]==="X")for(c++;c<e.length&&/[0-9a-fA-F]/.test(e[c]);)c++;else for(;c<e.length&&/[0-9]/.test(e[c]);)c++;let u=e.slice(l,c);return{expr:{type:"ArithDynamicNumber",prefix:o,suffix:u},pos:c}}return n=l,{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 c=e[n];for(n++,a="";n<e.length&&e[n]!==c;)a+=e[n],n++;e[n]===c&&n++,n=J(e,n),e[n]==="]"&&n++}let o;if(a===void 0){let{expr:c,pos:u}=De(t,e,n);o=c,n=u,e[n]==="]"&&n++}if(n=J(e,n),e[n]==="["&&o)return{expr:{type:"ArithDoubleSubscript",array:s,index:o},pos:n};let l=["=","+=","-=","*=","/=","%=","<<=",">>=","&=","|=","^="];for(let c of l)if(e.slice(n,n+c.length)===c&&e.slice(n,n+c.length+1)!=="=="){n+=c.length;let{expr:u,pos:f}=er(t,e,n);return{expr:{type:"ArithAssignment",operator:c,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:l}=er(t,e,n);return{expr:{type:"ArithAssignment",operator:a,variable:s,value:o},pos:l}}return{expr:{type:"ArithVariable",name:s},pos:n}}return{expr:{type:"ArithNumber",value:0},pos:n}}function ft(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 tr={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 lo(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 hd=[[";",";","&",m.SEMI_SEMI_AND],["<","<","<",m.TLESS],["&",">",">",m.AND_DGREAT]],pd=[["[","[",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]],md={"|":m.PIPE,"&":m.AMP,";":m.SEMICOLON,"(":m.LPAREN,")":m.RPAREN,"<":m.LESS,">":m.GREAT};function yd(t){return/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(t)}var rr=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
+ `)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===`
403
440
  `)return this.pos=r+1,this.line++,this.column=1,{type:m.NEWLINE,value:`
404
- `,start:r,end:r+1,line:n,column:s};if(o==="<"&&i==="<"&&a==="-")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 lf)if(o===l&&i===u&&a===f)return this.pos=r+3,this.column=s+3,this.makeToken(d,l+u+f,r,n,s);if(o==="<"&&i==="<")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 cf)if(o===l&&i===u)return this.pos=r+2,this.column=s+2,this.makeToken(f,l+u,r,n,s);let c=uf[o];return c?(this.pos=r+1,this.column=s+1,this.makeToken(c,o,r,n,s)):o==="{"?i==="}"?(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):i!==void 0&&i!==" "&&i!==" "&&i!==`
405
- `?this.readWord(r,n,s):(this.pos=r+1,this.column=s+1,this.makeToken(m.LBRACE,"{",r,n,s)):o==="}"?this.isWordCharFollowing(r+1)?this.readWord(r,n,s):(this.pos=r+1,this.column=s+1,this.makeToken(m.RBRACE,"}",r,n,s)):o==="!"?i==="="?(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,o){return{type:e,value:r,start:n,end:this.pos,line:s,column:o}}readComment(e,r,n){let s=this.input,o=s.length,i=this.pos;for(;i<o&&s[i]!==`
406
- `;)i++;let a=s.slice(e,i);return this.pos=i,this.column=n+(i-e),{type:m.COMMENT,value:a,start:e,end:i,line:r,column:n}}readWord(e,r,n){let s=this.input,o=s.length,i=this.pos,a=i;for(;i<o;){let g=s[i];if(g===" "||g===" "||g===`
407
- `||g===";"||g==="&"||g==="|"||g==="("||g===")"||g==="<"||g===">"||g==="'"||g==='"'||g==="\\"||g==="$"||g==="`"||g==="{"||g==="}"||g==="~"||g==="*"||g==="?"||g==="[")break;i++}if(i>a){let g=s[i];if(i>=o||g===" "||g===" "||g===`
408
- `||g===";"||g==="&"||g==="|"||g==="("||g===")"||g==="<"||g===">"){let y=s.slice(a,i);if(this.pos=i,this.column=n+(i-a),Ot[y])return{type:Ot[y],value:y,start:e,end:i,line:r,column:n};let w=y.indexOf("=");return w>0&&Ho(y.slice(0,w))?{type:m.ASSIGNMENT_WORD,value:y,start:e,end:i,line:r,column:n}:/^[0-9]+$/.test(y)?{type:m.NUMBER,value:y,start:e,end:i,line:r,column:n}:/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(y)?{type:m.NAME,value:y,start:e,end:i,line:r,column:n,quoted:!1,singleQuoted:!1}:{type:m.WORD,value:y,start:e,end:i,line:r,column:n,quoted:!1,singleQuoted:!1}}}i=this.pos;let c=this.column,l=this.line,u="",f=!1,d=!1,h=!1,p=!1,b=s[i]==='"'||s[i]==="'";for(;i<o;){let g=s[i];if(!h&&!p&&(g===" "||g===" "||g===`
409
- `||g===";"||g==="&"||g==="|"||g==="("||g===")"||g==="<"||g===">"))break;if(g==="$"&&i+1<o&&s[i+1]==="'"&&!h&&!p){for(u+="$'",i+=2,c+=2;i<o&&s[i]!=="'";)s[i]==="\\"&&i+1<o?(u+=s[i]+s[i+1],i+=2,c+=2):(u+=s[i],i++,c++);i<o&&(u+="'",i++,c++);continue}if(g==="$"&&i+1<o&&s[i+1]==='"'&&!h&&!p){i++,c++,p=!0,f=!0,u===""&&(b=!0),i++,c++;continue}if(g==="'"&&!p){h?(h=!1,b||(u+=g)):(h=!0,b?(d=!0,f=!0):u+=g),i++,c++;continue}if(g==='"'&&!h){p?(p=!1,b||(u+=g)):(p=!0,b?f=!0:u+=g),i++,c++;continue}if(g==="\\"&&!h&&i+1<o){let y=s[i+1];if(y===`
410
- `){i+=2,l++,c=1;continue}if(p){if(y==='"'||y==="\\"||y==="$"||y==="`"||y===`
411
- `){y==="$"||y==="`"?u+=g+y:u+=y,i+=2,c+=2;continue}}else{y==='"'||y==="'"?u+=g+y:u+=y,i+=2,c+=2;continue}}if(g==="$"&&i+1<o&&s[i+1]==="("){u+=g,i++,c++,u+=s[i],i++,c++;let y=1,w=!1,E=!1,$=0,A=!1,P="",J=s[i]==="(";for(;y>0&&i<o;){let L=s[i];if(u+=L,w)L==="'"&&(w=!1);else if(E)L==="\\"&&i+1<o?(u+=s[i+1],i++,c++):L==='"'&&(E=!1);else if(L==="'")w=!0,P="";else if(L==='"')E=!0,P="";else if(L==="\\"&&i+1<o)u+=s[i+1],i++,c++,P="";else if(L==="#"&&!J&&(P===""||/\s/.test(s[i-1]||""))){for(;i+1<o&&s[i+1]!==`
412
- `;)i++,c++,u+=s[i];P=""}else/[a-zA-Z_]/.test(L)?P+=L:(P==="case"?($++,A=!1):P==="in"&&$>0?A=!0:P==="esac"&&$>0&&($--,A=!1),P="",L==="("?i>0&&s[i-1]==="$"?y++:A||y++:L===")"?A?A=!1:y--:L===";"&&$>0&&i+1<o&&s[i+1]===";"&&(A=!0));L===`
413
- `&&(l++,c=0,P=""),i++,c++}continue}if(g==="$"&&i+1<o&&s[i+1]==="["){u+=g,i++,c++,u+=s[i],i++,c++;let y=1;for(;y>0&&i<o;){let w=s[i];u+=w,w==="["?y++:w==="]"?y--:w===`
414
- `&&(l++,c=0),i++,c++}continue}if(g==="$"&&i+1<o&&s[i+1]==="{"){u+=g,i++,c++,u+=s[i],i++,c++;let y=1;for(;y>0&&i<o;){let w=s[i];u+=w,w==="{"?y++:w==="}"?y--:w===`
415
- `&&(l++,c=0),i++,c++}continue}if(g==="$"&&i+1<o){let y=s[i+1];if(y==="#"||y==="?"||y==="$"||y==="!"||y==="@"||y==="*"||y==="-"||y>="0"&&y<="9"){u+=g+y,i+=2,c+=2;continue}}if(g==="`"){for(u+=g,i++,c++;i<o&&s[i]!=="`";){let y=s[i];u+=y,y==="\\"&&i+1<o&&(u+=s[i+1],i++,c++),y===`
416
- `&&(l++,c=0),i++,c++}i<o&&(u+=s[i],i++,c++);continue}u+=g,i++,g===`
417
- `?(l++,c=1):c++}if(this.pos=i,this.column=c,this.line=l,u==="")return{type:m.WORD,value:"",start:e,end:i,line:r,column:n,quoted:f,singleQuoted:d};if(!f&&Ot[u])return{type:Ot[u],value:u,start:e,end:i,line:r,column:n};if(!b){let g=u.indexOf("=");if(g>0&&Ho(u.slice(0,g)))return{type:m.ASSIGNMENT_WORD,value:u,start:e,end:i,line:r,column:n,quoted:f,singleQuoted:d}}return/^[0-9]+$/.test(u)?{type:m.NUMBER,value:u,start:e,end:i,line:r,column:n}:ff(u)?{type:m.NAME,value:u,start:e,end:i,line:r,column:n,quoted:f,singleQuoted:d}:{type:m.WORD,value:u,start:e,end:i,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,o="";for(;this.pos<this.input.length;){let i=this.pos,a="";for(;this.pos<this.input.length&&this.input[this.pos]!==`
418
- `;)a+=this.input[this.pos],this.pos++,this.column++;if((e.stripTabs?a.replace(/^\t+/,""):a)===e.delimiter){this.pos<this.input.length&&this.input[this.pos]===`
419
- `&&(this.pos++,this.line++,this.column=1);break}o+=a,this.pos<this.input.length&&this.input[this.pos]===`
420
- `&&(o+=`
421
- `,this.pos++,this.line++,this.column=1)}this.tokens.push({type:m.HEREDOC_CONTENT,value:o,start:r,end:this.pos,line:n,column:s})}}addPendingHeredoc(e,r,n){this.pendingHeredocs.push({delimiter:e,stripTabs:r,quoted:n})}registerHeredocFromLookahead(e){let r=this.pos,n=this.column;for(;this.pos<this.input.length&&(this.input[this.pos]===" "||this.input[this.pos]===" ");)this.pos++,this.column++;let s="",o=!1,i=this.input[this.pos];if(i==="'"||i==='"'){o=!0;let a=i;for(this.pos++,this.column++;this.pos<this.input.length&&this.input[this.pos]!==a;)s+=this.input[this.pos],this.pos++,this.column++}else for(;this.pos<this.input.length&&!/[\s;<>&|()]/.test(this.input[this.pos]);)s+=this.input[this.pos],this.pos++,this.column++;this.pos=r,this.column=n,s&&this.pendingHeredocs.push({delimiter:s,stripTabs:e,quoted:o})}isWordCharFollowing(e){if(e>=this.input.length)return!1;let r=this.input[e];return!(r===" "||r===" "||r===`
422
- `||r===";"||r==="&"||r==="|"||r==="("||r===")"||r==="<"||r===">")}readWordWithBraceExpansion(e,r,n){let s=this.input,o=s.length,i=e,a=n;for(;i<o;){let l=s[i];if(l===" "||l===" "||l===`
423
- `||l===";"||l==="&"||l==="|"||l==="("||l===")"||l==="<"||l===">")break;if(l==="{"){if(this.scanBraceExpansion(i)!==null){let f=1;for(i++,a++;i<o&&f>0;)s[i]==="{"?f++:s[i]==="}"&&f--,i++,a++;continue}i++,a++;continue}if(l==="}"){i++,a++;continue}if(l==="$"&&i+1<o&&s[i+1]==="("){i++,a++,i++,a++;let u=1;for(;u>0&&i<o;)s[i]==="("?u++:s[i]===")"&&u--,i++,a++;continue}if(l==="$"&&i+1<o&&s[i+1]==="{"){i++,a++,i++,a++;let u=1;for(;u>0&&i<o;)s[i]==="{"?u++:s[i]==="}"&&u--,i++,a++;continue}if(l==="`"){for(i++,a++;i<o&&s[i]!=="`";)s[i]==="\\"&&i+1<o?(i+=2,a+=2):(i++,a++);i<o&&(i++,a++);continue}i++,a++}let c=s.slice(e,i);return this.pos=i,this.column=a,{type:m.WORD,value:c,start:e,end:i,line:r,column:n,quoted:!1,singleQuoted:!1}}scanBraceExpansion(e){let r=this.input,n=r.length,s=e+1,o=1,i=!1,a=!1;for(;s<n&&o>0;){let c=r[s];if(c==="{")o++,s++;else if(c==="}")o--,s++;else if(c===","&&o===1)i=!0,s++;else if(c==="."&&s+1<n&&r[s+1]===".")a=!0,s+=2;else{if(c===" "||c===" "||c===`
424
- `||c===";"||c==="&"||c==="|")return null;s++}}return o===0&&(i||a)?r.slice(e,s):null}scanLiteralBraceWord(e){let r=this.input,n=r.length,s=e+1,o=1;for(;s<n&&o>0;){let i=r[s];if(i==="{")o++,s++;else if(i==="}"){if(o--,o===0)return r.slice(e,s+1);s++}else{if(i===" "||i===" "||i===`
425
- `||i===";"||i==="&"||i==="|")return null;s++}}return null}};var Dr=1e6,Tr=1e5,Bo=1e6,zo=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]),Uo=new Set([m.LESS,m.GREAT,m.DLESS,m.DGREAT,m.LESSAND,m.GREATAND,m.LESSGREAT,m.DLESSDASH,m.CLOBBER,m.TLESS]),$e=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 qo(t,e,r){let n=r+1;for(;n<e.length&&/[a-zA-Z0-9_-]/.test(e[n]);)n++;return n}function Mr(t,e,r,n,s){let o=1,i=r+1;for(;i<e.length&&o>0;)e[i]===n?o++:e[i]===s&&o--,o>0&&i++;return o===0?i:-1}function He(t,e,r){let n=r,s=1;for(;n<e.length&&s>0;){let o=e[n];if(o==="\\"&&n+1<e.length){n+=2;continue}if(o==="'"){let i=e.indexOf("'",n+1);if(i!==-1){n=i+1;continue}}if(o==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?n+=2:n++;n<e.length&&n++;continue}o==="{"?s++:o==="}"&&s--,s>0&&n++}return n}function Go(t,e,r){let n=r,s=!1;for(;n<e.length;){let o=e[n];if(o==="/"&&s||o==="}")break;if(o==="'"){let i=e.indexOf("'",n+1);if(i!==-1){n=i+1,s=!0;continue}}if(o==='"'){for(n++;n<e.length&&e[n]!=='"';)e[n]==="\\"&&n+1<e.length?n+=2:n++;n<e.length&&n++,s=!0;continue}o==="\\"?(n+=2,s=!0):(n++,s=!0)}return n}function Vo(t,e,r){let n=r,s="";for(;n<e.length;){let o=e[n];if(o==="*"||o==="?")s+=o,n++;else if(o==="["){let i=df(e,n);i===-1?(s+=o,n++):(s+=e.slice(n,i+1),n=i+1)}else break}return{pattern:s,endIndex:n}}function df(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 o=`${t[r+1]}]`,i=t.indexOf(o,r+2);if(i!==-1){r=i+2;continue}}r++}return-1}function Zo(t,e,r){let n="",s=r;for(;s<e.length&&e[s]!=="'";){let o=e[s];if(o==="\\"&&s+1<e.length)switch(e[s+1]){case"n":n+=`
426
- `,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 a=e.slice(s+2,s+4),c=parseInt(a,16);Number.isNaN(c)?(n+="\\x",s+=2):(n+=String.fromCharCode(c),s+=4);break}case"u":{let a=e.slice(s+2,s+6),c=parseInt(a,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 a="",c=s+1;for(;c<e.length&&c<s+4&&/[0-7]/.test(e[c]);)a+=e[c],c++;let l=parseInt(a,8);n+=String.fromCharCode(l),s=c;break}default:n+=o,s++}else n+=o,s++}return s<e.length&&e[s]==="'"&&s++,{part:N.literal(n),endIndex:s}}function Fr(t,e){let r=e.trim();return r===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:K(t,r)}function jo(t){let e=[],r="",n=0;for(let s=0;s<t.length;s++){let o=t[s];o==="{"?(n++,r+=o):o==="}"?(n--,r+=o):o===","&&n===0?(e.push(r),r=""):r+=o}return e.push(r),e}function Qo(t,e,r,n){let s=Mr(t,e,r,"{","}");if(s===-1)return null;let o=e.slice(r+1,s),i=o.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(i)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(i[1],10),end:Number.parseInt(i[2],10),step:i[3]?Number.parseInt(i[3],10):void 0,startStr:i[1],endStr:i[2]}]},endIndex:s+1};let a=o.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return a?{part:{type:"BraceExpansion",items:[{type:"Range",start:a[1],end:a[2],step:a[3]?Number.parseInt(a[3],10):void 0}]},endIndex:s+1}:o.includes(",")&&n?{part:{type:"BraceExpansion",items:jo(o).map(u=>({type:"Word",word:N.word(n(t,u,!1,!1,!1))}))},endIndex:s+1}:o.includes(",")?{part:{type:"BraceExpansion",items:jo(o).map(u=>({type:"Word",word:N.word([N.literal(u)])}))},endIndex:s+1}:null}function Ko(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 Tt(t){let e=t.current(),r=e.type;if(r===m.NUMBER){let n=t.peek(1);return e.end!==n.start?!1:Uo.has(n.type)}return zo.has(r)}function Mt(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 hf(t,n,e,r.type===m.DLESSDASH);t.isWord()||t.error("Expected redirection target");let s=t.parseWord();return N.redirection(n,s,e)}function hf(t,e,r,n){t.isWord()||t.error("Expected here-document delimiter");let s=t.advance(),o=s.value,i=s.quoted||!1;(o.startsWith("'")&&o.endsWith("'")||o.startsWith('"')&&o.endsWith('"'))&&(o=o.slice(1,-1));let a=N.redirection(n?"<<-":"<<",N.hereDoc(o,N.word([]),n,i),r);return t.addPendingHeredoc(a,o,n,i),a}function Jo(t){let e=[],r=null,n=[],s=[];for(;t.check(m.ASSIGNMENT_WORD);)t.checkIterationLimit(),e.push(pf(t));for(;Tt(t);)t.checkIterationLimit(),s.push(Mt(t));for(t.isWord()&&(r=t.parseWord());(!t.isStatementEnd()||t.check(m.RBRACE))&&!t.check(m.PIPE,m.PIPE_AMP);)if(t.checkIterationLimit(),Tt(t))s.push(Mt(t));else if(t.check(m.RBRACE)){let o=t.advance();n.push(t.parseWordFromString(o.value,!1,!1))}else if(t.isWord())n.push(t.parseWord());else if(t.check(m.ASSIGNMENT_WORD)){let o=t.advance(),i=o.value,a=i.endsWith("="),c=i.endsWith("=(");if((a||c)&&(c||t.check(m.LPAREN))){let l=c?i.slice(0,-2):i.slice(0,-1);c||t.expect(m.LPAREN);let u=Lr(t);t.expect(m.RPAREN);let f=u.map(h=>Ko(t,h)),d=`${l}=(${f.join(" ")})`;n.push(t.parseWordFromString(d,!1,!1))}else n.push(t.parseWordFromString(i,o.quoted,o.singleQuoted))}else if(t.check(m.LPAREN))t.error("syntax error near unexpected token `('");else break;return N.simpleCommand(r,n,e,s)}function pf(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],o,i=s.length;if(r[i]==="["){let f=0,d=i+1;for(;i<r.length;i++)if(r[i]==="[")f++;else if(r[i]==="]"&&(f--,f===0))break;f!==0&&t.error(`Invalid assignment: ${r}`),o=r.slice(d,i),i++}let a=r[i]==="+";a&&i++,r[i]!=="="&&t.error(`Invalid assignment: ${r}`),i++;let c=r.slice(i);if(c==="("){let f=Lr(t);t.expect(m.RPAREN);let d=o!==void 0?`${s}[${o}]`:s;return N.assignment(d,null,a,f)}if(c===""&&t.check(m.LPAREN)){let f=t.current();if(e.end===f.start){t.advance();let d=Lr(t);t.expect(m.RPAREN);let h=o!==void 0?`${s}[${o}]`:s;return N.assignment(h,null,a,d)}}let l=c?t.parseWordFromString(c,e.quoted,e.singleQuoted,!0):null,u=o!==void 0?`${s}[${o}]`:s;return N.assignment(u,l,a,null)}function Lr(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 Wr(t){t.expect(m.IF);let e=[],r=t.parseCompoundList();t.expect(m.THEN);let n=t.parseCompoundList();if(n.length===0){let i=t.check(m.FI)?"fi":t.check(m.ELSE)?"else":t.check(m.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${i}'`)}for(e.push({condition:r,body:n});t.check(m.ELIF);){t.advance();let i=t.parseCompoundList();t.expect(m.THEN);let a=t.parseCompoundList();if(a.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:i,body:a})}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 o=t.parseOptionalRedirections();return N.ifNode(e,s,o)}function _r(t){if(t.expect(m.FOR),t.check(m.DPAREN_START))return gf(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 o=t.parseOptionalRedirections();return N.forNode(r,n,s,o)}function gf(t){t.expect(m.DPAREN_START);let e=null,r=null,n=null,s=["","",""],o=0,i=0;for(;!t.check(m.DPAREN_END,m.EOF);){let l=t.advance();if(l.type===m.SEMICOLON&&i===0){if(o++,o>2)break}else l.value==="("&&i++,l.value===")"&&i--,s[o]+=l.value}t.expect(m.DPAREN_END),s[0].trim()&&(e=K(t,s[0].trim())),s[1].trim()&&(r=K(t,s[1].trim())),s[2].trim()&&(n=K(t,s[2].trim())),t.skipNewlines(),t.check(m.SEMICOLON)&&t.advance(),t.skipNewlines(),t.expect(m.DO);let a=t.parseCompoundList();t.expect(m.DONE);let c=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:r,update:n,body:a,redirections:c}}function Hr(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 N.whileNode(e,r,n)}function Br(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 N.untilNode(e,r,n)}function zr(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(),o=yf(t);if(o&&r.push(o),t.skipNewlines(),t.getPos()===s&&!o)break}t.expect(m.ESAC);let n=t.parseOptionalRedirections();return N.caseNode(e,r,n)}function yf(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(),o=t.parseStatement();if(o&&r.push(o),t.skipSeparators(!1),t.getPos()===s&&!o)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=";;&"),N.caseItem(e,r,n)}function Ur(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 N.subshell(e,r)}function jr(t){t.expect(m.LBRACE);let e=t.parseCompoundList();t.expect(m.RBRACE);let r=t.parseOptionalRedirections();return N.group(e,r)}var bf=["-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"],Ef=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function Gr(t){return t.skipNewlines(),xf(t)}function xf(t){let e=ea(t);for(t.skipNewlines();t.check(m.OR_OR);){t.advance(),t.skipNewlines();let r=ea(t);e={type:"CondOr",left:e,right:r},t.skipNewlines()}return e}function ea(t){let e=qr(t);for(t.skipNewlines();t.check(m.AND_AND);){t.advance(),t.skipNewlines();let r=qr(t);e={type:"CondAnd",left:e,right:r},t.skipNewlines()}return e}function qr(t){return t.skipNewlines(),t.check(m.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:qr(t)}):Sf(t)}function Sf(t){if(t.check(m.LPAREN)){t.advance();let e=Gr(t);return t.expect(m.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),r=e.value;if(bf.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()&&Ef.includes(t.current().value)){let s=t.advance().value,o=t.parseWord();return{type:"CondBinary",operator:s,left:n,right:o}}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 Af(t,e,r){let n=r+1,s=e[n];if("@*#?$!-0123456789".includes(s))return{part:N.parameterExpansion(s),endIndex:n+1};let o="";for(;n<e.length&&/[a-zA-Z0-9_]/.test(e[n]);)o+=e[n],n++;return{part:N.parameterExpansion(o),endIndex:n}}function $f(t,e,r,n=!1){let s=r+2,o=!1;e[s]==="!"&&(o=!0,s++);let i=!1;e[s]==="#"&&!/[}:#%/^,]/.test(e[s+1]||"}")&&(i=!0,s++);let a="",c=e[s];if(/[@*#?$!-]/.test(c)&&!/[a-zA-Z0-9_]/.test(e[s+1]||""))a=c,s++;else for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)a+=e[s],s++;if(e[s]==="["){let u=Mr(t,e,s,"[","]");a+=e.slice(s,u+1),s=u+1}a===""&&!o&&!i&&e[s]!=="}"&&t.error(`\${${e[s]}}: bad substitution`);let l=null;if(o){let u=a.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)l={type:"ArrayKeys",array:u[1],star:u[2]==="*"},a="";else if(e[s]==="*"||e[s]==="@"){let f=e[s];s++,l={type:"VarNamePrefix",prefix:a,star:f==="*"},a=""}else l={type:"Indirection"}}else if(i)if(e[s]===":")for(l={type:"LengthSliceError"};s<e.length&&e[s]!=="}";)s++;else e[s]!=="}"&&/[-+=?]/.test(e[s])?t.error(`\${#${a}${e.slice(s,e.indexOf("}",s))}}: bad substitution`):l={type:"Length"};if(!l&&s<e.length&&e[s]!=="}"){let u=Nf(t,e,s,a,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:N.parameterExpansion(a,l),endIndex:s+1}}function Nf(t,e,r,n,s=!1){let o=r,i=e[o],a=e[o+1]||"";if(i===":"){let c=a;if("-=?+".includes(c)){o+=2;let y=He(t,e,o),w=e.slice(o,y),E=Re(t,w,!1,!1,!0,!1,s),$=N.word(E.length>0?E:[N.literal("")]);if(c==="-")return{operation:{type:"DefaultValue",word:$,checkEmpty:!0},endIndex:y};if(c==="=")return{operation:{type:"AssignDefault",word:$,checkEmpty:!0},endIndex:y};if(c==="?")return{operation:{type:"ErrorIfUnset",word:$,checkEmpty:!0},endIndex:y};if(c==="+")return{operation:{type:"UseAlternative",word:$,checkEmpty:!0},endIndex:y}}o++;let l=He(t,e,o),u=e.slice(o,l),f=-1,d=0,h=0;for(let g=0;g<u.length;g++){let y=u[g];if(y==="("||y==="[")d++;else if(y===")"||y==="]")d--;else if(y==="?"&&d===0)h++;else if(y===":"&&d===0)if(h>0)h--;else{f=g;break}}let p=f>=0?u.slice(0,f):u,b=f>=0?u.slice(f+1):null;return{operation:{type:"Substring",offset:Fr(t,p),length:b?Fr(t,b):null},endIndex:l}}if("-=?+".includes(i)){o++;let c=He(t,e,o),l=e.slice(o,c),u=Re(t,l,!1,!1,!0,!1,s),f=N.word(u.length>0?u:[N.literal("")]);if(i==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:c};if(i==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:c};if(i==="?")return{operation:{type:"ErrorIfUnset",word:l?f:null,checkEmpty:!1},endIndex:c};if(i==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:c}}if(i==="#"||i==="%"){let c=a===i,l=i==="#"?"prefix":"suffix";o+=c?2:1;let u=He(t,e,o),f=e.slice(o,u),d=Re(t,f,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:N.word(d.length>0?d:[N.literal("")]),side:l,greedy:c},endIndex:u}}if(i==="/"){let c=a==="/";o+=c?2:1;let l=null;e[o]==="#"?(l="start",o++):e[o]==="%"&&(l="end",o++);let u=Go(t,e,o),f=e.slice(o,u),d=Re(t,f,!1,!1,!1),h=N.word(d.length>0?d:[N.literal("")]),p=null,b=u;if(e[u]==="/"){let g=u+1,y=He(t,e,g),w=e.slice(g,y),E=Re(t,w,!1,!1,!1);p=N.word(E.length>0?E:[N.literal("")]),b=y}return{operation:{type:"PatternReplacement",pattern:h,replacement:p,all:c,anchor:l},endIndex:b}}if(i==="^"||i===","){let c=a===i,l=i==="^"?"upper":"lower";o+=c?2:1;let u=He(t,e,o),f=e.slice(o,u),d=f?N.word([N.literal(f)]):null;return{operation:{type:"CaseModification",direction:l,all:c,pattern:d},endIndex:u}}return i==="@"&&/[QPaAEK]/.test(a)?{operation:{type:"Transform",operator:a},endIndex:o+2}:{operation:null,endIndex:o}}function Vr(t,e,r,n=!1){let s=r+1;if(s>=e.length)return{part:N.literal("$"),endIndex:s};let o=e[s];if(o==="("&&e[s+1]==="(")return t.parseArithmeticExpansion(e,r);if(o==="["){let i=1,a=s+1;for(;a<e.length&&i>0;)e[a]==="["?i++:e[a]==="]"&&i--,i>0&&a++;if(i===0){let c=e.slice(s+1,a),l=K(t,c);return{part:N.arithmeticExpansion(l),endIndex:a+1}}}return o==="("?t.parseCommandSubstitution(e,r):o==="{"?$f(t,e,r,n):/[a-zA-Z_0-9@*#?$!-]/.test(o)?Af(t,e,r):{part:N.literal("$"),endIndex:s}}function vf(t,e){let r=[],n=0,s="",o=()=>{s&&(r.push(N.literal(s)),s="")};for(;n<e.length;){let i=e[n];if(i==="\\"&&n+1<e.length){let a=e[n+1];if(a==="$"||a==="`"){s+=a,n+=2;continue}s+=i,n++;continue}if(i==="$"){o();let{part:a,endIndex:c}=Vr(t,e,n,!0);a&&r.push(a),n=c;continue}if(i==="`"){o();let{part:a,endIndex:c}=t.parseBacktickSubstitution(e,n,!0);r.push(a),n=c;continue}s+=i,n++}return o(),r}function kf(t,e,r){let n=[],s=r,o="",i=()=>{o&&(n.push(N.literal(o)),o="")};for(;s<e.length&&e[s]!=='"';){let a=e[s];if(a==="\\"&&s+1<e.length){let c=e[s+1];if('"\\$`\n'.includes(c)){o+=c,s+=2;continue}o+=a,s++;continue}if(a==="$"){i();let{part:c,endIndex:l}=Vr(t,e,s,!0);c&&n.push(c),s=l;continue}if(a==="`"){i();let{part:c,endIndex:l}=t.parseBacktickSubstitution(e,s,!0);n.push(c),s=l;continue}o+=a,s++}return i(),{part:N.doubleQuoted(n),endIndex:s}}function Re(t,e,r=!1,n=!1,s=!1,o=!1,i=!1){if(n)return[N.singleQuoted(e)];if(r){let f=vf(t,e);return[N.doubleQuoted(f)]}let a=[],c=0,l="",u=()=>{l&&(a.push(N.literal(l)),l="")};for(;c<e.length;){let f=e[c];if(f==="\\"&&c+1<e.length){let d=e[c+1];(o?d==="$"||d==="`"||d==="\\"||d===`
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[c,u,f,d]of hd)if(i===c&&a===u&&o===f)return this.pos=r+3,this.column=s+3,this.makeToken(d,c+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[c,u,f]of pd)if(i===c&&a===u)return this.pos=r+2,this.column=s+2,this.makeToken(f,c+u,r,n,s);let l=md[i];return l?(this.pos=r+1,this.column=s+1,this.makeToken(l,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
+ `?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
+ `;)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
+ `||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),tr[g])return{type:tr[g],value:g,start:e,end:a,line:r,column:n};let E=g.indexOf("=");return E>0&&lo(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 l=this.column,c=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,l+=2;a<i&&s[a]!=="'";)s[a]==="\\"&&a+1<i?(u+=s[a]+s[a+1],a+=2,l+=2):(u+=s[a],a++,l++);a<i&&(u+="'",a++,l++);continue}if(w==="$"&&a+1<i&&s[a+1]==='"'&&!h&&!p){a++,l++,p=!0,f=!0,u===""&&(b=!0),a++,l++;continue}if(w==="'"&&!p){h?(h=!1,b||(u+=w)):(h=!0,b?(d=!0,f=!0):u+=w),a++,l++;continue}if(w==='"'&&!h){p?(p=!1,b||(u+=w)):(p=!0,b?f=!0:u+=w),a++,l++;continue}if(w==="\\"&&!h&&a+1<i){let g=s[a+1];if(g===`
447
+ `){a+=2,c++,l=1;continue}if(p){if(g==='"'||g==="\\"||g==="$"||g==="`"||g===`
448
+ `){g==="$"||g==="`"?u+=w+g:u+=g,a+=2,l+=2;continue}}else{g==='"'||g==="'"?u+=w+g:u+=g,a+=2,l+=2;continue}}if(w==="$"&&a+1<i&&s[a+1]==="("){u+=w,a++,l++,u+=s[a],a++,l++;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++,l++):_==='"'&&(x=!1);else if(_==="'")E=!0,R="";else if(_==='"')x=!0,R="";else if(_==="\\"&&a+1<i)u+=s[a+1],a++,l++,R="";else if(_==="#"&&!M&&(R===""||/\s/.test(s[a-1]||""))){for(;a+1<i&&s[a+1]!==`
449
+ `;)a++,l++,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
+ `&&(c++,l=0,R=""),a++,l++}continue}if(w==="$"&&a+1<i&&s[a+1]==="["){u+=w,a++,l++,u+=s[a],a++,l++;let g=1;for(;g>0&&a<i;){let E=s[a];u+=E,E==="["?g++:E==="]"?g--:E===`
451
+ `&&(c++,l=0),a++,l++}continue}if(w==="$"&&a+1<i&&s[a+1]==="{"){u+=w,a++,l++,u+=s[a],a++,l++;let g=1;for(;g>0&&a<i;){let E=s[a];u+=E,E==="{"?g++:E==="}"?g--:E===`
452
+ `&&(c++,l=0),a++,l++}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,l+=2;continue}}if(w==="`"){for(u+=w,a++,l++;a<i&&s[a]!=="`";){let g=s[a];u+=g,g==="\\"&&a+1<i&&(u+=s[a+1],a++,l++),g===`
453
+ `&&(c++,l=0),a++,l++}a<i&&(u+=s[a],a++,l++);continue}u+=w,a++,w===`
454
+ `?(c++,l=1):l++}if(this.pos=a,this.column=l,this.line=c,u==="")return{type:m.WORD,value:"",start:e,end:a,line:r,column:n,quoted:f,singleQuoted:d};if(!f&&tr[u])return{type:tr[u],value:u,start:e,end:a,line:r,column:n};if(!b){let w=u.indexOf("=");if(w>0&&lo(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}:yd(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
+ `;)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
+ `&&(this.pos++,this.line++,this.column=1);break}i+=o,this.pos<this.input.length&&this.input[this.pos]===`
457
+ `&&(i+=`
458
+ `,this.pos++,this.line++,this.column=1)}this.tokens.push({type:m.HEREDOC_CONTENT,value:i,start:r,end:this.pos,line:n,column:s})}}addPendingHeredoc(e,r,n){this.pendingHeredocs.push({delimiter:e,stripTabs:r,quoted:n})}registerHeredocFromLookahead(e){let r=this.pos,n=this.column;for(;this.pos<this.input.length&&(this.input[this.pos]===" "||this.input[this.pos]===" ");)this.pos++,this.column++;let s="",i=!1,a=this.input[this.pos];if(a==="'"||a==='"'){i=!0;let o=a;for(this.pos++,this.column++;this.pos<this.input.length&&this.input[this.pos]!==o;)s+=this.input[this.pos],this.pos++,this.column++}else for(;this.pos<this.input.length&&!/[\s;<>&|()]/.test(this.input[this.pos]);)s+=this.input[this.pos],this.pos++,this.column++;this.pos=r,this.column=n,s&&this.pendingHeredocs.push({delimiter:s,stripTabs:e,quoted:i})}isWordCharFollowing(e){if(e>=this.input.length)return!1;let r=this.input[e];return!(r===" "||r===" "||r===`
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 c=s[a];if(c===" "||c===" "||c===`
460
+ `||c===";"||c==="&"||c==="|"||c==="("||c===")"||c==="<"||c===">")break;if(c==="{"){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(c==="}"){a++,o++;continue}if(c==="$"&&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(c==="$"&&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(c==="`"){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 l=s.slice(e,a);return this.pos=a,this.column=o,{type:m.WORD,value:l,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 l=r[s];if(l==="{")i++,s++;else if(l==="}")i--,s++;else if(l===","&&i===1)a=!0,s++;else if(l==="."&&s+1<n&&r[s+1]===".")o=!0,s+=2;else{if(l===" "||l===" "||l===`
461
+ `||l===";"||l==="&"||l==="|")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 un=1e6,fn=1e5,co=1e6,uo=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]),fo=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 po(t,e,r){let n=r+1;for(;n<e.length&&/[a-zA-Z0-9_-]/.test(e[n]);)n++;return n}function dn(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 et(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 mo(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 yo(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=gd(e,n);a===-1?(s+=i,n++):(s+=e.slice(n,a+1),n=a+1)}else break}return{pattern:s,endIndex:n}}function gd(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 go(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),l=parseInt(o,16);Number.isNaN(l)?(n+="\\x",s+=2):(n+=String.fromCharCode(l),s+=4);break}case"u":{let o=e.slice(s+2,s+6),l=parseInt(o,16);Number.isNaN(l)?(n+="\\u",s+=2):(n+=String.fromCharCode(l),s+=6);break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let o="",l=s+1;for(;l<e.length&&l<s+4&&/[0-7]/.test(e[l]);)o+=e[l],l++;let c=parseInt(o,8);n+=String.fromCharCode(c),s=l;break}default:n+=i,s++}else n+=i,s++}return s<e.length&&e[s]==="'"&&s++,{part:k.literal(n),endIndex:s}}function hn(t,e){let r=e.trim();return r===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:se(t,r)}function ho(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 wo(t,e,r,n){let s=dn(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:ho(i).map(u=>({type:"Word",word:k.word(n(t,u,!1,!1,!1))}))},endIndex:s+1}:i.includes(",")?{part:{type:"BraceExpansion",items:ho(i).map(u=>({type:"Word",word:k.word([k.literal(u)])}))},endIndex:s+1}:null}function Eo(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 bo(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 nr(t){let e=t.current(),r=e.type;if(r===m.NUMBER){let n=t.peek(1);return e.end!==n.start?!1:fo.has(n.type)}return uo.has(r)}function sr(t){let e=null;t.check(m.NUMBER)&&(e=Number.parseInt(t.advance().value,10));let r=t.advance(),n=bo(t,r.type);if(r.type===m.DLESS||r.type===m.DLESSDASH)return wd(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 wd(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 So(t){let e=[],r=null,n=[],s=[];for(;t.check(m.ASSIGNMENT_WORD);)t.checkIterationLimit(),e.push(Ed(t));for(;nr(t);)t.checkIterationLimit(),s.push(sr(t));for(t.isWord()&&(r=t.parseWord());(!t.isStatementEnd()||t.check(m.RBRACE))&&!t.check(m.PIPE,m.PIPE_AMP);)if(t.checkIterationLimit(),nr(t))s.push(sr(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("="),l=a.endsWith("=(");if((o||l)&&(l||t.check(m.LPAREN))){let c=l?a.slice(0,-2):a.slice(0,-1);l||t.expect(m.LPAREN);let u=pn(t);t.expect(m.RPAREN);let f=u.map(h=>Eo(t,h)),d=`${c}=(${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 Ed(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 l=r.slice(a);if(l==="("){let f=pn(t);t.expect(m.RPAREN);let d=i!==void 0?`${s}[${i}]`:s;return k.assignment(d,null,o,f)}if(l===""&&t.check(m.LPAREN)){let f=t.current();if(e.end===f.start){t.advance();let d=pn(t);t.expect(m.RPAREN);let h=i!==void 0?`${s}[${i}]`:s;return k.assignment(h,null,o,d)}}let c=l?t.parseWordFromString(l,e.quoted,e.singleQuoted,!0):null,u=i!==void 0?`${s}[${i}]`:s;return k.assignment(u,c,o,null)}function pn(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 mn(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 l=t.check(m.FI)?"fi":t.check(m.ELSE)?"else":t.check(m.ELIF)?"elif":"fi";t.error(`syntax error near unexpected token \`${l}'`)}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 yn(t){if(t.expect(m.FOR),t.check(m.DPAREN_START))return xd(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 xd(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 c=t.advance();if(c.type===m.SEMICOLON&&a===0){if(i++,i>2)break}else c.value==="("&&a++,c.value===")"&&a--,s[i]+=c.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 l=t.parseOptionalRedirections();return{type:"CStyleFor",init:e,condition:r,update:n,body:o,redirections:l}}function gn(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 wn(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 En(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=Sd(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 Sd(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 bn(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 xn(t){t.expect(m.LBRACE);let e=t.parseCompoundList();t.expect(m.RBRACE);let r=t.parseOptionalRedirections();return k.group(e,r)}var Cd=["-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"],Nd=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function An(t){return t.skipNewlines(),vd(t)}function vd(t){let e=Ao(t);for(t.skipNewlines();t.check(m.OR_OR);){t.advance(),t.skipNewlines();let r=Ao(t);e={type:"CondOr",left:e,right:r},t.skipNewlines()}return e}function Ao(t){let e=Sn(t);for(t.skipNewlines();t.check(m.AND_AND);){t.advance(),t.skipNewlines();let r=Sn(t);e={type:"CondAnd",left:e,right:r},t.skipNewlines()}return e}function Sn(t){return t.skipNewlines(),t.check(m.BANG)?(t.advance(),t.skipNewlines(),{type:"CondNot",operand:Sn(t)}):kd(t)}function kd(t){if(t.check(m.LPAREN)){t.advance();let e=An(t);return t.expect(m.RPAREN),{type:"CondGroup",expression:e}}if(t.isWord()){let e=t.current(),r=e.value;if(Cd.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()&&Nd.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 Rd(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="",l=e[s];if(/[@*#?$!-]/.test(l)&&!/[a-zA-Z0-9_]/.test(e[s+1]||""))o=l,s++;else for(;s<e.length&&/[a-zA-Z0-9_]/.test(e[s]);)o+=e[s],s++;if(e[s]==="["){let u=dn(t,e,s,"[","]");o+=e.slice(s,u+1),s=u+1}o===""&&!i&&!a&&e[s]!=="}"&&t.error(`\${${e[s]}}: bad substitution`);let c=null;if(i){let u=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},o="";else if(e[s]==="*"||e[s]==="@"){let f=e[s];s++,c={type:"VarNamePrefix",prefix:o,star:f==="*"},o=""}else c={type:"Indirection"}}else if(a)if(e[s]===":")for(c={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`):c={type:"Length"};if(!c&&s<e.length&&e[s]!=="}"){let u=Pd(t,e,s,o,n);c=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,c),endIndex:s+1}}function Pd(t,e,r,n,s=!1){let i=r,a=e[i],o=e[i+1]||"";if(a===":"){let l=o;if("-=?+".includes(l)){i+=2;let g=et(t,e,i),E=e.slice(i,g),x=Ue(t,E,!1,!1,!0,!1,s),S=k.word(x.length>0?x:[k.literal("")]);if(l==="-")return{operation:{type:"DefaultValue",word:S,checkEmpty:!0},endIndex:g};if(l==="=")return{operation:{type:"AssignDefault",word:S,checkEmpty:!0},endIndex:g};if(l==="?")return{operation:{type:"ErrorIfUnset",word:S,checkEmpty:!0},endIndex:g};if(l==="+")return{operation:{type:"UseAlternative",word:S,checkEmpty:!0},endIndex:g}}i++;let c=et(t,e,i),u=e.slice(i,c),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:hn(t,p),length:b?hn(t,b):null},endIndex:c}}if("-=?+".includes(a)){i++;let l=et(t,e,i),c=e.slice(i,l),u=Ue(t,c,!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:l};if(a==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:l};if(a==="?")return{operation:{type:"ErrorIfUnset",word:c?f:null,checkEmpty:!1},endIndex:l};if(a==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:l}}if(a==="#"||a==="%"){let l=o===a,c=a==="#"?"prefix":"suffix";i+=l?2:1;let u=et(t,e,i),f=e.slice(i,u),d=Ue(t,f,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:k.word(d.length>0?d:[k.literal("")]),side:c,greedy:l},endIndex:u}}if(a==="/"){let l=o==="/";i+=l?2:1;let c=null;e[i]==="#"?(c="start",i++):e[i]==="%"&&(c="end",i++);let u=mo(t,e,i),f=e.slice(i,u),d=Ue(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=et(t,e,w),E=e.slice(w,g),x=Ue(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:l,anchor:c},endIndex:b}}if(a==="^"||a===","){let l=o===a,c=a==="^"?"upper":"lower";i+=l?2:1;let u=et(t,e,i),f=e.slice(i,u),d=f?k.word([k.literal(f)]):null;return{operation:{type:"CaseModification",direction:c,all:l,pattern:d},endIndex:u}}return a==="@"&&/[QPaAEK]/.test(o)?{operation:{type:"Transform",operator:o},endIndex:i+2}:{operation:null,endIndex:i}}function Cn(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 l=e.slice(s+1,o),c=se(t,l);return{part:k.arithmeticExpansion(c),endIndex:o+1}}}return i==="("?t.parseCommandSubstitution(e,r):i==="{"?$d(t,e,r,n):/[a-zA-Z_0-9@*#?$!-]/.test(i)?Rd(t,e,r):{part:k.literal("$"),endIndex:s}}function Od(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:l}=Cn(t,e,n,!0);o&&r.push(o),n=l;continue}if(a==="`"){i();let{part:o,endIndex:l}=t.parseBacktickSubstitution(e,n,!0);r.push(o),n=l;continue}s+=a,n++}return i(),r}function Dd(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 l=e[s+1];if('"\\$`\n'.includes(l)){i+=l,s+=2;continue}i+=o,s++;continue}if(o==="$"){a();let{part:l,endIndex:c}=Cn(t,e,s,!0);l&&n.push(l),s=c;continue}if(o==="`"){a();let{part:l,endIndex:c}=t.parseBacktickSubstitution(e,s,!0);n.push(l),s=c;continue}i+=o,s++}return a(),{part:k.doubleQuoted(n),endIndex:s}}function Ue(t,e,r=!1,n=!1,s=!1,i=!1,a=!1){if(n)return[k.singleQuoted(e)];if(r){let f=Od(t,e);return[k.doubleQuoted(f)]}let o=[],l=0,c="",u=()=>{c&&(o.push(k.literal(c)),c="")};for(;l<e.length;){let f=e[l];if(f==="\\"&&l+1<e.length){let d=e[l+1];(i?d==="$"||d==="`"||d==="\\"||d===`
427
464
  `:d==="$"||d==="`"||d==="\\"||d==='"'||d===`
428
- `)?l+=d:l+=`\\${d}`,c+=2;continue}if(f==="'"&&!i){u();let d=e.indexOf("'",c+1);if(d===-1){l+=e.slice(c);break}a.push(N.singleQuoted(e.slice(c+1,d))),c=d+1;continue}if(f==='"'){u();let{part:d,endIndex:h}=kf(t,e,c+1);a.push(d),c=h+1;continue}if(f==="$"&&e[c+1]==="'"){u();let{part:d,endIndex:h}=Zo(t,e,c+2);a.push(d),c=h;continue}if(f==="$"){u();let{part:d,endIndex:h}=Vr(t,e,c);d&&a.push(d),c=h;continue}if(f==="`"){u();let{part:d,endIndex:h}=t.parseBacktickSubstitution(e,c);a.push(d),c=h;continue}if(f==="~"){let d=c>0?e[c-1]:"";if(c===0||d==="="||s&&d===":"){let p=qo(t,e,c),b=e[p];if(b===void 0||b==="/"||b===":"){u();let g=e.slice(c+1,p)||null;a.push({type:"TildeExpansion",user:g}),c=p;continue}}}if(f==="*"||f==="?"||f==="["){u();let{pattern:d,endIndex:h}=Vo(t,e,c);a.push({type:"Glob",pattern:d}),c=h;continue}if(f==="{"&&!s){let d=Qo(t,e,c,Re);if(d){u(),a.push(d.part),c=d.endIndex;continue}}l+=f,c++}return u(),a}var ee=class t{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;checkIterationLimit(){if(this.parseIterations++,this.parseIterations>Bo)throw new $e("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}parse(e){if(e.length>Dr)throw new $e(`Input too large: ${e.length} bytes exceeds limit of ${Dr}`,1,1);let r=new Dt(e);if(this.tokens=r.tokenize(),this.tokens.length>Tr)throw new $e(`Too many tokens: ${this.tokens.length} exceeds limit of ${Tr}`,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,...o){let i=this.tokens[this.pos]?.type;return i===e||r!==void 0&&i===r||n!==void 0&&i===n||s!==void 0&&i===s?!0:o.length>0?o.includes(i):!1}expect(e,r){if(this.check(e))return this.advance();let n=this.current();throw new $e(r||`Expected ${e}, got ${n.type}`,n.line,n.column,n)}error(e){let r=this.current();throw new $e(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=N.word([N.literal(r.value)]):n=this.parseWordFromString(r.value,!1,!1,!1,!0),e.redirect.target=N.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,o=this.parseStatement();o&&e.push(o),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 N.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 o=this.advance();r.push(o.type===m.AND_AND?"&&":"||"),this.skipNewlines();let i=this.parsePipeline();e.push(i)}return this.check(m.AMP)&&(this.advance(),n=!0),N.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 o=this.advance();this.skipNewlines();let i=this.parseCommand();o.type===m.PIPE_AMP&&i.type==="SimpleCommand"&&i.redirections.unshift(N.redirection(">&",N.word([N.literal("1")]),2)),n.push(i)}return N.pipeline(n,r)}parseCommand(){return this.check(m.IF)?Wr(this):this.check(m.FOR)?_r(this):this.check(m.WHILE)?Hr(this):this.check(m.UNTIL)?Br(this):this.check(m.CASE)?zr(this):this.check(m.LPAREN)?Ur(this):this.check(m.LBRACE)?jr(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():Jo(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,o=!1){let i=Re(this,e,r,n,s,o);return N.word(i)}parseCommandSubstitution(e,r){let n=r+2,s=1,o=n,i=!1,a=!1,c=0,l=!1,u="";for(;o<e.length&&s>0;){let p=e[o];i?p==="'"&&(i=!1):a?p==="\\"&&o+1<e.length?o++:p==='"'&&(a=!1):p==="'"?(i=!0,u=""):p==='"'?(a=!0,u=""):p==="\\"&&o+1<e.length?(o++,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==="("?o>0&&e[o-1]==="$"?s++:l||s++:p===")"?l?l=!1:s--:p===";"&&c>0&&o+1<e.length&&e[o+1]===";"&&(l=!0)),s>0&&o++}s>0&&this.error("unexpected EOF while looking for matching `)'");let f=e.slice(n,o),h=new t().parse(f);return{part:N.commandSubstitution(h,!1),endIndex:o+1}}parseBacktickSubstitution(e,r,n=!1){let o=r+1,i="";for(;o<e.length&&e[o]!=="`";)if(e[o]==="\\"){let l=e[o+1];l==="$"||l==="`"||l==="\\"||l===`
429
- `||n&&l==='"'?(l!==`
430
- `&&(i+=l),o+=2):(i+=e[o],o++)}else i+=e[o],o++;o>=e.length&&this.error("unexpected EOF while looking for matching ``'");let c=new t().parse(i);return{part:N.commandSubstitution(c,!0),endIndex:o+1}}parseArithmeticExpansion(e,r){let n=r+3,s=1,o=0,i=n;for(;i<e.length-1&&s>0;)e[i]==="$"&&e[i+1]==="("?e[i+2]==="("?(s++,i+=3):(o++,i+=2):e[i]==="("&&e[i+1]==="("?(s++,i+=2):e[i]===")"&&e[i+1]===")"?o>0?(o--,i++):(s--,s>0&&(i+=2)):e[i]==="("?(o++,i++):(e[i]===")"&&o>0&&o--,i++);let a=e.slice(n,i),c=this.parseArithmeticExpression(a);return{part:N.arithmeticExpansion(c),endIndex:i+2}}parseArithmeticCommand(){this.expect(m.DPAREN_START);let e="",r=1,n=0,s=!1,o=!1;for(;r>0&&!this.check(m.EOF);){if(s){if(s=!1,n>0){n--,e+=")";continue}if(this.check(m.RPAREN)){r--,o=!0,this.advance();continue}if(this.check(m.DPAREN_END)){r--,o=!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--,o=!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())}o||this.expect(m.DPAREN_END);let i=this.parseArithmeticExpression(e.trim()),a=this.parseOptionalRedirections();return N.arithmeticCommand(i,a)}parseConditionalCommand(){this.expect(m.DBRACK_START);let e=Gr(this);this.expect(m.DBRACK_END);let r=this.parseOptionalRedirections();return N.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 N.functionDef(e,r,n)}parseCompoundCommandBody(){if(this.check(m.LBRACE))return jr(this);if(this.check(m.LPAREN))return Ur(this);if(this.check(m.IF))return Wr(this);if(this.check(m.FOR))return _r(this);if(this.check(m.WHILE))return Hr(this);if(this.check(m.UNTIL))return Br(this);if(this.check(m.CASE))return zr(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(;Tt(this);){this.checkIterationLimit();let r=this.pos;if(e.push(Mt(this)),this.pos===r)break}return e}parseArithmeticExpression(e){return K(this,e)}};function Oe(t){return new ee().parse(t)}Z();var Qe=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 o=e[s];if((r?.[s]??!1)||!this.isGlobPattern(o))n.push(o);else{let a=await this.expand(o);a.length>0?n.push(...a):n.push(o)}}return n}async expand(e){return e.includes("**")?this.expandRecursive(e):this.expandSimple(e)}async expandSimple(e){let r=[],n=e.lastIndexOf("/"),s,o;n===-1?(s=this.cwd,o=e):(s=e.slice(0,n)||"/",o=e.slice(n+1));let i=this.fs.resolvePath(this.cwd,s);try{let a=await this.fs.readdir(i);for(let c of a)if(this.matchPattern(c,o)){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(/\/$/,"")||".",i=e.slice(n+2).replace(/^\//,"");return await this.walkDirectory(s,i,r),r.sort()}async walkDirectory(e,r,n){let s=this.fs.resolvePath(this.cwd,e);try{let o=await this.fs.readdir(s);for(let i of o){let a=e==="."?i:`${e}/${i}`,c=this.fs.resolvePath(this.cwd,a);try{(await this.fs.stat(c)).isDirectory?await this.walkDirectory(a,r,n):r&&this.matchPattern(i,r)&&n.push(a)}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 o=n+1,i="[";for(o<e.length&&(e[o]==="^"||e[o]==="!")&&(i+="^",o++),o<e.length&&e[o]==="]"&&(i+="\\]",o++);o<e.length&&e[o]!=="]";){if(e[o]==="["&&o+1<e.length&&e[o+1]===":"){let a=e.indexOf(":]",o+2);if(a!==-1){let c=e.slice(o+2,a),l=this.posixClassToRegex(c);i+=l,o=a+2;continue}}if(e[o]==="\\"&&o+1<e.length){i+=`\\${e[o+1]}`,o+=2;continue}e[o]==="-"?i+="\\-":i+=e[o],o++}i+="]",r+=i,n=o}else if(s==="\\"&&n+1<e.length){let o=e[n+1];/[.+^${}()|\\*?[\]]/.test(o)?r+=`\\${o}`:r+=o,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]||""}};Z();function pe(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return pe(t.expression);case"ArithBinary":return pe(t.left)||pe(t.right);case"ArithUnary":return pe(t.operand);case"ArithTernary":return pe(t.condition)||pe(t.consequent)||pe(t.alternate);case"ArithAssignment":return pe(t.value);case"ArithGroup":return pe(t.expression);case"ArithArrayElement":return t.index?pe(t.index):!1;case"ArithConcat":return t.parts.some(pe);default:return!1}}function Zr(t){let e=t.operation;return e?!!("word"in e&&e.word&&Ne(e.word)||e.type==="PatternReplacement"&&(e.pattern&&Ne(e.pattern)||e.replacement&&Ne(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&Ne(e.pattern)):!1}function Ft(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return pe(t.expression.expression);case"DoubleQuoted":return t.parts.some(Ft);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&Ne(e.word));case"ParameterExpansion":return Zr(t);default:return!1}}function Ne(t){return t.parts.some(Ft)}function Qr(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 ta(t){let e=!1,r=!1,n=!1,s=!1,o=!1;for(let i of t){if((i.type==="SingleQuoted"||i.type==="DoubleQuoted")&&(e=!0,i.type==="DoubleQuoted"))for(let a of i.parts)a.type==="ParameterExpansion"&&a.parameter.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/)&&!a.operation&&(s=!0);i.type==="CommandSubstitution"&&(r=!0),i.type==="ParameterExpansion"&&(o=!0,(i.parameter==="@"||i.parameter==="*")&&(n=!0),Qr(i)&&(e=!0))}return{hasQuoted:e,hasCommandSub:r,hasArrayVar:n,hasArrayAtExpansion:s,hasParamExpansion:o}}function Pf(t,e,r,n,s){let o=r??1;o===0&&(o=1);let i=Math.abs(o),a=[],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+=i,f++)a.push(l(u));else for(let u=t,f=0;u>=e&&f<1e4;u-=i,f++)a.push(l(u));return a}function Rf(t,e,r){let n=r??1;n===0&&(n=1);let s=t.charCodeAt(0),o=e.charCodeAt(0),i=Math.abs(n),a=t>="A"&&t<="Z",c=t>="a"&&t<="z",l=e>="A"&&e<="Z",u=e>="a"&&e<="z";if(a&&u||c&&l)return null;let f=[];if(s<=o)for(let d=s,h=0;d<=o&&h<1e4;d+=i,h++)f.push(String.fromCharCode(d));else for(let d=s,h=0;d>=o&&h<1e4;d-=i,h++)f.push(String.fromCharCode(d));return f}function st(t,e,r,n,s){let o=r!==void 0?`..${r}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:Pf(t,e,r,n,s),literal:`{${t}..${e}${o}}`}:typeof t=="string"&&typeof e=="string"?{expanded:Rf(t,e,r),literal:`{${t}..${e}${o}}`}:{expanded:null,literal:`{${t}..${e}${o}}`}}function ae(t,e){let r="",n=0;for(;n<t.length;){let s=t[n];if(s==="\\")if(n+1<t.length){let o=t[n+1];/[\\^$.|+(){}[\]*?]/.test(o)?r+=`\\${o}`:r+=o,n+=2}else r+="\\\\",n++;else if(s==="*")r+=e?".*":".*?",n++;else if(s==="?")r+=".",n++;else if(s==="["){let o=Of(t,n);if(o===-1)r+="\\[",n++;else{let i=t.slice(n+1,o);r+=Df(i),n=o+1}}else/[\^$.|+(){}]/.test(s)?(r+=`\\${s}`,n++):(r+=s,n++)}return r}function Of(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 Df(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 o=t.slice(r+1,s);for(let i of o)i==="\\"?e+="\\\\":i==="]"?e+="\\]":i==="^"&&e==="["?e+="\\^":e+=i;r=s+1;continue}}if(t[r]==="["&&r+1<t.length&&t[r+1]===":"){let s=t.indexOf(":]",r+2);if(s!==-1){let o=t.slice(r+2,s);e+=Mf(o),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 Tf={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 Mf(t){return Tf[t]??""}Z();function it(t,e){let r=`${e}_`,n=[];for(let s of Object.keys(t.state.env))if(s.startsWith(r)){let o=s.slice(r.length),i=Number.parseInt(o,10);!Number.isNaN(i)&&String(i)===o&&n.push(i)}return n.sort((s,o)=>s-o)}function Kr(t,e){let r=`${e}_`;for(let n of Object.keys(t.state.env))n.startsWith(r)&&delete t.state.env[n]}function Xr(t,e){let r=`${e}_`,n=[];for(let s of Object.keys(t.state.env))if(s.startsWith(r)&&!s.includes("__")){let o=s.slice(r.length);n.push(o)}return n.sort()}function ra(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function Lt(t){return t.IFS??`
431
- `}function na(t){return t.IFS===""}function ot(t){return t.split("").map(e=>/[\\^$.*+?()[\]{}|-]/.test(e)?`\\${e}`:e===" "?"\\t":e===`
432
- `?"\\n":e).join("")}function Ff(t,e){let r=ot(t);return new RegExp(`[${r}]+`,e)}function Lf(t){let e=ot(t);return new RegExp(`^[${e}]+`)}function Wf(t){let e=ot(t);return new RegExp(`[${e}]+$`)}function at(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function sa(t,e){if(e==="")return{words:[t],wordStarts:[0]};let r=[],n=[],s=Ff(e,"g"),o=0,i=t.match(Lf(e));i&&(o=i[0].length),s.lastIndex=o;let a=s.exec(t);for(;a!==null;)a.index>o&&(n.push(o),r.push(t.substring(o,a.index))),o=s.lastIndex,a=s.exec(t);return o<t.length&&(n.push(o),r.push(t.substring(o))),{words:r,wordStarts:n}}function ia(t,e){return e===""?t:t.replace(Wf(e),"")}function X(t,e){return t.state.associativeArrays?.has(e)?Xr(t,e).map(o=>[o,t.state.env[`${e}_${o}`]]):it(t,e).map(s=>[s,t.state.env[`${e}_${s}`]])}function oa(t,e){return t.state.associativeArrays?.has(e)?Xr(t,e).length>0:it(t,e).length>0}function me(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 i="";return t.state.options.errexit&&(i+="e"),t.state.options.nounset&&(i+="u"),t.state.options.verbose&&(i+="v"),t.state.options.xtrace&&(i+="x"),t.state.options.pipefail&&(i+="p"),i}case"*":{let i=Number.parseInt(t.state.env["#"]||"0",10);if(i===0)return"";let a=[];for(let c=1;c<=i;c++)a.push(t.state.env[String(c)]||"");return a.join(at(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 Ce(`\${${e}}`);let s=e.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(s){let i=s[1],a=s[2];if(a==="@"||a==="*"){let f=X(t,i);if(f.length>0)return f.map(([,h])=>h).join(" ");let d=t.state.env[i];return d!==void 0?d:""}if(t.state.associativeArrays?.has(i)){let f=ra(a),d=t.state.env[`${i}_${f}`];if(d===void 0&&r&&t.state.options.nounset)throw new fe(`${i}[${a}]`);return d||""}let l;if(/^-?\d+$/.test(a))l=Number.parseInt(a,10);else try{let f=new ee,d=K(f,a);l=W(t,d.expression)}catch{let f=t.state.env[a];l=f?Number.parseInt(f,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let f=X(t,i);if(f.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
433
- `,"";let h=Math.max(...f.map(([b])=>typeof b=="number"?b:0))+1+l;return h<0?(t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${i}: bad array subscript
434
- `,""):t.state.env[`${i}_${h}`]||""}let u=t.state.env[`${i}_${l}`];if(u===void 0&&r&&t.state.options.nounset)throw new fe(`${i}[${l}]`);return u||""}if(/^[1-9][0-9]*$/.test(e)){let i=t.state.env[e];if(i===void 0&&r&&t.state.options.nounset)throw new fe(e);return i||""}let o=t.state.env[e];if(o===void 0&&r&&t.state.options.nounset)throw new fe(e);return o||""}async function aa(t,e,r,n,s){let o=[];for(let u of e){let f=u.type==="ParameterExpansion"||u.type==="CommandSubstitution"||u.type==="ArithmeticExpansion";if(u.type==="ParameterExpansion"&&Qr(u)){let d=await s(t,u);o.push({value:d,splittable:!1})}else{let d=await s(t,u);o.push({value:d,splittable:f})}}if(!o.some(u=>u.splittable&&new RegExp(`[${n}]`).test(u.value))){let u=o.map(f=>f.value).join("");return u?[u]:[]}let a=new RegExp(`[${n}]+`),c=[],l="";for(let u=0;u<o.length;u++){let f=o[u];if(!f.splittable)l+=f.value;else{let d=f.value.split(a);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 le(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function la(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function ca(t){switch(t.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return t.value==="";default:return!1}}function Yr(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`
435
- `: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 Be(t,e,r=!1){return e.map(n=>ve(t,n,r)).join("")}async function ze(t,e,r=!1){let n=[];for(let s of e)n.push(await xe(t,s));return n.join("")}function _f(t){return ca(t)}function ua(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!_f(e))return!1;return!0}function fa(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function da(t,e,r=!1){let n=la(e);if(n!==null)return n;switch(e.type){case"ParameterExpansion":return ya(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 ve(t,e,r=!1){let n=da(t,e,r);if(n!==null)return n;switch(e.type){case"DoubleQuoted":{let s=[];for(let o of e.parts)s.push(ve(t,o,!0));return s.join("")}case"ArithmeticExpansion":return String(W(t,e.expression.expression));case"BraceExpansion":{let s=[];for(let o of e.items)if(o.type==="Range"){let i=st(o.start,o.end,o.step,o.startStr,o.endStr);if(i.expanded)s.push(...i.expanded);else return i.literal}else s.push(Wt(t,o.word));return s.join(" ")}default:return""}}function Wt(t,e){let r=e.parts,n=r.length;if(n===1)return ve(t,r[0]);let s=[];for(let o=0;o<n;o++)s.push(ve(t,r[o]));return s.join("")}async function U(t,e){return Ne(e)?ga(t,e):Wt(t,e)}function _t(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&_t(e.parts))return!0;return!1}function Hf(t){for(let e of t){if(e.type==="BraceExpansion"){for(let r of e.items)if(r.type==="Word"&&Ne(r.word))return!0}if(Ft(e))return!0}return!1}var ha=1e4,Ke=1e5;function pa(t,e,r={count:0}){if(r.count>Ke)return[[]];let n=[[]];for(let s of e)if(s.type==="BraceExpansion"){let o=[],i=!1,a="";for(let u of s.items)if(u.type==="Range"){let f=st(u.start,u.end,u.step,u.startStr,u.endStr);if(f.expanded)for(let d of f.expanded)r.count++,o.push(d);else{i=!0,a=f.literal;break}}else{let f=pa(t,u.word.parts,r);for(let d of f)r.count++,o.push(d.join(""))}if(i){for(let u of n)r.count++,u.push(a);continue}if(n.length*o.length>ha||r.count>Ke)return n;let l=[];for(let u of n)for(let f of o){if(r.count++,r.count>Ke)return l.length>0?l:n;l.push([...u,f])}n=l}else{let o=ve(t,s);for(let i of n)r.count++,i.push(o)}return n}function Bf(t,e){let r=e.parts;return _t(r)?pa(t,r).map(s=>s.join("")):[Wt(t,e)]}async function ma(t,e,r={count:0}){if(r.count>Ke)return[[]];let n=[[]];for(let s of e)if(s.type==="BraceExpansion"){let o=[],i=!1,a="";for(let u of s.items)if(u.type==="Range"){let f=st(u.start,u.end,u.step,u.startStr,u.endStr);if(f.expanded)for(let d of f.expanded)r.count++,o.push(d);else{i=!0,a=f.literal;break}}else{let f=await ma(t,u.word.parts,r);for(let d of f)r.count++,o.push(d.join(""))}if(i){for(let u of n)r.count++,u.push(a);continue}if(n.length*o.length>ha||r.count>Ke)return n;let l=[];for(let u of n)for(let f of o){if(r.count++,r.count>Ke)return l.length>0?l:n;l.push([...u,f])}n=l}else{let o=await xe(t,s);for(let i of n)r.count++,i.push(o)}return n}async function zf(t,e){let r=e.parts;return _t(r)?(await ma(t,r)).map(s=>s.join("")):[await U(t,e)]}async function lt(t,e){let r=e.parts,{hasQuoted:n,hasCommandSub:s,hasArrayVar:o,hasArrayAtExpansion:i,hasParamExpansion:a}=ta(r),l=_t(r)?Hf(r)?await zf(t,e):Bf(t,e):null;if(l&&l.length>1){let d=[];for(let h of l)if(!n&&/[*?[]/.test(h)){let b=await new Qe(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(i&&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],g=X(t,b);if(g.length>0)return{values:g.map(([,w])=>w),quoted:!0};let y=t.state.env[b];return y!==void 0?{values:[y],quoted:!0}:{values:[],quoted:!0}}}}if(!n&&o&&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||o||a)&&!na(t.state.env)){let d=Lt(t.state.env),h=ot(d),p=await aa(t,r,d,h,xe),b=[],g=new Qe(t.fs,t.state.cwd);for(let y of p)if(/[*?[]/.test(y)){let w=await g.expand(y);w.length>0?b.push(...w):b.push(y)}else b.push(y);return{values:b,quoted:!1}}let f=Ne(e)?await ga(t,e):Wt(t,e);if(!n&&/[*?[]/.test(f)){let h=await new Qe(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 ga(t,e){let r=e.parts,n=r.length;if(n===1)return xe(t,r[0]);let s=[];for(let o=0;o<n;o++)s.push(await xe(t,r[o]));return s.join("")}async function xe(t,e){if(e.type==="ParameterExpansion"&&Zr(e))return Uf(t,e);let r=da(t,e);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let n=[];for(let s of e.parts)n.push(await xe(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 j)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 _(t,e.expression.expression));case"BraceExpansion":{let n=[];for(let s of e.items)if(s.type==="Range"){let o=st(s.start,s.end,s.step,s.startStr,s.endStr);if(o.expanded)n.push(...o.expanded);else return o.literal}else n.push(await U(t,s.word));return n.join(" ")}default:return""}}function ya(t,e,r=!1){let{parameter:n,operation:s}=e,o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),i=me(t,n,!o);if(!s)return i;let a=!(n in t.state.env),c=i==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&c)&&s.word?Be(t,s.word.parts,r):i;case"AssignDefault":{if((a||s.checkEmpty&&c)&&s.word){let u=Be(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 g=new ee,y=K(g,h);p=W(t,y.expression)}catch{let g=t.state.env[h];p=g?Number.parseInt(g,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 i}case"ErrorIfUnset":{if(a||s.checkEmpty&&c){let u=s.word?Be(t,s.word.parts,r):`${n}: parameter null or not set`;throw new z(1,"",`bash: ${u}
436
- `)}return i}case"UseAlternative":return!(a||s.checkEmpty&&c)&&s.word?Be(t,s.word.parts,r):"";case"Length":{let l=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l){let u=X(t,l[1]);return String(u.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&oa(t,n)){let u=t.state.env[`${n}_0`]||"";return String(u.length)}return String(i.length)}case"LengthSliceError":throw new Ce(n);case"Substring":{let l=s.offset?W(t,s.offset.expression):0,u=s.length?W(t,s.length.expression):void 0;if(n==="@"||n==="*"){let p=(t.state.env["@"]||"").split(" ").filter(w=>w),b=t.state.env[0]||"bash",g=l===0?[b,...p]:p,y=l===0?0:l-1;if(y<0||y>=g.length)return"";if(u!==void 0){let w=u<0?g.length+u:y+u;return g.slice(y,Math.max(y,w)).join(" ")}return g.slice(y).join(" ")}let f=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(f){let b=X(t,f[1]).map(([,y])=>y),g=l;if(g<0&&(g=b.length+g,g<0))return"";if(u!==void 0){if(u<0){let y=b.length+u;return b.slice(g,Math.max(g,y)).join(" ")}return b.slice(g,g+u).join(" ")}return b.slice(g).join(" ")}let d=[...i],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+=ae(f.pattern,s.greedy);else if(f.type==="Literal")l+=ae(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")l+=le(f.value);else if(f.type==="DoubleQuoted"){let d=Be(t,f.parts);l+=le(d)}else if(f.type==="ParameterExpansion"){let d=ve(t,f);l+=ae(d,s.greedy)}else{let d=ve(t,f);l+=le(d)}if(s.side==="prefix")return i.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return i.replace(u,"");for(let f=i.length;f>=0;f--){let d=i.slice(f);if(u.test(d))return i.slice(0,f)}return i}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=ae(d.pattern,!0);else if(d.type==="Literal")l+=ae(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=le(d.value);else if(d.type==="DoubleQuoted"){let h=Be(t,d.parts);l+=le(h)}else if(d.type==="ParameterExpansion"){let h=ve(t,d);l+=ae(h,!0)}else{let h=ve(t,d);l+=le(h)}let u=s.replacement?Be(t,s.replacement.parts):"";if(l==="")return i;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(i);for(;b!==null&&!(b[0].length===0&&b.index===i.length);)h+=i.slice(p,b.index)+u,p=b.index+b[0].length,b[0].length===0&&p++,b=d.exec(i);return h+=i.slice(p),h}return i.replace(d,u)}catch{return i}}case"CaseModification":return s.direction==="upper"?s.all?i.toUpperCase():i.charAt(0).toUpperCase()+i.slice(1):s.all?i.toLowerCase():i.charAt(0).toLowerCase()+i.slice(1);case"Transform":{let l=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(l&&s.operator==="Q")return X(t,l[1]).map(([,d])=>Yr(d)).join(" ");switch(s.operator){case"Q":return Yr(i);case"P":return i;case"a":return"";case"A":return`${n}=${Yr(i)}`;case"E":return i.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`
437
- `;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 i}}case"Indirection":return me(t,i);case"ArrayKeys":{let u=X(t,s.array).map(([f])=>String(f));return s.star?u.join(at(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(at(t.state.env)):l.join(" ")}default:return i}}async function Uf(t,e,r=!1){let{parameter:n,operation:s}=e,o=s&&(s.type==="DefaultValue"||s.type==="AssignDefault"||s.type==="UseAlternative"||s.type==="ErrorIfUnset"),i=me(t,n,!o);if(!s)return i;let a=!(n in t.state.env),c=i==="";switch(s.type){case"DefaultValue":return(a||s.checkEmpty&&c)&&s.word?ze(t,s.word.parts,r):i;case"AssignDefault":{if((a||s.checkEmpty&&c)&&s.word){let u=await ze(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 g=new ee,y=K(g,h);p=await _(t,y.expression)}catch{let g=t.state.env[h];p=g?Number.parseInt(g,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 i}case"ErrorIfUnset":{if(a||s.checkEmpty&&c){let u=s.word?await ze(t,s.word.parts,r):`${n}: parameter null or not set`;throw new z(1,"",`bash: ${u}
438
- `)}return i}case"UseAlternative":return!(a||s.checkEmpty&&c)&&s.word?ze(t,s.word.parts,r):"";case"PatternRemoval":{let l="";if(s.pattern)for(let f of s.pattern.parts)if(f.type==="Glob")l+=ae(f.pattern,s.greedy);else if(f.type==="Literal")l+=ae(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")l+=le(f.value);else if(f.type==="DoubleQuoted"){let d=await ze(t,f.parts);l+=le(d)}else if(f.type==="ParameterExpansion"){let d=await xe(t,f);l+=ae(d,s.greedy)}else{let d=await xe(t,f);l+=le(d)}if(s.side==="prefix")return i.replace(new RegExp(`^${l}`),"");let u=new RegExp(`${l}$`);if(s.greedy)return i.replace(u,"");for(let f=i.length;f>=0;f--){let d=i.slice(f);if(u.test(d))return i.slice(0,f)}return i}case"PatternReplacement":{let l="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")l+=ae(d.pattern,!0);else if(d.type==="Literal")l+=ae(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")l+=le(d.value);else if(d.type==="DoubleQuoted"){let h=await ze(t,d.parts);l+=le(h)}else if(d.type==="ParameterExpansion"){let h=await xe(t,d);l+=ae(h,!0)}else{let h=await xe(t,d);l+=le(h)}let u=s.replacement?await ze(t,s.replacement.parts):"";if(l==="")return i;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(i);for(;b!==null&&!(b[0].length===0&&b.index===i.length);)h+=i.slice(p,b.index)+u,p=b.index+b[0].length,b[0].length===0&&p++,b=d.exec(i);return h+=i.slice(p),h}return i.replace(d,u)}catch{return i}}default:return ya(t,e,r)}}function Jr(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 V("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 wa(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 en(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function jf(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:me(t,e)}function Xe(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 ee,{expr:s,pos:o}=Ae(n,r,0);if(o<r.length){let i=r.slice(o).trim().split(/\s+/)[0];throw new V(`${r}: syntax error in expression (error token is "${i}")`)}return s.type==="ArithNumber"?s.value:e||0}catch(n){if(n instanceof V)throw n;let s=r.split(/\s+/).slice(1)[0]||r;throw new V(`${r}: syntax error in expression (error token is "${s}")`)}}function Ht(t,e,r=new Set){if(r.has(e))return 0;r.add(e);let n=jf(t,e);if(!n)return 0;let s=Number.parseInt(n,10);if(!Number.isNaN(s)&&/^-?\d+$/.test(n.trim()))return s;let o=n.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(o))return Ht(t,o,r);try{let i=new ee,{expr:a}=Ae(i,o,0);return ge(t,a,r)}catch{return 0}}function ge(t,e,r){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new V("value too great for base");return e.value;case"ArithVariable":return Ht(t,e.name,r);case"ArithBinary":{if(e.operator==="||")return ge(t,e.left,r)||ge(t,e.right,r)?1:0;if(e.operator==="&&")return ge(t,e.left,r)&&ge(t,e.right,r)?1:0;let n=ge(t,e.left,r),s=ge(t,e.right,r);return Jr(n,s,e.operator)}case"ArithUnary":{let n=ge(t,e.operand,r);return en(n,e.operator)}case"ArithTernary":return ge(t,e.condition,r)?ge(t,e.consequent,r):ge(t,e.alternate,r);case"ArithGroup":return ge(t,e.expression,r);default:return W(t,e)}}function De(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 me(t,e);let o=e.slice(0,n),i=e.slice(n+s.length),a=t.state.env[o],c=a===void 0,l=a==="",u=s.startsWith(":");switch(s){case":-":case"-":return c||u&&l?i:a||"";case":=":case"=":return c||u&&l?(t.state.env[o]=i,i):a||"";case":+":case"+":return!(c||u&&l)?i:"";case":?":case"?":{if(c||u&&l)throw new Error(i||`${o}: parameter null or not set`);return a||""}default:return a||""}}function W(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new V("value too great for base");return e.value;case"ArithVariable":return Ht(t,e.name);case"ArithNested":return W(t,e.expression);case"ArithCommandSubst":return 0;case"ArithBracedExpansion":{let r=De(t,e.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=De(t,e.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)return 0;let s=`${n}#${e.value}`;return Ze(s)}case"ArithDynamicNumber":{let n=De(t,e.prefix)+e.suffix;return Ze(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 o=W(t,e.index);if(o<0){let a=X(t,e.array);if(a.length===0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
439
- `,0;let l=Math.max(...a.map(([u])=>typeof u=="number"?u:0))+1+o;if(l<0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
440
- `,0;o=l}n=`${e.array}_${o}`;let i=t.state.env[n];if(i!==void 0)return Xe(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return Xe(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new fe(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?Xe(s):0}case"ArithDoubleSubscript":throw new V("double subscript","","");case"ArithNumberSubscript":throw new V(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return W(t,e.left)||W(t,e.right)?1:0;if(e.operator==="&&")return W(t,e.left)&&W(t,e.right)?1:0;let r=W(t,e.left),n=W(t,e.right);return Jr(r,n,e.operator)}case"ArithUnary":{let r=W(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let n=e.operand.name,s=Number.parseInt(me(t,n),10)||0,o=e.operator==="++"?s+1:s-1;return t.state.env[n]=String(o),e.prefix?o:s}if(e.operand.type==="ArithArrayElement"){let n=e.operand.array,s=t.state.associativeArrays?.has(n),o;if(e.operand.stringKey!==void 0)o=`${n}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")o=`${n}_${e.operand.index.name}`;else if(e.operand.index){let c=W(t,e.operand.index);o=`${n}_${c}`}else return r;let i=Number.parseInt(t.state.env[o]||"0",10)||0,a=e.operator==="++"?i+1:i-1;return t.state.env[o]=String(a),e.prefix?a:i}return r}return en(r,e.operator)}case"ArithTernary":return W(t,e.condition)?W(t,e.consequent):W(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 a=t.state.associativeArrays?.has(r);if(a&&e.subscript.type==="ArithVariable")n=`${r}_${e.subscript.name}`;else if(a){let c=W(t,e.subscript);n=`${r}_${c}`}else{let c=W(t,e.subscript);if(c<0){let l=X(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,o=W(t,e.value),i=wa(s,o,e.operator);return t.state.env[n]=String(i),i}case"ArithGroup":return W(t,e.expression);case"ArithConcat":{let r="";for(let n of e.parts)r+=ba(t,n);return Number.parseInt(r,10)||0}default:return 0}}function ba(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return me(t,e.name);case"ArithBracedExpansion":return De(t,e.content);case"ArithCommandSubst":return"0";case"ArithConcat":{let r="";for(let n of e.parts)r+=ba(t,n);return r}default:return String(W(t,e))}}async function _(t,e){switch(e.type){case"ArithNumber":if(Number.isNaN(e.value))throw new V("value too great for base");return e.value;case"ArithVariable":return Ht(t,e.name);case"ArithNested":return _(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=De(t,e.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=De(t,e.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)return 0;let s=`${n}#${e.value}`;return Ze(s)}case"ArithDynamicNumber":{let n=De(t,e.prefix)+e.suffix;return Ze(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 o=await _(t,e.index);n=`${e.array}_${o}`;let i=t.state.env[n];if(i!==void 0)return Xe(i);if(o===0){let a=t.state.env[e.array];if(a!==void 0)return Xe(a)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(c=>c===e.array||c.startsWith(`${e.array}_`)))throw new fe(`${e.array}[${o}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?Xe(s):0}case"ArithDoubleSubscript":throw new V("double subscript","","");case"ArithNumberSubscript":throw new V(`${e.number}${e.errorToken}: syntax error: invalid arithmetic operator (error token is "${e.errorToken}")`);case"ArithBinary":{if(e.operator==="||")return await _(t,e.left)||await _(t,e.right)?1:0;if(e.operator==="&&")return await _(t,e.left)&&await _(t,e.right)?1:0;let r=await _(t,e.left),n=await _(t,e.right);return Jr(r,n,e.operator)}case"ArithUnary":{let r=await _(t,e.operand);if(e.operator==="++"||e.operator==="--"){if(e.operand.type==="ArithVariable"){let n=e.operand.name,s=Number.parseInt(me(t,n),10)||0,o=e.operator==="++"?s+1:s-1;return t.state.env[n]=String(o),e.prefix?o:s}if(e.operand.type==="ArithArrayElement"){let n=e.operand.array,s=t.state.associativeArrays?.has(n),o;if(e.operand.stringKey!==void 0)o=`${n}_${e.operand.stringKey}`;else if(s&&e.operand.index?.type==="ArithVariable")o=`${n}_${e.operand.index.name}`;else if(e.operand.index){let c=await _(t,e.operand.index);o=`${n}_${c}`}else return r;let i=Number.parseInt(t.state.env[o]||"0",10)||0,a=e.operator==="++"?i+1:i-1;return t.state.env[o]=String(a),e.prefix?a:i}return r}return en(r,e.operator)}case"ArithTernary":return await _(t,e.condition)?await _(t,e.consequent):await _(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 a=t.state.associativeArrays?.has(r);if(a&&e.subscript.type==="ArithVariable")n=`${r}_${e.subscript.name}`;else if(a){let c=await _(t,e.subscript);n=`${r}_${c}`}else{let c=await _(t,e.subscript);if(c<0){let l=X(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,o=await _(t,e.value),i=wa(s,o,e.operator);return t.state.env[n]=String(i),i}case"ArithGroup":return await _(t,e.expression);case"ArithConcat":{let r="";for(let n of e.parts)r+=await Ea(t,n);return Number.parseInt(r,10)||0}default:return 0}}async function Ea(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return me(t,e.name);case"ArithBracedExpansion":return De(t,e.content);case"ArithCommandSubst":return t.execFn?(await t.execFn(e.command)).stdout.trim():"0";case"ArithConcat":{let r="";for(let n of e.parts)r+=await Ea(t,n);return r}default:return String(await _(t,e))}}Z();Z();var F=Object.freeze({stdout:"",stderr:"",exitCode:0});function ce(t=""){return{stdout:t,stderr:"",exitCode:0}}function D(t,e=1){return{stdout:"",stderr:t,exitCode:e}}function k(t,e,r){return{stdout:t,stderr:e,exitCode:r}}function Q(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function ke(t,e,r="",n=""){throw new j(t,e,r,n)}function tn(t,e){if(t.state.loopDepth===0)return F;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
441
- `);r=n}throw new te(r)}async function rn(t,e){let r,n=!1,s=!1,o=0;for(;o<e.length;)if(e[o]==="--"){o++;break}else if(e[o]==="-L")s=!1,o++;else if(e[o]==="-P")s=!0,o++;else if(e[o].startsWith("-")&&e[o]!=="-")o++;else break;let i=e.slice(o);if(i.length===0||i[0]==="~"?r=t.state.env.HOME||"/":i[0]==="-"?(r=t.state.previousDir,n=!0):r=i[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 D(`bash: cd: ${r}: Not a directory
442
- `)}catch{return D(`bash: cd: ${r}: No such file or directory
443
- `)}}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,ce(n?`${u}
444
- `:"")}Z();function nn(t,e){if(t.state.loopDepth===0)return F;if(e.length>1)throw new te(1);let r=1;if(e.length>0){let n=Number.parseInt(e[0],10);if(Number.isNaN(n)||n<1)return D(`bash: continue: ${e[0]}: numeric argument required
445
- `);r=n}throw new ie(r)}function Ue(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function qf(t,e){return t.state.readonlyVars?.has(e)??!1}function Te(t,e,r="bash"){return qf(t,e)?D(`${r}: ${e}: readonly variable
446
- `):null}function xa(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(e)return{name:e[1],isArray:!0,arrayElements:sn(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 Sa(t,e,r={}){let{name:n,isArray:s,arrayElements:o,value:i}=e,{makeReadonly:a=!1,checkReadonly:c=!0}=r;if(c){let l=Te(t,n);if(l)return l}if(s&&o){for(let l=0;l<o.length;l++)t.state.env[`${n}_${l}`]=o[l];t.state.env[`${n}__length`]=String(o.length)}else i!==void 0&&(t.state.env[n]=i);return a&&Ue(t,n),null}function on(t,e){let r=!1,n=!1,s=!1,o=!1,i=!1,a=[];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")o=!0;else if(l==="-p")i=!0;else if(l==="--"){a.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"?o=!0:u==="p"&&(i=!0);else a.push(l)}if(i&&a.length>0){let c="";for(let l of a){let u=t.state.env[l];if(u!==void 0){let f=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');c+=`declare -- ${l}="${f}"
447
- `}}return ce(c)}if(a.length===0&&!i){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}'
448
- `}return ce(c)}for(let c of a){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=Gf(f);for(let[h,p]of d)t.state.env[`${u}_${h}`]=p}else{let d=sn(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&&Ue(t,u);continue}if(c.includes("=")){let u=c.indexOf("="),f=c.slice(0,u),d=c.slice(u+1),h=Te(t,f);if(h)return h;t.state.env[f]=d,s&&Ue(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&&Ue(t,u)}}return F}function sn(t){let e=[],r="",n=!1,s=!1,o=!1;for(let i of t){if(o){r+=i,o=!1;continue}if(i==="\\"){o=!0;continue}if(i==="'"&&!s){n=!n;continue}if(i==='"'&&!n){s=!s;continue}if((i===" "||i===" "||i===`
449
- `)&&!n&&!s){r&&(e.push(r),r="");continue}r+=i}return r&&e.push(r),e}function Gf(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 o=t[r];for(r++;r<t.length&&t[r]!==o;)n+=t[r],r++;t[r]===o&&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 o=t[r];for(r++;r<t.length&&t[r]!==o;)t[r]==="\\"&&r+1<t.length&&r++,s+=t[r],r++;t[r]===o&&r++}else for(;r<t.length&&!/\s/.test(t[r]);)s+=t[r],r++;e.push([n,s])}return e}function an(t,e){let r=!1,n=!1,s=[];for(let o=0;o<e.length;o++){let i=e[o];if(i==="-a")r=!0;else if(i==="-A")n=!0;else if(i==="-p"){if(e.length===1){let a="";for(let c of t.state.readonlyVars||[]){let l=t.state.env[c];l!==void 0&&(a+=`declare -r ${c}="${l}"
450
- `)}return ce(a)}}else if(i==="--"){s.push(...e.slice(o+1));break}else i.startsWith("-")||s.push(i)}for(let o of s){let i=xa(o);if(i.value===void 0&&!i.isArray){Ue(t,i.name);continue}let a=Sa(t,i,{makeReadonly:!0});if(a)return a}return F}Z();async function ln(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 D(`bash: eval: ${s}: invalid option
465
+ `)?c+=d:c+=`\\${d}`,l+=2;continue}if(f==="'"&&!a){u();let d=e.indexOf("'",l+1);if(d===-1){c+=e.slice(l);break}o.push(k.singleQuoted(e.slice(l+1,d))),l=d+1;continue}if(f==='"'){u();let{part:d,endIndex:h}=Dd(t,e,l+1);o.push(d),l=h+1;continue}if(f==="$"&&e[l+1]==="'"){u();let{part:d,endIndex:h}=go(t,e,l+2);o.push(d),l=h;continue}if(f==="$"){u();let{part:d,endIndex:h}=Cn(t,e,l);d&&o.push(d),l=h;continue}if(f==="`"){u();let{part:d,endIndex:h}=t.parseBacktickSubstitution(e,l);o.push(d),l=h;continue}if(f==="~"){let d=l>0?e[l-1]:"";if(l===0||d==="="||s&&d===":"){let p=po(t,e,l),b=e[p];if(b===void 0||b==="/"||b===":"){u();let w=e.slice(l+1,p)||null;o.push({type:"TildeExpansion",user:w}),l=p;continue}}}if(f==="*"||f==="?"||f==="["){u();let{pattern:d,endIndex:h}=yo(t,e,l);o.push({type:"Glob",pattern:d}),l=h;continue}if(f==="{"&&!s){let d=wo(t,e,l,Ue);if(d){u(),o.push(d.part),l=d.endIndex;continue}}c+=f,l++}return u(),o}var le=class t{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;checkIterationLimit(){if(this.parseIterations++,this.parseIterations>co)throw new Te("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}parse(e){if(e.length>un)throw new Te(`Input too large: ${e.length} bytes exceeds limit of ${un}`,1,1);let r=new rr(e);if(this.tokens=r.tokenize(),this.tokens.length>fn)throw new Te(`Too many tokens: ${this.tokens.length} exceeds limit of ${fn}`,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)?mn(this):this.check(m.FOR)?yn(this):this.check(m.WHILE)?gn(this):this.check(m.UNTIL)?wn(this):this.check(m.CASE)?En(this):this.check(m.LPAREN)?bn(this):this.check(m.LBRACE)?xn(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():So(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=Ue(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,l=0,c=!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"?(l++,c=!1):u==="in"&&l>0?c=!0:u==="esac"&&l>0&&(l--,c=!1),u="",p==="("?i>0&&e[i-1]==="$"?s++:c||s++:p===")"?c?c=!1:s--:p===";"&&l>0&&i+1<e.length&&e[i+1]===";"&&(c=!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 c=e[i+1];c==="$"||c==="`"||c==="\\"||c===`
466
+ `||n&&c==='"'?(c!==`
467
+ `&&(a+=c),i+=2):(a+=e[i],i++)}else a+=e[i],i++;i>=e.length&&this.error("unexpected EOF while looking for matching ``'");let l=new t().parse(a);return{part:k.commandSubstitution(l,!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),l=this.parseArithmeticExpression(o);return{part:k.arithmeticExpansion(l),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=An(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 xn(this);if(this.check(m.LPAREN))return bn(this);if(this.check(m.IF))return mn(this);if(this.check(m.FOR))return yn(this);if(this.check(m.WHILE))return gn(this);if(this.check(m.UNTIL))return wn(this);if(this.check(m.CASE))return En(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(;nr(this);){this.checkIterationLimit();let r=this.pos;if(e.push(sr(this)),this.pos===r)break}return e}parseArithmeticExpression(e){return se(this,e)}};function ze(t){return new le().parse(t)}X();var dt=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 l of o)if(this.matchPattern(l,i)){let c=n===-1?l:`${s}/${l}`;r.push(c)}}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}`,l=this.fs.resolvePath(this.cwd,o);try{(await this.fs.stat(l)).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 l=e.slice(i+2,o),c=this.posixClassToRegex(l);a+=c,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 Se(t){switch(t.type){case"ArithCommandSubst":return!0;case"ArithNested":return Se(t.expression);case"ArithBinary":return Se(t.left)||Se(t.right);case"ArithUnary":return Se(t.operand);case"ArithTernary":return Se(t.condition)||Se(t.consequent)||Se(t.alternate);case"ArithAssignment":return Se(t.value);case"ArithGroup":return Se(t.expression);case"ArithArrayElement":return t.index?Se(t.index):!1;case"ArithConcat":return t.parts.some(Se);default:return!1}}function Nn(t){let e=t.operation;return e?!!("word"in e&&e.word&&Le(e.word)||e.type==="PatternReplacement"&&(e.pattern&&Le(e.pattern)||e.replacement&&Le(e.replacement))||e.type==="PatternRemoval"&&e.pattern&&Le(e.pattern)):!1}function ir(t){switch(t.type){case"CommandSubstitution":return!0;case"ArithmeticExpansion":return Se(t.expression.expression);case"DoubleQuoted":return t.parts.some(ir);case"BraceExpansion":return t.items.some(e=>e.type==="Word"&&Le(e.word));case"ParameterExpansion":return Nn(t);default:return!1}}function Le(t){return t.parts.some(ir)}function vn(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 Co(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),vn(a)&&(e=!0))}return{hasQuoted:e,hasCommandSub:r,hasArrayVar:n,hasArrayAtExpansion:s,hasParamExpansion:i}}function Ld(t,e,r,n,s){let i=r??1;i===0&&(i=1);let a=Math.abs(i),o=[],l=0;n?.match(/^-?0\d/)&&(l=Math.max(l,n.replace(/^-/,"").length)),s?.match(/^-?0\d/)&&(l=Math.max(l,s.replace(/^-/,"").length));let c=u=>{if(l>0){let f=u<0,d=String(Math.abs(u)).padStart(l,"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(c(u));else for(let u=t,f=0;u>=e&&f<1e4;u-=a,f++)o.push(c(u));return o}function Fd(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",l=t>="a"&&t<="z",c=e>="A"&&e<="Z",u=e>="a"&&e<="z";if(o&&u||l&&c)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 Nt(t,e,r,n,s){let i=r!==void 0?`..${r}`:"";return typeof t=="number"&&typeof e=="number"?{expanded:Ld(t,e,r,n,s),literal:`{${t}..${e}${i}}`}:typeof t=="string"&&typeof e=="string"?{expanded:Fd(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=Md(t,n);if(i===-1)r+="\\[",n++;else{let a=t.slice(n+1,i);r+=_d(a),n=i+1}}else/[\^$.|+(){}]/.test(s)?(r+=`\\${s}`,n++):(r+=s,n++)}return r}function Md(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 _d(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+=Bd(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 Wd={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 Bd(t){return Wd[t]??""}X();function vt(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 kn(t,e){let r=`${e}_`;for(let n of Object.keys(t.state.env))n.startsWith(r)&&delete t.state.env[n]}function In(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 No(t){return t.startsWith("'")&&t.endsWith("'")||t.startsWith('"')&&t.endsWith('"')?t.slice(1,-1):t}function ar(t){return t.IFS??`
468
+ `}function vo(t){return t.IFS===""}function kt(t){return t.split("").map(e=>/[\\^$.*+?()[\]{}|-]/.test(e)?`\\${e}`:e===" "?"\\t":e===`
469
+ `?"\\n":e).join("")}function Hd(t,e){let r=kt(t);return new RegExp(`[${r}]+`,e)}function Ud(t){let e=kt(t);return new RegExp(`^[${e}]+`)}function zd(t){let e=kt(t);return new RegExp(`[${e}]+$`)}function It(t){let e=t.IFS;return e===void 0?" ":e[0]||""}function ko(t,e){if(e==="")return{words:[t],wordStarts:[0]};let r=[],n=[],s=Hd(e,"g"),i=0,a=t.match(Ud(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 Io(t,e){return e===""?t:t.replace(zd(e),"")}function ie(t,e){return t.state.associativeArrays?.has(e)?In(t,e).map(i=>[i,t.state.env[`${e}_${i}`]]):vt(t,e).map(s=>[s,t.state.env[`${e}_${s}`]])}function Ro(t,e){return t.state.associativeArrays?.has(e)?In(t,e).length>0:vt(t,e).length>0}function Ae(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 l=1;l<=a;l++)o.push(t.state.env[String(l)]||"");return o.join(It(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 Oe(`\${${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=No(o),d=t.state.env[`${a}_${f}`];if(d===void 0&&r&&t.state.options.nounset)throw new xe(`${a}[${o}]`);return d||""}let c;if(/^-?\d+$/.test(o))c=Number.parseInt(o,10);else try{let f=new le,d=se(f,o);c=j(t,d.expression)}catch{let f=t.state.env[o];c=f?Number.parseInt(f,10):0,Number.isNaN(c)&&(c=0)}if(c<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+c;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}_${c}`];if(u===void 0&&r&&t.state.options.nounset)throw new xe(`${a}[${c}]`);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 xe(e);return a||""}let i=t.state.env[e];if(i===void 0&&r&&t.state.options.nounset)throw new xe(e);return i||""}async function $o(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"&&vn(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}]+`),l=[],c="";for(let u=0;u<i.length;u++){let f=i[u];if(!f.splittable)c+=f.value;else{let d=f.value.split(o);for(let h=0;h<d.length;h++)h===0?c+=d[h]:(c!==""&&l.push(c),c=d[h])}}return c!==""&&l.push(c),l}function ge(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Po(t){switch(t.type){case"Literal":return t.value;case"SingleQuoted":return t.value;case"Escaped":return t.value;default:return null}}function Oo(t){switch(t.type){case"SingleQuoted":case"Escaped":case"DoubleQuoted":return!0;case"Literal":return t.value==="";default:return!1}}function Rn(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 tt(t,e,r=!1){return e.map(n=>Fe(t,n,r)).join("")}async function rt(t,e,r=!1){let n=[];for(let s of e)n.push(await $e(t,s));return n.join("")}function Gd(t){return Oo(t)}function Do(t){if(t.parts.length===0)return!0;for(let e of t.parts)if(!Gd(e))return!1;return!0}function To(t){return t.replace(/([*?[\]\\])/g,"\\$1")}function Lo(t,e,r=!1){let n=Po(e);if(n!==null)return n;switch(e.type){case"ParameterExpansion":return Bo(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 Fe(t,e,r=!1){let n=Lo(t,e,r);if(n!==null)return n;switch(e.type){case"DoubleQuoted":{let s=[];for(let i of e.parts)s.push(Fe(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=Nt(i.start,i.end,i.step,i.startStr,i.endStr);if(a.expanded)s.push(...a.expanded);else return a.literal}else s.push(or(t,i.word));return s.join(" ")}default:return""}}function or(t,e){let r=e.parts,n=r.length;if(n===1)return Fe(t,r[0]);let s=[];for(let i=0;i<n;i++)s.push(Fe(t,r[i]));return s.join("")}async function Q(t,e){return Le(e)?Wo(t,e):or(t,e)}function lr(t){for(let e of t)if(e.type==="BraceExpansion"||e.type==="DoubleQuoted"&&lr(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"&&Le(r.word))return!0}if(ir(e))return!0}return!1}var Fo=1e4,ht=1e5;function Mo(t,e,r={count:0}){if(r.count>ht)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=Nt(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=Mo(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>Fo||r.count>ht)return n;let c=[];for(let u of n)for(let f of i){if(r.count++,r.count>ht)return c.length>0?c:n;c.push([...u,f])}n=c}else{let i=Fe(t,s);for(let a of n)r.count++,a.push(i)}return n}function qd(t,e){let r=e.parts;return lr(r)?Mo(t,r).map(s=>s.join("")):[or(t,e)]}async function _o(t,e,r={count:0}){if(r.count>ht)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=Nt(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 _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>Fo||r.count>ht)return n;let c=[];for(let u of n)for(let f of i){if(r.count++,r.count>ht)return c.length>0?c:n;c.push([...u,f])}n=c}else{let i=await $e(t,s);for(let a of n)r.count++,a.push(i)}return n}async function Vd(t,e){let r=e.parts;return lr(r)?(await _o(t,r)).map(s=>s.join("")):[await Q(t,e)]}async function Rt(t,e){let r=e.parts,{hasQuoted:n,hasCommandSub:s,hasArrayVar:i,hasArrayAtExpansion:a,hasParamExpansion:o}=Co(r),c=lr(r)?jd(r)?await Vd(t,e):qd(t,e):null;if(c&&c.length>1){let d=[];for(let h of c)if(!n&&/[*?[]/.test(h)){let b=await new dt(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)&&!vo(t.state.env)){let d=ar(t.state.env),h=kt(d),p=await $o(t,r,d,h,$e),b=[],w=new dt(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=Le(e)?await Wo(t,e):or(t,e);if(!n&&/[*?[]/.test(f)){let h=await new dt(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 Wo(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(await $e(t,r[i]));return s.join("")}async function $e(t,e){if(e.type==="ParameterExpansion"&&Nn(e))return Zd(t,e);let r=Lo(t,e);if(r!==null)return r;switch(e.type){case"DoubleQuoted":{let n=[];for(let s of e.parts)n.push(await $e(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=Nt(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 Bo(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=Ae(t,n,!i);if(!s)return a;let o=!(n in t.state.env),l=a==="";switch(s.type){case"DefaultValue":return(o||s.checkEmpty&&l)&&s.word?tt(t,s.word.parts,r):a;case"AssignDefault":{if((o||s.checkEmpty&&l)&&s.word){let u=tt(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&&l){let u=s.word?tt(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&&l)&&s.word?tt(t,s.word.parts,r):"";case"Length":{let c=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(c){let u=ie(t,c[1]);return String(u.length)}if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(n)&&Ro(t,n)){let u=t.state.env[`${n}_0`]||"";return String(u.length)}return String(a.length)}case"LengthSliceError":throw new Oe(n);case"Substring":{let c=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=c===0?[b,...p]:p,g=c===0?0:c-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=c;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=c;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 c="";if(s.pattern)for(let f of s.pattern.parts)if(f.type==="Glob")c+=ye(f.pattern,s.greedy);else if(f.type==="Literal")c+=ye(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")c+=ge(f.value);else if(f.type==="DoubleQuoted"){let d=tt(t,f.parts);c+=ge(d)}else if(f.type==="ParameterExpansion"){let d=Fe(t,f);c+=ye(d,s.greedy)}else{let d=Fe(t,f);c+=ge(d)}if(s.side==="prefix")return a.replace(new RegExp(`^${c}`),"");let u=new RegExp(`${c}$`);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 c="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")c+=ye(d.pattern,!0);else if(d.type==="Literal")c+=ye(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")c+=ge(d.value);else if(d.type==="DoubleQuoted"){let h=tt(t,d.parts);c+=ge(h)}else if(d.type==="ParameterExpansion"){let h=Fe(t,d);c+=ye(h,!0)}else{let h=Fe(t,d);c+=ge(h)}let u=s.replacement?tt(t,s.replacement.parts):"";if(c==="")return a;s.anchor==="start"?c=`^${c}`:s.anchor==="end"&&(c=`${c}$`);let f=s.all?"g":"";try{let d=new RegExp(c,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 c=n.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(c&&s.operator==="Q")return ie(t,c[1]).map(([,d])=>Rn(d)).join(" ");switch(s.operator){case"Q":return Rn(a);case"P":return a;case"a":return"";case"A":return`${n}=${Rn(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 Ae(t,a);case"ArrayKeys":{let u=ie(t,s.array).map(([f])=>String(f));return s.star?u.join(It(t.state.env)):u.join(" ")}case"VarNamePrefix":{let c=Object.keys(t.state.env).filter(u=>u.startsWith(s.prefix)&&!u.includes("__")).sort();return s.star?c.join(It(t.state.env)):c.join(" ")}default:return a}}async function Zd(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=Ae(t,n,!i);if(!s)return a;let o=!(n in t.state.env),l=a==="";switch(s.type){case"DefaultValue":return(o||s.checkEmpty&&l)&&s.word?rt(t,s.word.parts,r):a;case"AssignDefault":{if((o||s.checkEmpty&&l)&&s.word){let u=await 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=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&&l){let u=s.word?await rt(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&&l)&&s.word?rt(t,s.word.parts,r):"";case"PatternRemoval":{let c="";if(s.pattern)for(let f of s.pattern.parts)if(f.type==="Glob")c+=ye(f.pattern,s.greedy);else if(f.type==="Literal")c+=ye(f.value,s.greedy);else if(f.type==="SingleQuoted"||f.type==="Escaped")c+=ge(f.value);else if(f.type==="DoubleQuoted"){let d=await rt(t,f.parts);c+=ge(d)}else if(f.type==="ParameterExpansion"){let d=await $e(t,f);c+=ye(d,s.greedy)}else{let d=await $e(t,f);c+=ge(d)}if(s.side==="prefix")return a.replace(new RegExp(`^${c}`),"");let u=new RegExp(`${c}$`);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 c="";if(s.pattern)for(let d of s.pattern.parts)if(d.type==="Glob")c+=ye(d.pattern,!0);else if(d.type==="Literal")c+=ye(d.value,!0);else if(d.type==="SingleQuoted"||d.type==="Escaped")c+=ge(d.value);else if(d.type==="DoubleQuoted"){let h=await rt(t,d.parts);c+=ge(h)}else if(d.type==="ParameterExpansion"){let h=await $e(t,d);c+=ye(h,!0)}else{let h=await $e(t,d);c+=ge(h)}let u=s.replacement?await rt(t,s.replacement.parts):"";if(c==="")return a;s.anchor==="start"?c=`^${c}`:s.anchor==="end"&&(c=`${c}$`);let f=s.all?"g":"";try{let d=new RegExp(c,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 Bo(t,e,r)}}function $n(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 Ho(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 Pn(t,e){switch(e){case"-":return-t;case"+":return+t;case"!":return t===0?1:0;case"~":return~t;default:return t}}function Qd(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:Ae(t,e)}function pt(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}=De(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 cr(t,e,r=new Set){if(r.has(e))return 0;r.add(e);let n=Qd(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 cr(t,i,r);try{let a=new le,{expr:o}=De(a,i,0);return Ce(t,o,r)}catch{return 0}}function Ce(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 cr(t,e.name,r);case"ArithBinary":{if(e.operator==="||")return Ce(t,e.left,r)||Ce(t,e.right,r)?1:0;if(e.operator==="&&")return Ce(t,e.left,r)&&Ce(t,e.right,r)?1:0;let n=Ce(t,e.left,r),s=Ce(t,e.right,r);return $n(n,s,e.operator)}case"ArithUnary":{let n=Ce(t,e.operand,r);return Pn(n,e.operator)}case"ArithTernary":return Ce(t,e.condition,r)?Ce(t,e.consequent,r):Ce(t,e.alternate,r);case"ArithGroup":return Ce(t,e.expression,r);default:return j(t,e)}}function Ge(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 Ae(t,e);let i=e.slice(0,n),a=e.slice(n+s.length),o=t.state.env[i],l=o===void 0,c=o==="",u=s.startsWith(":");switch(s){case":-":case"-":return l||u&&c?a:o||"";case":=":case"=":return l||u&&c?(t.state.env[i]=a,a):o||"";case":+":case"+":return!(l||u&&c)?a:"";case":?":case"?":{if(l||u&&c)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 cr(t,e.name);case"ArithNested":return j(t,e.expression);case"ArithCommandSubst":return 0;case"ArithBracedExpansion":{let r=Ge(t,e.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=Ge(t,e.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)return 0;let s=`${n}#${e.value}`;return ft(s)}case"ArithDynamicNumber":{let n=Ge(t,e.prefix)+e.suffix;return ft(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
476
+ `,0;let c=Math.max(...o.map(([u])=>typeof u=="number"?u:0))+1+i;if(c<0)return t.state.expansionStderr=(t.state.expansionStderr||"")+`bash: ${e.array}: bad array subscript
477
+ `,0;i=c}n=`${e.array}_${i}`;let a=t.state.env[n];if(a!==void 0)return pt(a);if(i===0){let o=t.state.env[e.array];if(o!==void 0)return pt(o)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(l=>l===e.array||l.startsWith(`${e.array}_`)))throw new xe(`${e.array}[${i}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?pt(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 $n(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(Ae(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 l=j(t,e.operand.index);i=`${n}_${l}`}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 Pn(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 l=j(t,e.subscript);n=`${r}_${l}`}else{let l=j(t,e.subscript);if(l<0){let c=ie(t,r);c.length>0&&(l=Math.max(...c.map(([f])=>typeof f=="number"?f:0))+1+l)}n=`${r}_${l}`}}let s=Number.parseInt(t.state.env[n]||"0",10)||0,i=j(t,e.value),a=Ho(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+=Uo(t,n);return Number.parseInt(r,10)||0}default:return 0}}function Uo(t,e){switch(e.type){case"ArithNumber":return String(e.value);case"ArithVariable":return Ae(t,e.name);case"ArithBracedExpansion":return Ge(t,e.content);case"ArithCommandSubst":return"0";case"ArithConcat":{let r="";for(let n of e.parts)r+=Uo(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 cr(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=Ge(t,e.content);return Number.parseInt(r,10)||0}case"ArithDynamicBase":{let r=Ge(t,e.baseExpr),n=Number.parseInt(r,10);if(n<2||n>64)return 0;let s=`${n}#${e.value}`;return ft(s)}case"ArithDynamicNumber":{let n=Ge(t,e.prefix)+e.suffix;return ft(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 pt(a);if(i===0){let o=t.state.env[e.array];if(o!==void 0)return pt(o)}if(t.state.options.nounset&&!Object.keys(t.state.env).some(l=>l===e.array||l.startsWith(`${e.array}_`)))throw new xe(`${e.array}[${i}]`);return 0}else return 0;let s=t.state.env[n];return s!==void 0?pt(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 $n(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(Ae(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 l=await q(t,e.operand.index);i=`${n}_${l}`}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 Pn(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 l=await q(t,e.subscript);n=`${r}_${l}`}else{let l=await q(t,e.subscript);if(l<0){let c=ie(t,r);c.length>0&&(l=Math.max(...c.map(([f])=>typeof f=="number"?f:0))+1+l)}n=`${r}_${l}`}}let s=Number.parseInt(t.state.env[n]||"0",10)||0,i=await q(t,e.value),a=Ho(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 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 Ae(t,e.name);case"ArithBracedExpansion":return Ge(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 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 P(t,e,r){return{stdout:t,stderr:e,exitCode:r}}function re(t){return{stdout:"",stderr:"",exitCode:t?0:1}}function Me(t,e,r="",n=""){throw new W(t,e,r,n)}function On(t,e){if(t.state.loopDepth===0)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 Dn(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 l=(r.startsWith("/")?r:`${t.state.cwd}/${r}`).split("/").filter(f=>f&&f!=="."),c="";for(let f of l)if(f==="..")c=c.split("/").slice(0,-1).join("/")||"/";else{c=c?`${c}/${f}`:`/${f}`;try{if(!(await t.fs.stat(c)).isDirectory)return F(`bash: cd: ${r}: Not a directory
479
+ `)}catch{return F(`bash: cd: ${r}: No such file or directory
480
+ `)}}let u=c||"/";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)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 nt(t,e){t.state.readonlyVars=t.state.readonlyVars||new Set,t.state.readonlyVars.add(e)}function Kd(t,e){return t.state.readonlyVars?.has(e)??!1}function je(t,e,r="bash"){return Kd(t,e)?F(`${r}: ${e}: readonly variable
483
+ `):null}function Go(t){let e=t.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(e)return{name:e[1],isArray:!0,arrayElements:Ln(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 jo(t,e,r={}){let{name:n,isArray:s,arrayElements:i,value:a}=e,{makeReadonly:o=!1,checkReadonly:l=!0}=r;if(l){let c=je(t,n);if(c)return c}if(s&&i){for(let c=0;c<i.length;c++)t.state.env[`${n}_${c}`]=i[c];t.state.env[`${n}__length`]=String(i.length)}else a!==void 0&&(t.state.env[n]=a);return o&&nt(t,n),null}function Fn(t,e){let r=!1,n=!1,s=!1,i=!1,a=!1,o=[];for(let l=0;l<e.length;l++){let c=e[l];if(c==="-a")r=!0;else if(c==="-A")n=!0;else if(c==="-r")s=!0;else if(c==="-x")i=!0;else if(c==="-p")a=!0;else if(c==="--"){o.push(...e.slice(l+1));break}else if(c.startsWith("-"))for(let u of c.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(c)}if(a&&o.length>0){let l="";for(let c of o){let u=t.state.env[c];if(u!==void 0){let f=u.replace(/\\/g,"\\\\").replace(/"/g,'\\"');l+=`declare -- ${c}="${f}"
484
+ `}}return we(l)}if(o.length===0&&!a){let l="",c=Object.entries(t.state.env).filter(([u])=>!u.startsWith("BASH_")).sort(([u],[f])=>u.localeCompare(f));for(let[u,f]of c){let d=f.replace(/'/g,"'\\''");l+=`declare -- ${u}='${d}'
485
+ `}return we(l)}for(let l of o){let c=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)=\((.*)\)$/s);if(c){let u=c[1],f=c[2];if(n&&(t.state.associativeArrays??=new Set,t.state.associativeArrays.add(u)),n&&f.includes("[")){let d=Xd(f);for(let[h,p]of d)t.state.env[`${u}_${h}`]=p}else{let d=Ln(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&&nt(t,u);continue}if(l.includes("=")){let u=l.indexOf("="),f=l.slice(0,u),d=l.slice(u+1),h=je(t,f);if(h)return h;t.state.env[f]=d,s&&nt(t,f)}else{let u=l;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&&nt(t,u)}}return G}function Ln(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 Xd(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 Mn(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 l of t.state.readonlyVars||[]){let c=t.state.env[l];c!==void 0&&(o+=`declare -r ${l}="${c}"
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=Go(i);if(a.value===void 0&&!a.isArray){nt(t,a.name);continue}let o=jo(t,a,{makeReadonly:!0});if(o)return o}return G}X();async function _n(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
451
488
  eval: usage: eval [arg ...]
452
- `,2)}if(r.length===0)return F;let n=r.join(" ");if(n.trim()==="")return F;try{let s=Oe(n);return t.executeScript(s)}catch(s){if(s instanceof te||s instanceof ie||s instanceof re||s instanceof z)throw s;if(s.name==="ParseException")return D(`bash: eval: ${s.message}
453
- `);throw s}}Z();function cn(t,e){let r,n="";if(e.length===0)r=t.state.lastExitCode;else{let s=e[0],o=Number.parseInt(s,10);s===""||Number.isNaN(o)||!/^-?\d+$/.test(s)?(n=`bash: exit: ${s}: numeric argument required
454
- `,r=2):r=(o%256+256)%256}throw new z(r,"",n)}function un(t,e){let r=!1,n=[];for(let i of e)i==="-n"?r=!0:i==="-p"||i==="--"||n.push(i);if(n.length===0&&!r){let i="",a=Object.entries(t.state.env).filter(([c])=>!c.startsWith("BASH_ALIAS_")).sort(([c],[l])=>c.localeCompare(l));for(let[c,l]of a){let u=l.replace(/'/g,"'\\''");i+=`declare -x ${c}='${u}'
455
- `}return ce(i)}if(r){for(let i of n){let a=i.split("=")[0];delete t.state.env[a]}return F}let s="",o=0;for(let i of n){let a,c;if(i.includes("=")){let l=i.indexOf("=");a=i.slice(0,l),c=i.slice(l+1)}else a=i;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(a)){s+=`bash: export: \`${i}': not a valid identifier
456
- `,o=1;continue}c!==void 0?t.state.env[a]=c:a in t.state.env||(t.state.env[a]="")}return k("",s,o)}function Vf(t){let e=[],r="",n=0;for(let s of t){for(let o of s)o==="("?n++:o===")"&&n--;r?r+=` ${s}`:r=s,n===0&&(e.push(r),r="")}return r&&e.push(r),e}async function fn(t,e){if(e.length===0)return D(`bash: let: expression expected
457
- `);let r=Vf(e),n=0;for(let s of r)try{let i=Oe(`(( ${s} ))`).statements[0];if(i&&i.pipelines.length>0&&i.pipelines[0].commands.length>0){let a=i.pipelines[0].commands[0];a.type==="ArithmeticCommand"&&(n=await _(t,a.expression.expression))}}catch(o){return D(`bash: let: ${s}: ${o.message}
458
- `)}return k("","",n===0?1:0)}function Zf(t,e){let r=t.state.env.HOME||"/home/user";return e.split(":").map(o=>o==="~"?r:o==="~root"?"/root":o.startsWith("~/")?r+o.slice(1):o.startsWith("~root/")?`/root${o.slice(5)}`:o).join(":")}function dn(t,e){if(t.state.localScopes.length===0)return D(`bash: local: can only be used in a function
459
- `);let r=t.state.localScopes[t.state.localScopes.length-1],n="",s=0;for(let o of e){let i,a;if(o.includes("=")){let c=o.indexOf("=");i=o.slice(0,c),a=Zf(t,o.slice(c+1))}else i=o;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i)){n+=`bash: local: \`${o}': not a valid identifier
460
- `,s=1;continue}r.has(i)||r.set(i,t.state.env[i]),a!==void 0&&(t.state.env[i]=a)}return k("",n,s)}function hn(t,e,r){let n=!1,s=`
461
- `,o="",i=-1,a=null,c=[],l=0,u=!1;for(;l<e.length;){let w=e[l];w==="-r"?n=!0:w==="-d"&&l+1<e.length?(s=e[l+1],l++):w==="-p"&&l+1<e.length?(o=e[l+1],l++):w==="-n"&&l+1<e.length?(i=Number.parseInt(e[l+1],10),(Number.isNaN(i)||i<0)&&(u=!0,i=0),l++):w==="-a"&&l+1<e.length?(a=e[l+1],l++):w==="-t"?l+1<e.length&&!e[l+1].startsWith("-")&&l++:w==="-s"||w.startsWith("-")||c.push(w),l++}if(u)return k("","",1);c.length===0&&a===null&&c.push("REPLY");let f=r;!f&&t.state.groupStdin!==void 0&&(f=t.state.groupStdin);let d="",h=0,p=!0;if(i>=0){for(let w=0;w<f.length&&w<i;w++){let E=f[w];if(E===s){h=w+1;break}d+=E,h=w+1}t.state.groupStdin!==void 0&&!r&&(t.state.groupStdin=f.substring(h))}else{let w=f;for(h=0;;){let E=w.indexOf(s);if(E!==-1){let $=w.substring(0,E);if(h+=E+s.length,w=w.substring(E+s.length),!n&&$.endsWith("\\")){d+=$.slice(0,-1);continue}d+=$,p=!0;break}else if(w.length>0){d+=w,h+=w.length,p=!1,w="";break}else{if(d.length===0){for(let $ of c)t.state.env[$]="";return a&&Kr(t,a),k("","",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 G;let n=r.join(" ");if(n.trim()==="")return G;try{let s=ze(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 Wn(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 Bn(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(([l])=>!l.startsWith("BASH_ALIAS_")).sort(([l],[c])=>l.localeCompare(c));for(let[l,c]of o){let u=c.replace(/'/g,"'\\''");a+=`declare -x ${l}='${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,l;if(a.includes("=")){let c=a.indexOf("=");o=a.slice(0,c),l=a.slice(c+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}l!==void 0?t.state.env[o]=l:o in t.state.env||(t.state.env[o]="")}return P("",s,i)}function Yd(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 Hn(t,e){if(e.length===0)return F(`bash: let: expression expected
494
+ `);let r=Yd(e),n=0;for(let s of r)try{let a=ze(`(( ${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 P("","",n===0?1:0)}function Jd(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 Un(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 l=i.indexOf("=");a=i.slice(0,l),o=Jd(t,i.slice(l+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 P("",n,s)}function zn(t,e,r){let n=!1,s=`
498
+ `,i="",a=-1,o=null,l=[],c=0,u=!1;for(;c<e.length;){let E=e[c];E==="-r"?n=!0:E==="-d"&&c+1<e.length?(s=e[c+1],c++):E==="-p"&&c+1<e.length?(i=e[c+1],c++):E==="-n"&&c+1<e.length?(a=Number.parseInt(e[c+1],10),(Number.isNaN(a)||a<0)&&(u=!0,a=0),c++):E==="-a"&&c+1<e.length?(o=e[c+1],c++):E==="-t"?c+1<e.length&&!e[c+1].startsWith("-")&&c++:E==="-s"||E.startsWith("-")||l.push(E),c++}if(u)return P("","",1);l.length===0&&o===null&&l.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 l)t.state.env[S]="";return o&&kn(t,o),P("","",1)}p=!1;break}}t.state.groupStdin!==void 0&&!r&&(t.state.groupStdin=f.substring(h))}if(s===`
462
499
  `&&d.endsWith(`
463
- `)&&(d=d.slice(0,-1)),n||(d=d.replace(/\\(.)/g,"$1")),c.length===1&&c[0]==="REPLY")return t.state.env.REPLY=d,k("","",p?0:1);let b=Lt(t.state.env),{words:g,wordStarts:y}=sa(d,b);if(a){Kr(t,a);for(let w=0;w<g.length;w++)t.state.env[`${a}_${w}`]=g[w];return k("","",p?0:1)}for(let w=0;w<c.length;w++){let E=c[w];if(w<c.length-1)t.state.env[E]=g[w]??"";else if(w<y.length){let $=ia(d.substring(y[w]),b);t.state.env[E]=$}else t.state.env[E]=""}return k("","",p?0:1)}Z();function pn(t,e){if(t.state.callDepth===0&&t.state.sourceDepth===0)return D("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 D(`bash: return: ${n}: numeric argument required
464
- `,2);r=(s%256+256)%256}throw new re(r)}function Qf(t){return/^[a-zA-Z0-9_/.:-]*$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var Bt=`set: usage: set [-eux] [+eux] [-o option] [+o option]
500
+ `)&&(d=d.slice(0,-1)),n||(d=d.replace(/\\(.)/g,"$1")),l.length===1&&l[0]==="REPLY")return t.state.env.REPLY=d,P("","",p?0:1);let b=ar(t.state.env),{words:w,wordStarts:g}=ko(d,b);if(o){kn(t,o);for(let E=0;E<w.length;E++)t.state.env[`${o}_${E}`]=w[E];return P("","",p?0:1)}for(let E=0;E<l.length;E++){let x=l[E];if(E<l.length-1)t.state.env[x]=w[E]??"";else if(E<g.length){let S=Io(d.substring(g[E]),b);t.state.env[x]=S}else t.state.env[x]=""}return P("","",p?0:1)}X();function Gn(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 eh(t){return/^[a-zA-Z0-9_/.:-]*$/.test(t)?t:`'${t.replace(/'/g,"'\\''")}'`}var ur=`set: usage: set [-eux] [+eux] [-o option] [+o option]
465
502
  Options:
466
503
  -e Exit immediately if a command exits with non-zero status
467
504
  +e Disable -e
@@ -477,65 +514,65 @@ Options:
477
514
  +o pipefail Disable pipefail
478
515
  -o xtrace Same as -x
479
516
  +o xtrace Disable xtrace
480
- `,Ca={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},Aa={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},$a=["errexit","nounset","pipefail","verbose","xtrace"],Na=["allexport","braceexpand","emacs","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","noclobber","noexec","noglob","nolog","notify","onecmd","physical","posix","privileged","vi"];function va(t,e,r){e!==null&&(t.state.options[e]=r)}function Kf(t,e){return e+1<t.length&&!t[e+1].startsWith("-")&&!t[e+1].startsWith("+")}function gn(t,e){if(e.includes("--help"))return ce(Bt);if(e.length===0){let n=Object.entries(t.state.env).filter(([s])=>/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(s)).sort(([s],[o])=>s.localeCompare(o)).map(([s,o])=>`${s}=${Qf(o)}`).join(`
481
- `);return ce(n?`${n}
482
- `:"")}let r=0;for(;r<e.length;){let n=e[r];if((n==="-o"||n==="+o")&&Kf(e,r)){let s=e[r+1];if(!(s in Aa))return D(`bash: set: ${s}: invalid option name
483
- ${Bt}`);va(t,Aa[s],n==="-o"),r+=2;continue}if(n==="-o"){let s=$a.map(a=>`${a.padEnd(16)}${t.state.options[a]?"on":"off"}`),o=Na.map(a=>`${a.padEnd(16)}off`),i=[...s,...o].sort();return ce(`${i.join(`
517
+ `,qo={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},Vo={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},Zo=["errexit","nounset","pipefail","verbose","xtrace"],Qo=["allexport","braceexpand","emacs","errtrace","functrace","hashall","histexpand","history","ignoreeof","interactive-comments","keyword","monitor","noclobber","noexec","noglob","nolog","notify","onecmd","physical","posix","privileged","vi"];function Ko(t,e,r){e!==null&&(t.state.options[e]=r)}function th(t,e){return e+1<t.length&&!t[e+1].startsWith("-")&&!t[e+1].startsWith("+")}function qn(t,e){if(e.includes("--help"))return we(ur);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}=${eh(i)}`).join(`
518
+ `);return we(n?`${n}
519
+ `:"")}let r=0;for(;r<e.length;){let n=e[r];if((n==="-o"||n==="+o")&&th(e,r)){let s=e[r+1];if(!(s in Vo))return F(`bash: set: ${s}: invalid option name
520
+ ${ur}`);Ko(t,Vo[s],n==="-o"),r+=2;continue}if(n==="-o"){let s=Zo.map(o=>`${o.padEnd(16)}${t.state.options[o]?"on":"off"}`),i=Qo.map(o=>`${o.padEnd(16)}off`),a=[...s,...i].sort();return we(`${a.join(`
484
521
  `)}
485
- `)}if(n==="+o"){let s=$a.map(a=>`set ${t.state.options[a]?"-o":"+o"} ${a}`),o=Na.map(a=>`set +o ${a}`),i=[...s,...o].sort();return ce(`${i.join(`
522
+ `)}if(n==="+o"){let s=Zo.map(o=>`set ${t.state.options[o]?"-o":"+o"} ${o}`),i=Qo.map(o=>`set +o ${o}`),a=[...s,...i].sort();return we(`${a.join(`
486
523
  `)}
487
- `)}if(n.length>1&&(n[0]==="-"||n[0]==="+")&&n[1]!=="-"){let s=n[0]==="-";for(let o=1;o<n.length;o++){let i=n[o];if(!(i in Ca))return D(`bash: set: ${n[0]}${i}: invalid option
488
- ${Bt}`);va(t,Ca[i],s)}r++;continue}if(n==="--")return mn(t,e.slice(r+1)),F;if(n==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,r+1<e.length)return mn(t,e.slice(r+1)),F;r++;continue}if(n==="+"){r++;continue}return n.startsWith("-")||n.startsWith("+")?D(`bash: set: ${n}: invalid option
489
- ${Bt}`):(mn(t,e.slice(r)),F)}return F}function mn(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 yn(t,e){let r=1;if(e.length>0){let i=Number.parseInt(e[0],10);if(Number.isNaN(i)||i<0)return D(`bash: shift: ${e[0]}: numeric argument required
490
- `);r=i}let n=Number.parseInt(t.state.env["#"]||"0",10);if(r>n)return D(`bash: shift: shift count out of range
491
- `);if(r===0)return F;let s=[];for(let i=1;i<=n;i++)s.push(t.state.env[String(i)]||"");let o=s.slice(r);for(let i=1;i<=n;i++)delete t.state.env[String(i)];for(let i=0;i<o.length;i++)t.state.env[String(i+1)]=o[i];return t.state.env["#"]=String(o.length),t.state.env["@"]=o.join(" "),F}Z();async function wn(t,e){let r=e;if(r.length>0&&r[0]==="--"&&(r=r.slice(1)),r.length===0)return k("",`bash: source: filename argument required
492
- `,2);let n=r[0],s=null,o=null;if(n.includes("/")){let c=t.fs.resolvePath(t.state.cwd,n);try{o=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;o=await t.fs.readFile(f),s=f;break}catch{}}if(o===null){let u=t.fs.resolvePath(t.state.cwd,n);try{o=await t.fs.readFile(u),s=u}catch{}}}if(o===null)return D(`bash: ${n}: No such file or directory
493
- `);let i={};if(r.length>1){for(let l=1;l<=9;l++)i[String(l)]=t.state.env[String(l)];i["#"]=t.state.env["#"],i["@"]=t.state.env["@"];let c=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 a=()=>{if(t.state.sourceDepth--,r.length>1)for(let[c,l]of Object.entries(i))l===void 0?delete t.state.env[c]:t.state.env[c]=l};t.state.sourceDepth++;try{let c=Oe(o),l=await t.executeScript(c);return a(),l}catch(c){if(a(),c instanceof z)throw c;if(c instanceof re)return k(c.stdout,c.stderr,c.exitCode);if(c.name==="ParseException")return D(`bash: ${n}: ${c.message}
494
- `);throw c}}function bn(t,e){let r="variable",n="",s=0;for(let o of e){if(o==="-v"){r="variable";continue}if(o==="-f"){r="function";continue}if(r==="function"){t.state.functions.delete(o);continue}let i=o.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(i){let a=i[1],c=i[2];if(c==="@"||c==="*"){let u=X(t,a);for(let[f]of u)delete t.state.env[`${a}_${f}`];delete t.state.env[a];continue}let l;if(/^-?\d+$/.test(c))l=Number.parseInt(c,10);else{let u=t.state.env[c];l=u?Number.parseInt(u,10):0,Number.isNaN(l)&&(l=0)}if(l<0){let u=X(t,a),f=u.length;if(f===0){n+=`bash: unset: [${l}]: bad array subscript
495
- `,s=1;continue}let d=f+l;if(d<0){n+=`bash: unset: [${l}]: bad array subscript
496
- `,s=1;continue}let h=u[d][0];delete t.state.env[`${a}_${h}`];continue}delete t.state.env[`${a}_${l}`];continue}delete t.state.env[o],t.state.functions.delete(o)}return k("",n,s)}function En(t,e){return t.fs.resolvePath(t.state.cwd,e)}var Xf=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function zt(t){return Xf.includes(t)}async function Ut(t,e,r){let n=En(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(o=>n===o||n.endsWith(o));case"-p":return!1;case"-S":return!1;case"-t":return!1;case"-N":return t.fs.exists(n);default:return!1}}var Yf=["-nt","-ot","-ef"];function jt(t){return Yf.includes(t)}async function qt(t,e,r,n){let s=En(t,r),o=En(t,n);switch(e){case"-nt":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime>a.mtime}catch{return!1}case"-ot":try{let i=await t.fs.stat(s),a=await t.fs.stat(o);return i.mtime<a.mtime}catch{return!1}case"-ef":try{if(!await t.fs.exists(s)||!await t.fs.exists(o))return!1;let i=t.fs.resolvePath(t.state.cwd,s),a=t.fs.resolvePath(t.state.cwd,o);return i===a}catch{return!1}default:return!1}}var Jf=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function Gt(t){return Jf.has(t)}function Vt(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 Zt(t){return t==="="||t==="=="||t==="!="}function Qt(t,e,r,n=!1){let s=n?Kt(e,r):e===r;return t==="!="?!s:s}var ed=new Set(["-z","-n"]);function Xt(t){return ed.has(t)}function Yt(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function Jt(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,(i,a)=>t.state.env[a]||"");let o;if(/^-?\d+$/.test(s))o=Number.parseInt(s,10);else try{let i=Function(`"use strict"; return (${s})`)();o=typeof i=="number"?Math.floor(i):0}catch{let i=t.state.env[s];o=i?Number.parseInt(i,10):0}if(o<0){let i=it(t,n);if(i.length===0||(o=Math.max(...i)+1+o,o<0))return!1}return`${n}_${o}`in t.state.env}return e in t.state.env}async function Me(t,e){switch(e.type){case"CondBinary":{let r=await U(t,e.left),n=await U(t,e.right),s=e.right.parts.length>0&&e.right.parts.every(o=>o.type==="SingleQuoted"||o.type==="DoubleQuoted"||o.type==="Escaped");if(Zt(e.operator))return Qt(e.operator,r,n,!s);if(Gt(e.operator))return Vt(e.operator,Ia(t,r),Ia(t,n));if(jt(e.operator))return qt(t,e.operator,r,n);switch(e.operator){case"=~":try{let o=new RegExp(n),i=r.match(o);if(i){t.state.env.BASH_REMATCH=i[0];for(let a=1;a<i.length;a++)t.state.env[`BASH_REMATCH_${a}`]=i[a]||""}return i!==null}catch{throw new Error("syntax error in regular expression")}case"<":return r<n;case">":return r>n;default:return!1}}case"CondUnary":{let r=await U(t,e.operand);return zt(e.operator)?Ut(t,e.operator,r):Xt(e.operator)?Yt(e.operator,r):e.operator==="-v"?Jt(t,r):e.operator==="-o"?Sn(t,r):!1}case"CondNot":return!await Me(t,e.operand);case"CondAnd":return await Me(t,e.left)?await Me(t,e.right):!1;case"CondOr":return await Me(t,e.left)?!0:await Me(t,e.right);case"CondGroup":return await Me(t,e.expression);case"CondWord":return await U(t,e.word)!=="";default:return!1}}async function Ye(t,e){if(e.length===0)return k("","",1);if(e.length===1)return Q(!!e[0]);if(e.length===2){let n=e[0],s=e[1];return n==="("?D(`test: '(' without matching ')'
497
- `,2):zt(n)?Q(await Ut(t,n,s)):Xt(n)?Q(Yt(n,s)):n==="!"?Q(!s):n==="-v"?Q(Jt(t,s)):n==="-o"?Q(Sn(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"?D(`test: ${n}: unary operator expected
498
- `,2):k("","",1)}if(e.length===3){let n=e[0],s=e[1],o=e[2];if(Zt(s))return Q(Qt(s,n,o));if(Gt(s)){let i=er(n),a=er(o);return!i.valid||!a.valid?k("","",2):Q(Vt(s,i.value,a.value))}if(jt(s))return Q(await qt(t,s,n,o));switch(s){case"-a":return Q(n!==""&&o!=="");case"-o":return Q(n!==""||o!=="");case">":return Q(n>o);case"<":return Q(n<o)}if(n==="!"){let i=await Ye(t,[s,o]);return k("",i.stderr,i.exitCode===0?1:i.exitCode===1?0:i.exitCode)}if(n==="("&&o===")")return Q(s!=="")}if(e.length===4){if(e[0]==="!"){let n=await Ye(t,e.slice(1));return k("",n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(e[0]==="("&&e[3]===")")return Ye(t,[e[1],e[2]])}let r=await Ra(t,e,0);return r.pos<e.length?D(`test: too many arguments
499
- `,2):Q(r.value)}async function Ra(t,e,r){return td(t,e,r)}async function td(t,e,r){let{value:n,pos:s}=await ka(t,e,r);for(;e[s]==="-o";){let o=await ka(t,e,s+1);n=n||o.value,s=o.pos}return{value:n,pos:s}}async function ka(t,e,r){let{value:n,pos:s}=await xn(t,e,r);for(;e[s]==="-a";){let o=await xn(t,e,s+1);n=n&&o.value,s=o.pos}return{value:n,pos:s}}async function xn(t,e,r){if(e[r]==="!"){let{value:n,pos:s}=await xn(t,e,r+1);return{value:!n,pos:s}}return rd(t,e,r)}async function rd(t,e,r){let n=e[r];if(n==="("){let{value:o,pos:i}=await Ra(t,e,r+1);return{value:o,pos:e[i]===")"?i+1:i}}if(zt(n)){let o=e[r+1]??"";return{value:await Ut(t,n,o),pos:r+2}}if(Xt(n)){let o=e[r+1]??"";return{value:Yt(n,o),pos:r+2}}if(n==="-v"){let o=e[r+1]??"";return{value:Jt(t,o),pos:r+2}}if(n==="-o"){let o=e[r+1]??"";return{value:Sn(t,o),pos:r+2}}let s=e[r+1];if(Zt(s)){let o=n,i=e[r+2]??"";return{value:Qt(s,o,i),pos:r+3}}if(Gt(s)){let o=er(n),i=er(e[r+2]??"0");return!o.valid||!i.valid?{value:!1,pos:r+3}:{value:Vt(s,o.value,i.value),pos:r+3}}if(jt(s)){let o=n,i=e[r+2]??"";return{value:await qt(t,s,o,i),pos:r+3}}return{value:n!==void 0&&n!=="",pos:r+1}}function Kt(t,e){let r="^";for(let n=0;n<e.length;n++){let s=e[n];if(s==="\\")if(n+1<e.length){let o=e[n+1];/[\\^$.|+(){}[\]*?]/.test(o)?r+=`\\${o}`:r+=o,n++}else r+="\\\\";else if(s==="*")r+=".*";else if(s==="?")r+=".";else if(s==="["){let o=e.indexOf("]",n+1);o!==-1?(r+=e.slice(n,o+1),n=o):r+="\\["}else/[\\^$.|+(){}]/.test(s)?r+=`\\${s}`:r+=s}return r+="$",new RegExp(r).test(t)}function Sn(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 Ia(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 Pa(e);try{let r=new ee,n=K(r,e);return W(t,n.expression)}catch{return Pa(e)}}function nd(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 Pa(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=nd(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 er(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}}Z();async function Cn(t,e){let r=t.state.inCondition;t.state.inCondition=!0;let n="",s="",o=0;try{for(let i of e){let a=await t.executeStatement(i);n+=a.stdout,s+=a.stderr,o=a.exitCode}}finally{t.state.inCondition=r}return{stdout:n,stderr:s,exitCode:o}}Z();ye();function ct(t,e,r,n){if(t instanceof te)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 ie)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 re||t instanceof Ee||t instanceof z||t instanceof j)return t.prependOutput(e,r),{action:"rethrow",stdout:e,stderr:r,error:t};let s=q(t);return{action:"error",stdout:e,stderr:`${r}${s}
500
- `,exitCode:1}}Z();ye();async function tr(t,e,r="",n=""){let s=r,o=n,i=0;try{for(let a of e){let c=await t.executeStatement(a);s+=c.stdout,o+=c.stderr,i=c.exitCode}}catch(a){if(Ct(a)||a instanceof Ee||a instanceof z||a instanceof j)throw a.prependOutput(s,o),a;return{stdout:s,stderr:`${o}${q(a)}
501
- `,exitCode:1}}return{stdout:s,stderr:o,exitCode:i}}async function Oa(t,e){let r="",n="";for(let s of e.clauses){let o=await Cn(t,s.condition);if(r+=o.stdout,n+=o.stderr,o.exitCode===0)return tr(t,s.body,r,n)}return e.elseBody?tr(t,e.elseBody,r,n):k(r,n,0)}async function Da(t,e){let r="",n="",s=0,o=0;if(!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(e.variable))return D(`bash: \`${e.variable}': not a valid identifier
502
- `);let i=[];if(e.words===null)i=(t.state.env["@"]||"").split(" ").filter(Boolean);else if(e.words.length===0)i=[];else for(let a of e.words){let c=await lt(t,a);i.push(...c.values)}t.state.loopDepth++;try{for(let a of i){o++,o>t.limits.maxLoopIterations&&ke(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),t.state.env[e.variable]=a;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=ct(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 k(r,n,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return k(r,n,s)}async function Ta(t,e){let r="",n="",s=0,o=0;e.init&&await _(t,e.init.expression),t.state.loopDepth++;try{for(;o++,o>t.limits.maxLoopIterations&&ke(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),!(e.condition&&await _(t,e.condition.expression)===0);){try{for(let i of e.body){let a=await t.executeStatement(i);r+=a.stdout,n+=a.stderr,s=a.exitCode}}catch(i){let a=ct(i,r,n,t.state.loopDepth);if(r=a.stdout,n=a.stderr,a.action==="break")break;if(a.action==="continue"){e.update&&await _(t,e.update.expression);continue}if(a.action==="error")return k(r,n,a.exitCode??1);throw a.error}e.update&&await _(t,e.update.expression)}}finally{t.state.loopDepth--}return k(r,n,s)}async function Ma(t,e,r=""){let n="",s="",o=0,i=0,a=r;for(let l of e.redirections)if((l.operator==="<<"||l.operator==="<<-")&&l.target.type==="HereDoc"){let u=l.target,f=await U(t,u.content);u.stripTabs&&(f=f.split(`
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 qo))return F(`bash: set: ${n[0]}${a}: invalid option
525
+ ${ur}`);Ko(t,qo[a],s)}r++;continue}if(n==="--")return jn(t,e.slice(r+1)),G;if(n==="-"){if(t.state.options.xtrace=!1,t.state.options.verbose=!1,r+1<e.length)return jn(t,e.slice(r+1)),G;r++;continue}if(n==="+"){r++;continue}return n.startsWith("-")||n.startsWith("+")?F(`bash: set: ${n}: invalid option
526
+ ${ur}`):(jn(t,e.slice(r)),G)}return G}function jn(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 Vn(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 Zn(t,e){let r=e;if(r.length>0&&r[0]==="--"&&(r=r.slice(1)),r.length===0)return P("",`bash: source: filename argument required
529
+ `,2);let n=r[0],s=null,i=null;if(n.includes("/")){let l=t.fs.resolvePath(t.state.cwd,n);try{i=await t.fs.readFile(l),s=l}catch{}}else{let c=(t.state.env.PATH||"").split(":").filter(u=>u);for(let u of c){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 c=1;c<=9;c++)a[String(c)]=t.state.env[String(c)];a["#"]=t.state.env["#"],a["@"]=t.state.env["@"];let l=r.slice(1);t.state.env["#"]=String(l.length),t.state.env["@"]=l.join(" ");for(let c=0;c<l.length&&c<9;c++)t.state.env[String(c+1)]=l[c];for(let c=l.length+1;c<=9;c++)delete t.state.env[String(c)]}let o=()=>{if(t.state.sourceDepth--,r.length>1)for(let[l,c]of Object.entries(a))c===void 0?delete t.state.env[l]:t.state.env[l]=c};t.state.sourceDepth++;try{let l=ze(i),c=await t.executeScript(l);return o(),c}catch(l){if(o(),l instanceof Z)throw l;if(l instanceof ue)return P(l.stdout,l.stderr,l.exitCode);if(l.name==="ParseException")return F(`bash: ${n}: ${l.message}
531
+ `);throw l}}function Qn(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],l=a[2];if(l==="@"||l==="*"){let u=ie(t,o);for(let[f]of u)delete t.state.env[`${o}_${f}`];delete t.state.env[o];continue}let c;if(/^-?\d+$/.test(l))c=Number.parseInt(l,10);else{let u=t.state.env[l];c=u?Number.parseInt(u,10):0,Number.isNaN(c)&&(c=0)}if(c<0){let u=ie(t,o),f=u.length;if(f===0){n+=`bash: unset: [${c}]: bad array subscript
532
+ `,s=1;continue}let d=f+c;if(d<0){n+=`bash: unset: [${c}]: bad array subscript
533
+ `,s=1;continue}let h=u[d][0];delete t.state.env[`${o}_${h}`];continue}delete t.state.env[`${o}_${c}`];continue}delete t.state.env[i],t.state.functions.delete(i)}return P("",n,s)}function Kn(t,e){return t.fs.resolvePath(t.state.cwd,e)}var rh=["-e","-a","-f","-d","-r","-w","-x","-s","-L","-h","-k","-g","-u","-G","-O","-b","-c","-p","-S","-t","-N"];function fr(t){return rh.includes(t)}async function dr(t,e,r){let n=Kn(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 nh=["-nt","-ot","-ef"];function hr(t){return nh.includes(t)}async function pr(t,e,r,n){let s=Kn(t,r),i=Kn(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 sh=new Set(["-eq","-ne","-lt","-le","-gt","-ge"]);function mr(t){return sh.has(t)}function yr(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 gr(t){return t==="="||t==="=="||t==="!="}function wr(t,e,r,n=!1){let s=n?Er(e,r):e===r;return t==="!="?!s:s}var ih=new Set(["-z","-n"]);function br(t){return ih.has(t)}function xr(t,e){switch(t){case"-z":return e==="";case"-n":return e!==""}}function Sr(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=vt(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 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(gr(e.operator))return wr(e.operator,r,n,!s);if(mr(e.operator))return yr(e.operator,Yo(t,r),Yo(t,n));if(hr(e.operator))return pr(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 fr(e.operator)?dr(t,e.operator,r):br(e.operator)?xr(e.operator,r):e.operator==="-v"?Sr(t,r):e.operator==="-o"?Yn(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 Q(t,e.word)!=="";default:return!1}}async function mt(t,e){if(e.length===0)return P("","",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):fr(n)?re(await dr(t,n,s)):br(n)?re(xr(n,s)):n==="!"?re(!s):n==="-v"?re(Sr(t,s)):n==="-o"?re(Yn(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):P("","",1)}if(e.length===3){let n=e[0],s=e[1],i=e[2];if(gr(s))return re(wr(s,n,i));if(mr(s)){let a=Ar(n),o=Ar(i);return!a.valid||!o.valid?P("","",2):re(yr(s,a.value,o.value))}if(hr(s))return re(await pr(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 mt(t,[s,i]);return P("",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 mt(t,e.slice(1));return P("",n.stderr,n.exitCode===0?1:n.exitCode===1?0:n.exitCode)}if(e[0]==="("&&e[3]===")")return mt(t,[e[1],e[2]])}let r=await el(t,e,0);return r.pos<e.length?F(`test: too many arguments
536
+ `,2):re(r.value)}async function el(t,e,r){return ah(t,e,r)}async function ah(t,e,r){let{value:n,pos:s}=await Xo(t,e,r);for(;e[s]==="-o";){let i=await Xo(t,e,s+1);n=n||i.value,s=i.pos}return{value:n,pos:s}}async function Xo(t,e,r){let{value:n,pos:s}=await Xn(t,e,r);for(;e[s]==="-a";){let i=await Xn(t,e,s+1);n=n&&i.value,s=i.pos}return{value:n,pos:s}}async function Xn(t,e,r){if(e[r]==="!"){let{value:n,pos:s}=await Xn(t,e,r+1);return{value:!n,pos:s}}return oh(t,e,r)}async function oh(t,e,r){let n=e[r];if(n==="("){let{value:i,pos:a}=await el(t,e,r+1);return{value:i,pos:e[a]===")"?a+1:a}}if(fr(n)){let i=e[r+1]??"";return{value:await dr(t,n,i),pos:r+2}}if(br(n)){let i=e[r+1]??"";return{value:xr(n,i),pos:r+2}}if(n==="-v"){let i=e[r+1]??"";return{value:Sr(t,i),pos:r+2}}if(n==="-o"){let i=e[r+1]??"";return{value:Yn(t,i),pos:r+2}}let s=e[r+1];if(gr(s)){let i=n,a=e[r+2]??"";return{value:wr(s,i,a),pos:r+3}}if(mr(s)){let i=Ar(n),a=Ar(e[r+2]??"0");return!i.valid||!a.valid?{value:!1,pos:r+3}:{value:yr(s,i.value,a.value),pos:r+3}}if(hr(s)){let i=n,a=e[r+2]??"";return{value:await pr(t,s,i,a),pos:r+3}}return{value:n!==void 0&&n!=="",pos:r+1}}function Er(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 Yn(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 Yo(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 Jo(e);try{let r=new le,n=se(r,e);return j(t,n.expression)}catch{return Jo(e)}}function lh(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 Jo(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=lh(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 Ar(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 Jn(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();ve();function $t(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();ve();async function Cr(t,e,r="",n=""){let s=r,i=n,a=0;try{for(let o of e){let l=await t.executeStatement(o);s+=l.stdout,i+=l.stderr,a=l.exitCode}}catch(o){if(Ut(o)||o instanceof Re||o instanceof Z||o instanceof W)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 tl(t,e){let r="",n="";for(let s of e.clauses){let i=await Jn(t,s.condition);if(r+=i.stdout,n+=i.stderr,i.exitCode===0)return Cr(t,s.body,r,n)}return e.elseBody?Cr(t,e.elseBody,r,n):P(r,n,0)}async function rl(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 l=await Rt(t,o);a.push(...l.values)}t.state.loopDepth++;try{for(let o of a){i++,i>t.limits.maxLoopIterations&&Me(`for loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n),t.state.env[e.variable]=o;try{for(let l of e.body){let c=await t.executeStatement(l);r+=c.stdout,n+=c.stderr,s=c.exitCode}}catch(l){let c=$t(l,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 P(r,n,c.exitCode??1);throw c.error}}}finally{t.state.loopDepth--}return P(r,n,s)}async function nl(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&&Me(`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=$t(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 P(r,n,o.exitCode??1);throw o.error}e.update&&await q(t,e.update.expression)}}finally{t.state.loopDepth--}return P(r,n,s)}async function sl(t,e,r=""){let n="",s="",i=0,a=0,o=r;for(let c of e.redirections)if((c.operator==="<<"||c.operator==="<<-")&&c.target.type==="HereDoc"){let u=c.target,f=await Q(t,u.content);u.stripTabs&&(f=f.split(`
503
540
  `).map(d=>d.replace(/^\t+/,"")).join(`
504
- `)),a=f}else if(l.operator==="<<<"&&l.target.type==="Word")a=`${await U(t,l.target)}
505
- `;else if(l.operator==="<"&&l.target.type==="Word")try{let u=await U(t,l.target),f=t.fs.resolvePath(t.state.cwd,u);a=await t.fs.readFile(f)}catch{let u=await U(t,l.target);return D(`bash: ${u}: No such file or directory
506
- `)}let c=t.state.groupStdin;a&&(t.state.groupStdin=a),t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&ke(`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 te){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 ie){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,o=p.exitCode}}catch(h){let p=ct(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 k(n,s,p.exitCode??1);throw p.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=c}return k(n,s,o)}async function Fa(t,e){let r="",n="",s=0,o=0;t.state.loopDepth++;try{for(;;){o++,o>t.limits.maxLoopIterations&&ke(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let i=await Cn(t,e.condition);if(r+=i.stdout,n+=i.stderr,i.exitCode===0)break;try{for(let a of e.body){let c=await t.executeStatement(a);r+=c.stdout,n+=c.stderr,s=c.exitCode}}catch(a){let c=ct(a,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 k(r,n,c.exitCode??1);throw c.error}}}finally{t.state.loopDepth--}return k(r,n,s)}async function La(t,e){let r="",n="",s=0,o=await U(t,e.word),i=!1;for(let a=0;a<e.items.length;a++){let c=e.items[a],l=i;if(!i)for(let u of c.patterns){let f=await U(t,u);if(ua(u)&&(f=fa(f)),Kt(o,f)){l=!0;break}}if(l){let u=await tr(t,c.body,r,n);if(r=u.stdout,n=u.stderr,s=u.exitCode,c.terminator===";;")break;c.terminator===";&"?i=!0:i=!1}else i=!1}return k(r,n,s)}Z();Z();function Wa(t,e){return t.state.functions.set(e.name,e),F}async function _a(t,e,r){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,ke(`${e.name}: maximum recursion depth (${t.limits.maxCallDepth}) exceeded, increase executionLimits.maxCallDepth`,"recursion")),t.state.localScopes.push(new Map);let n={};for(let o=0;o<r.length;o++)n[String(o+1)]=t.state.env[String(o+1)],t.state.env[String(o+1)]=r[o];n["@"]=t.state.env["@"],n["#"]=t.state.env["#"],t.state.env["@"]=r.join(" "),t.state.env["#"]=String(r.length);let s=()=>{let o=t.state.localScopes.pop();if(o)for(let[i,a]of o)a===void 0?delete t.state.env[i]:t.state.env[i]=a;for(let[i,a]of Object.entries(n))a===void 0?delete t.state.env[i]:t.state.env[i]=a;t.state.callDepth--};try{let o=await t.executeCommand(e.body,"");return s(),o}catch(o){if(s(),o instanceof re)return k(o.stdout,o.stderr,o.exitCode);throw o}}ye();async function Ha(t,e,r){let{stdout:n,stderr:s,exitCode:o}=e;for(let i of r){if(i.target.type==="HereDoc")continue;let a=await U(t,i.target);switch(i.operator){case">":{let c=i.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
507
- `,o=1,n="";break}}catch{}await t.fs.writeFile(l,n),n=""}else if(c===2)if(a==="/dev/null")s="";else{let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
508
- `,o=1;break}}catch{}await t.fs.writeFile(l,s),s=""}break}case">>":{let c=i.fd??1;if(c===1){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
509
- `,o=1,n="";break}}catch{}await t.fs.appendFile(l,n),n=""}else if(c===2){let l=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(l)).isDirectory){s+=`bash: ${a}: Is a directory
510
- `,o=1;break}}catch{}await t.fs.appendFile(l,s),s=""}break}case">&":{let c=i.fd??1;a==="2"||a==="&2"?c===1&&(s+=n,n=""):(a==="1"||a==="&1")&&(n+=s,s="");break}case"&>":{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s=`bash: ${a}: Is a directory
511
- `,o=1,n="";break}}catch{}await t.fs.writeFile(c,n+s),n="",s="";break}case"&>>":{let c=t.fs.resolvePath(t.state.cwd,a);try{if((await t.fs.stat(c)).isDirectory){s=`bash: ${a}: Is a directory
512
- `,o=1,n="";break}}catch{}await t.fs.appendFile(c,n+s),n="",s="";break}}}return k(n,s,o)}var ut=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 o of e.statements)try{let i=await this.executeStatement(o);r+=i.stdout,n+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}catch(i){if(i instanceof z)throw i.prependOutput(r,n),i;if(i instanceof j)throw i;if(i instanceof Ee)return r+=i.stdout,n+=i.stderr,s=i.exitCode,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s),{stdout:r,stderr:n,exitCode:s,env:{...this.ctx.state.env}};if(i instanceof fe)return r+=i.stdout,n+=i.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(i instanceof Ce)return r+=i.stdout,n+=i.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(i instanceof te||i instanceof ie){if(this.ctx.state.loopDepth>0)throw i.prependOutput(r,n),i;r+=i.stdout,n+=i.stderr;continue}throw i instanceof re&&i.prependOutput(r,n),i}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&&ke(`too many commands executed (>${this.ctx.limits.maxCommandCount}), increase executionLimits.maxCommandCount`,"commands");let r="",n="",s=0,o=-1,i=!1;for(let a=0;a<e.pipelines.length;a++){let c=e.pipelines[a],l=a>0?e.operators[a-1]:null;if(l==="&&"&&s!==0||l==="||"&&s===0)continue;let u=await this.executePipeline(c);r+=u.stdout,n+=u.stderr,s=u.exitCode,o=a,i=c.negated,this.ctx.state.lastExitCode=s,this.ctx.state.env["?"]=String(s)}if(this.ctx.state.options.errexit&&s!==0&&o===e.pipelines.length-1&&!i&&!this.ctx.state.inCondition)throw new Ee(s,r,n);return k(r,n,s)}async executePipeline(e){let r="",n=F,s=0,o=[];for(let i=0;i<e.commands.length;i++){let a=e.commands[i],c=i===e.commands.length-1,l;try{l=await this.executeCommand(a,r)}catch(u){if(u instanceof Ce)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}o.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 i of Object.keys(this.ctx.state.env))i.startsWith("PIPESTATUS_")&&delete this.ctx.state.env[i];for(let i=0;i<o.length;i++)this.ctx.state.env[`PIPESTATUS_${i}`]=String(o[i]);return this.ctx.state.env.PIPESTATUS__length=String(o.length),this.ctx.state.options.pipefail&&s!==0&&(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 Oa(this.ctx,e);case"For":return Da(this.ctx,e);case"CStyleFor":return Ta(this.ctx,e);case"While":return Ma(this.ctx,e,r);case"Until":return Fa(this.ctx,e);case"Case":return La(this.ctx,e);case"Subshell":return this.executeSubshell(e,r);case"Group":return this.executeGroup(e,r);case"FunctionDef":return Wa(this.ctx,e);case"ArithmeticCommand":return this.executeArithmeticCommand(e);case"ConditionalCommand":return this.executeConditionalCommand(e);default:return F}}async executeSimpleCommand(e,r){try{return await this.executeSimpleCommandInner(e,r)}catch(n){if(n instanceof V)return D(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 k("",`bash: ${l}: cannot assign list to array member
513
- `,1);let b=Te(this.ctx,l);if(b)return b;let g=[];for(let w of c.array){let E=await lt(this.ctx,w);g.push(...E.values)}let y=0;if(c.append){let w=X(this.ctx,l);w.length>0&&(y=Math.max(...w.map(([$])=>typeof $=="number"?$:0))+1)}else{let w=`${l}_`;for(let E of Object.keys(this.ctx.state.env))E.startsWith(w)&&!E.includes("__")&&delete this.ctx.state.env[E]}for(let w=0;w<g.length;w++)this.ctx.state.env[`${l}_${y+w}`]=g[w];c.append||(this.ctx.state.env[`${l}__length`]=String(g.length));continue}let u=c.value?await U(this.ctx,c.value):"";if(l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return k("",`bash: ${l}: bad array subscript
514
- `,1);let d=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let b=d[1],g=d[2],y=Te(this.ctx,b);if(y)return y;let w=this.ctx.state.associativeArrays?.has(b),E;if(w){let A;if(g.startsWith("'")&&g.endsWith("'"))A=g.slice(1,-1);else if(g.startsWith('"')&&g.endsWith('"')){let P=g.slice(1,-1),L=new ee().parseWordFromString(P,!0,!1);A=await U(this.ctx,L)}else if(g.includes("$")){let J=new ee().parseWordFromString(g,!1,!1);A=await U(this.ctx,J)}else A=g;E=`${b}_${A}`}else{let A;if(/^-?\d+$/.test(g))A=Number.parseInt(g,10);else{try{let P=new ee,J=K(P,g);A=W(this.ctx,J.expression)}catch{let P=this.ctx.state.env[g];A=P?Number.parseInt(P,10):0}Number.isNaN(A)&&(A=0)}if(A<0){let P=X(this.ctx,b);if(P.length===0)return k("",`bash: ${b}[${g}]: bad array subscript
515
- `,1);if(A=Math.max(...P.map(([L])=>typeof L=="number"?L:0))+1+A,A<0)return k("",`bash: ${b}[${g}]: bad array subscript
516
- `,1)}E=`${b}_${A}`}let $=c.append?(this.ctx.state.env[E]||"")+u:u;e.name?(n[E]=this.ctx.state.env[E],this.ctx.state.env[E]=$):this.ctx.state.env[E]=$;continue}let h=Te(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 k("","",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 U(this.ctx,l.content);l.stripTabs&&(u=u.split(`
541
+ `)),o=f}else if(c.operator==="<<<"&&c.target.type==="Word")o=`${await Q(t,c.target)}
542
+ `;else if(c.operator==="<"&&c.target.type==="Word")try{let u=await Q(t,c.target),f=t.fs.resolvePath(t.state.cwd,u);o=await t.fs.readFile(f)}catch{let u=await Q(t,c.target);return F(`bash: ${u}: No such file or directory
543
+ `)}let l=t.state.groupStdin;o&&(t.state.groupStdin=o),t.state.loopDepth++;try{for(;;){a++,a>t.limits.maxLoopIterations&&Me(`while loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",n,s);let c=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,c=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(c!==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=$t(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 P(n,s,p.exitCode??1);throw p.error}}}}finally{t.state.loopDepth--,t.state.groupStdin=l}return P(n,s,i)}async function il(t,e){let r="",n="",s=0,i=0;t.state.loopDepth++;try{for(;;){i++,i>t.limits.maxLoopIterations&&Me(`until loop: too many iterations (${t.limits.maxLoopIterations}), increase executionLimits.maxLoopIterations`,"iterations",r,n);let a=await Jn(t,e.condition);if(r+=a.stdout,n+=a.stderr,a.exitCode===0)break;try{for(let o of e.body){let l=await t.executeStatement(o);r+=l.stdout,n+=l.stderr,s=l.exitCode}}catch(o){let l=$t(o,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 P(r,n,l.exitCode??1);throw l.error}}}finally{t.state.loopDepth--}return P(r,n,s)}async function al(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 l=e.items[o],c=a;if(!a)for(let u of l.patterns){let f=await Q(t,u);if(Do(u)&&(f=To(f)),Er(i,f)){c=!0;break}}if(c){let u=await Cr(t,l.body,r,n);if(r=u.stdout,n=u.stderr,s=u.exitCode,l.terminator===";;")break;l.terminator===";&"?a=!0:a=!1}else a=!1}return P(r,n,s)}X();X();function ol(t,e){return t.state.functions.set(e.name,e),G}async function ll(t,e,r){t.state.callDepth++,t.state.callDepth>t.limits.maxCallDepth&&(t.state.callDepth--,Me(`${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 P(i.stdout,i.stderr,i.exitCode);throw i}}ve();async function cl(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 l=a.fd??1;if(l===1){let c=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${o}: Is a directory
544
+ `,i=1,n="";break}}catch{}await t.fs.writeFile(c,n),n=""}else if(l===2)if(o==="/dev/null")s="";else{let c=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${o}: Is a directory
545
+ `,i=1;break}}catch{}await t.fs.writeFile(c,s),s=""}break}case">>":{let l=a.fd??1;if(l===1){let c=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${o}: Is a directory
546
+ `,i=1,n="";break}}catch{}await t.fs.appendFile(c,n),n=""}else if(l===2){let c=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(c)).isDirectory){s+=`bash: ${o}: Is a directory
547
+ `,i=1;break}}catch{}await t.fs.appendFile(c,s),s=""}break}case">&":{let l=a.fd??1;o==="2"||o==="&2"?l===1&&(s+=n,n=""):(o==="1"||o==="&1")&&(n+=s,s="");break}case"&>":{let l=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(l)).isDirectory){s=`bash: ${o}: Is a directory
548
+ `,i=1,n="";break}}catch{}await t.fs.writeFile(l,n+s),n="",s="";break}case"&>>":{let l=t.fs.resolvePath(t.state.cwd,o);try{if((await t.fs.stat(l)).isDirectory){s=`bash: ${o}: Is a directory
549
+ `,i=1,n="";break}}catch{}await t.fs.appendFile(l,n+s),n="",s="";break}}}return P(n,s,i)}var Pt=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 xe)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 Oe)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&&Me(`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 l=e.pipelines[o],c=o>0?e.operators[o-1]:null;if(c==="&&"&&s!==0||c==="||"&&s===0)continue;let u=await this.executePipeline(l);r+=u.stdout,n+=u.stderr,s=u.exitCode,i=o,a=l.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 P(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],l=a===e.commands.length-1,c;try{c=await this.executeCommand(o,r)}catch(u){if(u instanceof Oe)c={stdout:u.stdout,stderr:u.stderr,exitCode:1};else if(u instanceof Z&&e.commands.length>1)c={stdout:u.stdout,stderr:u.stderr,exitCode:u.exitCode};else throw u}i.push(c.exitCode),c.exitCode!==0&&(s=c.exitCode),l?n=c:(r=c.stdout,n={stdout:"",stderr:c.stderr,exitCode:c.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 tl(this.ctx,e);case"For":return rl(this.ctx,e);case"CStyleFor":return nl(this.ctx,e);case"While":return sl(this.ctx,e,r);case"Until":return il(this.ctx,e);case"Case":return al(this.ctx,e);case"Subshell":return this.executeSubshell(e,r);case"Group":return this.executeGroup(e,r);case"FunctionDef":return ol(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 l of e.assignments){let c=l.name;if(l.array){if(/\[.+\]$/.test(c))return P("",`bash: ${c}: cannot assign list to array member
550
+ `,1);let b=je(this.ctx,c);if(b)return b;let w=[];for(let E of l.array){let x=await Rt(this.ctx,E);w.push(...x.values)}let g=0;if(l.append){let E=ie(this.ctx,c);E.length>0&&(g=Math.max(...E.map(([S])=>typeof S=="number"?S:0))+1)}else{let E=`${c}_`;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[`${c}_${g+E}`]=w[E];l.append||(this.ctx.state.env[`${c}__length`]=String(w.length));continue}let u=l.value?await Q(this.ctx,l.value):"";if(c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[\]$/))return P("",`bash: ${c}: bad array subscript
551
+ `,1);let d=c.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[(.+)\]$/);if(d){let b=d[1],w=d[2],g=je(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 P("",`bash: ${b}[${w}]: bad array subscript
552
+ `,1);if(v=Math.max(...R.map(([_])=>typeof _=="number"?_:0))+1+v,v<0)return P("",`bash: ${b}[${w}]: bad array subscript
553
+ `,1)}x=`${b}_${v}`}let S=l.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=je(this.ctx,c);if(h)return h;let p=l.append?(this.ctx.state.env[c]||"")+u:u;e.name?(n[c]=this.ctx.state.env[c],this.ctx.state.env[c]=p):this.ctx.state.env[c]=p}if(!e.name)return P("","",this.ctx.state.lastExitCode);for(let l of e.redirections){if((l.operator==="<<"||l.operator==="<<-")&&l.target.type==="HereDoc"){let c=l.target,u=await Q(this.ctx,c.content);c.stripTabs&&(u=u.split(`
517
554
  `).map(f=>f.replace(/^\t+/,"")).join(`
518
- `)),r=u;continue}if(c.operator==="<<<"&&c.target.type==="Word"){r=`${await U(this.ctx,c.target)}
519
- `;continue}if(c.operator==="<"&&c.target.type==="Word")try{let l=await U(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 U(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 D(`bash: ${l}: No such file or directory
520
- `)}}let s=await U(this.ctx,e.name),o=[],i=[];for(let c of e.args){let l=await lt(this.ctx,c);for(let u of l.values)o.push(u),i.push(l.quoted)}if(!s){if(e.name.parts.every(l=>l.type==="CommandSubstitution"||l.type==="ParameterExpansion"||l.type==="ArithmeticExpansion")){if(o.length>0){let l=o.shift();return i.shift(),await this.runCommand(l,o,i,r)}return k("","",this.ctx.state.lastExitCode)}return D(`bash: : command not found
521
- `,127)}let a=await this.runCommand(s,o,i,r);a=await Ha(this.ctx,a,e.redirections),this.ctx.state.lastArg=o.length>0?o[o.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&&(a={...a,stderr:this.ctx.state.expansionStderr+a.stderr},this.ctx.state.expansionStderr=""),a}async runCommand(e,r,n,s,o=!1){if(e==="cd")return await rn(this.ctx,r);if(e==="export")return un(this.ctx,r);if(e==="unset")return bn(this.ctx,r);if(e==="exit")return cn(this.ctx,r);if(e==="local")return dn(this.ctx,r);if(e==="set")return gn(this.ctx,r);if(e==="break")return tn(this.ctx,r);if(e==="continue")return nn(this.ctx,r);if(e==="return")return pn(this.ctx,r);if(e==="eval")return ln(this.ctx,r);if(e==="shift")return yn(this.ctx,r);if(e==="source"||e===".")return wn(this.ctx,r);if(e==="read")return hn(this.ctx,r,s);if(e==="declare"||e==="typeset")return on(this.ctx,r);if(e==="readonly")return an(this.ctx,r);if(!o){let u=this.ctx.state.functions.get(e);if(u)return _a(this.ctx,u,r)}if(e===":"||e==="true")return F;if(e==="false")return Q(!1);if(e==="let")return fn(this.ctx,r);if(e==="command"){if(r.length===0)return F;let u=r;for(;u.length>0&&u[0].startsWith("-");)u=u.slice(1);if(u.length===0)return F;let[f,...d]=u;return this.runCommand(f,d,[],s,!0)}if(e==="builtin"){if(r.length===0)return F;let[u,...f]=r;return this.runCommand(u,f,[],s)}if(e==="shopt")return F;if(e==="exec"){if(r.length===0)return F;let[u,...f]=r;return this.runCommand(u,f,[],s)}if(e==="wait")return F;if(e==="type")return this.handleType(r);if(e==="[["){let u=r.lastIndexOf("]]");if(u!==-1){let f=r.slice(0,u);return Ye(this.ctx,f)}return D("bash: [[: missing `]]'\n",2)}if(e==="["||e==="test"){let u=r;if(e==="["){if(r[r.length-1]!=="]")return D("[: missing `]'\n",2);u=r.slice(0,-1)}return Ye(this.ctx,u)}let i=await this.resolveCommand(e);if(!i)return D(`bash: ${e}: command not found
522
- `,127);let{cmd:a,path:c}=i,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 a.execute(r,l)}catch(u){return D(`${e}: ${q(u)}
523
- `)}}async resolveCommand(e){if(e.includes("/")){let o=this.ctx.fs.resolvePath(this.ctx.state.cwd,e);if(!await this.ctx.fs.exists(o))return null;let i=o.split("/").pop()||e,a=this.ctx.commands.get(i);return a?{cmd:a,path:o}:null}let n=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of n){if(!o)continue;let i=`${o}/${e}`;if(await this.ctx.fs.exists(i)){let a=this.ctx.commands.get(e);if(a)return{cmd:a,path:i}}}if(!await this.ctx.fs.exists("/bin")){let o=this.ctx.commands.get(e);if(o)return{cmd:o,path:`/bin/${e}`}}return null}async findCommandInPath(e){let r=[],s=(this.ctx.state.env.PATH||"/bin:/usr/bin").split(":");for(let o of s){if(!o)continue;let i=`${o}/${e}`;await this.ctx.fs.exists(i)&&r.push(i)}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="",o="",i=0;for(let a of e)r.has(a)?s+=`${a} is a shell keyword
524
- `:n.has(a)?s+=`${a} is a shell builtin
525
- `:this.ctx.state.functions.has(a)?s+=`${a} is a function
526
- `:this.ctx.commands.has(a)?s+=`${a} is /bin/${a}
527
- `:(o+=`bash: type: ${a}: not found
528
- `,i=1);return k(s,o,i)}async executeSubshell(e,r=""){let n={...this.ctx.state.env},s=this.ctx.state.cwd,o=this.ctx.state.loopDepth;this.ctx.state.loopDepth=0;let i=this.ctx.state.groupStdin;r&&(this.ctx.state.groupStdin=r);let a="",c="",l=0;try{for(let u of e.body){let f=await this.executeStatement(u);a+=f.stdout,c+=f.stderr,l=f.exitCode}}catch(u){if(this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.groupStdin=i,u instanceof j)throw u;if(u instanceof te||u instanceof ie)return a+=u.stdout,c+=u.stderr,k(a,c,0);if(u instanceof z)return a+=u.stdout,c+=u.stderr,k(a,c,u.exitCode);if(u instanceof re)return a+=u.stdout,c+=u.stderr,k(a,c,u.exitCode);if(u instanceof Ee)throw u.stdout=a+u.stdout,u.stderr=c+u.stderr,u;return k(a,`${c}${q(u)}
529
- `,1)}return this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=o,this.ctx.state.groupStdin=i,k(a,c,l)}async executeGroup(e,r=""){let n="",s="",o=0,i=this.ctx.state.groupStdin;r&&(this.ctx.state.groupStdin=r);try{for(let a of e.body){let c=await this.executeStatement(a);n+=c.stdout,s+=c.stderr,o=c.exitCode}}catch(a){if(this.ctx.state.groupStdin=i,a instanceof j)throw a;if(Ct(a)||a instanceof Ee||a instanceof z)throw a.prependOutput(n,s),a;return k(n,`${s}${q(a)}
530
- `,1)}return this.ctx.state.groupStdin=i,k(n,s,o)}async executeArithmeticCommand(e){try{let r=await _(this.ctx,e.expression.expression);return Q(r!==0)}catch(r){return D(`bash: arithmetic expression: ${r.message}
531
- `)}}async executeConditionalCommand(e){try{let r=await Me(this.ctx,e.expression);return Q(r)}catch(r){return D(`bash: conditional expression: ${r.message}
532
- `,2)}}};var Je={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4};function Ba(t){return t?{maxCallDepth:t.maxCallDepth??Je.maxCallDepth,maxCommandCount:t.maxCommandCount??Je.maxCommandCount,maxLoopIterations:t.maxLoopIterations??Je.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??Je.maxAwkIterations,maxSedIterations:t.maxSedIterations??Je.maxSedIterations}:{...Je}}function za(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function sd(t){let e=za(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function id(t,e){let r=za(t);if(!r)return!1;let n=sd(e);return!n||r.origin!==n.origin?!1:n.pathPrefix==="/"||n.pathPrefix===""?!0:r.pathname.startsWith(n.pathPrefix)}function An(t,e){return!e||e.length===0?!1:e.some(r=>id(t,r))}var ft=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},dt=class extends Error{constructor(e){super(`Too many redirects (max: ${e})`),this.name="TooManyRedirectsError"}},ht=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 od=20,ad=3e4,ld=["GET","HEAD"],cd=new Set(["GET","HEAD","OPTIONS"]),ud=new Set([301,302,303,307,308]);function $n(t){let e=t.maxRedirects??od,r=t.timeoutMs??ad,n=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??ld;function s(a){if(!t.dangerouslyAllowFullInternetAccess&&!An(a,t.allowedUrlPrefixes??[]))throw new ft(a)}function o(a){if(t.dangerouslyAllowFullInternetAccess)return;let c=a.toUpperCase();if(!n.includes(c))throw new rr(c,n)}async function i(a,c={}){let l=c.method?.toUpperCase()??"GET";s(a),o(l);let u=a,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 g={method:l,headers:c.headers,signal:p.signal,redirect:"manual"};c.body&&!cd.has(l)&&(g.body=c.body);let y=await fetch(u,g);if(ud.has(y.status)&&d){let w=y.headers.get("location");if(!w)return await Ua(y,u);let E=new URL(w,u).href;if(!t.dangerouslyAllowFullInternetAccess&&!An(E,t.allowedUrlPrefixes??[]))throw new ht(E);if(f++,f>e)throw new dt(e);u=E;continue}return await Ua(y,u)}finally{clearTimeout(b)}}}return i}async function Ua(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 nr=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;state;constructor(e={}){let r=e.fs??new _e(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:`
533
- `,OSTYPE:"linux-gnu",MACHTYPE:"x86_64-pc-linux-gnu",HOSTTYPE:"x86_64",PWD:n,OLDPWD:n,...e.env};if(this.limits=Ba({...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=$n(e.network)),this.sleepFn=e.sleep,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 _e)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 _e)try{r.mkdirSync(n,{recursive:!0})}catch{}for(let o of $o(e.commands))this.registerCommand(o);if(e.network)for(let o of No())this.registerCommand(o);if(e.customCommands)for(let o of e.customCommands)vo(o)?this.registerCommand(ko(o)):this.registerCommand(o)}registerCommand(e){if(this.commands.set(e.name,e),this.fs instanceof _e)try{this.fs.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
555
+ `)),r=u;continue}if(l.operator==="<<<"&&l.target.type==="Word"){r=`${await Q(this.ctx,l.target)}
556
+ `;continue}if(l.operator==="<"&&l.target.type==="Word")try{let c=await Q(this.ctx,l.target),u=this.ctx.fs.resolvePath(this.ctx.state.cwd,c);r=await this.ctx.fs.readFile(u)}catch{let c=await Q(this.ctx,l.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: ${c}: No such file or directory
557
+ `)}}let s=await Q(this.ctx,e.name),i=[],a=[];for(let l of e.args){let c=await Rt(this.ctx,l);for(let u of c.values)i.push(u),a.push(c.quoted)}if(!s){if(e.name.parts.every(c=>c.type==="CommandSubstitution"||c.type==="ParameterExpansion"||c.type==="ArithmeticExpansion")){if(i.length>0){let c=i.shift();return a.shift(),await this.runCommand(c,i,a,r)}return P("","",this.ctx.state.lastExitCode)}return F(`bash: : command not found
558
+ `,127)}let o=await this.runCommand(s,i,a,r);o=await cl(this.ctx,o,e.redirections),this.ctx.state.lastArg=i.length>0?i[i.length-1]:s;for(let[l,c]of Object.entries(n))c===void 0?delete this.ctx.state.env[l]:this.ctx.state.env[l]=c;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 Dn(this.ctx,r);if(e==="export")return Bn(this.ctx,r);if(e==="unset")return Qn(this.ctx,r);if(e==="exit")return Wn(this.ctx,r);if(e==="local")return Un(this.ctx,r);if(e==="set")return qn(this.ctx,r);if(e==="break")return On(this.ctx,r);if(e==="continue")return Tn(this.ctx,r);if(e==="return")return Gn(this.ctx,r);if(e==="eval")return _n(this.ctx,r);if(e==="shift")return Vn(this.ctx,r);if(e==="source"||e===".")return Zn(this.ctx,r);if(e==="read")return zn(this.ctx,r,s);if(e==="declare"||e==="typeset")return Fn(this.ctx,r);if(e==="readonly")return Mn(this.ctx,r);if(!i){let u=this.ctx.state.functions.get(e);if(u)return ll(this.ctx,u,r)}if(e===":"||e==="true")return G;if(e==="false")return re(!1);if(e==="let")return Hn(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 mt(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 mt(this.ctx,u)}let a=await this.resolveCommand(e);if(!a)return F(`bash: ${e}: command not found
559
+ `,127);let{cmd:o,path:l}=a,c={fs:this.ctx.fs,cwd:this.ctx.state.cwd,env:this.ctx.state.env,stdin:s,limits:this.ctx.limits,exec:this.ctx.execFn,fetch:this.ctx.fetch,getRegisteredCommands:()=>Array.from(this.ctx.commands.keys()),sleep:this.ctx.sleep};try{return await o.execute(r,c)}catch(u){return F(`${e}: ${Y(u)}
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
+ `:n.has(o)?s+=`${o} is a shell builtin
562
+ `:this.ctx.state.functions.has(o)?s+=`${o} is a function
563
+ `:this.ctx.commands.has(o)?s+=`${o} is /bin/${o}
564
+ `:(i+=`bash: type: ${o}: not found
565
+ `,a=1);return P(s,i,a)}async executeSubshell(e,r=""){let n={...this.ctx.state.env},s=this.ctx.state.cwd,i=this.ctx.state.loopDepth;this.ctx.state.loopDepth=0;let a=this.ctx.state.groupStdin;r&&(this.ctx.state.groupStdin=r);let o="",l="",c=0;try{for(let u of e.body){let f=await this.executeStatement(u);o+=f.stdout,l+=f.stderr,c=f.exitCode}}catch(u){if(this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=i,this.ctx.state.groupStdin=a,u instanceof W)throw u;if(u instanceof ce||u instanceof pe)return o+=u.stdout,l+=u.stderr,P(o,l,0);if(u instanceof Z)return o+=u.stdout,l+=u.stderr,P(o,l,u.exitCode);if(u instanceof ue)return o+=u.stdout,l+=u.stderr,P(o,l,u.exitCode);if(u instanceof Re)throw u.stdout=o+u.stdout,u.stderr=l+u.stderr,u;return P(o,`${l}${Y(u)}
566
+ `,1)}return this.ctx.state.env=n,this.ctx.state.cwd=s,this.ctx.state.loopDepth=i,this.ctx.state.groupStdin=a,P(o,l,c)}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 l=await this.executeStatement(o);n+=l.stdout,s+=l.stderr,i=l.exitCode}}catch(o){if(this.ctx.state.groupStdin=a,o instanceof W)throw o;if(Ut(o)||o instanceof Re||o instanceof Z)throw o.prependOutput(n,s),o;return P(n,`${s}${Y(o)}
567
+ `,1)}return this.ctx.state.groupStdin=a,P(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 qe(this.ctx,e.expression);return re(r)}catch(r){return F(`bash: conditional expression: ${r.message}
569
+ `,2)}}};var yt={maxCallDepth:100,maxCommandCount:1e4,maxLoopIterations:1e4,maxAwkIterations:1e4,maxSedIterations:1e4};function ul(t){return t?{maxCallDepth:t.maxCallDepth??yt.maxCallDepth,maxCommandCount:t.maxCommandCount??yt.maxCommandCount,maxLoopIterations:t.maxLoopIterations??yt.maxLoopIterations,maxAwkIterations:t.maxAwkIterations??yt.maxAwkIterations,maxSedIterations:t.maxSedIterations??yt.maxSedIterations}:{...yt}}function fl(t){try{let e=new URL(t);return{origin:e.origin,pathname:e.pathname,href:e.href}}catch{return null}}function ch(t){let e=fl(t);return e?{origin:e.origin,pathPrefix:e.pathname}:null}function uh(t,e){let r=fl(t);if(!r)return!1;let n=ch(e);return!n||r.origin!==n.origin?!1:n.pathPrefix==="/"||n.pathPrefix===""?!0:r.pathname.startsWith(n.pathPrefix)}function es(t,e){return!e||e.length===0?!1:e.some(r=>uh(t,r))}var Ot=class extends Error{constructor(e){super(`Network access denied: URL not in allow-list: ${e}`),this.name="NetworkAccessDeniedError"}},Dt=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"}},Nr=class extends Error{constructor(e,r){super(`HTTP method '${e}' not allowed. Allowed methods: ${r.join(", ")}`),this.name="MethodNotAllowedError"}};var fh=20,dh=3e4,hh=["GET","HEAD"],ph=new Set(["GET","HEAD","OPTIONS"]),mh=new Set([301,302,303,307,308]);function ts(t){let e=t.maxRedirects??fh,r=t.timeoutMs??dh,n=t.dangerouslyAllowFullInternetAccess?["GET","HEAD","POST","PUT","DELETE","PATCH","OPTIONS"]:t.allowedMethods??hh;function s(o){if(!t.dangerouslyAllowFullInternetAccess&&!es(o,t.allowedUrlPrefixes??[]))throw new Ot(o)}function i(o){if(t.dangerouslyAllowFullInternetAccess)return;let l=o.toUpperCase();if(!n.includes(l))throw new Nr(l,n)}async function a(o,l={}){let c=l.method?.toUpperCase()??"GET";s(o),i(c);let u=o,f=0,d=l.followRedirects??!0,h=l.timeoutMs!==void 0?Math.min(l.timeoutMs,r):r;for(;;){let p=new AbortController,b=setTimeout(()=>p.abort(),h);try{let w={method:c,headers:l.headers,signal:p.signal,redirect:"manual"};l.body&&!ph.has(c)&&(w.body=l.body);let g=await fetch(u,w);if(mh.has(g.status)&&d){let E=g.headers.get("location");if(!E)return await dl(g,u);let x=new URL(E,u).href;if(!t.dangerouslyAllowFullInternetAccess&&!es(x,t.allowedUrlPrefixes??[]))throw new Tt(x);if(f++,f>e)throw new Dt(e);u=x;continue}return await dl(g,u)}finally{clearTimeout(b)}}}return a}async function dl(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 vr=class{fs;commands=new Map;useDefaultLayout=!1;limits;secureFetch;sleepFn;logger;state;constructor(e={}){let r=e.fs??new Je(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=ul({...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=ts(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 Je)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 Je)try{r.mkdirSync(n,{recursive:!0})}catch{}for(let i of Va(e.commands))this.registerCommand(i);if(e.network)for(let i of Za())this.registerCommand(i);if(e.customCommands)for(let i of e.customCommands)Qa(i)?this.registerCommand(Ka(i)):this.registerCommand(i)}registerCommand(e){if(this.commands.set(e.name,e),this.fs instanceof Je)try{this.fs.writeFileSync(`/bin/${e.name}`,`#!/bin/bash
534
571
  # Built-in command: ${e.name}
535
- `)}catch{}}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.
536
- `,exitCode:1,env:{...this.state.env,...r?.env}};if(!e.trim())return{stdout:"",stderr:"",exitCode:0,env:{...this.state.env,...r?.env}};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}},o=e;r?.rawScript||(o=e.split(`
537
- `).map(a=>a.trimStart()).join(`
538
- `));try{let i=Oe(o),a={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn};return await new ut(a,s).executeScript(i)}catch(i){if(i instanceof z)return{stdout:i.stdout,stderr:i.stderr,exitCode:i.exitCode,env:{...this.state.env,...r?.env}};if(i instanceof V)return{stdout:i.stdout,stderr:i.stderr,exitCode:1,env:{...this.state.env,...r?.env}};if(i instanceof j)return{stdout:i.stdout,stderr:i.stderr,exitCode:j.EXIT_CODE,env:{...this.state.env,...r?.env}};if(i.name==="ParseException")return{stdout:"",stderr:`bash: syntax error: ${i.message}
539
- `,exitCode:2,env:{...this.state.env,...r?.env}};if(i instanceof RangeError)return{stdout:"",stderr:`bash: ${i.message}
540
- `,exitCode:1,env:{...this.state.env,...r?.env}};throw i}}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 hd(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(`
541
- `).trim()}var pd=ja.object({command:ja.string().describe("The bash command to execute")});function E0(t={}){let e=new nr({fs:t.fs,files:t.fs?void 0:t.files,env:t.env,cwd:t.cwd,network:t.network,commands:t.commands});return fd({description:hd(t),inputSchema:dd(pd),execute:async({command:r})=>{t.onCall?.(r);let n=await e.exec(r);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}})}export{E0 as createBashTool};
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
+ `,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
+ `).map(o=>o.trimStart()).join(`
575
+ `));try{let a=ze(i),o={fs:this.fs,commands:this.commands,limits:this.limits,exec:this.exec.bind(this),fetch:this.secureFetch,sleep:this.sleepFn},c=await new Pt(o,s).executeScript(a);return this.logResult(c)}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}
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 wh(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 Eh=hl.object({command:hl.string().describe("The bash command to execute")});function e0(t={}){let e=new vr({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 yh({description:wh(t),inputSchema:gh(Eh),execute:async({command:r})=>{t.onCall?.(r);let n=await e.exec(r);return{stdout:n.stdout,stderr:n.stderr,exitCode:n.exitCode}}})}export{e0 as createBashTool};