dispach 0.1.2 → 0.2.0-pilot.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 (247) hide show
  1. package/README.md +196 -118
  2. package/dist/APEv2Parser-2wqk09q7.js +5 -0
  3. package/dist/APEv2Parser-2wqk09q7.js.map +9 -0
  4. package/dist/AiffParser-zw4g2bdd.js +5 -0
  5. package/dist/AiffParser-zw4g2bdd.js.map +12 -0
  6. package/dist/App-ez7ve0yp.js +11 -0
  7. package/dist/{App-b1yrwrcq.js.map → App-ez7ve0yp.js.map} +6 -7
  8. package/dist/AsfParser-2hfcf5z2.js +5 -0
  9. package/dist/AsfParser-2hfcf5z2.js.map +14 -0
  10. package/dist/ConfigEditor-aamadrx3.js +6 -0
  11. package/dist/{ConfigEditor-n8hdw6r7.js.map → ConfigEditor-aamadrx3.js.map} +2 -2
  12. package/dist/DsdiffParser-n8smktvb.js +5 -0
  13. package/dist/DsdiffParser-n8smktvb.js.map +11 -0
  14. package/dist/DsfParser-npmjp4vr.js +5 -0
  15. package/dist/DsfParser-npmjp4vr.js.map +11 -0
  16. package/dist/FlacParser-xpbs2zmb.js +5 -0
  17. package/dist/FlacParser-xpbs2zmb.js.map +9 -0
  18. package/dist/KeyProbe-4fp152yv.js +5 -0
  19. package/dist/{KeyProbe-9jjeze5r.js.map → KeyProbe-4fp152yv.js.map} +2 -2
  20. package/dist/MP4Parser-es3afcmw.js +5 -0
  21. package/dist/MP4Parser-es3afcmw.js.map +12 -0
  22. package/dist/MatroskaParser-kxysj649.js +5 -0
  23. package/dist/MatroskaParser-kxysj649.js.map +13 -0
  24. package/dist/MpegParser-b3rr7b0f.js +5 -0
  25. package/dist/MpegParser-b3rr7b0f.js.map +13 -0
  26. package/dist/MusepackParser-sgjzmq0r.js +5 -0
  27. package/dist/MusepackParser-sgjzmq0r.js.map +16 -0
  28. package/dist/OggParser-x8h54ynf.js +5 -0
  29. package/dist/OggParser-x8h54ynf.js.map +18 -0
  30. package/dist/Picker-rq015kzc.js +5 -0
  31. package/dist/{Picker-hfeh1g6m.js.map → Picker-rq015kzc.js.map} +2 -2
  32. package/dist/SessionPicker-03zyvd2f.js +5 -0
  33. package/dist/{SessionPicker-zyqkg4dn.js.map → SessionPicker-03zyvd2f.js.map} +2 -2
  34. package/dist/SkillBrowser-8s8rjv98.js +5 -0
  35. package/dist/{SkillBrowser-3qdp8080.js.map → SkillBrowser-8s8rjv98.js.map} +2 -2
  36. package/dist/WavPackParser-w515nnw2.js +5 -0
  37. package/dist/WavPackParser-w515nnw2.js.map +11 -0
  38. package/dist/WaveParser-sb0w9m20.js +5 -0
  39. package/dist/WaveParser-sb0w9m20.js.map +13 -0
  40. package/dist/WizardApp-wr1tftcr.js +5 -0
  41. package/dist/{WizardApp-vzpbydy3.js.map → WizardApp-wr1tftcr.js.map} +3 -3
  42. package/dist/agents.d.ts +19 -3
  43. package/dist/agents.d.ts.map +1 -1
  44. package/dist/channels-gx951qdp.js +31 -0
  45. package/dist/channels-gx951qdp.js.map +10 -0
  46. package/dist/channels.d.ts +26 -0
  47. package/dist/channels.d.ts.map +1 -0
  48. package/dist/client.js +11 -11
  49. package/dist/client.js.map +3 -3
  50. package/dist/config-wvjeejgd.js +24 -0
  51. package/dist/{config-g7za9x13.js.map → config-wvjeejgd.js.map} +2 -2
  52. package/dist/credential-10dn3fxj.js +19 -0
  53. package/dist/{credential-npr6z8c8.js.map → credential-10dn3fxj.js.map} +1 -1
  54. package/dist/daemon.d.ts.map +1 -1
  55. package/dist/index-10009hp8.js +11 -0
  56. package/dist/index-10009hp8.js.map +11 -0
  57. package/dist/index-1xwrkwh5.js +14 -0
  58. package/dist/index-1xwrkwh5.js.map +50 -0
  59. package/dist/index-34p39yfc.js +47 -0
  60. package/dist/index-34p39yfc.js.map +15 -0
  61. package/dist/index-3y96s740.js +6 -0
  62. package/dist/{index-hwpvhaza.js.map → index-3y96s740.js.map} +1 -1
  63. package/dist/index-4ybeefmn.js +6 -0
  64. package/dist/index-4ybeefmn.js.map +11 -0
  65. package/dist/index-59z88wrb.js +6 -0
  66. package/dist/{index-h9mw7b9d.js.map → index-59z88wrb.js.map} +2 -2
  67. package/dist/index-5fwzn21m.js +6 -0
  68. package/dist/{index-gz9x25tz.js.map → index-5fwzn21m.js.map} +2 -2
  69. package/dist/index-6dvnfk8y.js +6 -0
  70. package/dist/index-6dvnfk8y.js.map +10 -0
  71. package/dist/index-6p70fnb7.js +153 -0
  72. package/dist/index-6p70fnb7.js.map +20 -0
  73. package/dist/index-6s471ydn.js +12 -0
  74. package/dist/{index-j55s3ehk.js.map → index-6s471ydn.js.map} +2 -2
  75. package/dist/index-87wcawta.js +6 -0
  76. package/dist/{index-0d93hyfc.js.map → index-87wcawta.js.map} +2 -2
  77. package/dist/index-92gfcbw0.js +6 -0
  78. package/dist/index-92gfcbw0.js.map +9 -0
  79. package/dist/index-a0h0p20f.js +991 -0
  80. package/dist/{index-tv4yv7d2.js.map → index-a0h0p20f.js.map} +27 -23
  81. package/dist/index-bamw24xc.js +6 -0
  82. package/dist/{index-6q4wf8e3.js.map → index-bamw24xc.js.map} +1 -1
  83. package/dist/index-c8ge88a9.js +12 -0
  84. package/dist/{index-258d8bzg.js.map → index-c8ge88a9.js.map} +4 -3
  85. package/dist/index-cb2q8nae.js +6 -0
  86. package/dist/index-cb2q8nae.js.map +13 -0
  87. package/dist/index-ct6bw0a6.js +6 -0
  88. package/dist/{index-4z7axw4r.js.map → index-ct6bw0a6.js.map} +1 -1
  89. package/dist/index-cz6yjxyz.js +10 -0
  90. package/dist/index-cz6yjxyz.js.map +42 -0
  91. package/dist/index-d0c5abkw.js +6 -0
  92. package/dist/{index-vgc3y3rm.js.map → index-d0c5abkw.js.map} +3 -3
  93. package/dist/index-d0vagham.js +31 -0
  94. package/dist/index-d0vagham.js.map +188 -0
  95. package/dist/index-d0zxvr99.js +90 -0
  96. package/dist/index-d0zxvr99.js.map +13 -0
  97. package/dist/{index-s9mbq7h6.js → index-d9c97ver.js} +4 -4
  98. package/dist/{index-s9mbq7h6.js.map → index-d9c97ver.js.map} +1 -1
  99. package/dist/index-e508e0vt.js +6 -0
  100. package/dist/{index-tf71ap9v.js.map → index-e508e0vt.js.map} +1 -1
  101. package/dist/index-esq0knqx.js +6 -0
  102. package/dist/index-esq0knqx.js.map +10 -0
  103. package/dist/index-featyhps.js +6 -0
  104. package/dist/index-featyhps.js.map +10 -0
  105. package/dist/index-fnq44zdt.js +45 -0
  106. package/dist/index-fnq44zdt.js.map +74 -0
  107. package/dist/index-gmn80dwc.js +7 -0
  108. package/dist/{index-02dn6m2j.js.map → index-gmn80dwc.js.map} +2 -2
  109. package/dist/index-gwhx69qs.js +66 -0
  110. package/dist/index-gwhx69qs.js.map +12 -0
  111. package/dist/index-kjgzhf3w.js +9 -0
  112. package/dist/{index-6p999cx4.js.map → index-kjgzhf3w.js.map} +4 -6
  113. package/dist/index-m68cd91a.js +12 -0
  114. package/dist/index-m68cd91a.js.map +23 -0
  115. package/dist/{index-3g3ny01d.js → index-mhmgw54j.js} +4 -4
  116. package/dist/{index-3g3ny01d.js.map → index-mhmgw54j.js.map} +1 -1
  117. package/dist/{index-gme2egyq.js → index-qm612hwa.js} +4 -4
  118. package/dist/{index-gme2egyq.js.map → index-qm612hwa.js.map} +1 -1
  119. package/dist/{index-j7gyr5nx.js → index-qwntpbwe.js} +7 -7
  120. package/dist/{index-j7gyr5nx.js.map → index-qwntpbwe.js.map} +1 -1
  121. package/dist/index-qx3xdk4x.js +6 -0
  122. package/dist/{index-d4x6yvqh.js.map → index-qx3xdk4x.js.map} +3 -4
  123. package/dist/{index-4cf6v9nb.js → index-rh0meegk.js} +4 -4
  124. package/dist/{index-4cf6v9nb.js.map → index-rh0meegk.js.map} +1 -1
  125. package/dist/index-ryb159ff.js +9 -0
  126. package/dist/{index-ff514z3y.js.map → index-ryb159ff.js.map} +3 -5
  127. package/dist/{index-ammv5st7.js → index-s6zfpyqa.js} +6 -6
  128. package/dist/{index-ammv5st7.js.map → index-s6zfpyqa.js.map} +1 -1
  129. package/dist/index-s9va2kmc.js +429 -0
  130. package/dist/index-s9va2kmc.js.map +11 -0
  131. package/dist/index-v5dmsgpx.js +7 -0
  132. package/dist/index-v5dmsgpx.js.map +11 -0
  133. package/dist/index-vaj3mn3a.js +6 -0
  134. package/dist/index-vaj3mn3a.js.map +14 -0
  135. package/dist/index-vy0rbzws.js +6 -0
  136. package/dist/{index-fex44816.js.map → index-vy0rbzws.js.map} +2 -2
  137. package/dist/index-w0s77wfx.js +6 -0
  138. package/dist/{index-v8e92nfw.js.map → index-w0s77wfx.js.map} +1 -1
  139. package/dist/index-wx1jzjzr.js +6 -0
  140. package/dist/{index-qdbq8crg.js.map → index-wx1jzjzr.js.map} +2 -2
  141. package/dist/index-xbn26c8g.js +126 -0
  142. package/dist/index-xbn26c8g.js.map +14 -0
  143. package/dist/index-ytvwyp6k.js +6 -0
  144. package/dist/{index-9r0wyj6w.js.map → index-ytvwyp6k.js.map} +2 -2
  145. package/dist/{index-cqqb6gaq.js → index-yvnwpxbb.js} +5 -5
  146. package/dist/{index-cqqb6gaq.js.map → index-yvnwpxbb.js.map} +1 -1
  147. package/dist/index.js +379 -448
  148. package/dist/index.js.map +26 -28
  149. package/dist/init.d.ts.map +1 -1
  150. package/dist/lib/agent-secrets.d.ts +38 -0
  151. package/dist/lib/agent-secrets.d.ts.map +1 -0
  152. package/dist/lib/agent-template.d.ts +54 -0
  153. package/dist/lib/agent-template.d.ts.map +1 -0
  154. package/dist/lib/channel-actions.d.ts +103 -0
  155. package/dist/lib/channel-actions.d.ts.map +1 -0
  156. package/dist/lib/chat-frame.d.ts +12 -1
  157. package/dist/lib/chat-frame.d.ts.map +1 -1
  158. package/dist/lib/commands.d.ts +13 -0
  159. package/dist/lib/commands.d.ts.map +1 -1
  160. package/dist/lib/const.d.ts +1 -1
  161. package/dist/lib/daemon-plan.d.ts.map +1 -1
  162. package/dist/lib/help.d.ts.map +1 -1
  163. package/dist/lib/host-actions.d.ts +121 -0
  164. package/dist/lib/host-actions.d.ts.map +1 -0
  165. package/dist/lib/init-flow.d.ts +32 -0
  166. package/dist/lib/init-flow.d.ts.map +1 -1
  167. package/dist/lib/init-whatsapp.d.ts +52 -0
  168. package/dist/lib/init-whatsapp.d.ts.map +1 -0
  169. package/dist/lib/plugin-install.d.ts +120 -0
  170. package/dist/lib/plugin-install.d.ts.map +1 -0
  171. package/dist/lib/providers.d.ts.map +1 -1
  172. package/dist/lib/provision.d.ts +13 -0
  173. package/dist/lib/provision.d.ts.map +1 -1
  174. package/dist/lib/readme-table.d.ts +15 -0
  175. package/dist/lib/readme-table.d.ts.map +1 -0
  176. package/dist/lib/sandbox.d.ts +17 -0
  177. package/dist/lib/sandbox.d.ts.map +1 -1
  178. package/dist/lib/schema.d.ts +34 -1
  179. package/dist/lib/schema.d.ts.map +1 -1
  180. package/dist/lib/subcommand.d.ts.map +1 -1
  181. package/dist/lib/web-url.d.ts +15 -0
  182. package/dist/lib/web-url.d.ts.map +1 -0
  183. package/dist/lib/wizard.d.ts.map +1 -1
  184. package/dist/memory.d.ts.map +1 -1
  185. package/dist/model.d.ts.map +1 -1
  186. package/dist/plugins.d.ts +27 -8
  187. package/dist/plugins.d.ts.map +1 -1
  188. package/dist/restart.d.ts +21 -0
  189. package/dist/restart.d.ts.map +1 -0
  190. package/dist/run.d.ts.map +1 -1
  191. package/dist/schedules.d.ts.map +1 -1
  192. package/dist/serve.d.ts.map +1 -1
  193. package/dist/sessions.d.ts.map +1 -1
  194. package/dist/skills.d.ts.map +1 -1
  195. package/dist/status.d.ts +16 -0
  196. package/dist/status.d.ts.map +1 -0
  197. package/dist/tools.d.ts.map +1 -1
  198. package/dist/validate.d.ts.map +1 -1
  199. package/dist/web-61cjhpv2.js +14 -0
  200. package/dist/{web-vkb16r62.js.map → web-61cjhpv2.js.map} +3 -3
  201. package/dist/web.d.ts +2 -13
  202. package/dist/web.d.ts.map +1 -1
  203. package/dist/workspace.d.ts.map +1 -1
  204. package/dist/wrapper-9msjh1xg.js +5 -0
  205. package/dist/wrapper-9msjh1xg.js.map +9 -0
  206. package/package.json +6 -3
  207. package/dist/App-b1yrwrcq.js +0 -11
  208. package/dist/ConfigEditor-n8hdw6r7.js +0 -6
  209. package/dist/KeyProbe-9jjeze5r.js +0 -5
  210. package/dist/Picker-hfeh1g6m.js +0 -5
  211. package/dist/SessionPicker-zyqkg4dn.js +0 -5
  212. package/dist/SkillBrowser-3qdp8080.js +0 -5
  213. package/dist/WizardApp-vzpbydy3.js +0 -5
  214. package/dist/config-g7za9x13.js +0 -24
  215. package/dist/credential-npr6z8c8.js +0 -19
  216. package/dist/index-02dn6m2j.js +0 -7
  217. package/dist/index-0d93hyfc.js +0 -6
  218. package/dist/index-1c5113t4.js +0 -66
  219. package/dist/index-1c5113t4.js.map +0 -12
  220. package/dist/index-258d8bzg.js +0 -12
  221. package/dist/index-4z7axw4r.js +0 -6
  222. package/dist/index-6p999cx4.js +0 -9
  223. package/dist/index-6q4wf8e3.js +0 -6
  224. package/dist/index-9r0wyj6w.js +0 -6
  225. package/dist/index-d4x6yvqh.js +0 -6
  226. package/dist/index-fecm8xe7.js +0 -77
  227. package/dist/index-fecm8xe7.js.map +0 -12
  228. package/dist/index-fex44816.js +0 -6
  229. package/dist/index-ff514z3y.js +0 -14
  230. package/dist/index-gz9x25tz.js +0 -6
  231. package/dist/index-h9mw7b9d.js +0 -6
  232. package/dist/index-hwpvhaza.js +0 -6
  233. package/dist/index-j55s3ehk.js +0 -12
  234. package/dist/index-mtn0g9vc.js +0 -7
  235. package/dist/index-mtn0g9vc.js.map +0 -11
  236. package/dist/index-qdbq8crg.js +0 -6
  237. package/dist/index-tf71ap9v.js +0 -6
  238. package/dist/index-ttwyrdjs.js +0 -427
  239. package/dist/index-ttwyrdjs.js.map +0 -11
  240. package/dist/index-tv4yv7d2.js +0 -903
  241. package/dist/index-ty24n0jh.js +0 -167
  242. package/dist/index-ty24n0jh.js.map +0 -19
  243. package/dist/index-v8e92nfw.js +0 -6
  244. package/dist/index-vgc3y3rm.js +0 -6
  245. package/dist/index-whaw4b18.js +0 -6
  246. package/dist/index-whaw4b18.js.map +0 -10
  247. package/dist/web-vkb16r62.js +0 -14
