just-bash 2.12.8 → 2.13.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/README.md +332 -260
  2. package/dist/AGENTS.md +1 -1
  3. package/dist/Bash.d.ts +17 -0
  4. package/dist/bin/chunks/{awk2-J2PNSA7C.js → awk2-VTJMI54B.js} +1 -1
  5. package/dist/bin/chunks/{chunk-O5B6WWQQ.js → chunk-A3HQTYHR.js} +1 -1
  6. package/dist/bin/chunks/chunk-AAW7UMPO.js +9 -0
  7. package/dist/bin/chunks/{chunk-2V53PP6G.js → chunk-B3RU2PUI.js} +27 -27
  8. package/dist/bin/chunks/chunk-CQG2HEAL.js +5 -0
  9. package/dist/bin/chunks/chunk-DOXYBGNA.js +12 -0
  10. package/dist/bin/chunks/chunk-FBJJY4ZV.js +14 -0
  11. package/dist/bin/{shell/chunks/chunk-YAEF6X2N.js → chunks/chunk-GR23MPTT.js} +1 -1
  12. package/dist/bin/{shell/chunks/chunk-35JD7YEM.js → chunks/chunk-HJEHIH4P.js} +13 -13
  13. package/dist/bin/chunks/{chunk-UG4GMDQL.js → chunk-LGF54XJQ.js} +1 -1
  14. package/dist/bin/chunks/chunk-LIYVQA3X.js +2 -0
  15. package/dist/bin/chunks/{chunk-2BC3N3L2.js → chunk-ORUYSLP4.js} +4 -4
  16. package/dist/bin/chunks/{chunk-REGSV3X5.js → chunk-SDLWFYVT.js} +1 -1
  17. package/dist/bin/chunks/{chunk-STOAUD75.js → chunk-THNL3XFF.js} +8 -8
  18. package/dist/bin/chunks/chunk-TKTKRRAL.js +11 -0
  19. package/dist/bin/chunks/{chunk-ZJGIBTWD.js → chunk-V7ZOPVQS.js} +1 -1
  20. package/dist/bin/chunks/{chunk-ZYQQ6B7B.js → chunk-ZO5PSLKR.js} +2 -2
  21. package/dist/bin/chunks/curl-SRTMGOVV.js +26 -0
  22. package/dist/bin/chunks/env-NTPN5QYM.js +2 -0
  23. package/dist/bin/{shell/chunks/expansion-JBCP2CHQ.js → chunks/expansion-2RO5M3QC.js} +1 -1
  24. package/dist/bin/{shell/chunks/find-MTLF23HX.js → chunks/find-GAYRV4IF.js} +1 -1
  25. package/dist/bin/{shell/chunks/flag-coverage-CFWN3JJN.js → chunks/flag-coverage-A4G6STMS.js} +1 -1
  26. package/dist/bin/chunks/{help-4H52JYYC.js → help-DVG4AAGE.js} +1 -1
  27. package/dist/bin/{shell/chunks/jq-JFXEKNLN.js → chunks/jq-V7FYGIKO.js} +1 -1
  28. package/dist/bin/chunks/js-exec-JORCTVUT.js +97 -0
  29. package/dist/bin/chunks/js-exec-worker.js +4369 -0
  30. package/dist/bin/chunks/python3-PF7AHNQM.js +12 -0
  31. package/dist/bin/chunks/rg-C6KMBFNG.js +2 -0
  32. package/dist/bin/chunks/time-DDS6JJ23.js +2 -0
  33. package/dist/bin/chunks/{timeout-JJWIFL7W.js → timeout-Z24MNWOP.js} +1 -1
  34. package/dist/bin/chunks/worker.js +88 -33
  35. package/dist/bin/chunks/{xan-M6MLWZCU.js → xan-MOZFJGMY.js} +1 -1
  36. package/dist/bin/chunks/xargs-SCYIFXOW.js +2 -0
  37. package/dist/bin/chunks/{yq-YWUQUXJJ.js → yq-JJLSDDST.js} +1 -1
  38. package/dist/bin/just-bash.js +212 -211
  39. package/dist/bin/shell/chunks/{awk2-J2PNSA7C.js → awk2-VTJMI54B.js} +1 -1
  40. package/dist/bin/shell/chunks/{chunk-O5B6WWQQ.js → chunk-A3HQTYHR.js} +1 -1
  41. package/dist/bin/shell/chunks/chunk-AAW7UMPO.js +9 -0
  42. package/dist/bin/shell/chunks/{chunk-2V53PP6G.js → chunk-B3RU2PUI.js} +27 -27
  43. package/dist/bin/shell/chunks/chunk-CQG2HEAL.js +5 -0
  44. package/dist/bin/shell/chunks/chunk-DOXYBGNA.js +12 -0
  45. package/dist/bin/shell/chunks/chunk-FBJJY4ZV.js +14 -0
  46. package/dist/bin/{chunks/chunk-YAEF6X2N.js → shell/chunks/chunk-GR23MPTT.js} +1 -1
  47. package/dist/bin/{chunks/chunk-35JD7YEM.js → shell/chunks/chunk-HJEHIH4P.js} +13 -13
  48. package/dist/bin/shell/chunks/{chunk-UG4GMDQL.js → chunk-LGF54XJQ.js} +1 -1
  49. package/dist/bin/shell/chunks/chunk-LIYVQA3X.js +2 -0
  50. package/dist/bin/shell/chunks/{chunk-2BC3N3L2.js → chunk-ORUYSLP4.js} +4 -4
  51. package/dist/bin/shell/chunks/{chunk-REGSV3X5.js → chunk-SDLWFYVT.js} +1 -1
  52. package/dist/bin/shell/chunks/{chunk-STOAUD75.js → chunk-THNL3XFF.js} +8 -8
  53. package/dist/bin/shell/chunks/chunk-TKTKRRAL.js +11 -0
  54. package/dist/bin/shell/chunks/{chunk-ZJGIBTWD.js → chunk-V7ZOPVQS.js} +1 -1
  55. package/dist/bin/shell/chunks/{chunk-ZYQQ6B7B.js → chunk-ZO5PSLKR.js} +2 -2
  56. package/dist/bin/shell/chunks/curl-SRTMGOVV.js +26 -0
  57. package/dist/bin/shell/chunks/env-NTPN5QYM.js +2 -0
  58. package/dist/bin/{chunks/expansion-JBCP2CHQ.js → shell/chunks/expansion-2RO5M3QC.js} +1 -1
  59. package/dist/bin/{chunks/find-MTLF23HX.js → shell/chunks/find-GAYRV4IF.js} +1 -1
  60. package/dist/bin/{chunks/flag-coverage-CFWN3JJN.js → shell/chunks/flag-coverage-A4G6STMS.js} +1 -1
  61. package/dist/bin/shell/chunks/{help-4H52JYYC.js → help-DVG4AAGE.js} +1 -1
  62. package/dist/bin/{chunks/jq-JFXEKNLN.js → shell/chunks/jq-V7FYGIKO.js} +1 -1
  63. package/dist/bin/shell/chunks/js-exec-B6QNYHUL.js +97 -0
  64. package/dist/bin/shell/chunks/python3-J7DP4JBQ.js +12 -0
  65. package/dist/bin/shell/chunks/rg-C6KMBFNG.js +2 -0
  66. package/dist/bin/shell/chunks/time-DDS6JJ23.js +2 -0
  67. package/dist/bin/shell/chunks/{timeout-JJWIFL7W.js → timeout-Z24MNWOP.js} +1 -1
  68. package/dist/bin/shell/chunks/{xan-M6MLWZCU.js → xan-MOZFJGMY.js} +1 -1
  69. package/dist/bin/shell/chunks/xargs-SCYIFXOW.js +2 -0
  70. package/dist/bin/shell/chunks/{yq-YWUQUXJJ.js → yq-JJLSDDST.js} +1 -1
  71. package/dist/bin/shell/shell.js +212 -212
  72. package/dist/bundle/browser.js +600 -600
  73. package/dist/bundle/chunks/{awk2-FUVZGMX2.js → awk2-POPGKRAI.js} +1 -1
  74. package/dist/bundle/chunks/{chunk-DZZS6SJP.js → chunk-7TSDKFEO.js} +1 -1
  75. package/dist/bundle/chunks/{chunk-D4QDMGEB.js → chunk-BBXLRYSX.js} +2 -2
  76. package/dist/bundle/chunks/chunk-CWQS3NFK.js +1 -0
  77. package/dist/bundle/chunks/chunk-F5CMUULS.js +13 -0
  78. package/dist/bundle/chunks/{chunk-TRD56HID.js → chunk-FEIOJCZD.js} +1 -1
  79. package/dist/bundle/chunks/chunk-H2WXJGD7.js +10 -0
  80. package/dist/bundle/chunks/{chunk-D2FZX7A2.js → chunk-LPQPILI2.js} +8 -8
  81. package/dist/bundle/chunks/{chunk-2GOYXRRP.js → chunk-MLXIYONF.js} +4 -4
  82. package/dist/bundle/chunks/chunk-NAERJDUW.js +8 -0
  83. package/dist/bundle/chunks/{chunk-OKEHYWBE.js → chunk-NYQYO467.js} +13 -13
  84. package/dist/bundle/chunks/{chunk-JKLUDNMU.js → chunk-O2DBFL6Z.js} +1 -1
  85. package/dist/bundle/chunks/{chunk-JDMQDJYE.js → chunk-OARHFVLG.js} +1 -1
  86. package/dist/bundle/chunks/{chunk-AKVMAONP.js → chunk-RUF7WQ7U.js} +1 -1
  87. package/dist/bundle/chunks/chunk-TOMNU26N.js +4 -0
  88. package/dist/bundle/chunks/{chunk-ZLJ5TCLC.js → chunk-UNYNJIFU.js} +27 -27
  89. package/dist/bundle/chunks/chunk-YTNYSM6T.js +11 -0
  90. package/dist/bundle/chunks/curl-COE4TZE6.js +25 -0
  91. package/dist/bundle/chunks/env-5EPCWSXR.js +1 -0
  92. package/dist/bundle/chunks/{expansion-XG7G47TX.js → expansion-ENLSRCXJ.js} +1 -1
  93. package/dist/bundle/chunks/{find-DOIVMX6X.js → find-TPUOAIUQ.js} +1 -1
  94. package/dist/bundle/chunks/{flag-coverage-VML3BMJT.js → flag-coverage-G2R7PMYU.js} +1 -1
  95. package/dist/bundle/chunks/{help-IA5CMGR4.js → help-VVWX7SA5.js} +1 -1
  96. package/dist/bundle/chunks/{jq-SSCW4AAA.js → jq-DIRZBOTX.js} +1 -1
  97. package/dist/bundle/chunks/js-exec-YJSMH5AG.js +96 -0
  98. package/dist/bundle/chunks/js-exec-worker.js +4369 -0
  99. package/dist/bundle/chunks/python3-6HF56IYI.js +11 -0
  100. package/dist/bundle/chunks/rg-FOQSCCX3.js +1 -0
  101. package/dist/bundle/chunks/{time-XL42Z4U5.js → time-YG5BMRIQ.js} +1 -1
  102. package/dist/bundle/chunks/{timeout-QCU4INQT.js → timeout-VRKMCG72.js} +1 -1
  103. package/dist/bundle/chunks/worker.js +88 -33
  104. package/dist/bundle/chunks/{xan-K7XYDHFV.js → xan-BXDXYEIB.js} +1 -1
  105. package/dist/bundle/chunks/xargs-I6EZUCYF.js +1 -0
  106. package/dist/bundle/chunks/{yq-WTK3HUOR.js → yq-XMVSIL6Z.js} +1 -1
  107. package/dist/bundle/index.cjs +969 -870
  108. package/dist/bundle/index.js +151 -151
  109. package/dist/commands/curl/types.d.ts +1 -1
  110. package/dist/commands/js-exec/fetch-polyfill.d.ts +6 -0
  111. package/dist/commands/js-exec/js-exec.d.ts +11 -0
  112. package/dist/commands/js-exec/module-shims.d.ts +29 -0
  113. package/dist/commands/js-exec/path-polyfill.d.ts +6 -0
  114. package/dist/commands/js-exec/worker.d.ts +30 -0
  115. package/dist/commands/python3/worker.d.ts +1 -0
  116. package/dist/commands/query-engine/safe-object.d.ts +11 -0
  117. package/dist/commands/registry.d.ts +13 -2
  118. package/dist/commands/{python3/fs-bridge-handler.d.ts → worker-bridge/bridge-handler.d.ts} +25 -8
  119. package/dist/commands/{python3 → worker-bridge}/protocol.d.ts +6 -3
  120. package/dist/commands/{python3/sync-fs-backend.d.ts → worker-bridge/sync-backend.d.ts} +25 -4
  121. package/dist/index.d.cts +4 -4
  122. package/dist/index.d.ts +4 -4
  123. package/dist/interpreter/interpreter.d.ts +3 -0
  124. package/dist/interpreter/types.d.ts +8 -0
  125. package/dist/limits.d.ts +3 -1
  126. package/dist/network/allow-list.d.ts +5 -3
  127. package/dist/network/fetch.d.ts +1 -1
  128. package/dist/network/index.d.ts +1 -1
  129. package/dist/network/types.d.ts +32 -1
  130. package/dist/types.d.ts +12 -0
  131. package/package.json +13 -12
  132. package/dist/bin/chunks/chunk-47HZU3SY.js +0 -5
  133. package/dist/bin/chunks/chunk-CZFRRDQC.js +0 -12
  134. package/dist/bin/chunks/chunk-N4EU64Y4.js +0 -9
  135. package/dist/bin/chunks/chunk-QZNF3Y3J.js +0 -2
  136. package/dist/bin/chunks/chunk-VIYJJTN2.js +0 -14
  137. package/dist/bin/chunks/curl-3GMIPMCI.js +0 -26
  138. package/dist/bin/chunks/env-HOVBNLUR.js +0 -2
  139. package/dist/bin/chunks/python3-KI2FQWSN.js +0 -17
  140. package/dist/bin/chunks/rg-34GE6REQ.js +0 -2
  141. package/dist/bin/chunks/time-GZSHCM77.js +0 -2
  142. package/dist/bin/chunks/xargs-GBL6PZ2K.js +0 -2
  143. package/dist/bin/shell/chunks/chunk-47HZU3SY.js +0 -5
  144. package/dist/bin/shell/chunks/chunk-CZFRRDQC.js +0 -12
  145. package/dist/bin/shell/chunks/chunk-N4EU64Y4.js +0 -9
  146. package/dist/bin/shell/chunks/chunk-QZNF3Y3J.js +0 -2
  147. package/dist/bin/shell/chunks/chunk-VIYJJTN2.js +0 -14
  148. package/dist/bin/shell/chunks/curl-3GMIPMCI.js +0 -26
  149. package/dist/bin/shell/chunks/env-HOVBNLUR.js +0 -2
  150. package/dist/bin/shell/chunks/python3-E5X6WBBU.js +0 -17
  151. package/dist/bin/shell/chunks/rg-34GE6REQ.js +0 -2
  152. package/dist/bin/shell/chunks/time-GZSHCM77.js +0 -2
  153. package/dist/bin/shell/chunks/xargs-GBL6PZ2K.js +0 -2
  154. package/dist/bundle/chunks/chunk-3RA5L262.js +0 -8
  155. package/dist/bundle/chunks/chunk-EX62JIX3.js +0 -13
  156. package/dist/bundle/chunks/chunk-RH6GWZAJ.js +0 -1
  157. package/dist/bundle/chunks/chunk-WECLUBEQ.js +0 -11
  158. package/dist/bundle/chunks/chunk-ZSJYNBAF.js +0 -4
  159. package/dist/bundle/chunks/curl-KM2ZAUR6.js +0 -25
  160. package/dist/bundle/chunks/env-XZY4LKEO.js +0 -1
  161. package/dist/bundle/chunks/python3-2OHR6PZU.js +0 -16
  162. package/dist/bundle/chunks/rg-RAICUFGG.js +0 -1
  163. package/dist/bundle/chunks/xargs-2BBAQDTC.js +0 -1
package/dist/AGENTS.md CHANGED
@@ -66,7 +66,7 @@ const result = await bash.exec("cat input.txt | grep pattern");
66
66
 
67
67
  **Text processing**: `awk`, `cat`, `column`, `comm`, `cut`, `egrep`, `expand`, `fgrep`, `fold`, `grep`, `head`, `join`, `nl`, `paste`, `rev`, `rg`, `sed`, `sort`, `strings`, `tac`, `tail`, `tr`, `unexpand`, `uniq`, `wc`, `xargs`
68
68
 
69
- **Data processing**: `jq` (JSON), `python3`/`python` (Python via Pyodide), `sqlite3` (SQLite), `xan` (CSV), `yq` (YAML/XML/TOML/CSV)
69
+ **Data processing**: `jq` (JSON), `js-exec` (JavaScript/TypeScript via QuickJS), `python3`/`python` (Python via WASM/CPython), `sqlite3` (SQLite), `xan` (CSV), `yq` (YAML/XML/TOML/CSV)
70
70
 
71
71
  **File operations**: `basename`, `chmod`, `cp`, `dirname`, `du`, `file`, `find`, `ln`, `ls`, `mkdir`, `mv`, `od`, `pwd`, `readlink`, `rm`, `rmdir`, `split`, `stat`, `touch`, `tree`
72
72
 
package/dist/Bash.d.ts CHANGED
@@ -27,6 +27,10 @@ export interface BashLogger {
27
27
  /** Log debug messages (stdout output) */
28
28
  debug(message: string, data?: Record<string, unknown>): void;
29
29
  }