@@ -0,0 +1,9 @@
1
+ #!/usr/bin/env node
2
+ import{zr}from"./index-qx3xdk4x.js";import{ts,qn,os,is,c,Is}from"./index-d0c5abkw.js";function p(){return{out:process.stdout,in:process.stdin}}var o=[],i=!1,s=!1,r=!1,a=!1,u=!1,d=!1,l=!1;function yn(){r=!0}function tA(){r=!0,a=!0}function ur(){r=!0,u=!0}function dr(){r=!0,d=!0}function P(e){o.push(e)}function Br(){l=!0}function Le(e=p()){if(s||!r)return;if(s=!0,e.in.isTTY===!0&&e.in.setRawMode!==void 0)e.in.setRawMode(!1);if(e.out.isTTY!==!0)return;if(e.out.write(`${qn}${ts}`),u)e.out.write(zr);if(d)e.out.write(is);if(a)e.out.write(os)}async function Xe(e=process.stdout){if(e.writableEnded===!0||e.destroyed===!0)return;await new Promise((n)=>{e.write("",()=>n())})}async function m(){for(let e of[...o].reverse())try{await e()}catch(n){process.stderr.write(`warning: cleanup failed: ${n instanceof Error?n.message:String(n)}
3
+ `)}o.length=0}async function w(e){await m(),Le(),process.exitCode=e,await Xe()}async function mo(e){await w(e),process.exit(e)}function pr(){if(i)return;i=!0,process.on("exit",()=>Le()),process.on("SIGTERM",()=>{if(l)return;mo(Is)});let e=(n)=>(t)=>{Le();let f=t instanceof Error?t.stack??t.message:String(t);process.stderr.write(`
4
+ ${n}: ${f}
5
+ `),mo(c)};process.on("uncaughtException",e("uncaught exception")),process.on("unhandledRejection",e("unhandled rejection"))}
6
+ export{yn,tA,ur,dr,P,Br,Le,Xe,mo,pr};
7
+
8
+ //# debugId=F27D9A285EA56E7C64756E2164756E21
9
+ //# sourceMappingURL=index-kjgzhf3w.js.map
@@ -1,12 +1,10 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/lib/exit.ts", "../src/lib/keyboard.ts", "../src/lib/output.ts"],
3
+ "sources": ["../src/lib/exit.ts"],
4
4
  "sourcesContent": [
5
- "/**\n * One way out of the process.\n *\n * Two failure modes this exists to prevent, both of which the previous CLI had:\n *\n * **A hidden cursor and a terminal left in raw mode.** Ink hides the cursor and puts stdin in raw\n * mode. `process.exit()` from anywhere else — an error path, a signal, an uncaught rejection —\n * skips React's cleanup, and the shell you get back does not echo what you type. Recovering needs\n * `stty sane`, and nothing tells you that. So the restore is registered on `process.on(\"exit\")`\n * as well as run explicitly: whatever route the process takes out, the terminal is handed back.\n *\n * **Truncated output.** `process.stdout.write` to a *pipe* is asynchronous, and `process.exit()`\n * discards whatever has not flushed — so a `sessions … | head` invocation could lose its last lines,\n * intermittently and only when piped. Measured: 10 MB written and then exited immediately arrives as\n * **65,536 bytes**, one pipe buffer.\n *\n * The rule used to be \"set `process.exitCode` and let the event loop drain\", and that rule assumed the\n * loop *can* drain. It cannot. A command that boots a runtime leaves a keep-alive TLS socket to the\n * tool provider in Node's global `fetch` pool — `backend.composio.dev:443`, opened by the\n * post-readiness refresh — and that socket is ref'd, with no public API to close it. Measured: the\n * process was still alive **180 seconds** after `/exit`, and the `tools` command had to be killed at 30 s.\n * `^C` appeared to work only because SIGINT is deliberately unhandled here, so the default action kills\n * the process. a `tools --json | jq` invocation would have waited forever.\n *\n * So the rule is now: run the teardowns, drain the output *properly*, then leave. Both halves are\n * load-bearing — draining without leaving is the hang above, and leaving without draining is the\n * truncation above.\n */\n\nimport {\n DISABLE_ENHANCED_KEYS,\n EXIT_FAILURE,\n EXIT_SIGTERM,\n LEAVE_ALT_SCREEN,\n RESET_STYLE,\n SHOW_CURSOR,\n} from \"#lib/const\"\nimport { DISABLE_MOUSE } from \"#lib/mouse\"\nimport type { TerminalHandles } from \"#lib/schema\"\n\n/**\n * The real streams. Spelled out rather than passing `process` itself, which has no `in`/`out` —\n * that mistake typechecked against the structural type and threw only at runtime, inside the one\n * function whose entire job is to run when things have already gone wrong.\n */\nfunction processHandles(): TerminalHandles {\n return { out: process.stdout, in: process.stdin }\n}\n\ntype Teardown = () => void | Promise<void>\n\nconst teardowns: Teardown[] = []\nlet guardsInstalled = false\nlet restored = false\nlet dirty = false\nlet altScreen = false\nlet mouse = false\nlet enhancedKeys = false\nlet signalsClaimed = false\n\n/**\n * Declare that the terminal has been put into a state that needs undoing — raw mode, a hidden\n * cursor, alternate styling. Only the rich path does this.\n *\n * Without the flag, the restore would fire on *every* exit, including the plain path, which puts a\n * cursor-and-style reset at the end of output that is otherwise pure text. That breaks the property\n * plain mode exists for: `--plain` at a terminal has to produce exactly what a pipe produces.\n */\nexport function markTerminalDirty(): void {\n dirty = true\n}\n\n/**\n * Declare that the alternate screen buffer has been entered, so the restore swaps back out of it.\n *\n * Separate from `markTerminalDirty` rather than folded into it, because the two are not the same\n * claim: every rich surface dirties the terminal, and only the ones that *take* it need swapping\n * back. Folding them together would write the leave sequence after every wizard and every chat\n * session, and a `1049l` sent to a terminal that never entered the buffer clears the screen the\n * output was just written to — the plain path's parity rule, broken in the least debuggable way.\n *\n * Setting this and never entering is therefore worse than the reverse. The host that writes\n * `ENTER_ALT_SCREEN` calls this in the same statement.\n */\nexport function markAltScreen(): void {\n dirty = true\n altScreen = true\n}\n\n/**\n * The session asked the terminal to report the mouse, so the terminal has to be told to stop.\n *\n * Separate from `markAltScreen` because only the chat reads mouse reports. A surface that enabled\n * tracking without claiming every report would have them typed into it as text, which is what Ink does\n * with one — so the flag follows whoever handles them rather than whoever took the screen.\n *\n * Left on, the shell that gets the terminal back emits a report on every click and scroll, into a prompt\n * that has no idea what they are. That is the failure worth being loud about: it outlives the process.\n */\nexport function markMouse(): void {\n dirty = true\n mouse = true\n}\n\n/**\n * Ink negotiated the kitty keyboard protocol, so the terminal has to be told to stop reporting that way.\n *\n * Ink pops it itself on unmount and around a suspend — this exists for the path it cannot cover, which is\n * the same one `markMouse` exists for: a signal. `SIGTERM` is the only route a service manager uses, and\n * a terminal left in the protocol hands the next shell `CSI u` for every Ctrl chord, which reads as a\n * broken keyboard and outlives the process.\n *\n * Set by the render sites rather than derived, because whether the protocol was actually *pushed* depends\n * on the terminal answering a query 200 ms after mount — so the honest flag is \"we asked\", and popping a\n * protocol that was never pushed is a no-op on every terminal.\n */\nexport function markEnhancedKeys(): void {\n dirty = true\n enhancedKeys = true\n}\n\n/**\n * Run before the process ends. Registration order is preserved and reversed on the way out, so a\n * later-registered resource is released before the thing it depends on.\n */\nexport function onExit(teardown: Teardown): void {\n teardowns.push(teardown)\n}\n\n/**\n * Take ownership of SIGTERM, for a command whose shutdown *is* the point.\n *\n * The default guard answers SIGTERM with `finishNow(EXIT_SIGTERM)`, which is right for a command\n * that was interrupted: 143 is the shell convention and the work was not finished. It is wrong for\n * `serve`, where a signal is the ordinary and expected way to stop — the work was to stay up, and\n * being asked to stop is the successful end of it, not a failure.\n *\n * That distinction is not cosmetic once a service manager is involved. The generated service\n * definition restarts only on a crash, precisely so a misconfiguration stops once instead of\n * looping forever; a graceful stop reported as 143 is indistinguishable from that misconfiguration,\n * so the supervisor would refuse to bring the agent back.\n *\n * The caller must resolve its own wait on the signal and return an exit code normally. Everything\n * registered with `onExit` still runs, because `finish` awaits the teardowns either way.\n */\nexport function claimSignals(): void {\n signalsClaimed = true\n}\n\n/**\n * Synchronous by necessity — `process.on(\"exit\")` cannot await. Idempotent, because it runs both\n * explicitly and from the exit hook.\n */\nexport function restoreTerminal(handles: TerminalHandles = processHandles()): void {\n if (restored || !dirty) return\n restored = true\n if (handles.in.isTTY === true && handles.in.setRawMode !== undefined) {\n handles.in.setRawMode(false)\n }\n if (handles.out.isTTY !== true) return\n // Style and cursor first, buffer swap second. A reset applies to the buffer that is current when\n // it arrives, so resetting after the swap leaves the app's last colour on the shell's screen and\n // dutifully resets the one being thrown away.\n handles.out.write(`${RESET_STYLE}${SHOW_CURSOR}`)\n // Before the buffer swap, for the same reason the style reset is: the request was made against this\n // buffer and the shell must not be left with a terminal that reports clicks at it.\n if (mouse) handles.out.write(DISABLE_MOUSE)\n // Before the buffer swap for the same reason, and after the mouse for no reason but stable ordering\n // — a test asserts the sequence, and an order nothing pins is an order that drifts.\n //\n // This is usually the *second* pop: Ink pops on unmount, and on both the normal and the signal path\n // the unmount teardown has already run by the time this fires. Kept anyway, because the path it exists\n // for is the one where teardowns do not run at all — a hard crash — and a terminal left reporting\n // `CSI u` for every Ctrl chord outlives the process. Seen in a capture as `[<u[<u`.\n //\n // The cost is stated rather than hidden. A pop on an empty stack is ignored, so standalone this is\n // harmless; nested inside *another* application that pushed its own flags, the extra pop takes that\n // application's entry instead. That trade is accepted for a top-level CLI and would be the wrong one\n // for a library.\n if (enhancedKeys) handles.out.write(DISABLE_ENHANCED_KEYS)\n if (altScreen) handles.out.write(LEAVE_ALT_SCREEN)\n}\n\n/** Test seam. Nothing in `src/` outside this module calls it. */\nexport function resetForTests(\n options: {\n readonly dirty?: boolean\n readonly altScreen?: boolean\n readonly mouse?: boolean\n readonly enhancedKeys?: boolean\n } = {},\n): void {\n teardowns.length = 0\n restored = false\n dirty = options.dirty ?? true\n altScreen = options.altScreen ?? false\n mouse = options.mouse ?? false\n enhancedKeys = options.enhancedKeys ?? false\n signalsClaimed = false\n}\n\n/** Enough of a stream to wait on. Spelled out so a test can supply one without a pipe. */\ninterface Drainable {\n write(chunk: string, callback: () => void): unknown\n readonly writableEnded?: boolean\n readonly destroyed?: boolean\n}\n\n/**\n * Wait until everything written to stdout has actually reached the operating system.\n *\n * This used to test `writableNeedDrain` and await a `drain` event, which is a weaker claim than it\n * reads as: the flag is only true once the buffer is *over* the high-water mark, so a modest pending\n * write to a pipe reported nothing to wait for and the function named \"flush\" returned immediately.\n * That was survivable while the process went on to idle until the loop emptied, and is not survivable\n * now that it exits on purpose.\n *\n * A zero-length write is the receipt. `Writable` invokes callbacks in write order once the underlying\n * write completes, so a chunk queued behind everything else calls back only after everything else has\n * gone out. Measured against a pipe with a sleeping reader: 10 MB exits complete, where an immediate\n * `process.exit` delivered 65,536 bytes.\n *\n * **The wait is deliberately unbounded.** A timeout would trade a silent truncation for a bounded exit,\n * and with a slow reader — `| less`, a terminal being scrolled — truncation is the worse of the two. A\n * closed reader is not the hazard it looks like: the callback still fires, carrying `EPIPE`.\n *\n * Also awaited between turns, where the point is different: a long session feeding a slow reader\n * accumulates unwritten output in memory, and this bounds that to one turn's worth.\n */\nexport async function flushOutput(stream: Drainable = process.stdout): Promise<void> {\n // Nothing to wait for, and writing would throw. Checked rather than caught, because a throw here\n // lands inside the function whose whole job is to run when things are already ending.\n if (stream.writableEnded === true || stream.destroyed === true) return\n await new Promise<void>((resolve) => {\n stream.write(\"\", () => resolve())\n })\n}\n\nasync function runTeardowns(): Promise<void> {\n for (const teardown of [...teardowns].reverse()) {\n try {\n await teardown()\n } catch (error) {\n // A failing teardown must not mask the exit code that brought us here, and must not\n // stop the remaining teardowns — the terminal restore is one of them.\n process.stderr.write(\n `warning: cleanup failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n )\n }\n }\n teardowns.length = 0\n}\n\n/**\n * Everything that has to happen before the process ends: teardowns, the terminal, the exit code, and\n * the output.\n *\n * Sets `process.exitCode` rather than exiting, so a caller that has its own reason to stay alive can.\n * Nothing in `src/` is such a caller any more — the entry point uses `finishNow` — but the split is\n * what makes this testable: a `finish` that exited would take the test runner with it.\n */\nexport async function finish(code: number): Promise<void> {\n await runTeardowns()\n restoreTerminal()\n process.exitCode = code\n await flushOutput()\n}\n\n/**\n * Finish, and then actually leave.\n *\n * The ordinary way out, not the exceptional one. It was written for a signal or a crash — \"where\n * waiting for the loop to drain would mean hanging\" — on the assumption that the ordinary path could\n * wait. It cannot: the module docstring records the measurement, a keep-alive socket in the global\n * `fetch` pool that outlived the process by three minutes.\n *\n * Safe to call here and nowhere earlier, because `finish` has already awaited the teardowns and the\n * output. Anything still holding the loop open at this point is a resource with no owner, and waiting\n * on one is what the hang was.\n */\nexport async function finishNow(code: number): Promise<never> {\n await finish(code)\n process.exit(code)\n}\n\n/**\n * Guards for the ways a process dies without being asked to.\n *\n * `SIGINT` is deliberately **not** handled here. During a turn it means \"cancel this turn\", not\n * \"exit\" — the chat path owns it, and a guard that exited would break the contract Phase 1\n * established and measured.\n */\nexport function installGuards(): void {\n if (guardsInstalled) return\n guardsInstalled = true\n\n // Last line of defence. Runs even when something calls process.exit directly.\n process.on(\"exit\", () => restoreTerminal())\n\n process.on(\"SIGTERM\", () => {\n // Yield to a command that owns its own shutdown. Without this the two handlers raced and\n // the hard exit won: `serve`'s graceful path started, `process.exit(143)` landed first, and\n // `runtime.stop()` never completed — so the outbox was not flushed, the database was not\n // closed, and the child processes `exec` backgrounds were never reaped. Invisible at a\n // terminal, because ctrl-C sends SIGINT and this guard deliberately ignores that one.\n if (signalsClaimed) return\n void finishNow(EXIT_SIGTERM)\n })\n\n const crash = (label: string) => (error: unknown) => {\n restoreTerminal()\n const message = error instanceof Error ? (error.stack ?? error.message) : String(error)\n // Loud and non-zero. An unexpected failure that exits 0 is the thing hard rule 8 forbids.\n process.stderr.write(`\\n${label}: ${message}\\n`)\n void finishNow(EXIT_FAILURE)\n }\n process.on(\"uncaughtException\", crash(\"uncaught exception\"))\n process.on(\"unhandledRejection\", crash(\"unhandled rejection\"))\n}\n",
6
- "/**\n * Whether this process asks the terminal for enhanced keys, and what it asks for.\n *\n * ## Why there is anything to ask for\n *\n * Ink 7.1 ships a complete kitty-keyboard-protocol parser — `parse-keypress.js` decodes `CSI u`, and\n * `Key` carries `super`, `hyper`, `home` and `end` — and **none of it runs unless a caller opts in**:\n *\n * initKittyKeyboard() {\n * // Protocol is opt-in: if kittyKeyboard is not specified, do nothing\n * if (!this.options.kittyKeyboard) return\n *\n * That single `return` is why `⌥r` typed `®` into the message instead of unfolding the reasoning block,\n * and why `cmd+←` word-moved instead of jumping to the start of the line: without the protocol, `⌥`\n * depends on a terminal setting that is off by default in Warp, and `super` cannot be expressed by any\n * legacy escape sequence at all — Ink's legacy branch folds it into `meta` (`modifier & 10`, bit 8 being\n * super and bit 2 alt), so the two chords become the same keystroke.\n *\n * ## Why both flags\n *\n * `disambiguateEscapeCodes` alone fixes the letter chords: `⌥r` arrives as `CSI 114;3u`, which Ink reports\n * as `input \"r\"` with `meta` set — exactly the shape `keymap.ts` already matched, which is why turning\n * this on required no change to a single binding. It is **not** enough for `cmd+←`: an arrow with a\n * modifier comes back as `CSI 1;9D`, and Ink's kitty branch for special keys (`kittySpecialKeyRe`)\n * *requires* the `:eventType` field, so without `reportEventTypes` the sequence falls through to the\n * legacy path and the super bit is folded away again.\n *\n * The cost of that second flag is stated where it is paid: Ink passes `eventType` through untouched and\n * filters nothing, so `keymap.ts` drops `release` or every enhanced chord fires twice.\n *\n * ## Why `enabled` rather than `auto`, measured\n *\n * `auto` is the careful-looking option: Ink writes `CSI ? u`, waits **200 ms**, and enables only if the\n * terminal answers. It was the first choice here and it loses the race. In a real Warp session the reply\n * arrived *after* the window closed — visible in `keys` as `bytes 1b 5b 3f 30 75` resolving to an insert,\n * because Ink strips the answer only while it is still listening. So the protocol stayed **off** on a\n * terminal that plainly supports it, and every option-letter chord went on depending on Warp's\n * *Left/Right Option Key is Meta* setting, which is off by default. That is the reported bug, one layer\n * down from where it looked like it was.\n *\n * `enabled` pushes `CSI > flags u` without asking. The cost is bounded by how terminals treat private-mode\n * sequences they do not know — they discard them — and the pop on the way out is the same shape. It is\n * also no longer load-bearing: `lib/csi.ts` reads modifiers off the bytes, so a terminal that ignores the\n * push still gets working cmd chords. The protocol now buys the *letter* chords, and losing it silently\n * costs those rather than everything.\n *\n * The override stays for the case neither argument covers: a terminal that accepts the push and then\n * implements it badly. The reference CLI carries the same hatch (`CLAUDE_CODE_DISABLE_MOUSE`), and a\n * switch nobody can reach is not a hatch.\n */\n\nimport { readEnv } from \"#lib/env\"\n/**\n * The render options fragment, shaped structurally rather than imported from Ink.\n *\n * Declared here for the same reason `KeyState` is declared in `lib/types.ts` rather than imported: this\n * module sits on a path every command touches, and Ink costs ~170-210 ms to load under Node — more than\n * the entire runtime of `validate --json`. TypeScript checks it structurally against `RenderOptions` at\n * each call site, so a drift in Ink's own type is still a compile error.\n */\nimport { markEnhancedKeys } from \"#lib/exit\"\n\nexport interface KeyboardOptions {\n readonly kittyKeyboard?: {\n readonly mode: \"auto\" | \"enabled\" | \"disabled\"\n /**\n * The property is readonly; the array is not, because Ink's own `flags` is a mutable\n * `KittyFlagName[]` and under `exactOptionalPropertyTypes` a `readonly` array does not satisfy\n * it. Nothing is shared as a result — `keyboardOptions` builds a fresh array on every call, which\n * is what makes the mutable type harmless rather than a hole.\n */\n readonly flags: (\"disambiguateEscapeCodes\" | \"reportEventTypes\")[]\n }\n}\n\n/**\n * One answer for every surface that mounts Ink, and the teardown registered with it.\n *\n * Every one of them reads keys, so a per-surface decision would mean the chat honoured `cmd+←` and the\n * settings editor did not — and the *next* surface would forget entirely. `inSession` on `CommandSpec` is\n * the same shape: derived once so a new caller cannot drift.\n *\n * It marks rather than merely returning, which is why it is not called `keyboardOptions`: asking for the\n * protocol and arranging to withdraw it are one decision, and six call sites each remembering to do the\n * second is six chances to leave a terminal reporting `CSI u` at somebody's shell. Ink withdraws it on\n * unmount by itself; the mark covers the signal path, which is the one Ink cannot see.\n */\nexport function negotiateKeyboard(disabled?: boolean): KeyboardOptions {\n // `??` rather than a default parameter: a default fires on an explicitly passed `undefined` too, and\n // this repo has already lost a debugging round to that (`load(dir, undefined)` used the runner it was\n // meant to omit). Written this way, \"no opinion\" and \"not passed\" are deliberately the same case.\n if (disabled ?? readEnv().noEnhancedKeys) return {}\n markEnhancedKeys()\n return {\n kittyKeyboard: {\n // Not \"auto\" — see above. Ink's 200 ms detection window loses the race in Warp, measured.\n mode: \"enabled\",\n flags: [\"disambiguateEscapeCodes\", \"reportEventTypes\"],\n },\n }\n}\n",
7
- "/**\n * How output is rendered, resolved once per process.\n *\n * This mirrors the reasoning behind decision 3.5, which forbids the tool dialect from changing with\n * the model: behaviour that shifts silently with the environment cannot be reasoned about. So the\n * resolution is total and ordered, and it returns *why* it chose — the reason is printable, which is\n * what turns \"it wasn't interactive and I don't know why\" into a question with an answer.\n *\n * Measured, not assumed: importing Ink and React costs ~65 ms under Bun and ~170-210 ms under Node,\n * against a ~70 ms total runtime for `validate --json`. Nothing on a non-rich path may import them,\n * which is why this returns a mode rather than a renderer.\n */\n\nimport { readEnv } from \"#lib/env\"\nimport type { ModeDecision, ModeInputs } from \"#lib/schema\"\n\n/**\n * Total and ordered. Every branch is reachable and every input is consulted, so no combination of\n * flags and environment lands somewhere undocumented.\n */\nexport function resolveMode(inputs: ModeInputs): ModeDecision {\n if (inputs.json) return { mode: \"json\", because: \"--json was passed\" }\n if (inputs.plain) return { mode: \"plain\", because: \"--plain was passed\" }\n\n // A one-shot is a scripting affordance. Its output must not depend on whether a human happened\n // to be at a terminal, or `--input` would mean two different things in a shell script and in a\n // shell.\n if (inputs.oneShot) return { mode: \"plain\", because: \"--input is always plain\" }\n\n if (!inputs.stdoutIsTTY) return { mode: \"plain\", because: \"stdout is not a terminal\" }\n // A live transcript with no way to type into it is a worse plain renderer, not a better one.\n if (!inputs.stdinIsTTY) return { mode: \"plain\", because: \"stdin is not a terminal\" }\n\n if (inputs.env.noColor) return { mode: \"plain\", because: \"NO_COLOR is set\" }\n if (inputs.env.dumbTerminal) return { mode: \"plain\", because: \"TERM is dumb\" }\n // CI logs are files that happen to scroll. Cursor movement in one is noise forever.\n if (inputs.env.ci) return { mode: \"plain\", because: \"CI is set\" }\n\n return { mode: \"rich\", because: \"stdout and stdin are both terminals\" }\n}\n\n/**\n * Deliberately not consulted: `FORCE_COLOR`. It says how much colour a stream can carry, not\n * whether a human is watching, and honouring it here would turn a CI job that wanted coloured logs\n * into one driving a cursor around a file. Ink's own colour depth still respects it.\n */\nexport function resolveModeFromProcess(flags: {\n readonly json: boolean\n readonly plain: boolean\n readonly oneShot: boolean\n}): ModeDecision {\n return resolveMode({\n ...flags,\n stdinIsTTY: process.stdin.isTTY === true,\n stdoutIsTTY: process.stdout.isTTY === true,\n env: readEnv(),\n })\n}\n"
5
+ "/**\n * One way out of the process.\n *\n * Two failure modes this exists to prevent, both of which the previous CLI had:\n *\n * **A hidden cursor and a terminal left in raw mode.** Ink hides the cursor and puts stdin in raw\n * mode. `process.exit()` from anywhere else — an error path, a signal, an uncaught rejection —\n * skips React's cleanup, and the shell you get back does not echo what you type. Recovering needs\n * `stty sane`, and nothing tells you that. So the restore is registered on `process.on(\"exit\")`\n * as well as run explicitly: whatever route the process takes out, the terminal is handed back.\n *\n * **Truncated output.** `process.stdout.write` to a *pipe* is asynchronous, and `process.exit()`\n * discards whatever has not flushed — so a `sessions … | head` invocation could lose its last lines,\n * intermittently and only when piped. Measured: 10 MB written and then exited immediately arrives as\n * **65,536 bytes**, one pipe buffer.\n *\n * The rule used to be \"set `process.exitCode` and let the event loop drain\", and that rule assumed the\n * loop *can* drain. It cannot. A command that boots a runtime leaves a keep-alive TLS socket to the\n * tool provider in Node's global `fetch` pool — `backend.composio.dev:443`, opened by the\n * post-readiness refresh — and that socket is ref'd, with no public API to close it. Measured: the\n * process was still alive **180 seconds** after `/exit`, and the `tools` command had to be killed at 30 s.\n * `^C` appeared to work only because SIGINT is deliberately unhandled here, so the default action kills\n * the process. a `tools --json | jq` invocation would have waited forever.\n *\n * So the rule is now: run the teardowns, drain the output *properly*, then leave. Both halves are\n * load-bearing — draining without leaving is the hang above, and leaving without draining is the\n * truncation above.\n */\n\nimport {\n DISABLE_ENHANCED_KEYS,\n EXIT_FAILURE,\n EXIT_SIGTERM,\n LEAVE_ALT_SCREEN,\n RESET_STYLE,\n SHOW_CURSOR,\n} from \"#lib/const\"\nimport { DISABLE_MOUSE } from \"#lib/mouse\"\nimport type { TerminalHandles } from \"#lib/schema\"\n\n/**\n * The real streams. Spelled out rather than passing `process` itself, which has no `in`/`out` —\n * that mistake typechecked against the structural type and threw only at runtime, inside the one\n * function whose entire job is to run when things have already gone wrong.\n */\nfunction processHandles(): TerminalHandles {\n return { out: process.stdout, in: process.stdin }\n}\n\ntype Teardown = () => void | Promise<void>\n\nconst teardowns: Teardown[] = []\nlet guardsInstalled = false\nlet restored = false\nlet dirty = false\nlet altScreen = false\nlet mouse = false\nlet enhancedKeys = false\nlet signalsClaimed = false\n\n/**\n * Declare that the terminal has been put into a state that needs undoing — raw mode, a hidden\n * cursor, alternate styling. Only the rich path does this.\n *\n * Without the flag, the restore would fire on *every* exit, including the plain path, which puts a\n * cursor-and-style reset at the end of output that is otherwise pure text. That breaks the property\n * plain mode exists for: `--plain` at a terminal has to produce exactly what a pipe produces.\n */\nexport function markTerminalDirty(): void {\n dirty = true\n}\n\n/**\n * Declare that the alternate screen buffer has been entered, so the restore swaps back out of it.\n *\n * Separate from `markTerminalDirty` rather than folded into it, because the two are not the same\n * claim: every rich surface dirties the terminal, and only the ones that *take* it need swapping\n * back. Folding them together would write the leave sequence after every wizard and every chat\n * session, and a `1049l` sent to a terminal that never entered the buffer clears the screen the\n * output was just written to — the plain path's parity rule, broken in the least debuggable way.\n *\n * Setting this and never entering is therefore worse than the reverse. The host that writes\n * `ENTER_ALT_SCREEN` calls this in the same statement.\n */\nexport function markAltScreen(): void {\n dirty = true\n altScreen = true\n}\n\n/**\n * The session asked the terminal to report the mouse, so the terminal has to be told to stop.\n *\n * Separate from `markAltScreen` because only the chat reads mouse reports. A surface that enabled\n * tracking without claiming every report would have them typed into it as text, which is what Ink does\n * with one — so the flag follows whoever handles them rather than whoever took the screen.\n *\n * Left on, the shell that gets the terminal back emits a report on every click and scroll, into a prompt\n * that has no idea what they are. That is the failure worth being loud about: it outlives the process.\n */\nexport function markMouse(): void {\n dirty = true\n mouse = true\n}\n\n/**\n * Ink negotiated the kitty keyboard protocol, so the terminal has to be told to stop reporting that way.\n *\n * Ink pops it itself on unmount and around a suspend — this exists for the path it cannot cover, which is\n * the same one `markMouse` exists for: a signal. `SIGTERM` is the only route a service manager uses, and\n * a terminal left in the protocol hands the next shell `CSI u` for every Ctrl chord, which reads as a\n * broken keyboard and outlives the process.\n *\n * Set by the render sites rather than derived, because whether the protocol was actually *pushed* depends\n * on the terminal answering a query 200 ms after mount — so the honest flag is \"we asked\", and popping a\n * protocol that was never pushed is a no-op on every terminal.\n */\nexport function markEnhancedKeys(): void {\n dirty = true\n enhancedKeys = true\n}\n\n/**\n * Run before the process ends. Registration order is preserved and reversed on the way out, so a\n * later-registered resource is released before the thing it depends on.\n */\nexport function onExit(teardown: Teardown): void {\n teardowns.push(teardown)\n}\n\n/**\n * Take ownership of SIGTERM, for a command whose shutdown *is* the point.\n *\n * The default guard answers SIGTERM with `finishNow(EXIT_SIGTERM)`, which is right for a command\n * that was interrupted: 143 is the shell convention and the work was not finished. It is wrong for\n * `serve`, where a signal is the ordinary and expected way to stop — the work was to stay up, and\n * being asked to stop is the successful end of it, not a failure.\n *\n * That distinction is not cosmetic once a service manager is involved. The generated service\n * definition restarts only on a crash, precisely so a misconfiguration stops once instead of\n * looping forever; a graceful stop reported as 143 is indistinguishable from that misconfiguration,\n * so the supervisor would refuse to bring the agent back.\n *\n * The caller must resolve its own wait on the signal and return an exit code normally. Everything\n * registered with `onExit` still runs, because `finish` awaits the teardowns either way.\n */\nexport function claimSignals(): void {\n signalsClaimed = true\n}\n\n/**\n * Synchronous by necessity — `process.on(\"exit\")` cannot await. Idempotent, because it runs both\n * explicitly and from the exit hook.\n */\nexport function restoreTerminal(handles: TerminalHandles = processHandles()): void {\n if (restored || !dirty) return\n restored = true\n if (handles.in.isTTY === true && handles.in.setRawMode !== undefined) {\n handles.in.setRawMode(false)\n }\n if (handles.out.isTTY !== true) return\n // Style and cursor first, buffer swap second. A reset applies to the buffer that is current when\n // it arrives, so resetting after the swap leaves the app's last colour on the shell's screen and\n // dutifully resets the one being thrown away.\n handles.out.write(`${RESET_STYLE}${SHOW_CURSOR}`)\n // Before the buffer swap, for the same reason the style reset is: the request was made against this\n // buffer and the shell must not be left with a terminal that reports clicks at it.\n if (mouse) handles.out.write(DISABLE_MOUSE)\n // Before the buffer swap for the same reason, and after the mouse for no reason but stable ordering\n // — a test asserts the sequence, and an order nothing pins is an order that drifts.\n //\n // This is usually the *second* pop: Ink pops on unmount, and on both the normal and the signal path\n // the unmount teardown has already run by the time this fires. Kept anyway, because the path it exists\n // for is the one where teardowns do not run at all — a hard crash — and a terminal left reporting\n // `CSI u` for every Ctrl chord outlives the process. Seen in a capture as `[<u[<u`.\n //\n // The cost is stated rather than hidden. A pop on an empty stack is ignored, so standalone this is\n // harmless; nested inside *another* application that pushed its own flags, the extra pop takes that\n // application's entry instead. That trade is accepted for a top-level CLI and would be the wrong one\n // for a library.\n if (enhancedKeys) handles.out.write(DISABLE_ENHANCED_KEYS)\n if (altScreen) handles.out.write(LEAVE_ALT_SCREEN)\n}\n\n/** Test seam. Nothing in `src/` outside this module calls it. */\nexport function resetForTests(\n options: {\n readonly dirty?: boolean\n readonly altScreen?: boolean\n readonly mouse?: boolean\n readonly enhancedKeys?: boolean\n } = {},\n): void {\n teardowns.length = 0\n restored = false\n dirty = options.dirty ?? true\n altScreen = options.altScreen ?? false\n mouse = options.mouse ?? false\n enhancedKeys = options.enhancedKeys ?? false\n signalsClaimed = false\n}\n\n/** Enough of a stream to wait on. Spelled out so a test can supply one without a pipe. */\ninterface Drainable {\n write(chunk: string, callback: () => void): unknown\n readonly writableEnded?: boolean\n readonly destroyed?: boolean\n}\n\n/**\n * Wait until everything written to stdout has actually reached the operating system.\n *\n * This used to test `writableNeedDrain` and await a `drain` event, which is a weaker claim than it\n * reads as: the flag is only true once the buffer is *over* the high-water mark, so a modest pending\n * write to a pipe reported nothing to wait for and the function named \"flush\" returned immediately.\n * That was survivable while the process went on to idle until the loop emptied, and is not survivable\n * now that it exits on purpose.\n *\n * A zero-length write is the receipt. `Writable` invokes callbacks in write order once the underlying\n * write completes, so a chunk queued behind everything else calls back only after everything else has\n * gone out. Measured against a pipe with a sleeping reader: 10 MB exits complete, where an immediate\n * `process.exit` delivered 65,536 bytes.\n *\n * **The wait is deliberately unbounded.** A timeout would trade a silent truncation for a bounded exit,\n * and with a slow reader — `| less`, a terminal being scrolled — truncation is the worse of the two. A\n * closed reader is not the hazard it looks like: the callback still fires, carrying `EPIPE`.\n *\n * Also awaited between turns, where the point is different: a long session feeding a slow reader\n * accumulates unwritten output in memory, and this bounds that to one turn's worth.\n */\nexport async function flushOutput(stream: Drainable = process.stdout): Promise<void> {\n // Nothing to wait for, and writing would throw. Checked rather than caught, because a throw here\n // lands inside the function whose whole job is to run when things are already ending.\n if (stream.writableEnded === true || stream.destroyed === true) return\n await new Promise<void>((resolve) => {\n stream.write(\"\", () => resolve())\n })\n}\n\nasync function runTeardowns(): Promise<void> {\n for (const teardown of [...teardowns].reverse()) {\n try {\n await teardown()\n } catch (error) {\n // A failing teardown must not mask the exit code that brought us here, and must not\n // stop the remaining teardowns — the terminal restore is one of them.\n process.stderr.write(\n `warning: cleanup failed: ${error instanceof Error ? error.message : String(error)}\\n`,\n )\n }\n }\n teardowns.length = 0\n}\n\n/**\n * Everything that has to happen before the process ends: teardowns, the terminal, the exit code, and\n * the output.\n *\n * Sets `process.exitCode` rather than exiting, so a caller that has its own reason to stay alive can.\n * Nothing in `src/` is such a caller any more — the entry point uses `finishNow` — but the split is\n * what makes this testable: a `finish` that exited would take the test runner with it.\n */\nexport async function finish(code: number): Promise<void> {\n await runTeardowns()\n restoreTerminal()\n process.exitCode = code\n await flushOutput()\n}\n\n/**\n * Finish, and then actually leave.\n *\n * The ordinary way out, not the exceptional one. It was written for a signal or a crash — \"where\n * waiting for the loop to drain would mean hanging\" — on the assumption that the ordinary path could\n * wait. It cannot: the module docstring records the measurement, a keep-alive socket in the global\n * `fetch` pool that outlived the process by three minutes.\n *\n * Safe to call here and nowhere earlier, because `finish` has already awaited the teardowns and the\n * output. Anything still holding the loop open at this point is a resource with no owner, and waiting\n * on one is what the hang was.\n */\nexport async function finishNow(code: number): Promise<never> {\n await finish(code)\n process.exit(code)\n}\n\n/**\n * Guards for the ways a process dies without being asked to.\n *\n * `SIGINT` is deliberately **not** handled here. During a turn it means \"cancel this turn\", not\n * \"exit\" — the chat path owns it, and a guard that exited would break the contract Phase 1\n * established and measured.\n */\nexport function installGuards(): void {\n if (guardsInstalled) return\n guardsInstalled = true\n\n // Last line of defence. Runs even when something calls process.exit directly.\n process.on(\"exit\", () => restoreTerminal())\n\n process.on(\"SIGTERM\", () => {\n // Yield to a command that owns its own shutdown. Without this the two handlers raced and\n // the hard exit won: `serve`'s graceful path started, `process.exit(143)` landed first, and\n // `runtime.stop()` never completed — so the outbox was not flushed, the database was not\n // closed, and the child processes `exec` backgrounds were never reaped. Invisible at a\n // terminal, because ctrl-C sends SIGINT and this guard deliberately ignores that one.\n if (signalsClaimed) return\n void finishNow(EXIT_SIGTERM)\n })\n\n const crash = (label: string) => (error: unknown) => {\n restoreTerminal()\n const message = error instanceof Error ? (error.stack ?? error.message) : String(error)\n // Loud and non-zero. An unexpected failure that exits 0 is the thing hard rule 8 forbids.\n process.stderr.write(`\\n${label}: ${message}\\n`)\n void finishNow(EXIT_FAILURE)\n }\n process.on(\"uncaughtException\", crash(\"uncaught exception\"))\n process.on(\"unhandledRejection\", crash(\"unhandled rejection\"))\n}\n"
8
6
  ],