30
+ export interface JavaScriptConfig {
31
+ /** Bootstrap JavaScript code to run before user scripts */
32
+ bootstrap?: string;
33
+ }
30
34
  export interface BashOptions {
31
35
  files?: InitialFiles;
32
36
  env?: Record<string, string>;
@@ -67,6 +71,11 @@ export interface BashOptions {
67
71
  * (arbitrary code execution via CPython Emscripten).
68
72
  */
69
73
  python?: boolean;
74
+ /**
75
+ * Enable js-exec command for sandboxed JavaScript execution via QuickJS.
76
+ * Disabled by default. Can be a boolean or a config object with bootstrap code.
77
+ */
78
+ javascript?: boolean | JavaScriptConfig;
70
79
  /**
71
80
  * Optional list of command names to register.
72
81
  * If not provided, all built-in commands are available.
@@ -185,6 +194,13 @@ export interface ExecOptions {
185
194
  * When aborted, the interpreter stops executing at the next statement boundary.
186
195
  */
187
196
  signal?: AbortSignal;
197
+ /**
198
+ * Additional argv entries appended to the first executed command at the interpreter level.
199
+ * Values bypass shell parsing entirely — no escaping, splitting, or globbing.
200
+ * Like child_process.spawnSync(cmd, args). These do not set or modify the shell's
201
+ * positional parameters ($1, $2, "$@", etc.).
202
+ */
203
+ args?: string[];
188
204
  }
189
205
  export declare class Bash {
190
206
  readonly fs: IFileSystem;
@@ -197,6 +213,7 @@ export declare class Bash {
197
213
  private logger?;
198
214
  private defenseInDepthConfig?;
199
215
  private coverageWriter?;
216
+ private jsBootstrapCode?;
200
217
  private transformPlugins;
201
218
  private state;
202
219
  constructor(options?: BashOptions);
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{a,b}from"./chunk-REGSV3X5.js";import"./chunk-4PRVMER6.js";import"./chunk-MO4RPBN2.js";import"./chunk-YU6OGPZR.js";import"./chunk-SE4C7FJY.js";import"./chunk-6KZRLMG3.js";import"./chunk-GTNBSMZR.js";import"./chunk-KGOUQS5A.js";export{a as awkCommand2,b as flagsForFuzzing};
2
+ import{a,b}from"./chunk-SDLWFYVT.js";import"./chunk-4PRVMER6.js";import"./chunk-MO4RPBN2.js";import"./chunk-YU6OGPZR.js";import"./chunk-SE4C7FJY.js";import"./chunk-6KZRLMG3.js";import"./chunk-GTNBSMZR.js";import"./chunk-KGOUQS5A.js";export{a as awkCommand2,b as flagsForFuzzing};
@@ -43,7 +43,7 @@ import{a as O}from"./chunk-SE4C7FJY.js";import{e as j,f as K,g as C,h as re,i as
43
43
  `);)f=!0,u++;if(f&&u<s&&r[u]===")")return!0}if(a===0)return!1;n++;continue}if(a===1&&(o==="|"&&n+1<s&&r[n+1]==="|"||o==="&"&&n+1<s&&r[n+1]==="&"||o==="|"&&n+1<s&&r[n+1]!=="|"))return!0;n++}return!1}};var Qe=1e6,Ze=1e5,Qt=1e6,Ue=200,Zt=new Set([p.LESS,p.GREAT,p.DLESS,p.DGREAT,p.LESSAND,p.GREATAND,p.LESSGREAT,p.DLESSDASH,p.CLOBBER,p.TLESS,p.AND_GREAT,p.AND_DGREAT]),Ut=new Set([p.LESS,p.GREAT,p.DLESS,p.DGREAT,p.LESSAND,p.GREATAND,p.LESSGREAT,p.DLESSDASH,p.CLOBBER,p.TLESS]),Ht=new Set([p.LESS,p.GREAT,p.DLESS,p.DGREAT,p.LESSAND,p.GREATAND,p.LESSGREAT,p.DLESSDASH,p.CLOBBER,p.TLESS,p.AND_GREAT,p.AND_DGREAT]),G=class extends Error{line;column;token;constructor(t,r,s,n=void 0){super(`Parse error at ${r}:${s}: ${t}`),this.line=r,this.column=s,this.token=n,this.name="ParseException"}};function Cr(e){let t="",r=0;for(;r<e.length;){let s=e[r];if(s<128){t+=String.fromCharCode(s),r++;continue}if((s&224)===192){if(r+1<e.length&&(e[r+1]&192)===128&&s>=194){let n=(s&31)<<6|e[r+1]&63;t+=String.fromCharCode(n),r+=2;continue}t+=String.fromCharCode(s),r++;continue}if((s&240)===224){if(r+2<e.length&&(e[r+1]&192)===128&&(e[r+2]&192)===128){if(s===224&&e[r+1]<160){t+=String.fromCharCode(s),r++;continue}let n=(s&15)<<12|(e[r+1]&63)<<6|e[r+2]&63;if(n>=55296&&n<=57343){t+=String.fromCharCode(s),r++;continue}t+=String.fromCharCode(n),r+=3;continue}t+=String.fromCharCode(s),r++;continue}if((s&248)===240&&s<=244){if(r+3<e.length&&(e[r+1]&192)===128&&(e[r+2]&192)===128&&(e[r+3]&192)===128){if(s===240&&e[r+1]<144){t+=String.fromCharCode(s),r++;continue}let n=(s&7)<<18|(e[r+1]&63)<<12|(e[r+2]&63)<<6|e[r+3]&63;if(n>1114111){t+=String.fromCharCode(s),r++;continue}t+=String.fromCodePoint(n),r+=4;continue}t+=String.fromCharCode(s),r++;continue}t+=String.fromCharCode(s),r++}return t}function Kt(e,t,r){let s=r+1;for(;s<t.length&&/[a-zA-Z0-9_-]/.test(t[s]);)s++;return s}function He(e,t,r,s,n){let a=1,i=r+1;for(;i<t.length&&a>0;)t[i]===s?a++:t[i]===n&&a--,a>0&&i++;return a===0?i:-1}function fe(e,t,r){let s=r,n=1;for(;s<t.length&&n>0;){let a=t[s];if(a==="\\"&&s+1<t.length){s+=2;continue}if(a==="'"){let i=t.indexOf("'",s+1);if(i!==-1){s=i+1;continue}}if(a==='"'){for(s++;s<t.length&&t[s]!=='"';)t[s]==="\\"&&s+1<t.length?s+=2:s++;s<t.length&&s++;continue}a==="{"?n++:a==="}"&&n--,n>0&&s++}return s}function Xt(e,t,r){let s=r,n=!1;for(;s<t.length;){let a=t[s];if(a==="/"&&n||a==="}")break;if(a==="'"){let i=t.indexOf("'",s+1);if(i!==-1){s=i+1,n=!0;continue}}if(a==='"'){for(s++;s<t.length&&t[s]!=='"';)t[s]==="\\"&&s+1<t.length?s+=2:s++;s<t.length&&s++,n=!0;continue}a==="\\"?(s+=2,n=!0):(s++,n=!0)}return s}function Jt(e,t,r){let s=r,n="";for(;s<t.length;){let a=t[s];if(a==="*"||a==="?")n+=a,s++;else if(a==="["){let i=Or(t,s);i===-1?(n+=a,s++):(n+=t.slice(s,i+1),s=i+1)}else break}return{pattern:n,endIndex:s}}function Or(e,t){let r=t+1;for(r<e.length&&e[r]==="^"&&r++,r<e.length&&e[r]==="]"&&r++;r<e.length;){let s=e[r];if(s==="\\"&&r+1<e.length){let n=e[r+1];if(n==='"'||n==="'")return-1;r+=2;continue}if(s==="]")return r;if(s==='"'||s==="$"||s==="`")return-1;if(s==="'"){let n=e.indexOf("'",r+1);if(n!==-1){r=n+1;continue}}if(s==="["&&r+1<e.length&&e[r+1]===":"){let n=e.indexOf(":]",r+2);if(n!==-1){r=n+2;continue}}if(s==="["&&r+1<e.length&&(e[r+1]==="."||e[r+1]==="=")){let a=`${e[r+1]}]`,i=e.indexOf(a,r+2);if(i!==-1){r=i+2;continue}}r++}return-1}function Yt(e,t,r){let s="",n=r;for(;n<t.length&&t[n]!=="'";){let a=t[n];if(a==="\\"&&n+1<t.length)switch(t[n+1]){case"n":s+=`
44
44
  `,n+=2;break;case"t":s+=" ",n+=2;break;case"r":s+="\r",n+=2;break;case"\\":s+="\\",n+=2;break;case"'":s+="'",n+=2;break;case'"':s+='"',n+=2;break;case"a":s+="\x07",n+=2;break;case"b":s+="\b",n+=2;break;case"e":case"E":s+="\x1B",n+=2;break;case"f":s+="\f",n+=2;break;case"v":s+="\v",n+=2;break;case"x":{let l=[],o=n;for(;o+1<t.length&&t[o]==="\\"&&t[o+1]==="x";){let c=t.slice(o+2,o+4),u=parseInt(c,16);if(!Number.isNaN(u)&&c.length>0)l.push(u),o+=2+c.length;else break}l.length>0?(s+=Cr(l),n=o):(s+="\\x",n+=2);break}case"u":{let l=t.slice(n+2,n+6),o=parseInt(l,16);Number.isNaN(o)?(s+="\\u",n+=2):(s+=String.fromCharCode(o),n+=6);break}case"c":{if(n+2<t.length){let o=t[n+2].charCodeAt(0)&31;s+=String.fromCharCode(o),n+=3}else s+="\\c",n+=2;break}case"0":case"1":case"2":case"3":case"4":case"5":case"6":case"7":{let l="",o=n+1;for(;o<t.length&&o<n+4&&/[0-7]/.test(t[o]);)l+=t[o],o++;let c=parseInt(l,8);s+=String.fromCharCode(c),n=o;break}default:s+=a,n++}else s+=a,n++}return n<t.length&&t[n]==="'"&&n++,{part:w.literal(s),endIndex:n}}function je(e,t){let r=t.trim();return r===""?{type:"ArithmeticExpression",expression:{type:"ArithNumber",value:0}}:M(e,r)}function jt(e){let t=[],r="",s=0;for(let n=0;n<e.length;n++){let a=e[n];a==="{"?(s++,r+=a):a==="}"?(s--,r+=a):a===","&&s===0?(t.push(r),r=""):r+=a}return t.push(r),t}function en(e,t,r,s){let n=He(e,t,r,"{","}");if(n===-1)return null;let a=t.slice(r+1,n),i=a.match(/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/);if(i)return{part:{type:"BraceExpansion",items:[{type:"Range",start:Number.parseInt(i[1],10),end:Number.parseInt(i[2],10),step:i[3]?Number.parseInt(i[3],10):void 0,startStr:i[1],endStr:i[2]}]},endIndex:n+1};let l=a.match(/^([a-zA-Z])\.\.([a-zA-Z])(?:\.\.(-?\d+))?$/);return l?{part:{type:"BraceExpansion",items:[{type:"Range",start:l[1],end:l[2],step:l[3]?Number.parseInt(l[3],10):void 0}]},endIndex:n+1}:a.includes(",")&&s?{part:{type:"BraceExpansion",items:jt(a).map(u=>({type:"Word",word:w.word(s(e,u,!1,!1,!1))}))},endIndex:n+1}:a.includes(",")?{part:{type:"BraceExpansion",items:jt(a).map(u=>({type:"Word",word:w.word([w.literal(u)])}))},endIndex:n+1}:null}function Ke(e,t){let r="";for(let s of t.parts)switch(s.type){case"Literal":r+=s.value;break;case"SingleQuoted":r+=`'${s.value}'`;break;case"Escaped":r+=s.value;break;case"DoubleQuoted":r+='"';for(let n of s.parts)n.type==="Literal"||n.type==="Escaped"?r+=n.value:n.type==="ParameterExpansion"&&(r+=`\${${n.parameter}}`);r+='"';break;case"ParameterExpansion":r+=`\${${s.parameter}}`;break;case"Glob":r+=s.pattern;break;case"TildeExpansion":r+="~",s.user&&(r+=s.user);break;case"BraceExpansion":{r+="{";let n=[];for(let a of s.items)if(a.type==="Range"){let i=a.startStr??String(a.start),l=a.endStr??String(a.end);a.step!==void 0?n.push(`${i}..${l}..${a.step}`):n.push(`${i}..${l}`)}else n.push(Ke(e,a.word));n.length===1&&s.items[0].type==="Range"?r+=n[0]:r+=n.join(","),r+="}";break}default:r+=s.type}return r}function tn(e,t){return{[p.LESS]:"<",[p.GREAT]:">",[p.DGREAT]:">>",[p.LESSAND]:"<&",[p.GREATAND]:">&",[p.LESSGREAT]:"<>",[p.CLOBBER]:">|",[p.TLESS]:"<<<",[p.AND_GREAT]:"&>",[p.AND_DGREAT]:"&>>",[p.DLESS]:"<",[p.DLESSDASH]:"<"}[t]||">"}function De(e){let t=e.current(),r=t.type;if(r===p.NUMBER){let s=e.peek(1);return t.end!==s.start?!1:Ut.has(s.type)}if(r===p.FD_VARIABLE){let s=e.peek(1);return Ht.has(s.type)}return Zt.has(r)}function xe(e){let t=null,r;e.check(p.NUMBER)?t=Number.parseInt(e.advance().value,10):e.check(p.FD_VARIABLE)&&(r=e.advance().value);let s=e.advance(),n=tn(e,s.type);if(s.type===p.DLESS||s.type===p.DLESSDASH)return Lr(e,n,t,s.type===p.DLESSDASH);e.isWord()||e.error("Expected redirection target");let a=e.parseWord();return w.redirection(n,a,t,r)}function Lr(e,t,r,s){e.isWord()||e.error("Expected here-document delimiter");let n=e.advance(),a=n.value,i=n.quoted||!1;(a.startsWith("'")&&a.endsWith("'")||a.startsWith('"')&&a.endsWith('"'))&&(a=a.slice(1,-1));let l=w.redirection(s?"<<-":"<<",w.hereDoc(a,w.word([]),s,i),r);return e.addPendingHeredoc(l,a,s,i),l}function rn(e){let t=e.current().line,r=[],s=null,n=[],a=[];for(;e.check(p.ASSIGNMENT_WORD)||De(e);)e.checkIterationLimit(),e.check(p.ASSIGNMENT_WORD)?r.push(Wr(e)):a.push(xe(e));if(e.isWord())s=e.parseWord();else if(r.length>0&&(e.check(p.DBRACK_START)||e.check(p.DPAREN_START))){let l=e.advance();s=w.word([w.literal(l.value)])}for(;(!e.isStatementEnd()||e.check(p.RBRACE))&&!e.check(p.PIPE,p.PIPE_AMP);)if(e.checkIterationLimit(),De(e))a.push(xe(e));else if(e.check(p.RBRACE)){let l=e.advance();n.push(e.parseWordFromString(l.value,!1,!1))}else if(e.check(p.LBRACE)){let l=e.advance();n.push(e.parseWordFromString(l.value,!1,!1))}else if(e.check(p.DBRACK_END)){let l=e.advance();n.push(e.parseWordFromString(l.value,!1,!1))}else if(e.isWord())n.push(e.parseWord());else if(e.check(p.ASSIGNMENT_WORD)){let l=e.advance(),o=l.value,c=o.endsWith("="),u=o.endsWith("=(");if((c||u)&&(u||e.check(p.LPAREN))){let f=u?o.slice(0,-2):o.slice(0,-1);u||e.expect(p.LPAREN);let h=Xe(e);e.expect(p.RPAREN);let d=h.map(g=>Ke(e,g)),m=`${f}=(${d.join(" ")})`;n.push(e.parseWordFromString(m,!1,!1))}else n.push(e.parseWordFromString(o,l.quoted,l.singleQuoted))}else if(e.check(p.LPAREN))e.error("syntax error near unexpected token `('");else break;let i=w.simpleCommand(s,n,r,a);return i.line=t,i}function Wr(e){let t=e.expect(p.ASSIGNMENT_WORD),r=t.value,s=r.match(/^[a-zA-Z_][a-zA-Z0-9_]*/);s||e.error(`Invalid assignment: ${r}`);let n=s[0],a,i=n.length;if(r[i]==="["){let f=0,h=i+1;for(;i<r.length;i++)if(r[i]==="[")f++;else if(r[i]==="]"&&(f--,f===0))break;f!==0&&e.error(`Invalid assignment: ${r}`),a=r.slice(h,i),i++}let l=r[i]==="+";l&&i++,r[i]!=="="&&e.error(`Invalid assignment: ${r}`),i++;let o=r.slice(i);if(o==="("){let f=Xe(e);e.expect(p.RPAREN);let h=a!==void 0?`${n}[${a}]`:n;return w.assignment(h,null,l,f)}if(o===""&&e.check(p.LPAREN)){let f=e.current();if(t.end===f.start){e.advance();let h=Xe(e);e.expect(p.RPAREN);let d=a!==void 0?`${n}[${a}]`:n;return w.assignment(d,null,l,h)}}let c=o?e.parseWordFromString(o,t.quoted,t.singleQuoted,!0):null,u=a!==void 0?`${n}[${a}]`:n;return w.assignment(u,c,l,null)}var Tr=new Set([p.AMP,p.PIPE,p.PIPE_AMP,p.SEMICOLON,p.AND_AND,p.OR_OR,p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND]);function Xe(e){let t=[];for(e.skipNewlines();!e.check(p.RPAREN,p.EOF);)e.checkIterationLimit(),e.isWord()?t.push(e.parseWord()):Tr.has(e.current().type)?e.error(`syntax error near unexpected token \`${e.current().value}'`):e.advance(),e.skipNewlines();return t}function Je(e,t){e.expect(p.IF);let r=[],s=e.parseCompoundList();e.expect(p.THEN);let n=e.parseCompoundList();if(n.length===0){let l=e.check(p.FI)?"fi":e.check(p.ELSE)?"else":e.check(p.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${l}'`)}for(r.push({condition:s,body:n});e.check(p.ELIF);){e.advance();let l=e.parseCompoundList();e.expect(p.THEN);let o=e.parseCompoundList();if(o.length===0){let c=e.check(p.FI)?"fi":e.check(p.ELSE)?"else":e.check(p.ELIF)?"elif":"fi";e.error(`syntax error near unexpected token \`${c}'`)}r.push({condition:l,body:o})}let a=null;e.check(p.ELSE)&&(e.advance(),a=e.parseCompoundList(),a.length===0&&e.error("syntax error near unexpected token `fi'")),e.expect(p.FI);let i=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.ifNode(r,a,i)}function Ye(e,t){let r=e.expect(p.FOR);if(e.check(p.DPAREN_START))return Vr(e,t,r.line);e.isWord()||e.error("Expected variable name in for loop");let n=e.advance().value,a=null;if(e.skipNewlines(),e.check(p.IN))for(e.advance(),a=[];!e.check(p.SEMICOLON,p.NEWLINE,p.DO,p.EOF)&&e.isWord();)a.push(e.parseWord());e.check(p.SEMICOLON)&&e.advance(),e.skipNewlines(),e.expect(p.DO);let i=e.parseCompoundList();e.expect(p.DONE);let l=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.forNode(n,a,i,l)}function Vr(e,t,r){e.expect(p.DPAREN_START);let s=null,n=null,a=null,i=["","",""],l=0,o=0;for(;!e.check(p.DPAREN_END,p.EOF);){let f=e.advance();if(f.type===p.SEMICOLON&&o===0){if(l++,l>2)break}else f.value==="("&&o++,f.value===")"&&o--,i[l]+=f.value}e.expect(p.DPAREN_END),i[0].trim()&&(s=M(e,i[0].trim())),i[1].trim()&&(n=M(e,i[1].trim())),i[2].trim()&&(a=M(e,i[2].trim())),e.skipNewlines(),e.check(p.SEMICOLON)&&e.advance(),e.skipNewlines();let c;e.check(p.LBRACE)?(e.advance(),c=e.parseCompoundList(),e.expect(p.RBRACE)):(e.expect(p.DO),c=e.parseCompoundList(),e.expect(p.DONE));let u=t?.skipRedirections?[]:e.parseOptionalRedirections();return{type:"CStyleFor",init:s,condition:n,update:a,body:c,redirections:u,line:r}}function et(e,t){e.expect(p.WHILE);let r=e.parseCompoundList();e.expect(p.DO);let s=e.parseCompoundList();s.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(p.DONE);let n=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.whileNode(r,s,n)}function tt(e,t){e.expect(p.UNTIL);let r=e.parseCompoundList();e.expect(p.DO);let s=e.parseCompoundList();s.length===0&&e.error("syntax error near unexpected token `done'"),e.expect(p.DONE);let n=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.untilNode(r,s,n)}function nt(e,t){e.expect(p.CASE),e.isWord()||e.error("Expected word after 'case'");let r=e.parseWord();e.skipNewlines(),e.expect(p.IN),e.skipNewlines();let s=[];for(;!e.check(p.ESAC,p.EOF);){e.checkIterationLimit();let a=e.getPos(),i=qr(e);if(i&&s.push(i),e.skipNewlines(),e.getPos()===a&&!i)break}e.expect(p.ESAC);let n=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.caseNode(r,s,n)}function qr(e){e.check(p.LPAREN)&&e.advance();let t=[];for(;e.isWord()&&(t.push(e.parseWord()),e.check(p.PIPE));)e.advance();if(t.length===0)return null;e.expect(p.RPAREN),e.skipNewlines();let r=[];for(;!e.check(p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND,p.ESAC,p.EOF);){e.checkIterationLimit(),e.isWord()&&e.peek(1).type===p.RPAREN&&e.error("syntax error near unexpected token `)'"),e.check(p.LPAREN)&&e.peek(1).type===p.WORD&&e.error(`syntax error near unexpected token \`${e.peek(1).value}'`);let n=e.getPos(),a=e.parseStatement();if(a&&r.push(a),e.skipSeparators(!1),e.getPos()===n&&!a)break}let s=";;";return e.check(p.DSEMI)?(e.advance(),s=";;"):e.check(p.SEMI_AND)?(e.advance(),s=";&"):e.check(p.SEMI_SEMI_AND)&&(e.advance(),s=";;&"),w.caseItem(t,r,s)}function rt(e,t){e.expect(p.LPAREN);let r=e.parseCompoundList();e.expect(p.RPAREN);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.subshell(r,s)}function st(e,t){e.expect(p.LBRACE);let r=e.parseCompoundList();e.expect(p.RBRACE);let s=t?.skipRedirections?[]:e.parseOptionalRedirections();return w.group(r,s)}var Fr=["-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"],zr=["==","!=","=~","<",">","-eq","-ne","-lt","-le","-gt","-ge","-nt","-ot","-ef"];function sn(e){return e.isWord()||e.check(p.LBRACE)||e.check(p.RBRACE)||e.check(p.ASSIGNMENT_WORD)}function an(e){if(e.check(p.BANG)&&e.peek(1).type===p.LPAREN){e.advance(),e.advance();let t=1,r="!(";for(;t>0&&!e.check(p.EOF);)if(e.check(p.LPAREN))t++,r+="(",e.advance();else if(e.check(p.RPAREN))t--,t>0&&(r+=")"),e.advance();else if(e.isWord())r+=e.advance().value;else if(e.check(p.PIPE))r+="|",e.advance();else break;return r+=")",e.parseWordFromString(r,!1,!1,!1,!1,!0)}return e.parseWordNoBraceExpansion()}function at(e){return e.skipNewlines(),Gr(e)}function Gr(e){let t=on(e);for(e.skipNewlines();e.check(p.OR_OR);){e.advance(),e.skipNewlines();let r=on(e);t={type:"CondOr",left:t,right:r},e.skipNewlines()}return t}function on(e){let t=it(e);for(e.skipNewlines();e.check(p.AND_AND);){e.advance(),e.skipNewlines();let r=it(e);t={type:"CondAnd",left:t,right:r},e.skipNewlines()}return t}function it(e){return e.skipNewlines(),e.check(p.BANG)?(e.advance(),e.skipNewlines(),{type:"CondNot",operand:it(e)}):Qr(e)}function Qr(e){if(e.check(p.LPAREN)){e.advance();let t=at(e);return e.expect(p.RPAREN),{type:"CondGroup",expression:t}}if(sn(e)){let t=e.current(),r=t.value;if(Fr.includes(r)&&!t.quoted){if(e.advance(),e.check(p.DBRACK_END)&&e.error(`Expected operand after ${r}`),sn(e)){let a=e.parseWordNoBraceExpansion();return{type:"CondUnary",operator:r,operand:a}}let n=e.current();e.error(`unexpected argument \`${n.value}' to conditional unary operator`)}let s=e.parseWordNoBraceExpansion();if(e.isWord()&&zr.includes(e.current().value)){let n=e.advance().value,a;return n==="=~"?a=Zr(e):n==="=="||n==="!="?a=an(e):a=e.parseWordNoBraceExpansion(),{type:"CondBinary",operator:n,left:s,right:a}}if(e.check(p.LESS)){e.advance();let n=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:"<",left:s,right:n}}if(e.check(p.GREAT)){e.advance();let n=e.parseWordNoBraceExpansion();return{type:"CondBinary",operator:">",left:s,right:n}}if(e.isWord()&&e.current().value==="="){e.advance();let n=an(e);return{type:"CondBinary",operator:"==",left:s,right:n}}return{type:"CondWord",word:s}}e.error("Expected conditional expression")}function Zr(e){let t=[],r=0,s=-1,n=e.getInput(),a=()=>e.check(p.DBRACK_END)||e.check(p.AND_AND)||e.check(p.OR_OR)||e.check(p.NEWLINE)||e.check(p.EOF);for(;!a();){let i=e.current(),l=s>=0&&i.start>s;if(r===0&&l)break;if(r>0&&l){let o=n.slice(s,i.start);t.push({type:"Literal",value:o})}if(e.isWord()||e.check(p.ASSIGNMENT_WORD)){let o=e.parseWordForRegex();t.push(...o.parts),s=e.peek(-1).end}else if(e.check(p.LPAREN)){let o=e.advance();t.push({type:"Literal",value:"("}),r++,s=o.end}else if(e.check(p.DPAREN_START)){let o=e.advance();t.push({type:"Literal",value:"(("}),r+=2,s=o.end}else if(e.check(p.DPAREN_END))if(r>=2){let o=e.advance();t.push({type:"Literal",value:"))"}),r-=2,s=o.end}else{if(r===1)break;break}else if(e.check(p.RPAREN))if(r>0){let o=e.advance();t.push({type:"Literal",value:")"}),r--,s=o.end}else break;else if(e.check(p.PIPE)){let o=e.advance();t.push({type:"Literal",value:"|"}),s=o.end}else if(e.check(p.SEMICOLON))if(r>0){let o=e.advance();t.push({type:"Literal",value:";"}),s=o.end}else break;else if(r>0&&e.check(p.LESS)){let o=e.advance();t.push({type:"Literal",value:"<"}),s=o.end}else if(r>0&&e.check(p.GREAT)){let o=e.advance();t.push({type:"Literal",value:">"}),s=o.end}else if(r>0&&e.check(p.DGREAT)){let o=e.advance();t.push({type:"Literal",value:">>"}),s=o.end}else if(r>0&&e.check(p.DLESS)){let o=e.advance();t.push({type:"Literal",value:"<<"}),s=o.end}else if(r>0&&e.check(p.LESSAND)){let o=e.advance();t.push({type:"Literal",value:"<&"}),s=o.end}else if(r>0&&e.check(p.GREATAND)){let o=e.advance();t.push({type:"Literal",value:">&"}),s=o.end}else if(r>0&&e.check(p.LESSGREAT)){let o=e.advance();t.push({type:"Literal",value:"<>"}),s=o.end}else if(r>0&&e.check(p.CLOBBER)){let o=e.advance();t.push({type:"Literal",value:">|"}),s=o.end}else if(r>0&&e.check(p.TLESS)){let o=e.advance();t.push({type:"Literal",value:"<<<"}),s=o.end}else if(r>0&&e.check(p.AMP)){let o=e.advance();t.push({type:"Literal",value:"&"}),s=o.end}else if(r>0&&e.check(p.LBRACE)){let o=e.advance();t.push({type:"Literal",value:"{"}),s=o.end}else if(r>0&&e.check(p.RBRACE)){let o=e.advance();t.push({type:"Literal",value:"}"}),s=o.end}else break}return t.length===0&&e.error("Expected regex pattern after =~"),{type:"Word",parts:t}}function Ee(e){return e.length>0?e:[w.literal("")]}function Hr(e,t){let r=1,s=t+1;for(;s<e.length&&r>0;){let n=e[s];if(n==="\\"){s+=2;continue}if("@*+?!".includes(n)&&s+1<e.length&&e[s+1]==="("){s++,r++,s++;continue}if(n==="(")r++;else if(n===")"&&(r--,r===0))return s;s++}return-1}function jr(e,t,r){let s=r+1,n=t[s];if("@*#?$!-0123456789".includes(n))return{part:w.parameterExpansion(n),endIndex:s+1};let a="";for(;s<t.length&&/[a-zA-Z0-9_]/.test(t[s]);)a+=t[s],s++;return{part:w.parameterExpansion(a),endIndex:s}}function Kr(e,t,r,s=!1){let n=r+2,a=!1;t[n]==="!"&&(a=!0,n++);let i=!1;t[n]==="#"&&!/[}:#%/^,]/.test(t[n+1]||"}")&&(i=!0,n++);let l="",o=t[n];if(/[@*#?$!-]/.test(o)&&!/[a-zA-Z0-9_]/.test(t[n+1]||""))l=o,n++;else for(;n<t.length&&/[a-zA-Z0-9_]/.test(t[n]);)l+=t[n],n++;if(t[n]==="["){let u=He(e,t,n,"[","]");if(l+=t.slice(n,u+1),n=u+1,t[n]==="["){let f=1,h=n;for(;h<t.length&&f>0;)t[h]==="{"?f++:t[h]==="}"&&f--,f>0&&h++;let d=t.slice(r+2,h);return{part:w.parameterExpansion("",{type:"BadSubstitution",text:d}),endIndex:h+1}}}if(l===""&&!a&&!i&&t[n]!=="}"){let u=1,f=n;for(;f<t.length&&u>0;)t[f]==="{"?u++:t[f]==="}"&&u--,u>0&&f++;if(u>0)throw new G("unexpected EOF while looking for matching '}'",0,0);let h=t.slice(r+2,f);return{part:w.parameterExpansion("",{type:"BadSubstitution",text:h}),endIndex:f+1}}let c=null;if(a){let u=l.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[([@*])\]$/);if(u)if(n<t.length&&t[n]!=="}"&&/[:=\-+?#%/^,@]/.test(t[n])){let f=ot(e,t,n,l,s);f.operation?(c={type:"Indirection",innerOp:f.operation},n=f.endIndex):(c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},l="")}else c={type:"ArrayKeys",array:u[1],star:u[2]==="*"},l="";else if(t[n]==="*"||t[n]==="@"&&!/[QPaAEKkuUL]/.test(t[n+1]||"")){let f=t[n];n++,c={type:"VarNamePrefix",prefix:l,star:f==="*"},l=""}else if(n<t.length&&t[n]!=="}"&&/[:=\-+?#%/^,@]/.test(t[n])){let f=ot(e,t,n,l,s);f.operation?(c={type:"Indirection",innerOp:f.operation},n=f.endIndex):c={type:"Indirection"}}else c={type:"Indirection"}}else if(i)if(t[n]===":")for(c={type:"LengthSliceError"};n<t.length&&t[n]!=="}";)n++;else t[n]!=="}"&&/[-+=?]/.test(t[n])?e.error(`\${#${l}${t.slice(n,t.indexOf("}",n))}}: bad substitution`):t[n]==="/"?e.error(`\${#${l}${t.slice(n,t.indexOf("}",n))}}: bad substitution`):c={type:"Length"};if(!c&&n<t.length&&t[n]!=="}"){let u=ot(e,t,n,l,s);c=u.operation,n=u.endIndex}if(n<t.length&&t[n]!=="}"){let u=t[n];if(!/[:\-+=?#%/^,@[]/.test(u)){let f=n;for(;f<t.length&&t[f]!=="}";)f++;let h=t.slice(r,f+1);e.error(`\${${h.slice(2,-1)}}: bad substitution`)}}for(;n<t.length&&t[n]!=="}";)n++;if(n>=t.length)throw new G("unexpected EOF while looking for matching '}'",0,0);return{part:w.parameterExpansion(l,c),endIndex:n+1}}function ot(e,t,r,s,n=!1){let a=r,i=t[a],l=t[a+1]||"";if(i===":"){let o=l;if("-=?+".includes(o)){a+=2;let A=fe(e,t,a),S=t.slice(a,A),y=ae(e,S,!1,!1,!0,!1,n,!1,!1,!0),b=w.word(Ee(y));if(o==="-")return{operation:{type:"DefaultValue",word:b,checkEmpty:!0},endIndex:A};if(o==="=")return{operation:{type:"AssignDefault",word:b,checkEmpty:!0},endIndex:A};if(o==="?")return{operation:{type:"ErrorIfUnset",word:b,checkEmpty:!0},endIndex:A};if(o==="+")return{operation:{type:"UseAlternative",word:b,checkEmpty:!0},endIndex:A}}a++;let c=fe(e,t,a),u=t.slice(a,c),f=-1,h=0,d=0;for(let E=0;E<u.length;E++){let A=u[E];if(A==="("||A==="[")h++;else if(A===")"||A==="]")h--;else if(A==="?"&&h===0)d++;else if(A===":"&&h===0)if(d>0)d--;else{f=E;break}}let m=f>=0?u.slice(0,f):u,g=f>=0?u.slice(f+1):null;return{operation:{type:"Substring",offset:je(e,m),length:g!==null?je(e,g):null},endIndex:c}}if("-=?+".includes(i)){a++;let o=fe(e,t,a),c=t.slice(a,o),u=ae(e,c,!1,!1,!0,!1,n,!1,!1,!0),f=w.word(Ee(u));if(i==="-")return{operation:{type:"DefaultValue",word:f,checkEmpty:!1},endIndex:o};if(i==="=")return{operation:{type:"AssignDefault",word:f,checkEmpty:!1},endIndex:o};if(i==="?")return{operation:{type:"ErrorIfUnset",word:c?f:null,checkEmpty:!1},endIndex:o};if(i==="+")return{operation:{type:"UseAlternative",word:f,checkEmpty:!1},endIndex:o}}if(i==="#"||i==="%"){let o=l===i,c=i==="#"?"prefix":"suffix";a+=o?2:1;let u=fe(e,t,a),f=t.slice(a,u),h=ae(e,f,!1,!1,!1);return{operation:{type:"PatternRemoval",pattern:w.word(Ee(h)),side:c,greedy:o},endIndex:u}}if(i==="/"){let o=l==="/";a+=o?2:1;let c=null;t[a]==="#"?(c="start",a++):t[a]==="%"&&(c="end",a++);let u;c!==null&&(t[a]==="/"||t[a]==="}")?u=a:u=Xt(e,t,a);let f=t.slice(a,u),h=ae(e,f,!1,!1,!1),d=w.word(Ee(h)),m=null,g=u;if(t[u]==="/"){let E=u+1,A=fe(e,t,E),S=t.slice(E,A),y=ae(e,S,!1,!1,!1);m=w.word(Ee(y)),g=A}return{operation:{type:"PatternReplacement",pattern:d,replacement:m,all:o,anchor:c},endIndex:g}}if(i==="^"||i===","){let o=l===i,c=i==="^"?"upper":"lower";a+=o?2:1;let u=fe(e,t,a),f=t.slice(a,u),h=f?w.word([w.literal(f)]):null;return{operation:{type:"CaseModification",direction:c,all:o,pattern:h},endIndex:u}}return i==="@"&&/[QPaAEKkuUL]/.test(l)?{operation:{type:"Transform",operator:l},endIndex:a+2}:{operation:null,endIndex:a}}function lt(e,t,r,s=!1){let n=r+1;if(n>=t.length)return{part:w.literal("$"),endIndex:n};let a=t[n];if(a==="("&&t[n+1]==="(")return e.isDollarDparenSubshell(t,r)?e.parseCommandSubstitution(t,r):e.parseArithmeticExpansion(t,r);if(a==="["){let i=1,l=n+1;for(;l<t.length&&i>0;)t[l]==="["?i++:t[l]==="]"&&i--,i>0&&l++;if(i===0){let o=t.slice(n+1,l),c=M(e,o);return{part:w.arithmeticExpansion(c),endIndex:l+1}}}return a==="("?e.parseCommandSubstitution(t,r):a==="{"?Kr(e,t,r,s):/[a-zA-Z_0-9@*#?$!-]/.test(a)?jr(e,t,r):{part:w.literal("$"),endIndex:n}}function ln(e,t){let r=[],s=0,n="",a=()=>{n&&(r.push(w.literal(n)),n="")};for(;s<t.length;){let i=t[s];if(i==="\\"&&s+1<t.length){let l=t[s+1];if(l==="$"||l==="`"||l==='"'||l==="\\"){n+=l,s+=2;continue}n+=i,s++;continue}if(i==="$"){a();let{part:l,endIndex:o}=lt(e,t,s,!0);l&&r.push(l),s=o;continue}if(i==="`"){a();let{part:l,endIndex:o}=e.parseBacktickSubstitution(t,s,!0);r.push(l),s=o;continue}n+=i,s++}return a(),r}function Xr(e,t,r){let s=[],n=r,a="",i=()=>{a&&(s.push(w.literal(a)),a="")};for(;n<t.length&&t[n]!=='"';){let l=t[n];if(l==="\\"&&n+1<t.length){let o=t[n+1];if('"\\$`\n'.includes(o)){a+=o,n+=2;continue}a+=l,n++;continue}if(l==="$"){i();let{part:o,endIndex:c}=lt(e,t,n,!0);o&&s.push(o),n=c;continue}if(l==="`"){i();let{part:o,endIndex:c}=e.parseBacktickSubstitution(t,n,!0);s.push(o),n=c;continue}a+=l,n++}return i(),{part:w.doubleQuoted(s),endIndex:n}}function ae(e,t,r=!1,s=!1,n=!1,a=!1,i=!1,l=!1,o=!1,c=!1){if(s)return[w.singleQuoted(t)];if(r){let m=ln(e,t);return[w.doubleQuoted(m)]}if(t.length>=2&&t[0]==='"'&&t[t.length-1]==='"'){let m=t.slice(1,-1),g=!1;for(let E=0;E<m.length;E++){if(m[E]==='"'){g=!0;break}m[E]==="\\"&&E+1<m.length&&E++}if(!g){let E=ln(e,m);return[w.doubleQuoted(E)]}}let u=[],f=0,h="",d=()=>{h&&(u.push(w.literal(h)),h="")};for(;f<t.length;){let m=t[f];if(m==="\\"&&f+1<t.length){let g=t[f+1];if(o){d(),u.push(w.escaped(g)),f+=2;continue}let E=a?g==="$"||g==="`"||g===`
45
45
  `:g==="$"||g==="`"||g==='"'||g==="'"||g===`
46
- `||c&&g==="}",A=i?"*?[]\\".includes(g):"*?[]\\(){}.^+".includes(g);E?h+=g:A?(d(),u.push(w.escaped(g))):h+=`\\${g}`,f+=2;continue}if(m==="'"&&!i&&!a){d();let g=t.indexOf("'",f+1);if(g===-1){h+=t.slice(f);break}u.push(w.singleQuoted(t.slice(f+1,g))),f=g+1;continue}if(m==='"'&&!a){d();let{part:g,endIndex:E}=Xr(e,t,f+1);u.push(g),f=E+1;continue}if(m==="$"&&t[f+1]==="'"){d();let{part:g,endIndex:E}=Yt(e,t,f+2);u.push(g),f=E;continue}if(m==="$"){d();let{part:g,endIndex:E}=lt(e,t,f);g&&u.push(g),f=E;continue}if(m==="`"){d();let{part:g,endIndex:E}=e.parseBacktickSubstitution(t,f);u.push(g),f=E;continue}if(m==="~"){let g=f>0?t[f-1]:"";if(f===0||g==="="||n&&g===":"){let A=Kt(e,t,f),S=t[A];if(S===void 0||S==="/"||S===":"){d();let y=t.slice(f+1,A)||null;u.push({type:"TildeExpansion",user:y}),f=A;continue}}}if("@*+?!".includes(m)&&f+1<t.length&&t[f+1]==="("){let g=Hr(t,f+1);if(g!==-1){d();let E=t.slice(f,g+1);u.push({type:"Glob",pattern:E}),f=g+1;continue}}if(m==="*"||m==="?"||m==="["){d();let{pattern:g,endIndex:E}=Jt(e,t,f);u.push({type:"Glob",pattern:g}),f=E;continue}if(m==="{"&&!n&&!l){let g=en(e,t,f,ae);if(g){d(),u.push(g.part),f=g.endIndex;continue}}h+=m,f++}return d(),u}function un(e,t){let r=e.length,s=t+3,n=2,a=!1,i=!1;for(;s<r&&n>0;){let l=e[s];if(a){l==="'"&&(a=!1),s++;continue}if(i){if(l==="\\"){s+=2;continue}l==='"'&&(i=!1),s++;continue}if(l==="'"){a=!0,s++;continue}if(l==='"'){i=!0,s++;continue}if(l==="\\"){s+=2;continue}if(l==="("){n++,s++;continue}if(l===")"){if(n--,n===1){let o=s+1;return!(o<r&&e[o]===")")}if(n===0)return!1;s++;continue}if(n===1&&(l==="|"&&s+1<r&&e[s+1]==="|"||l==="&"&&s+1<r&&e[s+1]==="&"||l==="|"&&s+1<r&&e[s+1]!=="|"))return!0;s++}return!1}function cn(e,t,r,s){let n=t+2,a=1,i=n,l=!1,o=!1,c=0,u=!1,f="";for(;i<e.length&&a>0;){let g=e[i];l?g==="'"&&(l=!1):o?g==="\\"&&i+1<e.length?i++:g==='"'&&(o=!1):g==="'"?(l=!0,f=""):g==='"'?(o=!0,f=""):g==="\\"&&i+1<e.length?(i++,f=""):/[a-zA-Z_]/.test(g)?f+=g:(f==="case"?(c++,u=!1):f==="in"&&c>0?u=!0:f==="esac"&&c>0&&(c--,u=!1),f="",g==="("?i>0&&e[i-1]==="$"?a++:u||a++:g===")"?u?u=!1:a--:g===";"&&c>0&&i+1<e.length&&e[i+1]===";"&&(u=!0)),a>0&&i++}a>0&&s("unexpected EOF while looking for matching `)'");let h=e.slice(n,i),m=r().parse(h);return{part:w.commandSubstitution(m,!1),endIndex:i+1}}function fn(e,t,r,s,n){let i=t+1,l="";for(;i<e.length&&e[i]!=="`";)if(e[i]==="\\"){let u=e[i+1];u==="$"||u==="`"||u==="\\"||u===`
46
+ `||c&&g==="}",A=i?"*?[]\\".includes(g):"*?[]\\(){}.^+".includes(g);E?h+=g:A?(d(),u.push(w.escaped(g))):h+=`\\${g}`,f+=2;continue}if(m==="'"&&!i&&!a){d();let g=t.indexOf("'",f+1);if(g===-1){h+=t.slice(f);break}u.push(w.singleQuoted(t.slice(f+1,g))),f=g+1;continue}if(m==='"'&&!a){d();let{part:g,endIndex:E}=Xr(e,t,f+1);u.push(g),f=E+1;continue}if(m==="$"&&t[f+1]==="'"){d();let{part:g,endIndex:E}=Yt(e,t,f+2);u.push(g),f=E;continue}if(m==="$"){d();let{part:g,endIndex:E}=lt(e,t,f);g&&u.push(g),f=E;continue}if(m==="`"){d();let{part:g,endIndex:E}=e.parseBacktickSubstitution(t,f);u.push(g),f=E;continue}if(m==="~"){let g=f>0?t[f-1]:"";if(f===0||g==="="||n&&g===":"){let A=Kt(e,t,f),S=t[A];if(S===void 0||S==="/"||S===":"){d();let y=t.slice(f+1,A)||null;u.push({type:"TildeExpansion",user:y}),f=A;continue}}}if("@*+?!".includes(m)&&f+1<t.length&&t[f+1]==="("){let g=Hr(t,f+1);if(g!==-1){d();let E=t.slice(f,g+1);u.push({type:"Glob",pattern:E}),f=g+1;continue}}if(m==="*"||m==="?"||m==="["){d();let{pattern:g,endIndex:E}=Jt(e,t,f);u.push({type:"Glob",pattern:g}),f=E;continue}if(m==="{"&&!n&&!l&&!a){let g=en(e,t,f,ae);if(g){d(),u.push(g.part),f=g.endIndex;continue}}h+=m,f++}return d(),u}function un(e,t){let r=e.length,s=t+3,n=2,a=!1,i=!1;for(;s<r&&n>0;){let l=e[s];if(a){l==="'"&&(a=!1),s++;continue}if(i){if(l==="\\"){s+=2;continue}l==='"'&&(i=!1),s++;continue}if(l==="'"){a=!0,s++;continue}if(l==='"'){i=!0,s++;continue}if(l==="\\"){s+=2;continue}if(l==="("){n++,s++;continue}if(l===")"){if(n--,n===1){let o=s+1;return!(o<r&&e[o]===")")}if(n===0)return!1;s++;continue}if(n===1&&(l==="|"&&s+1<r&&e[s+1]==="|"||l==="&"&&s+1<r&&e[s+1]==="&"||l==="|"&&s+1<r&&e[s+1]!=="|"))return!0;s++}return!1}function cn(e,t,r,s){let n=t+2,a=1,i=n,l=!1,o=!1,c=0,u=!1,f="";for(;i<e.length&&a>0;){let g=e[i];l?g==="'"&&(l=!1):o?g==="\\"&&i+1<e.length?i++:g==='"'&&(o=!1):g==="'"?(l=!0,f=""):g==='"'?(o=!0,f=""):g==="\\"&&i+1<e.length?(i++,f=""):/[a-zA-Z_]/.test(g)?f+=g:(f==="case"?(c++,u=!1):f==="in"&&c>0?u=!0:f==="esac"&&c>0&&(c--,u=!1),f="",g==="("?i>0&&e[i-1]==="$"?a++:u||a++:g===")"?u?u=!1:a--:g===";"&&c>0&&i+1<e.length&&e[i+1]===";"&&(u=!0)),a>0&&i++}a>0&&s("unexpected EOF while looking for matching `)'");let h=e.slice(n,i),m=r().parse(h);return{part:w.commandSubstitution(m,!1),endIndex:i+1}}function fn(e,t,r,s,n){let i=t+1,l="";for(;i<e.length&&e[i]!=="`";)if(e[i]==="\\"){let u=e[i+1];u==="$"||u==="`"||u==="\\"||u===`
47
47
  `||r&&u==='"'?(u!==`
48
48
  `&&(l+=u),i+=2):(l+=e[i],i++)}else l+=e[i],i++;i>=e.length&&n("unexpected EOF while looking for matching ``'");let c=s().parse(l);return{part:w.commandSubstitution(c,!0),endIndex:i+1}}var V=class e{tokens=[];pos=0;pendingHeredocs=[];parseIterations=0;parseDepth=0;_input="";getInput(){return this._input}checkIterationLimit(){if(this.parseIterations++,this.parseIterations>Qt)throw new G("Maximum parse iterations exceeded (possible infinite loop)",this.current().line,this.current().column)}enterDepth(){if(this.parseDepth++,this.parseDepth>Ue)throw new G(`Maximum parser nesting depth exceeded (${Ue})`,this.current().line,this.current().column);return()=>{this.parseDepth--}}parse(t,r){if(t.length>Qe)throw new G(`Input too large: ${t.length} bytes exceeds limit of ${Qe}`,1,1);this._input=t;let s=new ve(t,r);if(this.tokens=s.tokenize(),this.tokens.length>Ze)throw new G(`Too many tokens: ${this.tokens.length} exceeds limit of ${Ze}`,1,1);return this.pos=0,this.pendingHeredocs=[],this.parseIterations=0,this.parseDepth=0,this.parseScript()}parseTokens(t){return this.tokens=t,this.pos=0,this.pendingHeredocs=[],this.parseIterations=0,this.parseDepth=0,this.parseScript()}current(){return this.tokens[this.pos]||this.tokens[this.tokens.length-1]}peek(t=0){return this.tokens[this.pos+t]||this.tokens[this.tokens.length-1]}advance(){let t=this.current();return this.pos<this.tokens.length-1&&this.pos++,t}getPos(){return this.pos}check(t,r,s,n,...a){let i=this.tokens[this.pos]?.type;return i===t||r!==void 0&&i===r||s!==void 0&&i===s||n!==void 0&&i===n?!0:a.length>0?a.includes(i):!1}expect(t,r){if(this.check(t))return this.advance();let s=this.current();throw new G(r||`Expected ${t}, got ${s.type}`,s.line,s.column,s)}error(t){let r=this.current();throw new G(t,r.line,r.column,r)}skipNewlines(){for(;this.check(p.NEWLINE,p.COMMENT);)this.check(p.NEWLINE)?(this.advance(),this.processHeredocs()):this.advance()}skipSeparators(t=!0){for(;;){if(this.check(p.NEWLINE)){this.advance(),this.processHeredocs();continue}if(this.check(p.SEMICOLON,p.COMMENT)){this.advance();continue}if(t&&this.check(p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND)){this.advance();continue}break}}addPendingHeredoc(t,r,s,n){this.pendingHeredocs.push({redirect:t,delimiter:r,stripTabs:s,quoted:n})}processHeredocs(){for(let t of this.pendingHeredocs)if(this.check(p.HEREDOC_CONTENT)){let r=this.advance(),s;t.quoted?s=w.word([w.literal(r.value)]):s=this.parseWordFromString(r.value,!1,!1,!1,!0),t.redirect.target=w.hereDoc(t.delimiter,s,t.stripTabs,t.quoted)}this.pendingHeredocs=[]}isStatementEnd(){return this.check(p.EOF,p.NEWLINE,p.SEMICOLON,p.AMP,p.AND_AND,p.OR_OR,p.RPAREN,p.RBRACE,p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND)}isCommandStart(){let t=this.current().type;return t===p.WORD||t===p.NAME||t===p.NUMBER||t===p.ASSIGNMENT_WORD||t===p.IF||t===p.FOR||t===p.WHILE||t===p.UNTIL||t===p.CASE||t===p.LPAREN||t===p.LBRACE||t===p.DPAREN_START||t===p.DBRACK_START||t===p.FUNCTION||t===p.BANG||t===p.TIME||t===p.IN||t===p.LESS||t===p.GREAT||t===p.DLESS||t===p.DGREAT||t===p.LESSAND||t===p.GREATAND||t===p.LESSGREAT||t===p.DLESSDASH||t===p.CLOBBER||t===p.TLESS||t===p.AND_GREAT||t===p.AND_DGREAT}parseScript(){let t=[],s=0;for(this.skipNewlines();!this.check(p.EOF);){s++,s>1e4&&this.error("Parser stuck: too many iterations (>10000)");let n=this.checkUnexpectedToken();if(n){t.push(n),this.skipSeparators(!1);continue}let a=this.pos,i=this.parseStatement();i&&t.push(i),this.skipSeparators(!1),this.check(p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${this.current().value}'`),this.pos===a&&!this.check(p.EOF)&&this.advance()}return w.script(t)}checkUnexpectedToken(){let t=this.current().type,r=this.current().value;if((t===p.DO||t===p.DONE||t===p.THEN||t===p.ELSE||t===p.ELIF||t===p.FI||t===p.ESAC)&&this.error(`syntax error near unexpected token \`${r}'`),t===p.RBRACE||t===p.RPAREN){let s=`syntax error near unexpected token \`${r}'`;return this.advance(),w.statement([w.pipeline([w.simpleCommand(null,[],[],[])])],[],!1,{message:s,token:r})}return(t===p.DSEMI||t===p.SEMI_AND||t===p.SEMI_SEMI_AND)&&this.error(`syntax error near unexpected token \`${r}'`),t===p.SEMICOLON&&this.error(`syntax error near unexpected token \`${r}'`),(t===p.PIPE||t===p.PIPE_AMP)&&this.error(`syntax error near unexpected token \`${r}'`),null}parseStatement(){if(this.skipNewlines(),!this.isCommandStart())return null;let t=this.current().start,r=[],s=[],n=!1,a=this.parsePipeline();for(r.push(a);this.check(p.AND_AND,p.OR_OR);){let o=this.advance();s.push(o.type===p.AND_AND?"&&":"||"),this.skipNewlines();let c=this.parsePipeline();r.push(c)}this.check(p.AMP)&&(this.advance(),n=!0);let i=this.pos>0?this.tokens[this.pos-1].end:t,l=this._input.slice(t,i);return w.statement(r,s,n,void 0,l)}parsePipeline(){let t=!1,r=!1;this.check(p.TIME)&&(this.advance(),t=!0,this.check(p.WORD,p.NAME)&&this.current().value==="-p"&&(this.advance(),r=!0));let s=0;for(;this.check(p.BANG);)this.advance(),s++;let n=s%2===1,a=[],i=[],l=this.parseCommand();for(a.push(l);this.check(p.PIPE,p.PIPE_AMP);){let o=this.advance();this.skipNewlines(),i.push(o.type===p.PIPE_AMP);let c=this.parseCommand();a.push(c)}return w.pipeline(a,n,t,r,i.length>0?i:void 0)}parseCommand(){return this.check(p.IF)?Je(this):this.check(p.FOR)?Ye(this):this.check(p.WHILE)?et(this):this.check(p.UNTIL)?tt(this):this.check(p.CASE)?nt(this):this.check(p.LPAREN)?rt(this):this.check(p.LBRACE)?st(this):this.check(p.DPAREN_START)?this.dparenClosesWithSpacedParens()?this.parseNestedSubshellsFromDparen():this.parseArithmeticCommand():this.check(p.DBRACK_START)?this.parseConditionalCommand():this.check(p.FUNCTION)?this.parseFunctionDef():this.check(p.NAME,p.WORD)&&this.peek(1).type===p.LPAREN&&this.peek(2).type===p.RPAREN?this.parseFunctionDef():rn(this)}dparenClosesWithSpacedParens(){let t=1,r=1;for(;r<this.tokens.length-this.pos;){let s=this.peek(r);if(s.type===p.EOF)return!1;if(s.type===p.DPAREN_START||s.type===p.LPAREN)t++;else if(s.type===p.DPAREN_END){if(t-=2,t<=0)return!1}else if(s.type===p.RPAREN&&(t--,t===0&&this.peek(r+1).type===p.RPAREN))return!0;r++}return!1}parseNestedSubshellsFromDparen(){this.advance();let t=this.parseCompoundList();this.expect(p.RPAREN),this.expect(p.RPAREN);let r=this.parseOptionalRedirections(),s=w.subshell(t,[]);return w.subshell([w.statement([w.pipeline([s],!1,!1,!1)])],r)}isWord(){let t=this.current().type;return t===p.WORD||t===p.NAME||t===p.NUMBER||t===p.IF||t===p.FOR||t===p.WHILE||t===p.UNTIL||t===p.CASE||t===p.FUNCTION||t===p.ELSE||t===p.ELIF||t===p.FI||t===p.THEN||t===p.DO||t===p.DONE||t===p.ESAC||t===p.IN||t===p.SELECT||t===p.TIME||t===p.COPROC||t===p.BANG}parseWord(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted)}parseWordNoBraceExpansion(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted,!1,!1,!0)}parseWordForRegex(){let t=this.advance();return this.parseWordFromString(t.value,t.quoted,t.singleQuoted,!1,!1,!0,!0)}parseWordFromString(t,r=!1,s=!1,n=!1,a=!1,i=!1,l=!1){let o=ae(this,t,r,s,n,a,!1,i,l);return w.word(o)}parseCommandSubstitution(t,r){return cn(t,r,()=>new e,s=>this.error(s))}parseBacktickSubstitution(t,r,s=!1){return fn(t,r,s,()=>new e,n=>this.error(n))}isDollarDparenSubshell(t,r){return un(t,r)}parseArithmeticExpansion(t,r){let s=r+3,n=1,a=0,i=s;for(;i<t.length-1&&n>0;)t[i]==="$"&&t[i+1]==="("?t[i+2]==="("?(n++,i+=3):(a++,i+=2):t[i]==="("&&t[i+1]==="("?(n++,i+=2):t[i]===")"&&t[i+1]===")"?a>0?(a--,i++):(n--,n>0&&(i+=2)):t[i]==="("?(a++,i++):(t[i]===")"&&a>0&&a--,i++);let l=t.slice(s,i),o=this.parseArithmeticExpression(l);return{part:w.arithmeticExpansion(o),endIndex:i+2}}parseArithmeticCommand(){let t=this.expect(p.DPAREN_START),r="",s=1,n=0,a=!1,i=!1;for(;s>0&&!this.check(p.EOF);){if(a){if(a=!1,n>0){n--,r+=")";continue}if(this.check(p.RPAREN)){s--,i=!0,this.advance();continue}if(this.check(p.DPAREN_END)){s--,i=!0;continue}r+=")";continue}if(this.check(p.DPAREN_START))s++,r+="((",this.advance();else if(this.check(p.DPAREN_END))n>=2?(n-=2,r+="))",this.advance()):n===1?(n--,r+=")",a=!0,this.advance()):(s--,i=!0,s>0&&(r+="))"),this.advance());else if(this.check(p.LPAREN))n++,r+="(",this.advance();else if(this.check(p.RPAREN))n>0&&n--,r+=")",this.advance();else{let c=this.current().value,u=r.length>0?r[r.length-1]:"";r.length>0&&!r.endsWith(" ")&&!(c==="="&&/[|&^+\-*/%<>]$/.test(r))&&!(c==="<"&&u==="<")&&!(c===">"&&u===">")&&(r+=" "),r+=c,this.advance()}}i||this.expect(p.DPAREN_END);let l=this.parseArithmeticExpression(r.trim()),o=this.parseOptionalRedirections();return w.arithmeticCommand(l,o,t.line)}parseConditionalCommand(){let t=this.expect(p.DBRACK_START),r=at(this);this.expect(p.DBRACK_END);let s=this.parseOptionalRedirections();return w.conditionalCommand(r,s,t.line)}parseFunctionDef(){let t;if(this.check(p.FUNCTION)){if(this.advance(),this.check(p.NAME)||this.check(p.WORD))t=this.advance().value;else{let n=this.current();throw new G("Expected function name",n.line,n.column,n)}this.check(p.LPAREN)&&(this.advance(),this.expect(p.RPAREN))}else t=this.advance().value,t.includes("$")&&this.error(`\`${t}': not a valid identifier`),this.expect(p.LPAREN),this.expect(p.RPAREN);this.skipNewlines();let r=this.parseCompoundCommandBody({forFunctionBody:!0}),s=this.parseOptionalRedirections();return w.functionDef(t,r,s)}parseCompoundCommandBody(t){let r=t?.forFunctionBody;if(this.check(p.LBRACE))return st(this,{skipRedirections:r});if(this.check(p.LPAREN))return rt(this,{skipRedirections:r});if(this.check(p.IF))return Je(this,{skipRedirections:r});if(this.check(p.FOR))return Ye(this,{skipRedirections:r});if(this.check(p.WHILE))return et(this,{skipRedirections:r});if(this.check(p.UNTIL))return tt(this,{skipRedirections:r});if(this.check(p.CASE))return nt(this,{skipRedirections:r});this.error("Expected compound command for function body")}parseCompoundList(){let t=this.enterDepth(),r=[];for(this.skipNewlines();!this.check(p.EOF,p.FI,p.ELSE,p.ELIF,p.THEN,p.DO,p.DONE,p.ESAC,p.RPAREN,p.RBRACE,p.DSEMI,p.SEMI_AND,p.SEMI_SEMI_AND)&&this.isCommandStart();){this.checkIterationLimit();let s=this.pos,n=this.parseStatement();if(n&&r.push(n),this.skipSeparators(),this.pos===s&&!n)break}return t(),r}parseOptionalRedirections(){let t=[];for(;De(this);){this.checkIterationLimit();let r=this.pos;if(t.push(xe(this)),this.pos===r)break}return t}parseArithmeticExpression(t){return M(this,t)}};function di(e,t){return new V().parse(e,t)}var Yr=new Map([["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 ut(e){return Yr.get(e)??""}function hn(e){let t=[],r="",s=0;for(;s<e.length;){let n=e[s];if(n==="["){for(r+=n,s++,s<e.length&&(e[s]==="!"||e[s]==="^")&&(r+=e[s],s++),s<e.length&&e[s]==="]"&&(r+=e[s],s++);s<e.length&&e[s]!=="]";){if(e[s]==="["&&s+1<e.length&&e[s+1]===":"){let a=e.indexOf(":]",s+2);if(a!==-1){r+=e.slice(s,a+2),s=a+2;continue}}if(e[s]==="\\"&&s+1<e.length){r+=e[s]+e[s+1],s+=2;continue}r+=e[s],s++}s<e.length&&e[s]==="]"&&(r+=e[s],s++)}else n===":"?(r!==""&&t.push(r),r="",s++):n==="\\"&&s+1<e.length?(r+=n+e[s+1],s+=2):(r+=n,s++)}return r!==""&&t.push(r),t}function pn(e){let t="^";for(let r=0;r<e.length;r++){let s=e[r];if(s==="*")t+="[^/]*";else if(s==="?")t+="[^/]";else if(s==="["){let n=r+1,a="[";n<e.length&&(e[n]==="^"||e[n]==="!")&&(a+="^",n++),n<e.length&&e[n]==="]"&&(a+="\\]",n++);let i=n;for(;i<e.length;){if(e[i]==="\\"&&i+1<e.length){i+=2;continue}if(e[i]==="["&&i+1<e.length&&e[i+1]===":"){let o=e.indexOf(":]",i+2);if(o!==-1){i=o+2;continue}}if(e[i]==="]")break;i++}let l=n;for(;n<e.length&&e[n]!=="]";){if(e[n]==="["&&n+1<e.length&&e[n+1]===":"){let o=e.indexOf(":]",n+2);if(o!==-1){let c=e.slice(n+2,o),u=ut(c);a+=u,n=o+2;continue}}if(e[n]==="\\"&&n+1<e.length){a+=`\\${e[n+1]}`,n+=2;continue}if(e[n]==="-"){let o=n===l,c=n+1===i;o||c?a+="\\-":a+="-"}else a+=e[n];n++}a+="]",t+=a,r=n}else if(s==="\\"&&r+1<e.length){let n=e[r+1];/[.+^${}()|\\*?[\]]/.test(n)?t+=`\\${n}`:t+=n,r++}else/[.+^${}()|]/.test(s)?t+=`\\${s}`:t+=s}return t+="$",O(t)}function ct(e,t){let r=1,s=t+1;for(;s<e.length&&r>0;){let n=e[s];if(n==="\\"){s+=2;continue}if(n==="(")r++;else if(n===")"&&(r--,r===0))return s;s++}return-1}function ft(e){let t=[],r="",s=0,n=!1,a=0;for(;a<e.length;){let i=e[a];if(i==="'"&&!n){n=!0,r+="\0QUOTE_START\0",a++;continue}if(i==="'"&&n){n=!1,r+="\0QUOTE_END\0",a++;continue}if(n){r+=i,a++;continue}if(i==="\\"){r+=i,a+1<e.length?(r+=e[a+1],a+=2):a++;continue}i==="("?(s++,r+=i):i===")"?(s--,r+=i):i==="|"&&s===0?(t.push(r),r=""):r+=i,a++}return t.push(r),t}var dn=5,oe=class{fs;cwd;globignorePatterns=[];hasGlobignore=!1;globstar=!1;nullglob=!1;failglob=!1;dotglob=!1;extglob=!1;globskipdots=!0;ops={count:0};maxOps;constructor(t,r,s,n){this.fs=t,this.cwd=r,typeof n=="boolean"?(this.globstar=n,this.maxOps=1e5):n?(this.globstar=n.globstar??!1,this.nullglob=n.nullglob??!1,this.failglob=n.failglob??!1,this.dotglob=n.dotglob??!1,this.extglob=n.extglob??!1,this.globskipdots=n.globskipdots??!0,this.maxOps=n.maxGlobOperations??1e5):this.maxOps=1e5;let a=s?.get("GLOBIGNORE");a!==void 0&&a!==""&&(this.hasGlobignore=!0,this.globignorePatterns=hn(a))}checkOpsLimit(){if(++this.ops.count>this.maxOps)throw new L(`Glob operation limit exceeded (${this.maxOps})`,"glob_operations")}hasNullglob(){return this.nullglob}hasFailglob(){return this.failglob}filterGlobignore(t){return!this.hasGlobignore&&!this.globskipdots?t:t.filter(r=>{let s=r.split("/").pop()||r;if((this.hasGlobignore||this.globskipdots)&&(s==="."||s===".."))return!1;if(this.hasGlobignore){for(let n of this.globignorePatterns)if(this.matchGlobignorePattern(r,n))return!1}return!0})}matchGlobignorePattern(t,r){return pn(r).test(t)}isGlobPattern(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandArgs(t,r){let s=t.map((i,l)=>(r?.[l]??!1)||!this.isGlobPattern(i)?null:this.expand(i)),n=await Promise.all(s.map(i=>i||Promise.resolve(null))),a=[];for(let i=0;i<t.length;i++){let l=n[i];l===null?a.push(t[i]):l.length>0?a.push(...l):a.push(t[i])}return a}async expand(t){if(this.globstar){let s=t.split("/"),n=0;for(let a of s)if(a==="**"&&(n++,n>dn))throw new L(`Glob pattern has too many ** segments (max ${dn})`,"glob_operations")}let r;if(t.includes("**")&&this.globstar&&this.isGlobstarValid(t))r=await this.expandRecursive(t);else{let s=t.replace(/\*\*+/g,"*");r=await this.expandSimple(s)}return this.filterGlobignore(r)}isGlobstarValid(t){let r=t.split("/");for(let s of r)if(s.includes("**")&&s!=="**")return!1;return!0}hasGlobChars(t){return!!(t.includes("*")||t.includes("?")||/\[.*\]/.test(t)||this.extglob&&/[@*+?!]\(/.test(t))}async expandSimple(t){let r=t.startsWith("/"),s=t.split("/").filter(c=>c!==""),n=-1;for(let c=0;c<s.length;c++)if(this.hasGlobChars(s[c])){n=c;break}if(n===-1)return[t];let a,i;if(n===0)r?(a="/",i="/"):(a=this.cwd,i="");else{let c=s.slice(0,n);r?(a=`/${c.join("/")}`,i=`/${c.join("/")}`):(a=this.fs.resolvePath(this.cwd,c.join("/")),i=c.join("/"))}let l=s.slice(n);return(await this.expandSegments(a,i,l)).sort()}async expandSegments(t,r,s){if(this.checkOpsLimit(),s.length===0)return[r];let[n,...a]=s,i=[];try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let l=await this.fs.readdirWithFileTypes(t),o=[],c=[...l],u=this.dotglob||this.hasGlobignore;if(n.startsWith(".")||this.dotglob){let h=l.some(m=>m.name==="."),d=l.some(m=>m.name==="..");h||c.push({name:".",isFile:!1,isDirectory:!0,isSymbolicLink:!1}),d||c.push({name:"..",isFile:!1,isDirectory:!0,isSymbolicLink:!1})}for(let h of c)if(!(h.name.startsWith(".")&&!n.startsWith(".")&&!u)&&this.matchPattern(h.name,n)){let d=t==="/"?`/${h.name}`:`${t}/${h.name}`,m;r===""?m=h.name:r==="/"?m=`/${h.name}`:m=`${r}/${h.name}`,a.length===0?o.push(Promise.resolve([m])):h.isDirectory&&o.push(this.expandSegments(d,m,a))}let f=await Promise.all(o);for(let h of f)i.push(...h)}else{this.checkOpsLimit();let l=await this.fs.readdir(t),o=[],c=[...l],u=this.dotglob||this.hasGlobignore;(n.startsWith(".")||this.dotglob)&&(l.includes(".")||c.push("."),l.includes("..")||c.push(".."));for(let h of c)if(!(h.startsWith(".")&&!n.startsWith(".")&&!u)&&this.matchPattern(h,n)){let d=t==="/"?`/${h}`:`${t}/${h}`,m;r===""?m=h:r==="/"?m=`/${h}`:m=`${r}/${h}`,a.length===0?o.push(Promise.resolve([m])):o.push((async()=>{try{if(this.checkOpsLimit(),(await this.fs.stat(d)).isDirectory)return this.expandSegments(d,m,a)}catch(g){if(g instanceof L)throw g}return[]})())}let f=await Promise.all(o);for(let h of f)i.push(...h)}}catch(l){if(l instanceof L)throw l}return i}async expandRecursive(t){let r=[],s=t.indexOf("**"),n=t.slice(0,s).replace(/\/$/,"")||".",i=t.slice(s+2).replace(/^\//,"");return i.includes("**")&&this.isGlobstarValid(i)?(await this.walkDirectoryMultiGlobstar(n,i,r),[...new Set(r)].sort()):(await this.walkDirectory(n,i,r),r.sort())}async walkDirectoryMultiGlobstar(t,r,s){this.checkOpsLimit();let n=this.fs.resolvePath(this.cwd,t);try{this.checkOpsLimit();let a=this.fs.readdirWithFileTypes?await this.fs.readdirWithFileTypes(n):null;if(a){let i=[];for(let c of a){let u=t==="."?c.name:`${t}/${c.name}`;c.isDirectory&&i.push(u)}let l=t==="."?r:`${t}/${r}`,o=await this.expandRecursive(l);s.push(...o);for(let c=0;c<i.length;c+=100){let u=i.slice(c,c+100);await Promise.all(u.map(f=>this.walkDirectoryMultiGlobstar(f,r,s)))}}else{this.checkOpsLimit();let i=await this.fs.readdir(n),l=[];for(let u of i){let f=t==="."?u:`${t}/${u}`,h=this.fs.resolvePath(this.cwd,f);try{this.checkOpsLimit(),(await this.fs.stat(h)).isDirectory&&l.push(f)}catch(d){if(d instanceof L)throw d}}let o=t==="."?r:`${t}/${r}`,c=await this.expandRecursive(o);s.push(...c);for(let u=0;u<l.length;u+=100){let f=l.slice(u,u+100);await Promise.all(f.map(h=>this.walkDirectoryMultiGlobstar(h,r,s)))}}}catch(a){if(a instanceof L)throw a}}async walkDirectory(t,r,s){this.checkOpsLimit();let n=this.fs.resolvePath(this.cwd,t);try{if(this.fs.readdirWithFileTypes){this.checkOpsLimit();let a=await this.fs.readdirWithFileTypes(n),i=[],l=[];for(let o of a){let c=t==="."?o.name:`${t}/${o.name}`;o.isDirectory?l.push(c):r&&this.matchPattern(o.name,r)&&i.push(c)}s.push(...i);for(let o=0;o<l.length;o+=100){let c=l.slice(o,o+100);await Promise.all(c.map(u=>this.walkDirectory(u,r,s)))}}else{this.checkOpsLimit();let a=await this.fs.readdir(n),i=[];for(let o=0;o<a.length;o+=100){let c=a.slice(o,o+100),u=await Promise.all(c.map(async f=>{let h=t==="."?f:`${t}/${f}`,d=this.fs.resolvePath(this.cwd,h);try{this.checkOpsLimit();let m=await this.fs.stat(d);return{name:f,path:h,isDirectory:m.isDirectory}}catch(m){if(m instanceof L)throw m;return null}}));i.push(...u.filter(f=>f!==null))}for(let o of i)!o.isDirectory&&r&&this.matchPattern(o.name,r)&&s.push(o.path);let l=i.filter(o=>o.isDirectory);for(let o=0;o<l.length;o+=100){let c=l.slice(o,o+100);await Promise.all(c.map(u=>this.walkDirectory(u.path,r,s)))}}}catch(a){if(a instanceof L)throw a}}matchPattern(t,r){return this.patternToRegex(r).test(t)}patternToRegex(t){let r=this.patternToRegexStr(t);return O(`^${r}$`)}patternToRegexStr(t){let r="",s=!1;for(let n=0;n<t.length;n++){if(t.slice(n,n+13)==="\0QUOTE_START\0"){s=!0,n+=12;continue}if(t.slice(n,n+11)==="\0QUOTE_END\0"){s=!1,n+=10;continue}let a=t[n];if(s){/[.+^${}()|\\*?[\]]/.test(a)?r+=`\\${a}`:r+=a;continue}if(this.extglob&&(a==="@"||a==="*"||a==="+"||a==="?"||a==="!")&&n+1<t.length&&t[n+1]==="("){let i=ct(t,n+1);if(i!==-1){let l=t.slice(n+2,i),o=ft(l),c=o.map(f=>this.patternToRegexStr(f)),u=c.length>0?c.join("|"):"(?:)";if(a==="@")r+=`(?:${u})`;else if(a==="*")r+=`(?:${u})*`;else if(a==="+")r+=`(?:${u})+`;else if(a==="?")r+=`(?:${u})?`;else if(a==="!")if(i<t.length-1){let h=o.map(m=>this.computePatternLength(m));if(h.every(m=>m!==null)&&h.every(m=>m===h[0])&&h[0]!==null){let m=h[0];if(m===0)r+="(?:.+)";else{let g=[];m>0&&g.push(`.{0,${m-1}}`),g.push(`.{${m+1},}`),g.push(`(?!(?:${u})).{${m}}`),r+=`(?:${g.join("|")})`}}else r+=`(?:(?!(?:${u})).)*?`}else r+=`(?!(?:${u})$).*`;n=i;continue}}if(a==="*")r+=".*";else if(a==="?")r+=".";else if(a==="["){let i=n+1,l="[";i<t.length&&(t[i]==="^"||t[i]==="!")&&(l+="^",i++),i<t.length&&t[i]==="]"&&(l+="\\]",i++);let o=i;for(;o<t.length;){if(t[o]==="\\"&&o+1<t.length){o+=2;continue}if(t[o]==="["&&o+1<t.length&&t[o+1]===":"){let u=t.indexOf(":]",o+2);if(u!==-1){o=u+2;continue}}if(t[o]==="]")break;o++}let c=i;for(;i<t.length&&t[i]!=="]";){if(t[i]==="["&&i+1<t.length&&t[i+1]===":"){let u=t.indexOf(":]",i+2);if(u!==-1){let f=t.slice(i+2,u),h=ut(f);l+=h,i=u+2;continue}}if(t[i]==="\\"&&i+1<t.length){l+=`\\${t[i+1]}`,i+=2;continue}if(t[i]==="-"){let u=i===c,f=i+1===o;u||f?l+="\\-":l+="-"}else l+=t[i];i++}l+="]",r+=l,n=i}else if(a==="\\"&&n+1<t.length){let i=t[n+1];/[.+^${}()|\\*?[\]]/.test(i)?r+=`\\${i}`:r+=i,n++}else/[.+^${}()|]/.test(a)?r+=`\\${a}`:r+=a}return r}computePatternLength(t){let r=0,s=0,n=!1;for(;s<t.length;){if(t.slice(s,s+13)==="\0QUOTE_START\0"){n=!0,s+=13;continue}if(t.slice(s,s+11)==="\0QUOTE_END\0"){n=!1,s+=11;continue}let a=t[s];if(n){r+=1,s++;continue}if((a==="@"||a==="*"||a==="+"||a==="?"||a==="!")&&s+1<t.length&&t[s+1]==="("){let i=ct(t,s+1);if(i!==-1){if(a==="@"){let l=t.slice(s+2,i),c=ft(l).map(u=>this.computePatternLength(u));if(c.every(u=>u!==null)&&c.every(u=>u===c[0])){r+=c[0],s=i+1;continue}return null}return null}}if(a==="*")return null;if(a==="?"){r+=1,s++;continue}if(a==="["){let i=t.indexOf("]",s+1);if(i!==-1){r+=1,s=i+1;continue}r+=1,s++;continue}if(a==="\\"){r+=1,s+=2;continue}r+=1,s++}return r}};function es(e,t,r){switch(r){case"+":return e+t;case"-":return e-t;case"*":return e*t;case"/":if(t===0)throw new C("division by 0");return Math.trunc(e/t);case"%":if(t===0)throw new C("division by 0");return e%t;case"**":if(t<0)throw new C("exponent less than 0");return e**t;case"<<":return e<<t;case">>":return e>>t;case"<":return e<t?1:0;case"<=":return e<=t?1:0;case">":return e>t?1:0;case">=":return e>=t?1:0;case"==":return e===t?1:0;case"!=":return e!==t?1:0;case"&":return e&t;case"|":return e|t;case"^":return e^t;case",":return t;default:return 0}}function mn(e,t,r){switch(r){case"=":return t;case"+=":return e+t;case"-=":return e-t;case"*=":return e*t;case"/=":return t!==0?Math.trunc(e/t):0;case"%=":return t!==0?e%t:0;case"<<=":return e<<t;case">>=":return e>>t;case"&=":return e&t;case"|=":return e|t;case"^=":return e^t;default:return t}}function ts(e,t){switch(t){case"-":return-e;case"+":return+e;case"!":return e===0?1:0;case"~":return~e;default:return e}}async function ns(e,t){let r=e.state.env.get(t);if(r!==void 0)return r;let s=e.state.env.get(`${t}_0`);return s!==void 0?s:await v(e,t)}function rs(e){if(!e)return 0;let t=Number.parseInt(e,10);if(!Number.isNaN(t)&&/^-?\d+$/.test(e.trim()))return t;let r=e.trim();if(!r)return 0;try{let s=new V,{expr:n,pos:a}=Z(s,r,0);if(a<r.length){let i=r.slice(a).trim().split(/\s+/)[0];throw new C(`${r}: syntax error in expression (error token is "${i}")`)}return n.type==="ArithNumber"?n.value:t||0}catch(s){if(s instanceof C)throw s;let n=r.split(/\s+/).slice(1)[0]||r;throw new C(`${r}: syntax error in expression (error token is "${n}")`)}}async function ht(e,t){if(!t)return 0;let r=Number.parseInt(t,10);if(!Number.isNaN(r)&&/^-?\d+$/.test(t.trim()))return r;let s=t.trim();if(!s)return 0;let n=new V,{expr:a,pos:i}=Z(n,s,0);if(i<s.length){let l=s.slice(i).trim(),o=l.split(/\s+/)[0]||l;throw new C(`syntax error in expression (error token is "${o}")`,"","")}return await R(e,a)}async function pt(e,t,r=new Set,s=0){if(s>100)throw new C("maximum variable indirection depth exceeded");if(r.has(t))return 0;r.add(t);let n=await ns(e,t);if(!n)return 0;let a=Number.parseInt(n,10);if(!Number.isNaN(a)&&/^-?\d+$/.test(n.trim()))return a;let i=n.trim();if(/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(i))return await pt(e,i,r,s+1);let l=new V,{expr:o,pos:c}=Z(l,i,0);if(c<i.length){let u=i.slice(c).trim(),f=u.split(/\s+/)[0]||u;throw new C(`${i}: syntax error in expression (error token is "${f}")`)}return await R(e,o)}async function _e(e,t){if(t.startsWith("#")){let f=t.slice(1),h=f.match(/^([a-zA-Z_][a-zA-Z0-9_]*)\[[@*]\]$/);if(h){let m=h[1],g=P(e,m);return String(g.length)}let d=e.state.env.get(f)||"";return String(d.length)}if(t.startsWith("!")){let f=t.slice(1),h=e.state.env.get(f)||"";return e.state.env.get(h)||""}let r=[":-",":=",":?",":+","-","=","?","+"],s=-1,n="";for(let f of r){let h=t.indexOf(f);h>0&&(s===-1||h<s)&&(s=h,n=f)}if(s===-1)return await v(e,t);let a=t.slice(0,s),i=t.slice(s+n.length),l=e.state.env.get(a),o=l===void 0,c=l==="",u=n.startsWith(":");switch(n){case":-":case"-":return o||u&&c?i:l||"";case":=":case"=":return o||u&&c?(e.state.env.set(a,i),i):l||"";case":+":case"+":return!(o||u&&c)?i:"";case":?":case"?":{if(o||u&&c)throw new Error(i||`${a}: parameter null or not set`);return l||""}default:return l||""}}async function R(e,t,r=!1){switch(t.type){case"ArithNumber":if(Number.isNaN(t.value))throw new C("value too great for base");return t.value;case"ArithVariable":return await pt(e,t.name);case"ArithSpecialVar":{let n=(await v(e,t.name)).trim();if(!n)return 0;let a=Number.parseInt(n,10);if(!Number.isNaN(a)&&/^-?\d+$/.test(n))return a;let i=new V,{expr:l}=Z(i,n,0);return await R(e,l)}case"ArithNested":return await R(e,t.expression);case"ArithCommandSubst":{if(e.execFn){let s=await e.execFn(t.command,{signal:e.state.signal});s.stderr&&(e.state.expansionStderr=(e.state.expansionStderr||"")+s.stderr);let n=s.stdout.trim();return Number.parseInt(n,10)||0}return 0}case"ArithBracedExpansion":{let s=await _e(e,t.content);return Number.parseInt(s,10)||0}case"ArithDynamicBase":{let s=await _e(e,t.baseExpr),n=Number.parseInt(s,10);if(n<2||n>64)return 0;let a=`${n}#${t.value}`;return ge(a)}case"ArithDynamicNumber":{let n=await _e(e,t.prefix)+t.suffix;return ge(n)}case"ArithArrayElement":{let s=e.state.associativeArrays?.has(t.array),n=async a=>{let i=e.state.env.get(a);return i!==void 0?await ht(e,i):0};if(t.stringKey!==void 0)return await n(`${t.array}_${t.stringKey}`);if(s&&t.index?.type==="ArithVariable"&&!t.index.hasDollarPrefix)return await n(`${t.array}_${t.index.name}`);if(s&&t.index?.type==="ArithVariable"&&t.index.hasDollarPrefix){let a=await v(e,t.index.name);return await n(`${t.array}_${a}`)}if(t.index){let a=await R(e,t.index,r);if(a<0){let o=P(e,t.array),c=e.state.currentLine;if(o.length===0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${c}: ${t.array}: bad array subscript
49
49
  `,0;let f=Math.max(...o.map(([h])=>typeof h=="number"?h:0))+1+a;if(f<0)return e.state.expansionStderr=(e.state.expansionStderr||"")+`bash: line ${c}: ${t.array}: bad array subscript
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import{a as v}from"./chunk-4PRVMER6.js";import{a as c,b as f,c as m}from"./chunk-GTNBSMZR.js";var g={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"]},w={name:"env",async execute(o,i){if(f(o))return c(g);let a=!1,r=[],u=new Map,t=-1;for(let n=0;n<o.length;n++){let e=o[n];if(e==="-i"||e==="--ignore-environment")a=!0;else if(e==="-u"&&n+1<o.length)r.push(o[++n]);else if(e.startsWith("-u"))r.push(e.slice(2));else if(e.startsWith("--unset="))r.push(e.slice(8));else{if(e.startsWith("--")&&e!=="--")return m("env",e);if(e.startsWith("-")&&e!=="-"){for(let l of e.slice(1))if(l!=="i"&&l!=="u")return m("env",`-${l}`);e.includes("i")&&(a=!0)}else if(e.includes("=")&&t===-1){let l=e.indexOf("="),d=e.slice(0,l),h=e.slice(l+1);u.set(d,h)}else{t=n;break}}}let s;if(a)s=new Map(u);else{s=new Map(i.env);for(let n of r)s.delete(n);for(let[n,e]of u)s.set(n,e)}if(t===-1){let n=[];for(let[e,l]of s)n.push(`${e}=${l}`);return{stdout:n.join(`
3
+ `)+(n.length>0?`
4
+ `:""),stderr:"",exitCode:0}}if(!i.exec)return{stdout:"",stderr:`env: command execution not supported in this context
5
+ `,exitCode:1};let p=o.slice(t);return i.exec("command",{cwd:i.cwd,env:v(s),replaceEnv:!0,stdin:i.stdin,signal:i.signal,args:p})}},x={name:"printenv",summary:"print all or part of environment",usage:"printenv [OPTION]... [VARIABLE]...",options:[" --help display this help and exit"]},E={name:"printenv",async execute(o,i){if(f(o))return c(x);let a=o.filter(t=>!t.startsWith("-"));if(a.length===0){let t=[];for(let[s,p]of i.env)t.push(`${s}=${p}`);return{stdout:t.join(`
6
+ `)+(t.length>0?`
7
+ `:""),stderr:"",exitCode:0}}let r=[],u=0;for(let t of a){let s=i.env.get(t);s!==void 0?r.push(s):u=1}return{stdout:r.join(`
8
+ `)+(r.length>0?`
9
+ `:""),stderr:"",exitCode:u}}},M={name:"env",flags:[{flag:"-i",type:"boolean"},{flag:"-u",type:"value",valueHint:"string"}]},N={name:"printenv",flags:[]};export{w as a,E as b,M as c,N as d};
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- import{a as F,b,c as M,d as qe,e as w,f as v,g as X,h as Y}from"./chunk-GZHFXDDO.js";import{a as et}from"./chunk-QSDVMMYI.js";import{a as $}from"./chunk-ZYQQ6B7B.js";import{f as G}from"./chunk-ZJGIBTWD.js";import{a as H}from"./chunk-SE4C7FJY.js";import{a as We}from"./chunk-5WFYIUU2.js";import{a as D,b as K}from"./chunk-GTNBSMZR.js";import{b as Ue,d as Be,e as Ze,f as Qe}from"./chunk-KGOUQS5A.js";var q,_e=Ue(()=>{"use strict";q=class{input;pos=0;tokens=[];constructor(n){this.input=n}tokenize(){for(;this.pos<this.input.length&&(this.skipWhitespace(),!(this.pos>=this.input.length));){let n=this.nextToken();n&&this.tokens.push(n)}return this.tokens.push({type:"eof",value:"",pos:this.pos}),this.tokens}skipWhitespace(){for(;this.pos<this.input.length;){let n=this.input[this.pos];if(n===" "||n===" "||n===`
2
+ import{a as O,b,c as M,d as _e,e as w,f as v,g as Y,h as B}from"./chunk-GZHFXDDO.js";import{a as tt}from"./chunk-QSDVMMYI.js";import{a as $}from"./chunk-ZO5PSLKR.js";import{f as qe,g as X}from"./chunk-V7ZOPVQS.js";import{a as H}from"./chunk-SE4C7FJY.js";import{a as We}from"./chunk-5WFYIUU2.js";import{a as D,b as G}from"./chunk-GTNBSMZR.js";import{b as Ue,d as Ze,e as Qe,f as et}from"./chunk-KGOUQS5A.js";var q,He=Ue(()=>{"use strict";q=class{input;pos=0;tokens=[];constructor(n){this.input=n}tokenize(){for(;this.pos<this.input.length&&(this.skipWhitespace(),!(this.pos>=this.input.length));){let n=this.nextToken();n&&this.tokens.push(n)}return this.tokens.push({type:"eof",value:"",pos:this.pos}),this.tokens}skipWhitespace(){for(;this.pos<this.input.length;){let n=this.input[this.pos];if(n===" "||n===" "||n===`
3
3
  `||n==="\r")this.pos++;else if(n==="#")for(;this.pos<this.input.length&&this.input[this.pos]!==`
4
4
  `;)this.pos++;else break}}nextToken(){let n=this.pos,t=this.input[this.pos];if(t>="0"&&t<="9")return this.readNumber();if(t==='"'||t==="'"||t==="`")return this.readString(t);if(t==="b"&&this.pos+1<this.input.length){let o=this.input[this.pos+1];if(o==='"'||o==="'"||o==="`")return this.pos++,this.readString(o)}if(t==="/"){let o=this.tokens[this.tokens.length-1];return o&&(o.type==="int"||o.type==="float"||o.type==="string"||o.type==="ident"||o.type===")"||o.type==="]")?this.input[this.pos+1]==="/"?(this.pos+=2,{type:"//",value:"//",pos:n}):(this.pos++,{type:"/",value:"/",pos:n}):this.readRegex()}if(this.match("not in"))return{type:"not in",value:"not in",pos:n};if(this.match("=>"))return{type:"=>",value:"=>",pos:n};if(this.match("**"))return{type:"**",value:"**",pos:n};if(this.match("++"))return{type:"++",value:"++",pos:n};if(this.match("//"))return{type:"//",value:"//",pos:n};if(this.match("=="))return{type:"==",value:"==",pos:n};if(this.match("!="))return{type:"!=",value:"!=",pos:n};if(this.match("<="))return{type:"<=",value:"<=",pos:n};if(this.match(">="))return{type:">=",value:">=",pos:n};if(this.match("&&"))return{type:"&&",value:"&&",pos:n};if(this.match("||"))return{type:"||",value:"||",pos:n};let r=new Map([["(","("],[")",")"],["[","["],["]","]"],["{","{"],["}","}"],[",",","],[":",":"],[";",";"],["+","+"],["-","-"],["*","*"],["%","%"],["<","<"],[">",">"],["!","!"],[".","."],["|","|"],["=","="]]).get(t);if(r!==void 0)return this.pos++,{type:r,value:t,pos:n};if(this.isIdentStart(t))return this.readIdentifier();throw new Error(`Unexpected character '${t}' at position ${this.pos}`)}match(n){if(this.input.slice(this.pos,this.pos+n.length)===n){if(/^[a-zA-Z]/.test(n)){let t=this.input[this.pos+n.length];if(t&&this.isIdentChar(t))return!1}return this.pos+=n.length,!0}return!1}isIdentStart(n){return n>="a"&&n<="z"||n>="A"&&n<="Z"||n==="_"}isIdentChar(n){return this.isIdentStart(n)||n>="0"&&n<="9"}readNumber(){let n=this.pos,t=!1,s=!1;for(;this.pos<this.input.length;){let o=this.input[this.pos];if(o>="0"&&o<="9")this.pos++;else if(o==="_")this.pos++;else if(o==="."&&!t&&!s)t=!0,this.pos++;else if((o==="e"||o==="E")&&!s)s=!0,t=!0,this.pos++,this.pos<this.input.length&&(this.input[this.pos]==="+"||this.input[this.pos]==="-")&&this.pos++;else break}let r=this.input.slice(n,this.pos).replace(/_/g,"");return{type:t?"float":"int",value:r,pos:n}}readString(n){let t=this.pos;this.pos++;let s="";for(;this.pos<this.input.length;){let r=this.input[this.pos];if(r===n)return this.pos++,{type:"string",value:s,pos:t};if(r==="\\"){if(this.pos++,this.pos<this.input.length){let o=this.input[this.pos];switch(o){case"n":s+=`
5
- `;break;case"r":s+="\r";break;case"t":s+=" ";break;case"\\":s+="\\";break;case'"':s+='"';break;case"'":s+="'";break;case"`":s+="`";break;case"0":s+="\0";break;default:s+=o}this.pos++}}else s+=r,this.pos++}throw new Error(`Unterminated string starting at position ${t}`)}readRegex(){let n=this.pos;this.pos++;let t="",s="";for(;this.pos<this.input.length;){let r=this.input[this.pos];if(r==="/"){for(this.pos++;this.pos<this.input.length&&this.input[this.pos]==="i";)s+=this.input[this.pos],this.pos++;return{type:"regex",value:t+(s?`/${s}`:""),pos:n}}r==="\\"?(t+=r,this.pos++,this.pos<this.input.length&&(t+=this.input[this.pos],this.pos++)):(t+=r,this.pos++)}throw new Error(`Unterminated regex starting at position ${n}`)}readIdentifier(){let n=this.pos;for(;this.pos<this.input.length&&this.isIdentChar(this.input[this.pos]);)this.pos++;let t=!1;this.pos<this.input.length&&this.input[this.pos]==="?"&&(t=!0,this.pos++);let s=this.input.slice(n,t?this.pos-1:this.pos);t&&(s+="?");let r=new Map([["true","true"],["false","false"],["null","null"],["and","and"],["or","or"],["eq","eq"],["ne","ne"],["lt","lt"],["le","le"],["gt","gt"],["ge","ge"],["in","in"],["as","as"],["_","_"]]),o=s.replace(/\?$/,""),i=r.get(o);return i!==void 0&&!t?{type:i,value:o,pos:n}:{type:"ident",value:s,pos:n}}}});var He={};Be(He,{parseMoonblade:()=>_,parseNamedExpressions:()=>V});function V(e){let n=[],s=new q(e).tokenize(),r=0,o=()=>s[r]||{type:"eof",value:"",pos:0},i=()=>s[r++];for(;o().type!=="eof";){if(o().type===","&&n.length>0){i();continue}let h=[],u=0,p=r;for(;o().type!=="eof";){let a=o();if((a.type===","||a.type==="as")&&u===0)break;(a.type==="("||a.type==="["||a.type==="{")&&u++,(a.type===")"||a.type==="]"||a.type==="}")&&u--,h.push(i())}h.push({type:"eof",value:"",pos:0});let f=new J(h).parse(),c;if(o().type==="as")if(i(),o().type==="("){i();let a=[];for(;o().type!==")"&&o().type!=="eof";)(o().type==="ident"||o().type==="string")&&(a.push(o().value),i()),o().type===","&&i();o().type===")"&&i(),c=a}else if(o().type==="ident"||o().type==="string")c=o().value,i();else throw new Error(`Expected name after 'as', got ${o().type}`);else c=e.slice(s[p].pos,s[r-1]?.pos||e.length).trim(),f.type==="identifier"&&(c=f.name);n.push({expr:f,name:c})}return n}function _(e){let t=new q(e).tokenize();return new J(t).parse()}var R,J,U=Ue(()=>{"use strict";_e();R={PIPE:1,OR:2,AND:3,EQUALITY:4,COMPARISON:5,ADDITIVE:6,MULTIPLICATIVE:7,POWER:8,UNARY:9,POSTFIX:10},J=class{pos=0;tokens;constructor(n){this.tokens=n}parse(){let n=this.parseExpr(0);if(this.peek().type!=="eof")throw new Error(`Unexpected token: ${this.peek().value}`);return n}parseExpr(n){let t=this.parsePrefix();for(;;){let s=this.peek(),r=this.getInfixPrec(s.type);if(r<n)break;t=this.parseInfix(t,r)}return t}parsePrefix(){let n=this.peek();switch(n.type){case"int":return this.advance(),{type:"int",value:Number.parseInt(n.value,10)};case"float":return this.advance(),{type:"float",value:Number.parseFloat(n.value)};case"string":return this.advance(),{type:"string",value:n.value};case"regex":{this.advance();let t=n.value.split("/"),s=t.length>1?t[t.length-1]:"";return{type:"regex",pattern:t.slice(0,-1).join("/")||n.value,caseInsensitive:s.includes("i")}}case"true":return this.advance(),{type:"bool",value:!0};case"false":return this.advance(),{type:"bool",value:!1};case"null":return this.advance(),{type:"null"};case"_":return this.advance(),{type:"underscore"};case"ident":{let t=n.value,s=t.endsWith("?"),r=s?t.slice(0,-1):t;if(this.advance(),this.peek().type==="(")return this.parseFunctionCall(r);if(this.peek().type==="=>"){this.advance();let o=this.parseExpr(0);return this.bindLambdaArgs({type:"lambda",params:[r],body:o},[r])}return{type:"identifier",name:r,unsure:s}}case"(":{this.advance();let t=[];if(this.peek().type===")"){if(this.advance(),this.peek().type==="=>"){this.advance();let r=this.parseExpr(0);return{type:"lambda",params:[],body:r}}throw new Error("Empty parentheses not allowed")}if(this.peek().type==="ident"){let r=this.peek().value;if(this.advance(),this.peek().type===","||this.peek().type===")"){for(t.push(r);this.peek().type===","&&(this.advance(),this.peek().type==="ident");)t.push(this.peek().value),this.advance();if(this.peek().type===")"&&(this.advance(),this.peek().type==="=>")){this.advance();let o=this.parseExpr(0);return this.bindLambdaArgs({type:"lambda",params:t,body:o},t)}this.pos-=t.length*2,t.length>1&&(this.pos=this.pos)}this.pos--}let s=this.parseExpr(0);return this.expect(")"),this.peek().type,s}case"[":return this.parseList();case"{":return this.parseMap();case"-":{this.advance();let t=this.parseExpr(R.UNARY);return t.type==="int"?{type:"int",value:-t.value}:t.type==="float"?{type:"float",value:-t.value}:{type:"func",name:"neg",args:[{expr:t}]}}case"!":return this.advance(),{type:"func",name:"not",args:[{expr:this.parseExpr(R.UNARY)}]};default:throw new Error(`Unexpected token: ${n.type} (${n.value})`)}}parseFunctionCall(n){this.expect("(");let t=[];if(this.peek().type!==")")do{t.length>0&&this.peek().type===","&&this.advance();let s;if(this.peek().type==="ident"){let o=this.peek().value,i=this.pos+1;i<this.tokens.length&&this.tokens[i].type==="="&&(s=o,this.advance(),this.advance())}let r=this.parseExpr(0);t.push({name:s,expr:r})}while(this.peek().type===",");return this.expect(")"),{type:"func",name:n.toLowerCase(),args:t}}parseList(){this.expect("[");let n=[];if(this.peek().type!=="]")do n.length>0&&this.peek().type===","&&this.advance(),n.push(this.parseExpr(0));while(this.peek().type===",");return this.expect("]"),{type:"list",elements:n}}parseMap(){this.expect("{");let n=[];if(this.peek().type!=="}")do{n.length>0&&this.peek().type===","&&this.advance();let t;if(this.peek().type==="ident")t=this.peek().value,this.advance();else if(this.peek().type==="string")t=this.peek().value,this.advance();else throw new Error(`Expected map key, got ${this.peek().type}`);this.expect(":");let s=this.parseExpr(0);n.push({key:t,value:s})}while(this.peek().type===",");return this.expect("}"),{type:"map",entries:n}}parseInfix(n,t){let s=this.peek(),o=new Map([["+","add"],["-","sub"],["*","mul"],["/","div"],["//","idiv"],["%","mod"],["**","pow"],["++","concat"],["==","=="],["!=","!="],["<","<"],["<=","<="],[">",">"],[">=",">="],["eq","eq"],["ne","ne"],["lt","lt"],["le","le"],["gt","gt"],["ge","ge"],["&&","and"],["and","and"],["||","or"],["or","or"]]).get(s.type);if(o!==void 0){this.advance();let i=this.parseExpr(t+(this.isRightAssoc(s.type)?0:1));return{type:"func",name:o,args:[{expr:n},{expr:i}]}}if(s.type==="|"){this.advance();let i=this.parseExpr(t);return this.handlePipe(n,i)}if(s.type===".")return this.advance(),this.handleDot(n);if(s.type==="[")return this.advance(),this.handleIndexing(n);if(s.type==="in")return this.advance(),{type:"func",name:"contains",args:[{expr:this.parseExpr(t+1)},{expr:n}]};if(s.type==="not in")return this.advance(),{type:"func",name:"not",args:[{expr:{type:"func",name:"contains",args:[{expr:this.parseExpr(t+1)},{expr:n}]}}]};throw new Error(`Unexpected infix token: ${s.type}`)}handlePipe(n,t){if(t.type==="identifier")return{type:"func",name:t.name,args:[{expr:n}]};if(t.type==="func"){let s=this.countUnderscores(t);return s===0?t:s===1?this.fillUnderscore(t,n):{type:"pipeline",exprs:[n,t]}}return this.countUnderscores(t)===1?this.fillUnderscore(t,n):t}handleDot(n){let t=this.peek();if(t.type==="ident"){let s=t.value;if(this.advance(),this.peek().type==="("){let r=this.parseFunctionCall(s);return r.type==="func"&&r.args.unshift({expr:n}),r}return{type:"func",name:"get",args:[{expr:n},{expr:{type:"string",value:s}}]}}if(t.type==="int"){let s=Number.parseInt(t.value,10);return this.advance(),{type:"func",name:"get",args:[{expr:n},{expr:{type:"int",value:s}}]}}if(t.type==="string"){let s=t.value;return this.advance(),{type:"func",name:"get",args:[{expr:n},{expr:{type:"string",value:s}}]}}throw new Error(`Expected identifier, number, or string after dot, got ${t.type}`)}handleIndexing(n){if(this.peek().type===":"){if(this.advance(),this.peek().type==="]")return this.advance(),{type:"func",name:"slice",args:[{expr:n}]};let s=this.parseExpr(0);return this.expect("]"),{type:"func",name:"slice",args:[{expr:n},{expr:{type:"int",value:0}},{expr:s}]}}let t=this.parseExpr(0);if(this.peek().type===":"){if(this.advance(),this.peek().type==="]")return this.advance(),{type:"func",name:"slice",args:[{expr:n},{expr:t}]};let s=this.parseExpr(0);return this.expect("]"),{type:"func",name:"slice",args:[{expr:n},{expr:t},{expr:s}]}}return this.expect("]"),{type:"func",name:"get",args:[{expr:n},{expr:t}]}}countUnderscores(n){return n.type==="underscore"?1:n.type==="func"?n.args.reduce((t,s)=>t+this.countUnderscores(s.expr),0):n.type==="list"?n.elements.reduce((t,s)=>t+this.countUnderscores(s),0):n.type==="map"?n.entries.reduce((t,s)=>t+this.countUnderscores(s.value),0):0}fillUnderscore(n,t){return n.type==="underscore"?t:n.type==="func"?{...n,args:n.args.map(s=>({...s,expr:this.fillUnderscore(s.expr,t)}))}:n.type==="list"?{...n,elements:n.elements.map(s=>this.fillUnderscore(s,t))}:n.type==="map"?{...n,entries:n.entries.map(s=>({...s,value:this.fillUnderscore(s.value,t)}))}:n}bindLambdaArgs(n,t){return{...n,body:this.bindLambdaArgsInExpr(n.body,t)}}bindLambdaArgsInExpr(n,t){return n.type==="identifier"&&t.includes(n.name)?{type:"lambdaBinding",name:n.name}:n.type==="func"?{...n,args:n.args.map(s=>({...s,expr:this.bindLambdaArgsInExpr(s.expr,t)}))}:n.type==="list"?{...n,elements:n.elements.map(s=>this.bindLambdaArgsInExpr(s,t))}:n.type==="map"?{...n,entries:n.entries.map(s=>({...s,value:this.bindLambdaArgsInExpr(s.value,t)}))}:n}getInfixPrec(n){switch(n){case"|":return R.PIPE;case"||":case"or":return R.OR;case"&&":case"and":return R.AND;case"==":case"!=":case"eq":case"ne":return R.EQUALITY;case"<":case"<=":case">":case">=":case"lt":case"le":case"gt":case"ge":case"in":case"not in":return R.COMPARISON;case"+":case"-":case"++":return R.ADDITIVE;case"*":case"/":case"//":case"%":return R.MULTIPLICATIVE;case"**":return R.POWER;case".":case"[":return R.POSTFIX;default:return-1}}isRightAssoc(n){return n==="**"}peek(){return this.tokens[this.pos]||{type:"eof",value:"",pos:0}}advance(){return this.tokens[this.pos++]}expect(n){let t=this.peek();if(t.type!==n)throw new Error(`Expected ${n}, got ${t.type}`);return this.advance()}}});U();function E(e,n){return n.length===0?k(e,[]):n.length===1?{type:"Pipe",left:n[0],right:k(e,[])}:{type:"Pipe",left:n[0],right:k(e,n.slice(1))}}var B={add:e=>S("+",e[0],e[1]),sub:e=>S("-",e[0],e[1]),mul:e=>S("*",e[0],e[1]),div:e=>S("/",e[0],e[1]),mod:e=>S("%",e[0],e[1]),idiv:e=>k("floor",[S("/",e[0],e[1])]),pow:e=>E("pow",e),neg:e=>({type:"UnaryOp",op:"-",operand:e[0]}),"==":e=>S("==",e[0],e[1]),"!=":e=>S("!=",e[0],e[1]),"<":e=>S("<",e[0],e[1]),"<=":e=>S("<=",e[0],e[1]),">":e=>S(">",e[0],e[1]),">=":e=>S(">=",e[0],e[1]),eq:e=>S("==",P(e[0]),P(e[1])),ne:e=>S("!=",P(e[0]),P(e[1])),lt:e=>S("<",P(e[0]),P(e[1])),le:e=>S("<=",P(e[0]),P(e[1])),gt:e=>S(">",P(e[0]),P(e[1])),ge:e=>S(">=",P(e[0]),P(e[1])),and:e=>S("and",e[0],e[1]),or:e=>S("or",e[0],e[1]),not:e=>({type:"UnaryOp",op:"not",operand:e[0]}),len:e=>E("length",e),length:e=>E("length",e),upper:e=>E("ascii_upcase",e),lower:e=>E("ascii_downcase",e),trim:e=>E("trim",e),ltrim:e=>e.length===0?k("ltrimstr",[{type:"Literal",value:" "}]):{type:"Pipe",left:e[0],right:k("ltrimstr",[{type:"Literal",value:" "}])},rtrim:e=>e.length===0?k("rtrimstr",[{type:"Literal",value:" "}]):{type:"Pipe",left:e[0],right:k("rtrimstr",[{type:"Literal",value:" "}])},split:e=>E("split",e),join:e=>e.length===1?k("join",[{type:"Literal",value:""}]):E("join",e),concat:e=>S("+",e[0],e[1]),startswith:e=>E("startswith",e),endswith:e=>E("endswith",e),contains:e=>E("contains",e),replace:e=>E("gsub",e),substr:e=>e.length===2?{type:"Slice",base:e[0],start:e[1]}:{type:"Slice",base:e[0],start:e[1],end:S("+",e[1],e[2])},abs:e=>E("fabs",e),floor:e=>E("floor",e),ceil:e=>E("ceil",e),round:e=>E("round",e),sqrt:e=>E("sqrt",e),log:e=>E("log",e),log10:e=>E("log10",e),log2:e=>E("log2",e),exp:e=>E("exp",e),sin:e=>E("sin",e),cos:e=>E("cos",e),tan:e=>E("tan",e),asin:e=>E("asin",e),acos:e=>E("acos",e),atan:e=>E("atan",e),min:e=>E("min",e),max:e=>E("max",e),first:e=>e.length===0?{type:"Index",index:{type:"Literal",value:0}}:{type:"Index",index:{type:"Literal",value:0},base:e[0]},last:e=>e.length===0?{type:"Index",index:{type:"Literal",value:-1}}:{type:"Index",index:{type:"Literal",value:-1},base:e[0]},get:e=>e.length===1?{type:"Index",index:e[0]}:{type:"Index",index:e[1],base:e[0]},slice:e=>e.length===1?{type:"Slice",base:e[0]}:e.length===2?{type:"Slice",base:e[0],start:e[1]}:{type:"Slice",base:e[0],start:e[1],end:e[2]},keys:"keys",values:"values",entries:e=>k("to_entries",e),from_entries:"from_entries",reverse:"reverse",sort:"sort",sort_by:"sort_by",group_by:"group_by",unique:"unique",unique_by:"unique_by",flatten:"flatten",map:e=>({type:"Pipe",left:e[0],right:{type:"Array",elements:e[1]}}),select:e=>k("select",e),empty:()=>k("empty",[]),count:()=>k("length",[]),sum:e=>e.length===0?k("add",[]):{type:"Pipe",left:{type:"Array",elements:e[0]},right:k("add",[])},mean:e=>e.length===0?{type:"Pipe",left:{type:"Identity"},right:S("/",k("add",[]),k("length",[]))}:{type:"Pipe",left:{type:"Array",elements:e[0]},right:S("/",k("add",[]),k("length",[]))},avg:e=>e.length===0?{type:"Pipe",left:{type:"Identity"},right:S("/",k("add",[]),k("length",[]))}:{type:"Pipe",left:{type:"Array",elements:e[0]},right:S("/",k("add",[]),k("length",[]))},type:"type",isnull:e=>e.length===0?S("==",{type:"Identity"},{type:"Literal",value:null}):S("==",e[0],{type:"Literal",value:null}),isempty:e=>e.length===0?S("==",{type:"Identity"},{type:"Literal",value:""}):S("==",e[0],{type:"Literal",value:""}),tonumber:e=>e.length===0?k("tonumber",[]):k("tonumber",e),tostring:e=>e.length===0?k("tostring",[]):k("tostring",e),if:e=>Je(e[0],e[1],e[2]),coalesce:e=>{if(e.length===0)return{type:"Literal",value:null};if(e.length===1)return e[0];let[n,...t]=e,s=S("and",S("!=",n,{type:"Literal",value:null}),S("!=",n,{type:"Literal",value:""}));return Je(s,n,t.length===1?t[0]:B.coalesce(t))},index:()=>({type:"Field",name:"_row_index"}),now:()=>k("now",[]),fmt:e=>k("tostring",e),format:e=>k("tostring",e)};function S(e,n,t){return{type:"BinaryOp",op:e,left:n,right:t}}function k(e,n){return{type:"Call",name:e,args:n}}var tt="then";function Je(e,n,t){let s={type:"Cond",cond:e,elifs:[],else:t||{type:"Literal",value:null}};return s[tt]=n,s}function P(e){return{type:"Pipe",left:e,right:{type:"Call",name:"tostring",args:[]}}}function O(e,n=!0){switch(e.type){case"int":case"float":return{type:"Literal",value:e.value};case"string":return{type:"Literal",value:e.value};case"bool":return{type:"Literal",value:e.value};case"null":return{type:"Literal",value:null};case"underscore":return{type:"Index",base:{type:"Identity"},index:{type:"Literal",value:"_"}};case"identifier":return n?{type:"Field",name:e.name}:{type:"VarRef",name:e.name};case"lambdaBinding":return{type:"VarRef",name:e.name};case"func":{let t=e.args.map(r=>O(r.expr,n)),s=Object.hasOwn(B,e.name)?B[e.name]:void 0;return typeof s=="function"?s(t):k(typeof s=="string"?s:e.name,t)}case"list":return e.elements.length===0?{type:"Array"}:{type:"Array",elements:e.elements.reduce((t,s,r)=>{let o=O(s,n);return r===0?o:{type:"Comma",left:t,right:o}},null)};case"map":return{type:"Object",entries:e.entries.map(t=>({key:t.key,value:O(t.value,n)}))};case"regex":return{type:"Literal",value:e.pattern};case"slice":return{type:"Slice",start:e.start?O(e.start,n):void 0,end:e.end?O(e.end,n):void 0};case"lambda":return O(e.body,n);case"pipeline":return{type:"Identity"};default:throw new Error(`Unknown moonblade expression type: ${e.type}`)}}function Q(e){let n=[],t=0;for(;t<e.length;){for(;t<e.length&&(e[t]===" "||e[t]===",");)t++;if(t>=e.length)break;let s=t;for(;t<e.length&&/\w/.test(e[t]);)t++;let r=e.slice(s,t);for(;t<e.length&&e[t]===" ";)t++;if(e[t]!=="(")break;t++;let o=1,i=t;for(;t<e.length&&o>0;)e[t]==="("?o++:e[t]===")"&&o--,o>0&&t++;let h=e.slice(i,t).trim();for(t++;t<e.length&&e[t]===" ";)t++;let u="";if(e.slice(t,t+3).toLowerCase()==="as "){for(t+=3;t<e.length&&e[t]===" ";)t++;let p=t;for(;t<e.length&&/\w/.test(e[t]);)t++;u=e.slice(p,t)}u||(u=h?`${r}(${h})`:`${r}()`),n.push({func:r,expr:h,alias:u})}return n}function ze(e){return/^\w+$/.test(e)}function Z(e,n,t){let s=O(_(n)),r=$(e,s,t);return r.length>0?r[0]:null}function ee(e,n,t={}){let{func:s,expr:r}=n;if(s==="count"&&!r)return e.length;let o;switch(ze(r)?o=e.map(i=>i[r]).filter(i=>i!=null):o=e.map(i=>Z(i,r,t)).filter(i=>i!=null),s){case"count":return ze(r)?o.length:o.filter(i=>!!i).length;case"sum":return o.map(h=>typeof h=="number"?h:Number.parseFloat(String(h))).reduce((h,u)=>h+u,0);case"mean":case"avg":{let i=o.map(h=>typeof h=="number"?h:Number.parseFloat(String(h)));return i.length>0?i.reduce((h,u)=>h+u,0)/i.length:0}case"min":{let i=o.map(h=>typeof h=="number"?h:Number.parseFloat(String(h)));return i.length>0?Math.min(...i):null}case"max":{let i=o.map(h=>typeof h=="number"?h:Number.parseFloat(String(h)));return i.length>0?Math.max(...i):null}case"first":return o.length>0?o[0]:null;case"last":return o.length>0?o[o.length-1]:null;case"median":{let i=o.map(u=>typeof u=="number"?u:Number.parseFloat(String(u))).filter(u=>!Number.isNaN(u)).sort((u,p)=>u-p);if(i.length===0)return null;let h=Math.floor(i.length/2);return i.length%2===0?(i[h-1]+i[h])/2:i[h]}case"mode":{let i=new Map;for(let p of o){let l=String(p);i.set(l,(i.get(l)||0)+1)}let h=0,u=null;for(let[p,l]of i)l>h&&(h=l,u=p);return u}case"cardinality":return new Set(o.map(h=>String(h))).size;case"values":return o.map(i=>String(i)).join("|");case"distinct_values":return[...new Set(o.map(h=>String(h)))].sort().join("|");case"all":{if(e.length===0)return!0;for(let i of e)if(!Z(i,r,t))return!1;return!0}case"any":{for(let i of e)if(Z(i,r,t))return!0;return!1}default:return null}}function Ke(e,n,t={}){let s=F();for(let r of n)b(s,r.alias,ee(e,r,t));return s}async function te(e,n){let t="",s=[];for(let l of e)l.startsWith("-")||(t?s.push(l):t=l);if(!t)return{stdout:"",stderr:`xan agg: no aggregation expression
6
- `,exitCode:1};let{data:r,error:o}=await v(s,n);if(o)return o;let i={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},h=Q(t),u=h.map(l=>l.alias),p=Ke(r,h,i);return{stdout:w(u,[p]),stderr:"",exitCode:0}}async function ne(e,n){let t="",s="",r=[];for(let d=0;d<e.length;d++){let m=e[d];m==="--sorted"||m.startsWith("-")||(t?s?r.push(m):s=m:t=m)}if(!t||!s)return{stdout:"",stderr:`xan groupby: usage: xan groupby COLS EXPR [FILE]
7
- `,exitCode:1};let{data:o,error:i}=await v(r,n);if(i)return i;let h={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},u=t.split(","),p=Q(s),l=[],f=new Map;for(let d of o){let m=u.map(g=>String(d[g])).join("\0");f.has(m)||(f.set(m,[]),l.push(m)),f.get(m)?.push(d)}let c=[...u,...p.map(d=>d.alias)],a=[];for(let d of l){let m=f.get(d);if(!m)continue;let g=F();for(let y of u)b(g,y,m[0][y]);for(let y of p)b(g,y.alias,ee(m,y,h));a.push(g)}return{stdout:w(c,a),stderr:"",exitCode:0}}async function se(e,n){let t=[],s="",r=10,o=!1,i=[];for(let a=0;a<e.length;a++){let d=e[a];(d==="-s"||d==="--select")&&a+1<e.length?t=e[++a].split(","):(d==="-g"||d==="--groupby")&&a+1<e.length?s=e[++a]:(d==="-l"||d==="--limit")&&a+1<e.length?r=Number.parseInt(e[++a],10):d==="--no-extra"?o=!0:d==="-A"||d==="--all"?r=0:d.startsWith("-")||i.push(d)}let{headers:h,data:u,error:p}=await v(i,n);if(p)return p;let l=t.length>0?t:h.filter(a=>a!==s);s&&t.length===0&&(l=h.filter(a=>a!==s));let f=[],c=s?["field",s,"value","count"]:["field","value","count"];if(s){let a=new Map;for(let d of u){let m=String(d[s]??"");a.has(m)||a.set(m,[]),a.get(m)?.push(d)}for(let d of l)for(let[m,g]of a){let y=new Map;for(let I of g){let N=I[d],C=N===""||N===null||N===void 0?"":String(N);y.set(C,(y.get(C)||0)+1)}let x=[...y.entries()].sort((I,N)=>N[1]!==I[1]?N[1]-I[1]:I[0].localeCompare(N[0]));o&&(x=x.filter(([I])=>I!=="")),r>0&&(x=x.slice(0,r));for(let[I,N]of x)f.push({field:d,[s]:m,value:I===""?"<empty>":I,count:N})}}else for(let a of l){let d=new Map;for(let g of u){let y=g[a],x=y===""||y===null||y===void 0?"":String(y);d.set(x,(d.get(x)||0)+1)}let m=[...d.entries()].sort((g,y)=>y[1]!==g[1]?y[1]-g[1]:g[0].localeCompare(y[0]));o&&(m=m.filter(([g])=>g!=="")),r>0&&(m=m.slice(0,r));for(let[g,y]of m)f.push({field:a,value:g===""?"<empty>":g,count:y})}return{stdout:w(c,f),stderr:"",exitCode:0}}async function re(e,n){let t=[],s=[];for(let l=0;l<e.length;l++){let f=e[l];f==="-s"&&l+1<e.length?t=e[++l].split(","):f.startsWith("-")||s.push(f)}let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=t.length>0?t:r,u=["field","type","count","min","max","mean"],p=[];for(let l of h){let f=o.map(d=>d[l]).filter(d=>d!=null),c=f.map(d=>typeof d=="number"?d:Number.parseFloat(String(d))).filter(d=>!Number.isNaN(d)),a=c.length===f.length&&c.length>0;p.push({field:l,type:a?"Number":"String",count:f.length,min:a?Math.min(...c):"",max:a?Math.max(...c):"",mean:a?Math.round(c.reduce((d,m)=>d+m,0)/c.length*1e10)/1e10:""})}return{stdout:w(u,p),stderr:"",exitCode:0}}U();function Ge(e){let n=_(e);return O(n)}function nt(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return H(`^${t}$`)}function z(e,n){let t=[],s=new Set;for(let r of e.split(",")){let o=r.trim();if(o.startsWith("!")){let p=o.slice(1),l=z(p,n);for(let f of l)s.add(f);continue}if(o==="*"){for(let p of n)t.includes(p)||t.push(p);continue}if(o.includes("*")){let p=nt(o);for(let l of n)p.test(l)&&!t.includes(l)&&t.push(l);continue}let i=o.match(/^([^:]*):([^:]*)$/);if(i&&(i[1]||i[2])){let p=i[1],l=i[2],f=p?n.indexOf(p):0,c=l?n.indexOf(l):n.length-1;if(f!==-1&&c!==-1){let a=f<=c?1:-1;for(let d=f;a>0?d<=c:d>=c;d+=a)t.includes(n[d])||t.push(n[d])}continue}let h=o.match(/^(\d+)-(\d+)$/);if(h){let p=Number.parseInt(h[1],10),l=Number.parseInt(h[2],10);for(let f=p;f<=l&&f<n.length;f++)t.push(n[f]);continue}let u=Number.parseInt(o,10);if(!Number.isNaN(u)&&u>=0&&u<n.length){t.push(n[u]);continue}n.includes(o)&&t.push(o)}return s.size>0?t.filter(r=>!s.has(r)):t}async function oe(e,n){let t="",s=[];for(let p of e)p.startsWith("-")||(t?s.push(p):t=p);if(!t)return{stdout:"",stderr:`xan select: no columns specified
8
- `,exitCode:1};let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=z(t,r),u=o.map(p=>{let l=F();for(let f of h)b(l,f,p[f]);return l});return{stdout:w(h,u),stderr:"",exitCode:0}}async function ie(e,n){let t="",s=[];for(let l of e)l.startsWith("-")||(t?s.push(l):t=l);if(!t)return{stdout:"",stderr:`xan drop: no columns specified
9
- `,exitCode:1};let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=new Set(z(t,r)),u=r.filter(l=>!h.has(l)),p=o.map(l=>{let f=F();for(let c of u)b(f,c,l[c]);return f});return{stdout:w(u,p),stderr:"",exitCode:0}}async function ae(e,n){let t="",s="",r=[];for(let l=0;l<e.length;l++){let f=e[l];f==="-s"&&l+1<e.length?s=e[++l]:f.startsWith("-")||(t?r.push(f):t=f)}if(!t)return{stdout:"",stderr:`xan rename: no new name(s) specified
10
- `,exitCode:1};let{headers:o,data:i,error:h}=await v(r,n);if(h)return h;let u;if(s){let l=s.split(","),f=t.split(","),c=new Map;for(let a=0;a<l.length&&a<f.length;a++)c.set(l[a],f[a]);u=o.map(a=>c.get(a)||a)}else{let l=t.split(",");u=o.map((f,c)=>c<l.length?l[c]:f)}let p=i.map(l=>{let f=F();for(let c=0;c<o.length;c++)b(f,u[c],l[o[c]]);return f});return{stdout:w(u,p),stderr:"",exitCode:0}}async function le(e,n){let t="index",s=[];for(let p=0;p<e.length;p++)e[p]==="-c"&&p+1<e.length?t=e[++p]:s.push(e[p]);let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=[t,...r],u=o.map((p,l)=>{let f=F();b(f,t,l);for(let c of r)b(f,c,p[c]);return f});return{stdout:w(h,u),stderr:"",exitCode:0}}async function ue(e,n){let t=e.includes("-j")||e.includes("--just-names"),{headers:s,error:r}=await v(e.filter(i=>i!=="-j"&&i!=="--just-names"),n);return r||{stdout:t?`${s.map(i=>i).join(`
5
+ `;break;case"r":s+="\r";break;case"t":s+=" ";break;case"\\":s+="\\";break;case'"':s+='"';break;case"'":s+="'";break;case"`":s+="`";break;case"0":s+="\0";break;default:s+=o}this.pos++}}else s+=r,this.pos++}throw new Error(`Unterminated string starting at position ${t}`)}readRegex(){let n=this.pos;this.pos++;let t="",s="";for(;this.pos<this.input.length;){let r=this.input[this.pos];if(r==="/"){for(this.pos++;this.pos<this.input.length&&this.input[this.pos]==="i";)s+=this.input[this.pos],this.pos++;return{type:"regex",value:t+(s?`/${s}`:""),pos:n}}r==="\\"?(t+=r,this.pos++,this.pos<this.input.length&&(t+=this.input[this.pos],this.pos++)):(t+=r,this.pos++)}throw new Error(`Unterminated regex starting at position ${n}`)}readIdentifier(){let n=this.pos;for(;this.pos<this.input.length&&this.isIdentChar(this.input[this.pos]);)this.pos++;let t=!1;this.pos<this.input.length&&this.input[this.pos]==="?"&&(t=!0,this.pos++);let s=this.input.slice(n,t?this.pos-1:this.pos);t&&(s+="?");let r=new Map([["true","true"],["false","false"],["null","null"],["and","and"],["or","or"],["eq","eq"],["ne","ne"],["lt","lt"],["le","le"],["gt","gt"],["ge","ge"],["in","in"],["as","as"],["_","_"]]),o=s.replace(/\?$/,""),i=r.get(o);return i!==void 0&&!t?{type:i,value:o,pos:n}:{type:"ident",value:s,pos:n}}}});var Je={};Ze(Je,{parseMoonblade:()=>_,parseNamedExpressions:()=>V});function V(e){let n=[],s=new q(e).tokenize(),r=0,o=()=>s[r]||{type:"eof",value:"",pos:0},i=()=>s[r++];for(;o().type!=="eof";){if(o().type===","&&n.length>0){i();continue}let h=[],u=0,p=r;for(;o().type!=="eof";){let a=o();if((a.type===","||a.type==="as")&&u===0)break;(a.type==="("||a.type==="["||a.type==="{")&&u++,(a.type===")"||a.type==="]"||a.type==="}")&&u--,h.push(i())}h.push({type:"eof",value:"",pos:0});let f=new J(h).parse(),c;if(o().type==="as")if(i(),o().type==="("){i();let a=[];for(;o().type!==")"&&o().type!=="eof";)(o().type==="ident"||o().type==="string")&&(a.push(o().value),i()),o().type===","&&i();o().type===")"&&i(),c=a}else if(o().type==="ident"||o().type==="string")c=o().value,i();else throw new Error(`Expected name after 'as', got ${o().type}`);else c=e.slice(s[p].pos,s[r-1]?.pos||e.length).trim(),f.type==="identifier"&&(c=f.name);n.push({expr:f,name:c})}return n}function _(e){let t=new q(e).tokenize();return new J(t).parse()}var R,J,U=Ue(()=>{"use strict";He();R={PIPE:1,OR:2,AND:3,EQUALITY:4,COMPARISON:5,ADDITIVE:6,MULTIPLICATIVE:7,POWER:8,UNARY:9,POSTFIX:10},J=class{pos=0;tokens;constructor(n){this.tokens=n}parse(){let n=this.parseExpr(0);if(this.peek().type!=="eof")throw new Error(`Unexpected token: ${this.peek().value}`);return n}parseExpr(n){let t=this.parsePrefix();for(;;){let s=this.peek(),r=this.getInfixPrec(s.type);if(r<n)break;t=this.parseInfix(t,r)}return t}parsePrefix(){let n=this.peek();switch(n.type){case"int":return this.advance(),{type:"int",value:Number.parseInt(n.value,10)};case"float":return this.advance(),{type:"float",value:Number.parseFloat(n.value)};case"string":return this.advance(),{type:"string",value:n.value};case"regex":{this.advance();let t=n.value.split("/"),s=t.length>1?t[t.length-1]:"";return{type:"regex",pattern:t.slice(0,-1).join("/")||n.value,caseInsensitive:s.includes("i")}}case"true":return this.advance(),{type:"bool",value:!0};case"false":return this.advance(),{type:"bool",value:!1};case"null":return this.advance(),{type:"null"};case"_":return this.advance(),{type:"underscore"};case"ident":{let t=n.value,s=t.endsWith("?"),r=s?t.slice(0,-1):t;if(this.advance(),this.peek().type==="(")return this.parseFunctionCall(r);if(this.peek().type==="=>"){this.advance();let o=this.parseExpr(0);return this.bindLambdaArgs({type:"lambda",params:[r],body:o},[r])}return{type:"identifier",name:r,unsure:s}}case"(":{this.advance();let t=[];if(this.peek().type===")"){if(this.advance(),this.peek().type==="=>"){this.advance();let r=this.parseExpr(0);return{type:"lambda",params:[],body:r}}throw new Error("Empty parentheses not allowed")}if(this.peek().type==="ident"){let r=this.peek().value;if(this.advance(),this.peek().type===","||this.peek().type===")"){for(t.push(r);this.peek().type===","&&(this.advance(),this.peek().type==="ident");)t.push(this.peek().value),this.advance();if(this.peek().type===")"&&(this.advance(),this.peek().type==="=>")){this.advance();let o=this.parseExpr(0);return this.bindLambdaArgs({type:"lambda",params:t,body:o},t)}this.pos-=t.length*2,t.length>1&&(this.pos=this.pos)}this.pos--}let s=this.parseExpr(0);return this.expect(")"),this.peek().type,s}case"[":return this.parseList();case"{":return this.parseMap();case"-":{this.advance();let t=this.parseExpr(R.UNARY);return t.type==="int"?{type:"int",value:-t.value}:t.type==="float"?{type:"float",value:-t.value}:{type:"func",name:"neg",args:[{expr:t}]}}case"!":return this.advance(),{type:"func",name:"not",args:[{expr:this.parseExpr(R.UNARY)}]};default:throw new Error(`Unexpected token: ${n.type} (${n.value})`)}}parseFunctionCall(n){this.expect("(");let t=[];if(this.peek().type!==")")do{t.length>0&&this.peek().type===","&&this.advance();let s;if(this.peek().type==="ident"){let o=this.peek().value,i=this.pos+1;i<this.tokens.length&&this.tokens[i].type==="="&&(s=o,this.advance(),this.advance())}let r=this.parseExpr(0);t.push({name:s,expr:r})}while(this.peek().type===",");return this.expect(")"),{type:"func",name:n.toLowerCase(),args:t}}parseList(){this.expect("[");let n=[];if(this.peek().type!=="]")do n.length>0&&this.peek().type===","&&this.advance(),n.push(this.parseExpr(0));while(this.peek().type===",");return this.expect("]"),{type:"list",elements:n}}parseMap(){this.expect("{");let n=[];if(this.peek().type!=="}")do{n.length>0&&this.peek().type===","&&this.advance();let t;if(this.peek().type==="ident")t=this.peek().value,this.advance();else if(this.peek().type==="string")t=this.peek().value,this.advance();else throw new Error(`Expected map key, got ${this.peek().type}`);this.expect(":");let s=this.parseExpr(0);n.push({key:t,value:s})}while(this.peek().type===",");return this.expect("}"),{type:"map",entries:n}}parseInfix(n,t){let s=this.peek(),o=new Map([["+","add"],["-","sub"],["*","mul"],["/","div"],["//","idiv"],["%","mod"],["**","pow"],["++","concat"],["==","=="],["!=","!="],["<","<"],["<=","<="],[">",">"],[">=",">="],["eq","eq"],["ne","ne"],["lt","lt"],["le","le"],["gt","gt"],["ge","ge"],["&&","and"],["and","and"],["||","or"],["or","or"]]).get(s.type);if(o!==void 0){this.advance();let i=this.parseExpr(t+(this.isRightAssoc(s.type)?0:1));return{type:"func",name:o,args:[{expr:n},{expr:i}]}}if(s.type==="|"){this.advance();let i=this.parseExpr(t);return this.handlePipe(n,i)}if(s.type===".")return this.advance(),this.handleDot(n);if(s.type==="[")return this.advance(),this.handleIndexing(n);if(s.type==="in")return this.advance(),{type:"func",name:"contains",args:[{expr:this.parseExpr(t+1)},{expr:n}]};if(s.type==="not in")return this.advance(),{type:"func",name:"not",args:[{expr:{type:"func",name:"contains",args:[{expr:this.parseExpr(t+1)},{expr:n}]}}]};throw new Error(`Unexpected infix token: ${s.type}`)}handlePipe(n,t){if(t.type==="identifier")return{type:"func",name:t.name,args:[{expr:n}]};if(t.type==="func"){let s=this.countUnderscores(t);return s===0?t:s===1?this.fillUnderscore(t,n):{type:"pipeline",exprs:[n,t]}}return this.countUnderscores(t)===1?this.fillUnderscore(t,n):t}handleDot(n){let t=this.peek();if(t.type==="ident"){let s=t.value;if(this.advance(),this.peek().type==="("){let r=this.parseFunctionCall(s);return r.type==="func"&&r.args.unshift({expr:n}),r}return{type:"func",name:"get",args:[{expr:n},{expr:{type:"string",value:s}}]}}if(t.type==="int"){let s=Number.parseInt(t.value,10);return this.advance(),{type:"func",name:"get",args:[{expr:n},{expr:{type:"int",value:s}}]}}if(t.type==="string"){let s=t.value;return this.advance(),{type:"func",name:"get",args:[{expr:n},{expr:{type:"string",value:s}}]}}throw new Error(`Expected identifier, number, or string after dot, got ${t.type}`)}handleIndexing(n){if(this.peek().type===":"){if(this.advance(),this.peek().type==="]")return this.advance(),{type:"func",name:"slice",args:[{expr:n}]};let s=this.parseExpr(0);return this.expect("]"),{type:"func",name:"slice",args:[{expr:n},{expr:{type:"int",value:0}},{expr:s}]}}let t=this.parseExpr(0);if(this.peek().type===":"){if(this.advance(),this.peek().type==="]")return this.advance(),{type:"func",name:"slice",args:[{expr:n},{expr:t}]};let s=this.parseExpr(0);return this.expect("]"),{type:"func",name:"slice",args:[{expr:n},{expr:t},{expr:s}]}}return this.expect("]"),{type:"func",name:"get",args:[{expr:n},{expr:t}]}}countUnderscores(n){return n.type==="underscore"?1:n.type==="func"?n.args.reduce((t,s)=>t+this.countUnderscores(s.expr),0):n.type==="list"?n.elements.reduce((t,s)=>t+this.countUnderscores(s),0):n.type==="map"?n.entries.reduce((t,s)=>t+this.countUnderscores(s.value),0):0}fillUnderscore(n,t){return n.type==="underscore"?t:n.type==="func"?{...n,args:n.args.map(s=>({...s,expr:this.fillUnderscore(s.expr,t)}))}:n.type==="list"?{...n,elements:n.elements.map(s=>this.fillUnderscore(s,t))}:n.type==="map"?{...n,entries:n.entries.map(s=>({...s,value:this.fillUnderscore(s.value,t)}))}:n}bindLambdaArgs(n,t){return{...n,body:this.bindLambdaArgsInExpr(n.body,t)}}bindLambdaArgsInExpr(n,t){return n.type==="identifier"&&t.includes(n.name)?{type:"lambdaBinding",name:n.name}:n.type==="func"?{...n,args:n.args.map(s=>({...s,expr:this.bindLambdaArgsInExpr(s.expr,t)}))}:n.type==="list"?{...n,elements:n.elements.map(s=>this.bindLambdaArgsInExpr(s,t))}:n.type==="map"?{...n,entries:n.entries.map(s=>({...s,value:this.bindLambdaArgsInExpr(s.value,t)}))}:n}getInfixPrec(n){switch(n){case"|":return R.PIPE;case"||":case"or":return R.OR;case"&&":case"and":return R.AND;case"==":case"!=":case"eq":case"ne":return R.EQUALITY;case"<":case"<=":case">":case">=":case"lt":case"le":case"gt":case"ge":case"in":case"not in":return R.COMPARISON;case"+":case"-":case"++":return R.ADDITIVE;case"*":case"/":case"//":case"%":return R.MULTIPLICATIVE;case"**":return R.POWER;case".":case"[":return R.POSTFIX;default:return-1}}isRightAssoc(n){return n==="**"}peek(){return this.tokens[this.pos]||{type:"eof",value:"",pos:0}}advance(){return this.tokens[this.pos++]}expect(n){let t=this.peek();if(t.type!==n)throw new Error(`Expected ${n}, got ${t.type}`);return this.advance()}}});U();function E(e,n){return n.length===0?k(e,[]):n.length===1?{type:"Pipe",left:n[0],right:k(e,[])}:{type:"Pipe",left:n[0],right:k(e,n.slice(1))}}var z={add:e=>S("+",e[0],e[1]),sub:e=>S("-",e[0],e[1]),mul:e=>S("*",e[0],e[1]),div:e=>S("/",e[0],e[1]),mod:e=>S("%",e[0],e[1]),idiv:e=>k("floor",[S("/",e[0],e[1])]),pow:e=>E("pow",e),neg:e=>({type:"UnaryOp",op:"-",operand:e[0]}),"==":e=>S("==",e[0],e[1]),"!=":e=>S("!=",e[0],e[1]),"<":e=>S("<",e[0],e[1]),"<=":e=>S("<=",e[0],e[1]),">":e=>S(">",e[0],e[1]),">=":e=>S(">=",e[0],e[1]),eq:e=>S("==",P(e[0]),P(e[1])),ne:e=>S("!=",P(e[0]),P(e[1])),lt:e=>S("<",P(e[0]),P(e[1])),le:e=>S("<=",P(e[0]),P(e[1])),gt:e=>S(">",P(e[0]),P(e[1])),ge:e=>S(">=",P(e[0]),P(e[1])),and:e=>S("and",e[0],e[1]),or:e=>S("or",e[0],e[1]),not:e=>({type:"UnaryOp",op:"not",operand:e[0]}),len:e=>E("length",e),length:e=>E("length",e),upper:e=>E("ascii_upcase",e),lower:e=>E("ascii_downcase",e),trim:e=>E("trim",e),ltrim:e=>e.length===0?k("ltrimstr",[{type:"Literal",value:" "}]):{type:"Pipe",left:e[0],right:k("ltrimstr",[{type:"Literal",value:" "}])},rtrim:e=>e.length===0?k("rtrimstr",[{type:"Literal",value:" "}]):{type:"Pipe",left:e[0],right:k("rtrimstr",[{type:"Literal",value:" "}])},split:e=>E("split",e),join:e=>e.length===1?k("join",[{type:"Literal",value:""}]):E("join",e),concat:e=>S("+",e[0],e[1]),startswith:e=>E("startswith",e),endswith:e=>E("endswith",e),contains:e=>E("contains",e),replace:e=>E("gsub",e),substr:e=>e.length===2?{type:"Slice",base:e[0],start:e[1]}:{type:"Slice",base:e[0],start:e[1],end:S("+",e[1],e[2])},abs:e=>E("fabs",e),floor:e=>E("floor",e),ceil:e=>E("ceil",e),round:e=>E("round",e),sqrt:e=>E("sqrt",e),log:e=>E("log",e),log10:e=>E("log10",e),log2:e=>E("log2",e),exp:e=>E("exp",e),sin:e=>E("sin",e),cos:e=>E("cos",e),tan:e=>E("tan",e),asin:e=>E("asin",e),acos:e=>E("acos",e),atan:e=>E("atan",e),min:e=>E("min",e),max:e=>E("max",e),first:e=>e.length===0?{type:"Index",index:{type:"Literal",value:0}}:{type:"Index",index:{type:"Literal",value:0},base:e[0]},last:e=>e.length===0?{type:"Index",index:{type:"Literal",value:-1}}:{type:"Index",index:{type:"Literal",value:-1},base:e[0]},get:e=>e.length===1?{type:"Index",index:e[0]}:{type:"Index",index:e[1],base:e[0]},slice:e=>e.length===1?{type:"Slice",base:e[0]}:e.length===2?{type:"Slice",base:e[0],start:e[1]}:{type:"Slice",base:e[0],start:e[1],end:e[2]},keys:"keys",values:"values",entries:e=>k("to_entries",e),from_entries:"from_entries",reverse:"reverse",sort:"sort",sort_by:"sort_by",group_by:"group_by",unique:"unique",unique_by:"unique_by",flatten:"flatten",map:e=>({type:"Pipe",left:e[0],right:{type:"Array",elements:e[1]}}),select:e=>k("select",e),empty:()=>k("empty",[]),count:()=>k("length",[]),sum:e=>e.length===0?k("add",[]):{type:"Pipe",left:{type:"Array",elements:e[0]},right:k("add",[])},mean:e=>e.length===0?{type:"Pipe",left:{type:"Identity"},right:S("/",k("add",[]),k("length",[]))}:{type:"Pipe",left:{type:"Array",elements:e[0]},right:S("/",k("add",[]),k("length",[]))},avg:e=>e.length===0?{type:"Pipe",left:{type:"Identity"},right:S("/",k("add",[]),k("length",[]))}:{type:"Pipe",left:{type:"Array",elements:e[0]},right:S("/",k("add",[]),k("length",[]))},type:"type",isnull:e=>e.length===0?S("==",{type:"Identity"},{type:"Literal",value:null}):S("==",e[0],{type:"Literal",value:null}),isempty:e=>e.length===0?S("==",{type:"Identity"},{type:"Literal",value:""}):S("==",e[0],{type:"Literal",value:""}),tonumber:e=>e.length===0?k("tonumber",[]):k("tonumber",e),tostring:e=>e.length===0?k("tostring",[]):k("tostring",e),if:e=>ze(e[0],e[1],e[2]),coalesce:e=>{if(e.length===0)return{type:"Literal",value:null};if(e.length===1)return e[0];let[n,...t]=e,s=S("and",S("!=",n,{type:"Literal",value:null}),S("!=",n,{type:"Literal",value:""}));return ze(s,n,t.length===1?t[0]:z.coalesce(t))},index:()=>({type:"Field",name:"_row_index"}),now:()=>k("now",[]),fmt:e=>k("tostring",e),format:e=>k("tostring",e)};Object.setPrototypeOf(z,null);function S(e,n,t){return{type:"BinaryOp",op:e,left:n,right:t}}function k(e,n){return{type:"Call",name:e,args:n}}var nt="then";function ze(e,n,t){let s=qe({type:"Cond",cond:e,elifs:[],else:t||{type:"Literal",value:null}});return s[nt]=n,s}function P(e){return{type:"Pipe",left:e,right:{type:"Call",name:"tostring",args:[]}}}function F(e,n=!0){switch(e.type){case"int":case"float":return{type:"Literal",value:e.value};case"string":return{type:"Literal",value:e.value};case"bool":return{type:"Literal",value:e.value};case"null":return{type:"Literal",value:null};case"underscore":return{type:"Index",base:{type:"Identity"},index:{type:"Literal",value:"_"}};case"identifier":return n?{type:"Field",name:e.name}:{type:"VarRef",name:e.name};case"lambdaBinding":return{type:"VarRef",name:e.name};case"func":{let t=e.args.map(r=>F(r.expr,n)),s=Object.hasOwn(z,e.name)?z[e.name]:void 0;return typeof s=="function"?s(t):k(typeof s=="string"?s:e.name,t)}case"list":return e.elements.length===0?{type:"Array"}:{type:"Array",elements:e.elements.reduce((t,s,r)=>{let o=F(s,n);return r===0?o:{type:"Comma",left:t,right:o}},null)};case"map":return{type:"Object",entries:e.entries.map(t=>({key:t.key,value:F(t.value,n)}))};case"regex":return{type:"Literal",value:e.pattern};case"slice":return{type:"Slice",start:e.start?F(e.start,n):void 0,end:e.end?F(e.end,n):void 0};case"lambda":return F(e.body,n);case"pipeline":return{type:"Identity"};default:throw new Error(`Unknown moonblade expression type: ${e.type}`)}}function Q(e){let n=[],t=0;for(;t<e.length;){for(;t<e.length&&(e[t]===" "||e[t]===",");)t++;if(t>=e.length)break;let s=t;for(;t<e.length&&/\w/.test(e[t]);)t++;let r=e.slice(s,t);for(;t<e.length&&e[t]===" ";)t++;if(e[t]!=="(")break;t++;let o=1,i=t;for(;t<e.length&&o>0;)e[t]==="("?o++:e[t]===")"&&o--,o>0&&t++;let h=e.slice(i,t).trim();for(t++;t<e.length&&e[t]===" ";)t++;let u="";if(e.slice(t,t+3).toLowerCase()==="as "){for(t+=3;t<e.length&&e[t]===" ";)t++;let p=t;for(;t<e.length&&/\w/.test(e[t]);)t++;u=e.slice(p,t)}u||(u=h?`${r}(${h})`:`${r}()`),n.push({func:r,expr:h,alias:u})}return n}function Ke(e){return/^\w+$/.test(e)}function Z(e,n,t){let s=F(_(n)),r=$(e,s,t);return r.length>0?r[0]:null}function ee(e,n,t={}){let{func:s,expr:r}=n;if(s==="count"&&!r)return e.length;let o;switch(Ke(r)?o=e.map(i=>i[r]).filter(i=>i!=null):o=e.map(i=>Z(i,r,t)).filter(i=>i!=null),s){case"count":return Ke(r)?o.length:o.filter(i=>!!i).length;case"sum":return o.map(h=>typeof h=="number"?h:Number.parseFloat(String(h))).reduce((h,u)=>h+u,0);case"mean":case"avg":{let i=o.map(h=>typeof h=="number"?h:Number.parseFloat(String(h)));return i.length>0?i.reduce((h,u)=>h+u,0)/i.length:0}case"min":{let i=o.map(h=>typeof h=="number"?h:Number.parseFloat(String(h)));return i.length>0?Math.min(...i):null}case"max":{let i=o.map(h=>typeof h=="number"?h:Number.parseFloat(String(h)));return i.length>0?Math.max(...i):null}case"first":return o.length>0?o[0]:null;case"last":return o.length>0?o[o.length-1]:null;case"median":{let i=o.map(u=>typeof u=="number"?u:Number.parseFloat(String(u))).filter(u=>!Number.isNaN(u)).sort((u,p)=>u-p);if(i.length===0)return null;let h=Math.floor(i.length/2);return i.length%2===0?(i[h-1]+i[h])/2:i[h]}case"mode":{let i=new Map;for(let p of o){let l=String(p);i.set(l,(i.get(l)||0)+1)}let h=0,u=null;for(let[p,l]of i)l>h&&(h=l,u=p);return u}case"cardinality":return new Set(o.map(h=>String(h))).size;case"values":return o.map(i=>String(i)).join("|");case"distinct_values":return[...new Set(o.map(h=>String(h)))].sort().join("|");case"all":{if(e.length===0)return!0;for(let i of e)if(!Z(i,r,t))return!1;return!0}case"any":{for(let i of e)if(Z(i,r,t))return!0;return!1}default:return null}}function Ge(e,n,t={}){let s=O();for(let r of n)b(s,r.alias,ee(e,r,t));return s}async function te(e,n){let t="",s=[];for(let l of e)l.startsWith("-")||(t?s.push(l):t=l);if(!t)return{stdout:"",stderr:`xan agg: no aggregation expression
6
+ `,exitCode:1};let{data:r,error:o}=await v(s,n);if(o)return o;let i={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},h=Q(t),u=h.map(l=>l.alias),p=Ge(r,h,i);return{stdout:w(u,[p]),stderr:"",exitCode:0}}async function ne(e,n){let t="",s="",r=[];for(let d=0;d<e.length;d++){let m=e[d];m==="--sorted"||m.startsWith("-")||(t?s?r.push(m):s=m:t=m)}if(!t||!s)return{stdout:"",stderr:`xan groupby: usage: xan groupby COLS EXPR [FILE]
7
+ `,exitCode:1};let{data:o,error:i}=await v(r,n);if(i)return i;let h={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},u=t.split(","),p=Q(s),l=[],f=new Map;for(let d of o){let m=u.map(g=>String(d[g])).join("\0");f.has(m)||(f.set(m,[]),l.push(m)),f.get(m)?.push(d)}let c=[...u,...p.map(d=>d.alias)],a=[];for(let d of l){let m=f.get(d);if(!m)continue;let g=O();for(let y of u)b(g,y,m[0][y]);for(let y of p)b(g,y.alias,ee(m,y,h));a.push(g)}return{stdout:w(c,a),stderr:"",exitCode:0}}async function se(e,n){let t=[],s="",r=10,o=!1,i=[];for(let a=0;a<e.length;a++){let d=e[a];(d==="-s"||d==="--select")&&a+1<e.length?t=e[++a].split(","):(d==="-g"||d==="--groupby")&&a+1<e.length?s=e[++a]:(d==="-l"||d==="--limit")&&a+1<e.length?r=Number.parseInt(e[++a],10):d==="--no-extra"?o=!0:d==="-A"||d==="--all"?r=0:d.startsWith("-")||i.push(d)}let{headers:h,data:u,error:p}=await v(i,n);if(p)return p;let l=t.length>0?t:h.filter(a=>a!==s);s&&t.length===0&&(l=h.filter(a=>a!==s));let f=[],c=s?["field",s,"value","count"]:["field","value","count"];if(s){let a=new Map;for(let d of u){let m=String(d[s]??"");a.has(m)||a.set(m,[]),a.get(m)?.push(d)}for(let d of l)for(let[m,g]of a){let y=new Map;for(let I of g){let N=I[d],C=N===""||N===null||N===void 0?"":String(N);y.set(C,(y.get(C)||0)+1)}let x=[...y.entries()].sort((I,N)=>N[1]!==I[1]?N[1]-I[1]:I[0].localeCompare(N[0]));o&&(x=x.filter(([I])=>I!=="")),r>0&&(x=x.slice(0,r));for(let[I,N]of x)f.push({field:d,[s]:m,value:I===""?"<empty>":I,count:N})}}else for(let a of l){let d=new Map;for(let g of u){let y=g[a],x=y===""||y===null||y===void 0?"":String(y);d.set(x,(d.get(x)||0)+1)}let m=[...d.entries()].sort((g,y)=>y[1]!==g[1]?y[1]-g[1]:g[0].localeCompare(y[0]));o&&(m=m.filter(([g])=>g!=="")),r>0&&(m=m.slice(0,r));for(let[g,y]of m)f.push({field:a,value:g===""?"<empty>":g,count:y})}return{stdout:w(c,f),stderr:"",exitCode:0}}async function re(e,n){let t=[],s=[];for(let l=0;l<e.length;l++){let f=e[l];f==="-s"&&l+1<e.length?t=e[++l].split(","):f.startsWith("-")||s.push(f)}let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=t.length>0?t:r,u=["field","type","count","min","max","mean"],p=[];for(let l of h){let f=o.map(d=>d[l]).filter(d=>d!=null),c=f.map(d=>typeof d=="number"?d:Number.parseFloat(String(d))).filter(d=>!Number.isNaN(d)),a=c.length===f.length&&c.length>0;p.push({field:l,type:a?"Number":"String",count:f.length,min:a?Math.min(...c):"",max:a?Math.max(...c):"",mean:a?Math.round(c.reduce((d,m)=>d+m,0)/c.length*1e10)/1e10:""})}return{stdout:w(u,p),stderr:"",exitCode:0}}U();function Xe(e){let n=_(e);return F(n)}function st(e){let t=e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return H(`^${t}$`)}function K(e,n){let t=[],s=new Set;for(let r of e.split(",")){let o=r.trim();if(o.startsWith("!")){let p=o.slice(1),l=K(p,n);for(let f of l)s.add(f);continue}if(o==="*"){for(let p of n)t.includes(p)||t.push(p);continue}if(o.includes("*")){let p=st(o);for(let l of n)p.test(l)&&!t.includes(l)&&t.push(l);continue}let i=o.match(/^([^:]*):([^:]*)$/);if(i&&(i[1]||i[2])){let p=i[1],l=i[2],f=p?n.indexOf(p):0,c=l?n.indexOf(l):n.length-1;if(f!==-1&&c!==-1){let a=f<=c?1:-1;for(let d=f;a>0?d<=c:d>=c;d+=a)t.includes(n[d])||t.push(n[d])}continue}let h=o.match(/^(\d+)-(\d+)$/);if(h){let p=Number.parseInt(h[1],10),l=Number.parseInt(h[2],10);for(let f=p;f<=l&&f<n.length;f++)t.push(n[f]);continue}let u=Number.parseInt(o,10);if(!Number.isNaN(u)&&u>=0&&u<n.length){t.push(n[u]);continue}n.includes(o)&&t.push(o)}return s.size>0?t.filter(r=>!s.has(r)):t}async function oe(e,n){let t="",s=[];for(let p of e)p.startsWith("-")||(t?s.push(p):t=p);if(!t)return{stdout:"",stderr:`xan select: no columns specified
8
+ `,exitCode:1};let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=K(t,r),u=o.map(p=>{let l=O();for(let f of h)b(l,f,p[f]);return l});return{stdout:w(h,u),stderr:"",exitCode:0}}async function ie(e,n){let t="",s=[];for(let l of e)l.startsWith("-")||(t?s.push(l):t=l);if(!t)return{stdout:"",stderr:`xan drop: no columns specified
9
+ `,exitCode:1};let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=new Set(K(t,r)),u=r.filter(l=>!h.has(l)),p=o.map(l=>{let f=O();for(let c of u)b(f,c,l[c]);return f});return{stdout:w(u,p),stderr:"",exitCode:0}}async function ae(e,n){let t="",s="",r=[];for(let l=0;l<e.length;l++){let f=e[l];f==="-s"&&l+1<e.length?s=e[++l]:f.startsWith("-")||(t?r.push(f):t=f)}if(!t)return{stdout:"",stderr:`xan rename: no new name(s) specified
10
+ `,exitCode:1};let{headers:o,data:i,error:h}=await v(r,n);if(h)return h;let u;if(s){let l=s.split(","),f=t.split(","),c=new Map;for(let a=0;a<l.length&&a<f.length;a++)c.set(l[a],f[a]);u=o.map(a=>c.get(a)||a)}else{let l=t.split(",");u=o.map((f,c)=>c<l.length?l[c]:f)}let p=i.map(l=>{let f=O();for(let c=0;c<o.length;c++)b(f,u[c],l[o[c]]);return f});return{stdout:w(u,p),stderr:"",exitCode:0}}async function le(e,n){let t="index",s=[];for(let p=0;p<e.length;p++)e[p]==="-c"&&p+1<e.length?t=e[++p]:s.push(e[p]);let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=[t,...r],u=o.map((p,l)=>{let f=O();b(f,t,l);for(let c of r)b(f,c,p[c]);return f});return{stdout:w(h,u),stderr:"",exitCode:0}}async function ue(e,n){let t=e.includes("-j")||e.includes("--just-names"),{headers:s,error:r}=await v(e.filter(i=>i!=="-j"&&i!=="--just-names"),n);return r||{stdout:t?`${s.map(i=>i).join(`
11
11
  `)}
12
12
  `:`${s.map((i,h)=>`${h} ${i}`).join(`
13
13
  `)}
14
14
  `,stderr:"",exitCode:0}}async function ce(e,n){let{data:t,error:s}=await v(e,n);return s||{stdout:`${t.length}
15
- `,stderr:"",exitCode:0}}async function pe(e,n){let t=10,s=[];for(let u=0;u<e.length;u++)(e[u]==="-l"||e[u]==="-n")&&u+1<e.length?t=Number.parseInt(e[++u],10):s.push(e[u]);let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=o.slice(0,t);return{stdout:w(r,h),stderr:"",exitCode:0}}async function fe(e,n){let t=10,s=[];for(let u=0;u<e.length;u++)(e[u]==="-l"||e[u]==="-n")&&u+1<e.length?t=Number.parseInt(e[++u],10):s.push(e[u]);let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=o.slice(-t);return{stdout:w(r,h),stderr:"",exitCode:0}}async function de(e,n){let t,s,r,o=[];for(let c=0;c<e.length;c++){let a=e[c];(a==="-s"||a==="--start")&&c+1<e.length?t=Number.parseInt(e[++c],10):(a==="-e"||a==="--end")&&c+1<e.length?s=Number.parseInt(e[++c],10):(a==="-l"||a==="--len")&&c+1<e.length?r=Number.parseInt(e[++c],10):a.startsWith("-")||o.push(a)}let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;let p=t??0,l;r!==void 0?l=p+r:s!==void 0?l=s:l=h.length;let f=h.slice(p,l);return{stdout:w(i,f),stderr:"",exitCode:0}}async function he(e,n){let{headers:t,data:s,error:r}=await v(e,n);if(r)return r;let o=[...s].reverse();return{stdout:w(t,o),stderr:"",exitCode:0}}var me=Ze(et(),1);async function ge(e,n){let t=e.filter(p=>!p.startsWith("-")),{headers:s,data:r,error:o}=await v(t,n);if(o)return o;if(r.length===0){let p=["column"],l=s.map(f=>({column:f}));return{stdout:w(p,l),stderr:"",exitCode:0}}let i=s[0],h=[i,...r.map((p,l)=>String(p[i]??`row_${l}`))],u=[];for(let p=1;p<s.length;p++){let l=s[p],f=F();b(f,i,l);for(let c=0;c<r.length;c++)b(f,h[c+1],r[c][l]);u.push(f)}return{stdout:w(h,u),stderr:"",exitCode:0}}async function ye(e,n){let t=null,s=[];for(let l=0;l<e.length;l++){let f=e[l];f==="--seed"&&l+1<e.length?t=Number.parseInt(e[++l],10):f.startsWith("-")||s.push(f)}let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=t!==null?t:Date.now(),u=()=>(h=h*1103515245+12345&2147483647,h/2147483647),p=[...o];for(let l=p.length-1;l>0;l--){let f=Math.floor(u()*(l+1));[p[l],p[f]]=[p[f],p[l]]}return{stdout:w(r,p),stderr:"",exitCode:0}}async function xe(e,n){let t=null,s="",r=[];for(let a=0;a<e.length;a++){let d=e[a];(d==="-l"||d==="--length")&&a+1<e.length?t=Number.parseInt(e[++a],10):(d==="-d"||d==="--default")&&a+1<e.length?s=e[++a]:d.startsWith("-")||r.push(d)}let o=r[0],i;if(!o||o==="-")i=n.stdin;else try{let a=n.fs.resolvePath(n.cwd,o);i=await n.fs.readFile(a)}catch{return{stdout:"",stderr:`xan fixlengths: ${o}: No such file or directory
15
+ `,stderr:"",exitCode:0}}async function pe(e,n){let t=10,s=[];for(let u=0;u<e.length;u++)(e[u]==="-l"||e[u]==="-n")&&u+1<e.length?t=Number.parseInt(e[++u],10):s.push(e[u]);let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=o.slice(0,t);return{stdout:w(r,h),stderr:"",exitCode:0}}async function fe(e,n){let t=10,s=[];for(let u=0;u<e.length;u++)(e[u]==="-l"||e[u]==="-n")&&u+1<e.length?t=Number.parseInt(e[++u],10):s.push(e[u]);let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=o.slice(-t);return{stdout:w(r,h),stderr:"",exitCode:0}}async function de(e,n){let t,s,r,o=[];for(let c=0;c<e.length;c++){let a=e[c];(a==="-s"||a==="--start")&&c+1<e.length?t=Number.parseInt(e[++c],10):(a==="-e"||a==="--end")&&c+1<e.length?s=Number.parseInt(e[++c],10):(a==="-l"||a==="--len")&&c+1<e.length?r=Number.parseInt(e[++c],10):a.startsWith("-")||o.push(a)}let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;let p=t??0,l;r!==void 0?l=p+r:s!==void 0?l=s:l=h.length;let f=h.slice(p,l);return{stdout:w(i,f),stderr:"",exitCode:0}}async function he(e,n){let{headers:t,data:s,error:r}=await v(e,n);if(r)return r;let o=[...s].reverse();return{stdout:w(t,o),stderr:"",exitCode:0}}var me=Qe(tt(),1);async function ge(e,n){let t=e.filter(p=>!p.startsWith("-")),{headers:s,data:r,error:o}=await v(t,n);if(o)return o;if(r.length===0){let p=["column"],l=s.map(f=>({column:f}));return{stdout:w(p,l),stderr:"",exitCode:0}}let i=s[0],h=[i,...r.map((p,l)=>String(p[i]??`row_${l}`))],u=[];for(let p=1;p<s.length;p++){let l=s[p],f=O();b(f,i,l);for(let c=0;c<r.length;c++)b(f,h[c+1],r[c][l]);u.push(f)}return{stdout:w(h,u),stderr:"",exitCode:0}}async function ye(e,n){let t=null,s=[];for(let l=0;l<e.length;l++){let f=e[l];f==="--seed"&&l+1<e.length?t=Number.parseInt(e[++l],10):f.startsWith("-")||s.push(f)}let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=t!==null?t:Date.now(),u=()=>(h=h*1103515245+12345&2147483647,h/2147483647),p=[...o];for(let l=p.length-1;l>0;l--){let f=Math.floor(u()*(l+1));[p[l],p[f]]=[p[f],p[l]]}return{stdout:w(r,p),stderr:"",exitCode:0}}async function xe(e,n){let t=null,s="",r=[];for(let a=0;a<e.length;a++){let d=e[a];(d==="-l"||d==="--length")&&a+1<e.length?t=Number.parseInt(e[++a],10):(d==="-d"||d==="--default")&&a+1<e.length?s=e[++a]:d.startsWith("-")||r.push(d)}let o=r[0],i;if(!o||o==="-")i=n.stdin;else try{let a=n.fs.resolvePath(n.cwd,o);i=await n.fs.readFile(a)}catch{return{stdout:"",stderr:`xan fixlengths: ${o}: No such file or directory
16
16
  `,exitCode:1}}let u=me.default.parse(i.trim(),{header:!1,skipEmptyLines:!0}).data;if(u.length===0)return{stdout:"",stderr:"",exitCode:0};let p=Math.max(...u.map(a=>a.length)),l=t??p,f=u.map(a=>a.length===l?a:a.length<l?[...a,...Array(l-a.length).fill(s)]:a.slice(0,l));return{stdout:`${me.default.unparse(f).replace(/\r\n/g,`
17
17
  `)}
18
18
  `,stderr:"",exitCode:0}}async function we(e,n){let t=null,s=null,r=".",o=[];for(let c=0;c<e.length;c++){let a=e[c];(a==="-c"||a==="--chunks")&&c+1<e.length?t=Number.parseInt(e[++c],10):(a==="-S"||a==="--size")&&c+1<e.length?s=Number.parseInt(e[++c],10):(a==="-o"||a==="--output")&&c+1<e.length?r=e[++c]:a.startsWith("-")||o.push(a)}if(!t&&!s)return{stdout:"",stderr:`xan split: must specify -c or -S
@@ -25,41 +25,41 @@ import{a as F,b,c as M,d as qe,e as w,f as v,g as X,h as Y}from"./chunk-GZHFXDDO
25
25
  `,stderr:"",exitCode:0}}catch{return{stdout:`${Array.from(u.entries()).map(([l,f])=>`${l}: ${f.length} rows`).join(`
26
26
  `)}
27
27
  `,stderr:"",exitCode:0}}}async function Ce(e,n){if(e.length===0)return{stdout:"",stderr:`xan to: usage: xan to <format> [FILE]
28
- `,exitCode:1};let t=e[0],s=e.slice(1);return t==="json"?st(s,n):{stdout:"",stderr:`xan to: unsupported format '${t}'
29
- `,exitCode:1}}async function st(e,n){let t=e.filter(i=>!i.startsWith("-")),{data:s,error:r}=await v(t,n);return r||{stdout:`${JSON.stringify(s,null,2)}
30
- `,stderr:"",exitCode:0}}async function be(e,n){let t="",s=[];for(let r=0;r<e.length;r++){let o=e[r];(o==="-f"||o==="--format")&&r+1<e.length?t=e[++r]:o.startsWith("-")||s.push(o)}return t?t==="json"?rt(s,n):{stdout:"",stderr:`xan from: unsupported format '${t}'
28
+ `,exitCode:1};let t=e[0],s=e.slice(1);return t==="json"?rt(s,n):{stdout:"",stderr:`xan to: unsupported format '${t}'
29
+ `,exitCode:1}}async function rt(e,n){let t=e.filter(i=>!i.startsWith("-")),{data:s,error:r}=await v(t,n);return r||{stdout:`${JSON.stringify(s,null,2)}
30
+ `,stderr:"",exitCode:0}}async function be(e,n){let t="",s=[];for(let r=0;r<e.length;r++){let o=e[r];(o==="-f"||o==="--format")&&r+1<e.length?t=e[++r]:o.startsWith("-")||s.push(o)}return t?t==="json"?ot(s,n):{stdout:"",stderr:`xan from: unsupported format '${t}'
31
31
  `,exitCode:1}:{stdout:"",stderr:`xan from: usage: xan from -f <format> [FILE]
32
- `,exitCode:1}}async function rt(e,n){let t=e[0],s;if(!t||t==="-")s=n.stdin;else try{let r=n.fs.resolvePath(n.cwd,t);s=await n.fs.readFile(r)}catch{return{stdout:"",stderr:`xan from: ${t}: No such file or directory
32
+ `,exitCode:1}}async function ot(e,n){let t=e[0],s;if(!t||t==="-")s=n.stdin;else try{let r=n.fs.resolvePath(n.cwd,t);s=await n.fs.readFile(r)}catch{return{stdout:"",stderr:`xan from: ${t}: No such file or directory
33
33
  `,exitCode:1}}try{let r=JSON.parse(s.trim());if(!Array.isArray(r))return{stdout:"",stderr:`xan from: JSON input must be an array
34
34
  `,exitCode:1};if(r.length===0)return{stdout:`
35
- `,stderr:"",exitCode:0};if(Array.isArray(r[0])){let[i,...h]=r,u=h.map(p=>{let l=F();for(let f=0;f<i.length;f++)b(l,i[f],p[f]);return l});return{stdout:w(i,u),stderr:"",exitCode:0}}let o=Object.keys(r[0]).sort();return{stdout:w(o,r),stderr:"",exitCode:0}}catch{return{stdout:"",stderr:`xan from: invalid JSON input
35
+ `,stderr:"",exitCode:0};if(Array.isArray(r[0])){let[i,...h]=r,u=h.map(p=>{let l=O();for(let f=0;f<i.length;f++)b(l,i[f],p[f]);return l});return{stdout:w(i,u),stderr:"",exitCode:0}}let o=Object.keys(r[0]).sort();return{stdout:w(o,r),stderr:"",exitCode:0}}catch{return{stdout:"",stderr:`xan from: invalid JSON input
36
36
  `,exitCode:1}}}async function Se(e,n){let t=!1,s=0,r="",o=[];for(let c=0;c<e.length;c++){let a=e[c];if(a==="-v"||a==="--invert")t=!0;else if((a==="-l"||a==="--limit")&&c+1<e.length)s=Number.parseInt(e[++c],10);else{if(a==="--help")return D({name:"xan filter",summary:"Filter rows by expression",usage:"xan filter [OPTIONS] EXPR [FILE]",description:"Filter CSV rows using moonblade expressions.",options:["-v, --invert invert match","-l, --limit N limit output to N rows"," --help display help"]});a.startsWith("-")||(r?o.push(a):r=a)}}if(!r)return{stdout:"",stderr:`xan filter: no expression specified
37
- `,exitCode:1};let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;let p={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},l=Ge(r),f=[];for(let c of h){if(s>0&&f.length>=s)break;let a=$(c,l,p),d=a.length>0&&a.some(m=>!!m);(t?!d:d)&&f.push(c)}return{stdout:w(i,f),stderr:"",exitCode:0}}async function Ie(e,n){let t="",s=!1,r=!1,o=[];for(let l=0;l<e.length;l++){let f=e[l];f==="-N"||f==="--numeric"?s=!0:f==="-R"||f==="-r"||f==="--reverse"?r=!0:f==="-s"&&l+1<e.length?t=e[++l]:f.startsWith("-")||o.push(f)}let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;!t&&i.length>0&&(t=i[0]);let p=[...h].sort((l,f)=>{let c=l[t],a=f[t],d;if(s){let m=typeof c=="number"?c:Number.parseFloat(String(c)),g=typeof a=="number"?a:Number.parseFloat(String(a));d=m-g}else d=String(c).localeCompare(String(a));return r?-d:d});return{stdout:w(i,p),stderr:"",exitCode:0}}async function ke(e,n){let t="",s=[];for(let p=0;p<e.length;p++){let l=e[p];l==="-s"&&p+1<e.length?t=e[++p]:l.startsWith("-")||s.push(l)}let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=new Set,u=o.filter(p=>{let l=t?String(p[t]):JSON.stringify(p);return h.has(l)?!1:(h.add(l),!0)});return{stdout:w(r,u),stderr:"",exitCode:0}}async function Ne(e,n){let t=10,s="",r=!1,o=[];for(let f=0;f<e.length;f++){let c=e[f];(c==="-l"||c==="-n")&&f+1<e.length?t=Number.parseInt(e[++f],10):c==="-R"||c==="-r"||c==="--reverse"?r=!0:c.startsWith("-")||(s?o.push(c):s=c)}let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;!s&&i.length>0&&(s=i[0]);let l=[...h].sort((f,c)=>{let a=f[s],d=c[s],m=typeof a=="number"?a:Number.parseFloat(String(a)),g=typeof d=="number"?d:Number.parseFloat(String(d));return r?m-g:g-m}).slice(0,t);return{stdout:w(i,l),stderr:"",exitCode:0}}U();async function Ee(e,n){let t="",s=!1,r=!1,o=[];for(let d=0;d<e.length;d++){let m=e[d];m==="-O"||m==="--overwrite"?s=!0:m==="--filter"?r=!0:m.startsWith("-")||(t?o.push(m):t=m)}if(!t)return{stdout:"",stderr:`xan map: no expression specified
38
- `,exitCode:1};let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;let l=V(t).map(({expr:d,name:m})=>({alias:typeof m=="string"?m:m[0],ast:O(d)})),f={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},c;if(s){c=[...i];for(let d of l)i.includes(d.alias)||c.push(d.alias)}else c=[...i,...l.map(d=>d.alias)];let a=[];for(let d=0;d<h.length;d++){let m=h[d],g=M(m),y=!1,x=Object.assign(G(m),{_row_index:d});for(let I of l){let N=$(x,I.ast,f),C=N.length>0?N[0]:null;if(r&&C==null){y=!0;break}b(g,I.alias,C)}y||a.push(g)}return{stdout:w(c,a),stderr:"",exitCode:0}}async function Ae(e,n){let t="",s="",r="",o=[];for(let m=0;m<e.length;m++){let g=e[m];(g==="-r"||g==="--rename")&&m+1<e.length?r=e[++m]:g.startsWith("-")||(t?s?o.push(g):s=g:t=g)}if(!t||!s)return{stdout:"",stderr:`xan transform: usage: xan transform COLUMN EXPR [FILE]
37
+ `,exitCode:1};let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;let p={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},l=Xe(r),f=[];for(let c of h){if(s>0&&f.length>=s)break;let a=$(c,l,p),d=a.length>0&&a.some(m=>!!m);(t?!d:d)&&f.push(c)}return{stdout:w(i,f),stderr:"",exitCode:0}}async function Ie(e,n){let t="",s=!1,r=!1,o=[];for(let l=0;l<e.length;l++){let f=e[l];f==="-N"||f==="--numeric"?s=!0:f==="-R"||f==="-r"||f==="--reverse"?r=!0:f==="-s"&&l+1<e.length?t=e[++l]:f.startsWith("-")||o.push(f)}let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;!t&&i.length>0&&(t=i[0]);let p=[...h].sort((l,f)=>{let c=l[t],a=f[t],d;if(s){let m=typeof c=="number"?c:Number.parseFloat(String(c)),g=typeof a=="number"?a:Number.parseFloat(String(a));d=m-g}else d=String(c).localeCompare(String(a));return r?-d:d});return{stdout:w(i,p),stderr:"",exitCode:0}}async function ke(e,n){let t="",s=[];for(let p=0;p<e.length;p++){let l=e[p];l==="-s"&&p+1<e.length?t=e[++p]:l.startsWith("-")||s.push(l)}let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let h=new Set,u=o.filter(p=>{let l=t?String(p[t]):JSON.stringify(p);return h.has(l)?!1:(h.add(l),!0)});return{stdout:w(r,u),stderr:"",exitCode:0}}async function Ne(e,n){let t=10,s="",r=!1,o=[];for(let f=0;f<e.length;f++){let c=e[f];(c==="-l"||c==="-n")&&f+1<e.length?t=Number.parseInt(e[++f],10):c==="-R"||c==="-r"||c==="--reverse"?r=!0:c.startsWith("-")||(s?o.push(c):s=c)}let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;!s&&i.length>0&&(s=i[0]);let l=[...h].sort((f,c)=>{let a=f[s],d=c[s],m=typeof a=="number"?a:Number.parseFloat(String(a)),g=typeof d=="number"?d:Number.parseFloat(String(d));return r?m-g:g-m}).slice(0,t);return{stdout:w(i,l),stderr:"",exitCode:0}}U();async function Ee(e,n){let t="",s=!1,r=!1,o=[];for(let d=0;d<e.length;d++){let m=e[d];m==="-O"||m==="--overwrite"?s=!0:m==="--filter"?r=!0:m.startsWith("-")||(t?o.push(m):t=m)}if(!t)return{stdout:"",stderr:`xan map: no expression specified
38
+ `,exitCode:1};let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;let l=V(t).map(({expr:d,name:m})=>({alias:typeof m=="string"?m:m[0],ast:F(d)})),f={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},c;if(s){c=[...i];for(let d of l)i.includes(d.alias)||c.push(d.alias)}else c=[...i,...l.map(d=>d.alias)];let a=[];for(let d=0;d<h.length;d++){let m=h[d],g=M(m),y=!1,x=Object.assign(X(m),{_row_index:d});for(let I of l){let N=$(x,I.ast,f),C=N.length>0?N[0]:null;if(r&&C==null){y=!0;break}b(g,I.alias,C)}y||a.push(g)}return{stdout:w(c,a),stderr:"",exitCode:0}}async function Ae(e,n){let t="",s="",r="",o=[];for(let m=0;m<e.length;m++){let g=e[m];(g==="-r"||g==="--rename")&&m+1<e.length?r=e[++m]:g.startsWith("-")||(t?s?o.push(g):s=g:t=g)}if(!t||!s)return{stdout:"",stderr:`xan transform: usage: xan transform COLUMN EXPR [FILE]
39
39
  `,exitCode:1};let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;let p=t.split(",").map(m=>m.trim()),l=r?r.split(",").map(m=>m.trim()):[];for(let m of p)if(!i.includes(m))return{stdout:"",stderr:`xan transform: column '${m}' not found
40
- `,exitCode:1};let f=O(V(s)[0]?.expr||(U(),Qe(He)).parseMoonblade(s)),c={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},a=i.map(m=>{let g=p.indexOf(m);return g!==-1&&l[g]?l[g]:m}),d=[];for(let m of h){let g=M(m);for(let y=0;y<p.length;y++){let x=p[y],I=Object.assign(G(m),{_:m[x]}),N=$(I,f,c),C=N.length>0?N[0]:null,A=l[y]||x;A!==x&&delete g[x],b(g,A,C)}d.push(g)}return{stdout:w(a,d),stderr:"",exitCode:0}}async function Fe(e,n){let t="",s="|",r=!1,o="",i=[];for(let a=0;a<e.length;a++){let d=e[a];(d==="-s"||d==="--separator")&&a+1<e.length?s=e[++a]:d==="--drop-empty"?r=!0:(d==="-r"||d==="--rename")&&a+1<e.length?o=e[++a]:d.startsWith("-")||(t?i.push(d):t=d)}if(!t)return{stdout:"",stderr:`xan explode: usage: xan explode COLUMN [FILE]
40
+ `,exitCode:1};let f=F(V(s)[0]?.expr||(U(),et(Je)).parseMoonblade(s)),c={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},a=i.map(m=>{let g=p.indexOf(m);return g!==-1&&l[g]?l[g]:m}),d=[];for(let m of h){let g=M(m);for(let y=0;y<p.length;y++){let x=p[y],I=Object.assign(X(m),{_:m[x]}),N=$(I,f,c),C=N.length>0?N[0]:null,A=l[y]||x;A!==x&&delete g[x],b(g,A,C)}d.push(g)}return{stdout:w(a,d),stderr:"",exitCode:0}}async function Oe(e,n){let t="",s="|",r=!1,o="",i=[];for(let a=0;a<e.length;a++){let d=e[a];(d==="-s"||d==="--separator")&&a+1<e.length?s=e[++a]:d==="--drop-empty"?r=!0:(d==="-r"||d==="--rename")&&a+1<e.length?o=e[++a]:d.startsWith("-")||(t?i.push(d):t=d)}if(!t)return{stdout:"",stderr:`xan explode: usage: xan explode COLUMN [FILE]
41
41
  `,exitCode:1};let{headers:h,data:u,error:p}=await v(i,n);if(p)return p;if(!h.includes(t))return{stdout:"",stderr:`xan explode: column '${t}' not found
42
- `,exitCode:1};let l=o?h.map(a=>a===t?o:a):h,f=o||t,c=[];for(let a of u){let d=a[t],m=d==null?"":String(d);if(m===""){if(!r){let g=M(a);o&&(delete g[t],b(g,f,"")),c.push(g)}}else{let g=m.split(s);for(let y of g){let x=M(a);o&&delete x[t],b(x,f,y),c.push(x)}}}return{stdout:w(l,c),stderr:"",exitCode:0}}async function Oe(e,n){let t="",s="|",r="",o=[];for(let g=0;g<e.length;g++){let y=e[g];(y==="-s"||y==="--sep")&&g+1<e.length?s=e[++g]:(y==="-r"||y==="--rename")&&g+1<e.length?r=e[++g]:y.startsWith("-")||(t?o.push(y):t=y)}if(!t)return{stdout:"",stderr:`xan implode: usage: xan implode COLUMN [FILE]
42
+ `,exitCode:1};let l=o?h.map(a=>a===t?o:a):h,f=o||t,c=[];for(let a of u){let d=a[t],m=d==null?"":String(d);if(m===""){if(!r){let g=M(a);o&&(delete g[t],b(g,f,"")),c.push(g)}}else{let g=m.split(s);for(let y of g){let x=M(a);o&&delete x[t],b(x,f,y),c.push(x)}}}return{stdout:w(l,c),stderr:"",exitCode:0}}async function Fe(e,n){let t="",s="|",r="",o=[];for(let g=0;g<e.length;g++){let y=e[g];(y==="-s"||y==="--sep")&&g+1<e.length?s=e[++g]:(y==="-r"||y==="--rename")&&g+1<e.length?r=e[++g]:y.startsWith("-")||(t?o.push(y):t=y)}if(!t)return{stdout:"",stderr:`xan implode: usage: xan implode COLUMN [FILE]
43
43
  `,exitCode:1};let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;if(!i.includes(t))return{stdout:"",stderr:`xan implode: column '${t}' not found
44
44
  `,exitCode:1};let p=i.filter(g=>g!==t),l=r?i.map(g=>g===t?r:g):i,f=r||t,c=[],a=null,d=[],m=null;for(let g of h){let y=p.map(N=>String(g[N]??"")).join("\0"),x=g[t],I=x==null?"":String(x);if(y!==a){if(m!==null){let N=M(m);r&&delete N[t],b(N,f,d.join(s)),c.push(N)}a=y,d=[I],m=g}else d.push(I)}if(m!==null){let g=M(m);r&&delete g[t],b(g,f,d.join(s)),c.push(g)}return{stdout:w(l,c),stderr:"",exitCode:0}}async function Le(e,n){let t="",s="",r="",o="",i="inner",h="",u=0;for(let C=0;C<e.length;C++){let A=e[C];A==="--left"?i="left":A==="--right"?i="right":A==="--full"?i="full":(A==="-D"||A==="--default")&&C+1<e.length?h=e[++C]:A.startsWith("-")||(u++,u===1?t=A:u===2?s=A:u===3?r=A:u===4&&(o=A))}if(!t||!s||!r||!o)return{stdout:"",stderr:`xan join: usage: xan join KEY1 FILE1 KEY2 FILE2 [OPTIONS]
45
45
  `,exitCode:1};let p=await v([s],n);if(p.error)return p.error;let l=await v([o],n);if(l.error)return l.error;let{headers:f,data:c}=p,{headers:a,data:d}=l;if(!f.includes(t))return{stdout:"",stderr:`xan join: column '${t}' not found in first file
46
46
  `,exitCode:1};if(!a.includes(r))return{stdout:"",stderr:`xan join: column '${r}' not found in second file
47
- `,exitCode:1};let m=new Map;for(let C of d){let A=String(C[r]??"");m.has(A)||m.set(A,[]),m.get(A)?.push(C)}let g=new Set(f),y=a.filter(C=>!g.has(C)),x=[...f,...y],I=[],N=new Set;for(let C of c){let A=String(C[t]??""),j=m.get(A);if(j&&j.length>0){N.add(A);for(let L of j){let T=F();for(let W of f)b(T,W,C[W]);for(let W of y)b(T,W,L[W]);I.push(T)}}else if(i==="left"||i==="full"){let L=F();for(let T of f)b(L,T,C[T]);for(let T of y)b(L,T,h);I.push(L)}}if(i==="right"||i==="full")for(let C of d){let A=String(C[r]??"");if(!N.has(A)){let j=F();for(let L of f)b(j,L,a.includes(L)?C[L]:h);for(let L of y)b(j,L,C[L]);I.push(j)}}return{stdout:w(x,I),stderr:"",exitCode:0}}async function Pe(e,n){let t="",s="",r=[],o=[];for(let y=0;y<e.length;y++){let x=e[y];(x==="-g"||x==="--groupby")&&y+1<e.length?r=e[++y].split(",").map(I=>I.trim()):x.startsWith("-")||(t?s?o.push(x):s=x:t=x)}if(!t||!s)return{stdout:"",stderr:`xan pivot: usage: xan pivot COLUMN AGG_EXPR [OPTIONS] [FILE]
47
+ `,exitCode:1};let m=new Map;for(let C of d){let A=String(C[r]??"");m.has(A)||m.set(A,[]),m.get(A)?.push(C)}let g=new Set(f),y=a.filter(C=>!g.has(C)),x=[...f,...y],I=[],N=new Set;for(let C of c){let A=String(C[t]??""),j=m.get(A);if(j&&j.length>0){N.add(A);for(let L of j){let T=O();for(let W of f)b(T,W,C[W]);for(let W of y)b(T,W,L[W]);I.push(T)}}else if(i==="left"||i==="full"){let L=O();for(let T of f)b(L,T,C[T]);for(let T of y)b(L,T,h);I.push(L)}}if(i==="right"||i==="full")for(let C of d){let A=String(C[r]??"");if(!N.has(A)){let j=O();for(let L of f)b(j,L,a.includes(L)?C[L]:h);for(let L of y)b(j,L,C[L]);I.push(j)}}return{stdout:w(x,I),stderr:"",exitCode:0}}async function Pe(e,n){let t="",s="",r=[],o=[];for(let y=0;y<e.length;y++){let x=e[y];(x==="-g"||x==="--groupby")&&y+1<e.length?r=e[++y].split(",").map(I=>I.trim()):x.startsWith("-")||(t?s?o.push(x):s=x:t=x)}if(!t||!s)return{stdout:"",stderr:`xan pivot: usage: xan pivot COLUMN AGG_EXPR [OPTIONS] [FILE]
48
48
  `,exitCode:1};let{headers:i,data:h,error:u}=await v(o,n);if(u)return u;if(!i.includes(t))return{stdout:"",stderr:`xan pivot: column '${t}' not found
49
49
  `,exitCode:1};let p=s.match(/^(\w+)\((\w+)\)$/);if(!p)return{stdout:"",stderr:`xan pivot: invalid aggregation expression '${s}'
50
- `,exitCode:1};let[,l,f]=p;r.length===0&&(r=i.filter(y=>y!==t&&y!==f));let c=[];for(let y of h){let x=String(y[t]??"");c.includes(x)||c.push(x)}let a=new Map,d=[];for(let y of h){let x=r.map(A=>String(y[A]??"")).join("\0"),I=String(y[t]??""),N=y[f];a.has(x)||(a.set(x,new Map),d.push(x));let C=a.get(x);C&&(C.has(I)||C.set(I,[]),C.get(I)?.push(N))}let m=[...r,...c],g=[];for(let y of d){let x=y.split("\0"),I=a.get(y);if(!I)continue;let N=F();for(let C=0;C<r.length;C++)b(N,r[C],x[C]);for(let C of c){let A=I.get(C)||[];b(N,C,ot(l,A))}g.push(N)}return{stdout:w(m,g),stderr:"",exitCode:0}}function ot(e,n){let t=n.filter(s=>s!=null).map(s=>typeof s=="number"?s:Number.parseFloat(String(s))).filter(s=>!Number.isNaN(s));switch(e){case"count":return n.length;case"sum":return t.reduce((s,r)=>s+r,0);case"mean":case"avg":return t.length>0?t.reduce((s,r)=>s+r,0)/t.length:null;case"min":return t.length>0?Math.min(...t):null;case"max":return t.length>0?Math.max(...t):null;case"first":return n.length>0?String(n[0]??""):null;case"last":return n.length>0?String(n[n.length-1]??""):null;default:return null}}async function Re(e,n){let t="",s=[];for(let h=0;h<e.length;h++){let u=e[h];(u==="-s"||u==="--sort")&&h+1<e.length?t=e[++h]:u.startsWith("-")||s.push(u)}if(s.length<2)return{stdout:"",stderr:`xan merge: usage: xan merge [OPTIONS] FILE1 FILE2 ...
50
+ `,exitCode:1};let[,l,f]=p;r.length===0&&(r=i.filter(y=>y!==t&&y!==f));let c=[];for(let y of h){let x=String(y[t]??"");c.includes(x)||c.push(x)}let a=new Map,d=[];for(let y of h){let x=r.map(A=>String(y[A]??"")).join("\0"),I=String(y[t]??""),N=y[f];a.has(x)||(a.set(x,new Map),d.push(x));let C=a.get(x);C&&(C.has(I)||C.set(I,[]),C.get(I)?.push(N))}let m=[...r,...c],g=[];for(let y of d){let x=y.split("\0"),I=a.get(y);if(!I)continue;let N=O();for(let C=0;C<r.length;C++)b(N,r[C],x[C]);for(let C of c){let A=I.get(C)||[];b(N,C,it(l,A))}g.push(N)}return{stdout:w(m,g),stderr:"",exitCode:0}}function it(e,n){let t=n.filter(s=>s!=null).map(s=>typeof s=="number"?s:Number.parseFloat(String(s))).filter(s=>!Number.isNaN(s));switch(e){case"count":return n.length;case"sum":return t.reduce((s,r)=>s+r,0);case"mean":case"avg":return t.length>0?t.reduce((s,r)=>s+r,0)/t.length:null;case"min":return t.length>0?Math.min(...t):null;case"max":return t.length>0?Math.max(...t):null;case"first":return n.length>0?String(n[0]??""):null;case"last":return n.length>0?String(n[n.length-1]??""):null;default:return null}}async function Re(e,n){let t="",s=[];for(let h=0;h<e.length;h++){let u=e[h];(u==="-s"||u==="--sort")&&h+1<e.length?t=e[++h]:u.startsWith("-")||s.push(u)}if(s.length<2)return{stdout:"",stderr:`xan merge: usage: xan merge [OPTIONS] FILE1 FILE2 ...
51
51
  `,exitCode:1};let r=[],o=null;for(let h of s){let u=await v([h],n);if(u.error)return u.error;if(o===null)o=u.headers;else if(JSON.stringify(o)!==JSON.stringify(u.headers))return{stdout:"",stderr:`xan merge: all files must have the same headers
52
52
  `,exitCode:1};r.push({headers:u.headers,data:u.data})}if(!o)return{stdout:"",stderr:"",exitCode:0};let i=[];for(let{data:h}of r)i=i.concat(h);if(t){if(!o.includes(t))return{stdout:"",stderr:`xan merge: column '${t}' not found
53
- `,exitCode:1};i.sort((h,u)=>{let p=h[t],l=u[t],f=typeof p=="number"?p:Number.parseFloat(String(p)),c=typeof l=="number"?l:Number.parseFloat(String(l));return!Number.isNaN(f)&&!Number.isNaN(c)?f-c:String(p??"").localeCompare(String(l??""))})}return{stdout:w(o,i),stderr:"",exitCode:0}}U();async function Me(e,n){let t=e.filter(u=>!u.startsWith("-")),{headers:s,data:r,error:o}=await v(t,n);return o||(r.length===0?{stdout:"",stderr:"",exitCode:0}:{stdout:r.map(u=>s.map(p=>u[p])).map(u=>u.map(p=>it(p)).join(",")).join(`
53
+ `,exitCode:1};i.sort((h,u)=>{let p=h[t],l=u[t],f=typeof p=="number"?p:Number.parseFloat(String(p)),c=typeof l=="number"?l:Number.parseFloat(String(l));return!Number.isNaN(f)&&!Number.isNaN(c)?f-c:String(p??"").localeCompare(String(l??""))})}return{stdout:w(o,i),stderr:"",exitCode:0}}U();async function Me(e,n){let t=e.filter(u=>!u.startsWith("-")),{headers:s,data:r,error:o}=await v(t,n);return o||(r.length===0?{stdout:"",stderr:"",exitCode:0}:{stdout:r.map(u=>s.map(p=>u[p])).map(u=>u.map(p=>at(p)).join(",")).join(`
54
54
  `)+`
55
- `,stderr:"",exitCode:0})}function it(e){if(e==null)return"";let n=String(e);return n.includes(",")||n.includes('"')||n.includes(`
55
+ `,stderr:"",exitCode:0})}function at(e){if(e==null)return"";let n=String(e);return n.includes(",")||n.includes('"')||n.includes(`
56
56
  `)?`"${n.replace(/"/g,'""')}"`:n}async function $e(e,n){let t=null,s=null,r=[];for(let c=0;c<e.length;c++){let a=e[c];if(a==="--seed"&&c+1<e.length)s=Number.parseInt(e[++c],10);else if(!a.startsWith("-")){let d=Number.parseInt(a,10);t===null&&!Number.isNaN(d)&&d>0?t=d:r.push(a)}}if(t===null)return{stdout:"",stderr:`xan sample: usage: xan sample <sample-size> [FILE]
57
57
  `,exitCode:1};let{headers:o,data:i,error:h}=await v(r,n);if(h)return h;if(i.length<=t)return{stdout:w(o,i),stderr:"",exitCode:0};let u=s!==null?s:Date.now(),p=()=>(u=u*1103515245+12345&2147483647,u/2147483647),l=i.map((c,a)=>a);for(let c=l.length-1;c>0;c--){let a=Math.floor(p()*(c+1));[l[c],l[a]]=[l[a],l[c]]}let f=l.slice(0,t).sort((c,a)=>c-a).map(c=>i[c]);return{stdout:w(o,f),stderr:"",exitCode:0}}async function Te(e,n){let t=!1,s=[];for(let u=0;u<e.length;u++){let p=e[u];p==="-p"||p==="--pad"?t=!0:p.startsWith("-")||s.push(p)}if(s.length===0)return{stdout:"",stderr:`xan cat: no files specified
58
- `,exitCode:1};let r=await We(n,s,{cmdName:"xan cat",stopOnError:!0});if(r.exitCode!==0)return{stdout:"",stderr:r.stderr,exitCode:r.exitCode};let o=[],i=[];for(let{content:u}of r.files){let{headers:p,data:l}=qe(u);o.push({headers:p,data:l});for(let f of p)i.includes(f)||i.push(f)}if(!t){let u=JSON.stringify(o[0].headers);for(let p=1;p<o.length;p++)if(JSON.stringify(o[p].headers)!==u)return{stdout:"",stderr:`xan cat: headers do not match (use -p to pad)
59
- `,exitCode:1};i=o[0].headers}let h=[];for(let{headers:u,data:p}of o)for(let l of p){let f=F();for(let c of i)b(f,c,u.includes(c)?l[c]:"");h.push(f)}return{stdout:w(i,h),stderr:"",exitCode:0}}async function je(e,n){let t="",s=[],r=!1,o=!1,i=[];for(let a=0;a<e.length;a++){let d=e[a];(d==="-s"||d==="--select")&&a+1<e.length?s=e[++a].split(","):d==="-v"||d==="--invert"?r=!0:d==="-i"||d==="--ignore-case"?o=!0:d==="-r"||d==="--regex"||d.startsWith("-")||(t?i.push(d):t=d)}if(!t)return{stdout:"",stderr:`xan search: no pattern specified
58
+ `,exitCode:1};let r=await We(n,s,{cmdName:"xan cat",stopOnError:!0});if(r.exitCode!==0)return{stdout:"",stderr:r.stderr,exitCode:r.exitCode};let o=[],i=[];for(let{content:u}of r.files){let{headers:p,data:l}=_e(u);o.push({headers:p,data:l});for(let f of p)i.includes(f)||i.push(f)}if(!t){let u=JSON.stringify(o[0].headers);for(let p=1;p<o.length;p++)if(JSON.stringify(o[p].headers)!==u)return{stdout:"",stderr:`xan cat: headers do not match (use -p to pad)
59
+ `,exitCode:1};i=o[0].headers}let h=[];for(let{headers:u,data:p}of o)for(let l of p){let f=O();for(let c of i)b(f,c,u.includes(c)?l[c]:"");h.push(f)}return{stdout:w(i,h),stderr:"",exitCode:0}}async function je(e,n){let t="",s=[],r=!1,o=!1,i=[];for(let a=0;a<e.length;a++){let d=e[a];(d==="-s"||d==="--select")&&a+1<e.length?s=e[++a].split(","):d==="-v"||d==="--invert"?r=!0:d==="-i"||d==="--ignore-case"?o=!0:d==="-r"||d==="--regex"||d.startsWith("-")||(t?i.push(d):t=d)}if(!t)return{stdout:"",stderr:`xan search: no pattern specified
60
60
  `,exitCode:1};let{headers:h,data:u,error:p}=await v(i,n);if(p)return p;let l=s.length>0?s:h,f;try{f=H(t,o?"i":"")}catch{return{stdout:"",stderr:`xan search: invalid regex pattern '${t}'
61
61
  `,exitCode:1}}let c=u.filter(a=>{let d=l.some(m=>{let g=a[m];return g!=null&&f.test(String(g))});return r?!d:d});return{stdout:w(h,c),stderr:"",exitCode:0}}async function De(e,n){let t="",s=[];for(let c of e)c.startsWith("-")||(t?s.push(c):t=c);if(!t)return{stdout:"",stderr:`xan flatmap: no expression specified
62
- `,exitCode:1};let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let u=V(t).map(({expr:c,name:a})=>({alias:typeof a=="string"?a:a[0],ast:O(c)})),p={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},l=[...r,...u.map(c=>c.alias)],f=[];for(let c of o){let a=[],d=1;for(let m of u){let g=$(c,m.ast,p),y=g.length>0&&Array.isArray(g[0])?g[0]:g;a.push(y),d=Math.max(d,y.length)}for(let m=0;m<d;m++){let g=M(c);for(let y=0;y<u.length;y++){let x=a[y][m]??null;b(g,u[y].alias,x)}f.push(g)}}return{stdout:w(l,f),stderr:"",exitCode:0}}async function Ve(e,n){let{cmdView:t}=await import("./xan-view-5SZBYPLG.js");return t(e,n)}var Ye=new Set(["fuzzy-join","glob","hist","input","parallel","plot","progress","range","scrape","tokenize","union-find"]),at=new Set(["agg","behead","cat","count","dedup","drop","enum","explode","f","filter","fixlengths","flatmap","flatten","fmt","frequency","freq","from","groupby","head","headers","implode","join","map","merge","partition","pivot","rename","reverse","sample","search","select","shuffle","slice","sort","split","stats","tail","to","top","transform","transpose","view",...Ye]),Xe={name:"xan",summary:"CSV toolkit for data manipulation",usage:"xan <COMMAND> [OPTIONS] [FILE]",description:`xan is a collection of commands for working with CSV data.
62
+ `,exitCode:1};let{headers:r,data:o,error:i}=await v(s,n);if(i)return i;let u=V(t).map(({expr:c,name:a})=>({alias:typeof a=="string"?a:a[0],ast:F(c)})),p={limits:n.limits?{maxIterations:n.limits.maxJqIterations}:void 0},l=[...r,...u.map(c=>c.alias)],f=[];for(let c of o){let a=[],d=1;for(let m of u){let g=$(c,m.ast,p),y=g.length>0&&Array.isArray(g[0])?g[0]:g;a.push(y),d=Math.max(d,y.length)}for(let m=0;m<d;m++){let g=M(c);for(let y=0;y<u.length;y++){let x=a[y][m]??null;b(g,u[y].alias,x)}f.push(g)}}return{stdout:w(l,f),stderr:"",exitCode:0}}async function Ve(e,n){let{cmdView:t}=await import("./xan-view-5SZBYPLG.js");return t(e,n)}var Be=new Set(["fuzzy-join","glob","hist","input","parallel","plot","progress","range","scrape","tokenize","union-find"]),lt=new Set(["agg","behead","cat","count","dedup","drop","enum","explode","f","filter","fixlengths","flatmap","flatten","fmt","frequency","freq","from","groupby","head","headers","implode","join","map","merge","partition","pivot","rename","reverse","sample","search","select","shuffle","slice","sort","split","stats","tail","to","top","transform","transpose","view",...Be]),Ye={name:"xan",summary:"CSV toolkit for data manipulation",usage:"xan <COMMAND> [OPTIONS] [FILE]",description:`xan is a collection of commands for working with CSV data.
63
63
  It provides a simple, ergonomic interface for common data operations.
64
64
 
65
65
  COMMANDS:
@@ -133,8 +133,8 @@ EXAMPLES:
133
133
  xan groupby region 'count() as n' data.csv
134
134
  xan explode tags data.csv
135
135
  xan join id file1.csv id file2.csv
136
- xan pivot year 'sum(sales)' data.csv`,options:[" --help display this help and exit"]},lt={headers:{name:"xan headers",summary:"Show column names",usage:"xan headers [OPTIONS] [FILE]",description:"Display column names from a CSV file.",options:["-j, --just-names show names only (no index)"]},count:{name:"xan count",summary:"Count rows",usage:"xan count [FILE]",description:"Count the number of data rows (excluding header).",options:[]},filter:{name:"xan filter",summary:"Filter rows by expression",usage:"xan filter [OPTIONS] EXPR [FILE]",description:"Filter CSV rows using moonblade expressions.",options:["-v, --invert invert match","-l, --limit N limit output rows"]},search:{name:"xan search",summary:"Filter rows by regex",usage:"xan search [OPTIONS] PATTERN [FILE]",description:"Filter CSV rows by regex match on columns.",options:["-s, --select COLS search only these columns","-v, --invert invert match","-i, --ignore-case case insensitive"]},select:{name:"xan select",summary:"Select columns",usage:"xan select COLS [FILE]",description:"Select columns by name, index, glob, or range.",options:["Supports: col names, indices (0,1), ranges (a:c), globs (vec_*), negation (!col)"]},explode:{name:"xan explode",summary:"Split column into rows",usage:"xan explode COLUMN [OPTIONS] [FILE]",description:"Split delimited column values into multiple rows.",options:["-s, --separator SEP separator (default: |)","--drop-empty drop empty values","-r, --rename NAME rename column"]},implode:{name:"xan implode",summary:"Combine rows",usage:"xan implode COLUMN [OPTIONS] [FILE]",description:"Combine consecutive rows, joining column values.",options:["-s, --sep SEP separator (default: |)","-r, --rename NAME rename column"]},join:{name:"xan join",summary:"Join CSV files",usage:"xan join KEY1 FILE1 KEY2 FILE2 [OPTIONS]",description:"Join two CSV files on key columns.",options:["--left left outer join","--right right outer join","--full full outer join","-D, --default VAL default for missing"]},pivot:{name:"xan pivot",summary:"Reshape to columns",usage:"xan pivot COLUMN AGG_EXPR [OPTIONS] [FILE]",description:"Turn row values into columns.",options:["-g, --groupby COLS group by columns"]}},cn={name:"xan",async execute(e,n){if(e.length===0||K(e))return D(Xe);let t=e[0],s=e.slice(1);if(K(s)){let r=lt[t];return r?D(r):D(Xe)}if(Ye.has(t))return{stdout:"",stderr:`xan ${t}: not yet implemented
137
- `,exitCode:1};switch(t){case"headers":return ue(s,n);case"count":return ce(s,n);case"head":return pe(s,n);case"tail":return fe(s,n);case"slice":return de(s,n);case"reverse":return he(s,n);case"behead":return Me(s,n);case"sample":return $e(s,n);case"select":return oe(s,n);case"drop":return ie(s,n);case"rename":return ae(s,n);case"enum":return le(s,n);case"filter":return Se(s,n);case"search":return je(s,n);case"sort":return Ie(s,n);case"dedup":return ke(s,n);case"top":return Ne(s,n);case"map":return Ee(s,n);case"transform":return Ae(s,n);case"explode":return Fe(s,n);case"implode":return Oe(s,n);case"flatmap":return De(s,n);case"pivot":return Pe(s,n);case"agg":return te(s,n);case"groupby":return ne(s,n);case"frequency":case"freq":return se(s,n);case"stats":return re(s,n);case"cat":return Te(s,n);case"join":return Le(s,n);case"merge":return Re(s,n);case"split":return we(s,n);case"partition":return ve(s,n);case"to":return Ce(s,n);case"from":return be(s,n);case"transpose":return ge(s,n);case"shuffle":return ye(s,n);case"fixlengths":return xe(s,n);case"view":return Y(s,n);case"flatten":case"f":return X(s,n);case"fmt":return Ve(s,n);default:return at.has(t)?{stdout:"",stderr:`xan ${t}: not yet implemented
136
+ xan pivot year 'sum(sales)' data.csv`,options:[" --help display this help and exit"]},ut={headers:{name:"xan headers",summary:"Show column names",usage:"xan headers [OPTIONS] [FILE]",description:"Display column names from a CSV file.",options:["-j, --just-names show names only (no index)"]},count:{name:"xan count",summary:"Count rows",usage:"xan count [FILE]",description:"Count the number of data rows (excluding header).",options:[]},filter:{name:"xan filter",summary:"Filter rows by expression",usage:"xan filter [OPTIONS] EXPR [FILE]",description:"Filter CSV rows using moonblade expressions.",options:["-v, --invert invert match","-l, --limit N limit output rows"]},search:{name:"xan search",summary:"Filter rows by regex",usage:"xan search [OPTIONS] PATTERN [FILE]",description:"Filter CSV rows by regex match on columns.",options:["-s, --select COLS search only these columns","-v, --invert invert match","-i, --ignore-case case insensitive"]},select:{name:"xan select",summary:"Select columns",usage:"xan select COLS [FILE]",description:"Select columns by name, index, glob, or range.",options:["Supports: col names, indices (0,1), ranges (a:c), globs (vec_*), negation (!col)"]},explode:{name:"xan explode",summary:"Split column into rows",usage:"xan explode COLUMN [OPTIONS] [FILE]",description:"Split delimited column values into multiple rows.",options:["-s, --separator SEP separator (default: |)","--drop-empty drop empty values","-r, --rename NAME rename column"]},implode:{name:"xan implode",summary:"Combine rows",usage:"xan implode COLUMN [OPTIONS] [FILE]",description:"Combine consecutive rows, joining column values.",options:["-s, --sep SEP separator (default: |)","-r, --rename NAME rename column"]},join:{name:"xan join",summary:"Join CSV files",usage:"xan join KEY1 FILE1 KEY2 FILE2 [OPTIONS]",description:"Join two CSV files on key columns.",options:["--left left outer join","--right right outer join","--full full outer join","-D, --default VAL default for missing"]},pivot:{name:"xan pivot",summary:"Reshape to columns",usage:"xan pivot COLUMN AGG_EXPR [OPTIONS] [FILE]",description:"Turn row values into columns.",options:["-g, --groupby COLS group by columns"]}},fn={name:"xan",async execute(e,n){if(e.length===0||G(e))return D(Ye);let t=e[0],s=e.slice(1);if(G(s)){let r=ut[t];return r?D(r):D(Ye)}if(Be.has(t))return{stdout:"",stderr:`xan ${t}: not yet implemented
137
+ `,exitCode:1};switch(t){case"headers":return ue(s,n);case"count":return ce(s,n);case"head":return pe(s,n);case"tail":return fe(s,n);case"slice":return de(s,n);case"reverse":return he(s,n);case"behead":return Me(s,n);case"sample":return $e(s,n);case"select":return oe(s,n);case"drop":return ie(s,n);case"rename":return ae(s,n);case"enum":return le(s,n);case"filter":return Se(s,n);case"search":return je(s,n);case"sort":return Ie(s,n);case"dedup":return ke(s,n);case"top":return Ne(s,n);case"map":return Ee(s,n);case"transform":return Ae(s,n);case"explode":return Oe(s,n);case"implode":return Fe(s,n);case"flatmap":return De(s,n);case"pivot":return Pe(s,n);case"agg":return te(s,n);case"groupby":return ne(s,n);case"frequency":case"freq":return se(s,n);case"stats":return re(s,n);case"cat":return Te(s,n);case"join":return Le(s,n);case"merge":return Re(s,n);case"split":return we(s,n);case"partition":return ve(s,n);case"to":return Ce(s,n);case"from":return be(s,n);case"transpose":return ge(s,n);case"shuffle":return ye(s,n);case"fixlengths":return xe(s,n);case"view":return B(s,n);case"flatten":case"f":return Y(s,n);case"fmt":return Ve(s,n);default:return lt.has(t)?{stdout:"",stderr:`xan ${t}: not yet implemented
138
138
  `,exitCode:1}:{stdout:"",stderr:`xan: unknown command '${t}'
139
139
  Run 'xan --help' for usage.
140
- `,exitCode:1}}}},pn={name:"xan",flags:[],stdinType:"text",needsArgs:!0};export{cn as a,pn as b};
140
+ `,exitCode:1}}}},dn={name:"xan",flags:[],stdinType:"text",needsArgs:!0};export{fn as a,dn as b};