9
- "mappings": ";0HA6CA,SAAS,CAAc,EAAoB,CACvC,MAAO,CAAE,IAAK,QAAQ,OAAQ,GAAI,QAAQ,KAAM,EAKpD,IAAM,EAAwB,CAAC,EAC3B,EAAkB,GAClB,EAAW,GACX,EAAQ,GACR,EAAY,GACZ,EAAQ,GACR,EAAe,GACf,EAAiB,GAUd,SAAS,EAAiB,EAAS,CACtC,EAAQ,GAeL,SAAS,EAAa,EAAS,CAClC,EAAQ,GACR,EAAY,GAaT,SAAS,EAAS,EAAS,CAC9B,EAAQ,GACR,EAAQ,GAeL,SAAS,CAAgB,EAAS,CACrC,EAAQ,GACR,EAAe,GAOZ,SAAS,CAAM,CAAC,EAA0B,CAC7C,EAAU,KAAK,CAAQ,EAmBpB,SAAS,EAAY,EAAS,CACjC,EAAiB,GAOd,SAAS,CAAe,CAAC,EAA2B,EAAe,EAAS,CAC/E,GAAI,GAAY,CAAC,EAAO,OAExB,GADA,EAAW,GACP,EAAQ,GAAG,QAAU,IAAQ,EAAQ,GAAG,aAAe,OACvD,EAAQ,GAAG,WAAW,EAAK,EAE/B,GAAI,EAAQ,IAAI,QAAU,GAAM,OAOhC,GAHA,EAAQ,IAAI,MAAM,GAAG,KAAc,IAAa,EAG5C,EAAO,EAAQ,IAAI,MAAM,EAAa,EAa1C,GAAI,EAAc,EAAQ,IAAI,MAAM,EAAqB,EACzD,GAAI,EAAW,EAAQ,IAAI,MAAM,EAAgB,EAiDrD,eAAsB,EAAW,CAAC,EAAoB,QAAQ,OAAuB,CAGjF,GAAI,EAAO,gBAAkB,IAAQ,EAAO,YAAc,GAAM,OAChE,MAAM,IAAI,QAAc,CAAC,IAAY,CACjC,EAAO,MAAM,GAAI,IAAM,EAAQ,CAAC,EACnC,EAGL,eAAe,CAAY,EAAkB,CACzC,QAAW,IAAY,CAAC,GAAG,CAAS,EAAE,QAAQ,EAC1C,GAAI,CACA,MAAM,EAAS,EACjB,MAAO,EAAO,CAGZ,QAAQ,OAAO,MACX,4BAA4B,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK;AAAA,CACrF,EAGR,EAAU,OAAS,EAWvB,eAAsB,CAAM,CAAC,EAA6B,CACtD,MAAM,EAAa,EACnB,EAAgB,EAChB,QAAQ,SAAW,EACnB,MAAM,GAAY,EAetB,eAAsB,EAAS,CAAC,EAA8B,CAC1D,MAAM,EAAO,CAAI,EACjB,QAAQ,KAAK,CAAI,EAUd,SAAS,EAAa,EAAS,CAClC,GAAI,EAAiB,OACrB,EAAkB,GAGlB,QAAQ,GAAG,OAAQ,IAAM,EAAgB,CAAC,EAE1C,QAAQ,GAAG,UAAW,IAAM,CAMxB,GAAI,EAAgB,OACf,GAAU,EAAY,EAC9B,EAED,IAAM,EAAQ,CAAC,IAAkB,CAAC,IAAmB,CACjD,EAAgB,EAChB,IAAM,EAAU,aAAiB,MAAS,EAAM,OAAS,EAAM,QAAW,OAAO,CAAK,EAEtF,QAAQ,OAAO,MAAM;AAAA,EAAK,MAAU;AAAA,CAAW,EAC1C,GAAU,CAAY,GAE/B,QAAQ,GAAG,oBAAqB,EAAM,oBAAoB,CAAC,EAC3D,QAAQ,GAAG,qBAAsB,EAAM,qBAAqB,CAAC,ECtO1D,SAAS,CAAiB,CAAC,EAAqC,CAInE,GAAI,GAAY,GAAQ,EAAE,eAAgB,MAAO,CAAC,EAElD,OADA,EAAiB,EACV,CACH,cAAe,CAEX,KAAM,UACN,MAAO,CAAC,0BAA2B,kBAAkB,CACzD,CACJ,EC/EG,SAAS,CAAW,CAAC,EAAkC,CAC1D,GAAI,EAAO,KAAM,MAAO,CAAE,KAAM,OAAQ,QAAS,mBAAoB,EACrE,GAAI,EAAO,MAAO,MAAO,CAAE,KAAM,QAAS,QAAS,oBAAqB,EAKxE,GAAI,EAAO,QAAS,MAAO,CAAE,KAAM,QAAS,QAAS,yBAA0B,EAE/E,GAAI,CAAC,EAAO,YAAa,MAAO,CAAE,KAAM,QAAS,QAAS,0BAA2B,EAErF,GAAI,CAAC,EAAO,WAAY,MAAO,CAAE,KAAM,QAAS,QAAS,yBAA0B,EAEnF,GAAI,EAAO,IAAI,QAAS,MAAO,CAAE,KAAM,QAAS,QAAS,iBAAkB,EAC3E,GAAI,EAAO,IAAI,aAAc,MAAO,CAAE,KAAM,QAAS,QAAS,cAAe,EAE7E,GAAI,EAAO,IAAI,GAAI,MAAO,CAAE,KAAM,QAAS,QAAS,WAAY,EAEhE,MAAO,CAAE,KAAM,OAAQ,QAAS,qCAAsC,EAQnE,SAAS,EAAsB,CAAC,EAItB,CACb,OAAO,EAAY,IACZ,EACH,WAAY,QAAQ,MAAM,QAAU,GACpC,YAAa,QAAQ,OAAO,QAAU,GACtC,IAAK,GAAQ,CACjB,CAAC",
10
- "debugId": "3E8EC0EBBACD374564756E2164756E21",
7
+ "mappings": ";sFA6CA,SAAS,CAAc,EAAoB,CACvC,MAAO,CAAE,IAAK,QAAQ,OAAQ,GAAI,QAAQ,KAAM,EAKpD,IAAM,EAAwB,CAAC,EAC3B,EAAkB,GAClB,EAAW,GACX,EAAQ,GACR,EAAY,GACZ,EAAQ,GACR,EAAe,GACf,EAAiB,GAUd,SAAS,EAAiB,EAAS,CACtC,EAAQ,GAeL,SAAS,EAAa,EAAS,CAClC,EAAQ,GACR,EAAY,GAaT,SAAS,EAAS,EAAS,CAC9B,EAAQ,GACR,EAAQ,GAeL,SAAS,EAAgB,EAAS,CACrC,EAAQ,GACR,EAAe,GAOZ,SAAS,CAAM,CAAC,EAA0B,CAC7C,EAAU,KAAK,CAAQ,EAmBpB,SAAS,EAAY,EAAS,CACjC,EAAiB,GAOd,SAAS,EAAe,CAAC,EAA2B,EAAe,EAAS,CAC/E,GAAI,GAAY,CAAC,EAAO,OAExB,GADA,EAAW,GACP,EAAQ,GAAG,QAAU,IAAQ,EAAQ,GAAG,aAAe,OACvD,EAAQ,GAAG,WAAW,EAAK,EAE/B,GAAI,EAAQ,IAAI,QAAU,GAAM,OAOhC,GAHA,EAAQ,IAAI,MAAM,GAAG,KAAc,IAAa,EAG5C,EAAO,EAAQ,IAAI,MAAM,EAAa,EAa1C,GAAI,EAAc,EAAQ,IAAI,MAAM,EAAqB,EACzD,GAAI,EAAW,EAAQ,IAAI,MAAM,EAAgB,EAiDrD,eAAsB,EAAW,CAAC,EAAoB,QAAQ,OAAuB,CAGjF,GAAI,EAAO,gBAAkB,IAAQ,EAAO,YAAc,GAAM,OAChE,MAAM,IAAI,QAAc,CAAC,IAAY,CACjC,EAAO,MAAM,GAAI,IAAM,EAAQ,CAAC,EACnC,EAGL,eAAe,CAAY,EAAkB,CACzC,QAAW,IAAY,CAAC,GAAG,CAAS,EAAE,QAAQ,EAC1C,GAAI,CACA,MAAM,EAAS,EACjB,MAAO,EAAO,CAGZ,QAAQ,OAAO,MACX,4BAA4B,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK;AAAA,CACrF,EAGR,EAAU,OAAS,EAWvB,eAAsB,CAAM,CAAC,EAA6B,CACtD,MAAM,EAAa,EACnB,GAAgB,EAChB,QAAQ,SAAW,EACnB,MAAM,GAAY,EAetB,eAAsB,EAAS,CAAC,EAA8B,CAC1D,MAAM,EAAO,CAAI,EACjB,QAAQ,KAAK,CAAI,EAUd,SAAS,EAAa,EAAS,CAClC,GAAI,EAAiB,OACrB,EAAkB,GAGlB,QAAQ,GAAG,OAAQ,IAAM,GAAgB,CAAC,EAE1C,QAAQ,GAAG,UAAW,IAAM,CAMxB,GAAI,EAAgB,OACf,GAAU,EAAY,EAC9B,EAED,IAAM,EAAQ,CAAC,IAAkB,CAAC,IAAmB,CACjD,GAAgB,EAChB,IAAM,EAAU,aAAiB,MAAS,EAAM,OAAS,EAAM,QAAW,OAAO,CAAK,EAEtF,QAAQ,OAAO,MAAM;AAAA,EAAK,MAAU;AAAA,CAAW,EAC1C,GAAU,CAAY,GAE/B,QAAQ,GAAG,oBAAqB,EAAM,oBAAoB,CAAC,EAC3D,QAAQ,GAAG,qBAAsB,EAAM,qBAAqB,CAAC",
8
+ "debugId": "F27D9A285EA56E7C64756E2164756E21",
11
9
  "names": []
12
10
  }
@@ -0,0 +1,12 @@
1
+ #!/usr/bin/env node
2
+ import{g,e,u}from"./index-92gfcbw0.js";var b=e(function(cr,Me){var Re=["nodebuffer","arraybuffer","fragments"],Ue=typeof Blob<"u";if(Ue)Re.push("blob");Me.exports={BINARY_TYPES:Re,CLOSE_TIMEOUT:30000,EMPTY_BUFFER:Buffer.alloc(0),GUID:"258EAFA5-E914-47DA-95CA-C5AB0DC85B11",hasBlob:Ue,kForOnEventAttribute:Symbol("kIsForOnEventAttribute"),kListener:Symbol("kListener"),kStatusCode:Symbol("status-code"),kWebSocket:Symbol("websocket"),NOOP:()=>{}}});var K=e(function(ur,re){var{EMPTY_BUFFER:At}=b(),ye=Buffer[Symbol.species];function Ft(t,s){if(t.length===0)return At;if(t.length===1)return t[0];let r=Buffer.allocUnsafe(s),i=0;for(let n=0;n<t.length;n++){let o=t[n];r.set(o,i),i+=o.length}if(i<s)return new ye(r.buffer,r.byteOffset,i);return r}function Ae(t,s,r,i,n){for(let o=0;o<n;o++)r[i+o]=t[o]^s[o&3]}function Fe(t,s){for(let r=0;r<t.length;r++)t[r]^=s[r&3]}function Gt(t){if(t.length===t.buffer.byteLength)return t.buffer;return t.buffer.slice(t.byteOffset,t.byteOffset+t.length)}function xe(t){if(xe.readOnly=!0,Buffer.isBuffer(t))return t;let s;if(t instanceof ArrayBuffer)s=new ye(t);else if(ArrayBuffer.isView(t))s=new ye(t.buffer,t.byteOffset,t.byteLength);else s=Buffer.from(t),xe.readOnly=!1;return s}re.exports={concat:Ft,mask:Ae,toArrayBuffer:Gt,toBuffer:xe,unmask:Fe};if(!process.env.WS_NO_BUFFER_UTIL)try{let t=(()=>{throw new Error("Cannot require module "+"bufferutil");})();re.exports.mask=function(s,r,i,n,o){if(o<48)Ae(s,r,i,n,o);else t.mask(s,r,i,n,o)},re.exports.unmask=function(s,r){if(s.length<32)Fe(s,r);else t.unmask(s,r)}}catch(t){}});var Ve=e(function(_r,$e){var Ge=Symbol("kDone"),Ee=Symbol("kRun");class qe{constructor(t){this[Ge]=()=>{this.pending--,this[Ee]()},this.concurrency=t||1/0,this.jobs=[],this.pending=0}add(t){this.jobs.push(t),this[Ee]()}[Ee](){if(this.pending===this.concurrency)return;if(this.jobs.length){let t=this.jobs.shift();this.pending++,t(this[Ge])}}}$e.exports=qe});var q=e(function(dr,Ye){var X=u("zlib"),je=K(),qt=Ve(),{kStatusCode:We}=b(),$t=Buffer[Symbol.species],Vt=Buffer.from([0,0,255,255]),ne=Symbol("permessage-deflate"),N=Symbol("total-length"),F=Symbol("callback"),L=Symbol("buffers"),G=Symbol("error"),ie;class ze{constructor(t){if(this._options=t||{},this._threshold=this._options.threshold!==void 0?this._options.threshold:1024,this._maxPayload=this._options.maxPayload|0,this._isServer=!!this._options.isServer,this._deflate=null,this._inflate=null,this.params=null,!ie){let s=this._options.concurrencyLimit!==void 0?this._options.concurrencyLimit:10;ie=new qt(s)}}static get extensionName(){return"permessage-deflate"}offer(){let t={};if(this._options.serverNoContextTakeover)t.server_no_context_takeover=!0;if(this._options.clientNoContextTakeover)t.client_no_context_takeover=!0;if(this._options.serverMaxWindowBits)t.server_max_window_bits=this._options.serverMaxWindowBits;if(this._options.clientMaxWindowBits)t.client_max_window_bits=this._options.clientMaxWindowBits;else if(this._options.clientMaxWindowBits==null)t.client_max_window_bits=!0;return t}accept(t){return t=this.normalizeParams(t),this.params=this._isServer?this.acceptAsServer(t):this.acceptAsClient(t),this.params}cleanup(){if(this._inflate)this._inflate.close(),this._inflate=null;if(this._deflate){let t=this._deflate[F];if(this._deflate.close(),this._deflate=null,t)t(Error("The deflate stream was closed while data was being processed"))}}acceptAsServer(t){let s=this._options,r=t.find((i)=>{if(s.serverNoContextTakeover===!1&&i.server_no_context_takeover||i.server_max_window_bits&&(s.serverMaxWindowBits===!1||typeof s.serverMaxWindowBits==="number"&&s.serverMaxWindowBits>i.server_max_window_bits)||typeof s.clientMaxWindowBits==="number"&&(typeof i.client_max_window_bits==="number"?s.clientMaxWindowBits>i.client_max_window_bits:!i.client_max_window_bits))return!1;return!0});if(!r)throw Error("None of the extension offers can be accepted");if(s.serverNoContextTakeover)r.server_no_context_takeover=!0;if(s.clientNoContextTakeover)r.client_no_context_takeover=!0;if(typeof s.serverMaxWindowBits==="number")r.server_max_window_bits=s.serverMaxWindowBits;if(typeof s.clientMaxWindowBits==="number")r.client_max_window_bits=s.clientMaxWindowBits;else if(r.client_max_window_bits===!0||s.clientMaxWindowBits===!1)delete r.client_max_window_bits;return r}acceptAsClient(t){let s=t[0];if(this._options.clientNoContextTakeover===!1&&s.client_no_context_takeover)throw Error('Unexpected parameter "client_no_context_takeover"');if(!s.client_max_window_bits){if(typeof this._options.clientMaxWindowBits==="number")s.client_max_window_bits=this._options.clientMaxWindowBits}else if(this._options.clientMaxWindowBits===!1||typeof this._options.clientMaxWindowBits==="number"&&s.client_max_window_bits>this._options.clientMaxWindowBits)throw Error('Unexpected or invalid parameter "client_max_window_bits"');return s}normalizeParams(t){return t.forEach((s)=>{Object.keys(s).forEach((r)=>{let i=s[r];if(i.length>1)throw Error(`Parameter "${r}" must have only a single value`);if(i=i[0],r==="client_max_window_bits"){if(i!==!0){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(!this._isServer)throw TypeError(`Invalid value for parameter "${r}": ${i}`)}else if(r==="server_max_window_bits"){let n=+i;if(!Number.isInteger(n)||n<8||n>15)throw TypeError(`Invalid value for parameter "${r}": ${i}`);i=n}else if(r==="client_no_context_takeover"||r==="server_no_context_takeover"){if(i!==!0)throw TypeError(`Invalid value for parameter "${r}": ${i}`)}else throw Error(`Unknown parameter "${r}"`);s[r]=i})}),t}decompress(t,s,r){ie.add((i)=>{this._decompress(t,s,(n,o)=>{i(),r(n,o)})})}compress(t,s,r){ie.add((i)=>{this._compress(t,s,(n,o)=>{i(),r(n,o)})})}_decompress(t,s,r){let i=this._isServer?"client":"server";if(!this._inflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!=="number"?X.Z_DEFAULT_WINDOWBITS:this.params[n];this._inflate=X.createInflateRaw({...this._options.zlibInflateOptions,windowBits:o}),this._inflate[ne]=this,this._inflate[N]=0,this._inflate[L]=[],this._inflate.on("error",Wt),this._inflate.on("data",He)}if(this._inflate[F]=r,this._inflate.write(t),s)this._inflate.write(Vt);this._inflate.flush(()=>{let n=this._inflate[G];if(n){this._inflate.close(),this._inflate=null,r(n);return}let o=je.concat(this._inflate[L],this._inflate[N]);if(this._inflate._readableState.endEmitted)this._inflate.close(),this._inflate=null;else if(this._inflate[N]=0,this._inflate[L]=[],s&&this.params[`${i}_no_context_takeover`])this._inflate.reset();r(null,o)})}_compress(t,s,r){let i=this._isServer?"server":"client";if(!this._deflate){let n=`${i}_max_window_bits`,o=typeof this.params[n]!=="number"?X.Z_DEFAULT_WINDOWBITS:this.params[n];this._deflate=X.createDeflateRaw({...this._options.zlibDeflateOptions,windowBits:o}),this._deflate[N]=0,this._deflate[L]=[],this._deflate.on("data",jt)}this._deflate[F]=r,this._deflate.write(t),this._deflate.flush(X.Z_SYNC_FLUSH,()=>{if(!this._deflate)return;let n=je.concat(this._deflate[L],this._deflate[N]);if(s)n=new $t(n.buffer,n.byteOffset,n.length-4);if(this._deflate[F]=null,this._deflate[N]=0,this._deflate[L]=[],s&&this.params[`${i}_no_context_takeover`])this._deflate.reset();r(null,n)})}}Ye.exports=ze;function jt(t){this[L].push(t),this[N]+=t.length}function He(t){if(this[N]+=t.length,this[ne]._maxPayload<1||this[N]<=this[ne]._maxPayload){this[L].push(t);return}this[G]=RangeError("Max payload size exceeded"),this[G].code="WS_ERR_UNSUPPORTED_MESSAGE_LENGTH",this[G][We]=1009,this.removeListener("data",He),this.reset()}function Wt(t){if(this[ne]._inflate=null,this[G]){this[F](this[G]);return}t[We]=1007,this[F](t)}});var V=e(function(mr,oe){var{isUtf8:Ze}=u("buffer"),{hasBlob:zt}=b(),Ht=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,1,1,1,1,0,0,1,1,0,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,0,1,0];function Yt(t){return t>=1000&&t<=1014&&t!==1004&&t!==1005&&t!==1006||t>=3000&&t<=4999}function Se(t){let s=t.length,r=0;while(r<s)if((t[r]&128)===0)r++;else if((t[r]&224)===192){if(r+1===s||(t[r+1]&192)!==128||(t[r]&254)===192)return!1;r+=2}else if((t[r]&240)===224){if(r+2>=s||(t[r+1]&192)!==128||(t[r+2]&192)!==128||t[r]===224&&(t[r+1]&224)===128||t[r]===237&&(t[r+1]&224)===160)return!1;r+=3}else if((t[r]&248)===240){if(r+3>=s||(t[r+1]&192)!==128||(t[r+2]&192)!==128||(t[r+3]&192)!==128||t[r]===240&&(t[r+1]&240)===128||t[r]===244&&t[r+1]>143||t[r]>244)return!1;r+=4}else return!1;return!0}function Zt(t){return zt&&typeof t==="object"&&typeof t.arrayBuffer==="function"&&typeof t.type==="string"&&typeof t.stream==="function"&&(t[Symbol.toStringTag]==="Blob"||t[Symbol.toStringTag]==="File")}oe.exports={isBlob:Zt,isValidStatusCode:Yt,isValidUTF8:Se,tokenChars:Ht};if(Ze)oe.exports.isValidUTF8=function(t){return t.length<24?Se(t):Ze(t)};else if(!process.env.WS_NO_UTF_8_VALIDATE)try{let t=(()=>{throw new Error("Cannot require module "+"utf-8-validate");})();oe.exports.isValidUTF8=function(s){return s.length<32?Se(s):t(s)}}catch(t){}});var Te=e(function(pr,et){var{Writable:Kt}=u("stream"),Ke=q(),{BINARY_TYPES:Xt,EMPTY_BUFFER:Xe,kStatusCode:Qt,kWebSocket:Jt}=b(),{concat:ve,toArrayBuffer:es,unmask:ts}=K(),{isValidStatusCode:ss,isValidUTF8:Qe}=V(),ae=Buffer[Symbol.species];class Je extends Kt{constructor(t={}){super();this._allowSynchronousEvents=t.allowSynchronousEvents!==void 0?t.allowSynchronousEvents:!0,this._binaryType=t.binaryType||Xt[0],this._extensions=t.extensions||{},this._isServer=!!t.isServer,this._maxBufferedChunks=t.maxBufferedChunks|0,this._maxFragments=t.maxFragments|0,this._maxPayload=t.maxPayload|0,this._skipUTF8Validation=!!t.skipUTF8Validation,this[Jt]=void 0,this._bufferedBytes=0,this._buffers=[],this._compressed=!1,this._payloadLength=0,this._mask=void 0,this._fragmented=0,this._masked=!1,this._fin=!1,this._opcode=0,this._totalPayloadLength=0,this._messageLength=0,this._numFragments=0,this._fragments=[],this._errored=!1,this._loop=!1,this._state=0}_write(t,s,r){if(this._opcode===8&&this._state==0)return r();if(this._maxBufferedChunks>0&&this._buffers.length>=this._maxBufferedChunks){r(this.createError(RangeError,"Too many buffered chunks",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS"));return}this._bufferedBytes+=t.length,this._buffers.push(t),this.startLoop(r)}consume(t){if(this._bufferedBytes-=t,t===this._buffers[0].length)return this._buffers.shift();if(t<this._buffers[0].length){let r=this._buffers[0];return this._buffers[0]=new ae(r.buffer,r.byteOffset+t,r.length-t),new ae(r.buffer,r.byteOffset,t)}let s=Buffer.allocUnsafe(t);do{let r=this._buffers[0],i=s.length-t;if(t>=r.length)s.set(this._buffers.shift(),i);else s.set(new Uint8Array(r.buffer,r.byteOffset,t),i),this._buffers[0]=new ae(r.buffer,r.byteOffset+t,r.length-t);t-=r.length}while(t>0);return s}startLoop(t){this._loop=!0;do switch(this._state){case 0:this.getInfo(t);break;case 1:this.getPayloadLength16(t);break;case 2:this.getPayloadLength64(t);break;case 3:this.getMask();break;case 4:this.getData(t);break;case 5:case 6:this._loop=!1;return}while(this._loop);if(!this._errored)t()}getInfo(t){if(this._bufferedBytes<2){this._loop=!1;return}let s=this.consume(2);if((s[0]&48)!==0){let i=this.createError(RangeError,"RSV2 and RSV3 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_2_3");t(i);return}let r=(s[0]&64)===64;if(r&&!this._extensions[Ke.extensionName]){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(i);return}if(this._fin=(s[0]&128)===128,this._opcode=s[0]&15,this._payloadLength=s[1]&127,this._opcode===0){if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(i);return}if(!this._fragmented){let i=this.createError(RangeError,"invalid opcode 0",!0,1002,"WS_ERR_INVALID_OPCODE");t(i);return}this._opcode=this._fragmented}else if(this._opcode===1||this._opcode===2){if(this._fragmented){let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(i);return}this._compressed=r}else if(this._opcode>7&&this._opcode<11){if(!this._fin){let i=this.createError(RangeError,"FIN must be set",!0,1002,"WS_ERR_EXPECTED_FIN");t(i);return}if(r){let i=this.createError(RangeError,"RSV1 must be clear",!0,1002,"WS_ERR_UNEXPECTED_RSV_1");t(i);return}if(this._payloadLength>125||this._opcode===8&&this._payloadLength===1){let i=this.createError(RangeError,`invalid payload length ${this._payloadLength}`,!0,1002,"WS_ERR_INVALID_CONTROL_PAYLOAD_LENGTH");t(i);return}}else{let i=this.createError(RangeError,`invalid opcode ${this._opcode}`,!0,1002,"WS_ERR_INVALID_OPCODE");t(i);return}if(!this._fin&&!this._fragmented)this._fragmented=this._opcode;if(this._masked=(s[1]&128)===128,this._isServer){if(!this._masked){let i=this.createError(RangeError,"MASK must be set",!0,1002,"WS_ERR_EXPECTED_MASK");t(i);return}}else if(this._masked){let i=this.createError(RangeError,"MASK must be clear",!0,1002,"WS_ERR_UNEXPECTED_MASK");t(i);return}if(this._payloadLength===126)this._state=1;else if(this._payloadLength===127)this._state=2;else this.haveLength(t)}getPayloadLength16(t){if(this._bufferedBytes<2){this._loop=!1;return}this._payloadLength=this.consume(2).readUInt16BE(0),this.haveLength(t)}getPayloadLength64(t){if(this._bufferedBytes<8){this._loop=!1;return}let s=this.consume(8),r=s.readUInt32BE(0);if(r>Math.pow(2,21)-1){let i=this.createError(RangeError,"Unsupported WebSocket frame: payload length > 2^53 - 1",!1,1009,"WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH");t(i);return}this._payloadLength=r*Math.pow(2,32)+s.readUInt32BE(4),this.haveLength(t)}haveLength(t){if(this._payloadLength&&this._opcode<8){if(this._totalPayloadLength+=this._payloadLength,this._totalPayloadLength>this._maxPayload&&this._maxPayload>0){let s=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");t(s);return}}if(this._masked)this._state=3;else this._state=4}getMask(){if(this._bufferedBytes<4){this._loop=!1;return}this._mask=this.consume(4),this._state=4}getData(t){let s=Xe;if(this._payloadLength){if(this._bufferedBytes<this._payloadLength){this._loop=!1;return}if(s=this.consume(this._payloadLength),this._masked&&(this._mask[0]|this._mask[1]|this._mask[2]|this._mask[3])!==0)ts(s,this._mask)}if(this._opcode>7){this.controlMessage(s,t);return}if(this._maxFragments>0&&++this._numFragments>this._maxFragments){let r=this.createError(RangeError,"Too many message fragments",!1,1008,"WS_ERR_TOO_MANY_BUFFERED_PARTS");t(r);return}if(this._compressed){this._state=5,this.decompress(s,t);return}if(s.length)this._messageLength=this._totalPayloadLength,this._fragments.push(s);this.dataMessage(t)}decompress(t,s){this._extensions[Ke.extensionName].decompress(t,this._fin,(i,n)=>{if(i)return s(i);if(n.length){if(this._messageLength+=n.length,this._messageLength>this._maxPayload&&this._maxPayload>0){let o=this.createError(RangeError,"Max payload size exceeded",!1,1009,"WS_ERR_UNSUPPORTED_MESSAGE_LENGTH");s(o);return}this._fragments.push(n)}if(this.dataMessage(s),this._state===0)this.startLoop(s)})}dataMessage(t){if(!this._fin){this._state=0;return}let s=this._messageLength,r=this._fragments;if(this._totalPayloadLength=0,this._messageLength=0,this._fragmented=0,this._numFragments=0,this._fragments=[],this._opcode===2){let i;if(this._binaryType==="nodebuffer")i=ve(r,s);else if(this._binaryType==="arraybuffer")i=es(ve(r,s));else if(this._binaryType==="blob")i=new Blob(r);else i=r;if(this._allowSynchronousEvents)this.emit("message",i,!0),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",i,!0),this._state=0,this.startLoop(t)})}else{let i=ve(r,s);if(!this._skipUTF8Validation&&!Qe(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");t(n);return}if(this._state===5||this._allowSynchronousEvents)this.emit("message",i,!1),this._state=0;else this._state=6,setImmediate(()=>{this.emit("message",i,!1),this._state=0,this.startLoop(t)})}}controlMessage(t,s){if(this._opcode===8){if(t.length===0)this._loop=!1,this.emit("conclude",1005,Xe),this.end();else{let r=t.readUInt16BE(0);if(!ss(r)){let n=this.createError(RangeError,`invalid status code ${r}`,!0,1002,"WS_ERR_INVALID_CLOSE_CODE");s(n);return}let i=new ae(t.buffer,t.byteOffset+2,t.length-2);if(!this._skipUTF8Validation&&!Qe(i)){let n=this.createError(Error,"invalid UTF-8 sequence",!0,1007,"WS_ERR_INVALID_UTF8");s(n);return}this._loop=!1,this.emit("conclude",r,i),this.end()}this._state=0;return}if(this._allowSynchronousEvents)this.emit(this._opcode===9?"ping":"pong",t),this._state=0;else this._state=6,setImmediate(()=>{this.emit(this._opcode===9?"ping":"pong",t),this._state=0,this.startLoop(s)})}createError(t,s,r,i,n){this._loop=!1,this._errored=!0;let o=new t(r?`Invalid WebSocket frame: ${s}`:s);return Error.captureStackTrace(o,this.createError),o.code=n,o[Qt]=i,o}}et.exports=Je});var we=e(function(yr,rt){var{Duplex:gr}=u("stream"),{randomFillSync:rs}=u("crypto"),{types:{isUint8Array:is}}=u("util"),tt=q(),{EMPTY_BUFFER:ns,kWebSocket:os,NOOP:as}=b(),{isBlob:j,isValidStatusCode:fs}=V(),{mask:st,toBuffer:B}=K(),T=Symbol("kByteLength"),ls=Buffer.alloc(4),I,W=8192,O=0,hs=1,cs=2;class P{constructor(t,s,r){if(this._extensions=s||{},r)this._generateMask=r,this._maskBuffer=Buffer.alloc(4);this._socket=t,this._firstFragment=!0,this._compress=!1,this._bufferedBytes=0,this._queue=[],this._state=O,this.onerror=as,this[os]=void 0}static frame(t,s){let r,i=!1,n=2,o=!1;if(s.mask){if(r=s.maskBuffer||ls,s.generateMask)s.generateMask(r);else{if(W===8192){if(I===void 0)I=Buffer.alloc(8192);rs(I,0,8192),W=0}r[0]=I[W++],r[1]=I[W++],r[2]=I[W++],r[3]=I[W++]}o=(r[0]|r[1]|r[2]|r[3])===0,n=6}let a;if(typeof t==="string")if((!s.mask||o)&&s[T]!==void 0)a=s[T];else t=Buffer.from(t),a=t.length;else a=t.length,i=s.mask&&s.readOnly&&!o;let l=a;if(a>=65536)n+=8,l=127;else if(a>125)n+=2,l=126;let f=Buffer.allocUnsafe(i?a+n:n);if(f[0]=s.fin?s.opcode|128:s.opcode,s.rsv1)f[0]|=64;if(f[1]=l,l===126)f.writeUInt16BE(a,2);else if(l===127)f[2]=f[3]=0,f.writeUIntBE(a,4,6);if(!s.mask)return[f,t];if(f[1]|=128,f[n-4]=r[0],f[n-3]=r[1],f[n-2]=r[2],f[n-1]=r[3],o)return[f,t];if(i)return st(t,r,f,n,a),[f];return st(t,r,t,0,a),[f,t]}close(t,s,r,i){let n;if(t===void 0)n=ns;else if(typeof t!=="number"||!fs(t))throw TypeError("First argument must be a valid error code number");else if(s===void 0||!s.length)n=Buffer.allocUnsafe(2),n.writeUInt16BE(t,0);else{let a=Buffer.byteLength(s);if(a>123)throw RangeError("The message must not be greater than 123 bytes");if(n=Buffer.allocUnsafe(2+a),n.writeUInt16BE(t,0),typeof s==="string")n.write(s,2);else if(is(s))n.set(s,2);else throw TypeError("Second argument must be a string or a Uint8Array")}let o={[T]:n.length,fin:!0,generateMask:this._generateMask,mask:r,maskBuffer:this._maskBuffer,opcode:8,readOnly:!1,rsv1:!1};if(this._state!==O)this.enqueue([this.dispatch,n,!1,o,i]);else this.sendFrame(P.frame(n,o),i)}ping(t,s,r){let i,n;if(typeof t==="string")i=Buffer.byteLength(t),n=!1;else if(j(t))i=t.size,n=!1;else t=B(t),i=t.length,n=B.readOnly;if(i>125)throw RangeError("The data size must not be greater than 125 bytes");let o={[T]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:9,readOnly:n,rsv1:!1};if(j(t))if(this._state!==O)this.enqueue([this.getBlobData,t,!1,o,r]);else this.getBlobData(t,!1,o,r);else if(this._state!==O)this.enqueue([this.dispatch,t,!1,o,r]);else this.sendFrame(P.frame(t,o),r)}pong(t,s,r){let i,n;if(typeof t==="string")i=Buffer.byteLength(t),n=!1;else if(j(t))i=t.size,n=!1;else t=B(t),i=t.length,n=B.readOnly;if(i>125)throw RangeError("The data size must not be greater than 125 bytes");let o={[T]:i,fin:!0,generateMask:this._generateMask,mask:s,maskBuffer:this._maskBuffer,opcode:10,readOnly:n,rsv1:!1};if(j(t))if(this._state!==O)this.enqueue([this.getBlobData,t,!1,o,r]);else this.getBlobData(t,!1,o,r);else if(this._state!==O)this.enqueue([this.dispatch,t,!1,o,r]);else this.sendFrame(P.frame(t,o),r)}send(t,s,r){let i=this._extensions[tt.extensionName],n=s.binary?2:1,o=s.compress,a,l;if(typeof t==="string")a=Buffer.byteLength(t),l=!1;else if(j(t))a=t.size,l=!1;else t=B(t),a=t.length,l=B.readOnly;if(this._firstFragment){if(this._firstFragment=!1,o&&i&&i.params[i._isServer?"server_no_context_takeover":"client_no_context_takeover"])o=a>=i._threshold;this._compress=o}else o=!1,n=0;if(s.fin)this._firstFragment=!0;let f={[T]:a,fin:s.fin,generateMask:this._generateMask,mask:s.mask,maskBuffer:this._maskBuffer,opcode:n,readOnly:l,rsv1:o};if(j(t))if(this._state!==O)this.enqueue([this.getBlobData,t,this._compress,f,r]);else this.getBlobData(t,this._compress,f,r);else if(this._state!==O)this.enqueue([this.dispatch,t,this._compress,f,r]);else this.dispatch(t,this._compress,f,r)}getBlobData(t,s,r,i){this._bufferedBytes+=r[T],this._state=cs,t.arrayBuffer().then((n)=>{if(this._socket.destroyed){let a=Error("The socket was closed while the blob was being read");process.nextTick(Oe,this,a,i);return}this._bufferedBytes-=r[T];let o=B(n);if(!s)this._state=O,this.sendFrame(P.frame(o,r),i),this.dequeue();else this.dispatch(o,s,r,i)}).catch((n)=>{process.nextTick(us,this,n,i)})}dispatch(t,s,r,i){if(!s){this.sendFrame(P.frame(t,r),i);return}let n=this._extensions[tt.extensionName];this._bufferedBytes+=r[T],this._state=hs,n.compress(t,r.fin,(o,a)=>{if(this._socket.destroyed){let l=Error("The socket was closed while data was being compressed");Oe(this,l,i);return}this._bufferedBytes-=r[T],this._state=O,r.readOnly=!1,this.sendFrame(P.frame(a,r),i),this.dequeue()})}dequeue(){while(this._state===O&&this._queue.length){let t=this._queue.shift();this._bufferedBytes-=t[3][T],Reflect.apply(t[0],this,t.slice(1))}}enqueue(t){this._bufferedBytes+=t[3][T],this._queue.push(t)}sendFrame(t,s){if(t.length===2)this._socket.cork(),this._socket.write(t[0]),this._socket.write(t[1],s),this._socket.uncork();else this._socket.write(t[0],s)}}rt.exports=P;function Oe(t,s,r){if(typeof r==="function")r(s);for(let i=0;i<t._queue.length;i++){let n=t._queue[i],o=n[n.length-1];if(typeof o==="function")o(s)}}function us(t,s,r){Oe(t,s,r),t.onerror(s)}});var ut=e(function(xr,ct){var{kForOnEventAttribute:Q,kListener:be}=b(),it=Symbol("kCode"),nt=Symbol("kData"),ot=Symbol("kError"),at=Symbol("kMessage"),ft=Symbol("kReason"),z=Symbol("kTarget"),lt=Symbol("kType"),ht=Symbol("kWasClean");class k{constructor(t){this[z]=null,this[lt]=t}get target(){return this[z]}get type(){return this[lt]}}Object.defineProperty(k.prototype,"target",{enumerable:!0});Object.defineProperty(k.prototype,"type",{enumerable:!0});class H extends k{constructor(t,s={}){super(t);this[it]=s.code===void 0?0:s.code,this[ft]=s.reason===void 0?"":s.reason,this[ht]=s.wasClean===void 0?!1:s.wasClean}get code(){return this[it]}get reason(){return this[ft]}get wasClean(){return this[ht]}}Object.defineProperty(H.prototype,"code",{enumerable:!0});Object.defineProperty(H.prototype,"reason",{enumerable:!0});Object.defineProperty(H.prototype,"wasClean",{enumerable:!0});class J extends k{constructor(t,s={}){super(t);this[ot]=s.error===void 0?null:s.error,this[at]=s.message===void 0?"":s.message}get error(){return this[ot]}get message(){return this[at]}}Object.defineProperty(J.prototype,"error",{enumerable:!0});Object.defineProperty(J.prototype,"message",{enumerable:!0});class le extends k{constructor(t,s={}){super(t);this[nt]=s.data===void 0?null:s.data}get data(){return this[nt]}}Object.defineProperty(le.prototype,"data",{enumerable:!0});var _s={addEventListener(t,s,r={}){for(let n of this.listeners(t))if(!r[Q]&&n[be]===s&&!n[Q])return;let i;if(t==="message")i=function(o,a){let l=new le("message",{data:a?o:o.toString()});l[z]=this,fe(s,this,l)};else if(t==="close")i=function(o,a){let l=new H("close",{code:o,reason:a.toString(),wasClean:this._closeFrameReceived&&this._closeFrameSent});l[z]=this,fe(s,this,l)};else if(t==="error")i=function(o){let a=new J("error",{error:o,message:o.message});a[z]=this,fe(s,this,a)};else if(t==="open")i=function(){let o=new k("open");o[z]=this,fe(s,this,o)};else return;if(i[Q]=!!r[Q],i[be]=s,r.once)this.once(t,i);else this.on(t,i)},removeEventListener(t,s){for(let r of this.listeners(t))if(r[be]===s&&!r[Q]){this.removeListener(t,r);break}}};ct.exports={CloseEvent:H,ErrorEvent:J,Event:k,EventTarget:_s,MessageEvent:le};function fe(t,s,r){if(typeof t==="object"&&t.handleEvent)t.handleEvent.call(t,r);else t.call(s,r)}});var he=e(function(Er,_t){var{tokenChars:ee}=V();function w(t,s,r){if(t[s]===void 0)t[s]=[r];else t[s].push(r)}function ds(t){let s=Object.create(null),r=Object.create(null),i=!1,n=!1,o=!1,a,l,f=-1,_=-1,d=-1,c=0;for(;c<t.length;c++)if(_=t.charCodeAt(c),a===void 0)if(d===-1&&ee[_]===1){if(f===-1)f=c}else if(c!==0&&(_===32||_===9)){if(d===-1&&f!==-1)d=c}else if(_===59||_===44){if(f===-1)throw SyntaxError(`Unexpected character at index ${c}`);if(d===-1)d=c;let E=t.slice(f,d);if(_===44)w(s,E,r),r=Object.create(null);else a=E;f=d=-1}else throw SyntaxError(`Unexpected character at index ${c}`);else if(l===void 0)if(d===-1&&ee[_]===1){if(f===-1)f=c}else if(_===32||_===9){if(d===-1&&f!==-1)d=c}else if(_===59||_===44){if(f===-1)throw SyntaxError(`Unexpected character at index ${c}`);if(d===-1)d=c;if(w(r,t.slice(f,d),!0),_===44)w(s,a,r),r=Object.create(null),a=void 0;f=d=-1}else if(_===61&&f!==-1&&d===-1)l=t.slice(f,c),f=d=-1;else throw SyntaxError(`Unexpected character at index ${c}`);else if(n){if(ee[_]!==1)throw SyntaxError(`Unexpected character at index ${c}`);if(f===-1)f=c;else if(!i)i=!0;n=!1}else if(o)if(ee[_]===1){if(f===-1)f=c}else if(_===34&&f!==-1)o=!1,d=c;else if(_===92)n=!0;else throw SyntaxError(`Unexpected character at index ${c}`);else if(_===34&&t.charCodeAt(c-1)===61)o=!0;else if(d===-1&&ee[_]===1){if(f===-1)f=c}else if(f!==-1&&(_===32||_===9)){if(d===-1)d=c}else if(_===59||_===44){if(f===-1)throw SyntaxError(`Unexpected character at index ${c}`);if(d===-1)d=c;let E=t.slice(f,d);if(i)E=E.replace(/\\/g,""),i=!1;if(w(r,l,E),_===44)w(s,a,r),r=Object.create(null),a=void 0;l=void 0,f=d=-1}else throw SyntaxError(`Unexpected character at index ${c}`);if(f===-1||o||_===32||_===9)throw SyntaxError("Unexpected end of input");if(d===-1)d=c;let x=t.slice(f,d);if(a===void 0)w(s,x,r);else{if(l===void 0)w(r,x,!0);else if(i)w(r,l,x.replace(/\\/g,""));else w(r,l,x);w(s,a,r)}return s}function ms(t){return Object.keys(t).map((s)=>{let r=t[s];if(!Array.isArray(r))r=[r];return r.map((i)=>[s].concat(Object.keys(i).map((n)=>{let o=i[n];if(!Array.isArray(o))o=[o];return o.map((a)=>a===!0?n:`${n}=${a}`).join("; ")})).join("; ")).join(", ")}).join(", ")}_t.exports={format:ms,parse:ds}});var de=e(function(Tr,wt){var ps=u("events"),gs=u("https"),xs=u("http"),pt=u("net"),Es=u("tls"),{randomBytes:Ss,createHash:vs}=u("crypto"),{Duplex:Sr,Readable:vr}=u("stream"),{URL:Ne}=u("url"),D=q(),Ts=Te(),Os=we(),{isBlob:ws}=V(),{BINARY_TYPES:dt,CLOSE_TIMEOUT:bs,EMPTY_BUFFER:ce,GUID:Ns,kForOnEventAttribute:Ce,kListener:Cs,kStatusCode:Ls,kWebSocket:y,NOOP:gt}=b(),{EventTarget:{addEventListener:Ps,removeEventListener:ks}}=ut(),{format:Ds,parse:Bs}=he(),{toBuffer:Is}=K(),yt=Symbol("kAborted"),Le=[8,13],C=["CONNECTING","OPEN","CLOSING","CLOSED"],Rs=/^[!#$%&'*+\-.0-9A-Z^_`|a-z~]+$/;class h extends ps{constructor(t,s,r){super();if(this._binaryType=dt[0],this._closeCode=1006,this._closeFrameReceived=!1,this._closeFrameSent=!1,this._closeMessage=ce,this._closeTimer=null,this._errorEmitted=!1,this._extensions={},this._paused=!1,this._protocol="",this._readyState=h.CONNECTING,this._receiver=null,this._sender=null,this._socket=null,t!==null){if(this._bufferedAmount=0,this._isServer=!1,this._redirects=0,s===void 0)s=[];else if(!Array.isArray(s))if(typeof s==="object"&&s!==null)r=s,s=[];else s=[s];xt(this,t,s,r)}else this._autoPong=r.autoPong,this._closeTimeout=r.closeTimeout,this._isServer=!0}get binaryType(){return this._binaryType}set binaryType(t){if(!dt.includes(t))return;if(this._binaryType=t,this._receiver)this._receiver._binaryType=t}get bufferedAmount(){if(!this._socket)return this._bufferedAmount;return this._socket._writableState.length+this._sender._bufferedBytes}get extensions(){return Object.keys(this._extensions).join()}get isPaused(){return this._paused}get onclose(){return null}get onerror(){return null}get onopen(){return null}get onmessage(){return null}get protocol(){return this._protocol}get readyState(){return this._readyState}get url(){return this._url}setSocket(t,s,r){let i=new Ts({allowSynchronousEvents:r.allowSynchronousEvents,binaryType:this.binaryType,extensions:this._extensions,isServer:this._isServer,maxBufferedChunks:r.maxBufferedChunks,maxFragments:r.maxFragments,maxPayload:r.maxPayload,skipUTF8Validation:r.skipUTF8Validation}),n=new Os(t,this._extensions,r.generateMask);if(this._receiver=i,this._sender=n,this._socket=t,i[y]=this,n[y]=this,t[y]=this,i.on("conclude",As),i.on("drain",Fs),i.on("error",Gs),i.on("message",qs),i.on("ping",$s),i.on("pong",Vs),n.onerror=js,t.setTimeout)t.setTimeout(0);if(t.setNoDelay)t.setNoDelay();if(s.length>0)t.unshift(s);t.on("close",vt),t.on("data",_e),t.on("end",Tt),t.on("error",Ot),this._readyState=h.OPEN,this.emit("open")}emitClose(){if(!this._socket){this._readyState=h.CLOSED,this.emit("close",this._closeCode,this._closeMessage);return}if(this._extensions[D.extensionName])this._extensions[D.extensionName].cleanup();this._receiver.removeAllListeners(),this._readyState=h.CLOSED,this.emit("close",this._closeCode,this._closeMessage)}close(t,s){if(this.readyState===h.CLOSED)return;if(this.readyState===h.CONNECTING){v(this,this._req,"WebSocket was closed before the connection was established");return}if(this.readyState===h.CLOSING){if(this._closeFrameSent&&(this._closeFrameReceived||this._receiver._writableState.errorEmitted))this._socket.end();return}this._readyState=h.CLOSING,this._sender.close(t,s,!this._isServer,(r)=>{if(r)return;if(this._closeFrameSent=!0,this._closeFrameReceived||this._receiver._writableState.errorEmitted)this._socket.end()}),St(this)}pause(){if(this.readyState===h.CONNECTING||this.readyState===h.CLOSED)return;this._paused=!0,this._socket.pause()}ping(t,s,r){if(this.readyState===h.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t==="function")r=t,t=s=void 0;else if(typeof s==="function")r=s,s=void 0;if(typeof t==="number")t=t.toString();if(this.readyState!==h.OPEN){Pe(this,t,r);return}if(s===void 0)s=!this._isServer;this._sender.ping(t||ce,s,r)}pong(t,s,r){if(this.readyState===h.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof t==="function")r=t,t=s=void 0;else if(typeof s==="function")r=s,s=void 0;if(typeof t==="number")t=t.toString();if(this.readyState!==h.OPEN){Pe(this,t,r);return}if(s===void 0)s=!this._isServer;this._sender.pong(t||ce,s,r)}resume(){if(this.readyState===h.CONNECTING||this.readyState===h.CLOSED)return;if(this._paused=!1,!this._receiver._writableState.needDrain)this._socket.resume()}send(t,s,r){if(this.readyState===h.CONNECTING)throw Error("WebSocket is not open: readyState 0 (CONNECTING)");if(typeof s==="function")r=s,s={};if(typeof t==="number")t=t.toString();if(this.readyState!==h.OPEN){Pe(this,t,r);return}let i={binary:typeof t!=="string",mask:!this._isServer,compress:!0,fin:!0,...s};if(!this._extensions[D.extensionName])i.compress=!1;this._sender.send(t||ce,i,r)}terminate(){if(this.readyState===h.CLOSED)return;if(this.readyState===h.CONNECTING){v(this,this._req,"WebSocket was closed before the connection was established");return}if(this._socket)this._readyState=h.CLOSING,this._socket.destroy()}}Object.defineProperty(h,"CONNECTING",{enumerable:!0,value:C.indexOf("CONNECTING")});Object.defineProperty(h.prototype,"CONNECTING",{enumerable:!0,value:C.indexOf("CONNECTING")});Object.defineProperty(h,"OPEN",{enumerable:!0,value:C.indexOf("OPEN")});Object.defineProperty(h.prototype,"OPEN",{enumerable:!0,value:C.indexOf("OPEN")});Object.defineProperty(h,"CLOSING",{enumerable:!0,value:C.indexOf("CLOSING")});Object.defineProperty(h.prototype,"CLOSING",{enumerable:!0,value:C.indexOf("CLOSING")});Object.defineProperty(h,"CLOSED",{enumerable:!0,value:C.indexOf("CLOSED")});Object.defineProperty(h.prototype,"CLOSED",{enumerable:!0,value:C.indexOf("CLOSED")});["binaryType","bufferedAmount","extensions","isPaused","protocol","readyState","url"].forEach((t)=>{Object.defineProperty(h.prototype,t,{enumerable:!0})});["open","error","close","message"].forEach((t)=>{Object.defineProperty(h.prototype,`on${t}`,{enumerable:!0,get(){for(let s of this.listeners(t))if(s[Ce])return s[Cs];return null},set(s){for(let r of this.listeners(t))if(r[Ce]){this.removeListener(t,r);break}if(typeof s!=="function")return;this.addEventListener(t,s,{[Ce]:!0})}})});h.prototype.addEventListener=Ps;h.prototype.removeEventListener=ks;wt.exports=h;function xt(t,s,r,i){let n={allowSynchronousEvents:!0,autoPong:!0,closeTimeout:bs,protocolVersion:Le[1],maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!0,followRedirects:!1,maxRedirects:10,...i,socketPath:void 0,hostname:void 0,protocol:void 0,timeout:void 0,method:"GET",host:void 0,path:void 0,port:void 0};if(t._autoPong=n.autoPong,t._closeTimeout=n.closeTimeout,!Le.includes(n.protocolVersion))throw RangeError(`Unsupported protocol version: ${n.protocolVersion} (supported versions: ${Le.join(", ")})`);let o;if(s instanceof Ne)o=s;else try{o=new Ne(s)}catch{throw SyntaxError(`Invalid URL: ${s}`)}if(o.protocol==="http:")o.protocol="ws:";else if(o.protocol==="https:")o.protocol="wss:";t._url=o.href;let a=o.protocol==="wss:",l=o.protocol==="ws+unix:",f;if(o.protocol!=="ws:"&&!a&&!l)f=`The URL's protocol must be one of "ws:", "wss:", "http:", "https:", or "ws+unix:"`;else if(l&&!o.pathname)f="The URL's pathname is empty";else if(o.hash)f="The URL contains a fragment identifier";if(f){let m=SyntaxError(f);if(t._redirects===0)throw m;else{ue(t,m);return}}let _=a?443:80,d=Ss(16).toString("base64"),c=a?gs.request:xs.request,x=new Set,E;if(n.createConnection=n.createConnection||(a?Ms:Us),n.defaultPort=n.defaultPort||_,n.port=o.port||_,n.host=o.hostname.startsWith("[")?o.hostname.slice(1,-1):o.hostname,n.headers={...n.headers,"Sec-WebSocket-Version":n.protocolVersion,"Sec-WebSocket-Key":d,Connection:"Upgrade",Upgrade:"websocket"},n.path=o.pathname+o.search,n.timeout=n.handshakeTimeout,n.perMessageDeflate)E=new D({...n.perMessageDeflate,isServer:!1,maxPayload:n.maxPayload}),n.headers["Sec-WebSocket-Extensions"]=Ds({[D.extensionName]:E.offer()});if(r.length){for(let m of r){if(typeof m!=="string"||!Rs.test(m)||x.has(m))throw SyntaxError("An invalid or duplicated subprotocol was specified");x.add(m)}n.headers["Sec-WebSocket-Protocol"]=r.join(",")}if(n.origin)if(n.protocolVersion<13)n.headers["Sec-WebSocket-Origin"]=n.origin;else n.headers.Origin=n.origin;if(o.username||o.password)n.auth=`${o.username}:${o.password}`;if(l){let m=n.path.split(":");n.socketPath=m[0],n.path=m[1]}let p;if(n.followRedirects){if(t._redirects===0){t._originalIpc=l,t._originalSecure=a,t._originalHostOrSocketPath=l?n.socketPath:o.host;let m=i&&i.headers;if(i={...i,headers:{}},m)for(let[S,M]of Object.entries(m))i.headers[S.toLowerCase()]=M}else if(t.listenerCount("redirect")===0){let m=l?t._originalIpc?n.socketPath===t._originalHostOrSocketPath:!1:t._originalIpc?!1:o.host===t._originalHostOrSocketPath;if(!m||t._originalSecure&&!a){if(delete n.headers.authorization,delete n.headers.cookie,!m)delete n.headers.host;n.auth=void 0}}if(n.auth&&!i.headers.authorization)i.headers.authorization="Basic "+Buffer.from(n.auth).toString("base64");if(p=t._req=c(n),t._redirects)t.emit("redirect",t.url,p)}else p=t._req=c(n);if(n.timeout)p.on("timeout",()=>{v(t,p,"Opening handshake has timed out")});if(p.on("error",(m)=>{if(p===null||p[yt])return;p=t._req=null,ue(t,m)}),p.on("response",(m)=>{let S=m.headers.location,M=m.statusCode;if(S&&n.followRedirects&&M>=300&&M<400){if(++t._redirects>n.maxRedirects){v(t,p,"Maximum redirects exceeded");return}p.abort();let Y;try{Y=new Ne(S,s)}catch(De){let A=SyntaxError(`Invalid URL: ${S}`);ue(t,A);return}xt(t,Y,r,i)}else if(!t.emit("unexpected-response",p,m))v(t,p,`Unexpected server response: ${m.statusCode}`)}),p.on("upgrade",(m,S,M)=>{if(t.emit("upgrade",m),t.readyState!==h.CONNECTING)return;p=t._req=null;let Y=m.headers.upgrade;if(Y===void 0||Y.toLowerCase()!=="websocket"){v(t,S,"Invalid Upgrade header");return}let De=vs("sha1").update(d+Ns).digest("base64");if(m.headers["sec-websocket-accept"]!==De){v(t,S,"Invalid Sec-WebSocket-Accept header");return}let A=m.headers["sec-websocket-protocol"],Z;if(A!==void 0){if(!x.size)Z="Server sent a subprotocol but none was requested";else if(!x.has(A))Z="Server sent an invalid subprotocol"}else if(x.size)Z="Server sent no subprotocol";if(Z){v(t,S,Z);return}if(A)t._protocol=A;let Be=m.headers["sec-websocket-extensions"];if(Be!==void 0){if(!E){v(t,S,"Server sent a Sec-WebSocket-Extensions header but no extension was requested");return}let pe;try{pe=Bs(Be)}catch(ge){v(t,S,"Invalid Sec-WebSocket-Extensions header");return}let Ie=Object.keys(pe);if(Ie.length!==1||Ie[0]!==D.extensionName){v(t,S,"Server indicated an extension that was not requested");return}try{E.accept(pe[D.extensionName])}catch(ge){v(t,S,"Invalid Sec-WebSocket-Extensions header");return}t._extensions[D.extensionName]=E}t.setSocket(S,M,{allowSynchronousEvents:n.allowSynchronousEvents,generateMask:n.generateMask,maxBufferedChunks:n.maxBufferedChunks,maxFragments:n.maxFragments,maxPayload:n.maxPayload,skipUTF8Validation:n.skipUTF8Validation})}),n.finishRequest)n.finishRequest(p,t);else p.end()}function ue(t,s){t._readyState=h.CLOSING,t._errorEmitted=!0,t.emit("error",s),t.emitClose()}function Us(t){return t.path=t.socketPath,pt.connect(t)}function Ms(t){if(t.path=void 0,!t.servername&&t.servername!=="")t.servername=pt.isIP(t.host)?"":t.host;return Es.connect(t)}function v(t,s,r){t._readyState=h.CLOSING;let i=Error(r);if(Error.captureStackTrace(i,v),s.setHeader){if(s[yt]=!0,s.abort(),s.socket&&!s.socket.destroyed)s.socket.destroy();process.nextTick(ue,t,i)}else s.destroy(i),s.once("error",t.emit.bind(t,"error")),s.once("close",t.emitClose.bind(t))}function Pe(t,s,r){if(s){let i=ws(s)?s.size:Is(s).length;if(t._socket)t._sender._bufferedBytes+=i;else t._bufferedAmount+=i}if(r){let i=Error(`WebSocket is not open: readyState ${t.readyState} (${C[t.readyState]})`);process.nextTick(r,i)}}function As(t,s){let r=this[y];if(r._closeFrameReceived=!0,r._closeMessage=s,r._closeCode=t,r._socket[y]===void 0)return;if(r._socket.removeListener("data",_e),process.nextTick(Et,r._socket),t===1005)r.close();else r.close(t,s)}function Fs(){let t=this[y];if(!t.isPaused)t._socket.resume()}function Gs(t){let s=this[y];if(s._socket[y]!==void 0)s._socket.removeListener("data",_e),process.nextTick(Et,s._socket),s.close(t[Ls]);if(!s._errorEmitted)s._errorEmitted=!0,s.emit("error",t)}function mt(){this[y].emitClose()}function qs(t,s){this[y].emit("message",t,s)}function $s(t){let s=this[y];if(s._autoPong)s.pong(t,!this._isServer,gt);s.emit("ping",t)}function Vs(t){this[y].emit("pong",t)}function Et(t){t.resume()}function js(t){let s=this[y];if(s.readyState===h.CLOSED)return;if(s.readyState===h.OPEN)s._readyState=h.CLOSING,St(s);if(this._socket.end(),!s._errorEmitted)s._errorEmitted=!0,s.emit("error",t)}function St(t){t._closeTimer=setTimeout(t._socket.destroy.bind(t._socket),t._closeTimeout)}function vt(){let t=this[y];if(this.removeListener("close",vt),this.removeListener("data",_e),this.removeListener("end",Tt),t._readyState=h.CLOSING,!this._readableState.endEmitted&&!t._closeFrameReceived&&!t._receiver._writableState.errorEmitted&&this._readableState.length!==0){let s=this.read(this._readableState.length);t._receiver.write(s)}if(t._receiver.end(),this[y]=void 0,clearTimeout(t._closeTimer),t._receiver._writableState.finished||t._receiver._writableState.errorEmitted)t.emitClose();else t._receiver.on("error",mt),t._receiver.on("finish",mt)}function _e(t){if(!this[y]._receiver.write(t))this.pause()}function Tt(){let t=this[y];t._readyState=h.CLOSING,t._receiver.end(),this.end()}function Ot(){let t=this[y];if(this.removeListener("error",Ot),this.on("error",gt),t)t._readyState=h.CLOSING,this.destroy()}});var Lt=e(function(wr,Ct){var Or=de(),{Duplex:Ws}=u("stream");function bt(t){t.emit("close")}function zs(){if(!this.destroyed&&this._writableState.finished)this.destroy()}function Nt(t){if(this.removeListener("error",Nt),this.destroy(),this.listenerCount("error")===0)this.emit("error",t)}function Hs(t,s){let r=!0,i=new Ws({...s,autoDestroy:!1,emitClose:!1,objectMode:!1,writableObjectMode:!1});return t.on("message",function(o,a){let l=!a&&i._readableState.objectMode?o.toString():o;if(!i.push(l))t.pause()}),t.once("error",function(o){if(i.destroyed)return;r=!1,i.destroy(o)}),t.once("close",function(){if(i.destroyed)return;i.push(null)}),i._destroy=function(n,o){if(t.readyState===t.CLOSED){o(n),process.nextTick(bt,i);return}let a=!1;if(t.once("error",function(f){a=!0,o(f)}),t.once("close",function(){if(!a)o(n);process.nextTick(bt,i)}),r)t.terminate()},i._final=function(n){if(t.readyState===t.CONNECTING){t.once("open",function(){i._final(n)});return}if(t._socket===null)return;if(t._socket._writableState.finished){if(n(),i._readableState.endEmitted)i.destroy()}else t._socket.once("finish",function(){n()}),t.close()},i._read=function(){if(t.isPaused)t.resume()},i._write=function(n,o,a){if(t.readyState===t.CONNECTING){t.once("open",function(){i._write(n,o,a)});return}t.send(n,a)},i.on("end",zs),i.on("error",Nt),i}Ct.exports=Hs});var ke=e(function(br,Pt){var{tokenChars:Ys}=V();function Zs(t){let s=new Set,r=-1,i=-1,n=0;for(n;n<t.length;n++){let a=t.charCodeAt(n);if(i===-1&&Ys[a]===1){if(r===-1)r=n}else if(n!==0&&(a===32||a===9)){if(i===-1&&r!==-1)i=n}else if(a===44){if(r===-1)throw SyntaxError(`Unexpected character at index ${n}`);if(i===-1)i=n;let l=t.slice(r,i);if(s.has(l))throw SyntaxError(`The "${l}" subprotocol is duplicated`);s.add(l),r=i=-1}else throw SyntaxError(`Unexpected character at index ${n}`)}if(r===-1||i!==-1)throw SyntaxError("Unexpected end of input");let o=t.slice(r,n);if(s.has(o))throw SyntaxError(`The "${o}" subprotocol is duplicated`);return s.add(o),s}Pt.exports={parse:Zs}});var Rt=e(function(Cr,It){var Ks=u("events"),me=u("http"),{Duplex:Nr}=u("stream"),{createHash:Xs}=u("crypto"),Dt=he(),R=q(),Qs=ke(),Js=de(),{CLOSE_TIMEOUT:er,GUID:tr,kWebSocket:sr}=b(),rr=/^[+/0-9A-Za-z]{22}==$/;class Bt extends Ks{constructor(t,s){super();if(t={allowSynchronousEvents:!0,autoPong:!0,maxBufferedChunks:262144,maxFragments:16384,maxPayload:104857600,skipUTF8Validation:!1,perMessageDeflate:!1,handleProtocols:null,clientTracking:!0,closeTimeout:er,verifyClient:null,noServer:!1,backlog:null,server:null,host:null,path:null,port:null,WebSocket:Js,...t},t.port==null&&!t.server&&!t.noServer||t.port!=null&&(t.server||t.noServer)||t.server&&t.noServer)throw TypeError('One and only one of the "port", "server", or "noServer" options must be specified');if(t.port!=null)this._server=me.createServer((r,i)=>{let n=me.STATUS_CODES[426];i.writeHead(426,{"Content-Length":n.length,"Content-Type":"text/plain"}),i.end(n)}),this._server.listen(t.port,t.host,t.backlog,s);else if(t.server)this._server=t.server;if(this._server){let r=this.emit.bind(this,"connection");this._removeListeners=ir(this._server,{listening:this.emit.bind(this,"listening"),error:this.emit.bind(this,"error"),upgrade:(i,n,o)=>{this.handleUpgrade(i,n,o,r)}})}if(t.perMessageDeflate===!0)t.perMessageDeflate={};if(t.clientTracking)this.clients=new Set,this._shouldEmitClose=!1;this.options=t,this._state=0}address(){if(this.options.noServer)throw Error('The server is operating in "noServer" mode');if(!this._server)return null;return this._server.address()}close(t){if(this._state===2){if(t)this.once("close",()=>{t(Error("The server is not running"))});process.nextTick(te,this);return}if(t)this.once("close",t);if(this._state===1)return;if(this._state=1,this.options.noServer||this.options.server){if(this._server)this._removeListeners(),this._removeListeners=this._server=null;if(this.clients)if(!this.clients.size)process.nextTick(te,this);else this._shouldEmitClose=!0;else process.nextTick(te,this)}else{let s=this._server;this._removeListeners(),this._removeListeners=this._server=null,s.close(()=>{te(this)})}}shouldHandle(t){if(this.options.path){let s=t.url.indexOf("?");if((s!==-1?t.url.slice(0,s):t.url)!==this.options.path)return!1}return!0}handleUpgrade(t,s,r,i){s.on("error",kt);let n=t.headers["sec-websocket-key"],o=t.headers.upgrade,a=+t.headers["sec-websocket-version"];if(t.method!=="GET"){U(this,t,s,405,"Invalid HTTP method");return}if(o===void 0||o.toLowerCase()!=="websocket"){U(this,t,s,400,"Invalid Upgrade header");return}if(n===void 0||!rr.test(n)){U(this,t,s,400,"Missing or invalid Sec-WebSocket-Key header");return}if(a!==13&&a!==8){U(this,t,s,400,"Missing or invalid Sec-WebSocket-Version header",{"Sec-WebSocket-Version":"13, 8"});return}if(!this.shouldHandle(t)){se(s,400);return}let l=t.headers["sec-websocket-protocol"],f=new Set;if(l!==void 0)try{f=Qs.parse(l)}catch(c){U(this,t,s,400,"Invalid Sec-WebSocket-Protocol header");return}let _=t.headers["sec-websocket-extensions"],d={};if(this.options.perMessageDeflate&&_!==void 0){let c=new R({...this.options.perMessageDeflate,isServer:!0,maxPayload:this.options.maxPayload});try{let x=Dt.parse(_);if(x[R.extensionName])c.accept(x[R.extensionName]),d[R.extensionName]=c}catch(x){U(this,t,s,400,"Invalid or unacceptable Sec-WebSocket-Extensions header");return}}if(this.options.verifyClient){let c={origin:t.headers[`${a===8?"sec-websocket-origin":"origin"}`],secure:!!(t.socket.authorized||t.socket.encrypted),req:t};if(this.options.verifyClient.length===2){this.options.verifyClient(c,(x,E,p,m)=>{if(!x)return se(s,E||401,p,m);this.completeUpgrade(d,n,f,t,s,r,i)});return}if(!this.options.verifyClient(c))return se(s,401)}this.completeUpgrade(d,n,f,t,s,r,i)}completeUpgrade(t,s,r,i,n,o,a){if(!n.readable||!n.writable)return n.destroy();if(n[sr])throw Error("server.handleUpgrade() was called more than once with the same socket, possibly due to a misconfiguration");if(this._state>0)return se(n,503);let f=["HTTP/1.1 101 Switching Protocols","Upgrade: websocket","Connection: Upgrade",`Sec-WebSocket-Accept: ${Xs("sha1").update(s+tr).digest("base64")}`],_=new this.options.WebSocket(null,void 0,this.options);if(r.size){let d=this.options.handleProtocols?this.options.handleProtocols(r,i):r.values().next().value;if(d)f.push(`Sec-WebSocket-Protocol: ${d}`),_._protocol=d}if(t[R.extensionName]){let d=t[R.extensionName].params,c=Dt.format({[R.extensionName]:[d]});f.push(`Sec-WebSocket-Extensions: ${c}`),_._extensions=t}if(this.emit("headers",f,i),n.write(f.concat(`\r
3
+ `).join(`\r
4
+ `)),n.removeListener("error",kt),_.setSocket(n,o,{allowSynchronousEvents:this.options.allowSynchronousEvents,maxBufferedChunks:this.options.maxBufferedChunks,maxFragments:this.options.maxFragments,maxPayload:this.options.maxPayload,skipUTF8Validation:this.options.skipUTF8Validation}),this.clients)this.clients.add(_),_.on("close",()=>{if(this.clients.delete(_),this._shouldEmitClose&&!this.clients.size)process.nextTick(te,this)});a(_,i)}}It.exports=Bt;function ir(t,s){for(let r of Object.keys(s))t.on(r,s[r]);return function(){for(let i of Object.keys(s))t.removeListener(i,s[i])}}function te(t){t._state=2,t.emit("close")}function kt(){this.destroy()}function se(t,s,r,i){r=r||me.STATUS_CODES[s],i={Connection:"close","Content-Type":"text/html","Content-Length":Buffer.byteLength(r),...i},t.once("finish",t.destroy),t.end(`HTTP/1.1 ${s} ${me.STATUS_CODES[s]}\r
5
+ `+Object.keys(i).map((n)=>`${n}: ${i[n]}`).join(`\r
6
+ `)+`\r
7
+ \r
8
+ `+r)}function U(t,s,r,i,n,o){if(t.listenerCount("wsClientError")){let a=Error(n);Error.captureStackTrace(a,U),t.emit("wsClientError",a,r,s)}else se(r,i,n,o)}});var nr=g(Lt(),1),or=g(he(),1),ar=g(q(),1),fr=g(Te(),1),lr=g(we(),1),hr=g(ke(),1),Ut=g(de(),1),ys=g(Rt(),1);var ZA=Ut.default;
9
+ export{ys,ZA};
10
+
11
+ //# debugId=EFDBAA14D18E50D364756E2164756E21
12
+ //# sourceMappingURL=index-m68cd91a.js.map