@humain/humain-code 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (792) hide show
  1. package/CHANGELOG.md +119 -0
  2. package/README.md +23 -6
  3. package/dist/agent-monitor/entry.lazy.d.ts +3 -0
  4. package/dist/agent-monitor/entry.lazy.d.ts.map +1 -0
  5. package/dist/agent-monitor/entry.lazy.js +3 -0
  6. package/dist/agent-monitor/entry.lazy.js.map +1 -0
  7. package/dist/bundle/agent-monitor.js +1 -1
  8. package/dist/bundle/chunks/adaptive-peer-worker-X2ZNZE3S.js +8 -0
  9. package/dist/bundle/chunks/adaptive-session-host-7KDSQV5I.js +162 -0
  10. package/dist/bundle/chunks/anthropic-messages-TQK3FUV3.js +68 -0
  11. package/dist/bundle/chunks/anthropic.js +13 -10
  12. package/dist/bundle/chunks/{azure-openai-responses-IV74M5OR.js → azure-openai-responses-JY7OSLH2.js} +6 -6
  13. package/dist/bundle/chunks/bedrock-converse-stream.js +79 -74
  14. package/dist/bundle/chunks/chunk-2FYYW6FY.js +2 -0
  15. package/dist/bundle/chunks/{chunk-A2VPLMF2.js → chunk-2G7YVAVF.js} +1 -1
  16. package/dist/bundle/chunks/chunk-32QLLD2P.js +1114 -0
  17. package/dist/bundle/chunks/{chunk-3LP543EX.js → chunk-3EDMWQ35.js} +17 -16
  18. package/dist/bundle/chunks/chunk-3HVHETMU.js +18 -0
  19. package/dist/bundle/chunks/{chunk-XMZGB3H4.js → chunk-4HTVBBJD.js} +11 -6
  20. package/dist/bundle/chunks/chunk-4JRER4XK.js +175 -0
  21. package/dist/bundle/chunks/{chunk-FHLLDO7U.js → chunk-4PRNKB6V.js} +5 -5
  22. package/dist/bundle/chunks/chunk-4QAXV5T6.js +49 -0
  23. package/dist/bundle/chunks/{chunk-JCTQQ3DX.js → chunk-4V5VL2BO.js} +1 -1
  24. package/dist/bundle/chunks/chunk-5B25YXF7.js +24 -0
  25. package/dist/bundle/chunks/chunk-5L4PBYC7.js +11 -0
  26. package/dist/bundle/chunks/chunk-66FZJO75.js +5146 -0
  27. package/dist/bundle/chunks/chunk-6P6GJPYB.js +4 -0
  28. package/dist/bundle/chunks/chunk-6PNQYO6A.js +10 -0
  29. package/dist/bundle/chunks/chunk-7NKUVTBL.js +76 -0
  30. package/dist/bundle/chunks/chunk-AEWYICBL.js +89 -0
  31. package/dist/bundle/chunks/chunk-AQ4EXORZ.js +14 -0
  32. package/dist/bundle/chunks/chunk-AZXVJN6E.js +19 -0
  33. package/dist/bundle/chunks/chunk-CRN54O4D.js +24 -0
  34. package/dist/bundle/chunks/chunk-CTU2ECLD.js +7 -0
  35. package/dist/bundle/chunks/{chunk-BQ3TMEWD.js → chunk-EIC7CQX3.js} +4 -3
  36. package/dist/bundle/chunks/chunk-F6ZAYLU2.js +59 -0
  37. package/dist/bundle/chunks/chunk-G4QPSFBF.js +493 -0
  38. package/dist/bundle/chunks/chunk-GME4AWDG.js +23 -0
  39. package/dist/bundle/chunks/{chunk-SFMDIVZ4.js → chunk-GRJUKEE3.js} +43 -30
  40. package/dist/bundle/chunks/chunk-GTILMMUF.js +12 -0
  41. package/dist/bundle/chunks/chunk-GUHNFZ2Q.js +51 -0
  42. package/dist/bundle/chunks/chunk-GY663MNP.js +11 -0
  43. package/dist/bundle/chunks/chunk-HTA325LJ.js +56 -0
  44. package/dist/bundle/chunks/{chunk-5L4JG6PO.js → chunk-I3NDOUHE.js} +8 -7
  45. package/dist/bundle/chunks/chunk-I5E7RQ5V.js +21 -0
  46. package/dist/bundle/chunks/chunk-IWZQ25I3.js +5 -0
  47. package/dist/bundle/chunks/chunk-IYGHKVUG.js +2 -0
  48. package/dist/bundle/chunks/chunk-J57HOSWD.js +21 -0
  49. package/dist/bundle/chunks/chunk-JF7FYXAI.js +288 -0
  50. package/dist/bundle/chunks/chunk-JSZBTGI6.js +10 -0
  51. package/dist/bundle/chunks/chunk-JYWUOKOI.js +1061 -0
  52. package/dist/bundle/chunks/{chunk-DLCBSLHW.js → chunk-KRCX3ZBA.js} +1 -1
  53. package/dist/bundle/chunks/chunk-KTSJYIYC.js +30 -0
  54. package/dist/bundle/chunks/{chunk-K7SDY3VJ.js → chunk-LB4CIS4F.js} +40 -165
  55. package/dist/bundle/chunks/{chunk-NN53K2QQ.js → chunk-LYZ37DJP.js} +2 -14
  56. package/dist/bundle/chunks/chunk-MD7K7RPN.js +20 -0
  57. package/dist/bundle/chunks/chunk-MX4Q4W6H.js +214 -0
  58. package/dist/bundle/chunks/{chunk-6PD3T2EF.js → chunk-N2SNMUD3.js} +1 -1
  59. package/dist/bundle/chunks/chunk-NXA6NEHE.js +54 -0
  60. package/dist/bundle/chunks/chunk-OB332KMV.js +300 -0
  61. package/dist/bundle/chunks/chunk-P6AXBESH.js +1883 -0
  62. package/dist/bundle/chunks/chunk-PPBDDQHP.js +11 -0
  63. package/dist/bundle/chunks/chunk-PWUDFU5V.js +51 -0
  64. package/dist/bundle/chunks/chunk-Q5RKNQ2T.js +73 -0
  65. package/dist/bundle/chunks/chunk-QT6ZHDMP.js +12 -0
  66. package/dist/bundle/chunks/chunk-R5OOX7RW.js +16 -0
  67. package/dist/bundle/chunks/chunk-R6YQR7TZ.js +25 -0
  68. package/dist/bundle/chunks/{chunk-4ZBGTJJM.js → chunk-RNBZBCH2.js} +1 -1
  69. package/dist/bundle/chunks/chunk-RQU722SY.js +1 -0
  70. package/dist/bundle/chunks/{chunk-RGUZULEE.js → chunk-RS6PZK35.js} +71 -72
  71. package/dist/bundle/chunks/{jiti-loader-6P33XTLC.js → chunk-RW7GT7L3.js} +1 -1
  72. package/dist/bundle/chunks/{chunk-PCTLFSQG.js → chunk-SCINMV4X.js} +1 -1
  73. package/dist/bundle/chunks/{chunk-NCC2FAJN.js → chunk-SSRCVJZK.js} +28 -28
  74. package/dist/bundle/chunks/chunk-T5A6T24H.js +93 -0
  75. package/dist/bundle/chunks/chunk-T7BXP46S.js +3367 -0
  76. package/dist/bundle/chunks/chunk-TGDPZCSW.js +9 -0
  77. package/dist/bundle/chunks/{chunk-4J6BGNX2.js → chunk-TWAHPPXN.js} +434 -429
  78. package/dist/bundle/chunks/chunk-UEW6TUSP.js +36 -0
  79. package/dist/bundle/chunks/chunk-UZNIPOGS.js +323 -0
  80. package/dist/bundle/chunks/{chunk-KM4GQ2BU.js → chunk-VFLVWPLZ.js} +5 -6
  81. package/dist/bundle/chunks/chunk-WAPZN4KP.js +74 -0
  82. package/dist/bundle/chunks/chunk-WCFHG6NO.js +16 -0
  83. package/dist/bundle/chunks/chunk-WQ7EJQIT.js +839 -0
  84. package/dist/bundle/chunks/chunk-WQOOJP7U.js +4 -0
  85. package/dist/bundle/chunks/chunk-XHDVDJM7.js +17 -0
  86. package/dist/bundle/chunks/chunk-YPZPCHNV.js +3 -0
  87. package/dist/bundle/chunks/chunk-Z5YLKK3S.js +41 -0
  88. package/dist/bundle/chunks/chunk-ZJUU6WOV.js +2052 -0
  89. package/dist/bundle/chunks/{cli-N7KOVPLB.js → cli-H4LJNE2V.js} +2 -2
  90. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-KRMHG2L3.js → cloudflare-workers-ai-system-one-T5R2RVFQ.js} +1 -1
  91. package/dist/bundle/chunks/codemode-worker.js +2 -0
  92. package/dist/bundle/chunks/compat-ZK2DIW3P.js +15 -0
  93. package/dist/bundle/chunks/dist-EY7YKQHB.js +11 -0
  94. package/dist/bundle/chunks/dist-FMWWM4H7.js +268 -0
  95. package/dist/bundle/chunks/dist-NHQTBDHT.js +1107 -0
  96. package/dist/bundle/chunks/{easter-egg-3d-O2GG2XIG.js → easter-egg-3d-BUEOC3NO.js} +1 -1
  97. package/dist/bundle/chunks/entry-A2CSLKHC.js +323 -0
  98. package/dist/bundle/chunks/entry-AL54ZGYO.js +2 -0
  99. package/dist/bundle/chunks/{execute-LMBACTKA.js → execute-MY5JSEPV.js} +18 -15
  100. package/dist/bundle/chunks/{extract-CXXLVFC5.js → extract-PTGACPGP.js} +3 -3
  101. package/dist/bundle/chunks/flow-implementer-APJFY4YI.js +21 -0
  102. package/dist/bundle/chunks/github-copilot.js +66 -62
  103. package/dist/bundle/chunks/{google-generative-ai-SBL77OXO.js → google-generative-ai-UL7YEQ6J.js} +2 -3
  104. package/dist/bundle/chunks/{google-vertex-NZBNNXMK.js → google-vertex-OTMSPUYH.js} +3 -3
  105. package/dist/bundle/chunks/host-75YAHLDR.js +3 -0
  106. package/dist/bundle/chunks/index.bundle-THL4EUSU.js +390 -0
  107. package/dist/bundle/chunks/inprocess-5NP5VJHZ.js +32 -0
  108. package/dist/bundle/chunks/interactive-mode-IW4PIVAQ.js +5 -0
  109. package/dist/bundle/chunks/jiti-bun-loader-VSLLRCSD.js +3459 -0
  110. package/dist/bundle/chunks/jiti-loader-TMJL6S2D.js +2 -0
  111. package/dist/bundle/chunks/{llama-cpp-classify-PP63BYDF.js → llama-cpp-classify-GJAXULWL.js} +1 -1
  112. package/dist/bundle/chunks/{mistral-conversations-DX4YKJSO.js → mistral-conversations-E72Y6OC3.js} +2 -2
  113. package/dist/bundle/chunks/{node-UGQUSQE6.js → node-ZFIIS5IM.js} +32 -32
  114. package/dist/bundle/chunks/openai-codex-responses-S7CMCAOY.js +101 -0
  115. package/dist/bundle/chunks/openai-completions-2Z57N7PC.js +87 -0
  116. package/dist/bundle/chunks/{openai-decisions-ALJROWBE.js → openai-decisions-JIOJDB4C.js} +1 -1
  117. package/dist/bundle/chunks/openai-responses-5VBZSTHL.js +27 -0
  118. package/dist/bundle/chunks/{openrouter-images-FCJT7C7I.js → openrouter-images-S6O7DBEJ.js} +1 -1
  119. package/dist/bundle/chunks/{pi-messages-NHTQQOPW.js → pi-messages-SMLN5J2W.js} +10 -7
  120. package/dist/bundle/chunks/runtime-OYTWXIUM.js +2 -0
  121. package/dist/bundle/chunks/session-picker-DM6S37IF.js +4 -0
  122. package/dist/bundle/chunks/startup-ui-4GGLWNSU.js +3 -0
  123. package/dist/bundle/chunks/trace-command-YLDYCL55.js +254 -0
  124. package/dist/bundle/chunks/typesafe-system-one-7BEL3H5N.js +3 -0
  125. package/dist/bundle/chunks/virtual-modules-TI3W24YL.js +28 -0
  126. package/dist/bundle/cli-runtime.js +5 -3
  127. package/dist/bundle/flow/agents/orch-implementation-fast.md +4 -4
  128. package/dist/bundle/flow/agents/orch-implementation-strong.md +5 -5
  129. package/dist/bundle/flow/package.json +35 -3
  130. package/dist/bundle/index.js +20 -17
  131. package/dist/bundle/orchestrate/README.md +37 -0
  132. package/dist/bundle/{flow → orchestrate}/agents/orch-qa-agent.md +1 -1
  133. package/dist/bundle/{flow → orchestrate}/agents/orch-worker.md +1 -1
  134. package/dist/bundle/{flow → orchestrate}/agents/orchestrator-lead.md +1 -1
  135. package/dist/bundle/orchestrate/package.json +29 -0
  136. package/dist/bundle/rpc-entry.js +5 -3
  137. package/dist/cli/args.d.ts +6 -0
  138. package/dist/cli/args.d.ts.map +1 -1
  139. package/dist/cli/args.js +69 -2
  140. package/dist/cli/args.js.map +1 -1
  141. package/dist/cli/auth-check.d.ts +3 -2
  142. package/dist/cli/auth-check.d.ts.map +1 -1
  143. package/dist/cli/auth-check.js +4 -3
  144. package/dist/cli/auth-check.js.map +1 -1
  145. package/dist/cli/config-selector.d.ts.map +1 -1
  146. package/dist/cli/config-selector.js +3 -1
  147. package/dist/cli/config-selector.js.map +1 -1
  148. package/dist/cli/file-processor.d.ts +2 -0
  149. package/dist/cli/file-processor.d.ts.map +1 -1
  150. package/dist/cli/file-processor.js +6 -6
  151. package/dist/cli/file-processor.js.map +1 -1
  152. package/dist/cli/metadata-disclosure.d.ts +4 -0
  153. package/dist/cli/metadata-disclosure.d.ts.map +1 -0
  154. package/dist/cli/metadata-disclosure.js +23 -0
  155. package/dist/cli/metadata-disclosure.js.map +1 -0
  156. package/dist/cli/project-trust.d.ts.map +1 -1
  157. package/dist/cli/project-trust.js +4 -1
  158. package/dist/cli/project-trust.js.map +1 -1
  159. package/dist/cli/session-picker.lazy.d.ts +3 -0
  160. package/dist/cli/session-picker.lazy.d.ts.map +1 -0
  161. package/dist/cli/session-picker.lazy.js +3 -0
  162. package/dist/cli/session-picker.lazy.js.map +1 -0
  163. package/dist/cli/startup-ui.d.ts +4 -4
  164. package/dist/cli/startup-ui.d.ts.map +1 -1
  165. package/dist/cli/startup-ui.js +38 -14
  166. package/dist/cli/startup-ui.js.map +1 -1
  167. package/dist/cli/startup-ui.lazy.d.ts +3 -0
  168. package/dist/cli/startup-ui.lazy.d.ts.map +1 -0
  169. package/dist/cli/startup-ui.lazy.js +3 -0
  170. package/dist/cli/startup-ui.lazy.js.map +1 -0
  171. package/dist/cli/trace-command.lazy.d.ts +3 -0
  172. package/dist/cli/trace-command.lazy.d.ts.map +1 -0
  173. package/dist/cli/trace-command.lazy.js +3 -0
  174. package/dist/cli/trace-command.lazy.js.map +1 -0
  175. package/dist/cli.js.map +1 -1
  176. package/dist/coordination/broker/entry.lazy.d.ts +3 -0
  177. package/dist/coordination/broker/entry.lazy.d.ts.map +1 -0
  178. package/dist/coordination/broker/entry.lazy.js +3 -0
  179. package/dist/coordination/broker/entry.lazy.js.map +1 -0
  180. package/dist/core/acceptance-command.d.ts +15 -0
  181. package/dist/core/acceptance-command.d.ts.map +1 -0
  182. package/dist/core/acceptance-command.js +150 -0
  183. package/dist/core/acceptance-command.js.map +1 -0
  184. package/dist/core/acceptance-ledger.d.ts +52 -0
  185. package/dist/core/acceptance-ledger.d.ts.map +1 -0
  186. package/dist/core/acceptance-ledger.js +341 -0
  187. package/dist/core/acceptance-ledger.js.map +1 -0
  188. package/dist/core/admission-types.d.ts +69 -0
  189. package/dist/core/admission-types.js +2 -0
  190. package/dist/core/admission-types.js.map +1 -0
  191. package/dist/core/agent-session-runtime.d.ts +7 -0
  192. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  193. package/dist/core/agent-session-runtime.js +43 -9
  194. package/dist/core/agent-session-runtime.js.map +1 -1
  195. package/dist/core/agent-session-services.d.ts +8 -0
  196. package/dist/core/agent-session-services.d.ts.map +1 -1
  197. package/dist/core/agent-session-services.js +13 -1
  198. package/dist/core/agent-session-services.js.map +1 -1
  199. package/dist/core/agent-session.d.ts +127 -10
  200. package/dist/core/agent-session.d.ts.map +1 -1
  201. package/dist/core/agent-session.js +1390 -145
  202. package/dist/core/agent-session.js.map +1 -1
  203. package/dist/core/anthropic-subscription-usage.d.ts +1 -1
  204. package/dist/core/anthropic-subscription-usage.d.ts.map +1 -1
  205. package/dist/core/anthropic-subscription-usage.js +31 -3
  206. package/dist/core/anthropic-subscription-usage.js.map +1 -1
  207. package/dist/core/auth-storage.d.ts +2 -1
  208. package/dist/core/auth-storage.d.ts.map +1 -1
  209. package/dist/core/auth-storage.js +13 -10
  210. package/dist/core/auth-storage.js.map +1 -1
  211. package/dist/core/auto-session-namer.d.ts.map +1 -1
  212. package/dist/core/auto-session-namer.js +3 -1
  213. package/dist/core/auto-session-namer.js.map +1 -1
  214. package/dist/core/bash-executor.d.ts.map +1 -1
  215. package/dist/core/bash-executor.js +3 -1
  216. package/dist/core/bash-executor.js.map +1 -1
  217. package/dist/core/bug-report-redaction.d.ts +4 -0
  218. package/dist/core/bug-report-redaction.d.ts.map +1 -0
  219. package/dist/core/bug-report-redaction.js +209 -0
  220. package/dist/core/bug-report-redaction.js.map +1 -0
  221. package/dist/core/bug-report.d.ts +26 -6
  222. package/dist/core/bug-report.d.ts.map +1 -1
  223. package/dist/core/bug-report.js +82 -9
  224. package/dist/core/bug-report.js.map +1 -1
  225. package/dist/core/cache-warmer.d.ts.map +1 -1
  226. package/dist/core/cache-warmer.js +5 -0
  227. package/dist/core/cache-warmer.js.map +1 -1
  228. package/dist/core/compaction/compaction.d.ts +6 -0
  229. package/dist/core/compaction/compaction.d.ts.map +1 -1
  230. package/dist/core/compaction/compaction.js +103 -71
  231. package/dist/core/compaction/compaction.js.map +1 -1
  232. package/dist/core/compaction/utils.d.ts.map +1 -1
  233. package/dist/core/compaction/utils.js +2 -1
  234. package/dist/core/compaction/utils.js.map +1 -1
  235. package/dist/core/extensions/jiti-bun-babel.d.ts +4 -0
  236. package/dist/core/extensions/jiti-bun-babel.d.ts.map +1 -0
  237. package/dist/core/extensions/jiti-bun-babel.js +4 -0
  238. package/dist/core/extensions/jiti-bun-babel.js.map +1 -0
  239. package/dist/core/extensions/jiti-bun-loader.d.ts +4 -0
  240. package/dist/core/extensions/jiti-bun-loader.d.ts.map +1 -0
  241. package/dist/core/extensions/jiti-bun-loader.js +13 -0
  242. package/dist/core/extensions/jiti-bun-loader.js.map +1 -0
  243. package/dist/core/extensions/jiti-bun-loader.lazy.d.ts +3 -0
  244. package/dist/core/extensions/jiti-bun-loader.lazy.d.ts.map +1 -0
  245. package/dist/core/extensions/jiti-bun-loader.lazy.js +3 -0
  246. package/dist/core/extensions/jiti-bun-loader.lazy.js.map +1 -0
  247. package/dist/core/extensions/loader.d.ts.map +1 -1
  248. package/dist/core/extensions/loader.js +9 -3
  249. package/dist/core/extensions/loader.js.map +1 -1
  250. package/dist/core/extensions/runner.d.ts.map +1 -1
  251. package/dist/core/extensions/runner.js +4 -0
  252. package/dist/core/extensions/runner.js.map +1 -1
  253. package/dist/core/extensions/types.d.ts +3 -0
  254. package/dist/core/extensions/types.d.ts.map +1 -1
  255. package/dist/core/extensions/types.js.map +1 -1
  256. package/dist/core/flow-implementer.d.ts +25 -0
  257. package/dist/core/flow-implementer.d.ts.map +1 -0
  258. package/dist/core/flow-implementer.js +301 -0
  259. package/dist/core/flow-implementer.js.map +1 -0
  260. package/dist/core/internal-process.d.ts +23 -0
  261. package/dist/core/internal-process.d.ts.map +1 -0
  262. package/dist/core/internal-process.js +88 -0
  263. package/dist/core/internal-process.js.map +1 -0
  264. package/dist/core/keybindings.d.ts +2 -2
  265. package/dist/core/keybindings.js +1 -1
  266. package/dist/core/keybindings.js.map +1 -1
  267. package/dist/core/model-config.d.ts +52 -0
  268. package/dist/core/model-config.d.ts.map +1 -1
  269. package/dist/core/model-config.js +4 -4
  270. package/dist/core/model-config.js.map +1 -1
  271. package/dist/core/model-registry.d.ts +4 -0
  272. package/dist/core/model-registry.d.ts.map +1 -1
  273. package/dist/core/model-registry.js +8 -0
  274. package/dist/core/model-registry.js.map +1 -1
  275. package/dist/core/model-request-admission.d.ts +51 -0
  276. package/dist/core/model-request-admission.d.ts.map +1 -0
  277. package/dist/core/model-request-admission.js +103 -0
  278. package/dist/core/model-request-admission.js.map +1 -0
  279. package/dist/core/model-resolver.d.ts +4 -0
  280. package/dist/core/model-resolver.d.ts.map +1 -1
  281. package/dist/core/model-resolver.js +109 -2
  282. package/dist/core/model-resolver.js.map +1 -1
  283. package/dist/core/model-runtime.d.ts +56 -1
  284. package/dist/core/model-runtime.d.ts.map +1 -1
  285. package/dist/core/model-runtime.js +482 -40
  286. package/dist/core/model-runtime.js.map +1 -1
  287. package/dist/core/model-selection-intent.d.ts +14 -0
  288. package/dist/core/model-selection-intent.d.ts.map +1 -0
  289. package/dist/core/model-selection-intent.js +15 -0
  290. package/dist/core/model-selection-intent.js.map +1 -0
  291. package/dist/core/oauth-account-pool.d.ts +4 -1
  292. package/dist/core/oauth-account-pool.d.ts.map +1 -1
  293. package/dist/core/oauth-account-pool.js +251 -228
  294. package/dist/core/oauth-account-pool.js.map +1 -1
  295. package/dist/core/os-secret-store.d.ts +25 -0
  296. package/dist/core/os-secret-store.d.ts.map +1 -0
  297. package/dist/core/os-secret-store.js +290 -0
  298. package/dist/core/os-secret-store.js.map +1 -0
  299. package/dist/core/output-guard.d.ts.map +1 -1
  300. package/dist/core/output-guard.js +62 -2
  301. package/dist/core/output-guard.js.map +1 -1
  302. package/dist/core/pi-ai-schemas.d.ts +4 -0
  303. package/dist/core/pi-ai-schemas.d.ts.map +1 -1
  304. package/dist/core/private-windows-path.d.ts +4 -0
  305. package/dist/core/private-windows-path.d.ts.map +1 -0
  306. package/dist/core/private-windows-path.js +44 -0
  307. package/dist/core/private-windows-path.js.map +1 -0
  308. package/dist/core/prompt-templates.d.ts.map +1 -1
  309. package/dist/core/prompt-templates.js +18 -2
  310. package/dist/core/prompt-templates.js.map +1 -1
  311. package/dist/core/provider-composer.d.ts.map +1 -1
  312. package/dist/core/provider-composer.js +1 -1
  313. package/dist/core/provider-composer.js.map +1 -1
  314. package/dist/core/resource-loader.d.ts.map +1 -1
  315. package/dist/core/resource-loader.js +6 -2
  316. package/dist/core/resource-loader.js.map +1 -1
  317. package/dist/core/run-outcome.d.ts +40 -0
  318. package/dist/core/run-outcome.d.ts.map +1 -0
  319. package/dist/core/run-outcome.js +91 -0
  320. package/dist/core/run-outcome.js.map +1 -0
  321. package/dist/core/run-preflight.d.ts +5 -0
  322. package/dist/core/run-preflight.d.ts.map +1 -0
  323. package/dist/core/run-preflight.js +96 -0
  324. package/dist/core/run-preflight.js.map +1 -0
  325. package/dist/core/runtime-credentials.d.ts +18 -2
  326. package/dist/core/runtime-credentials.d.ts.map +1 -1
  327. package/dist/core/runtime-credentials.js +65 -9
  328. package/dist/core/runtime-credentials.js.map +1 -1
  329. package/dist/core/sdk.d.ts +19 -3
  330. package/dist/core/sdk.d.ts.map +1 -1
  331. package/dist/core/sdk.js +115 -20
  332. package/dist/core/sdk.js.map +1 -1
  333. package/dist/core/settings-defaults.d.ts +2 -1
  334. package/dist/core/settings-defaults.d.ts.map +1 -1
  335. package/dist/core/settings-defaults.js +2 -1
  336. package/dist/core/settings-defaults.js.map +1 -1
  337. package/dist/core/settings-manager.d.ts +15 -4
  338. package/dist/core/settings-manager.d.ts.map +1 -1
  339. package/dist/core/settings-manager.js +114 -22
  340. package/dist/core/settings-manager.js.map +1 -1
  341. package/dist/core/settings-schema.d.ts +7 -2
  342. package/dist/core/settings-schema.d.ts.map +1 -1
  343. package/dist/core/settings-schema.js +12 -5
  344. package/dist/core/settings-schema.js.map +1 -1
  345. package/dist/core/skills.d.ts.map +1 -1
  346. package/dist/core/skills.js +11 -0
  347. package/dist/core/skills.js.map +1 -1
  348. package/dist/core/system-prompt.d.ts +3 -0
  349. package/dist/core/system-prompt.d.ts.map +1 -1
  350. package/dist/core/system-prompt.js +10 -2
  351. package/dist/core/system-prompt.js.map +1 -1
  352. package/dist/core/tools/bash-jobs.d.ts +109 -0
  353. package/dist/core/tools/bash-jobs.d.ts.map +1 -0
  354. package/dist/core/tools/bash-jobs.js +563 -0
  355. package/dist/core/tools/bash-jobs.js.map +1 -0
  356. package/dist/core/tools/bash.d.ts +68 -6
  357. package/dist/core/tools/bash.d.ts.map +1 -1
  358. package/dist/core/tools/bash.js +350 -37
  359. package/dist/core/tools/bash.js.map +1 -1
  360. package/dist/core/tools/edit-diff.d.ts +11 -1
  361. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  362. package/dist/core/tools/edit-diff.js +89 -20
  363. package/dist/core/tools/edit-diff.js.map +1 -1
  364. package/dist/core/tools/edit.d.ts.map +1 -1
  365. package/dist/core/tools/edit.js +15 -7
  366. package/dist/core/tools/edit.js.map +1 -1
  367. package/dist/core/tools/file-mutation-custody.d.ts +29 -0
  368. package/dist/core/tools/file-mutation-custody.d.ts.map +1 -0
  369. package/dist/core/tools/file-mutation-custody.js +173 -0
  370. package/dist/core/tools/file-mutation-custody.js.map +1 -0
  371. package/dist/core/tools/find.d.ts +6 -0
  372. package/dist/core/tools/find.d.ts.map +1 -1
  373. package/dist/core/tools/find.js +84 -38
  374. package/dist/core/tools/find.js.map +1 -1
  375. package/dist/core/tools/grep.d.ts +8 -2
  376. package/dist/core/tools/grep.d.ts.map +1 -1
  377. package/dist/core/tools/grep.js +121 -77
  378. package/dist/core/tools/grep.js.map +1 -1
  379. package/dist/core/tools/index.d.ts +3 -1
  380. package/dist/core/tools/index.d.ts.map +1 -1
  381. package/dist/core/tools/index.js +12 -0
  382. package/dist/core/tools/index.js.map +1 -1
  383. package/dist/core/tools/jobs.d.ts +24 -0
  384. package/dist/core/tools/jobs.d.ts.map +1 -0
  385. package/dist/core/tools/jobs.js +86 -0
  386. package/dist/core/tools/jobs.js.map +1 -0
  387. package/dist/core/tools/ls.d.ts.map +1 -1
  388. package/dist/core/tools/ls.js +2 -1
  389. package/dist/core/tools/ls.js.map +1 -1
  390. package/dist/core/tools/output-accumulator.d.ts +12 -1
  391. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  392. package/dist/core/tools/output-accumulator.js +88 -8
  393. package/dist/core/tools/output-accumulator.js.map +1 -1
  394. package/dist/core/tools/output-cleanup.d.ts +40 -0
  395. package/dist/core/tools/output-cleanup.d.ts.map +1 -0
  396. package/dist/core/tools/output-cleanup.js +273 -0
  397. package/dist/core/tools/output-cleanup.js.map +1 -0
  398. package/dist/core/tools/powershell.d.ts.map +1 -1
  399. package/dist/core/tools/powershell.js +15 -2
  400. package/dist/core/tools/powershell.js.map +1 -1
  401. package/dist/core/tools/read.d.ts +21 -0
  402. package/dist/core/tools/read.d.ts.map +1 -1
  403. package/dist/core/tools/read.js +162 -29
  404. package/dist/core/tools/read.js.map +1 -1
  405. package/dist/core/tools/renderers/bash.d.ts.map +1 -1
  406. package/dist/core/tools/renderers/bash.js +3 -1
  407. package/dist/core/tools/renderers/bash.js.map +1 -1
  408. package/dist/core/tools/renderers/index.d.ts.map +1 -1
  409. package/dist/core/tools/renderers/index.js +1 -0
  410. package/dist/core/tools/renderers/index.js.map +1 -1
  411. package/dist/core/tools/subagent.d.ts +5 -1
  412. package/dist/core/tools/subagent.d.ts.map +1 -1
  413. package/dist/core/tools/subagent.js +76 -19
  414. package/dist/core/tools/subagent.js.map +1 -1
  415. package/dist/core/tools/truncate.d.ts +4 -0
  416. package/dist/core/tools/truncate.d.ts.map +1 -1
  417. package/dist/core/tools/truncate.js +24 -1
  418. package/dist/core/tools/truncate.js.map +1 -1
  419. package/dist/core/tools/write.d.ts.map +1 -1
  420. package/dist/core/tools/write.js +6 -1
  421. package/dist/core/tools/write.js.map +1 -1
  422. package/dist/core/trace/config.js +3 -3
  423. package/dist/core/trace/config.js.map +1 -1
  424. package/dist/core/trace/redaction.d.ts.map +1 -1
  425. package/dist/core/trace/redaction.js +12 -9
  426. package/dist/core/trace/redaction.js.map +1 -1
  427. package/dist/core/trace-client/credential-store.d.ts +1 -1
  428. package/dist/core/trace-client/credential-store.d.ts.map +1 -1
  429. package/dist/core/trace-client/credential-store.js +20 -3
  430. package/dist/core/trace-client/credential-store.js.map +1 -1
  431. package/dist/core/usage-ledger.d.ts +35 -0
  432. package/dist/core/usage-ledger.d.ts.map +1 -0
  433. package/dist/core/usage-ledger.js +140 -0
  434. package/dist/core/usage-ledger.js.map +1 -0
  435. package/dist/extensions/codemode/execute.d.ts.map +1 -1
  436. package/dist/extensions/codemode/execute.js +24 -15
  437. package/dist/extensions/codemode/execute.js.map +1 -1
  438. package/dist/extensions/codemode/index.d.ts +4 -2
  439. package/dist/extensions/codemode/index.d.ts.map +1 -1
  440. package/dist/extensions/codemode/index.js +8 -4
  441. package/dist/extensions/codemode/index.js.map +1 -1
  442. package/dist/extensions/codemode/tool.d.ts +4 -2
  443. package/dist/extensions/codemode/tool.d.ts.map +1 -1
  444. package/dist/extensions/codemode/tool.js +34 -12
  445. package/dist/extensions/codemode/tool.js.map +1 -1
  446. package/dist/extensions/llama/client.d.ts +2 -0
  447. package/dist/extensions/llama/client.d.ts.map +1 -1
  448. package/dist/extensions/llama/client.js +23 -2
  449. package/dist/extensions/llama/client.js.map +1 -1
  450. package/dist/extensions/llama/ui.d.ts.map +1 -1
  451. package/dist/extensions/llama/ui.js +15 -3
  452. package/dist/extensions/llama/ui.js.map +1 -1
  453. package/dist/extensions/mcp/runtime.d.ts.map +1 -1
  454. package/dist/extensions/mcp/runtime.js +3 -2
  455. package/dist/extensions/mcp/runtime.js.map +1 -1
  456. package/dist/extensions/tool-search/tool.d.ts.map +1 -1
  457. package/dist/extensions/tool-search/tool.js +18 -6
  458. package/dist/extensions/tool-search/tool.js.map +1 -1
  459. package/dist/extensions/usage/hcode-overview.d.ts +23 -0
  460. package/dist/extensions/usage/hcode-overview.d.ts.map +1 -0
  461. package/dist/extensions/usage/hcode-overview.js +109 -0
  462. package/dist/extensions/usage/hcode-overview.js.map +1 -0
  463. package/dist/extensions/usage/index.d.ts +5 -0
  464. package/dist/extensions/usage/index.d.ts.map +1 -1
  465. package/dist/extensions/usage/index.js +194 -12
  466. package/dist/extensions/usage/index.js.map +1 -1
  467. package/dist/extensions/usage/overview.d.ts +5 -0
  468. package/dist/extensions/usage/overview.d.ts.map +1 -1
  469. package/dist/extensions/usage/overview.js +21 -1
  470. package/dist/extensions/usage/overview.js.map +1 -1
  471. package/dist/extensions/usage/popup.d.ts +14 -3
  472. package/dist/extensions/usage/popup.d.ts.map +1 -1
  473. package/dist/extensions/usage/popup.js +199 -25
  474. package/dist/extensions/usage/popup.js.map +1 -1
  475. package/dist/humain/adaptive-execution.d.ts +51 -0
  476. package/dist/humain/adaptive-execution.d.ts.map +1 -0
  477. package/dist/humain/adaptive-execution.js +100 -0
  478. package/dist/humain/adaptive-execution.js.map +1 -0
  479. package/dist/humain/adaptive-peer-process.d.ts +44 -0
  480. package/dist/humain/adaptive-peer-process.d.ts.map +1 -0
  481. package/dist/humain/adaptive-peer-process.js +159 -0
  482. package/dist/humain/adaptive-peer-process.js.map +1 -0
  483. package/dist/humain/adaptive-peer-worker.d.ts +3 -0
  484. package/dist/humain/adaptive-peer-worker.d.ts.map +1 -0
  485. package/dist/humain/adaptive-peer-worker.js +122 -0
  486. package/dist/humain/adaptive-peer-worker.js.map +1 -0
  487. package/dist/humain/adaptive-runtime-types.d.ts +621 -0
  488. package/dist/humain/adaptive-runtime-types.d.ts.map +1 -0
  489. package/dist/humain/adaptive-runtime-types.js +3 -0
  490. package/dist/humain/adaptive-runtime-types.js.map +1 -0
  491. package/dist/humain/adaptive-session-host.d.ts +113 -0
  492. package/dist/humain/adaptive-session-host.d.ts.map +1 -0
  493. package/dist/humain/adaptive-session-host.js +1838 -0
  494. package/dist/humain/adaptive-session-host.js.map +1 -0
  495. package/dist/humain/adhd/index.d.ts +2 -2
  496. package/dist/humain/adhd/index.d.ts.map +1 -1
  497. package/dist/humain/adhd/index.js +22 -13
  498. package/dist/humain/adhd/index.js.map +1 -1
  499. package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +162 -49
  500. package/dist/humain/caveman/index.d.ts +1 -1
  501. package/dist/humain/caveman/index.d.ts.map +1 -1
  502. package/dist/humain/caveman/index.js +21 -12
  503. package/dist/humain/caveman/index.js.map +1 -1
  504. package/dist/humain/classify-tool.d.ts +4 -0
  505. package/dist/humain/classify-tool.d.ts.map +1 -0
  506. package/dist/humain/classify-tool.js +50 -0
  507. package/dist/humain/classify-tool.js.map +1 -0
  508. package/dist/humain/flow-command.d.ts +1 -1
  509. package/dist/humain/flow-command.d.ts.map +1 -1
  510. package/dist/humain/flow-command.js +21 -3
  511. package/dist/humain/flow-command.js.map +1 -1
  512. package/dist/humain/flow-loader.d.ts +15 -10
  513. package/dist/humain/flow-loader.d.ts.map +1 -1
  514. package/dist/humain/flow-loader.js +72 -18
  515. package/dist/humain/flow-loader.js.map +1 -1
  516. package/dist/humain/fuse-provider.d.ts +5 -0
  517. package/dist/humain/fuse-provider.d.ts.map +1 -0
  518. package/dist/humain/fuse-provider.js +302 -0
  519. package/dist/humain/fuse-provider.js.map +1 -0
  520. package/dist/humain/gateway/provider.d.ts.map +1 -1
  521. package/dist/humain/gateway/provider.js +2 -0
  522. package/dist/humain/gateway/provider.js.map +1 -1
  523. package/dist/humain/gateway/secret-store.d.ts +3 -7
  524. package/dist/humain/gateway/secret-store.d.ts.map +1 -1
  525. package/dist/humain/gateway/secret-store.js +21 -249
  526. package/dist/humain/gateway/secret-store.js.map +1 -1
  527. package/dist/humain/hcode/account-store.d.ts +92 -0
  528. package/dist/humain/hcode/account-store.d.ts.map +1 -0
  529. package/dist/humain/hcode/account-store.js +720 -0
  530. package/dist/humain/hcode/account-store.js.map +1 -0
  531. package/dist/humain/hcode/account.d.ts +42 -0
  532. package/dist/humain/hcode/account.d.ts.map +1 -0
  533. package/dist/humain/hcode/account.js +552 -0
  534. package/dist/humain/hcode/account.js.map +1 -0
  535. package/dist/humain/hcode/catalog.d.ts +6 -0
  536. package/dist/humain/hcode/catalog.d.ts.map +1 -0
  537. package/dist/humain/hcode/catalog.js +47 -0
  538. package/dist/humain/hcode/catalog.js.map +1 -0
  539. package/dist/humain/hcode/contracts.d.ts +389 -0
  540. package/dist/humain/hcode/contracts.d.ts.map +1 -0
  541. package/dist/humain/hcode/contracts.js +1243 -0
  542. package/dist/humain/hcode/contracts.js.map +1 -0
  543. package/dist/humain/hcode/environment.d.ts +9 -0
  544. package/dist/humain/hcode/environment.d.ts.map +1 -0
  545. package/dist/humain/hcode/environment.js +24 -0
  546. package/dist/humain/hcode/environment.js.map +1 -0
  547. package/dist/humain/hcode/facade.d.ts +54 -0
  548. package/dist/humain/hcode/facade.d.ts.map +1 -0
  549. package/dist/humain/hcode/facade.js +326 -0
  550. package/dist/humain/hcode/facade.js.map +1 -0
  551. package/dist/humain/hcode/http.d.ts +10 -0
  552. package/dist/humain/hcode/http.d.ts.map +1 -0
  553. package/dist/humain/hcode/http.js +119 -0
  554. package/dist/humain/hcode/http.js.map +1 -0
  555. package/dist/humain/hcode/notices.d.ts +15 -0
  556. package/dist/humain/hcode/notices.d.ts.map +1 -0
  557. package/dist/humain/hcode/notices.js +69 -0
  558. package/dist/humain/hcode/notices.js.map +1 -0
  559. package/dist/humain/hcode/ports.d.ts +34 -0
  560. package/dist/humain/hcode/ports.d.ts.map +1 -0
  561. package/dist/humain/hcode/ports.js +2 -0
  562. package/dist/humain/hcode/ports.js.map +1 -0
  563. package/dist/humain/hcode/provider.d.ts +15 -0
  564. package/dist/humain/hcode/provider.d.ts.map +1 -0
  565. package/dist/humain/hcode/provider.js +200 -0
  566. package/dist/humain/hcode/provider.js.map +1 -0
  567. package/dist/humain/hcode/selection.d.ts +16 -0
  568. package/dist/humain/hcode/selection.d.ts.map +1 -0
  569. package/dist/humain/hcode/selection.js +37 -0
  570. package/dist/humain/hcode/selection.js.map +1 -0
  571. package/dist/humain/hcode/transport.d.ts +22 -0
  572. package/dist/humain/hcode/transport.d.ts.map +1 -0
  573. package/dist/humain/hcode/transport.js +368 -0
  574. package/dist/humain/hcode/transport.js.map +1 -0
  575. package/dist/humain/hcode/usage.d.ts +5 -0
  576. package/dist/humain/hcode/usage.d.ts.map +1 -0
  577. package/dist/humain/hcode/usage.js +66 -0
  578. package/dist/humain/hcode/usage.js.map +1 -0
  579. package/dist/humain/hcode/wire.d.ts +16 -0
  580. package/dist/humain/hcode/wire.d.ts.map +1 -0
  581. package/dist/humain/hcode/wire.js +104 -0
  582. package/dist/humain/hcode/wire.js.map +1 -0
  583. package/dist/humain/index.d.ts +1 -3
  584. package/dist/humain/index.d.ts.map +1 -1
  585. package/dist/humain/index.js +8 -60
  586. package/dist/humain/index.js.map +1 -1
  587. package/dist/humain/login-menu.d.ts.map +1 -1
  588. package/dist/humain/login-menu.js +8 -1
  589. package/dist/humain/login-menu.js.map +1 -1
  590. package/dist/humain/metadata/contracts.d.ts +82 -0
  591. package/dist/humain/metadata/contracts.d.ts.map +1 -0
  592. package/dist/humain/metadata/contracts.js +214 -0
  593. package/dist/humain/metadata/contracts.js.map +1 -0
  594. package/dist/humain/metadata/identity.d.ts +10 -0
  595. package/dist/humain/metadata/identity.d.ts.map +1 -0
  596. package/dist/humain/metadata/identity.js +209 -0
  597. package/dist/humain/metadata/identity.js.map +1 -0
  598. package/dist/humain/metadata/index.d.ts +41 -0
  599. package/dist/humain/metadata/index.d.ts.map +1 -0
  600. package/dist/humain/metadata/index.js +100 -0
  601. package/dist/humain/metadata/index.js.map +1 -0
  602. package/dist/humain/metadata/sender.d.ts +20 -0
  603. package/dist/humain/metadata/sender.d.ts.map +1 -0
  604. package/dist/humain/metadata/sender.js +302 -0
  605. package/dist/humain/metadata/sender.js.map +1 -0
  606. package/dist/humain/metadata/version.d.ts +8 -0
  607. package/dist/humain/metadata/version.d.ts.map +1 -0
  608. package/dist/humain/metadata/version.js +38 -0
  609. package/dist/humain/metadata/version.js.map +1 -0
  610. package/dist/humain/node-http.d.ts +2 -0
  611. package/dist/humain/node-http.d.ts.map +1 -1
  612. package/dist/humain/node-http.js +9 -4
  613. package/dist/humain/node-http.js.map +1 -1
  614. package/dist/humain/node-provider.d.ts +2 -0
  615. package/dist/humain/node-provider.d.ts.map +1 -1
  616. package/dist/humain/node-provider.js +39 -8
  617. package/dist/humain/node-provider.js.map +1 -1
  618. package/dist/humain/ponytail/vendor/hooks/ponytail-config.d.ts +1 -1
  619. package/dist/humain/ponytail/vendor/hooks/ponytail-config.d.ts.map +1 -1
  620. package/dist/humain/ponytail/vendor/hooks/ponytail-config.js +4 -4
  621. package/dist/humain/ponytail/vendor/hooks/ponytail-config.js.map +1 -1
  622. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.d.ts.map +1 -1
  623. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js +7 -0
  624. package/dist/humain/ponytail/vendor/hooks/ponytail-instructions.js.map +1 -1
  625. package/dist/humain/ponytail/vendor/pi-extension/index.d.ts.map +1 -1
  626. package/dist/humain/ponytail/vendor/pi-extension/index.js +12 -1
  627. package/dist/humain/ponytail/vendor/pi-extension/index.js.map +1 -1
  628. package/dist/humain/systemone.d.ts +23 -0
  629. package/dist/humain/systemone.d.ts.map +1 -0
  630. package/dist/humain/systemone.js +101 -0
  631. package/dist/humain/systemone.js.map +1 -0
  632. package/dist/humain/trace-capture/flow-producer.d.ts.map +1 -1
  633. package/dist/humain/trace-capture/flow-producer.js +3 -3
  634. package/dist/humain/trace-capture/flow-producer.js.map +1 -1
  635. package/dist/index.d.ts +4 -2
  636. package/dist/index.d.ts.map +1 -1
  637. package/dist/index.js.map +1 -1
  638. package/dist/main.d.ts +1 -0
  639. package/dist/main.d.ts.map +1 -1
  640. package/dist/main.js +292 -183
  641. package/dist/main.js.map +1 -1
  642. package/dist/modes/interactive/bug-report.d.ts.map +1 -1
  643. package/dist/modes/interactive/bug-report.js +82 -36
  644. package/dist/modes/interactive/bug-report.js.map +1 -1
  645. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  646. package/dist/modes/interactive/components/assistant-message.js +8 -5
  647. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  648. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  649. package/dist/modes/interactive/components/diff.js +11 -5
  650. package/dist/modes/interactive/components/diff.js.map +1 -1
  651. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  652. package/dist/modes/interactive/components/extension-selector.js +9 -1
  653. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  654. package/dist/modes/interactive/components/first-time-setup.d.ts +10 -5
  655. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  656. package/dist/modes/interactive/components/first-time-setup.js +55 -29
  657. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  658. package/dist/modes/interactive/components/model-selector.d.ts +16 -2
  659. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  660. package/dist/modes/interactive/components/model-selector.js +164 -19
  661. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  662. package/dist/modes/interactive/components/oauth-selector.d.ts +3 -0
  663. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  664. package/dist/modes/interactive/components/oauth-selector.js +19 -2
  665. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  666. package/dist/modes/interactive/components/status-indicator.d.ts +17 -0
  667. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  668. package/dist/modes/interactive/components/status-indicator.js +78 -1
  669. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  670. package/dist/modes/interactive/components/tree-selector.d.ts +1 -0
  671. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  672. package/dist/modes/interactive/components/tree-selector.js +19 -10
  673. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  674. package/dist/modes/interactive/interactive-mode.d.ts +4 -0
  675. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  676. package/dist/modes/interactive/interactive-mode.js +353 -65
  677. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  678. package/dist/modes/interactive/interactive-mode.lazy.d.ts +3 -0
  679. package/dist/modes/interactive/interactive-mode.lazy.d.ts.map +1 -0
  680. package/dist/modes/interactive/interactive-mode.lazy.js +3 -0
  681. package/dist/modes/interactive/interactive-mode.lazy.js.map +1 -0
  682. package/dist/modes/interactive/model-catalog-refresh.d.ts +2 -0
  683. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -1
  684. package/dist/modes/interactive/model-catalog-refresh.js +12 -0
  685. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -1
  686. package/dist/modes/interactive/theme/theme-controller.d.ts +2 -3
  687. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  688. package/dist/modes/interactive/theme/theme-controller.js +4 -5
  689. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  690. package/dist/modes/interactive/theme/theme-schema.js +4 -4
  691. package/dist/modes/interactive/theme/theme-schema.js.map +1 -1
  692. package/dist/modes/interactive/theme/theme.d.ts +2 -0
  693. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  694. package/dist/modes/interactive/theme/theme.js +8 -0
  695. package/dist/modes/interactive/theme/theme.js.map +1 -1
  696. package/dist/modes/json-event.d.ts +2 -1
  697. package/dist/modes/json-event.d.ts.map +1 -1
  698. package/dist/modes/json-event.js.map +1 -1
  699. package/dist/modes/print-mode.d.ts +4 -0
  700. package/dist/modes/print-mode.d.ts.map +1 -1
  701. package/dist/modes/print-mode.js +57 -11
  702. package/dist/modes/print-mode.js.map +1 -1
  703. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  704. package/dist/modes/rpc/rpc-mode.js +68 -16
  705. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  706. package/dist/modes/rpc/rpc-types.d.ts +2 -0
  707. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  708. package/dist/modes/rpc/rpc-types.js.map +1 -1
  709. package/dist/utils/changelog.d.ts +1 -1
  710. package/dist/utils/changelog.d.ts.map +1 -1
  711. package/dist/utils/changelog.js +7 -5
  712. package/dist/utils/changelog.js.map +1 -1
  713. package/dist/utils/image-resize.d.ts.map +1 -1
  714. package/dist/utils/image-resize.js +3 -1
  715. package/dist/utils/image-resize.js.map +1 -1
  716. package/dist/utils/lazy-validator.d.ts +5 -0
  717. package/dist/utils/lazy-validator.d.ts.map +1 -0
  718. package/dist/utils/lazy-validator.js +7 -0
  719. package/dist/utils/lazy-validator.js.map +1 -0
  720. package/dist/utils/shell.d.ts +3 -1
  721. package/dist/utils/shell.d.ts.map +1 -1
  722. package/dist/utils/shell.js +9 -4
  723. package/dist/utils/shell.js.map +1 -1
  724. package/docs/cli.md +23 -5
  725. package/docs/codemode.md +21 -1
  726. package/docs/development.md +18 -0
  727. package/docs/docs.json +4 -0
  728. package/docs/extensions.md +4 -0
  729. package/docs/flow.md +115 -16
  730. package/docs/headless-modes.md +61 -0
  731. package/docs/humain-code-forge-architecture.md +65 -13
  732. package/docs/humain-code-forge-component-scorecard.md +10 -1
  733. package/docs/humain-code-forge-flow-walkthrough.md +54 -55
  734. package/docs/humain-code.md +22 -19
  735. package/docs/index.md +1 -0
  736. package/docs/keybindings.md +1 -1
  737. package/docs/models-configuration.md +6 -1
  738. package/docs/models.md +1 -1
  739. package/docs/prompt-templates.md +1 -1
  740. package/docs/providers.md +67 -15
  741. package/docs/run-preflight.md +47 -0
  742. package/docs/sdk.md +39 -1
  743. package/docs/security.md +1 -1
  744. package/docs/settings.md +12 -5
  745. package/docs/skills.md +2 -0
  746. package/docs/slash-commands.md +5 -3
  747. package/docs/usage.md +29 -0
  748. package/examples/extensions/custom-provider-anthropic/package-lock.json +4 -4
  749. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  750. package/examples/tsconfig.json +13 -0
  751. package/npm-shrinkwrap.json +67 -67
  752. package/package.json +25 -19
  753. package/schemas/models.schema.json +30 -0
  754. package/schemas/settings.schema.json +28 -9
  755. package/src/humain/caveman/UPSTREAM.md +19 -3
  756. package/src/humain/caveman/upstream.json +2 -2
  757. package/src/humain/ponytail/UPSTREAM.md +16 -1
  758. package/src/humain/web-access/UPSTREAM.md +10 -0
  759. package/src/humain/web-access/upstream.json +1 -0
  760. package/dist/bundle/chunks/anthropic-messages-MNISFDZA.js +0 -66
  761. package/dist/bundle/chunks/chunk-2HZ2V3HS.js +0 -1985
  762. package/dist/bundle/chunks/chunk-2PZ46FSM.js +0 -6
  763. package/dist/bundle/chunks/chunk-4SQUP6IR.js +0 -88
  764. package/dist/bundle/chunks/chunk-5JSLXC2A.js +0 -3
  765. package/dist/bundle/chunks/chunk-75CQYZ63.js +0 -1336
  766. package/dist/bundle/chunks/chunk-DCPACGLH.js +0 -12267
  767. package/dist/bundle/chunks/chunk-FLVBQ6GS.js +0 -24
  768. package/dist/bundle/chunks/chunk-H7Y4QY7K.js +0 -11
  769. package/dist/bundle/chunks/chunk-JEAM6N22.js +0 -139
  770. package/dist/bundle/chunks/chunk-PS2FJ7M4.js +0 -23
  771. package/dist/bundle/chunks/chunk-TEOMXMW6.js +0 -23
  772. package/dist/bundle/chunks/chunk-WEFEQEIQ.js +0 -28
  773. package/dist/bundle/chunks/chunk-WW4SILXG.js +0 -249
  774. package/dist/bundle/chunks/compat-MXAZPYDN.js +0 -13
  775. package/dist/bundle/chunks/dist-3V7ZSLER.js +0 -3166
  776. package/dist/bundle/chunks/dist-66CW64M2.js +0 -8
  777. package/dist/bundle/chunks/host-SCZ4IKWR.js +0 -2
  778. package/dist/bundle/chunks/openai-codex-responses-LZWBQYVP.js +0 -101
  779. package/dist/bundle/chunks/openai-completions-7NWH423P.js +0 -82
  780. package/dist/bundle/chunks/openai-responses-5YOLHMCF.js +0 -27
  781. package/dist/bundle/chunks/runtime-UVPDE4CX.js +0 -2
  782. package/dist/bundle/chunks/typesafe-system-one-BHJYAZ6E.js +0 -3
  783. package/dist/bundle/chunks/virtual-modules-YQPK57CW.js +0 -23
  784. package/dist/humain/legacy-workflow-tiers.d.ts +0 -3
  785. package/dist/humain/legacy-workflow-tiers.d.ts.map +0 -1
  786. package/dist/humain/legacy-workflow-tiers.js +0 -46
  787. package/dist/humain/legacy-workflow-tiers.js.map +0 -1
  788. /package/dist/bundle/{flow → orchestrate}/agents/orch-architect.md +0 -0
  789. /package/dist/bundle/{flow → orchestrate}/agents/orch-scout.md +0 -0
  790. /package/dist/bundle/{flow → orchestrate}/agents/orch-security-review.md +0 -0
  791. /package/dist/bundle/{flow → orchestrate}/agents/orch-technical-lead.md +0 -0
  792. /package/dist/bundle/{flow → orchestrate}/agents/orch-technical-review.md +0 -0
@@ -0,0 +1,1061 @@
1
+ import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
+ import{__export}from"./chunk-JXWJOIH4.js";function scorePositions(textLower,positions){let score=0,lastMatchIndex=-1,consecutiveMatches=0;for(let i of positions)lastMatchIndex===i-1?(consecutiveMatches++,score-=consecutiveMatches*5):(consecutiveMatches=0,lastMatchIndex>=0&&(score+=(i-lastMatchIndex-1)*2)),(i===0||/[\s\-_./:]/.test(textLower[i-1]))&&(score-=10),score+=i*.1,lastMatchIndex=i;return score}function matchQuery(normalizedQuery,textLower){if(normalizedQuery.length===0)return{matches:!0,score:0};if(normalizedQuery.length>textLower.
3
+ length)return{matches:!1,score:0};let positions=[],lastMatchIndex=-1;for(let queryIndex=0;queryIndex<normalizedQuery.length;queryIndex++){let i=textLower.indexOf(normalizedQuery[queryIndex],lastMatchIndex+1);if(i===-1)return{matches:!1,score:0};positions.push(i),lastMatchIndex=i}let score=scorePositions(textLower,positions);for(let start=textLower.indexOf(normalizedQuery);start!==-1;start=textLower.indexOf(normalizedQuery,start+1)){for(let k=0;k<positions.length;k++)positions[k]=start+k;score=Math.
4
+ min(score,scorePositions(textLower,positions))}return normalizedQuery===textLower&&(score-=100),{matches:!0,score}}function fuzzyMatch(query,text){let queryLower=query.toLowerCase(),textLower=text.toLowerCase(),primaryMatch=matchQuery(queryLower,textLower);if(primaryMatch.matches)return primaryMatch;let alphaNumericMatch=queryLower.match(/^(?<letters>[a-z]+)(?<digits>[0-9]+)$/),numericAlphaMatch=queryLower.match(/^(?<digits>[0-9]+)(?<letters>[a-z]+)$/),swappedQuery=alphaNumericMatch?`${alphaNumericMatch.
5
+ groups?.digits??""}${alphaNumericMatch.groups?.letters??""}`:numericAlphaMatch?`${numericAlphaMatch.groups?.letters??""}${numericAlphaMatch.groups?.digits??""}`:"";if(!swappedQuery)return primaryMatch;let swappedMatch=matchQuery(swappedQuery,textLower);return swappedMatch.matches?{matches:!0,score:swappedMatch.score+5}:primaryMatch}function fuzzyFilter(items,query,getText){if(!query.trim())return items;let tokens=query.trim().split(/[\s/]+/).filter(t=>t.length>0);if(tokens.length===0)return items;
6
+ let results=[];for(let item of items){let text=getText(item),totalScore=0,allMatch=!0;for(let token of tokens){let match=fuzzyMatch(token,text);if(match.matches)totalScore+=match.score;else{allMatch=!1;break}}allMatch&&results.push({item,totalScore})}return results.sort((a,b)=>a.totalScore-b.totalScore),results.map(r=>r.item)}var ambiguousRanges=[161,161,164,164,167,168,170,170,173,174,176,180,182,186,188,191,198,198,208,208,215,216,222,225,230,230,232,234,236,237,240,240,242,243,247,250,252,252,254,254,257,257,273,273,275,275,283,283,294,295,299,299,305,307,312,312,319,322,324,324,328,331,333,333,338,339,358,359,363,363,462,462,464,464,466,466,468,468,470,470,472,472,474,474,476,476,593,593,609,609,708,708,711,711,713,715,717,717,720,720,728,731,733,733,735,735,768,879,913,929,931,937,945,961,963,969,1025,1025,1040,
7
+ 1103,1105,1105,8208,8208,8211,8214,8216,8217,8220,8221,8224,8226,8228,8231,8240,8240,8242,8243,8245,8245,8251,8251,8254,8254,8308,8308,8319,8319,8321,8324,8364,8364,8451,8451,8453,8453,8457,8457,8467,8467,8470,8470,8481,8482,8486,8486,8491,8491,8531,8532,8539,8542,8544,8555,8560,8569,8585,8585,8592,8601,8632,8633,8658,8658,8660,8660,8679,8679,8704,8704,8706,8707,8711,8712,8715,8715,8719,8719,8721,8721,8725,8725,8730,8730,8733,8736,8739,8739,8741,8741,8743,8748,8750,8750,8756,8759,8764,8765,8776,
8
+ 8776,8780,8780,8786,8786,8800,8801,8804,8807,8810,8811,8814,8815,8834,8835,8838,8839,8853,8853,8857,8857,8869,8869,8895,8895,8978,8978,9312,9449,9451,9547,9552,9587,9600,9615,9618,9621,9632,9633,9635,9641,9650,9651,9654,9655,9660,9661,9664,9665,9670,9672,9675,9675,9678,9681,9698,9701,9711,9711,9733,9734,9737,9737,9742,9743,9756,9756,9758,9758,9792,9792,9794,9794,9824,9825,9827,9829,9831,9834,9836,9837,9839,9839,9886,9887,9919,9919,9926,9933,9935,9939,9941,9953,9955,9955,9960,9961,9963,9969,9972,
9
+ 9972,9974,9977,9979,9980,9982,9983,10045,10045,10102,10111,11094,11097,12872,12879,57344,63743,65024,65039,65533,65533,127232,127242,127248,127277,127280,127337,127344,127373,127375,127376,127387,127404,917760,917999,983040,1048573,1048576,1114109],fullwidthMinimalCodePoint=12288,fullwidthMaximumCodePoint=65510,fullwidthRanges=[12288,12288,65281,65376,65504,65510];var wideMinimalCodePoint=4352,wideMaximumCodePoint=262141,wideRanges=[4352,4447,8986,8987,9001,9002,9193,9196,9200,9200,9203,9203,9725,9726,9748,9749,9776,9783,9800,9811,9855,9855,9866,9871,9875,9875,9889,9889,9898,9899,9917,9918,9924,9925,9934,9934,9940,9940,9962,9962,9970,9971,9973,9973,9978,9978,9981,9981,9989,9989,9994,9995,10024,10024,10060,10060,10062,10062,10067,10069,10071,10071,10133,10135,10160,10160,10175,10175,11035,11036,11088,11088,11093,11093,11904,11929,11931,12019,12032,12245,12272,
10
+ 12287,12289,12350,12353,12438,12441,12543,12549,12591,12593,12686,12688,12773,12783,12830,12832,12871,12880,42124,42128,42182,43360,43388,44032,55203,63744,64255,65040,65049,65072,65106,65108,65126,65128,65131,94176,94180,94192,94198,94208,101594,101631,101664,101760,101874,101888,102801,102816,102866,110576,110579,110581,110587,110589,110590,110592,110888,110898,110898,110928,110930,110933,110933,110948,110952,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,
11
+ 127386,127406,127406,127488,127490,127504,127547,127552,127560,127568,127569,127584,127589,127744,127776,127789,127797,127799,127868,127870,127891,127904,127946,127951,127955,127968,127984,127988,127988,127992,128062,128064,128064,128066,128252,128255,128317,128331,128334,128336,128359,128378,128378,128405,128406,128420,128420,128507,128591,128640,128709,128716,128716,128720,128722,128725,128729,128732,128735,128747,128748,128756,128764,128986,128986,128992,129003,129008,129008,129292,129338,129340,
12
+ 129349,129351,129535,129648,129660,129664,129734,129736,129736,129740,129757,129759,129771,129775,129786,131072,196605,196608,262141];var isInRange=(ranges,codePoint)=>{let low=0,high=Math.floor(ranges.length/2)-1;for(;low<=high;){let mid=Math.floor((low+high)/2),i=mid*2;if(codePoint<ranges[i])high=mid-1;else if(codePoint>ranges[i+1])low=mid+1;else return!0}return!1};var commonCjkCodePoint=19968,[wideFastPathStart,wideFastPathEnd]=findWideFastPathRange(wideRanges);function findWideFastPathRange(ranges){let fastPathStart=ranges[0],fastPathEnd=ranges[1];for(let index=0;index<ranges.length;index+=2){let start=ranges[index],end=ranges[index+1];if(commonCjkCodePoint>=start&&commonCjkCodePoint<=end)return[start,end];end-start>fastPathEnd-fastPathStart&&(fastPathStart=start,fastPathEnd=end)}return[fastPathStart,fastPathEnd]}var isAmbiguous=codePoint=>codePoint<161||
13
+ codePoint>1114109?!1:isInRange(ambiguousRanges,codePoint),isFullwidth=codePoint=>codePoint<fullwidthMinimalCodePoint||codePoint>fullwidthMaximumCodePoint?!1:isInRange(fullwidthRanges,codePoint);var isWide=codePoint=>codePoint>=wideFastPathStart&&codePoint<=wideFastPathEnd?!0:codePoint<wideMinimalCodePoint||codePoint>wideMaximumCodePoint?!1:isInRange(wideRanges,codePoint);function validate(codePoint){if(!Number.isSafeInteger(codePoint))throw new TypeError(`Expected a code point, got \`${typeof codePoint}\`.`)}function eastAsianWidth(codePoint,{ambiguousAsWide=!1}={}){return validate(codePoint),isFullwidth(codePoint)||isWide(codePoint)||ambiguousAsWide&&isAmbiguous(codePoint)?2:1}var graphemeSegmenter,wordSegmenter;function getGraphemeSegmenter(){return graphemeSegmenter??=new Intl.Segmenter(void 0,{granularity:"grapheme"}),graphemeSegmenter}function getWordSegmenter(){return wordSegmenter??=new Intl.Segmenter(void 0,{granularity:"word"}),wordSegmenter}function couldBeEmoji(segment){let cp=segment.codePointAt(0);return cp>=126976&&cp<=130047||cp>=8960&&cp<=9215||cp>=9728&&cp<=10175||cp>=11088&&cp<=11093||segment.includes("\uFE0F")||segment.length>2}var zeroWidthRegex=new RegExp(
14
+ "^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Mark}|\\p{Surrogate})+$","v"),leadingNonPrintingRegex=new RegExp("^[\\p{Default_Ignorable_Code_Point}\\p{Control}\\p{Format}\\p{Mark}\\p{Surrogate}]+","v"),nonPrintingCharRegex=new RegExp("^(?:\\p{Default_Ignorable_Code_Point}|\\p{Control}|\\p{Format}|\\p{Mark}|\\p{Surrogate})$","v"),markCharRegex=new RegExp("^\\p{Mark}$","v"),terminalSpacingMarkRegex=new RegExp("^(?:[\\p{Spacing_Mark}--[\\u1734\\u302E\\u302F]]|[\\u065F\\u0F7F\\u102B\\u102C\\u1031\\u\
15
+ 1033-\\u1035\\u1038\\u103A-\\u103E])+$","v"),rgiEmojiRegex=new RegExp("^\\p{RGI_Emoji}$","v"),singleCodePointEmojiRegex=new RegExp("^(?![\\u{1F1E6}-\\u{1F1FF}])\\p{Emoji_Presentation}$","u"),WIDTH_CACHE_SIZE=512,widthCache=new Map,cjkBreakRegex=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,cjkPunctuationRegex=new RegExp(`(?:(?=\\p{Punctuation})${cjkBreakRegex.source}|[\uFF0C\uFF0E\uFF1A\uFF1B\uFF01\uFF1F\uFF08\uFF09\uFF3B\uFF3D\uFF5B\uFF5D\u201C\u201D\u2018\u2019\u2026\u2014])`,
16
+ "u"),autocompleteSeparatorRegex=new RegExp(`(?:\\s|${cjkPunctuationRegex.source})`,"u"),autocompleteBoundaryRegex=new RegExp(`(?:^|${autocompleteSeparatorRegex.source})`,"u");function isPrintableAscii(str){for(let i=0;i<str.length;i++){let code=str.charCodeAt(i);if(code<32||code>126)return!1}return!0}function truncateFragmentToWidth(text,maxWidth){if(maxWidth<=0||text.length===0)return{text:"",width:0};if(isPrintableAscii(text)){let clipped=text.slice(0,maxWidth);return{text:clipped,width:clipped.
17
+ length}}let hasAnsi=text.includes("\x1B"),hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){let result2="",width2=0;for(let{segment}of getGraphemeSegmenter().segment(text)){let w2=graphemeWidth(segment);if(width2+w2>maxWidth)break;result2+=segment,width2+=w2}return{text:result2,width:width2}}let result="",width=0,i=0,pendingAnsi="";for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(width+3>maxWidth)break;pendingAnsi&&
18
+ (result+=pendingAnsi,pendingAnsi=""),result+=" ",width+=3,i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of getGraphemeSegmenter().segment(text.slice(i,end))){let w2=graphemeWidth(segment);if(width+w2>maxWidth)return{text:result,width};pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,width+=w2}i=end}return{text:result,width}}function finalizeTruncatedResult(prefix,prefixWidth,ellipsis,ellipsisWidth,maxWidth,pad){let reset="\
19
+ \x1B[0m",hyperlinkClose=getActiveOsc8Close(prefix),visibleWidth2=prefixWidth+ellipsisWidth,result;return ellipsis.length>0?result=`${prefix}${hyperlinkClose}${reset}${ellipsis}${reset}`:result=`${prefix}${hyperlinkClose}${reset}`,pad?result+" ".repeat(Math.max(0,maxWidth-visibleWidth2)):result}function isRgiEmoji(segment){return segment.length===(segment.codePointAt(0)>65535?2:1)?singleCodePointEmojiRegex.test(segment):rgiEmojiRegex.test(segment)}function graphemeWidth(segment){if(segment.length===
20
+ 1){let code=segment.charCodeAt(0);if(code>=32&&code<=126)return 1;if(code===9)return 3}if(terminalSpacingMarkRegex.test(segment))return[...segment].length;if(zeroWidthRegex.test(segment))return 0;if(couldBeEmoji(segment)&&isRgiEmoji(segment))return 2;let base=segment.replace(leadingNonPrintingRegex,""),cp=base.codePointAt(0);if(cp===void 0)return 0;if(cp>=127462&&cp<=127487)return 2;let width=eastAsianWidth(cp),followsMark=!1,chars=[...base];for(let char of chars.slice(1))if(terminalSpacingMarkRegex.
21
+ test(char))width+=1,followsMark=!1;else if(markCharRegex.test(char))followsMark=!0;else if(!nonPrintingCharRegex.test(char)){let c=char.codePointAt(0);followsMark||c>=65280&&c<=65519?width+=eastAsianWidth(c):(c===3635||c===3763)&&(width+=1),followsMark=!1}return width}function visibleWidth(str){if(str.length===0)return 0;let asciiWidth=asciiVisibleWidth(str);if(asciiWidth!==-1)return asciiWidth;let cached=widthCache.get(str);if(cached!==void 0)return cached;let clean=str;str.includes(" ")&&(clean=
22
+ clean.replace(/\t/g," "));let escapeIndex=clean.indexOf("\x1B");if(escapeIndex!==-1){let stripped="",copyFrom=0;for(;escapeIndex!==-1;){let length=ansiCodeLength(clean,escapeIndex);length>0?(stripped+=clean.slice(copyFrom,escapeIndex),escapeIndex+=length,copyFrom=escapeIndex):escapeIndex++,escapeIndex=clean.indexOf("\x1B",escapeIndex)}clean=stripped+clean.slice(copyFrom)}let width=0;for(let{segment}of getGraphemeSegmenter().segment(clean))width+=graphemeWidth(segment);if(widthCache.size>=WIDTH_CACHE_SIZE){
23
+ let firstKey=widthCache.keys().next().value;firstKey!==void 0&&widthCache.delete(firstKey)}return widthCache.set(str,width),width}function stripTerminalSequences(str){if(!str.includes("\x1B"))return str;let result="",i=0;for(;i<str.length;){let ansi=extractAnsiCode(str,i);if(ansi){i+=ansi.length;continue}result+=str[i],i++}return result}var TERMINAL_CONTROL_REGEX=/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]|\r(?!\n)/g,TERMINAL_SEQUENCE_GLOBAL_REGEX=/\x1b\[[\x30-\x3f]*[\x20-\x2f]*[\x40-\x7e]|\x1b[\]PX^_][^\x07\x1b\x9c]*(?:\x07|\x1b\\|\x9c)|\x1b[\x20-\x2f]*[\x30-\x4f\x51-\x57\x59\x5a\x5c\x60-\x7e]|\r(?!\n)|[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f]/g;
24
+ function sanitizeTerminalText(text){return TERMINAL_CONTROL_REGEX.lastIndex=0,TERMINAL_CONTROL_REGEX.test(text)?text.replace(TERMINAL_SEQUENCE_GLOBAL_REGEX,match=>match==="\r"?`
25
+ `:""):text}var PENDING_ESCAPE_REGEX=/\x1b(?:\[[\x30-\x3f]*[\x20-\x2f]*|[\]PX^_][^\x07\x1b\x9c]*\x1b?|[\x20-\x2f]*)$/y;function startsWithText(text,prefix){return text.length>=prefix.length&&text.slice(0,prefix.length)===prefix}function sanitizeTerminalTextFrom(text,previous){let start=0,prefix="",unchanged=!0,extendsPrevious=!1;if(previous!==void 0&&startsWithText(text,previous.raw)){if(text.length===previous.raw.length)return{...previous,added:""};start=previous.safeRaw,unchanged=previous.unchanged,
26
+ prefix=previous.safeLength===previous.text.length?previous.text:previous.text.slice(0,previous.safeLength),extendsPrevious=prefix.length===previous.text.length}let tail=start===0?text:text.slice(start);if(TERMINAL_CONTROL_REGEX.lastIndex=0,!TERMINAL_CONTROL_REGEX.test(tail)){let sanitized2=unchanged?text:prefix+tail;return{raw:text,text:sanitized2,unchanged,safeRaw:text.length,safeLength:sanitized2.length,added:extendsPrevious?tail:void 0}}let added="",last=0,safeRaw=-1,safeLength=0,regex=TERMINAL_SEQUENCE_GLOBAL_REGEX;
27
+ regex.lastIndex=0;for(let match=regex.exec(tail);match!==null;match=regex.exec(tail)){let at2=match.index,sequence=match[0];if(safeRaw<0){let pending=!1;sequence==="\r"?pending=at2+1===tail.length:sequence==="\x1B"&&(PENDING_ESCAPE_REGEX.lastIndex=at2,pending=PENDING_ESCAPE_REGEX.test(tail)),pending&&(safeRaw=start+at2,safeLength=prefix.length+added.length+(at2-last))}added+=tail.slice(last,at2),sequence==="\r"&&(added+=`
28
+ `),last=at2+sequence.length}added+=tail.slice(last);let sanitized=prefix+added;return safeRaw<0&&(safeRaw=text.length,safeLength=sanitized.length),{raw:text,text:sanitized,unchanged:!1,safeRaw,safeLength,added:extendsPrevious?added:void 0}}function isWebLink(url){return/^(?:https?|mailto):/i.test(url)}function extractAnsiCodes(str){let result="",i=str.indexOf("\x1B");for(;i!==-1;){let length=ansiCodeLength(str,i);length>0?(result+=str.substring(i,i+length),i+=length):i++,i=str.indexOf("\x1B",i)}
29
+ return result}var WHITESPACE_REGEX=/\s/;function isWhitespaceToken(token){let i=0;for(;i<token.length;){let code=token.charCodeAt(i);if(code===27){let length=ansiCodeLength(token,i);if(length===0)return!1;i+=length}else if(code===32||code>=9&&code<=13)i++;else{if(code<128||!WHITESPACE_REGEX.test(token[i]))return!1;i++}}return!0}var CONTROL_CHARACTERS=/[\u0000-\u001f\u007f-\u009f]+/g;function replaceControlCharacters(str){return str.replace(CONTROL_CHARACTERS," ")}function getGraphemeCellRange(line,column){
30
+ let currentCol=0,i=0;for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of getGraphemeSegmenter().segment(line.slice(i,textEnd))){let width=graphemeWidth(segment);if(width>0&&column>=currentCol&&column<currentCol+width)return{start:currentCol,end:currentCol+width};currentCol+=width}i=textEnd}}function getOsc8LinkAtColumn(line,column){let activeUrl,currentCol=0,i=0;
31
+ for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){let hyperlink2=/^\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)$/.exec(ansi.code);hyperlink2&&(activeUrl=hyperlink2[1]||void 0),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of getGraphemeSegmenter().segment(line.slice(i,textEnd))){let width=segment===" "?3:graphemeWidth(segment);if(column>=currentCol&&column<currentCol+width)return activeUrl;currentCol+=width}i=
32
+ textEnd}}var THAI_LAO_AM_REGEX=/[\u0e33\u0eb3]/,THAI_LAO_AM_GLOBAL_REGEX=/[\u0e33\u0eb3]/g;function normalizeTerminalOutput(str){let normalized=str;if(THAI_LAO_AM_REGEX.test(normalized)&&(normalized=normalized.replace(THAI_LAO_AM_GLOBAL_REGEX,char=>char==="\u0E33"?"\u0E4D\u0E32":"\u0ECD\u0EB2")),!normalized.includes(" "))return normalized;let result="",i=0;for(;i<normalized.length;){let ansi=extractAnsiCode(normalized,i);if(ansi){result+=ansi.code,i+=ansi.length;continue}result+=normalized[i]===
33
+ " "?" ":normalized[i],i++}return result}function extractAnsiCode(str,pos){let length=ansiCodeLength(str,pos);return length>0?{code:str.substring(pos,pos+length),length}:null}function asciiVisibleWidth(str,maxWidth=1/0){let width=0,i=0;for(;i<str.length;){let code=str.charCodeAt(i);if(code>=32&&code<=126||code>=9472&&code<=9599)width++,i++;else if(code===9)width+=3,i++;else if(code===27){let length=ansiCodeLength(str,i);if(length===0)return-1;i+=length}else return-1;if(width>maxWidth)return width}
34
+ return width}function ansiCodeLength(str,pos){if(pos>=str.length||str.charCodeAt(pos)!==27)return 0;let next=str[pos+1];if(next==="["){for(let j2=pos+2;j2<str.length;j2++){let c=str.charCodeAt(j2);if(c===109||c===71||c===75||c===72||c===74)return j2+1-pos}return 0}if(next==="]"||next==="_"){for(let j2=pos+2;j2<str.length;j2++){let c=str.charCodeAt(j2);if(c===7)return j2+1-pos;if(c===27&&str[j2+1]==="\\")return j2+2-pos}return 0}return 0}function parseOsc8Hyperlink(ansiCode){if(!ansiCode.startsWith(
35
+ "\x1B]8;"))return;let terminator=ansiCode.endsWith("\x07")?"\x07":"\x1B\\",body=ansiCode.slice(4,terminator==="\x07"?-1:-2),separatorIndex=body.indexOf(";");if(separatorIndex===-1)return;let params=body.slice(0,separatorIndex),url=body.slice(separatorIndex+1);return url?{params,url,terminator}:null}function formatOsc8Hyperlink(hyperlink2){return`\x1B]8;${hyperlink2.params};${hyperlink2.url}${hyperlink2.terminator}`}function formatOsc8Close(terminator){return`\x1B]8;;${terminator}`}function getActiveOsc8Close(prefix){
36
+ if(!prefix.includes("\x1B]8;"))return"";let activeHyperlink=null,i=0;for(;i<prefix.length;){let ansi=extractAnsiCode(prefix,i);if(ansi){let hyperlink2=parseOsc8Hyperlink(ansi.code);hyperlink2!==void 0&&(activeHyperlink=hyperlink2),i+=ansi.length}else i++}return activeHyperlink?formatOsc8Close(activeHyperlink.terminator):""}var AnsiCodeTracker=class{bold=!1;dim=!1;italic=!1;underline=!1;blink=!1;inverse=!1;hidden=!1;strikethrough=!1;fgColor=null;bgColor=null;activeHyperlink=null;process(ansiCode){
37
+ let hyperlink2=parseOsc8Hyperlink(ansiCode);if(hyperlink2!==void 0){this.activeHyperlink=hyperlink2;return}if(!ansiCode.endsWith("m"))return;let match=ansiCode.match(/\x1b\[([\d;]*)m/);if(!match)return;let params=match[1];if(params===""||params==="0"){this.reset();return}let parts=params.split(";"),i=0;for(;i<parts.length;){let code=Number.parseInt(parts[i],10);if(code===38||code===48){if(parts[i+1]==="5"&&parts[i+2]!==void 0){let colorCode=`${parts[i]};${parts[i+1]};${parts[i+2]}`;code===38?this.
38
+ fgColor=colorCode:this.bgColor=colorCode,i+=3;continue}else if(parts[i+1]==="2"&&parts[i+4]!==void 0){let colorCode=`${parts[i]};${parts[i+1]};${parts[i+2]};${parts[i+3]};${parts[i+4]}`;code===38?this.fgColor=colorCode:this.bgColor=colorCode,i+=5;continue}}switch(code){case 0:this.reset();break;case 1:this.bold=!0;break;case 2:this.dim=!0;break;case 3:this.italic=!0;break;case 4:this.underline=!0;break;case 5:this.blink=!0;break;case 7:this.inverse=!0;break;case 8:this.hidden=!0;break;case 9:this.
39
+ strikethrough=!0;break;case 21:this.bold=!1;break;case 22:this.bold=!1,this.dim=!1;break;case 23:this.italic=!1;break;case 24:this.underline=!1;break;case 25:this.blink=!1;break;case 27:this.inverse=!1;break;case 28:this.hidden=!1;break;case 29:this.strikethrough=!1;break;case 39:this.fgColor=null;break;case 49:this.bgColor=null;break;default:code>=30&&code<=37||code>=90&&code<=97?this.fgColor=String(code):(code>=40&&code<=47||code>=100&&code<=107)&&(this.bgColor=String(code));break}i++}}reset(){
40
+ this.bold=!1,this.dim=!1,this.italic=!1,this.underline=!1,this.blink=!1,this.inverse=!1,this.hidden=!1,this.strikethrough=!1,this.fgColor=null,this.bgColor=null}clear(){this.reset(),this.activeHyperlink=null}getActiveCodes(){let codes=[];this.bold&&codes.push("1"),this.dim&&codes.push("2"),this.italic&&codes.push("3"),this.underline&&codes.push("4"),this.blink&&codes.push("5"),this.inverse&&codes.push("7"),this.hidden&&codes.push("8"),this.strikethrough&&codes.push("9"),this.fgColor&&codes.push(
41
+ this.fgColor),this.bgColor&&codes.push(this.bgColor);let result=codes.length>0?`\x1B[${codes.join(";")}m`:"";return this.activeHyperlink&&(result+=formatOsc8Hyperlink(this.activeHyperlink)),result}getActiveBackgroundCode(){return this.bgColor?`\x1B[${this.bgColor}m`:""}hasActiveCodes(){return this.bold||this.dim||this.italic||this.underline||this.blink||this.inverse||this.hidden||this.strikethrough||this.fgColor!==null||this.bgColor!==null||this.activeHyperlink!==null}getLineEndReset(){let result="";
42
+ return this.underline&&(result+="\x1B[24m"),this.strikethrough&&(result+="\x1B[29m"),this.activeHyperlink&&(result+=formatOsc8Close(this.activeHyperlink.terminator)),result}};function updateTrackerFromText(text,tracker){let i=text.indexOf("\x1B");for(;i!==-1;){let length=ansiCodeLength(text,i);length>0?(tracker.process(text.substring(i,i+length)),i+=length):i++,i=text.indexOf("\x1B",i)}}function getActiveBackgroundAnsi(text){let tracker=new AnsiCodeTracker;return updateTrackerFromText(text,tracker),
43
+ tracker.getActiveBackgroundCode()}function*graphemeSegments(text){for(let{segment}of getGraphemeSegmenter().segment(text))yield segment}function splitIntoTokensWithAnsi(text,widths){let tokens=[],current="",currentWidth=0,pendingAnsi="",currentKind=null,i=0,flushCurrent=()=>{current&&(tokens.push(current),widths?.push(currentWidth),current="",currentWidth=0,currentKind=null)},addSegment=(segment,segmentIsSpace,segmentWidth)=>{let segmentKind=segmentIsSpace?"space":"word";current&&currentKind!==segmentKind&&
44
+ flushCurrent(),pendingAnsi&&(current+=pendingAnsi,pendingAnsi=""),currentKind=segmentKind,current+=segment,currentWidth=currentWidth<0||segmentWidth<0?-1:currentWidth+segmentWidth};for(;i<text.length;){let ansiResult=extractAnsiCode(text,i);if(ansiResult){pendingAnsi+=ansiResult.code,i+=ansiResult.length;continue}let end=text.indexOf("\x1B",i+1);for(;end!==-1&&ansiCodeLength(text,end)===0;)end=text.indexOf("\x1B",end+1);end===-1&&(end=text.length);let chunk=text.slice(i,end);if(isPrintableAscii(
45
+ chunk)){let start=0;for(;start<chunk.length;){let isSpace=chunk.charCodeAt(start)===32,runEnd=start+1;for(;runEnd<chunk.length&&chunk.charCodeAt(runEnd)===32===isSpace;)runEnd++;addSegment(start===0&&runEnd===chunk.length?chunk:chunk.slice(start,runEnd),isSpace,runEnd-start),start=runEnd}}else for(let segment of graphemeSegments(chunk)){let segmentIsSpace=segment===" ";if(!segmentIsSpace&&cjkBreakRegex.test(segment)){flushCurrent();let token=pendingAnsi+segment;pendingAnsi="",tokens.push(token),
46
+ widths?.push(-1);continue}addSegment(segment,segmentIsSpace,-1)}i=end}return pendingAnsi&&(current?current+=pendingAnsi:tokens.length>0?tokens[tokens.length-1]+=pendingAnsi:current=pendingAnsi),current&&(tokens.push(current),widths?.push(currentWidth)),tokens}var INTERNED_LINE_LENGTH=32,internedLines=new Map,INTERNED_LINES_KEPT=1024;function internLine(line){let known=internedLines.get(line);return known!==void 0?known:(internedLines.size>=INTERNED_LINES_KEPT&&internedLines.clear(),internedLines.set(line,line),line)}function flattenLines(lines){for(let line of lines)Number(line)}function wrapTextWithAnsi(text,width){if(!text)return[""];if(text.indexOf(`
47
+ `)===-1&&text.indexOf("\r")===-1)return wrapSingleLine(text,width);let inputLines=text.split(/\r\n|\r|\n/),result=[],tracker=new AnsiCodeTracker;for(let index=0;index<inputLines.length;index++){let inputLine=inputLines[index],prefix=result.length>0?tracker.getActiveCodes():"",wrappedLines=wrapSingleLine(prefix+inputLine,width);for(let wrappedLine of wrappedLines)result.push(wrappedLine);index<inputLines.length-1&&updateTrackerFromText(inputLine,tracker)}return result.length>0?result:[""]}var MAX_ASCII_SCAN_LENGTH=4096,
48
+ scannedEnds=new Int32Array(64),scannedInfo=new Int32Array(64),scannedCount=0;function addScannedToken(end,width,spaces,codes){if(scannedCount===scannedEnds.length){let ends=new Int32Array(scannedCount*2);ends.set(scannedEnds),scannedEnds=ends;let info=new Int32Array(scannedCount*2);info.set(scannedInfo),scannedInfo=info}scannedEnds[scannedCount]=end,scannedInfo[scannedCount]=width<<2|(codes?2:0)|(spaces?1:0),scannedCount++}function scanPrintableAscii(text){if(scannedCount=0,text.length>MAX_ASCII_SCAN_LENGTH)
49
+ return-1;let total=0,tokenStart=0,tokenWidth=0,tokenCodes=!1,kind=0,i=0;for(;i<text.length;){let code=text.charCodeAt(i);if(code===27){let codesStart=i;do{let length=ansiCodeLength(text,i);if(length===0)return-1;i+=length}while(i<text.length&&text.charCodeAt(i)===27);if(i<text.length){let nextKind=text.charCodeAt(i)===32?1:2;if(kind!==0&&kind!==nextKind){addScannedToken(codesStart,tokenWidth,kind===1,tokenCodes),tokenStart=codesStart,tokenCodes=!0,tokenWidth=0,kind=nextKind;continue}}tokenCodes=
50
+ !0;continue}if(code<32||code>126)return-1;let charKind=code===32?1:2;kind!==charKind&&(kind!==0&&(addScannedToken(i,tokenWidth,kind===1,tokenCodes),tokenStart=i,tokenWidth=0,tokenCodes=!1),kind=charKind),tokenWidth++,total++,i++}return tokenStart<text.length&&addScannedToken(text.length,tokenWidth,kind!==2,tokenCodes),total}function wrapScannedLine(line,width){let wrapped=[],tracker=new AnsiCodeTracker,tracked=!1,currentLine="",currentVisibleLength=0,start=0;for(let index=0;index<scannedCount;index++){
51
+ let end=scannedEnds[index],info=scannedInfo[index],token=line.slice(start,end);start=end;let tokenVisibleLength=info>>2,isWhitespace=(info&1)!==0,hasCodes=(info&2)!==0;if(tokenVisibleLength>width&&!isWhitespace)return;let totalNeeded=currentVisibleLength+tokenVisibleLength;if(totalNeeded>width&&currentVisibleLength>0){let lineToWrap=currentLine.trimEnd();if(isWhitespace&&hasCodes&&(lineToWrap+=extractAnsiCodes(token),updateTrackerFromText(token,tracker),tracked=!0),tracked){let lineEndReset=tracker.
52
+ getLineEndReset();lineEndReset&&(lineToWrap+=lineEndReset)}if(wrapped.push(lineToWrap),isWhitespace){currentLine=tracked?tracker.getActiveCodes():"",currentVisibleLength=0;continue}currentLine=tracked?tracker.getActiveCodes()+token:token,currentVisibleLength=tokenVisibleLength}else isWhitespace&&totalNeeded>width&&hasCodes?currentLine+=extractAnsiCodes(token):(currentLine+=token,currentVisibleLength+=tokenVisibleLength);hasCodes&&(updateTrackerFromText(token,tracker),tracked=!0)}return currentLine&&
53
+ wrapped.push(currentLine),wrapped.length>0?wrapped.map(wrappedLine=>wrappedLine.trimEnd()):[""]}function wrapSingleLine(line,width){if(!line)return[""];let scannedWidth=scanPrintableAscii(line);if(scannedWidth!==-1){if(scannedWidth<=width)return[line];let scannedLines=wrapScannedLine(line,width);if(scannedLines)return scannedLines}if((scannedWidth!==-1?scannedWidth:visibleWidth(line))<=width)return[line];let wrapped=[],tracker=new AnsiCodeTracker,widths=[],tokens=splitIntoTokensWithAnsi(line,widths),
54
+ currentLine="",currentVisibleLength=0;for(let index=0;index<tokens.length;index++){let token=tokens[index],knownWidth=widths[index],tokenVisibleLength=knownWidth>=0?knownWidth:visibleWidth(token),isWhitespace=isWhitespaceToken(token);if(tokenVisibleLength>width&&!isWhitespace){if(currentLine){currentLine=currentLine.trimEnd();let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),wrapped.push(currentLine),currentLine="",currentVisibleLength=0}let broken=breakLongWord(
55
+ token,width,tracker);for(let i=0;i<broken.length-1;i++)wrapped.push(broken[i]);currentLine=broken[broken.length-1],currentVisibleLength=visibleWidth(currentLine);continue}let totalNeeded=currentVisibleLength+tokenVisibleLength;if(totalNeeded>width&&currentVisibleLength>0){let lineToWrap=currentLine.trimEnd();isWhitespace&&(lineToWrap+=extractAnsiCodes(token),updateTrackerFromText(token,tracker));let lineEndReset=tracker.getLineEndReset();if(lineEndReset&&(lineToWrap+=lineEndReset),wrapped.push(lineToWrap),
56
+ isWhitespace){currentLine=tracker.getActiveCodes(),currentVisibleLength=0;continue}currentLine=tracker.getActiveCodes()+token,currentVisibleLength=tokenVisibleLength}else isWhitespace&&totalNeeded>width&&token.includes("\x1B")?currentLine+=extractAnsiCodes(token):(currentLine+=token,currentVisibleLength+=tokenVisibleLength);updateTrackerFromText(token,tracker)}return currentLine&&wrapped.push(currentLine),wrapped.length>0?wrapped.map(line2=>line2.trimEnd()):[""]}var PUNCTUATION_REGEX=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;
57
+ function isWhitespaceChar(char){return/\s/.test(char)}function breakLongWord(word,width,tracker){let lines=[],currentLine=tracker.getActiveCodes(),currentWidth=0,i=0,segments=[];for(;i<word.length;){let ansiResult=extractAnsiCode(word,i);if(ansiResult)segments.push({type:"ansi",value:ansiResult.code}),i+=ansiResult.length;else{let end=i;for(;end<word.length&&!extractAnsiCode(word,end);)end++;let textPortion=word.slice(i,end);for(let seg of getGraphemeSegmenter().segment(textPortion))segments.push({type:"grapheme",value:seg.segment});i=end}}for(let seg of segments){
58
+ if(seg.type==="ansi"){currentLine+=seg.value,tracker.process(seg.value);continue}let grapheme=seg.value;if(!grapheme)continue;let graphemeWidth2=visibleWidth(grapheme);if(currentWidth+graphemeWidth2>width){let lineEndReset=tracker.getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),lines.push(currentLine),currentLine=tracker.getActiveCodes(),currentWidth=0}currentLine+=grapheme,currentWidth+=graphemeWidth2}return currentLine&&lines.push(currentLine),lines.length>0?lines:[""]}function applyBackgroundToLine(line,width,bgFn){
59
+ let visibleLen=visibleWidth(line),paddingNeeded=Math.max(0,width-visibleLen),padding=" ".repeat(paddingNeeded),withPadding=line+padding;return bgFn(withPadding)}function truncateToWidth(text,maxWidth,ellipsis="...",pad=!1){if(maxWidth<=0)return"";if(text.length===0)return pad?" ".repeat(maxWidth):"";let ellipsisWidth=visibleWidth(ellipsis);if(ellipsisWidth>=maxWidth){let textWidth=visibleWidth(text);if(textWidth<=maxWidth)return pad?text+" ".repeat(maxWidth-textWidth):text;let clippedEllipsis=truncateFragmentToWidth(
60
+ ellipsis,maxWidth);return clippedEllipsis.width===0?pad?" ".repeat(maxWidth):"":finalizeTruncatedResult("",0,clippedEllipsis.text,clippedEllipsis.width,maxWidth,pad)}if(isPrintableAscii(text)){if(text.length<=maxWidth)return pad?text+" ".repeat(maxWidth-text.length):text;let targetWidth2=maxWidth-ellipsisWidth;return finalizeTruncatedResult(text.slice(0,targetWidth2),targetWidth2,ellipsis,ellipsisWidth,maxWidth,pad)}let asciiWidth=asciiVisibleWidth(text,maxWidth);if(asciiWidth>=0&&asciiWidth<=maxWidth)
61
+ return pad?text+" ".repeat(maxWidth-asciiWidth):text;let targetWidth=maxWidth-ellipsisWidth,result="",pendingAnsi="",visibleSoFar=0,keptWidth=0,keepContiguousPrefix=!0,overflowed=!1,exhaustedInput=!1,hasAnsi=text.includes("\x1B"),hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){for(let{segment}of getGraphemeSegmenter().segment(text)){let width=graphemeWidth(segment);if(keepContiguousPrefix&&keptWidth+width<=targetWidth?(result+=segment,keptWidth+=width):keepContiguousPrefix=!1,visibleSoFar+=width,
62
+ visibleSoFar>maxWidth){overflowed=!0;break}}exhaustedInput=!overflowed}else{let i=0;for(;i<text.length;){let ansi=extractAnsiCode(text,i);if(ansi){pendingAnsi+=ansi.code,i+=ansi.length;continue}if(text[i]===" "){if(keepContiguousPrefix&&keptWidth+3<=targetWidth?(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=" ",keptWidth+=3):(keepContiguousPrefix=!1,pendingAnsi=""),visibleSoFar+=3,visibleSoFar>maxWidth){overflowed=!0;break}i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&
63
+ !extractAnsiCode(text,end);)end++;for(let{segment}of getGraphemeSegmenter().segment(text.slice(i,end))){let width=graphemeWidth(segment);if(keepContiguousPrefix&&keptWidth+width<=targetWidth?(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,keptWidth+=width):(keepContiguousPrefix=!1,pendingAnsi=""),visibleSoFar+=width,visibleSoFar>maxWidth){overflowed=!0;break}}if(overflowed)break;i=end}exhaustedInput=i>=text.length}return!overflowed&&exhaustedInput?pad?text+" ".repeat(Math.max(
64
+ 0,maxWidth-visibleSoFar)):text:finalizeTruncatedResult(result,keptWidth,ellipsis,ellipsisWidth,maxWidth,pad)}function sliceByColumn(line,startCol,length,strict=!1){return sliceWithWidth(line,startCol,length,strict).text}function sliceWithWidth(line,startCol,length,strict=!1){if(length<=0)return{text:"",width:0};let endCol=startCol+length,result="",resultWidth=0,currentCol=0,i=0,pendingAnsi="";for(;i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){currentCol>=startCol&&currentCol<endCol?(result+=
65
+ pendingAnsi+ansi.code,pendingAnsi=""):currentCol<startCol&&!ansi.code.startsWith("\x1B_")&&(pendingAnsi+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of getGraphemeSegmenter().segment(line.slice(i,textEnd))){let w2=graphemeWidth(segment),inRange=currentCol>=startCol&&currentCol<endCol,fits=!strict||currentCol+w2<=endCol;if(inRange&&fits&&(pendingAnsi&&(result+=pendingAnsi,pendingAnsi=""),result+=segment,resultWidth+=
66
+ w2),currentCol+=w2,currentCol>=endCol)break}if(i=textEnd,currentCol>=endCol)break}return{text:result,width:resultWidth}}var pooledStyleTracker=new AnsiCodeTracker;function extractSegments(line,beforeEnd,afterStart,afterLen,strictAfter=!1){let before="",beforeWidth=0,after="",afterWidth=0,currentCol=0,i=0,pendingAnsiBefore="",afterStarted=!1,afterEnd=afterStart+afterLen;for(pooledStyleTracker.clear();i<line.length;){let ansi=extractAnsiCode(line,i);if(ansi){pooledStyleTracker.process(ansi.code),currentCol<
67
+ beforeEnd?pendingAnsiBefore+=ansi.code:currentCol>=afterStart&&currentCol<afterEnd&&(afterStarted||ansi.code.startsWith("\x1B_"))&&(after+=ansi.code),i+=ansi.length;continue}let textEnd=i;for(;textEnd<line.length&&!extractAnsiCode(line,textEnd);)textEnd++;for(let{segment}of getGraphemeSegmenter().segment(line.slice(i,textEnd))){let w2=graphemeWidth(segment);if(currentCol<beforeEnd&&currentCol+w2<=beforeEnd?(pendingAnsiBefore&&(before+=pendingAnsiBefore,pendingAnsiBefore=""),before+=segment,beforeWidth+=
68
+ w2):currentCol>=afterStart&&currentCol<afterEnd&&(!strictAfter||currentCol+w2<=afterEnd)&&(afterStarted||(after+=pooledStyleTracker.getActiveCodes(),afterStarted=!0),after+=segment,afterWidth+=w2),currentCol+=w2,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}if(i=textEnd,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}return{before,beforeWidth,after,afterWidth}}import{spawn}from"child_process";import{readdirSync,statSync}from"fs";import{homedir}from"os";import{basename,dirname,join}from"path";var PATH_DELIMITERS=new Set([" "," ",'"',"'","="]),tokenStartRegex=new RegExp(`${autocompleteBoundaryRegex.source}$`,"u"),PATH_WRAPPERS={"(":")","[":"]","{":"}","<":">","`":"`"};function toDisplayPath(value){return value.replace(/\\/g,"/")}function escapeRegex(value){return value.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function buildFdPathQuery(query){let normalized=toDisplayPath(query);if(!normalized.includes("/"))return escapeRegex(normalized);let hasTrailingSeparator=normalized.endsWith("/"),trimmed=normalized.
69
+ replace(/^\/+|\/+$/g,"");if(!trimmed)return normalized;let separatorPattern="[\\\\/]",pattern=trimmed.split("/").filter(Boolean).map(segment=>escapeRegex(segment)).join(separatorPattern);return hasTrailingSeparator&&(pattern+=separatorPattern),pattern}function findLastDelimiter(text){let lastDelimiter=-1,index=0;for(let character of text)index+=character.length,(PATH_DELIMITERS.has(character)||autocompleteSeparatorRegex.test(character))&&(lastDelimiter=index-1);return lastDelimiter}function stripLeadingWrappers(token){
70
+ let result=token;for(;result.length>0;){let closer=PATH_WRAPPERS[result[0]];if(!closer||result.includes(closer,1))break;result=result.slice(1)}return result}function findUnclosedQuoteStart(text){let inQuotes=!1,quoteStart=-1;for(let i=0;i<text.length;i+=1)text[i]==='"'&&(inQuotes=!inQuotes,inQuotes&&(quoteStart=i));return inQuotes?quoteStart:null}function isTokenStart(text,index){let start=index;for(;start>0&&PATH_WRAPPERS[text[start-1]];)start-=1;return PATH_DELIMITERS.has(text[start-1]??"")||tokenStartRegex.
71
+ test(text.slice(0,start))}function extractQuotedPrefix(text){let quoteStart=findUnclosedQuoteStart(text);return quoteStart===null?null:quoteStart>0&&text[quoteStart-1]==="@"?isTokenStart(text,quoteStart-1)?text.slice(quoteStart-1):null:isTokenStart(text,quoteStart)?text.slice(quoteStart):null}function parsePathPrefix(prefix){return prefix.startsWith('@"')?{rawPrefix:prefix.slice(2),isAtPrefix:!0,isQuotedPrefix:!0}:prefix.startsWith('"')?{rawPrefix:prefix.slice(1),isAtPrefix:!1,isQuotedPrefix:!0}:
72
+ prefix.startsWith("@")?{rawPrefix:prefix.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:prefix,isAtPrefix:!1,isQuotedPrefix:!1}}function buildCompletionValue(path4,options){let needsQuotes=options.isQuotedPrefix||autocompleteSeparatorRegex.test(path4),prefix=options.isAtPrefix?"@":"";return needsQuotes?`${`${prefix}"`}${path4}"`:`${prefix}${path4}`}async function walkDirectoryWithFd(baseDir,fdPath,query,maxResults,signal,maxDepth){return(await runFdWalk(baseDir,fdPath,query,maxResults,signal,
73
+ maxDepth))?.entries??[]}function fdWalkArgs(baseDir,query,maxResults,maxDepth){let args=["--base-directory",baseDir,"--max-results",String(maxResults),"--type","f","--type","d","--follow","--hidden","--exclude",".git","--exclude",".git/*","--exclude",".git/**"];return maxDepth!==void 0&&args.push("--max-depth",String(maxDepth)),toDisplayPath(query).includes("/")&&args.push("--full-path"),query&&args.push(buildFdPathQuery(query)),args}function parseFdLine(line){let displayLine=toDisplayPath(line),
74
+ hasTrailingSeparator=displayLine.endsWith("/"),normalizedPath=hasTrailingSeparator?displayLine.slice(0,-1):displayLine;if(!(normalizedPath===".git"||normalizedPath.startsWith(".git/")||normalizedPath.includes("/.git/")))return{path:displayLine,isDirectory:hasTrailingSeparator}}function runFd(fdPath,args,signal,onOutput){return new Promise(resolve=>{if(signal?.aborted){resolve(!1);return}let child=spawn(fdPath,args,{stdio:["ignore","pipe","pipe"]}),resolved=!1,finish=ok=>{resolved||(resolved=!0,signal?.
75
+ removeEventListener("abort",onAbort),resolve(ok))},onAbort=()=>{child.exitCode===null&&child.kill("SIGKILL")};signal?.addEventListener("abort",onAbort,{once:!0}),child.stdout.setEncoding("utf-8"),child.stdout.on("data",onOutput),child.on("error",()=>{finish(!1)}),child.on("close",code=>{finish(!signal?.aborted&&code===0)})})}async function runFdWalk(baseDir,fdPath,query,maxResults,signal,maxDepth){let stdout="";if(!await runFd(fdPath,fdWalkArgs(baseDir,query,maxResults,maxDepth),signal,chunk=>{stdout+=
76
+ chunk}))return;if(!stdout)return{entries:[],lineCount:0};let lines=stdout.trim().split(`
77
+ `).filter(Boolean),results=[];for(let line of lines){let entry=parseFdLine(line);entry&&results.push(entry)}return{entries:results,lineCount:lines.length}}async function runFdListing(baseDir,fdPath,maxEntries,signal){let entries=[],lineCount=0,partial="",ok=await runFd(fdPath,fdWalkArgs(baseDir,"",maxEntries+1),signal,chunk=>{let lines=(partial+chunk).split(`
78
+ `);partial=lines.pop();for(let line of lines){if(!line)continue;lineCount++;let entry=parseFdLine(line);entry&&entries.push(indexFdEntry(entry))}});if(partial){lineCount++;let entry=parseFdLine(partial);entry&&entries.push(indexFdEntry(entry))}return ok&&lineCount<=maxEntries?entries:void 0}function indexFdEntry(entry){let path4=entry.isDirectory?entry.path.slice(0,-1):entry.path,slash=path4.lastIndexOf("/"),name=path4.slice(slash+1);return{path:entry.path,isDirectory:entry.isDirectory,name,topLevel:slash===
79
+ -1}}function isPlainFdQuery(query){return!query.startsWith("-")&&!/[\\/+*?()|[\]{}^$\x00-\x1f\x7f\uD800-\uDFFF]/.test(query)}function createFdNameMatcher(query){if(query==="")return()=>!0;let regex=new RegExp(escapeRegex(query),new RegExp("\\p{Uppercase}","u").test(query)?"su":"isu");return entry=>regex.test(entry.name)}function selectFdResults(matches,maxResults){let baseDirEntries=[],recursiveEntries=[];for(let entry of matches)if(recursiveEntries.length<maxResults&&recursiveEntries.push(entry),
80
+ entry.topLevel&&baseDirEntries.length<maxResults&&baseDirEntries.push(entry),recursiveEntries.length>=maxResults&&baseDirEntries.length>=maxResults)break;return{baseDirEntries,recursiveEntries}}var FD_MAX_RESULTS=100,FD_INDEX_MAX_ENTRIES=1e5,FD_INDEX_STALE_MS=3e3,FD_INDEX_RETRY_MS=6e5,FD_INDEX_MAX_FOLDERS=8,FdFolderIndex=class{fdPath;baseDir;generation=0;sessionGeneration=0;listing;narrowed;building;unusableUntil=0;constructor(fdPath,baseDir){this.fdPath=fdPath,this.baseDir=baseDir}startSession(){
81
+ if(Date.now()<this.unusableUntil){this.sessionGeneration=++this.generation;return}this.sessionGeneration=this.build()}cancelListing(){this.building?.abort.abort(),this.building=void 0}readyListFor(query){let now=Date.now(),narrowed=this.narrowed;if(narrowed&&narrowed.generation>=this.sessionGeneration&&query.startsWith(narrowed.query)&&(narrowed.fromListing?narrowed.generation===this.listing?.generation:now-narrowed.walkedAt<=FD_INDEX_STALE_MS))return narrowed.fromListing&&this.refreshIfStale(narrowed,
82
+ now),narrowed;if(this.listing&&this.listing.generation>=this.sessionGeneration)return this.refreshIfStale(this.listing,now),this.listing}pendingListing(){return this.building&&this.building.generation>=this.sessionGeneration?this.building.promise:void 0}setNarrowed(list){this.narrowed=list}setCompleteResult(query,entries,walkedAt){this.narrowed={query,entries:entries.map(indexFdEntry),generation:this.sessionGeneration,walkedAt,fromListing:!1}}refreshIfStale(list,now){now-list.walkedAt>FD_INDEX_STALE_MS&&
83
+ !this.building&&now>=this.unusableUntil&&this.build()}build(){this.cancelListing();let generation2=++this.generation,walkedAt=Date.now(),abort=new AbortController,promise=runFdListing(this.baseDir,this.fdPath,FD_INDEX_MAX_ENTRIES,abort.signal).catch(()=>{}).then(entries=>{if(this.building?.generation===generation2&&(this.building=void 0),abort.signal.aborted)return;if(!entries){this.unusableUntil=Date.now()+FD_INDEX_RETRY_MS;return}let list={query:"",entries,generation:generation2,walkedAt,fromListing:!0};
84
+ return(!this.listing||this.listing.generation<generation2)&&(this.listing=list),list});return this.building={generation:generation2,promise,abort},generation2}},CombinedAutocompleteProvider=class{commands;basePath;fdPath;fdIndexes=new Map;fdSessionKey;fdSessionIndex;constructor(commands=[],basePath,fdPath=null){this.commands=commands,this.basePath=basePath,this.fdPath=fdPath}async getSuggestions(lines,cursorLine,cursorCol,options){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol),atPrefix=this.
85
+ extractAtPrefix(textBeforeCursor);if(atPrefix){let{rawPrefix,isQuotedPrefix}=parsePathPrefix(atPrefix),suggestions2=await this.getFuzzyFileSuggestions(rawPrefix,{isQuotedPrefix,signal:options.signal,tokenKey:`${cursorLine}\0${textBeforeCursor.slice(0,textBeforeCursor.length-atPrefix.length)}`});return suggestions2.length===0?null:{items:suggestions2,prefix:atPrefix}}let commandText=textBeforeCursor.trimStart();if(!options.force&&commandText.startsWith("/")){let spaceIndex=commandText.indexOf(" ");
86
+ if(spaceIndex===-1){let prefix=commandText.slice(1),commandItems=this.commands.map(cmd=>{let name="name"in cmd?cmd.name:cmd.value,hint="argumentHint"in cmd&&cmd.argumentHint?cmd.argumentHint:void 0,desc=cmd.description??"",fullDesc=hint?desc?`${hint} \u2014 ${desc}`:hint:desc;return{name,label:name,description:fullDesc||void 0}}),bareNameMatches=fuzzyFilter(commandItems,prefix,item=>item.name.startsWith("skill:")?item.name.slice(6):item.name),bareNameMatchSet=new Set(bareNameMatches),fullNameOnlyMatches=fuzzyFilter(
87
+ commandItems.filter(item=>item.name.startsWith("skill:")&&!bareNameMatchSet.has(item)),prefix,item=>item.name),filtered=[...bareNameMatches,...fullNameOnlyMatches].map(item=>({value:item.name,label:item.label,...item.description&&{description:item.description}}));return filtered.length===0?null:{items:filtered,prefix:commandText}}let commandName=commandText.slice(1,spaceIndex),argumentText=commandText.slice(spaceIndex+1),command=this.commands.find(cmd=>("name"in cmd?cmd.name:cmd.value)===commandName);
88
+ if(!command||!("getArgumentCompletions"in command)||!command.getArgumentCompletions)return null;let argumentSuggestions=await command.getArgumentCompletions(argumentText);return!Array.isArray(argumentSuggestions)||argumentSuggestions.length===0?null:{items:argumentSuggestions,prefix:argumentText}}let pathMatch=this.extractPathPrefix(textBeforeCursor,options.force??!1);if(pathMatch===null)return null;let suggestions=this.getFileSuggestions(pathMatch);return suggestions.length===0?null:{items:suggestions,
89
+ prefix:pathMatch}}applyCompletion(lines,cursorLine,cursorCol,item,prefix){let currentLine=lines[cursorLine]||"",beforePrefix=currentLine.slice(0,cursorCol-prefix.length),afterCursor=currentLine.slice(cursorCol),isQuotedPrefix=prefix.startsWith('"')||prefix.startsWith('@"'),hasLeadingQuoteAfterCursor=afterCursor.startsWith('"'),hasTrailingQuoteInItem=item.value.endsWith('"'),adjustedAfterCursor=isQuotedPrefix&&hasTrailingQuoteInItem&&hasLeadingQuoteAfterCursor?afterCursor.slice(1):afterCursor;if(prefix.
90
+ startsWith("/")&&beforePrefix.trim()===""&&!prefix.slice(1).includes("/")){let newLine2=`${beforePrefix}/${item.value} ${adjustedAfterCursor}`,newLines2=[...lines];return newLines2[cursorLine]=newLine2,{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+item.value.length+2}}if(prefix.startsWith("@")){let isDirectory2=item.label.endsWith("/"),suffix=isDirectory2?"":" ",newLine2=`${beforePrefix+item.value}${suffix}${adjustedAfterCursor}`,newLines2=[...lines];newLines2[cursorLine]=newLine2;let hasTrailingQuote2=item.
91
+ value.endsWith('"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2+suffix.length}}let textBeforeCursor=currentLine.slice(0,cursorCol);if(textBeforeCursor.includes("/")&&textBeforeCursor.includes(" ")){let newLine2=beforePrefix+item.value+adjustedAfterCursor,newLines2=[...lines];newLines2[cursorLine]=newLine2;let isDirectory2=item.label.endsWith("/"),hasTrailingQuote2=item.value.endsWith(
92
+ '"'),cursorOffset2=isDirectory2&&hasTrailingQuote2?item.value.length-1:item.value.length;return{lines:newLines2,cursorLine,cursorCol:beforePrefix.length+cursorOffset2}}let newLine=beforePrefix+item.value+adjustedAfterCursor,newLines=[...lines];newLines[cursorLine]=newLine;let isDirectory=item.label.endsWith("/"),hasTrailingQuote=item.value.endsWith('"'),cursorOffset=isDirectory&&hasTrailingQuote?item.value.length-1:item.value.length;return{lines:newLines,cursorLine,cursorCol:beforePrefix.length+
93
+ cursorOffset}}extractAtPrefix(text){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix?.startsWith('@"'))return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),token=stripLeadingWrappers(lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return token.startsWith("@")?token:null}extractPathPrefix(text,forceExtract=!1){let quotedPrefix=extractQuotedPrefix(text);if(quotedPrefix)return quotedPrefix;let lastDelimiterIndex=findLastDelimiter(text),pathPrefix=stripLeadingWrappers(
94
+ lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return forceExtract||pathPrefix.includes("/")||pathPrefix.startsWith(".")||pathPrefix.startsWith("~/")||pathPrefix===""&&text!==""&&tokenStartRegex.test(text)?pathPrefix:null}expandHomePath(path4){if(path4.startsWith("~/")){let expandedPath=join(homedir(),path4.slice(2));return path4.endsWith("/")&&!expandedPath.endsWith("/")?`${expandedPath}/`:expandedPath}else if(path4==="~")return homedir();return path4}resolveScopedFuzzyQuery(rawQuery){
95
+ let normalizedQuery=toDisplayPath(rawQuery),slashIndex=normalizedQuery.lastIndexOf("/");if(slashIndex===-1)return null;let displayBase=normalizedQuery.slice(0,slashIndex+1),query=normalizedQuery.slice(slashIndex+1),baseDir;displayBase.startsWith("~/")?baseDir=this.expandHomePath(displayBase):displayBase.startsWith("/")?baseDir=displayBase:baseDir=join(this.basePath,displayBase);try{if(!statSync(baseDir).isDirectory())return null}catch{return null}return{baseDir,query,displayBase}}scopedPathForDisplay(displayBase,relativePath){
96
+ let normalizedRelativePath=toDisplayPath(relativePath);return displayBase==="/"?`/${normalizedRelativePath}`:`${toDisplayPath(displayBase)}${normalizedRelativePath}`}getFileSuggestions(prefix){try{let searchDir,searchPrefix,{rawPrefix,isAtPrefix,isQuotedPrefix}=parsePathPrefix(prefix),expandedPrefix=rawPrefix;if(expandedPrefix.startsWith("~")&&(expandedPrefix=this.expandHomePath(expandedPrefix)),rawPrefix===""||rawPrefix==="./"||rawPrefix==="../"||rawPrefix==="~"||rawPrefix==="~/"||rawPrefix==="\
97
+ /"||isAtPrefix&&rawPrefix==="")rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join(this.basePath,expandedPrefix),searchPrefix="";else if(rawPrefix.endsWith("/"))rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=expandedPrefix:searchDir=join(this.basePath,expandedPrefix),searchPrefix="";else{let dir=dirname(expandedPrefix),file=basename(expandedPrefix);rawPrefix.startsWith("~")||expandedPrefix.startsWith("/")?searchDir=dir:searchDir=
98
+ join(this.basePath,dir),searchPrefix=file}let entries=readdirSync(searchDir,{withFileTypes:!0}),suggestions=[];for(let entry of entries){if(!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase()))continue;let isDirectory=entry.isDirectory();if(!isDirectory&&entry.isSymbolicLink())try{let fullPath=join(searchDir,entry.name);isDirectory=statSync(fullPath).isDirectory()}catch{}let relativePath,name=entry.name,displayPrefix=rawPrefix;if(displayPrefix.endsWith("/"))relativePath=displayPrefix+
99
+ name;else if(displayPrefix.includes("/")||displayPrefix.includes("\\"))if(displayPrefix.startsWith("~/")){let homeRelativeDir=displayPrefix.slice(2),dir=dirname(homeRelativeDir);relativePath=`~/${dir==="."?name:join(dir,name)}`}else if(displayPrefix.startsWith("/")){let dir=dirname(displayPrefix);dir==="/"?relativePath=`/${name}`:relativePath=`${dir}/${name}`}else relativePath=join(dirname(displayPrefix),name),displayPrefix.startsWith("./")&&!relativePath.startsWith("./")&&(relativePath=`./${relativePath}`);else
100
+ displayPrefix.startsWith("~")?relativePath=`~/${name}`:relativePath=name;relativePath=toDisplayPath(relativePath);let pathValue=isDirectory?`${relativePath}/`:relativePath,value=buildCompletionValue(pathValue,{isDirectory,isAtPrefix,isQuotedPrefix});suggestions.push({value,label:name+(isDirectory?"/":"")})}return suggestions.sort((a,b)=>{let aIsDir=a.label.endsWith("/"),bIsDir=b.label.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a.label.localeCompare(b.label)}),suggestions}catch{return[]}}scoreEntry(filePath,query,isDirectory){
101
+ let lowerFileName=basename(filePath).toLowerCase(),lowerQuery=query.toLowerCase(),score=0;return lowerFileName===lowerQuery?score=100:lowerFileName.startsWith(lowerQuery)?score=80:lowerFileName.includes(lowerQuery)?score=50:filePath.toLowerCase().includes(lowerQuery)&&(score=30),isDirectory&&score>0&&(score+=10),score}async getBaseDirSuggestions(baseDir,query,signal){return!this.fdPath||signal.aborted?[]:await walkDirectoryWithFd(baseDir,this.fdPath,query,100,signal,1)}async getFuzzyFileSuggestions(query,options){
102
+ if(!this.fdPath||options.signal.aborted)return[];try{let scopedQuery=this.resolveScopedFuzzyQuery(query),fdBaseDir=scopedQuery?.baseDir??this.basePath,fdQuery=scopedQuery?.query??query,results=isPlainFdQuery(fdQuery)?await this.getIndexedFdResults(fdBaseDir,fdQuery,options.tokenKey,options.signal):await this.runFdForQuery(fdBaseDir,fdQuery,options.signal);return options.signal.aborted?[]:this.rankFdResults(results.baseDirEntries,results.recursiveEntries,fdQuery,scopedQuery,options)}catch{return[]}}async runFdForQuery(fdBaseDir,fdQuery,signal){
103
+ let[baseDirEntries,recursive]=await Promise.all([this.getBaseDirSuggestions(fdBaseDir,fdQuery,signal),this.fdPath?runFdWalk(fdBaseDir,this.fdPath,fdQuery,FD_MAX_RESULTS,signal):void 0]);return{baseDirEntries,recursiveEntries:recursive?.entries??[],recursiveLineCount:recursive?.lineCount}}async getIndexedFdResults(fdBaseDir,fdQuery,tokenKey,signal){let index=this.fdIndexes.get(fdBaseDir);if(index)this.fdIndexes.delete(fdBaseDir);else if(index=new FdFolderIndex(this.fdPath,fdBaseDir),this.fdIndexes.
104
+ size>=FD_INDEX_MAX_FOLDERS){let oldest=this.fdIndexes.keys().next().value;this.fdIndexes.get(oldest)?.cancelListing(),this.fdIndexes.delete(oldest)}this.fdIndexes.set(fdBaseDir,index);let sessionKey=`${fdBaseDir}\0${tokenKey}`;sessionKey!==this.fdSessionKey&&(this.fdSessionIndex!==index&&this.fdSessionIndex?.cancelListing(),this.fdSessionKey=sessionKey,this.fdSessionIndex=index,index.startSession());let ready=index.readyListFor(fdQuery);if(ready)return this.filterFdList(index,ready,fdQuery);let fdAbort=new AbortController,
105
+ abortFd=()=>fdAbort.abort();signal.addEventListener("abort",abortFd,{once:!0});try{let walkedAt=Date.now(),viaFd=this.runFdForQuery(fdBaseDir,fdQuery,fdAbort.signal).then(results2=>({results:results2})),viaListing=index.pendingListing()?.then(list=>list?{list}:viaFd),first=await(viaListing?Promise.race([viaListing,viaFd]):viaFd);if(signal.aborted)return{baseDirEntries:[],recursiveEntries:[]};if("list"in first)return fdAbort.abort(),this.filterFdList(index,first.list,fdQuery);let{results}=first;return results.
106
+ recursiveLineCount!==void 0&&results.recursiveLineCount<FD_MAX_RESULTS&&index.setCompleteResult(fdQuery,results.recursiveEntries,walkedAt),results}finally{signal.removeEventListener("abort",abortFd)}}filterFdList(index,list,fdQuery){let matches=list.query===fdQuery?list.entries:list.entries.filter(createFdNameMatcher(fdQuery));return index.setNarrowed({...list,query:fdQuery,entries:matches}),selectFdResults(matches,FD_MAX_RESULTS)}rankFdResults(baseDirEntries,recursiveEntries,fdQuery,scopedQuery,options){
107
+ let seenPaths=new Set(baseDirEntries.map(entry=>entry.path)),scoredEntries=[...baseDirEntries,...recursiveEntries.filter(entry=>seenPaths.has(entry.path)?!1:(seenPaths.add(entry.path),!0))].map(entry=>({path:entry.path,isDirectory:entry.isDirectory,score:fdQuery?this.scoreEntry(entry.path,fdQuery,entry.isDirectory):1})).filter(entry=>entry.score>0);scoredEntries.sort((a,b)=>{let scoreDiff=b.score-a.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a.path).split("/").filter(Boolean).
108
+ length,bDepth=toDisplayPath(b.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a.path.length-b.path.length;return lengthDiff!==0?lengthDiff:a.path.localeCompare(b.path)});let topEntries=scoredEntries.slice(0,20),suggestions=[];for(let{path:entryPath,isDirectory}of topEntries){let pathWithoutSlash=isDirectory?entryPath.slice(0,-1):entryPath,displayPath=scopedQuery?this.scopedPathForDisplay(scopedQuery.displayBase,pathWithoutSlash):pathWithoutSlash,
109
+ entryName=basename(pathWithoutSlash),completionPath=isDirectory?`${displayPath}/`:displayPath,value=buildCompletionValue(completionPath,{isDirectory,isAtPrefix:!0,isQuotedPrefix:options.isQuotedPrefix});suggestions.push({value,label:entryName+(isDirectory?"/":""),description:displayPath})}return suggestions}shouldTriggerFileCompletion(lines,cursorLine,cursorCol){let textBeforeCursor=(lines[cursorLine]||"").slice(0,cursorCol);return!(textBeforeCursor.trim().startsWith("/")&&!textBeforeCursor.trim().
110
+ includes(" "))}};var multiply=(m,[x2,y2,z2])=>m.map(row=>row[0]*x2+row[1]*y2+row[2]*z2),LINEAR_SRGB_TO_LMS=[[.4122214694707629,.5363325372617349,.0514459932675022],[.2119034958178251,.6806995506452344,.1073969535369405],[.0883024591900564,.2817188391361215,.6299787016738222]],LMS_TO_LAB=[[.210454268309314,.793617774702305,-.0040720430116193],[1.9779985324311684,-2.42859224204858,.450593709617411],[.0259040424655478,.7827717124575296,-.8086757549230774]],LAB_TO_LMS=[[1,.3963377773761749,.2158037573099136],[1,-.1055613458156586,
111
+ -.0638541728258133],[1,-.0894841775298119,-1.2914855480194092]],LMS_TO_LINEAR_SRGB=[[4.076741636075958,-3.307711539258063,.2309699031821043],[-1.2684379732850315,2.609757349287688,-.341319376002657],[-.0041960761386756,-.7034186179359362,1.7076146940746117]],SATURATION_FIT=[[[-1.8817031,-.80936501],[1.19086277,1.76576728,.59662641,.75515197,.56771245]],[[1.8144408,-1.19445267],[.73956515,-.45954404,.08285427,.12541073,-.14503204]],[[.13110758,1.81333971],[1.35733652,-.00915799,-1.1513021,-.50559606,
112
+ .00692167]]],K1=.206,K2=.03,K3=(1+K1)/(1+K2),oklabToOkhslLightness=x2=>.5*(K3*x2-K1+Math.sqrt((K3*x2-K1)**2+4*K2*K3*x2)),okhslToOklabLightness=x2=>(x2*x2+K1*x2)/(K3*(x2+K2)),linearToSrgb=value=>value>.0031308?1.055*value**(1/2.4)-.055:12.92*value,srgbToLinear=value=>value<=.04045?value/12.92:((value+.055)/1.055)**2.4;function oklabToLinearSrgb(lab){return multiply(LMS_TO_LINEAR_SRGB,multiply(LAB_TO_LMS,lab).map(value=>value**3))}function linearSrgbToOklab(rgb){return multiply(LMS_TO_LAB,multiply(
113
+ LINEAR_SRGB_TO_LMS,rgb).map(Math.cbrt))}function rgbToOklab({r,g,b}){return linearSrgbToOklab([r/255,g/255,b/255].map(srgbToLinear))}function linearSrgbToRgb(linear){let[r,g,b]=linear.map(value=>Math.round(Math.min(1,Math.max(0,linearToSrgb(value)))*255));return{r,g,b}}function lmsSlopes(a,b){return[LAB_TO_LMS[0],LAB_TO_LMS[1],LAB_TO_LMS[2]].map(row=>row[1]*a+row[2]*b)}function maxSaturation(a,b){let channel=SATURATION_FIT.findIndex(([[x2,y2]],index)=>index===2||x2*a+y2*b>1),[k0,k1,k2,k3,k4]=SATURATION_FIT[channel][1],
114
+ weights=LMS_TO_LINEAR_SRGB[channel],saturation=k0+k1*a+k2*b+k3*a*a+k4*a*b,slopes=lmsSlopes(a,b),base=slopes.map(k=>1+saturation*k),dot=values=>values.reduce((sum,value,index)=>sum+weights[index]*value,0),f=dot(base.map(value=>value**3)),f1=dot(base.map((value,index)=>3*slopes[index]*value**2)),f2=dot(base.map((value,index)=>6*slopes[index]**2*value));return saturation-f*f1/(f1*f1-.5*f*f2)}function cusp(a,b){let saturation=maxSaturation(a,b),lightness=Math.cbrt(1/Math.max(...oklabToLinearSrgb([1,
115
+ saturation*a,saturation*b])));return[lightness,lightness*saturation]}function maxChroma(a,b,lightness,[cuspL,cuspC]){if(lightness<=cuspL)return cuspC*lightness/cuspL;let t=cuspC*(lightness-1)/(cuspL-1),slopes=lmsSlopes(a,b),lms=slopes.map(k=>lightness+t*k),cubes=lms.map(value=>value**3),first=lms.map((value,index)=>3*slopes[index]*value**2),second=lms.map((value,index)=>6*slopes[index]**2*value),dot=(row,values)=>row[0]*values[0]+row[1]*values[1]+row[2]*values[2],steps=LMS_TO_LINEAR_SRGB.map(row=>{
116
+ let f=dot(row,cubes)-1,f1=dot(row,first),f2=dot(row,second),u=f1/(f1*f1-.5*f*f2);return u>=0?-f*u:Number.MAX_VALUE});return t+Math.min(...steps)}function chromaStops(L2,a,b){let peak=cusp(a,b),cMax=maxChroma(a,b,L2,peak),k=cMax/Math.min(L2*(peak[1]/peak[0]),(1-L2)*(peak[1]/(1-peak[0]))),midS=.11516993+1/(7.4477897+4.1590124*b+a*(-2.19557347+1.75198401*b+a*(-2.13704948-10.02301043*b+a*(-4.24894561+5.38770819*b+4.69891013*a)))),midT=.11239642+1/(1.6132032-.68124379*b+a*(.40370612+.90148123*b+a*(-.27087943+
117
+ .6122399*b+a*(.00299215-.45399568*b-.14661872*a)))),cMid=.9*k*Math.sqrt(Math.sqrt(1/(1/(L2*midS)**4+1/((1-L2)*midT)**4)));return[Math.sqrt(1/(1/(L2*.4)**2+1/((1-L2)*.8)**2)),cMid,cMax]}function okhslToRgb(hue,saturation,lightness){let L2=okhslToOklabLightness(lightness),lab=[L2,0,0];if(L2>0&&L2<1&&saturation>0){let angle=2*Math.PI*((hue%360+360)%360)/360,a=Math.cos(angle),b=Math.sin(angle),[c0,cMid,cMax]=chromaStops(L2,a,b),chroma;if(saturation<.8){let t=1.25*saturation,k1=.8*c0;chroma=t*k1/(1-(1-
118
+ k1/cMid)*t)}else{let t=5*(saturation-.8),k1=.2*cMid**2*1.25**2/c0;chroma=cMid+t*k1/(1-(1-k1/(cMax-cMid))*t)}lab=[L2,chroma*a,chroma*b]}return linearSrgbToRgb(oklabToLinearSrgb(lab))}function rgbToOkhsl(rgb){let[L2,labA,labB]=rgbToOklab(rgb),chroma=Math.hypot(labA,labB),lightness=oklabToOkhslLightness(L2);if(chroma<1e-9||lightness<=0||lightness>=1)return{h:0,s:0,l:lightness};let hue=(Math.atan2(labB,labA)*180/Math.PI+360)%360,[c0,cMid,cMax]=chromaStops(L2,labA/chroma,labB/chroma),saturation;if(chroma<
119
+ cMid){let k1=.8*c0;saturation=.8*(chroma/(k1+(1-k1/cMid)*chroma))}else{let k1=.2*cMid**2*1.5625/c0,offset=chroma-cMid;saturation=.8+.2*(offset/(k1+(1-k1/(cMax-cMid))*offset))}return{h:hue,s:Math.min(1,Math.max(0,saturation)),l:lightness}}function requireFinite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function indexedColor(index){if(!Number.isInteger(index)||index<0||index>255)throw new Error(`ANSI color index must be an integer from 0 to 255: ${index}`);return Object.freeze({kind:"indexed",index})}function rgbColor(r,g,b){for(let[name,value]of[["r",r],["g",g],["b",b]])if(requireFinite(value,name),value<0||value>255)throw new Error(`${name} must be between 0 and 255: ${value}`);return Object.
120
+ freeze({kind:"rgb",r,g,b})}function oklchColor(l3,c,h2){if(requireFinite(l3,"l"),requireFinite(c,"c"),requireFinite(h2,"h"),l3<0||l3>1)throw new Error(`l must be between 0 and 1: ${l3}`);if(c<0)throw new Error(`c must not be negative: ${c}`);return Object.freeze({kind:"oklch",l:l3,c,h:(h2%360+360)%360})}var NUMBER_PATTERN=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`,OKLCH_PATTERN=new RegExp(`^oklch\\(\\s*(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})\\s+(${NUMBER_PATTERN})(?:deg)?\\s*\\)\
121
+ $`,"i"),OKHSL_PATTERN=new RegExp(`^okhsl\\(\\s*(${NUMBER_PATTERN})(?:deg)?\\s+(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})(%)?\\s*\\)$`,"i"),COLOR_CACHE_LIMIT=1024,okhslColors=new Map,parsedColors=new Map;function remember(cache,key,color){return cache.size>=COLOR_CACHE_LIMIT&&cache.clear(),cache.set(key,color),color}function okhslColor(h2,s,l3){if(requireFinite(h2,"h"),requireFinite(s,"s"),requireFinite(l3,"l"),s<0||s>1)throw new Error(`s must be between 0 and 1: ${s}`);if(l3<0||l3>1)throw new Error(
122
+ `l must be between 0 and 1: ${l3}`);let key=`${Object.is(h2,-0)?"-0":h2} ${Object.is(s,-0)?"-0":s} ${Object.is(l3,-0)?"-0":l3}`,cached=okhslColors.get(key);if(cached)return cached;let{r,g,b}=okhslToRgb(h2,s,l3);return remember(okhslColors,key,rgbColor(r,g,b))}function colorToOkhsl(color){return rgbToOkhsl(colorToRgb(color))}function parseColor(value){if(typeof value=="number")return indexedColor(value);let cached=parsedColors.get(value);return cached||remember(parsedColors,value,parseColorString(
123
+ value))}function parseColorString(value){let hex=/^#([\da-f]{3}|[\da-f]{6})$/i.exec(value);if(hex){let digits=hex[1].length===3?[...hex[1]].map(digit=>digit+digit).join(""):hex[1];return rgbColor(Number.parseInt(digits.slice(0,2),16),Number.parseInt(digits.slice(2,4),16),Number.parseInt(digits.slice(4,6),16))}let oklch=OKLCH_PATTERN.exec(value);if(oklch){let lightness=Number.parseFloat(oklch[1])/(oklch[2]?100:1);return oklchColor(lightness,Number.parseFloat(oklch[3]),Number.parseFloat(oklch[4]))}
124
+ let okhsl=OKHSL_PATTERN.exec(value);if(okhsl){let saturation=Number.parseFloat(okhsl[2])/(okhsl[3]?100:1),lightness=Number.parseFloat(okhsl[4])/(okhsl[5]?100:1);return okhslColor(Number.parseFloat(okhsl[1]),saturation,lightness)}throw new Error(`Invalid color value: ${value}`)}var BASIC_COLORS=[{r:0,g:0,b:0},{r:128,g:0,b:0},{r:0,g:128,b:0},{r:128,g:128,b:0},{r:0,g:0,b:128},{r:128,g:0,b:128},{r:0,g:128,b:128},{r:192,g:192,b:192},{r:128,g:128,b:128},{r:255,g:0,b:0},{r:0,g:255,b:0},{r:255,g:255,b:0},
125
+ {r:0,g:0,b:255},{r:255,g:0,b:255},{r:0,g:255,b:255},{r:255,g:255,b:255}],CUBE_VALUES=[0,95,135,175,215,255],GRAY_VALUES=Array.from({length:24},(_2,index)=>8+index*10);function indexedToRgb(index){if(index<16)return{...BASIC_COLORS[index]};if(index<232){let cubeIndex=index-16;return{r:CUBE_VALUES[Math.floor(cubeIndex/36)],g:CUBE_VALUES[Math.floor(cubeIndex%36/6)],b:CUBE_VALUES[cubeIndex%6]}}let gray=8+(index-232)*10;return{r:gray,g:gray,b:gray}}function isInSrgbGamut(linear){return linear.every(channel=>channel>=
126
+ -1e-7&&channel<=1+1e-7)}function oklchToRgb({l:l3,c,h:h2}){let radians=h2*Math.PI/180,cos=Math.cos(radians),sin=Math.sin(radians),atChroma=chroma=>oklabToLinearSrgb([l3,chroma*cos,chroma*sin]),direct=atChroma(c);if(isInSrgbGamut(direct))return linearSrgbToRgb(direct);let linear=atChroma(0),low=0,high=c;for(let index=0;index<20;index++){let chroma=(low+high)/2,candidate=atChroma(chroma);isInSrgbGamut(candidate)?(low=chroma,linear=candidate):high=chroma}return linearSrgbToRgb(linear)}function colorToRgb(color){
127
+ switch(color.kind){case"indexed":return indexedToRgb(color.index);case"rgb":return{r:color.r,g:color.g,b:color.b};case"oklch":return oklchToRgb(color)}}function colorToOklch(color){if(color.kind==="oklch")return{l:color.l,c:color.c,h:color.h};let[l3,a,b]=rgbToOklab(colorToRgb(color));return{l:l3,c:Math.hypot(a,b),h:(Math.atan2(b,a)*180/Math.PI+360)%360}}function colorToHex(color){let{r,g,b}=colorToRgb(color),channel=value=>Math.round(value).toString(16).padStart(2,"0");return`#${channel(r)}${channel(
128
+ g)}${channel(b)}`}function mixColors(first,second,amount,space="oklch"){if(requireFinite(amount,"amount"),amount<0||amount>1)throw new Error(`amount must be between 0 and 1: ${amount}`);if(space==="srgb"){let a2=colorToRgb(first),b2=colorToRgb(second);return rgbColor(a2.r+(b2.r-a2.r)*amount,a2.g+(b2.g-a2.g)*amount,a2.b+(b2.b-a2.b)*amount)}let a=colorToOklch(first),b=colorToOklch(second),firstHue=a.c<1e-7?b.h:a.h,hueDelta=((b.c<1e-7?firstHue:b.h)-firstHue+540)%360-180;return oklchColor(a.l+(b.l-a.
129
+ l)*amount,a.c+(b.c-a.c)*amount,firstHue+hueDelta*amount)}function findClosest(values,target){let closestIndex=0,closestDistance=1/0;for(let index=0;index<values.length;index++){let distance=Math.abs(target-values[index]);distance<closestDistance&&(closestIndex=index,closestDistance=distance)}return closestIndex}function colorDistance(first,second){let dr=first.r-second.r,dg=first.g-second.g,db=first.b-second.b;return dr*dr*.299+dg*dg*.587+db*db*.114}function rgbToAnsi256(color){let rIndex=findClosest(
130
+ CUBE_VALUES,color.r),gIndex=findClosest(CUBE_VALUES,color.g),bIndex=findClosest(CUBE_VALUES,color.b),cubeColor={r:CUBE_VALUES[rIndex],g:CUBE_VALUES[gIndex],b:CUBE_VALUES[bIndex]},cubeIndex=16+36*rIndex+6*gIndex+bIndex,gray=Math.round(.299*color.r+.587*color.g+.114*color.b),grayOffset=findClosest(GRAY_VALUES,gray),grayValue=GRAY_VALUES[grayOffset];return Math.max(color.r,color.g,color.b)-Math.min(color.r,color.g,color.b)<10&&colorDistance(color,{r:grayValue,g:grayValue,b:grayValue})<colorDistance(
131
+ color,cubeColor)?232+grayOffset:cubeIndex}function colorAnsi(color,mode,background){if(color.kind==="indexed")return`\x1B[${background?48:38};5;${color.index}m`;let rgb=colorToRgb(color);return mode==="truecolor"?`\x1B[${background?48:38};2;${Math.round(rgb.r)};${Math.round(rgb.g)};${Math.round(rgb.b)}m`:`\x1B[${background?48:38};5;${rgbToAnsi256(rgb)}m`}function foregroundAnsi(color,mode){return colorAnsi(color,mode,!1)}function backgroundAnsi(color,mode){return colorAnsi(color,mode,!0)}function styleText(text,options,mode){
132
+ return styleTextWithAnsi(text,options.fg&&foregroundAnsi(options.fg,mode),options.bg&&backgroundAnsi(options.bg,mode),options)}function styleTextWithAnsi(text,fgAnsi,bgAnsi,options){let prefix="",suffix="";return fgAnsi&&(prefix+=fgAnsi,suffix="\x1B[39m"),bgAnsi&&(prefix+=bgAnsi,suffix=`\x1B[49m${suffix}`),options.bold&&(prefix+="\x1B[1m"),options.dim&&(prefix+="\x1B[2m"),(options.bold||options.dim)&&(suffix=`\x1B[22m${suffix}`),options.italic&&(prefix+="\x1B[3m",suffix=`\x1B[23m${suffix}`),options.
133
+ underline&&(prefix+="\x1B[4m",suffix=`\x1B[24m${suffix}`),options.inverse&&(prefix+="\x1B[7m",suffix=`\x1B[27m${suffix}`),options.strikethrough&&(prefix+="\x1B[9m",suffix=`\x1B[29m${suffix}`),`${prefix}${text}${suffix}`}var _kittyProtocolActive=!1;function setKittyProtocolActive(active){active!==_kittyProtocolActive&&typedInputMatches.clear(),_kittyProtocolActive=active}function isKittyProtocolActive(){return _kittyProtocolActive}var Key={escape:"escape",esc:"esc",enter:"enter",return:"return",tab:"tab",space:"space",backspace:"backspace",delete:"delete",insert:"insert",clear:"clear",home:"home",end:"end",pageUp:"pageUp",pageDown:"pageDown",up:"up",down:"down",left:"left",right:"right",f1:"f1",f2:"f2",f3:"f3",f4:"\
134
+ f4",f5:"f5",f6:"f6",f7:"f7",f8:"f8",f9:"f9",f10:"f10",f11:"f11",f12:"f12",backtick:"`",hyphen:"-",equals:"=",leftbracket:"[",rightbracket:"]",backslash:"\\",semicolon:";",quote:"'",comma:",",period:".",slash:"/",exclamation:"!",at:"@",hash:"#",dollar:"$",percent:"%",caret:"^",ampersand:"&",asterisk:"*",leftparen:"(",rightparen:")",underscore:"_",plus:"+",pipe:"|",tilde:"~",leftbrace:"{",rightbrace:"}",colon:":",lessthan:"<",greaterthan:">",question:"?",ctrl:key=>`ctrl+${key}`,shift:key=>`shift+${key}`,
135
+ alt:key=>`alt+${key}`,super:key=>`super+${key}`,ctrlShift:key=>`ctrl+shift+${key}`,shiftCtrl:key=>`shift+ctrl+${key}`,ctrlAlt:key=>`ctrl+alt+${key}`,altCtrl:key=>`alt+ctrl+${key}`,shiftAlt:key=>`shift+alt+${key}`,altShift:key=>`alt+shift+${key}`,ctrlSuper:key=>`ctrl+super+${key}`,superCtrl:key=>`super+ctrl+${key}`,shiftSuper:key=>`shift+super+${key}`,superShift:key=>`super+shift+${key}`,altSuper:key=>`alt+super+${key}`,superAlt:key=>`super+alt+${key}`,ctrlShiftAlt:key=>`ctrl+shift+alt+${key}`,ctrlShiftSuper:key=>`\
136
+ ctrl+shift+super+${key}`},SYMBOL_KEYS=new Set(["`","-","=","[","]","\\",";","'",",",".","/","!","@","#","$","%","^","&","*","(",")","_","+","|","~","{","}",":","<",">","?"]),SHIFTED_SYMBOL_KEYS=new Set("~!@#$%^&*()_+|{}:<>?"),MODIFIER_NAMES=["shift","alt","ctrl","super"],MODIFIERS={shift:1,alt:2,ctrl:4,super:8},LOCK_MASK=192,CODEPOINTS={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},ARROW_CODEPOINTS={up:-1,down:-2,right:-3,left:-4},FUNCTIONAL_CODEPOINTS={delete:-10,insert:-11,pageUp:-12,
137
+ pageDown:-13,home:-14,end:-15,f1:-21,f2:-22,f3:-23,f4:-24,f5:-25,f6:-26,f7:-27,f8:-28,f9:-29,f10:-30,f11:-31,f12:-32},KITTY_FUNCTIONAL_PUA_START=57344,KITTY_FUNCTIONAL_PUA_END=63743,KITTY_FUNCTIONAL_KEY_EQUIVALENTS=new Map([[57399,48],[57400,49],[57401,50],[57402,51],[57403,52],[57404,53],[57405,54],[57406,55],[57407,56],[57408,57],[57409,46],[57410,47],[57411,42],[57412,45],[57413,43],[57415,61],[57416,44],[57417,ARROW_CODEPOINTS.left],[57418,ARROW_CODEPOINTS.right],[57419,ARROW_CODEPOINTS.up],
138
+ [57420,ARROW_CODEPOINTS.down],[57421,FUNCTIONAL_CODEPOINTS.pageUp],[57422,FUNCTIONAL_CODEPOINTS.pageDown],[57423,FUNCTIONAL_CODEPOINTS.home],[57424,FUNCTIONAL_CODEPOINTS.end],[57425,FUNCTIONAL_CODEPOINTS.insert],[57426,FUNCTIONAL_CODEPOINTS.delete]]);function normalizeKittyFunctionalCodepoint(codepoint){return KITTY_FUNCTIONAL_KEY_EQUIVALENTS.get(codepoint)??codepoint}function normalizeShiftedLetterIdentityCodepoint(codepoint,modifier){return(modifier&~LOCK_MASK&MODIFIERS.shift)!==0&&codepoint>=
139
+ 65&&codepoint<=90?codepoint+32:codepoint}function getLogicalShiftedSymbolCandidate(codepoint,modifier,allowedSymbols){if(codepoint===void 0||(modifier&MODIFIERS.shift)===0)return;let normalizedCodepoint=normalizeKittyFunctionalCodepoint(codepoint);if(allowedSymbols.has(String.fromCharCode(normalizedCodepoint)))return{codepoint:normalizedCodepoint,modifier:modifier&~MODIFIERS.shift}}var LEGACY_KEY_SEQUENCES={up:["\x1B[A","\x1BOA"],down:["\x1B[B","\x1BOB"],right:["\x1B[C","\x1BOC"],left:["\x1B[D",
140
+ "\x1BOD"],home:["\x1B[H","\x1BOH","\x1B[1~","\x1B[7~"],end:["\x1B[F","\x1BOF","\x1B[4~","\x1B[8~"],insert:["\x1B[2~"],delete:["\x1B[3~"],pageUp:["\x1B[5~","\x1B[[5~"],pageDown:["\x1B[6~","\x1B[[6~"],clear:["\x1B[E","\x1BOE"],f1:["\x1BOP","\x1B[11~","\x1B[[A"],f2:["\x1BOQ","\x1B[12~","\x1B[[B"],f3:["\x1BOR","\x1B[13~","\x1B[[C"],f4:["\x1BOS","\x1B[14~","\x1B[[D"],f5:["\x1B[15~","\x1B[[E"],f6:["\x1B[17~"],f7:["\x1B[18~"],f8:["\x1B[19~"],f9:["\x1B[20~"],f10:["\x1B[21~"],f11:["\x1B[23~"],f12:["\x1B[24~"]},
141
+ LEGACY_SHIFT_SEQUENCES={up:["\x1B[a"],down:["\x1B[b"],right:["\x1B[c"],left:["\x1B[d"],clear:["\x1B[e"],insert:["\x1B[2$"],delete:["\x1B[3$"],pageUp:["\x1B[5$"],pageDown:["\x1B[6$"],home:["\x1B[7$"],end:["\x1B[8$"]},LEGACY_CTRL_SEQUENCES={up:["\x1BOa"],down:["\x1BOb"],right:["\x1BOc"],left:["\x1BOd"],clear:["\x1BOe"],insert:["\x1B[2^"],delete:["\x1B[3^"],pageUp:["\x1B[5^"],pageDown:["\x1B[6^"],home:["\x1B[7^"],end:["\x1B[8^"]},LEGACY_SEQUENCE_KEY_IDS={"\x1BOA":"up","\x1BOB":"down","\x1BOC":"righ\
142
+ t","\x1BOD":"left","\x1BOH":"home","\x1BOF":"end","\x1B[E":"clear","\x1BOE":"clear","\x1BOe":"ctrl+clear","\x1B[e":"shift+clear","\x1B[2~":"insert","\x1B[2$":"shift+insert","\x1B[2^":"ctrl+insert","\x1B[3$":"shift+delete","\x1B[3^":"ctrl+delete","\x1B[[5~":"pageUp","\x1B[[6~":"pageDown","\x1B[a":"shift+up","\x1B[b":"shift+down","\x1B[c":"shift+right","\x1B[d":"shift+left","\x1BOa":"ctrl+up","\x1BOb":"ctrl+down","\x1BOc":"ctrl+right","\x1BOd":"ctrl+left","\x1B[5$":"shift+pageUp","\x1B[6$":"shift+\
143
+ pageDown","\x1B[7$":"shift+home","\x1B[8$":"shift+end","\x1B[5^":"ctrl+pageUp","\x1B[6^":"ctrl+pageDown","\x1B[7^":"ctrl+home","\x1B[8^":"ctrl+end","\x1BOP":"f1","\x1BOQ":"f2","\x1BOR":"f3","\x1BOS":"f4","\x1B[11~":"f1","\x1B[12~":"f2","\x1B[13~":"f3","\x1B[14~":"f4","\x1B[[A":"f1","\x1B[[B":"f2","\x1B[[C":"f3","\x1B[[D":"f4","\x1B[[E":"f5","\x1B[15~":"f5","\x1B[17~":"f6","\x1B[18~":"f7","\x1B[19~":"f8","\x1B[20~":"f9","\x1B[21~":"f10","\x1B[23~":"f11","\x1B[24~":"f12","\x1Bb":"alt+left","\x1Bf":"\
144
+ alt+right","\x1Bp":"alt+up","\x1Bn":"alt+down"},matchesLegacySequence=(data,sequences)=>sequences.includes(data),matchesLegacyModifierSequence=(data,key,modifier)=>modifier===MODIFIERS.shift?matchesLegacySequence(data,LEGACY_SHIFT_SEQUENCES[key]):modifier===MODIFIERS.ctrl?matchesLegacySequence(data,LEGACY_CTRL_SEQUENCES[key]):!1,_lastEventType="press";function isKeyRelease(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":3u")||data.includes(":3~")||data.includes(":3A")||data.includes(
145
+ ":3B")||data.includes(":3C")||data.includes(":3D")||data.includes(":3H")||data.includes(":3F")||data.includes(":3P")||data.includes(":3Q")||data.includes(":3S"))}function isKeyRepeat(data){return data.includes("\x1B[200~")?!1:!!(data.includes(":2u")||data.includes(":2~")||data.includes(":2A")||data.includes(":2B")||data.includes(":2C")||data.includes(":2D")||data.includes(":2H")||data.includes(":2F")||data.includes(":2P")||data.includes(":2Q")||data.includes(":2S"))}function parseEventType(eventTypeStr){
146
+ if(!eventTypeStr)return"press";let eventType=parseInt(eventTypeStr,10);return eventType===2?"repeat":eventType===3?"release":"press"}var lastKittyData,lastKittySequence=null;function parseKittySequence(data){return data!==lastKittyData?(lastKittySequence=parseKittySequenceUncached(data),lastKittyData=data):lastKittySequence&&(_lastEventType=lastKittySequence.eventType),lastKittySequence}function parseKittySequenceUncached(data){let csiUMatch=data.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);
147
+ if(csiUMatch){let codepoint=parseInt(csiUMatch[1],10),shiftedKey=csiUMatch[2]&&csiUMatch[2].length>0?parseInt(csiUMatch[2],10):void 0,baseLayoutKey=csiUMatch[3]?parseInt(csiUMatch[3],10):void 0,modValue=csiUMatch[4]?parseInt(csiUMatch[4],10):1,eventType=parseEventType(csiUMatch[5]);return _lastEventType=eventType,{codepoint,shiftedKey,baseLayoutKey,modifier:modValue-1,eventType}}let arrowMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(arrowMatch){let modValue=parseInt(arrowMatch[1],10),
148
+ eventType=parseEventType(arrowMatch[2]),arrowCodes={A:-1,B:-2,C:-3,D:-4};return _lastEventType=eventType,{codepoint:arrowCodes[arrowMatch[3]],modifier:modValue-1,eventType}}let funcMatch=data.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(funcMatch){let keyNum=parseInt(funcMatch[1],10),modValue=funcMatch[2]?parseInt(funcMatch[2],10):1,eventType=parseEventType(funcMatch[3]),codepoint={2:FUNCTIONAL_CODEPOINTS.insert,3:FUNCTIONAL_CODEPOINTS.delete,5:FUNCTIONAL_CODEPOINTS.pageUp,6:FUNCTIONAL_CODEPOINTS.
149
+ pageDown,7:FUNCTIONAL_CODEPOINTS.home,8:FUNCTIONAL_CODEPOINTS.end,11:FUNCTIONAL_CODEPOINTS.f1,12:FUNCTIONAL_CODEPOINTS.f2,13:FUNCTIONAL_CODEPOINTS.f3,14:FUNCTIONAL_CODEPOINTS.f4,15:FUNCTIONAL_CODEPOINTS.f5,17:FUNCTIONAL_CODEPOINTS.f6,18:FUNCTIONAL_CODEPOINTS.f7,19:FUNCTIONAL_CODEPOINTS.f8,20:FUNCTIONAL_CODEPOINTS.f9,21:FUNCTIONAL_CODEPOINTS.f10,23:FUNCTIONAL_CODEPOINTS.f11,24:FUNCTIONAL_CODEPOINTS.f12}[keyNum];if(codepoint!==void 0)return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}
150
+ let homeEndMatch=data.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(homeEndMatch){let modValue=parseInt(homeEndMatch[1],10),eventType=parseEventType(homeEndMatch[2]),codepoint=homeEndMatch[3]==="H"?FUNCTIONAL_CODEPOINTS.home:FUNCTIONAL_CODEPOINTS.end;return _lastEventType=eventType,{codepoint,modifier:modValue-1,eventType}}let fKeyMatch=data.match(/^\x1b\[(?:1;(\d+)(?::(\d+))?)?([PQS])$/);if(fKeyMatch){let modValue=fKeyMatch[1]?parseInt(fKeyMatch[1],10):1,eventType=parseEventType(fKeyMatch[2]),fKeyCodes={
151
+ P:FUNCTIONAL_CODEPOINTS.f1,Q:FUNCTIONAL_CODEPOINTS.f2,S:FUNCTIONAL_CODEPOINTS.f4};return _lastEventType=eventType,{codepoint:fKeyCodes[fKeyMatch[3]],modifier:modValue-1,eventType}}return null}function matchesKittySequence(data,expectedCodepoint,expectedModifier){let parsed=parseKittySequence(data);if(!parsed)return!1;let actualMod=parsed.modifier&~LOCK_MASK,expectedMod=expectedModifier&~LOCK_MASK,normalizedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(parsed.
152
+ codepoint),parsed.modifier),normalizedExpectedCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizeKittyFunctionalCodepoint(expectedCodepoint),expectedModifier);if(actualMod===expectedMod&&normalizedCodepoint===normalizedExpectedCodepoint)return!0;let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(parsed.shiftedKey,actualMod,SYMBOL_KEYS);if(logicalShiftedSymbol&&(logicalShiftedSymbol.modifier&~LOCK_MASK)===expectedMod&&logicalShiftedSymbol.codepoint===normalizeKittyFunctionalCodepoint(
153
+ expectedCodepoint))return!0;if(actualMod!==expectedMod)return!1;if(parsed.baseLayoutKey!==void 0&&parsed.baseLayoutKey===expectedCodepoint){let cp=normalizedCodepoint,isLatinLetter=cp>=97&&cp<=122,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(cp));if(!isLatinLetter&&!isKnownSymbol)return!0}return!1}var lastModifyOtherKeysData,lastModifyOtherKeysSequence=null;function parseModifyOtherKeysSequence(data){return data!==lastModifyOtherKeysData&&(lastModifyOtherKeysSequence=parseModifyOtherKeysSequenceUncached(
154
+ data),lastModifyOtherKeysData=data),lastModifyOtherKeysSequence}function parseModifyOtherKeysSequenceUncached(data){let match=data.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!match)return null;let modValue=parseInt(match[1],10);return{codepoint:parseInt(match[2],10),modifier:modValue-1}}function matchesModifyOtherKeys(data,expectedKeycode,expectedModifier){let parsed=parseModifyOtherKeysSequence(data);return parsed?parsed.codepoint===expectedKeycode&&parsed.modifier===expectedModifier:!1}function isWindowsTerminalSession(){
155
+ return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function matchesRawBackspace(data,expectedModifier){return data==="\x7F"?expectedModifier===0:data!=="\b"?!1:isWindowsTerminalSession()?expectedModifier===MODIFIERS.ctrl:expectedModifier===0}function rawCtrlChar(key){let char=key.toLowerCase(),code=char.charCodeAt(0);return code>=97&&code<=122||char==="["||char==="\\"||char==="]"||char==="_"?String.fromCharCode(code&31):char==="-"?"":null}
156
+ function isDigitKey(key){return key>="0"&&key<="9"}function matchesPrintableModifyOtherKeys(data,expectedKeycode,expectedModifier){let parsed=parseModifyOtherKeysSequence(data);if(!parsed)return!1;if(parsed.modifier===expectedModifier&&normalizeShiftedLetterIdentityCodepoint(parsed.codepoint,parsed.modifier)===normalizeShiftedLetterIdentityCodepoint(expectedKeycode,expectedModifier))return!0;let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(parsed.codepoint,parsed.modifier,SHIFTED_SYMBOL_KEYS);
157
+ return logicalShiftedSymbol?.modifier===expectedModifier&&logicalShiftedSymbol.codepoint===expectedKeycode}function formatKeyNameWithModifiers(keyName,modifier){let mods=[],effectiveMod=modifier&~LOCK_MASK,supportedModifierMask=MODIFIERS.shift|MODIFIERS.ctrl|MODIFIERS.alt|MODIFIERS.super;if((effectiveMod&~supportedModifierMask)===0)return effectiveMod&MODIFIERS.shift&&mods.push("shift"),effectiveMod&MODIFIERS.ctrl&&mods.push("ctrl"),effectiveMod&MODIFIERS.alt&&mods.push("alt"),effectiveMod&MODIFIERS.
158
+ super&&mods.push("super"),mods.length>0?`${mods.join("+")}+${keyName}`:keyName}var parsedKeyIds=new Map,MAX_PARSED_KEY_IDS=512;function parseKeyId(keyId){let parsed=parsedKeyIds.get(keyId);return parsed===void 0&&(parsed=parseKeyIdUncached(keyId),parsedKeyIds.size>=MAX_PARSED_KEY_IDS&&parsedKeyIds.clear(),parsedKeyIds.set(keyId,parsed)),parsed}function parseKeyIdUncached(keyId){let key=keyId.toLowerCase(),modifiers=new Set;for(;;){let modifier2=MODIFIER_NAMES.find(name=>key.startsWith(`${name}+`));
159
+ if(!modifier2)break;if(modifiers.has(modifier2))return null;modifiers.add(modifier2),key=key.slice(modifier2.length+1)}if(!key||key.includes("+")&&key!=="+")return null;let modifier=0;return modifiers.has("shift")&&(modifier|=MODIFIERS.shift),modifiers.has("alt")&&(modifier|=MODIFIERS.alt),modifiers.has("ctrl")&&(modifier|=MODIFIERS.ctrl),modifiers.has("super")&&(modifier|=MODIFIERS.super),{key,modifier}}function matchesKey(data,keyId){if(data.length>MAX_TYPED_INPUT_LENGTH||data==="\b"||data.includes(
160
+ "\x1B"))return matchesKeyUncached(data,keyId);let byKey=typedInputMatches.get(data);byKey===void 0&&(typedInputMatches.size>=MAX_TYPED_INPUTS&&typedInputMatches.clear(),byKey=new Map,typedInputMatches.set(data,byKey));let matched=byKey.get(keyId);return matched===void 0&&(matched=matchesKeyUncached(data,keyId),byKey.set(keyId,matched)),matched}var typedInputMatches=new Map,MAX_TYPED_INPUTS=256,MAX_TYPED_INPUT_LENGTH=4;function matchesKeyUncached(data,keyId){let parsed=parseKeyId(keyId);if(!parsed)
161
+ return!1;let{key,modifier}=parsed;switch(key){case"escape":case"esc":return modifier!==0?!1:data==="\x1B"||matchesKittySequence(data,CODEPOINTS.escape,0)||matchesModifyOtherKeys(data,CODEPOINTS.escape,0);case"space":return!_kittyProtocolActive&&(modifier===MODIFIERS.ctrl&&data==="\0"||modifier===MODIFIERS.alt&&data==="\x1B ")?!0:modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.space,0)||matchesModifyOtherKeys(data,CODEPOINTS.space,0):matchesKittySequence(data,CODEPOINTS.space,modifier)||
162
+ matchesModifyOtherKeys(data,CODEPOINTS.space,modifier);case"tab":return modifier===MODIFIERS.shift?data==="\x1B[Z"||matchesKittySequence(data,CODEPOINTS.tab,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.tab,MODIFIERS.shift):modifier===0?data===" "||matchesKittySequence(data,CODEPOINTS.tab,0):matchesKittySequence(data,CODEPOINTS.tab,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.tab,modifier);case"enter":case"return":return modifier===MODIFIERS.shift?matchesKittySequence(data,CODEPOINTS.
163
+ enter,MODIFIERS.shift)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.shift)?!0:_kittyProtocolActive?data==="\x1B\r"||data===`
164
+ `:!1:modifier===MODIFIERS.alt?matchesKittySequence(data,CODEPOINTS.enter,MODIFIERS.alt)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.alt)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.alt)?!0:_kittyProtocolActive?!1:data==="\x1B\r":modifier===0?data==="\r"||!_kittyProtocolActive&&data===`
165
+ `||data==="\x1BOM"||matchesKittySequence(data,CODEPOINTS.enter,0)||matchesKittySequence(data,CODEPOINTS.kpEnter,0):matchesKittySequence(data,CODEPOINTS.enter,modifier)||matchesKittySequence(data,CODEPOINTS.kpEnter,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.enter,modifier);case"backspace":return modifier===MODIFIERS.alt?data==="\x1B\x7F"||data==="\x1B\b"?!0:matchesKittySequence(data,CODEPOINTS.backspace,MODIFIERS.alt)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,MODIFIERS.alt):modifier===
166
+ MODIFIERS.ctrl?matchesRawBackspace(data,MODIFIERS.ctrl)?!0:matchesKittySequence(data,CODEPOINTS.backspace,MODIFIERS.ctrl)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,MODIFIERS.ctrl):modifier===0?matchesRawBackspace(data,0)||matchesKittySequence(data,CODEPOINTS.backspace,0)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,0):matchesKittySequence(data,CODEPOINTS.backspace,modifier)||matchesModifyOtherKeys(data,CODEPOINTS.backspace,modifier);case"insert":return modifier===0?matchesLegacySequence(
167
+ data,LEGACY_KEY_SEQUENCES.insert)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.insert,0):matchesLegacyModifierSequence(data,"insert",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.insert,modifier);case"delete":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.delete)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.delete,0):matchesLegacyModifierSequence(data,"delete",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.delete,modifier);case"clear":return modifier===
168
+ 0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.clear):matchesLegacyModifierSequence(data,"clear",modifier);case"home":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.home)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.home,0):matchesLegacyModifierSequence(data,"home",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.home,modifier);case"end":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.end)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.
169
+ end,0):matchesLegacyModifierSequence(data,"end",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.end,modifier);case"pageup":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.pageUp)||matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageUp,0):matchesLegacyModifierSequence(data,"pageUp",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageUp,modifier);case"pagedown":return modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.pageDown)||matchesKittySequence(
170
+ data,FUNCTIONAL_CODEPOINTS.pageDown,0):matchesLegacyModifierSequence(data,"pageDown",modifier)?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS.pageDown,modifier);case"up":return modifier===MODIFIERS.alt?data==="\x1Bp"||matchesKittySequence(data,ARROW_CODEPOINTS.up,MODIFIERS.alt):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.up)||matchesKittySequence(data,ARROW_CODEPOINTS.up,0):matchesLegacyModifierSequence(data,"up",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.up,modifier);case"\
171
+ down":return modifier===MODIFIERS.alt?data==="\x1Bn"||matchesKittySequence(data,ARROW_CODEPOINTS.down,MODIFIERS.alt):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.down)||matchesKittySequence(data,ARROW_CODEPOINTS.down,0):matchesLegacyModifierSequence(data,"down",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.down,modifier);case"left":return modifier===MODIFIERS.alt?data==="\x1B[1;3D"||!_kittyProtocolActive&&data==="\x1BB"||data==="\x1Bb"||matchesKittySequence(data,ARROW_CODEPOINTS.
172
+ left,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5D"||matchesLegacyModifierSequence(data,"left",MODIFIERS.ctrl)||matchesKittySequence(data,ARROW_CODEPOINTS.left,MODIFIERS.ctrl):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.left)||matchesKittySequence(data,ARROW_CODEPOINTS.left,0):matchesLegacyModifierSequence(data,"left",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.left,modifier);case"right":return modifier===MODIFIERS.alt?data==="\x1B[1;3C"||!_kittyProtocolActive&&
173
+ data==="\x1BF"||data==="\x1Bf"||matchesKittySequence(data,ARROW_CODEPOINTS.right,MODIFIERS.alt):modifier===MODIFIERS.ctrl?data==="\x1B[1;5C"||matchesLegacyModifierSequence(data,"right",MODIFIERS.ctrl)||matchesKittySequence(data,ARROW_CODEPOINTS.right,MODIFIERS.ctrl):modifier===0?matchesLegacySequence(data,LEGACY_KEY_SEQUENCES.right)||matchesKittySequence(data,ARROW_CODEPOINTS.right,0):matchesLegacyModifierSequence(data,"right",modifier)?!0:matchesKittySequence(data,ARROW_CODEPOINTS.right,modifier);case"\
174
+ f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":{let functionKey=key;return modifier===0&&matchesLegacySequence(data,LEGACY_KEY_SEQUENCES[functionKey])?!0:matchesKittySequence(data,FUNCTIONAL_CODEPOINTS[functionKey],modifier)}}if(key.length===1&&(key>="a"&&key<="z"||isDigitKey(key)||SYMBOL_KEYS.has(key))){let codepoint=key.charCodeAt(0),rawCtrl=rawCtrlChar(key),isLetter=key>="a"&&key<="z",isDigit=isDigitKey(key);return modifier===MODIFIERS.
175
+ ctrl+MODIFIERS.alt&&!_kittyProtocolActive&&rawCtrl&&data===`\x1B${rawCtrl}`||modifier===MODIFIERS.alt&&!_kittyProtocolActive&&(isLetter||isDigit||SYMBOL_KEYS.has(key))&&data===`\x1B${key}`?!0:modifier===MODIFIERS.ctrl?rawCtrl&&data===rawCtrl?!0:matchesKittySequence(data,codepoint,MODIFIERS.ctrl)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.ctrl):modifier===MODIFIERS.shift+MODIFIERS.ctrl?matchesKittySequence(data,codepoint,MODIFIERS.shift+MODIFIERS.ctrl)||matchesPrintableModifyOtherKeys(
176
+ data,codepoint,MODIFIERS.shift+MODIFIERS.ctrl):modifier===MODIFIERS.shift?isLetter&&data===key.toUpperCase()?!0:matchesKittySequence(data,codepoint,MODIFIERS.shift)||matchesPrintableModifyOtherKeys(data,codepoint,MODIFIERS.shift):modifier!==0?matchesKittySequence(data,codepoint,modifier)||matchesPrintableModifyOtherKeys(data,codepoint,modifier):data===key||matchesKittySequence(data,codepoint,0)||matchesPrintableModifyOtherKeys(data,codepoint,0)}return!1}function formatParsedKey(codepoint,modifier,baseLayoutKey){
177
+ let normalizedCodepoint=normalizeKittyFunctionalCodepoint(codepoint),identityCodepoint=normalizeShiftedLetterIdentityCodepoint(normalizedCodepoint,modifier),isLatinLetter=identityCodepoint>=97&&identityCodepoint<=122,isDigit=identityCodepoint>=48&&identityCodepoint<=57,isKnownSymbol=SYMBOL_KEYS.has(String.fromCharCode(identityCodepoint)),effectiveCodepoint=isLatinLetter||isDigit||isKnownSymbol?identityCodepoint:baseLayoutKey??identityCodepoint,keyName;if(effectiveCodepoint===CODEPOINTS.escape?keyName=
178
+ "escape":effectiveCodepoint===CODEPOINTS.tab?keyName="tab":effectiveCodepoint===CODEPOINTS.enter||effectiveCodepoint===CODEPOINTS.kpEnter?keyName="enter":effectiveCodepoint===CODEPOINTS.space?keyName="space":effectiveCodepoint===CODEPOINTS.backspace?keyName="backspace":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.delete?keyName="delete":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.insert?keyName="insert":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.home?keyName="home":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.
179
+ end?keyName="end":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageUp?keyName="pageUp":effectiveCodepoint===FUNCTIONAL_CODEPOINTS.pageDown?keyName="pageDown":effectiveCodepoint<=FUNCTIONAL_CODEPOINTS.f1&&effectiveCodepoint>=FUNCTIONAL_CODEPOINTS.f12?keyName=`f${FUNCTIONAL_CODEPOINTS.f1-effectiveCodepoint+1}`:effectiveCodepoint===ARROW_CODEPOINTS.up?keyName="up":effectiveCodepoint===ARROW_CODEPOINTS.down?keyName="down":effectiveCodepoint===ARROW_CODEPOINTS.left?keyName="left":effectiveCodepoint===ARROW_CODEPOINTS.
180
+ right?keyName="right":(effectiveCodepoint>=48&&effectiveCodepoint<=57||effectiveCodepoint>=97&&effectiveCodepoint<=122||SYMBOL_KEYS.has(String.fromCharCode(effectiveCodepoint)))&&(keyName=String.fromCharCode(effectiveCodepoint)),!!keyName)return formatKeyNameWithModifiers(keyName,modifier)}function parseKey(data){let kitty=parseKittySequence(data);if(kitty){let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(kitty.shiftedKey,kitty.modifier,SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.
181
+ codepoint??kitty.codepoint,logicalShiftedSymbol?.modifier??kitty.modifier,kitty.baseLayoutKey)}let modifyOtherKeys=parseModifyOtherKeysSequence(data);if(modifyOtherKeys){let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(modifyOtherKeys.codepoint,modifyOtherKeys.modifier,SHIFTED_SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.codepoint??modifyOtherKeys.codepoint,logicalShiftedSymbol?.modifier??modifyOtherKeys.modifier)}if(_kittyProtocolActive&&(data==="\x1B\r"||data===`
182
+ `))return"shift+enter";let legacySequenceKeyId=LEGACY_SEQUENCE_KEY_IDS[data];if(legacySequenceKeyId)return legacySequenceKeyId;if(data==="\x1B")return"escape";if(data==="")return"ctrl+\\";if(data==="")return"ctrl+]";if(data==="")return"ctrl+-";if(data==="\x1B\x1B")return"ctrl+alt+[";if(data==="\x1B")return"ctrl+alt+\\";if(data==="\x1B")return"ctrl+alt+]";if(data==="\x1B")return"ctrl+alt+-";if(data===" ")return"tab";if(data==="\r"||!_kittyProtocolActive&&data===`
183
+ `||data==="\x1BOM")return"enter";if(data==="\0")return"ctrl+space";if(data===" ")return"space";if(data==="\x7F")return"backspace";if(data==="\b")return isWindowsTerminalSession()?"ctrl+backspace":"backspace";if(data==="\x1B[Z")return"shift+tab";if(!_kittyProtocolActive&&data==="\x1B\r")return"alt+enter";if(!_kittyProtocolActive&&data==="\x1B ")return"alt+space";if(data==="\x1B\x7F"||data==="\x1B\b")return"alt+backspace";if(!_kittyProtocolActive&&data==="\x1BB")return"alt+left";if(!_kittyProtocolActive&&
184
+ data==="\x1BF")return"alt+right";if(!_kittyProtocolActive&&data.length===2&&data[0]==="\x1B"){let code=data.charCodeAt(1);if(code>=1&&code<=26)return`ctrl+alt+${String.fromCharCode(code+96)}`;let key=String.fromCharCode(code);if(code>=97&&code<=122||code>=48&&code<=57||SYMBOL_KEYS.has(key))return`alt+${key}`}if(data==="\x1B[A")return"up";if(data==="\x1B[B")return"down";if(data==="\x1B[C")return"right";if(data==="\x1B[D")return"left";if(data==="\x1B[H"||data==="\x1BOH")return"home";if(data==="\x1B[F"||
185
+ data==="\x1BOF")return"end";if(data==="\x1B[3~")return"delete";if(data==="\x1B[5~")return"pageUp";if(data==="\x1B[6~")return"pageDown";if(data.length===1){let code=data.charCodeAt(0);if(code>=1&&code<=26)return`ctrl+${String.fromCharCode(code+96)}`;if(code>=32&&code<=126)return data}}var KITTY_CSI_U_REGEX=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,KITTY_PRINTABLE_ALLOWED_MODIFIERS=MODIFIERS.shift|LOCK_MASK;function decodeKittyPrintable(data){let match=data.match(KITTY_CSI_U_REGEX);
186
+ if(!match)return;let codepoint=Number.parseInt(match[1]??"",10);if(!Number.isFinite(codepoint))return;let shiftedKey=match[2]&&match[2].length>0?Number.parseInt(match[2],10):void 0,modValue=match[4]?Number.parseInt(match[4],10):1,modifier=Number.isFinite(modValue)?modValue-1:0;if((modifier&~KITTY_PRINTABLE_ALLOWED_MODIFIERS)!==0||modifier&(MODIFIERS.alt|MODIFIERS.ctrl))return;let effectiveCodepoint=codepoint;if(modifier&MODIFIERS.shift&&typeof shiftedKey=="number"&&(effectiveCodepoint=shiftedKey),
187
+ effectiveCodepoint=normalizeKittyFunctionalCodepoint(effectiveCodepoint),!(!Number.isFinite(effectiveCodepoint)||effectiveCodepoint<32)&&!(effectiveCodepoint>=KITTY_FUNCTIONAL_PUA_START&&effectiveCodepoint<=KITTY_FUNCTIONAL_PUA_END))try{return String.fromCodePoint(effectiveCodepoint)}catch{return}}function decodeModifyOtherKeysPrintable(data){let parsed=parseModifyOtherKeysSequence(data);if(!(!parsed||(parsed.modifier&~LOCK_MASK&~MODIFIERS.shift)!==0)&&!(!Number.isFinite(parsed.codepoint)||parsed.
188
+ codepoint<32))try{return String.fromCodePoint(parsed.codepoint)}catch{return}}function decodePrintableKey(data){return decodeKittyPrintable(data)??decodeModifyOtherKeysPrintable(data)}import{execFile}from"node:child_process";import{homedir as homedir2}from"node:os";import{isAbsolute}from"node:path";import{pathToFileURL}from"node:url";var cachedCapabilities=null,cachedBeforeTmuxAnswer=!1,capabilityOverrides={},capabilityChangeListeners=new Set,cellDimensions={widthPx:9,heightPx:18};function getCellDimensions(){return cellDimensions}function setCellDimensions(dims){cellDimensions=dims}var tmuxHyperlinks,tmuxProbeStarted=!1;function probeTmuxHyperlinks(){return tmuxHyperlinks!==
189
+ void 0?tmuxHyperlinks:(tmuxProbeStarted||(tmuxProbeStarted=!0,startTmuxProbe()),!1)}function startTmuxProbe(){let deadline=performance.now()+250,answered=!1,answer=forwards=>{if(!answered&&(answered=!0,tmuxHyperlinks=forwards,!(!forwards||!cachedBeforeTmuxAnswer))){cachedCapabilities=null,cachedBeforeTmuxAnswer=!1;for(let listener of capabilityChangeListeners)listener()}};try{let child=execFile("tmux",["display-message","-p","#{client_termfeatures}"],{encoding:"utf8"},(error,stdout)=>{clearTimeout(
190
+ timeout),answer(!error&&performance.now()<deadline&&stdout.split(",").map(feature=>feature.trim()).includes("hyperlinks"))}),timeout=setTimeout(()=>{answer(!1),child.kill()},Math.max(0,deadline-performance.now()));timeout.unref(),child.unref(),child.stdin?.end(),child.stdout?.unref(),child.stderr?.unref()}catch{answer(!1)}}function onCapabilitiesChange(listener){return capabilityChangeListeners.add(listener),()=>capabilityChangeListeners.delete(listener)}function detectCapabilitiesFromEnvironment(tmuxForwardsHyperlink){
191
+ let termProgram=process.env.TERM_PROGRAM?.toLowerCase()||"",terminalEmulator=process.env.TERMINAL_EMULATOR?.toLowerCase()||"",term=process.env.TERM?.toLowerCase()||"",colorTerm=process.env.COLORTERM?.toLowerCase()||"",hasTrueColorHint=colorTerm==="truecolor"||colorTerm==="24bit"||term.endsWith("-direct"),isWindowsConsole=process.platform==="win32";return process.env.TMUX||term.startsWith("tmux")?{images:null,trueColor:hasTrueColorHint,hyperlinks:tmuxForwardsHyperlink()}:term.startsWith("screen")?
192
+ {images:null,trueColor:hasTrueColorHint,hyperlinks:!1}:termProgram==="herdr"?{images:"kitty",trueColor:hasTrueColorHint,hyperlinks:!0}:termProgram==="rex"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="orca"&&process.env.ORCA_IMAGE_PROTOCOL==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.KITTY_WINDOW_ID||termProgram==="kitty"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="ghostty"||term.includes("ghostty")||process.env.GHOSTTY_RESOURCES_DIR?{images:"kitt\
193
+ y",trueColor:!0,hyperlinks:!0}:process.env.WEZTERM_PANE||termProgram==="wezterm"?{images:"kitty",trueColor:!0,hyperlinks:!0}:termProgram==="warpterminal"||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||termProgram==="iterm.app"?{images:"iterm2",trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION?{images:null,trueColor:!0,hyperlinks:!0}:termProgram==="alacritty"||term.startsWith("alacritty")||process.env.
194
+ ALACRITTY_WINDOW_ID||termProgram==="vscode"||termProgram==="zed"?{images:null,trueColor:!0,hyperlinks:!0}:terminalEmulator==="jetbrains-jediterm"?{images:null,trueColor:!0,hyperlinks:!1}:isWindowsConsole?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}}function parseBooleanCapabilityOverride(value){return value==="1"?!0:value==="0"?!1:void 0}function detectCapabilities(tmuxForwardsHyperlink=probeTmuxHyperlinks){let hyperlinks=parseBooleanCapabilityOverride(
195
+ process.env.HUMAIN_TERMINAL_HYPERLINKS??process.env.PI_HYPERLINKS),detected=detectCapabilitiesFromEnvironment(hyperlinks===void 0?tmuxForwardsHyperlink:()=>hyperlinks),imageProtocol=(process.env.HUMAIN_TERMINAL_IMAGE_PROTOCOL??process.env.PI_IMAGE_PROTOCOL)?.toLowerCase(),images=imageProtocol==="kitty"||imageProtocol==="iterm2"?imageProtocol:imageProtocol==="none"||imageProtocol==="0"?null:void 0,trueColor=parseBooleanCapabilityOverride(process.env.HUMAIN_TERMINAL_TRUE_COLOR??process.env.PI_TRUE_COLOR);
196
+ return{...detected,...images!==void 0?{images}:{},...trueColor!==void 0?{trueColor}:{},...hyperlinks!==void 0?{hyperlinks}:{}}}function getCapabilities(){if(!cachedCapabilities){let hyperlinks=capabilityOverrides.hyperlinks,probePending=!1;cachedCapabilities={...detectCapabilities(hyperlinks===void 0?()=>{let forwards=probeTmuxHyperlinks();return probePending=tmuxHyperlinks===void 0,forwards}:()=>hyperlinks),...capabilityOverrides},cachedBeforeTmuxAnswer=probePending}return cachedCapabilities}function getTerminalColorMode(capabilities=getCapabilities()){
197
+ return capabilities.trueColor?"truecolor":"256color"}function resetCapabilitiesCache(){cachedCapabilities=null,cachedBeforeTmuxAnswer=!1,tmuxHyperlinks=void 0,tmuxProbeStarted=!1}function setCapabilityOverrides(overrides){capabilityOverrides.images===overrides.images&&capabilityOverrides.trueColor===overrides.trueColor&&capabilityOverrides.hyperlinks===overrides.hyperlinks||(capabilityOverrides={...overrides},cachedCapabilities=null,cachedBeforeTmuxAnswer=!1)}function setCapabilities(caps){cachedCapabilities=
198
+ caps,cachedBeforeTmuxAnswer=!1}var KITTY_PREFIX="\x1B_G",ITERM2_PREFIX="\x1B]1337;File=";function isImageLine(line){return line.startsWith(KITTY_PREFIX)||line.startsWith(ITERM2_PREFIX)?!0:line.includes(KITTY_PREFIX)||line.includes(ITERM2_PREFIX)}function allocateImageId(){return Math.floor(Math.random()*4294967294)+1}function encodeKitty(base64Data,options={}){let params=["a=T","f=100","q=2"];if(options.moveCursor===!1&&params.push("C=1"),options.columns&&params.push(`c=${options.columns}`),options.
199
+ rows&&params.push(`r=${options.rows}`),options.imageId&&params.push(`i=${options.imageId}`),base64Data.length<=4096)return`\x1B_G${params.join(",")};${base64Data}\x1B\\`;let chunks=[],offset=0,isFirst=!0;for(;offset<base64Data.length;){let chunk=base64Data.slice(offset,offset+4096),isLast=offset+4096>=base64Data.length;isFirst?(chunks.push(`\x1B_G${params.join(",")},m=1;${chunk}\x1B\\`),isFirst=!1):isLast?chunks.push(`\x1B_Gm=0;${chunk}\x1B\\`):chunks.push(`\x1B_Gm=1;${chunk}\x1B\\`),offset+=4096}
200
+ return chunks.join("")}function deleteKittyImage(imageId){return`\x1B_Ga=d,d=I,i=${imageId},q=2\x1B\\`}function deleteAllKittyImages(){return"\x1B_Ga=d,d=A,q=2\x1B\\"}function deleteAllKittyPlacements(){return"\x1B_Ga=d,d=a,q=2\x1B\\"}function encodeITerm2(base64Data,options={}){let params=[`inline=${options.inline!==!1?1:0}`,`size=${Buffer.byteLength(base64Data,"base64")}`];if(options.width!==void 0&&params.push(`width=${options.width}`),options.height!==void 0&&params.push(`height=${options.height}`),
201
+ options.name){let nameBase64=Buffer.from(options.name).toString("base64");params.push(`name=${nameBase64}`)}return options.preserveAspectRatio===!1&&params.push("preserveAspectRatio=0"),`\x1B]1337;File=${params.join(";")}:${base64Data}\x07`}var kittyImageMetadata=new Map,kittyImageRegistered=!1,kittyTransmissionGeneration=0,maxKittyImageRows=0;function registerKittyImageMetadata(metadata){if(kittyTransmissionGeneration+=1,maxKittyImageRows=Math.max(maxKittyImageRows,metadata.rows),kittyImageRegistered=
202
+ !0,kittyImageMetadata.delete(metadata.imageId),kittyImageMetadata.set(metadata.imageId,{...metadata,transmissionGeneration:kittyTransmissionGeneration}),kittyImageMetadata.size>1e3){let oldestImageId=kittyImageMetadata.keys().next().value;oldestImageId!==void 0&&kittyImageMetadata.delete(oldestImageId)}}function findKittyControls(line){let index=line.indexOf("\x1B_G");if(index===-1)return;let end=line.indexOf(";",index+3);if(end!==-1)return{index,controls:line.slice(index+3,end),length:end+1-index}}
203
+ function getMaxKittyImageRows(){return maxKittyImageRows}function getRegisteredKittyImageMetadataFromControls(controls){let imageId=/(?:^|,)i=(\d+)(?:,|$)/.exec(controls)?.[1];return imageId===void 0?void 0:kittyImageMetadata.get(Number.parseInt(imageId,10))}function getRegisteredKittyImageMetadata(line){if(!kittyImageRegistered)return;let controls=findKittyControls(line)?.controls;return controls===void 0?void 0:getRegisteredKittyImageMetadataFromControls(controls)}function getExplicitKittyImageRows(controls){
204
+ let value=/(?:^|,)r=(\d+)(?:,|$)/.exec(controls)?.[1];if(value===void 0)return;let rows=Number.parseInt(value,10);return rows>0?rows:void 0}function getKittyImageRowsFromControls(controls,fallbackRows){return getExplicitKittyImageRows(controls)??fallbackRows}function getKittyImageMetadata(line){let metadata=getRegisteredKittyImageMetadata(line);if(metadata)return{imageId:metadata.imageId,columns:metadata.columns,rows:metadata.rows,widthPx:metadata.widthPx,heightPx:metadata.heightPx}}var KITTY_PLACEMENT_CONTROL_KEYS=new Set(
205
+ ["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function getKittyImagePlacementRows(line){let controls=findKittyControls(line)?.controls;if(controls===void 0)return;let explicitRows=getExplicitKittyImageRows(controls);return explicitRows!==void 0?explicitRows:getRegisteredKittyImageMetadataFromControls(controls)?.rows}function getKittyImagePlacement(line){let match=findKittyControls(line);if(!match)return;let metadata=getRegisteredKittyImageMetadataFromControls(match.controls);
206
+ if(!metadata)return;let commandStart=match.index,commandControls=match.controls,transmissionEnd;for(;;){let terminator=line.indexOf("\x1B\\",commandStart+KITTY_PREFIX.length);if(terminator===-1)return;if(transmissionEnd=terminator+2,!/(?:^|,)m=1(?:,|$)/.test(commandControls))break;if(commandStart=transmissionEnd,!line.startsWith(KITTY_PREFIX,commandStart))return;let controlsEnd=line.indexOf(";",commandStart+KITTY_PREFIX.length);if(controlsEnd===-1)return;commandControls=line.slice(commandStart+KITTY_PREFIX.
207
+ length,controlsEnd)}let sequence=`\x1B_Ga=p,q=2,${match.controls.split(",").filter(control=>KITTY_PLACEMENT_CONTROL_KEYS.has(control.split("=",1)[0]??"")).join(",")}\x1B\\`;return{imageId:metadata.imageId,transmissionGeneration:metadata.transmissionGeneration,transmissionBytes:transmissionEnd-match.index,estimatedDecodedBytes:metadata.widthPx*metadata.heightPx*4,rows:getKittyImageRowsFromControls(match.controls,metadata.rows),sequence,replacementLine:`${line.slice(0,match.index)}${sequence}${line.
208
+ slice(transmissionEnd)}`}}function cropKittyImageLine(line,hiddenRows,visibleRows){let metadata=getKittyImageMetadata(line),match=findKittyControls(line);if(!metadata||!match||hiddenRows<0||hiddenRows>=metadata.rows||visibleRows<=0)return line;let croppedRows=Math.min(visibleRows,metadata.rows-hiddenRows);if(hiddenRows===0&&croppedRows===metadata.rows)return line;let sourceY=Math.floor(metadata.heightPx*hiddenRows/metadata.rows),sourceEnd=Math.ceil(metadata.heightPx*(hiddenRows+croppedRows)/metadata.
209
+ rows),sourceHeight=Math.max(1,Math.min(metadata.heightPx,sourceEnd)-sourceY),controls=match.controls.split(",").filter(control=>!/^[yhr]=/.test(control));return controls.push(`y=${sourceY}`,`h=${sourceHeight}`,`r=${croppedRows}`),`${line.slice(0,match.index)}\x1B_G${controls.join(",")};${line.slice(match.index+match.length)}`}function chooseLessDistortedCellCount(upperCount,idealCount){if(upperCount<=1)return upperCount;let lowerCount=upperCount-1,upperDistortion=Math.max(upperCount/idealCount,idealCount/
210
+ upperCount);return Math.max(lowerCount/idealCount,idealCount/lowerCount)<upperDistortion?lowerCount:upperCount}function calculateImageCellSize(imageDimensions,maxWidthCells,maxHeightCells,cellDimensions2={widthPx:9,heightPx:18},optimizeAspectRatio=!1){let maxWidth=Math.max(1,Math.floor(maxWidthCells)),maxHeight=maxHeightCells===void 0?void 0:Math.max(1,Math.floor(maxHeightCells)),imageWidth=Math.max(1,imageDimensions.widthPx),imageHeight=Math.max(1,imageDimensions.heightPx),widthScale=maxWidth*cellDimensions2.
211
+ widthPx/imageWidth,heightScale=maxHeight===void 0?widthScale:maxHeight*cellDimensions2.heightPx/imageHeight,scale=Math.min(widthScale,heightScale),scaledWidthPx=imageWidth*scale,scaledHeightPx=imageHeight*scale,columns=Math.max(1,Math.min(maxWidth,Math.ceil(scaledWidthPx/cellDimensions2.widthPx))),heightRows=scaledHeightPx/cellDimensions2.heightPx,rows=Math.max(1,Math.ceil(heightRows));if(maxHeight!==void 0&&(rows=Math.min(maxHeight,rows)),!optimizeAspectRatio)return{columns,rows};if(widthScale<=
212
+ heightScale){let idealRows=columns*cellDimensions2.widthPx*imageHeight/(imageWidth*cellDimensions2.heightPx);rows=chooseLessDistortedCellCount(rows,idealRows)}else{let idealColumns=rows*cellDimensions2.heightPx*imageWidth/(imageHeight*cellDimensions2.widthPx);columns=chooseLessDistortedCellCount(columns,idealColumns)}return{columns,rows}}function calculateImageRows(imageDimensions,targetWidthCells,cellDimensions2={widthPx:9,heightPx:18}){return calculateImageCellSize(imageDimensions,targetWidthCells,
213
+ void 0,cellDimensions2).rows}function getPngDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<24||buffer[0]!==137||buffer[1]!==80||buffer[2]!==78||buffer[3]!==71)return null;let width=buffer.readUInt32BE(16),height=buffer.readUInt32BE(20);return{widthPx:width,heightPx:height}}catch{return null}}function getJpegDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<2||buffer[0]!==255||buffer[1]!==216)return null;let offset=2;for(;offset<
214
+ buffer.length-9;){if(buffer[offset]!==255){offset++;continue}let marker=buffer[offset+1];if(marker>=192&&marker<=194){let height=buffer.readUInt16BE(offset+5);return{widthPx:buffer.readUInt16BE(offset+7),heightPx:height}}if(offset+3>=buffer.length)return null;let length=buffer.readUInt16BE(offset+2);if(length<2)return null;offset+=2+length}return null}catch{return null}}function getGifDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<10)return null;let sig=buffer.
215
+ slice(0,6).toString("ascii");if(sig!=="GIF87a"&&sig!=="GIF89a")return null;let width=buffer.readUInt16LE(6),height=buffer.readUInt16LE(8);return{widthPx:width,heightPx:height}}catch{return null}}function getWebpDimensions(base64Data){try{let buffer=Buffer.from(base64Data,"base64");if(buffer.length<30)return null;let riff=buffer.slice(0,4).toString("ascii"),webp=buffer.slice(8,12).toString("ascii");if(riff!=="RIFF"||webp!=="WEBP")return null;let chunk=buffer.slice(12,16).toString("ascii");if(chunk===
216
+ "VP8 "){if(buffer.length<30)return null;let width=buffer.readUInt16LE(26)&16383,height=buffer.readUInt16LE(28)&16383;return{widthPx:width,heightPx:height}}else if(chunk==="VP8L"){if(buffer.length<25)return null;let bits=buffer.readUInt32LE(21),width=(bits&16383)+1,height=(bits>>14&16383)+1;return{widthPx:width,heightPx:height}}else if(chunk==="VP8X"){if(buffer.length<30)return null;let width=(buffer[24]|buffer[25]<<8|buffer[26]<<16)+1,height=(buffer[27]|buffer[28]<<8|buffer[29]<<16)+1;return{widthPx:width,
217
+ heightPx:height}}return null}catch{return null}}function getImageDimensions(base64Data,mimeType){return mimeType==="image/png"?getPngDimensions(base64Data):mimeType==="image/jpeg"?getJpegDimensions(base64Data):mimeType==="image/gif"?getGifDimensions(base64Data):mimeType==="image/webp"?getWebpDimensions(base64Data):null}function renderImage(base64Data,imageDimensions,options={}){let caps=getCapabilities();if(!caps.images)return null;let maxWidth=options.maxWidthCells??80,size=calculateImageCellSize(
218
+ imageDimensions,maxWidth,options.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.images==="kitty"?(options.imageId!==void 0&&registerKittyImageMetadata({imageId:options.imageId,columns:size.columns,rows:size.rows,widthPx:imageDimensions.widthPx,heightPx:imageDimensions.heightPx}),{sequence:encodeKitty(base64Data,{columns:size.columns,rows:size.rows,imageId:options.imageId,moveCursor:options.moveCursor}),columns:size.columns,rows:size.rows,imageId:options.imageId}):caps.images===
219
+ "iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options.preserveAspectRatio??!0}),columns:size.columns,rows:size.rows}:null}function hyperlink(text,url){return`\x1B]8;;${url}\x1B\\${text}\x1B]8;;\x1B\\`}function shortenImagePath(filename){let home=homedir2();return home&&(filename===home||filename.startsWith(`${home}/`)||filename.startsWith(`${home}\\`))?`~${filename.slice(home.length)}`:filename}function imageFallback(mimeType,dimensions,filename){
220
+ let parts=[];if(filename){let display=shortenImagePath(filename);getCapabilities().hyperlinks&&isAbsolute(filename)?parts.push(hyperlink(display,pathToFileURL(filename).href)):parts.push(display)}return parts.push(`[${mimeType}]`),dimensions&&parts.push(`${dimensions.widthPx}x${dimensions.heightPx}`),`[Image: ${parts.join(" ")}]`}var generation=0;function renderedMarkdownGeneration(){return generation}function invalidateRenderedMarkdown(){generation++}function hexToRgb(hex){let normalized=hex.startsWith("#")?hex.slice(1):hex,r=parseInt(normalized.slice(0,2),16),g=parseInt(normalized.slice(2,4),16),b=parseInt(normalized.slice(4,6),16);return{r,g,b}}function parseOscHexChannel(channel){if(!/^[0-9a-f]+$/i.test(channel))return;let max=16**channel.length-1;if(!(max<=0))return Math.round(parseInt(channel,16)/max*255)}var OSC_COLOR_RESPONSE_PATTERN=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,COLOR_SCHEME_REPORT_PATTERN=/^(?:\x1b\[\?997;(1|2)n)+$/;
221
+ function parseOscColorResponse(data){let match=data.match(OSC_COLOR_RESPONSE_PATTERN);return match?{target:match[1]==="10"?"foreground":match[1]==="11"?"background":Number.parseInt(match[2],10),rgb:parseOscColorValue(match[3])}:void 0}function parseOscColorValue(rawValue){let value=rawValue.trim();if(value.startsWith("#")){let hex=value.slice(1);if(/^[0-9a-f]{6}$/i.test(hex))return hexToRgb(value);if(/^[0-9a-f]{12}$/i.test(hex)){let r2=parseOscHexChannel(hex.slice(0,4)),g2=parseOscHexChannel(hex.
222
+ slice(4,8)),b2=parseOscHexChannel(hex.slice(8,12));return r2!==void 0&&g2!==void 0&&b2!==void 0?{r:r2,g:g2,b:b2}:void 0}return}let rgbValue=value.replace(/^rgba?:/i,""),[red,green,blue]=rgbValue.split("/");if(red===void 0||green===void 0||blue===void 0)return;let r=parseOscHexChannel(red),g=parseOscHexChannel(green),b=parseOscHexChannel(blue);return r!==void 0&&g!==void 0&&b!==void 0?{r,g,b}:void 0}function parseTerminalColorSchemeReport(data){let match=data.match(COLOR_SCHEME_REPORT_PATTERN);if(match)
223
+ return match[1]==="2"?"light":"dark"}function dispatchMouseEvent(component,event){let result=component.handleMouse?.(event);if(result){if("target"in result){let forwarded=result;return forwarded.focus&&component.handleInput?{...forwarded,focusTarget:component}:forwarded}if(!(!result.handled&&!result.capture&&!result.focus))return{...result,handled:!0,...result.focus?{focusTarget:component}:{},target:{component,originX:event.screenX-event.x,originY:event.screenY-event.y,width:event.width,height:event.height}}}}function retargetMouseEvent(event,target){
224
+ return{...event,x:event.screenX-target.originX,y:event.screenY-target.originY,width:target.width,height:target.height}}var renderClock=()=>performance.now();function setRenderClockForTest(clock){renderClock=clock??(()=>performance.now())}var FRAME_SPACING_FACTOR=3,TERMINAL_PALETTE_SIZE=16,TERMINAL_COLOR_REPLY_COUNT=2+TERMINAL_PALETTE_SIZE,TERMINAL_COLOR_QUERY=`\x1B]10;?\x07\x1B]11;?\x07${Array.from({length:TERMINAL_PALETTE_SIZE},(_2,index)=>`\x1B]4;${index};?\x07`).join("")}\x1B[c`,DEVICE_ATTRIBUTES_RESPONSE_PATTERN=/^\x1b\[\?[\d;]*c$/;
225
+ function isFocusable(component){return component!==null&&"focused"in component}var CURSOR_MARKER="\x1B_pi:c\x07",FAKE_CURSOR_START="\x1B_pi:fc\x07",FAKE_CURSOR_END="\x1B_pi:/fc\x07",FOCUSED_FAKE_CURSOR=/(\x1b_pi:c\x07)\x1b_pi:fc\x07(.*?)(?:\x1b_pi:\/fc\x07|$)/s;function renderFakeCursor(text){return`${FAKE_CURSOR_START}${text}${FAKE_CURSOR_END}`}function parseSizeValue(value,referenceSize){if(value===void 0)return;if(typeof value=="number")return value;let match=value.match(/^(\d+(?:\.\d+)?)%$/);if(match)return Math.floor(referenceSize*parseFloat(match[1])/100)}var stableRenders=new WeakSet;function markStableRender(componentClass){stableRenders.add(componentClass.prototype.render)}function isStableRender(component){return component instanceof Container&&component.render===Container.prototype.render||stableRenders.has(component.render)}
226
+ function renderSharedLines(component,width){return component instanceof Container&&component.render===Container.prototype.render?component.renderShared(width):component.render(width)}var LIVE_LINE_EDITS_KEPT=32,LiveLineArray=class{lines=[];revision=0;starts=[];changedSince(revision){if(revision===this.revision)return Number.POSITIVE_INFINITY;let changes=this.revision-revision;if(changes<0||changes>this.starts.length)return 0;let start=Number.POSITIVE_INFINITY;for(let i=this.starts.length-changes;i<
227
+ this.starts.length;i++)start=Math.min(start,this.starts[i]);return start}edit(start){this.lines.length=Math.min(this.lines.length,start),this.revision++,this.starts.push(start),this.starts.length>LIVE_LINE_EDITS_KEPT&&this.starts.shift()}},liveRenders=new WeakMap;function markLiveRender(key,renderLive){liveRenders.set(key,renderLive)}function renderLiveLines(component,width){let key=component instanceof Container&&component.render===Container.prototype.render?component.renderShared:component.render;
228
+ return liveRenders.get(key)?.call(component,width)}function renderChildren(children,width,previous){let count=children.length,before=previous?.width===width?previous:void 0,index=0,offset=0,changedLines;if(before!==void 0){for(;index<count;index++){let child=children[index],lines=renderSharedLines(child,width);if(index>=before.children.length||before.children[index]!==child||!sameLines(child,lines,before,index,offset)){changedLines=lines;break}offset+=lines.length}if(index===count&&count===before.
229
+ children.length)return before}let arrays=new Array(count),heights=new Array(count);for(let i=0;i<index;i++)arrays[i]=before.arrays[i],heights[i]=before.heights[i];let first=index;for(;index<count;index++){let lines=changedLines??renderSharedLines(children[index],width);changedLines=void 0,arrays[index]=lines,heights[index]=lines.length}let joined=before!==void 0&&offset>0?before.lines.slice(0,offset):[];for(let i=first;i<count;i+=1024)joined=joined.concat(...arrays.slice(i,Math.min(count,i+1024)));
230
+ return{width,children:children.slice(),arrays,heights,lines:joined}}function sameLines(child,lines,previous,index,offset){if(isStableRender(child))return lines===previous.arrays[index];let height=previous.heights[index];if(lines.length!==height)return!1;let joined=previous.lines;for(let i=0;i<height;i++)if(lines[i]!==joined[offset+i])return!1;return!0}var reportingRenders=new WeakSet,unreportedSubtrees=new WeakSet,renderOwners=new WeakMap;function liveRenderOwners(child){let owners=renderOwners.
231
+ get(child);if(owners===void 0)return;if(!Array.isArray(owners)){if(owners.deref()!==void 0)return owners;renderOwners.delete(child);return}let count=0;for(let ref of owners)ref.deref()!==void 0&&(owners[count++]=ref);if(owners.length=count,count>1)return owners;let remaining=owners[0];return remaining===void 0?renderOwners.delete(child):renderOwners.set(child,remaining),remaining}var CHILD_CHANGED=Symbol("pi-tui.childChanged");function renderKey(component){return component instanceof Container&&
232
+ component.render===Container.prototype.render?component.renderShared:component.render}function markReportsChanges(componentClass){let prototype=componentClass.prototype;reportingRenders.add(prototype.render===Container.prototype.render?prototype.renderShared:prototype.render)}var changeReportsUsed=!0;function setChangeReportsForTest(enabled){changeReportsUsed=enabled}function reportsChanges(component){return changeReportsUsed&&reportingRenders.has(renderKey(component))&&!unreportedSubtrees.has(component)}
233
+ function setSubtreeReportsChanges(component,reports){reports?unreportedSubtrees.delete(component):unreportedSubtrees.add(component)}function setRenderOwner(child,owner){let owners=liveRenderOwners(child);owners===void 0?renderOwners.set(child,new WeakRef(owner)):Array.isArray(owners)?owners.some(ref=>ref.deref()===owner)||owners.push(new WeakRef(owner)):owners.deref()!==owner&&renderOwners.set(child,[owners,new WeakRef(owner)])}function dropRenderOwner(child,owner){let owners=liveRenderOwners(child);
234
+ if(owners!==void 0)if(Array.isArray(owners)){let index=owners.findIndex(ref=>ref.deref()===owner);index!==-1&&owners.splice(index,1),liveRenderOwners(child)}else owners.deref()===owner&&renderOwners.delete(child)}function renderChildLines(owner,child,width){return setRenderOwner(child,owner),renderSharedLines(child,width)}function reportRenderChange(component){let owners=liveRenderOwners(component);if(owners!==void 0)if(Array.isArray(owners))for(let ref of owners.slice()){let owner=ref.deref();owner!==
235
+ void 0&&notifyOwner(owner,component)}else{let owner=owners.deref();owner!==void 0&&notifyOwner(owner,component)}}function notifyOwner(owner,child){owner instanceof Container?owner[CHILD_CHANGED](child):reportRenderChange(owner)}var LISTED_CHANGES=64;function emptyContainerLines(width){return{width,children:[],arrays:[],lives:[],revisions:[],heights:[],offsets:[],reports:[],unreported:[],live:new LiveLineArray}}function sameLinesAt(lines,joined,offset,count){if(lines.length!==count)return!1;for(let i=0;i<
236
+ count;i++)if(lines[i]!==joined[offset+i])return!1;return!0}function renderChildForContainer(owner,child,width){setRenderOwner(child,owner);let live=renderLiveLines(child,width);return live===void 0?{lines:renderSharedLines(child,width),live:void 0,revision:-1}:{lines:live.lines,live,revision:live.revision}}function childChangedFrom(before,index,child,rendered,joined,offset){return index>=before.children.length?0:rendered.live!==void 0?before.lives[index]===rendered.live&&before.arrays[index]===rendered.
237
+ lines?rendered.live.changedSince(before.revisions[index]):0:before.lives[index]!==void 0?0:before.children[index]===child&&before.arrays[index]===rendered.lines&&isStableRender(child)||sameLinesAt(rendered.lines,joined,offset,before.heights[index])?Number.POSITIVE_INFINITY:0}var Container=class{childList=[];rendered;sharedLines;changedChildren=[];changesUnlisted=!1;childrenUsed=!1;changeReported=!1;get children(){return this.noteChildrenUsed(),this.childList}set children(children){this.childList=
238
+ children,this.noteChildrenUsed()}ownChildren(){return Object.hasOwn(this,"children")?this.children:this.childList}noteChildrenUsed(){this.childrenUsed=!0,this.reportChange()}reportChange(){this.changeReported||(this.changeReported=!0,reportRenderChange(this))}noteRendered(){this.changeReported=!1}[CHILD_CHANGED](child){if(this.rendered!==void 0&&!this.changesUnlisted){let changed=this.changedChildren;changed[changed.length-1]!==child&&(changed.length<LISTED_CHANGES?changed.push(child):this.changesUnlisted=
239
+ !0)}this.reportChange()}addChild(component){this.ownChildren().push(component),this.noteChildrenUsed()}removeChild(component){let children=this.ownChildren(),index=children.indexOf(component);index!==-1&&(children.splice(index,1),this.noteChildrenUsed())}clear(){Object.hasOwn(this,"children")?this.children=[]:this.childList=[],this.noteChildrenUsed()}invalidate(){this.rendered=void 0,this.sharedLines=void 0,this.changedChildren=[],this.changesUnlisted=!1;for(let child of this.ownChildren())child.
240
+ invalidate?.();this.reportChange()}handleMouse(event){if(event.y<0||event.y>=event.height)return;let rendered=this.rendered?.width===event.width?this.rendered:void 0,children=rendered?.children??this.ownChildren(),childY=0;for(let i=0;i<children.length;i++){let child=children[i],childHeight=rendered?rendered.heights[i]:child.render(event.width).length;if(event.y>=childY&&event.y<childY+childHeight){let result=dispatchMouseEvent(child,{...event,y:event.y-childY,height:childHeight});return result?.
241
+ focus&&this.handleInput?{...result,focusTarget:this}:result}childY+=childHeight}}renderLiveChildren(width){this.changeReported=!1;let children=this.ownChildren(),shadowed=children!==this.childList,count=children.length,state=this.rendered;(state===void 0||state.width!==width)&&(state=emptyContainerLines(width),this.rendered=state);let before=state,joined=before.live.lines,beforeCount=before.children.length,changed=this.changedChildren;changed.length>0&&(this.changedChildren=[]);let renderAll=this.
242
+ changesUnlisted||shadowed;this.changesUnlisted=!1;let tail=count;if(this.childrenUsed||renderAll||beforeCount!==count){this.childrenUsed=!1;let common=Math.min(count,beforeCount),index=0;for(;index<common&&children[index]===before.children[index];)index++;(index<common||count!==beforeCount)&&(tail=index)}let again;if(renderAll){again=[];for(let i=0;i<tail;i++)again.push(i)}else{again=[];for(let i=0;i<changed.length;i++){let child=changed[i],index=before.children.lastIndexOf(child);index===-1?dropRenderOwner(
243
+ child,this):index<tail&&again.push(index)}let unreported=before.unreported;for(let i=0;i<unreported.length;i++){let index=unreported[i];if(index>=tail)break;again.push(index)}again.length>1&&(again.sort((a,b)=>a-b),again=again.filter((index,i)=>i===0||index!==again[i-1]))}let changeAt=Number.POSITIVE_INFINITY,firstChanged=tail,reportsChanged=!1;for(let i=0;i<again.length;i++){let index=again[i],child=children[index],rendered=renderChildForContainer(this,child,width),changedFrom=childChangedFrom(
244
+ before,index,child,rendered,joined,before.offsets[index]);changedFrom!==Number.POSITIVE_INFINITY&&(changeAt=Math.min(changeAt,before.offsets[index]+changedFrom)),rendered.lines.length!==before.heights[index]&&(firstChanged=Math.min(firstChanged,index)),before.arrays[index]=rendered.lines,before.lives[index]=rendered.live,before.revisions[index]=rendered.revision,before.heights[index]=rendered.lines.length;let reports=reportsChanges(child);reports!==before.reports[index]&&(before.reports[index]=reports,
245
+ reportsChanged=!0)}if(tail<count||tail<beforeCount){let moved=new Map;for(let i=beforeCount-1;i>=tail;i--)moved.set(before.children[i],i);let changedSet=changed.length>0?new Set(changed):void 0,tailChildren=[],tailLines=[],tailReports=[],offset=tail<beforeCount?before.offsets[tail]:tail===0?0:before.offsets[tail-1]+before.heights[tail-1];for(let i=tail;i<count;i++){let child=children[i],from=moved.get(child),rendered,reports,live=from===void 0?void 0:before.lives[from];if(from!==void 0&&!renderAll&&
246
+ before.reports[from]===!0&&changedSet?.has(child)!==!0&&(live===void 0||live.revision===before.revisions[from])?(moved.delete(child),rendered={lines:before.arrays[from],live,revision:before.revisions[from]},reports=!0):(from!==void 0&&moved.delete(child),rendered=renderChildForContainer(this,child,width),reports=reportsChanges(child)),changeAt===Number.POSITIVE_INFINITY){let changedFrom=childChangedFrom(before,i,child,rendered,joined,offset);changedFrom!==Number.POSITIVE_INFINITY&&(changeAt=offset+
247
+ changedFrom)}tailChildren.push(child),tailLines.push(rendered),tailReports.push(reports),offset+=rendered.lines.length}changeAt===Number.POSITIVE_INFINITY&&count!==beforeCount&&(changeAt=offset),before.children.length=tail,before.arrays.length=tail,before.lives.length=tail,before.revisions.length=tail,before.heights.length=tail,before.offsets.length=tail,before.reports.length=tail;for(let i=0;i<tailChildren.length;i++){let rendered=tailLines[i];before.children.push(tailChildren[i]),before.arrays.
248
+ push(rendered.lines),before.lives.push(rendered.live),before.revisions.push(rendered.revision),before.heights.push(rendered.lines.length),before.offsets.push(0),before.reports.push(tailReports[i])}reportsChanged=!0}if(changeAt!==Number.POSITIVE_INFINITY){let first=Math.min(firstChanged,count);for(;first>0&&before.offsets[first-1]+before.heights[first-1]>changeAt;)first--;for(;first<count&&first<firstChanged&&before.offsets[first]+before.heights[first]<=changeAt;)first++;firstChanged=Math.min(firstChanged,
249
+ first)}if(firstChanged<count){let offset=firstChanged===0?0:before.offsets[firstChanged-1]+before.heights[firstChanged-1];for(let i=firstChanged;i<count;i++){let live=before.lives[i];if(live!==void 0&&live.revision!==before.revisions[i]&&changeAt<=offset){let rendered=renderChildForContainer(this,children[i],width);before.arrays[i]=rendered.lines,before.lives[i]=rendered.live,before.revisions[i]=rendered.revision,before.heights[i]=rendered.lines.length}before.offsets[i]=offset,offset+=before.heights[i]}}
250
+ if(changeAt!==Number.POSITIVE_INFINITY){before.live.edit(changeAt);for(let i=firstChanged;i<count;i++){if(before.offsets[i]+before.heights[i]<=changeAt)continue;let lines=before.arrays[i];for(let j2=Math.max(0,changeAt-before.offsets[i]);j2<lines.length;j2++)joined.push(lines[j2])}}if(reportsChanged){before.unreported.length=0;for(let i=0;i<count;i++)before.reports[i]||before.unreported.push(i)}return setSubtreeReportsChanges(this,!shadowed&&before.unreported.length===0),before.live}renderShared(width){
251
+ let live=this.renderLiveChildren(width),shared=this.sharedLines;if(shared?.live===live&&shared.revision===live.revision)return shared.lines;let lines=live.lines.slice();return this.sharedLines={live,revision:live.revision,lines},lines}render(width){return this.renderShared(width).slice()}static renderLive(container,width){return container.renderLiveChildren(width)}};markLiveRender(Container.prototype.renderShared,function(width){return Container.renderLive(this,width)});markReportsChanges(Container);
252
+ var SEGMENT_RESET="\x1B[0m\x1B]8;;\x07";function compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth){if(isImageLine(baseLine))return baseLine;let afterStart=startCol+overlayWidth,base=extractSegments(baseLine,startCol,afterStart,totalWidth-afterStart,!0),overlay=sliceWithWidth(overlayLine,0,overlayWidth,!0),beforePad=Math.max(0,startCol-base.beforeWidth),overlayPad=Math.max(0,overlayWidth-overlay.width),actualBeforeWidth=Math.max(startCol,base.beforeWidth),actualOverlayWidth=Math.
253
+ max(overlayWidth,overlay.width),afterTarget=Math.max(0,totalWidth-actualBeforeWidth-actualOverlayWidth),afterPad=Math.max(0,afterTarget-base.afterWidth),result=base.before+" ".repeat(beforePad)+SEGMENT_RESET+overlay.text+" ".repeat(overlayPad)+SEGMENT_RESET+base.after+" ".repeat(afterPad);return visibleWidth(result)<=totalWidth?result:sliceByColumn(result,0,totalWidth,!0)}var VIEWPORT_TUI=Symbol.for("@earendil-works/pi-tui/viewport");function isViewportTUI(tui){return tui[VIEWPORT_TUI]===!0}var TuiBase=class _TuiBase extends Container{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;deferredRenderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;lastFrameDuration=0;nextFrameUnspaced=!0;nextFrameForInput=!1;handlingInput=!1;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){
254
+ return this.overlayStack.length>0}overlayFocusRestore={status:"inactive"};constructor(terminal,showHardwareCursor,logDirectory){super(),this.terminal=terminal,this.logDirectory=logDirectory,showHardwareCursor!==void 0&&(this.showHardwareCursor=showHardwareCursor)}renderFrame(){let start=renderClock();this.deferredRenderTimer&&(clearTimeout(this.deferredRenderTimer),this.deferredRenderTimer=void 0),this.doRender(),this.lastFrameDuration=this.nextFrameUnspaced?0:renderClock()-start,this.nextFrameUnspaced=
255
+ !1,this.nextFrameForInput=!1}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(_options){}afterTerminalStop(_options){}getExitRestorePrefix(){return`${this.terminalColorSchemeNotificationsEnabled?"\x1B[?2031l":""}\x1B[?25h`}getExitRestoreSuffix(){return""}exitRestoreHandler=()=>{if(!this.stopped)try{this.terminal.restoreOnExit?.(this.getExitRestorePrefix(),this.getExitRestoreSuffix())}catch{}};get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){
256
+ return this.showHardwareCursor}setShowHardwareCursor(enabled){this.showHardwareCursor!==enabled&&(this.showHardwareCursor=enabled,enabled||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(enabled){this.clearOnShrink=enabled}getFocusedComponent(){return this.focusedComponent}setFocus(component){this.setFocusInternal({component,overlayFocusRestore:"clear"})}setFocusInternal({component,overlayFocusRestore}){let previousFocus=this.focusedComponent,
257
+ nextFocus=component,previousFocusedOverlay=previousFocus?this.overlayStack.find(entry=>entry.component===previousFocus&&this.isOverlayVisible(entry)):void 0,nextFocusIsOverlay=nextFocus?this.overlayStack.some(entry=>entry.component===nextFocus):!1,restoreState=this.getVisibleOverlayFocusRestore();nextFocus&&!nextFocusIsOverlay?restoreState.status==="blocked"&&restoreState.blockedBy===previousFocus?restoreState.resume.status==="focus-target"||!this.isComponentMounted(restoreState.blockedBy)?nextFocus=
258
+ this.resolveBlockedOverlayFocusResume(restoreState):this.overlayFocusRestore={status:"blocked",overlay:restoreState.overlay,blockedBy:nextFocus,resume:restoreState.resume}:previousFocusedOverlay&&restoreState.status!=="inactive"&&restoreState.overlay===previousFocusedOverlay&&!this.isOverlayFocusAncestor(previousFocusedOverlay,nextFocus)&&(this.overlayFocusRestore={status:"blocked",overlay:previousFocusedOverlay,blockedBy:nextFocus,resume:{status:"restore-overlay"}}):nextFocus===null&&(restoreState.
259
+ status==="blocked"&&restoreState.blockedBy===previousFocus?nextFocus=this.resolveBlockedOverlayFocusResume(restoreState):overlayFocusRestore==="clear"&&this.clearOverlayFocusRestore()),isFocusable(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=nextFocus,isFocusable(nextFocus)&&(nextFocus.focused=!0);let focusedOverlay=nextFocus?this.overlayStack.find(entry=>entry.component===nextFocus&&this.isOverlayVisible(entry)):void 0;focusedOverlay&&(this.overlayFocusRestore=
260
+ {status:"eligible",overlay:focusedOverlay})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:"inactive"}}clearOverlayFocusRestoreFor(overlay){this.overlayFocusRestore.status!=="inactive"&&this.overlayFocusRestore.overlay===overlay&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(restoreState){return restoreState.resume.status==="restore-overlay"?restoreState.overlay.component:(this.clearOverlayFocusRestore(),restoreState.resume.target)}getVisibleOverlayFocusRestore(){
261
+ let restoreState=this.overlayFocusRestore;return restoreState.status==="inactive"?restoreState:!this.overlayStack.includes(restoreState.overlay)||!this.isOverlayVisible(restoreState.overlay)?{status:"inactive"}:restoreState}isOverlayFocusAncestor(entry,component){let visited=new Set,current=entry.preFocus;for(;current&&!visited.has(current);){if(visited.add(current),current===component)return!0;current=this.overlayStack.find(overlay=>overlay.component===current)?.preFocus??null}return!1}retargetOverlayPreFocus(removed){
262
+ for(let overlay of this.overlayStack)overlay!==removed&&overlay.preFocus===removed.component&&(overlay.preFocus=removed.preFocus)}getMountedRoots(){return this.children}isComponentMounted(component){return this.getMountedRoots().some(child=>this.containsComponent(child,component))}containsComponent(root,target){return root===target?!0:root instanceof Container?root.children.some(child=>this.containsComponent(child,target)):!1}showOverlay(component,options){let entry={component,...options===void 0?
263
+ {}:{options},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(entry),!options?.nonCapturing&&this.isOverlayVisible(entry)&&this.setFocus(component),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let index=this.overlayStack.indexOf(entry);if(index!==-1){if(this.clearOverlayFocusRestoreFor(entry),this.retargetOverlayPreFocus(entry),this.overlayStack.splice(index,1),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();
264
+ this.setFocus(topVisible?.component??entry.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},setHidden:hidden=>{if(entry.hidden!==hidden){if(entry.hidden=hidden,hidden){if(this.clearOverlayFocusRestoreFor(entry),this.focusedComponent===component){let topVisible=this.getTopmostVisibleOverlay();this.setFocus(topVisible?.component??entry.preFocus)}}else!options?.nonCapturing&&this.isOverlayVisible(entry)&&(entry.focusOrder=++this.focusOrderCounter,this.setFocus(
265
+ component));this.requestRender()}},isHidden:()=>entry.hidden,focus:()=>{!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||(entry.focusOrder=++this.focusOrderCounter,this.setFocus(component),this.requestRender())},unfocus:unfocusOptions=>{let isFocused=this.focusedComponent===component,restoreState=this.overlayFocusRestore,hasPendingRestore=restoreState.status!=="inactive"&&restoreState.overlay===entry;if(!(!isFocused&&!hasPendingRestore)){if(restoreState.status==="blocked"&&restoreState.
266
+ overlay===entry&&this.focusedComponent===restoreState.blockedBy){unfocusOptions?this.overlayFocusRestore={status:"blocked",overlay:entry,blockedBy:restoreState.blockedBy,resume:{status:"focus-target",target:unfocusOptions.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(entry),isFocused||unfocusOptions){let topVisible=this.getTopmostVisibleOverlay(),fallbackTarget=topVisible&&topVisible!==entry?topVisible.component:entry.preFocus;this.setFocus(
267
+ unfocusOptions?unfocusOptions.target:fallbackTarget)}this.requestRender()}},isFocused:()=>this.focusedComponent===component,getBounds:()=>{if(!(!this.overlayStack.includes(entry)||!this.isOverlayVisible(entry)||!entry.bounds))return{...entry.bounds}}}}hideOverlay(){let overlay=this.overlayStack[this.overlayStack.length-1];if(overlay){if(this.clearOverlayFocusRestoreFor(overlay),this.retargetOverlayPreFocus(overlay),this.overlayStack.pop(),this.focusedComponent===overlay.component){let topVisible=this.
268
+ getTopmostVisibleOverlay();this.setFocus(topVisible?.component??overlay.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.some(o=>this.isOverlayVisible(o))}isOverlayFocused(){return this.overlayStack.some(entry=>entry.component===this.focusedComponent&&this.isOverlayVisible(entry))}resolveMouseFocusTarget(component){for(let index=this.overlayStack.length-1;index>=
269
+ 0;index--){let overlay=this.overlayStack[index];if(this.isOverlayVisible(overlay)&&this.containsComponent(overlay.component,component))return overlay.component}return component}dispatchMouseToOverlay(event){for(let index=this.renderedOverlayLayouts.length-1;index>=0;index--){let layout=this.renderedOverlayLayouts[index];if(event.screenX<layout.col||event.screenX>=layout.col+layout.width||event.screenY<layout.row||event.screenY>=layout.row+layout.height)continue;let result=dispatchMouseEvent(layout.
270
+ entry.component,{...event,x:event.screenX-layout.col,y:event.screenY-layout.row,width:layout.width,height:layout.height});return result?{hit:!0,result:result.focus?{...result,focusTarget:layout.entry.component}:result}:{hit:!0}}return{hit:!1}}isOverlayVisible(entry){return entry.hidden?!1:entry.options?.visible?entry.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let topmost;for(let overlay of this.overlayStack)overlay.options?.nonCapturing||!this.isOverlayVisible(
271
+ overlay)||(!topmost||overlay.focusOrder>topmost.focusOrder)&&(topmost=overlay);return topmost}invalidate(){invalidateRenderedMarkdown();for(let root of this.getMountedRoots())root.invalidate();for(let overlay of this.overlayStack)overlay.component.invalidate()}start(){this.stopped=!1,this.nextFrameUnspaced=!0,process.off("exit",this.exitRestoreHandler),process.on("exit",this.exitRestoreHandler),this.beforeTerminalStart(),this.terminal.start(data=>{this.handlingInput=!0;try{this.handleTerminalInput(
272
+ data)}finally{this.handlingInput=!1}},()=>{this.nextFrameUnspaced=!0,this.requestRender()}),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031h"),this.queryCellSize(),this.requestRender()}addInputListener(listener){return this.inputListeners.add(listener),()=>{this.inputListeners.delete(listener)}}removeInputListener(listener){this.inputListeners.delete(listener)}onTerminalColorSchemeChange(listener){return this.terminalColorSchemeListeners.
273
+ add(listener),()=>{this.terminalColorSchemeListeners.delete(listener)}}setTerminalColorSchemeNotifications(enabled){this.terminalColorSchemeNotificationsEnabled!==enabled&&(this.terminalColorSchemeNotificationsEnabled=enabled,this.stopped||this.terminal.write(enabled?"\x1B[?2031h":"\x1B[?2031l"))}queryCellSize(){getCapabilities().images&&this.terminal.write("\x1B[16t")}stop(options={}){this.stopped=!0,process.off("exit",this.exitRestoreHandler),this.cancelRenderTimer(),this.deferredRenderTimer&&
274
+ (clearTimeout(this.deferredRenderTimer),this.deferredRenderTimer=void 0),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write("\x1B[?2031l"),this.beforeTerminalStop(options),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(options)}renderNow(force=!1){force&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=renderClock(),this.renderFrame()}requestRender(force=!1){if(force){this.resetRenderState(),this.nextFrameUnspaced=!0,
275
+ this.requestImmediateRender();return}this.handlingInput&&!this.nextFrameForInput&&(this.nextFrameForInput=!0,this.renderTimer&&(this.cancelRenderTimer(),process.nextTick(()=>this.scheduleRender()))),!this.renderRequested&&(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestRenderWithin(delayMs){this.stopped||this.renderRequested||this.deferredRenderTimer||(this.deferredRenderTimer=setTimeout(()=>{this.deferredRenderTimer=void 0,this.requestRender()},delayMs))}requestImmediateRender(){
276
+ this.cancelRenderTimer(),this.renderRequested=!0,!this.immediateRenderScheduled&&(this.immediateRenderScheduled=!0,process.nextTick(()=>{this.immediateRenderScheduled=!1,!(this.stopped||!this.renderRequested)&&(this.cancelRenderTimer(),this.renderRequested=!1,this.lastRenderAt=renderClock(),this.renderFrame())}))}cancelRenderTimer(){this.renderTimer&&(clearTimeout(this.renderTimer),this.renderTimer=void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let elapsed=renderClock()-
277
+ this.lastRenderAt,spacing=this.nextFrameUnspaced||this.nextFrameForInput?0:FRAME_SPACING_FACTOR*this.lastFrameDuration,delay=Math.max(0,Math.max(_TuiBase.MIN_RENDER_INTERVAL_MS,spacing)-elapsed);this.renderTimer=setTimeout(()=>this.renderTimedFrame(),delay)}renderTimedFrame(){this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=renderClock(),this.renderFrame(),this.renderRequested&&this.scheduleRender())}handleTerminalInput(data){if(this.consumeTerminalColorResponse(
278
+ data)||this.consumeTerminalColorSchemeReport(data))return;if(this.inputListeners.size>0){let current=data;for(let listener of this.inputListeners){let result=listener(current);if(result?.consume)return;result?.data!==void 0&&(current=result.data)}if(current.length===0)return;data=current}if(this.consumeCellSizeResponse(data))return;if(matchesKey(data,"shift+ctrl+d")&&this.onDebug){this.onDebug();return}let focusedOverlay=this.overlayStack.find(o=>o.component===this.focusedComponent);if(focusedOverlay&&
279
+ !this.isOverlayVisible(focusedOverlay)){let topVisible=this.getTopmostVisibleOverlay();topVisible?this.setFocus(topVisible.component):this.setFocusInternal({component:focusedOverlay.preFocus,overlayFocusRestore:"preserve"})}if(!this.overlayStack.some(o=>o.component===this.focusedComponent)){let restoreState=this.getVisibleOverlayFocusRestore();restoreState.status==="eligible"?this.setFocus(restoreState.overlay.component):restoreState.status==="blocked"&&restoreState.blockedBy!==this.focusedComponent&&
280
+ (restoreState.resume.status==="restore-overlay"?this.setFocus(restoreState.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(restoreState.resume.target)))}if(this.focusedComponent?.handleInput){if(isKeyRelease(data)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(data),this.requestImmediateRender()}}consumeTerminalColorResponse(data){let query=this.pendingTerminalColorQueries[0];if(!query)return!1;if(DEVICE_ATTRIBUTES_RESPONSE_PATTERN.test(data))return this.
281
+ pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(query),!0;let response=parseOscColorResponse(data);if(!response)return!1;let{target,rgb}=response,key=String(target);return!query.deliver||query.replied.has(key)||(query.replied.add(key),target==="foreground"?query.foreground=rgb:target==="background"?query.background=rgb:target<TERMINAL_PALETTE_SIZE&&(query.palette[target]=rgb),query.replied.size===TERMINAL_COLOR_REPLY_COUNT&&this.completeTerminalColorQuery(query)),!0}terminalColorQueryResult(query){
282
+ let palette=query.palette.every(color=>color!==void 0)?query.palette:void 0;return{foreground:query.foreground,background:query.background,palette}}completeTerminalColorQuery(query){let deliver=query.deliver;query.deliver=void 0,clearTimeout(query.timer),deliver?.(this.terminalColorQueryResult(query))}consumeTerminalColorSchemeReport(data){let scheme=parseTerminalColorSchemeReport(data);if(!scheme)return!1;for(let listener of this.terminalColorSchemeListeners)listener(scheme);return!0}consumeCellSizeResponse(data){
283
+ let match=data.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!match)return!1;let heightPx=parseInt(match[1],10),widthPx=parseInt(match[2],10);return heightPx<=0||widthPx<=0||(setCellDimensions({widthPx,heightPx}),this.invalidate(),this.requestRender()),!0}resolveOverlayLayout(options,overlayHeight,termWidth,termHeight){let opt=options??{},margin=typeof opt.margin=="number"?{top:opt.margin,right:opt.margin,bottom:opt.margin,left:opt.margin}:opt.margin??{},marginTop=Math.max(0,margin.top??0),marginRight=Math.
284
+ max(0,margin.right??0),marginBottom=Math.max(0,margin.bottom??0),marginLeft=Math.max(0,margin.left??0),availWidth=Math.max(1,termWidth-marginLeft-marginRight),availHeight=Math.max(1,termHeight-marginTop-marginBottom),width=parseSizeValue(opt.width,termWidth)??Math.min(80,availWidth);opt.minWidth!==void 0&&(width=Math.max(width,opt.minWidth)),width=Math.max(1,Math.min(width,availWidth));let maxHeight=parseSizeValue(opt.maxHeight,termHeight);maxHeight!==void 0&&(maxHeight=Math.max(1,Math.min(maxHeight,
285
+ availHeight)));let effectiveHeight=maxHeight!==void 0?Math.min(overlayHeight,maxHeight):overlayHeight,row,col;if(opt.row!==void 0)if(typeof opt.row=="string"){let match=opt.row.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxRow=Math.max(0,availHeight-effectiveHeight),percent=parseFloat(match[1])/100;row=marginTop+Math.floor(maxRow*percent)}else row=this.resolveAnchorRow("center",effectiveHeight,availHeight,marginTop)}else row=opt.row;else{let anchor=opt.anchor??"center";row=this.resolveAnchorRow(anchor,
286
+ effectiveHeight,availHeight,marginTop)}if(opt.col!==void 0)if(typeof opt.col=="string"){let match=opt.col.match(/^(\d+(?:\.\d+)?)%$/);if(match){let maxCol=Math.max(0,availWidth-width),percent=parseFloat(match[1])/100;col=marginLeft+Math.floor(maxCol*percent)}else col=this.resolveAnchorCol("center",width,availWidth,marginLeft)}else col=opt.col;else{let anchor=opt.anchor??"center";col=this.resolveAnchorCol(anchor,width,availWidth,marginLeft)}return opt.offsetY!==void 0&&(row+=opt.offsetY),opt.offsetX!==
287
+ void 0&&(col+=opt.offsetX),row=Math.max(marginTop,Math.min(row,termHeight-marginBottom-effectiveHeight)),col=Math.max(marginLeft,Math.min(col,termWidth-marginRight-width)),{width,row,col,maxHeight}}resolveAnchorRow(anchor,height,availHeight,marginTop){switch(anchor){case"top-left":case"top-center":case"top-right":return marginTop;case"bottom-left":case"bottom-center":case"bottom-right":return marginTop+availHeight-height;case"left-center":case"center":case"right-center":return marginTop+Math.floor(
288
+ (availHeight-height)/2)}}resolveAnchorCol(anchor,width,availWidth,marginLeft){switch(anchor){case"top-left":case"left-center":case"bottom-left":return marginLeft;case"top-right":case"right-center":case"bottom-right":return marginLeft+availWidth-width;case"top-center":case"center":case"bottom-center":return marginLeft+Math.floor((availWidth-width)/2)}}compositeOverlays(lines,termWidth,termHeight){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],lines;let result=[...lines];for(let entry of this.
289
+ overlayStack)entry.bounds=void 0;let rendered=[],minLinesNeeded=result.length,visibleEntries=this.overlayStack.filter(e=>this.isOverlayVisible(e));visibleEntries.sort((a,b)=>a.focusOrder-b.focusOrder);for(let entry of visibleEntries){let{component,options}=entry,{width,maxHeight}=this.resolveOverlayLayout(options,0,termWidth,termHeight),overlayLines=this.resolveFakeCursors(component.render(width));maxHeight!==void 0&&overlayLines.length>maxHeight&&(overlayLines=overlayLines.slice(0,maxHeight));let{
290
+ row,col}=this.resolveOverlayLayout(options,overlayLines.length,termWidth,termHeight);entry.bounds={row,col,width,height:overlayLines.length},rendered.push({entry,overlayLines,row,col,w:width}),minLinesNeeded=Math.max(minLinesNeeded,row+overlayLines.length)}this.renderedOverlayLayouts=rendered.map(({entry,row,col,w:w2,overlayLines})=>({entry,row,col,width:w2,height:overlayLines.length}));let workingHeight=Math.max(result.length,termHeight,minLinesNeeded);for(;result.length<workingHeight;)result.push(
291
+ "");let viewportStart=Math.max(0,workingHeight-termHeight);for(let{overlayLines,row,col,w:w2}of rendered)for(let i=0;i<overlayLines.length;i++){let idx=viewportStart+row+i;if(idx>=0&&idx<result.length){let truncatedOverlayLine=visibleWidth(overlayLines[i])>w2?sliceByColumn(overlayLines[i],0,w2,!0):overlayLines[i];result[idx]=this.compositeLineAt(result[idx],truncatedOverlayLine,col,w2,termWidth)}}return result}applyLineResets(lines){let reset=SEGMENT_RESET;for(let i=0;i<lines.length;i++){let line=lines[i];
292
+ isImageLine(line)||(lines[i]=normalizeTerminalOutput(line.replaceAll(CURSOR_MARKER,""))+reset)}return lines}compositeLineAt(baseLine,overlayLine,startCol,overlayWidth,totalWidth){return compositeTuiLine(baseLine,overlayLine,startCol,overlayWidth,totalWidth)}extractCursorPosition(lines,height){let viewportTop=Math.max(0,lines.length-height);for(let row=lines.length-1;row>=viewportTop;row--){let line=lines[row],markerIndex=line.indexOf(CURSOR_MARKER);if(markerIndex!==-1){let beforeMarker=line.slice(
293
+ 0,markerIndex),col=visibleWidth(beforeMarker);return lines[row]=line.replaceAll(CURSOR_MARKER,""),{row,col}}}return null}resolveFakeCursors(lines){return lines.map(line=>line.includes(FAKE_CURSOR_START)?(this.showHardwareCursor?line.replace(FOCUSED_FAKE_CURSOR,"$1$2"):line).replaceAll(FAKE_CURSOR_START,"\x1B[7m").replaceAll(FAKE_CURSOR_END,"\x1B[27m"):line)}queryTerminalColors({timeoutMs,onLateReply}){return new Promise(resolve=>{let query={palette:Array.from({length:TERMINAL_PALETTE_SIZE},()=>{}),
294
+ replied:new Set,deliver:resolve,timer:void 0};query.timer=setTimeout(()=>{query.deliver=onLateReply,resolve(this.terminalColorQueryResult(query))},timeoutMs),this.pendingTerminalColorQueries.push(query),this.terminal.write(TERMINAL_COLOR_QUERY)})}};var TUI_KEYBINDINGS={"tui.editor.cursorUp":{defaultKeys:"up",description:"Move cursor up"},"tui.editor.cursorDown":{defaultKeys:"down",description:"Move cursor down"},"tui.editor.historyPrevious":{defaultKeys:[],description:"Select previous prompt history entry"},"tui.editor.historyNext":{defaultKeys:[],description:"Select next prompt history entry"},"tui.editor.cursorLeft":{defaultKeys:["left","ctrl+b"],description:"Move cursor left"},"tui.editor.cursorRight":{defaultKeys:["right","ctrl+f"],description:"\
295
+ Move cursor right"},"tui.editor.cursorWordLeft":{defaultKeys:["alt+left","ctrl+left","alt+b"],description:"Move cursor word left"},"tui.editor.cursorWordRight":{defaultKeys:["alt+right","ctrl+right","alt+f"],description:"Move cursor word right"},"tui.editor.cursorLineStart":{defaultKeys:["home","ctrl+a"],description:"Move to line start"},"tui.editor.cursorLineEnd":{defaultKeys:["end","ctrl+e"],description:"Move to line end"},"tui.editor.jumpForward":{defaultKeys:"ctrl+]",description:"Jump forwar\
296
+ d to character"},"tui.editor.jumpBackward":{defaultKeys:"ctrl+alt+]",description:"Jump backward to character"},"tui.editor.pageUp":{defaultKeys:["pageUp","ctrl+pageUp"],description:"Page up"},"tui.editor.pageDown":{defaultKeys:["pageDown","ctrl+pageDown"],description:"Page down"},"tui.editor.deleteCharBackward":{defaultKeys:"backspace",description:"Delete character backward"},"tui.editor.deleteCharForward":{defaultKeys:["delete","ctrl+d"],description:"Delete character forward"},"tui.editor.delet\
297
+ eWordBackward":{defaultKeys:["ctrl+w","alt+backspace"],description:"Delete word backward"},"tui.editor.deleteWordForward":{defaultKeys:["alt+d","alt+delete"],description:"Delete word forward"},"tui.editor.deleteToLineStart":{defaultKeys:"ctrl+u",description:"Delete to line start"},"tui.editor.deleteToLineEnd":{defaultKeys:"ctrl+k",description:"Delete to line end"},"tui.editor.yank":{defaultKeys:"ctrl+y",description:"Yank"},"tui.editor.yankPop":{defaultKeys:"alt+y",description:"Yank pop"},"tui.ed\
298
+ itor.undo":{defaultKeys:"ctrl+-",description:"Undo"},"tui.input.newLine":{defaultKeys:["shift+enter","ctrl+j"],description:"Insert newline"},"tui.input.submit":{defaultKeys:"enter",description:"Submit input"},"tui.input.tab":{defaultKeys:"tab",description:"Tab / autocomplete"},"tui.input.copy":{defaultKeys:"ctrl+c",description:"Copy selection"},"tui.select.up":{defaultKeys:"up",description:"Move selection up"},"tui.select.down":{defaultKeys:"down",description:"Move selection down"},"tui.select.p\
299
+ ageUp":{defaultKeys:"pageUp",description:"Selection page up"},"tui.select.pageDown":{defaultKeys:"pageDown",description:"Selection page down"},"tui.select.confirm":{defaultKeys:"enter",description:"Confirm selection"},"tui.select.cancel":{defaultKeys:["escape","ctrl+c"],description:"Cancel selection"},"tui.altScreen.pageUp":{defaultKeys:"pageUp",description:"Scroll viewport up one page"},"tui.altScreen.pageDown":{defaultKeys:"pageDown",description:"Scroll viewport down one page"},"tui.altScreen.\
300
+ halfPageUp":{defaultKeys:[],description:"Scroll viewport up half a page"},"tui.altScreen.halfPageDown":{defaultKeys:[],description:"Scroll viewport down half a page"},"tui.altScreen.lineUp":{defaultKeys:[],description:"Scroll viewport up one line"},"tui.altScreen.lineDown":{defaultKeys:[],description:"Scroll viewport down one line"},"tui.altScreen.previousPrompt":{defaultKeys:["ctrl+shift+up","ctrl+up"],description:"Jump to previous semantic prompt"},"tui.altScreen.nextPrompt":{defaultKeys:["ctr\
301
+ l+shift+down","ctrl+down"],description:"Jump to next semantic prompt"},"tui.altScreen.search":{defaultKeys:"ctrl+shift+f",description:"Search the primary scroll view"},"tui.altScreen.searchNext":{defaultKeys:["enter","ctrl+g"],description:"Select the next search match"},"tui.altScreen.searchPrevious":{defaultKeys:["shift+enter","ctrl+shift+g"],description:"Select the previous search match"},"tui.altScreen.searchClose":{defaultKeys:"escape",description:"Close transcript search"},"tui.altScreen.to\
302
+ p":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen.bottom":{defaultKeys:"ctrl+end",description:"Scroll viewport to bottom"}};function normalizeKeys(keys){if(keys===void 0)return[];let keyList=Array.isArray(keys)?keys:[keys],seen=new Set,result=[];for(let key of keyList)seen.has(key)||(seen.add(key),result.push(key));return result}var KeybindingsManager=class{definitions;userBindings;keysById=new Map;conflicts=[];constructor(definitions,userBindings={}){this.definitions=
303
+ definitions,this.userBindings=userBindings,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let userClaims=new Map;for(let[keybinding,keys]of Object.entries(this.userBindings))if(keybinding in this.definitions)for(let key of normalizeKeys(keys)){let claimants=userClaims.get(key)??new Set;claimants.add(keybinding),userClaims.set(key,claimants)}for(let[key,keybindings]of userClaims)keybindings.size>1&&this.conflicts.push({key,keybindings:[...keybindings]});for(let[id,definition]of Object.
304
+ entries(this.definitions)){let userKeys=this.userBindings[id],keys=normalizeKeys(userKeys===void 0?definition.defaultKeys:userKeys);this.keysById.set(id,keys)}}matches(data,keybinding){let keys=this.keysById.get(keybinding)??[];for(let key of keys)if(matchesKey(data,key))return!0;return!1}getKeys(keybinding){return[...this.keysById.get(keybinding)??[]]}getDefinition(keybinding){return this.definitions[keybinding]}getConflicts(){return this.conflicts.map(conflict=>({...conflict,keybindings:[...conflict.
305
+ keybindings]}))}setUserBindings(userBindings){this.userBindings=userBindings,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let resolved={};for(let id of Object.keys(this.definitions)){let keys=this.keysById.get(id)??[];resolved[id]=keys.length===1?keys[0]:[...keys]}return resolved}},globalKeybindings=null;function setKeybindings(keybindings){globalKeybindings=keybindings}function getKeybindings(){return globalKeybindings||(globalKeybindings=new KeybindingsManager(
306
+ TUI_KEYBINDINGS)),globalKeybindings}function getSelectPageIndex(keybindings,data,selectedIndex,itemCount,pageSize){let direction;if(keybindings.matches(data,"tui.select.pageUp"))direction=-1;else if(keybindings.matches(data,"tui.select.pageDown"))direction=1;else return;return Math.max(0,Math.min(itemCount-1,selectedIndex+direction*pageSize))}var Text=class{text;paddingX;paddingY;customBgFn;cachedText;cachedWidth;cachedLines;constructor(text="",paddingX=1,paddingY=1,customBgFn){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY,this.customBgFn=customBgFn}setText(text){text!==this.text&&(this.text=text,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,reportRenderChange(this))}setCustomBgFn(customBgFn){this.customBgFn=customBgFn,this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,reportRenderChange(
307
+ this)}setPaddingX(paddingX){this.paddingX=paddingX,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0,reportRenderChange(this)}render(width){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;if(!this.text||this.text.trim()===""){let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let normalizedText=this.text.replace(/\t/g," "),paddingX=Math.min(
308
+ this.paddingX,Math.max(0,Math.floor((width-1)/2))),contentWidth=Math.max(1,width-paddingX*2),wrappedLines=wrapTextWithAnsi(normalizedText,contentWidth),leftMargin=" ".repeat(paddingX),rightMargin=" ".repeat(paddingX),contentLines=[];for(let line of wrappedLines){let lineWithMargins=leftMargin+line+rightMargin;if(this.customBgFn)contentLines.push(applyBackgroundToLine(lineWithMargins,width,this.customBgFn));else{let visibleLen=visibleWidth(lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);
309
+ contentLines.push(lineWithMargins+" ".repeat(paddingNeeded))}}let emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=this.customBgFn?applyBackgroundToLine(emptyLine,width,this.customBgFn):emptyLine;emptyLines.push(line)}let result=[...emptyLines,...contentLines,...emptyLines];return flattenLines(result),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0?result:[""]}};markStableRender(Text);markReportsChanges(Text);var DEFAULT_PRIMARY_COLUMN_WIDTH=32,PRIMARY_COLUMN_GAP=2,MIN_DESCRIPTION_WIDTH=10,normalizeToSingleLine=text=>text.replace(/[\r\n]+/g," ").trim(),clamp=(value,min,max)=>Math.max(min,Math.min(value,max)),SelectList=class{capturesViewportInput=!0;items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(items,maxVisible,theme,layout={}){this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme,this.
310
+ layout=layout}setFilter(filter){this.filteredItems=this.items.filter(item=>item.value.toLowerCase().startsWith(filter.toLowerCase())),this.selectedIndex=0}setSelectedIndex(index){this.selectedIndex=Math.max(0,Math.min(index,this.filteredItems.length-1))}invalidate(){}render(width){let lines=[];if(this.filteredItems.length===0)return lines.push(this.theme.noMatch(" No matching commands")),lines;let primaryColumnWidth=this.getPrimaryColumnWidth(),{startIndex,endIndex}=this.getVisibleRange();for(let i=startIndex;i<
311
+ endIndex;i++){let item=this.filteredItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,descriptionSingleLine=item.description?normalizeToSingleLine(item.description):void 0;lines.push(this.renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth))}if(startIndex>0||endIndex<this.filteredItems.length){let scrollText=` (${this.selectedIndex+1}/${this.filteredItems.length})`;lines.push(this.theme.scrollInfo(truncateToWidth(scrollText,width-2,"")))}return lines}handleMouse(event){
312
+ if(this.filteredItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+delta)),this.selectedIndex!==previousIndex&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let{startIndex,endIndex}=this.getVisibleRange(),itemIndex=startIndex+
313
+ event.y;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=itemIndex,this.selectedIndex!==itemIndex&&(this.selectedIndex=itemIndex,this.notifySelectionChange()),{handled:!0,focus:!0};if(event.type==="click"){let clickedIndex=this.mousePressedIndex??itemIndex;this.mousePressedIndex=void 0;let changed=this.selectedIndex!==clickedIndex;this.selectedIndex=clickedIndex,changed&&this.notifySelectionChange();let selectedItem=this.filteredItems[this.selectedIndex];
314
+ return selectedItem&&this.onSelect?.(selectedItem),{handled:!0}}}}handleInput(keyData){let kb=getKeybindings(),pageIndex=getSelectPageIndex(kb,keyData,this.selectedIndex,this.filteredItems.length,this.maxVisible);if(kb.matches(keyData,"tui.select.up"))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(kb.matches(keyData,"tui.select.down"))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+
315
+ 1,this.notifySelectionChange();else if(pageIndex!==void 0){if(this.filteredItems.length===0||pageIndex===this.selectedIndex)return;this.selectedIndex=pageIndex,this.notifySelectionChange()}else if(kb.matches(keyData,"tui.select.confirm")){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelect&&this.onSelect(selectedItem)}else kb.matches(keyData,"tui.select.cancel")&&this.onCancel&&this.onCancel()}getVisibleRange(){let startIndex=Math.max(0,Math.min(this.selectedIndex-
316
+ Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,this.filteredItems.length)}}renderItem(item,isSelected,width,descriptionSingleLine,primaryColumnWidth){let prefix=isSelected?"\u2192 ":" ",prefixWidth=visibleWidth(prefix);if(descriptionSingleLine&&width>40){let effectivePrimaryColumnWidth=Math.max(1,Math.min(primaryColumnWidth,width-prefixWidth-4)),maxPrimaryWidth=Math.max(1,effectivePrimaryColumnWidth-PRIMARY_COLUMN_GAP),
317
+ truncatedValue2=this.truncatePrimary(item,isSelected,maxPrimaryWidth,effectivePrimaryColumnWidth),truncatedValueWidth=visibleWidth(truncatedValue2),spacing=" ".repeat(Math.max(1,effectivePrimaryColumnWidth-truncatedValueWidth)),descriptionStart=prefixWidth+truncatedValueWidth+spacing.length,remainingWidth=width-descriptionStart-2;if(remainingWidth>MIN_DESCRIPTION_WIDTH){let truncatedDesc=truncateToWidth(descriptionSingleLine,remainingWidth,"");if(isSelected)return this.theme.selectedText(`${prefix}${truncatedValue2}${spacing}${truncatedDesc}`);
318
+ let descText=this.theme.description(spacing+truncatedDesc);return prefix+truncatedValue2+descText}}let maxWidth=width-prefixWidth-2,truncatedValue=this.truncatePrimary(item,isSelected,maxWidth,maxWidth);return isSelected?this.theme.selectedText(`${prefix}${truncatedValue}`):prefix+truncatedValue}getPrimaryColumnWidth(){let{min,max}=this.getPrimaryColumnBounds(),widestPrimary=this.filteredItems.reduce((widest,item)=>Math.max(widest,visibleWidth(this.getDisplayValue(item))+PRIMARY_COLUMN_GAP),0);return clamp(
319
+ widestPrimary,min,max)}getPrimaryColumnBounds(){let rawMin=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH,rawMax=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??DEFAULT_PRIMARY_COLUMN_WIDTH;return{min:Math.max(1,Math.min(rawMin,rawMax)),max:Math.max(1,Math.max(rawMin,rawMax))}}truncatePrimary(item,isSelected,maxWidth,columnWidth){let displayValue=this.getDisplayValue(item),truncatedValue=this.layout.truncatePrimary?this.layout.
320
+ truncatePrimary({text:displayValue,maxWidth,columnWidth,item,isSelected}):truncateToWidth(displayValue,maxWidth,"");return truncateToWidth(truncatedValue,maxWidth,"")}getDisplayValue(item){return item.label||item.value}notifySelectionChange(){let selectedItem=this.filteredItems[this.selectedIndex];selectedItem&&this.onSelectionChange&&this.onSelectionChange(selectedItem)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};function j(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var y=j();function ie(l3){y=l3}var D={exec:()=>null};function B(l3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l3(n),e[n]=s),s}}function h(l3,e=""){let t=typeof l3=="string"?l3:l3.source,n={replace:(s,i)=>{let r=typeof i=="string"?i:i.source;return r=r.replace(T.caret,"$1"),t=t.replace(s,r),n},getRegex:()=>new RegExp(t,e)};return n}
321
+ var we=((l3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+l3)}catch{return!1}})(),T={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,listInterruptsParagraph:/^ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,endingSpaceTabChar:/[ \t]$/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,leadingSpaceTab:/^[ \t]+/,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,
322
+ doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\n {0,3}((?:=+|-+)[ \t]*)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,blockquoteMarkerWhitespace:/^( {0,3}>)([ \t]+)/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\][ \t]+\S/,listReplaceTask:/^\[[ xX]\][ \t]+/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,
323
+ tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\s|>)/i,endPreScriptTag:/^<\/(pre|code|kbd|script)(\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'"]*[^\s])\s+(['"])(.*)\2/,unicodeAlphaNumeric:/[\p{L}\p{N}]/u,numericCharacterReference:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));/,numericCharacterReferenceOrAmpersand:/&#(?:(\d{1,7})|[Xx]([A-Fa-f0-9]{1,6}));|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,
324
+ escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:l3=>new RegExp(`^( {0,3}${l3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:B(l3=>new RegExp(`^ {0,${l3}}(?:[*+-]|\\d{\
325
+ 1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:B(l3=>new RegExp(`^ {0,${l3}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:B(l3=>new RegExp(`^ {0,${l3}}(?:\`\`\`|~~~)`)),headingBeginRegex:B(l3=>new RegExp(`^ {0,${l3}}#{1,6}(?:\\s|$)`)),pedanticHeadingBeginRegex:B(l3=>new RegExp(`^ {0,${l3}}#`)),htmlBeginRegex:B(l3=>new RegExp(`^ {0,${l3}}(?:</?(?:${K})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,"i")),blockquoteBeginRegex:B(
326
+ l3=>new RegExp(`^ {0,${l3}}>`)),nestedContainerMarkers:/^(?: {0,3}(?:(?:[*+-]|\d{1,9}[.)])[ \t]+|>[ \t]?))+/},He=/^(?:[ \t]*(?:\n|$))+/,je=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,Ge=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}(?:(?=`)\1`*|(?=~)\1~*) *(?=\n|$)|$)/,W=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,Ne=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ae=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Pe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+)[ \t]*(?:\n+|$)/,
327
+ ye=h(Pe).replace(/bull/g,ae).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,"").getRegex(),Fe=h(Pe).replace(/bull/g,ae).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(
328
+ /heading/g,/ {0,3}#{1,6}(?:\s|$)/).replace(/hr/g,/ {0,3}(?:(?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/).replace(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),le=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Qe=/^[^\n]+/,ue=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\\n]|\n(?![ \t]*\n))+/,Ue=h(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).
329
+ replace("label",ue).replace("title",/(?:"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\\n]|\n(?!\n))*'|\((?:\\[\s\S]|[^()\\])*\))/).getRegex(),We=h(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ae).getRegex(),K="address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|sect\
330
+ ion|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul",pe=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ke=h("^ {0,3}(?:<(script|pre|style|textarea)[\\s>][\\s\\S]*?(?:</\\1>[^\\n]*\\n*|$)|comment[^\\n]*(\\n+|$)|<\\?[\\s\\S]*?(?:\\?>[^\\n]*\\n*|$)|<![A-Z][\\s\\S]*?(?:>[^\\n]*\\n*|$)|<!\\[CDATA\\[[\\s\\S]*?(?:\\]\\]>[^\\n]*\\n*|$)|</?(tag)(?:[ \\t]+|\\n|/?>|$)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!(?:script|pre|style|textarea)(?![a-z0-9-]))([a-z][a-z0-9-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</[a-z][a-z0-9-]\
331
+ *\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",pe).replace("tag",K).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Se=l3=>h(le).replace("hr",W).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("|table","").replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list",l3).replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n\
332
+ |/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",K).getRegex(),Xe=Se(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ve=Se(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Je=h(/^( {0,3}> ?(?:(?![ \t]*(?:\n|$))(paragraph)|[^\n]*)(?:\n|$))+/).replace("paragraph",Ve).getRegex(),ce={blockquote:Je,code:je,def:Ue,fences:Ge,heading:Ne,hr:W,html:Ke,lheading:ye,list:We,newline:He,paragraph:Xe,table:D,text:Qe},Re=h("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:\
333
+ ?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)").replace("hr",W).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("blockquote"," {0,3}>").replace("code","(?: {4}| {0,3} )[^\\n]").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]").replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace(
334
+ "tag",K).getRegex(),Ye={...ce,lheading:Fe,table:Re,paragraph:h(le).replace("hr",W).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",Re).replace("blockquote"," {0,3}>").replace("fences"," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace("list"," {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]").replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",K).getRegex()},et={
335
+ ...ce,html:h(`^ *(?:comment(?: *\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1>(?: *\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?>(?: *\\n{2,}|\\s*$))`).replace("comment",pe).replace(/tag/g,"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\b)\\w+(?!:|[^\\w\\s@]*@)\\b").getRegex(),def:/^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +(["(][^\n]+[")]))? *(?:\n+|$)/,heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:D,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
336
+ paragraph:h(le).replace("hr",W).replace("heading",` *#{1,6} *[^
337
+ ]`).replace("lheading",ye).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},tt=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,nt=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,_e=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,rt=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,$=/[\p{P}\p{S}]/u,G=/[\s\p{P}\p{S}]/u,X=/[^\s\p{P}\p{S}]/u,st=h(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,G).getRegex(),
338
+ it=/[\p{Pi}\p{Ps}"']/u,$e=/(?!~)[\p{P}\p{S}]/u,ot=/(?!~)[\s\p{P}\p{S}]/u,at=/(?:[^\s\p{P}\p{S}]|~)/u,lt=h(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",we?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),Le=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,ut=h(Le,"u").replace(/punct/g,$).getRegex(),pt=h(
339
+ Le,"u").replace(/punct/g,$e).getRegex(),ct=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,ht=h(ct,"u").replace(/openQuote/g,it).replace(/punct/g,$).getRegex(),Ce="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",dt=h(Ce,"gu").replace(/notPunctSpace/g,
340
+ X).replace(/punctSpace/g,G).replace(/punct/g,$).getRegex(),gt=h(Ce,"gu").replace(/notPunctSpace/g,at).replace(/punctSpace/g,ot).replace(/punct/g,$e).getRegex(),kt="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",ft=h(kt,"gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,
341
+ G).replace(/punct/g,$).getRegex(),mt=h("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,G).replace(/punct/g,$).getRegex(),xt="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!\
342
+ _)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",bt=h(xt,"gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,G).replace(/punct/g,$).getRegex(),Rt=h(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,$).getRegex(),Tt="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Ot=h(Tt,"gu").replace(
343
+ /notPunctSpace/g,X).replace(/punctSpace/g,G).replace(/punct/g,$).getRegex(),wt=h(/\\(punct)/,"gu").replace(/punct/g,$).getRegex(),Pt=h(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,$).getRegex(),yt=h(/^<(scheme:[^\s\x00-\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),St=h(pe).replace(
344
+ "(?:-->|$)","-->").getRegex(),_t=h("^comment|^</[a-zA-Z][a-zA-Z0-9-]*\\s*>|^<[a-zA-Z][a-zA-Z0-9-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>").replace("comment",St).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Ie=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,re=h(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",Ie).getRegex(),
345
+ $t=h(/^!?\[(label)\]\([ \t\n]*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?[ \t\n]*\)/).replace("label",re).replace("href",/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace("title",/"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\])*'|\((?:\\[\s\S]|[^)\\])*\)/).getRegex(),Lt=h(/^!?\[(label)\]\[(ref)\]/).replace("label",re).replace("ref",ue).getRegex(),Ct=h(/^!?\[(ref)\](?:\[\])?/).replace("ref",ue).getRegex(),Te=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,It=h(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).
346
+ replace("brackets",Ie).getRegex(),At=h("reflink|nolink(?!\\()","g").replace("reflink",h(/^!?\[(label)\]\[(ref)\]/).replace("label",It).replace("ref",Te).getRegex()).replace("nolink",h(/^!?\[(ref)\](?:\[\])?/).replace("ref",Te).getRegex()).getRegex(),Oe=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,Et=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,zt=h(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,Et).getRegex(),he={_backpedal:D,anyPunctuation:wt,anyPunctuationOutsideCode:Pt,
347
+ autolink:yt,blockSkip:lt,br:_e,code:nt,del:D,delLDelim:D,delRDelim:D,emStrongLDelim:ut,emStrongRDelimAst:dt,emStrongRDelimUnd:mt,escape:tt,link:$t,nolink:Ct,punctuation:st,reflink:Lt,reflinkSearch:At,tag:_t,text:rt,url:D},Mt={...he,emStrongLDelim:ht,emStrongRDelimAst:ft,emStrongRDelimUnd:bt,link:h(/^!?\[(label)\]\((.*?)\)/).replace("label",re).getRegex(),reflink:h(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",re).getRegex()},oe={...he,emStrongRDelimAst:gt,emStrongLDelim:pt,delLDelim:Rt,delRDelim:Ot,
348
+ url:h(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",zt).replace("protocol",Oe).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:h(/^(?:[^a-zA-Z0-9](?=emailProtocol)|(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|wwwStart|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9](?=emailProtocol)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@))))/).
349
+ replace("protocol",Oe).replace(/emailProtocol/g,/(?:mailto|xmpp):/).replace("wwwStart",we?"(?<![^\\s*_~(])www\\.":"www\\.").getRegex()},Bt={...oe,br:h(_e).replace("{2,}","*").getRegex(),text:h(oe.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},V={normal:ce,gfm:Ye,pedantic:et},N={normal:he,gfm:oe,breaks:Bt,pedantic:Mt},Dt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ae=l3=>Dt[l3];function P(l3,e){if(e){if(T.escapeTest.test(l3))return l3.replace(T.escapeReplace,
350
+ Ae)}else if(T.escapeTestNoEncode.test(l3))return l3.replace(T.escapeReplaceNoEncode,Ae);return l3}function Ee(l3){return T.numericCharacterReference.test(l3)?l3.replace(T.numericCharacterReferenceOrAmpersand,(e,t,n)=>{if(t===void 0&&n===void 0)return"&amp;";let s=t===void 0?Number.parseInt(n,16):Number.parseInt(t,10);return s===0||s>1114111||s>=55296&&s<=57343?"\uFFFD":s===38?"&amp;":String.fromCodePoint(s)}):l3}function de(l3){try{l3=encodeURI(l3).replace(T.percentDecode,"%")}catch{return null}
351
+ return l3}function ge(l3,e){let t=l3.replace(T.findPipe,(i,r,o)=>{let a=!1,p=r;for(;--p>=0&&o[p]==="\\";)a=!a;return a?"|":" |"}),n=t.split(T.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push("");for(;s<n.length;s++)n[s]=n[s].trim().replace(T.slashPipe,"|");return n}function L(l3,e,t){let n=l3.length;if(n===0)return"";let s=0;for(;s<n;){let i=l3.charAt(n-s-1);if(i===e&&!t)s++;else if(i!==e&&t)s++;else break}return l3.
352
+ slice(0,n-s)}function ke(l3){let e=l3.split(`
353
+ `),t=e.length-1;for(;t>=0&&T.blankLine.test(e[t]);)t--;return e.length-t<=2?l3:e.slice(0,t+1).join(`
354
+ `)}function Q(l3){return l3.trim().replace(T.multipleSpaceGlobal," ").toLowerCase().toUpperCase().toLowerCase()}function fe(l3,e){if(l3.indexOf(e[0])===-1&&l3.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l3.length;n++)if(l3[n]==="\\")n++;else if(l3[n]===e[0])t++;else if(l3[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}var F=new WeakMap;function me(l3){let e={"*":-1,_:-1},t=-1,n=l3.length;for(let s=0;s<n;s++){let i=l3[s];if(i!=="*"&&i!=="_"&&i!=="~")continue;let r=s===0?`
355
+ `:l3[s-1],o=s+1;for(;o<n&&l3[o]===i;)o++;r!==" "&&r!==" "&&r!==`
356
+ `&&r!=="\r"&&r!=="\f"&&(i==="~"?t=s:e[i]=s),s=o-1}return{maskedSrc:l3,lastPossibleEmStrongCloserIndex:e,lastPossibleDelCloserIndex:t}}function ze(l3,e){let t=me(e),n=F.get(l3);n?n.push(t):F.set(l3,[t])}function Me(l3){let e=F.get(l3);e&&(e.pop(),e.length===0&&F.delete(l3))}function Be(l3,e,t){let n=F.get(l3)?.at(-1);return n&&n.maskedSrc===e?n.lastPossibleEmStrongCloserIndex[t]:me(e).lastPossibleEmStrongCloserIndex[t]}function De(l3,e){let t=F.get(l3)?.at(-1);return t&&t.maskedSrc===e?t.lastPossibleDelCloserIndex:
357
+ me(e).lastPossibleDelCloserIndex}function J(l3,e=0){let t=e,n="";for(let s of l3)if(s===" "){let i=4-t%4;n+=" ".repeat(i),t+=i}else n+=s,t++;return n}function qe(l3,e,t,n,s){let i=e.href,r=e.title||null,o=l3[1].replace(s.other.outputLinkReplace,"$1"),a=l3[0].charAt(0)==="!",p=n.state.inLink,c=n.state.linkEmitted,u=n.state.inRawBlock;n.state.inLink=!0,n.state.linkEmitted=!1;let d=n.inlineTokens(o),k=n.state.linkEmitted;if(n.state.linkEmitted=c,n.state.inLink=p,!a){if(k){n.state.inRawBlock=u;return}
358
+ n.state.linkEmitted=!0}return{type:a?"image":"link",raw:t,href:i,title:r,text:o,tokens:d}}function qt(l3,e,t){let n=l3.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(`
359
+ `).map(i=>{let r=i.match(t.other.beginningSpace);if(r===null)return i;let[o]=r;return i.slice(Math.min(o.length,s.length))}).join(`
360
+ `)}function ve(l3,e,t,n){if(!e.includes("<"))return!1;for(let s=0;s<e.length;s++){if(e[s]==="\\"){s++;continue}if(e[s]==="`"){let o=n.inline.code.exec(e.slice(s));if(o){s+=o[0].length-1;continue}}if(e[s]!=="<")continue;let i=l3.slice(t+s),r=n.inline.tag.exec(i)||n.inline.autolink.exec(i);if(r){if(r[0].length>e.length-s)return!0;s+=r[0].length-1}}return!1}var _=class{options;rules;lexer;constructor(e){this.options=e||y}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"\
361
+ space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:ke(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:n,codeBlockStyle:"indented",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=qt(n,t[3]||"",this.rules);return{type:"code",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.
362
+ rules.other.endingHash.test(n)){let s=L(n,"#");(this.options.pedantic||!s||this.rules.other.endingSpaceTabChar.test(s))&&(n=s.trim())}return{type:"heading",raw:L(t[0],`
363
+ `),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:L(t[0],`
364
+ `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=L(t[0],`
365
+ `).split(`
366
+ `),s="",i="",r=[];for(;n.length>0;){let o=!1,a=[],p;for(p=0;p<n.length;p++)if(this.rules.other.blockquoteStart.test(n[p]))a.push(n[p]),o=!0;else if(!o)a.push(n[p]);else break;n=n.slice(p);let c=a.join(`
367
+ `),u=c.replace(this.rules.other.blockquoteMarkerWhitespace,(g,b,f)=>b+J(f,b.length)).replace(this.rules.other.blockquoteSetextReplace,`
368
+ $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
369
+ ${c}`:c,i=i?`${i}
370
+ ${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,r,!0),this.lexer.state.top=d,n.length===0)break;let k=r.at(-1);if(k?.type==="code"||k?.type==="heading"||k?.type==="hr"||k?.type==="html"||k?.type==="table")break;if(k?.type==="blockquote"){let g=k,b=n.join(`
371
+ `),f=g.raw+`
372
+ `+b.replace(this.rules.other.blockquoteSetextReplace2,""),m=this.blockquote(f);r[r.length-1]=m;let S=f.substring(m.raw.length).replace(/^\n/,""),R=S?S.split(`
373
+ `).length:0,A=R?n.slice(0,-R):n;if(A.length>0&&(s=`${s}
374
+ ${A.join(`
375
+ `)}`),i=i.substring(0,i.length-g.text.length)+m.text,n=n.slice(A.length),n.length>0&&this.rules.other.blockquoteStart.test(n[0]))continue;break}else if(k?.type==="list"){let g=k,b=g.raw+`
376
+ `+n.join(`
377
+ `),f=this.list(b);r[r.length-1]=f;let m=f.raw.length>g.raw.length?b.slice(g.raw.length+1,f.raw.length).split(`
378
+ `).length:0;if(m>0){let S=n.slice(0,m).join(`
379
+ `);s=`${s}
380
+ ${S}`,i=`${i}
381
+ ${S}`}n=n.slice(m);continue}}return{type:"blockquote",raw:s,tokens:r,text:i}}}list(e){let t=this.rules.block.list.exec(e);if(t){if(!this.options.pedantic&&this.lexer.state.lastToken?.type==="text"&&!this.rules.other.listInterruptsParagraph.test(e))return;let n=e,s=()=>n.length-e.length,i=t[1].trim(),r=i.length>1,o={type:"list",raw:"",ordered:r,start:r?+i.slice(0,-1):"",loose:!1,items:[]};i=r?`\\d{1,9}\\${i.slice(-1)}`:`\\${i}`,this.options.pedantic&&(i=r?i:"[*+-]");let a=this.rules.other.listItemRegex(
382
+ i),p=!1;for(;e;){let u=!1,d="";if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;let k=s();e=e.substring(t[0].length);let g=t[2].split(`
383
+ `,1)[0],b=t[1].length,f=this.options.pedantic?J(g,b):g.replace(this.rules.other.leadingSpaceTab,v=>J(v,b)),m=e.split(`
384
+ `,1)[0],S=!f.trim(),R=0;if(this.options.pedantic?(R=2,d=f.trimStart()):S?R=b+1:(R=f.search(this.rules.other.nonSpaceChar),R=R>4?1:R,d=f.slice(R),R+=b),S&&this.rules.other.blankLine.test(m)&&(e=e.substring(m.length+1),u=!0),!u){let v=this.rules.other.nextBulletRegex(R),U=this.rules.other.hrRegex(R),ee=this.rules.other.fencesBeginRegex(R),te=this.options.pedantic?this.rules.other.pedanticHeadingBeginRegex(R):this.rules.other.headingBeginRegex(R),M=this.rules.other.htmlBeginRegex(R),ne=this.rules.other.
385
+ blockquoteBeginRegex(R),Z=!1;for(;e;){let xe=e.split(`
386
+ `,1)[0],H;if(m=xe,this.options.pedantic?(m=m.replace(this.rules.other.listReplaceNesting," "),H=m):H=m.replace(this.rules.other.leadingSpaceTab,be=>J(be)),ee.test(m)||te.test(m)||M.test(m)||ne.test(m)||v.test(m)||U.test(m))break;if(H.search(this.rules.other.nonSpaceChar)>=R||!m.trim())d+=`
387
+ `+H.slice(R),Z=!1;else{if(S||f.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ee.test(f)||te.test(f)||M.test(f)||U.test(f))break;if(!this.options.pedantic&&!Z){let se=f.replace(this.rules.other.nestedContainerMarkers,"");if(this.rules.block.fences.test(se)||this.rules.block.heading.test(se)||this.rules.block.hr.test(se))break}let Ze=!this.options.pedantic&&/^ {0,3}(?:=+|-+) *$/.test(m)&&this.rules.block.lheading.test(`${f}
388
+ ${m}`)?` ${H.replace(/^ {0,3}/,"")}`:m;d+=`
389
+ `+Ze,Z=!0}S=!m.trim(),e=e.substring(xe.length+1),f=H.slice(R)}}let A=n.slice(k,s());o.loose||(p?o.loose=!0:this.rules.other.doubleBlankLine.test(A)&&(p=!0)),o.items.push({type:"list_item",raw:A,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]})}let c=o.items.at(-1);if(c)c.raw=c.raw.trimEnd(),c.text=c.text.trimEnd();else return;o.raw=n.slice(0,s()).trimEnd();for(let u of o.items)if(this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]),!o.loose){let d=u.
390
+ tokens.filter(g=>g.type==="space"),k=d.length>0&&d.some(g=>this.rules.other.anyLine.test(g.raw));o.loose=k}for(let u of o.items){let d=u.tokens[0];if(u.task&&(d?.type==="text"||d?.type==="paragraph")){u.text=u.text.replace(this.rules.other.listReplaceTask,""),d.raw=d.raw.replace(this.rules.other.listReplaceTask,""),d.text=d.text.replace(this.rules.other.listReplaceTask,"");for(let g=this.lexer.inlineQueue.length-1;g>=0;g--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[g].src)){this.
391
+ lexer.inlineQueue[g].src=this.lexer.inlineQueue[g].src.replace(this.rules.other.listReplaceTask,"");break}let k=this.rules.other.listTaskCheckbox.exec(u.raw);if(k){let g={type:"checkbox",raw:k[0]+" ",checked:k[0]!=="[ ]"};u.checked=g.checked,o.loose?u.tokens[0]&&["paragraph","text"].includes(u.tokens[0].type)&&"tokens"in u.tokens[0]&&u.tokens[0].tokens?(u.tokens[0].raw=g.raw+u.tokens[0].raw,u.tokens[0].text=g.raw+u.tokens[0].text,u.tokens[0].tokens.unshift(g)):u.tokens.unshift({type:"paragraph",
392
+ raw:g.raw,text:g.raw,tokens:[g]}):u.tokens.unshift(g)}}else u.task&&(u.task=!1)}if(o.loose)for(let u of o.items){u.loose=!0;for(let d of u.tokens)d.type==="text"&&(d.type="paragraph")}return o}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=ke(t[0]);return{type:"html",block:!0,raw:n,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){if(!this.rules.other.startAngleBracket.test(t[2])&&fe(t[2],"()")!==-1)return;let n=Q(t[1]),s=t[2]?t[2].
393
+ replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",i=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:n,raw:L(t[0],`
394
+ `),href:s,title:i}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=ge(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
395
+ `):[],r={type:"table",raw:L(t[0],`
396
+ `),header:[],align:[],rows:[]};if(n.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?r.align.push("right"):this.rules.other.tableAlignCenter.test(o)?r.align.push("center"):this.rules.other.tableAlignLeft.test(o)?r.align.push("left"):r.align.push(null);for(let o=0;o<n.length;o++)r.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:r.align[o]});for(let o of i)r.rows.push(ge(o,r.header.length).map((a,p)=>({text:a,tokens:this.lexer.inline(a),header:!1,align:r.
397
+ align[p]})));return r}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:L(t[0],`
398
+ `),depth:t[2].charAt(0)==="="?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`
399
+ `?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.
400
+ test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){if(this.lexer.state.linkParenPossible===!1)return;let t=this.rules.inline.link.exec(e);if(t){let n=t[0].charAt(0)==="!"?2:1;if(!this.
401
+ options.pedantic&&ve(e,t[1],n,this.rules))return;let s=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let a=L(s.slice(0,-1),"\\");if((s.length-a.length)%2===0)return}else{let a=fe(t[2],"()");if(a===-2)return;if(a>-1){let c=(t[0].indexOf("!")===0?5:4)+t[1].length+a;t[2]=t[2].substring(0,a),t[0]=t[0].substring(0,c).trim(),t[3]=""}}let i=L(t[0].slice(0,-1),"\\");if((t[0].length-i.length)%2===0)return;let r=t[2],
402
+ o="";if(this.options.pedantic){let a=this.rules.other.pedanticHrefTitle.exec(r);a&&(r=a[1],o=a[3])}else o=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?r=r.slice(1):r=r.slice(1,-1)),qe(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:o&&o.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||
403
+ (n=this.rules.inline.nolink.exec(e))){let s=n[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&ve(e,n[1],s,this.rules))return;let i=t[Q(n[2]||n[1])];if(!i){let r=n[0].charAt(0);return{type:"text",raw:r,text:r}}return qe(n,i,n[0],this.lexer,this.rules)}}emStrong(e,t,n=""){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||!s[1]&&!s[2]&&!s[3]&&!s[4])return;let i=s[0][0],r=n===i,o=t.length-e.length,a=o;for(;!this.options.pedantic&&a>0&&t[a-1]===i;)a--;let p=[...t.slice(Math.max(0,a-2),a)].at(-1)??
404
+ "",c=p==="*"||p==="_"||!!this.rules.inline.punctuation.exec(p);a<o&&(n=p);let u=a<o?c:n==="*"||n==="_"||!!this.rules.inline.punctuation.exec(n);if(s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;let d=s[1]||s[3]||"";if(!d||!n||u){let k=[...s[0]].length-1,g,b,f=k,m=0,S=o-a+k,R=!this.options.pedantic&&!!p.trim()&&(!!d||i==="*"&&!c);if(i!=="*"&&i!=="_")return;let A=i==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd,v=Be(this,t,i),U=t.length-e.length+k;if(v<U)
405
+ return;t=t.slice(-1*e.length+k);let ee=v-U;for(A.lastIndex=0;(s=A.exec(t))!==null&&!(s.index>ee);){if(g=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!g)continue;if(b=[...g].length,s[3]||s[4]){f+=b;continue}else if(s[5]||s[6]||R){if(r&&(s[5]||s[6]))break;if(S%3&&!((S+b)%3)){m+=b;continue}}if(f-=b,f>0)continue;b=Math.min(b,b+f+m);let te=[...s[0]][0].length,M=e.slice(0,k+s.index+te+b);if(Math.min(k,b)%2){let Z=M.slice(1,-1);return{type:"em",raw:M,text:Z,tokens:this.lexer.inlineTokens(Z)}}let ne=M.slice(2,-2);
406
+ return{type:"strong",raw:M,text:ne,tokens:this.lexer.inlineTokens(ne)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal," "),s=this.rules.other.nonSpaceChar.test(n),i=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&i&&(n=n.substring(1,n.length-1)),{type:"codespan",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,n=""){let s=this.rules.inline.
407
+ delLDelim.exec(e);if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let r=[...s[0]].length-1,o,a,p=r,c=this.rules.inline.delRDelim,u=De(this,t),d=t.length-e.length+r;if(u<d)return;t=t.slice(-1*e.length+r);let k=u-d;for(c.lastIndex=0;(s=c.exec(t))!==null&&!(s.index>k);){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(a=[...o].length,a!==r))continue;if(s[3]||s[4]){p+=a;continue}if(p-=a,p>0)continue;a=Math.min(a,a+p);let g=[...s[0]][0].length,b=e.slice(0,r+s.index+g+a),f=b.slice(r,-r);return{type:"\
408
+ del",raw:b,text:f,tokens:this.lexer.inlineTokens(f)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]==="@"?(n=t[1],s="mailto:"+n):(n=t[1],s=n),{type:"link",raw:t[0],text:n,href:s,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]==="@")n=t[0],s="mailto:"+n;else{let i;do i=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(i!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"\
409
+ link",raw:t[0],text:n,href:s,autolink:!0,tokens:[{type:"text",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:n?t[0]:Ee(t[0]),escaped:n}}}},O=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||y,this.options.tokenizer=this.options.tokenizer||new _,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.
410
+ tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0};let t={other:T,block:V.normal,inline:N.normal};this.options.pedantic?(t.block=V.pedantic,t.inline=N.pedantic):this.options.gfm&&(t.block=V.gfm,this.options.breaks?t.inline=N.breaks:t.inline=N.gfm),this.tokenizer.rules=t}static get rules(){return{block:V,inline:N}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(T.carriageReturn,
411
+ `
412
+ `),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.state.inRawBlock=!1,this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this;let s=this.state.lastToken;this.options.pedantic&&(e=e.replace(T.tabCharGlobal," ").replace(T.spaceLine,""));let i=1/0;for(;e;){if(e.length<i)i=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}this.state.lastToken=t.at(-1);let r;if(this.
413
+ options.extensions?.block?.some(a=>(r=a.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let a=t.at(-1);r.raw.length===1&&a!==void 0?a.raw+=`
414
+ `:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let a=t.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
415
+ `)?"":`
416
+ `)+r.raw,a.text+=`
417
+ `+r.text,this.inlineQueue.at(-1).src=a.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.
418
+ length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let a=t.at(-1);a?.type==="paragraph"||a?.type==="text"?(a.raw+=(a.raw.endsWith(`
419
+ `)?"":`
420
+ `)+r.raw,a.text+=`
421
+ `+r.raw,this.inlineQueue.at(-1).src=a.text):(this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title}),t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let o=e;if(this.options.extensions?.startBlock){let a=1/0,p=e.slice(1),c;this.options.extensions.startBlock.forEach(u=>{c=u.call({lexer:this},p),typeof c=="number"&&c>=0&&(a=Math.min(a,c))}),a<1/0&&
422
+ a>=0&&(o=e.substring(0,a+1))}if(this.state.top&&(r=this.tokenizer.paragraph(o))){let a=t.at(-1);n&&a?.type==="paragraph"?(a.raw+=(a.raw.endsWith(`
423
+ `)?"":`
424
+ `)+r.raw,a.text+=`
425
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(r),n=o.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let a=t.at(-1);a?.type==="text"?(a.raw+=(a.raw.endsWith(`
426
+ `)?"":`
427
+ `)+r.raw,a.text+=`
428
+ `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=a.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,this.state.lastToken=s,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}linkInText(e){if(!e.includes("["))return!1;let t=this.tokenizer.rules.inline.link;for(let n of e.matchAll(this.tokenizer.rules.inline.blockSkip))if(t.test(n[0])&&e.charAt(n.index-1)!=="!")return!0;for(let n of e.matchAll(this.tokenizer.rules.inline.
429
+ reflinkSearch)){let s=n[0],i=s.lastIndexOf("[");if(!(s.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,Q(s.slice(i+1,-1))))&&!(i>1&&this.linkInText(s.slice(1,i-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=this.state.linkParenPossible;this.state.linkParenPossible=n&&e.includes(")");try{return this.#e(e,t)}finally{this.state.linkParenPossible=n}}#e(e,t){let n=e.includes("*")||e.includes("_")||e.includes("~")||this.options.hooks?.emStrongMask||this.tokenizer.emStrong!==
430
+ _.prototype.emStrong||this.tokenizer.del!==_.prototype.del?this.#r(e):e;ze(this.tokenizer,n);try{return this.#t(e,n,t)}finally{Me(this.tokenizer)}}#t(e,t,n){let s=!1,i="",r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}s||(i=""),s=!1;let o;if(this.options.extensions?.inline?.some(p=>(o=p.call({lexer:this},e,n))?(e=e.substring(o.raw.length),n.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.
431
+ tokenizer.tag(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let p=n.at(-1);o.type==="text"&&p?.type==="text"?(p.raw+=o.raw,p.text+=o.text):n.push(o);continue}if(o=this.tokenizer.emStrong(e,t,i)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.
432
+ br(e)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.del(e,t,i)){e=e.substring(o.raw.length),n.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),n.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),n.push(o);continue}let a=e;if(this.options.extensions?.startInline){let p=1/0,c=e.slice(1),u;this.options.extensions.startInline.forEach(d=>{u=d.call({lexer:this},c),typeof u=="number"&&u>=0&&(p=Math.min(p,u))}),
433
+ p<1/0&&p>=0&&(a=e.substring(0,p+1))}if(o=this.tokenizer.inlineText(a)){e=e.substring(o.raw.length),o.raw.slice(-1)!=="_"&&(i=o.raw.slice(-1)),s=!0;let p=n.at(-1);p?.type==="text"?(p.raw+=o.raw,p.text+=o.text):n.push(o);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}#n(e){let{blockSkip:t,tag:n,autolink:s}=this.tokenizer.rules.inline,i="",r=0,o;for(t.lastIndex=0;o=t.exec(e);){let a=o.index+(o[2]?o[2].length:0),p=o.index+o[0].length;if(e.charAt(a)==="<"){let c=e.slice(a),u=n.
434
+ exec(c)||s.exec(c);if(!u){t.lastIndex=a+1;continue}p=a+u[0].length,t.lastIndex=p}i+=e.slice(r,a)+"["+"a".repeat(p-a-2)+"]",r=p}return i+e.slice(r)}#r(e){let t=e;if(this.tokens.links&&e.includes("[")){let n=this.tokenizer.rules.inline.reflinkSearch,s=i=>{let r=i.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,Q(i.slice(r+1,-1))))return i;if(r>1&&i.charAt(0)!=="!"){let o=i.slice(1,r-1);if(this.linkInText(o))return"["+o.replace(n,s)+"]["+"a".repeat(i.length-r-2)+"]"}return"["+"a".repeat(i.length-
435
+ 2)+"]"};t=t.replace(n,s)}return t=t.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(n,s,i)=>i?"+".repeat(n.length):s?s+n.slice(s.length,-s.length).replace(/`/g,"+")+s:n),t=this.#n(t),t=this.options.hooks?.emStrongMask?.call({lexer:this},t)??t,t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}},C=class{options;parser;constructor(e){this.options=e||y}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").
436
+ match(T.notSpaceStart)?.[0],i=e?e.replace(T.endingNewline,"")+`
437
+ `:"";return s?'<pre><code class="language-'+P(s)+'">'+(n?i:P(i,!0))+`</code></pre>
438
+ `:"<pre><code>"+(n?i:P(i,!0))+`</code></pre>
439
+ `}blockquote({tokens:e}){return`<blockquote>
440
+ ${this.parser.parse(e)}</blockquote>
441
+ `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
442
+ `}hr(e){return`<hr>
443
+ `}list(e){let t=e.ordered,n=e.start,s="";for(let o=0;o<e.items.length;o++){let a=e.items[o];s+=this.listitem(a)}let i=t?"ol":"ul",r=t&&n!==1?' start="'+n+'"':"";return"<"+i+r+`>
444
+ `+s+"</"+i+`>
445
+ `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
446
+ `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
447
+ `}table(e){let t="",n="";for(let i=0;i<e.header.length;i++)n+=this.tablecell(e.header[i]);t+=this.tablerow({text:n});let s="";for(let i=0;i<e.rows.length;i++){let r=e.rows[i];n="";for(let o=0;o<r.length;o++)n+=this.tablecell(r[o]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
448
+ <thead>
449
+ `+t+`</thead>
450
+ `+s+`</table>
451
+ `}tablerow({text:e}){return`<tr>
452
+ ${e}</tr>
453
+ `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
454
+ `}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${P(e,!0)}</code>`}br(e){return"<br>"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,text:n,tokens:s,autolink:i}){let r=i?P(n,!0):this.parser.parseInline(s),o=de(e);if(o===null)return r;e=P(o,i);let a='<a href="'+e+'"';return t&&(a+=' title="'+P(t)+'"'),a+=">"+r+"</a>",a}image({href:e,title:t,
455
+ text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let i=de(e);if(i===null)return P(n);e=i;let r=`<img src="${P(e)}" alt="${P(n)}"`;return t&&(r+=` title="${P(t)}"`),r+=">",r}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:P(e.text)}},E=class{parser;strong({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}em({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}codespan({text:e}){return e}del({text:e,
456
+ tokens:t}){return t?this.parser.parseInline(t,this):e}html({text:e}){return e}text({text:e}){return e}link({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}image({text:e,tokens:t}){return t?this.parser.parseInline(t,this):e}br(){return`
457
+ `}checkbox({raw:e}){return e}},w=class l2{options;renderer;textRenderer;constructor(e){this.options=e||y,this.options.renderer=this.options.renderer||new C,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new E,this.textRenderer.parser=this}static parse(e,t){return new l2(t).parse(e)}static parseInline(e,t){return new l2(t).parseInline(e)}parse(e){this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let s=e[n];if(this.options.
458
+ extensions?.renderers?.[s.type]){let r=s,o=this.options.extensions.renderers[r.type].call({parser:this},r);if(o!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(r.type)){t+=o===!1?"":o??"";continue}}let i=s;switch(i.type){case"space":{t+=this.renderer.space(i);break}case"hr":{t+=this.renderer.hr(i);break}case"heading":{t+=this.renderer.heading(i);break}case"code":{t+=this.renderer.code(i);break}case"table":{t+=this.renderer.table(
459
+ i);break}case"blockquote":{t+=this.renderer.blockquote(i);break}case"list":{t+=this.renderer.list(i);break}case"checkbox":{t+=this.renderer.checkbox(i);break}case"html":{t+=this.renderer.html(i);break}case"def":{t+=this.renderer.def(i);break}case"paragraph":{t+=this.renderer.paragraph(i);break}case"text":{t+=this.renderer.text(i);break}default:{let r='Token with "'+i.type+'" type was not found.';if(this.options.silent)return console.error(r),"";throw new Error(r)}}}return t}parseInline(e,t=this.
460
+ renderer){this.renderer.parser=this;let n="";for(let s=0;s<e.length;s++){let i=e[s];if(this.options.extensions?.renderers?.[i.type]){let o=this.options.extensions.renderers[i.type].call({parser:this},i);if(o!==!1||!["escape","html","link","image","checkbox","strong","em","codespan","br","del","text"].includes(i.type)){n+=o===!1?"":o??"";continue}}let r=i;switch(r.type){case"escape":{n+=t.text(r);break}case"html":{n+=t.html(r);break}case"link":{n+=t.link(r);break}case"image":{n+=t.image(r);break}case"\
461
+ checkbox":{n+=t.checkbox(r);break}case"strong":{n+=t.strong(r);break}case"em":{n+=t.em(r);break}case"codespan":{n+=t.codespan(r);break}case"br":{n+=t.br(r);break}case"del":{n+=t.del(r);break}case"text":{n+=t.text(r);break}default:{let o='Token with "'+r.type+'" type was not found.';if(this.options.silent)return console.error(o),"";throw new Error(o)}}}return n}},I=class{options;block;constructor(e){this.options=e||y}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","\
462
+ emStrongMask"]);static passThroughHooksRespectAsync=new Set(["preprocess","postprocess","processAllTokens"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?O.lex:O.lexInline}provideParser(e=this.block){return e?w.parse:w.parseInline}};function z(l3,e){if(Array.isArray(e))for(let t=0;t<e.length;t++)l3.push(e[t]);else l3.push(e)}var Y=class{defaults=j();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.
463
+ parseMarkdown(!1);Parser=w;Renderer=C;TextRenderer=E;Lexer=O;Tokenizer=_;Hooks=I;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(z(n,t.call(this,s)),s.type){case"table":{let i=s;for(let r of i.header)z(n,this.walkTokens(r.tokens,t));for(let r of i.rows)for(let o of r)z(n,this.walkTokens(o.tokens,t));break}case"list":{let i=s;z(n,this.walkTokens(i.items,t));break}default:{let i=s;this.defaults.extensions?.childTokens?.[i.type]?this.defaults.extensions.childTokens[i.
464
+ type].forEach(r=>{let o=i[r].flat(1/0);z(n,this.walkTokens(o,t))}):i.tokens&&z(n,this.walkTokens(i.tokens,t))}}return n}use(...e){let t=this.defaults.extensions||{renderers:Object.create(null),childTokens:Object.create(null)};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(i=>{if(!i.name)throw new Error("extension name required");if("renderer"in i){let r=t.renderers[i.name];r?t.renderers[i.name]=function(...o){let a=i.renderer.apply(
465
+ this,o);return a===!1&&(a=r.apply(this,o)),a}:t.renderers[i.name]=i.renderer}if("tokenizer"in i){if(!i.level||i.level!=="block"&&i.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let r=t[i.level];r?r.unshift(i.tokenizer):t[i.level]=[i.tokenizer],i.start&&(i.level==="block"?t.startBlock?t.startBlock.push(i.start):t.startBlock=[i.start]:i.level==="inline"&&(t.startInline?t.startInline.push(i.start):t.startInline=[i.start]))}"childTokens"in i&&i.childTokens&&(t.childTokens[i.
466
+ name]=i.childTokens)}),s.extensions=t),n.renderer){let i=this.defaults.renderer||new C(this.defaults);for(let r in n.renderer){if(!(r in i))throw new Error(`renderer '${r}' does not exist`);if(["options","parser"].includes(r))continue;let o=r,a=n.renderer[o],p=i[o];i[o]=(...c)=>{let u=a.apply(i,c);return u===!1&&(u=p.apply(i,c)),u===!1?"":u??""}}s.renderer=i}if(n.tokenizer){let i=this.defaults.tokenizer||new _(this.defaults);for(let r in n.tokenizer){if(!(r in i))throw new Error(`tokenizer '${r}\
467
+ ' does not exist`);if(["options","rules","lexer"].includes(r))continue;let o=r,a=n.tokenizer[o],p=i[o];i[o]=(...c)=>{let u=a.apply(i,c);return u===!1&&(u=p.apply(i,c)),u}}s.tokenizer=i}if(n.hooks){let i=this.defaults.hooks||new I;for(let r in n.hooks){if(!(r in i))throw new Error(`hook '${r}' does not exist`);if(["options","block"].includes(r))continue;let o=r,a=n.hooks[o],p=i[o];I.passThroughHooks.has(r)?i[o]=c=>{if(i.options.async&&I.passThroughHooksRespectAsync.has(r))return(async()=>{let d=await a.
468
+ call(i,c);return p.call(i,d)})();let u=a.call(i,c);return p.call(i,u)}:i[o]=(...c)=>{if(i.options.async)return(async()=>{let d=await a.apply(i,c);return d===!1&&(d=await p.apply(i,c)),d})();let u=a.apply(i,c);return u===!1&&(u=p.apply(i,c)),u}}s.hooks=i}if(n.walkTokens){let i=this.defaults.walkTokens,r=n.walkTokens;s.walkTokens=function(o){let a=[];return z(a,r.call(this,o)),i&&z(a,i.call(this,o)),a}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,
469
+ ...e},this}lexer(e,t){return O.lex(e,t??this.defaults)}parser(e,t){return w.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let i={...s},r={...this.defaults,...i},o=this.onError(!!r.silent,!!r.async);if(this.defaults.async===!0&&i.async===!1)return o(new Error("marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise."));if(typeof n>"u"||n===null)return o(new Error("marked(): input parameter is undefined or null"));
470
+ if(typeof n!="string")return o(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(r.hooks&&(r.hooks.options=r,r.hooks.block=e),r.async)return(async()=>{let a=r.hooks?await r.hooks.preprocess(n):n,c=await(r.hooks?await r.hooks.provideLexer(e):e?O.lex:O.lexInline)(a,r),u=r.hooks?await r.hooks.processAllTokens(c):c;r.walkTokens&&await Promise.all(this.walkTokens(u,r.walkTokens));let k=await(r.hooks?await r.hooks.provideParser(e):e?w.parse:w.
471
+ parseInline)(u,r);return r.hooks?await r.hooks.postprocess(k):k})().catch(o);try{r.hooks&&(n=r.hooks.preprocess(n));let p=(r.hooks?r.hooks.provideLexer(e):e?O.lex:O.lexInline)(n,r);r.hooks&&(p=r.hooks.processAllTokens(p)),r.walkTokens&&this.walkTokens(p,r.walkTokens);let u=(r.hooks?r.hooks.provideParser(e):e?w.parse:w.parseInline)(p,r);return r.hooks&&(u=r.hooks.postprocess(u)),u}catch(a){return o(a)}}}onError(e,t){return n=>{if(n.message+=`
472
+ Please report this to https://github.com/markedjs/marked.`,e){let s="<p>An error occurred:</p><pre>"+P(n.message+"",!0)+"</pre>";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}},q=new Y;function x(l3,e){return q.parse(l3,e)}x.options=x.setOptions=function(l3){return q.setOptions(l3),x.defaults=q.defaults,ie(x.defaults),x};x.getDefaults=j;x.defaults=y;function vt(...l3){return q.use(...l3),x.defaults=q.defaults,ie(x.defaults),x}x.use=vt;x.walkTokens=function(l3,e){return q.walkTokens(
473
+ l3,e)};x.parseInline=q.parseInline;x.Parser=w;x.parser=w.parse;x.Renderer=C;x.TextRenderer=E;x.Lexer=O;x.lexer=O.lex;x.Tokenizer=_;x.Hooks=I;x.parse=x;var Ln=x.options,Cn=x.setOptions,In=x.walkTokens,An=x.parseInline;var zn=w.parse,Mn=O.lex;var CJK="\\u1100-\\u11ff\\u20a9\\u2329-\\u232a\\u2630-\\u2637\\u268a-\\u268f\\u2e80-\\u2e99\\u2e9b-\\u2ef3\\u2f00-\\u2fd5\\u2ff0-\\u303e\\u3041-\\u3096\\u3099-\\u30ff\\u3105-\\u312f\\u3131-\\u318e\\u3190-\\u31e5\\u31ef-\\u321e\\u3220-\\u3247\\u3250-\\ua48c\\ua490-\\ua4c6\\ua960-\\ua97c\\uac00-\\ud7a3\\ud7b0-\\ud7c6\\ud7cb-\\ud7fb\\uf900-\\ufaff\\ufe10-\\ufe19\\ufe30-\\ufe52\\ufe54-\\ufe66\\ufe68-\\ufe6b\\uff01-\\uffbe\\uffc2-\\uffc7\\uffca-\\uffcf\\uffd2-\\uffd7\\uffda-\\uffdc\\uffe0-\\uffe6\\uffe8-\\uffee\\u{16fe0}-\\u{16fe4}\\u{16ff0}-\\u{16ff6}\\u{17000}-\\u{18cda\
474
+ }\\u{18cff}-\\u{18d20}\\u{18d80}-\\u{18df2}\\u{18e00}-\\u{19191}\\u{191a0}-\\u{191d2}\\u{1aff0}-\\u{1aff3}\\u{1aff5}-\\u{1affb}\\u{1affd}-\\u{1affe}\\u{1b000}-\\u{1b128}\\u{1b132}\\u{1b150}-\\u{1b152}\\u{1b155}\\u{1b164}-\\u{1b168}\\u{1b170}-\\u{1b2fb}\\u{1d300}-\\u{1d356}\\u{1d360}-\\u{1d376}\\u{1f1ae}\\u{1f200}\\u{1f202}\\u{1f210}-\\u{1f219}\\u{1f21b}-\\u{1f22e}\\u{1f230}-\\u{1f231}\\u{1f237}\\u{1f23b}\\u{1f240}-\\u{1f248}\\u{1f260}-\\u{1f265}\\u{1f7da}\\u{20000}-\\u{3fffd}",cjkTest=new RegExp(
475
+ `[${CJK}]`,"u"),punctuationCjk=new RegExp(`^((?![*_])[\\s\\p{P}\\p{S}${CJK}])`,"u");function buildRDelimAst(punct,punctSpace,notPunctSpace){return new RegExp(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)${punct}(\\*+)(?=[\\s]|$)|${notPunctSpace}(\\*+)(?!\\*)(?=${punctSpace}|$)|(?!\\*)${punctSpace}(\\*+)(?=${notPunctSpace})|[\\s](\\*+)(?!\\*)(?=${punct})|(?!\\*)${punct}(\\*+)(?!\\*)(?=${punct})|${notPunctSpace}(\\*+)(?=${notPunctSpace})`,"gu")}function buildRDelimUnd(punct,punctSpace,notPunctSpace){
476
+ return new RegExp(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)${punct}(_+)(?=[\\s]|$)|${notPunctSpace}(_+)(?!_)(?=${punctSpace}|$)|(?!_)${punctSpace}(_+)(?=${notPunctSpace})|[\\s](_+)(?!_)(?=${punct})|(?!_)${punct}(_+)(?!_)(?=${punct})`,"gu")}function buildRDelimDel(punct,punctSpace,notPunctSpace){return new RegExp(`^[^~]+(?=[^~])|(?!~)${punct}(~~?)(?=[\\s]|$)|${notPunctSpace}(~~?)(?!~)(?=${punctSpace}|$)|(?!~)${punctSpace}(~~?)(?=${notPunctSpace})|[\\s](~~?)(?!~)(?=${punct})|(?!\
477
+ ~)${punct}(~~?)(?!~)(?=${punct})|${notPunctSpace}(~~?)(?=${notPunctSpace})`,"gu")}var cjkPunct=`[\\p{P}\\p{S}${CJK}]`,cjkPunctSpace=`[\\s\\p{P}\\p{S}${CJK}]`,cjkNotPunctSpace=`[^\\s\\p{P}\\p{S}${CJK}]`,cjkDelPunct=`(?![*_])[\\p{P}\\p{S}${CJK}]`,cjkDelPunctSpace=`(?![*_])[\\s\\p{P}\\p{S}${CJK}]`,cjkDelNotPunctSpace=`(?:[^\\s\\p{P}\\p{S}${CJK}]|[*_])`,cjkPunctGfm=`(?!~)[\\p{P}\\p{S}${CJK}]`,cjkPunctSpaceGfm=`(?!~)[\\s\\p{P}\\p{S}${CJK}]`,cjkNotPunctSpaceGfm=`(?:[^\\s\\p{P}\\p{S}${CJK}]|~)`,emStrongRDelimAstCjk=buildRDelimAst(
478
+ cjkPunct,cjkPunctSpace,cjkNotPunctSpace),emStrongRDelimAstCjkGfm=buildRDelimAst(cjkPunctGfm,cjkPunctSpaceGfm,cjkNotPunctSpaceGfm),emStrongRDelimUndCjk=buildRDelimUnd(cjkPunct,cjkPunctSpace,cjkNotPunctSpace),delRDelimCjk=buildRDelimDel(cjkDelPunct,cjkDelPunctSpace,cjkDelNotPunctSpace);function isPrevCharCjk(prevChar,maskedSrc,src){let prevIsCjk=punctuationCjk.test(prevChar);if(!prevIsCjk&&prevChar){let prevIdx=maskedSrc.length-src.length;if(prevIdx>=1){let idx=prevIdx-1,code=maskedSrc.charCodeAt(
479
+ idx);if(code>=65024&&code<=65038&&idx>=1&&(idx--,code=maskedSrc.charCodeAt(idx)),(code&64512)===56320&&idx>=1){let cp=maskedSrc.codePointAt(idx-1);cp!==void 0&&cp>65535&&(cp>=917760&&cp<=917999?prevIsCjk=!0:prevIsCjk=cjkTest.test(String.fromCodePoint(cp)))}else prevIsCjk=cjkTest.test(String.fromCharCode(code))}}return prevIsCjk}function isCjkAdjacentToDelimiter(rightMatch,clippedMaskedSrc){if(!(rightMatch[1]||rightMatch[2]||rightMatch[3]||rightMatch[4]))return!1;let charBefore=String.fromCodePoint(
480
+ rightMatch[0].codePointAt(0)),afterPos=rightMatch.index+rightMatch[0].length,charAfter=afterPos<clippedMaskedSrc.length?String.fromCodePoint(clippedMaskedSrc.codePointAt(afterPos)):"";return cjkTest.test(charBefore)||cjkTest.test(charAfter)}function usesModernEmStrongLayout(match){return match.length>=5}function hasEmStrongLeadContent(match){return!!(match[1]||match[2]||match[3]||match[4])}function isEmStrongUnderscoreWordChar(match){return usesModernEmStrongLayout(match)?!!match[4]:!!match[3]}function getEmStrongOpeningPunctuation(match){
481
+ return usesModernEmStrongLayout(match)?match[1]||match[3]||"":match[1]||match[2]||""}function codePointCount(str){let result=str.length,end=result-1;for(let i=0;i<end;){let bmpOrHigh=str.charCodeAt(i++);if(bmpOrHigh<55296||56320<=bmpOrHigh)continue;let low=str.charCodeAt(i);low<56320||57344<=low||(i++,result--)}return result}function markedCjkFriendly(){return{tokenizer:{emStrong(src,maskedSrc,prevChar=""){let{rules}=this,match=rules.inline.emStrongLDelim.exec(src);if(!match)return!1;let modernEmStrongLayout=usesModernEmStrongLayout(
482
+ match);if(modernEmStrongLayout&&!hasEmStrongLeadContent(match))return;if(isEmStrongUnderscoreWordChar(match)&&prevChar.match(rules.other.unicodeAlphaNumeric))return!1;let nextChar=getEmStrongOpeningPunctuation(match),prevIsCjk=isPrevCharCjk(prevChar,maskedSrc,src);if(!nextChar||!prevChar||rules.inline.punctuation.exec(prevChar)||prevIsCjk||cjkTest.test(nextChar)){let lLength=codePointCount(match[0])-1,rDelim,rLength,delimTotal=lLength,midDelimTotal=0,prevCharIsSameDelimiter=modernEmStrongLayout&&
483
+ prevChar===match[0][0],isGfm=rules.inline.emStrongRDelimAst.source.includes("(?!~)"),endReg;match[0][0]==="*"?endReg=isGfm?emStrongRDelimAstCjkGfm:emStrongRDelimAstCjk:endReg=emStrongRDelimUndCjk,endReg.lastIndex=0;let clippedMaskedSrc=maskedSrc.slice(-1*src.length+lLength),rMatch;for(;(rMatch=endReg.exec(clippedMaskedSrc))!=null;){if(rDelim=rMatch[1]||rMatch[2]||rMatch[3]||rMatch[4]||rMatch[5]||rMatch[6],!rDelim)continue;rLength=codePointCount(rDelim);let isCjkAdjacent=isCjkAdjacentToDelimiter(
484
+ rMatch,clippedMaskedSrc),isLeftOnly=!!(rMatch[3]||rMatch[4]),isBoth=!!(rMatch[5]||rMatch[6]);if(isLeftOnly&&!isCjkAdjacent){delimTotal+=rLength;continue}if(isBoth||isCjkAdjacent){if(lLength%3&&!((lLength+rLength)%3)){midDelimTotal+=rLength;continue}if(prevCharIsSameDelimiter&&isBoth)break}if(delimTotal-=rLength,delimTotal>0)continue;rLength=Math.min(rLength,rLength+delimTotal+midDelimTotal);let lastCharLength=rMatch[0].codePointAt(0)>65535?2:1,raw=src.slice(0,lLength+rMatch.index+lastCharLength+
485
+ rLength);if(Math.min(lLength,rLength)%2){let text2=raw.slice(1,-1);return{type:"em",raw,text:text2,tokens:this.lexer.inlineTokens(text2)}}let text=raw.slice(2,-2);return{type:"strong",raw,text,tokens:this.lexer.inlineTokens(text)}}}},del(src,maskedSrc,prevChar=""){let{rules}=this,match=rules.inline.delLDelim.exec(src);if(!match)return!1;let nextChar=match[1]||"",prevIsCjk=isPrevCharCjk(prevChar,maskedSrc,src);if(!nextChar||!prevChar||rules.inline.punctuation.exec(prevChar)||prevIsCjk||cjkTest.test(
486
+ nextChar)){let lLength=codePointCount(match[0])-1,rDelim,rLength,delimTotal=lLength;delRDelimCjk.lastIndex=0;let clippedMaskedSrc=maskedSrc.slice(-1*src.length+lLength),rMatch;for(;(rMatch=delRDelimCjk.exec(clippedMaskedSrc))!=null;){if(rDelim=rMatch[1]||rMatch[2]||rMatch[3]||rMatch[4]||rMatch[5]||rMatch[6],!rDelim||(rLength=codePointCount(rDelim),rLength!==lLength))continue;let isCjkAdjacent=isCjkAdjacentToDelimiter(rMatch,clippedMaskedSrc);if((rMatch[3]||rMatch[4])&&!isCjkAdjacent){delimTotal+=
487
+ rLength;continue}if(delimTotal-=rLength,delimTotal>0)continue;rLength=Math.min(rLength,rLength+delimTotal);let lastCharLength=rMatch[0].codePointAt(0)>65535?2:1,raw=src.slice(0,lLength+rMatch.index+lastCharLength+rLength),text=raw.slice(lLength,-lLength);return{type:"del",raw,text,tokens:this.lexer.inlineTokens(text)}}}}}}}var SYMBOLS={alpha:"\u03B1",beta:"\u03B2",gamma:"\u03B3",delta:"\u03B4",epsilon:"\u03F5",varepsilon:"\u03B5",zeta:"\u03B6",eta:"\u03B7",theta:"\u03B8",vartheta:"\u03D1",iota:"\u03B9",kappa:"\u03BA",varkappa:"\u03F0",lambda:"\u03BB",mu:"\u03BC",nu:"\u03BD",xi:"\u03BE",pi:"\u03C0",varpi:"\u03D6",rho:"\u03C1",varrho:"\u03F1",sigma:"\u03C3",varsigma:"\u03C2",tau:"\u03C4",upsilon:"\u03C5",phi:"\u03D5",varphi:"\u03C6",chi:"\u03C7",psi:"\u03C8",omega:"\u03C9",Gamma:"\u0393",Delta:"\u0394",Theta:"\u0398",
488
+ Lambda:"\u039B",Xi:"\u039E",Pi:"\u03A0",Sigma:"\u03A3",Upsilon:"\u03A5",Phi:"\u03A6",Psi:"\u03A8",Omega:"\u03A9",pm:"\xB1",mp:"\u2213",times:"\xD7",div:"\xF7",cdot:"\xB7",ast:"\u2217",star:"\u22C6",circ:"\u2218",bullet:"\u2022",oplus:"\u2295",ominus:"\u2296",otimes:"\u2297",oslash:"\u2298",odot:"\u2299",bigcirc:"\u25CB",dagger:"\u2020",ddagger:"\u2021",amalg:"\u2A3F",uplus:"\u228E",sqcap:"\u2293",sqcup:"\u2294",bowtie:"\u22C8",Join:"\u22C8",ltimes:"\u22C9",rtimes:"\u22CA",leftouterjoin:"\u27D5",
489
+ rightouterjoin:"\u27D6",fullouterjoin:"\u27D7",triangleleft:"\u25C1",triangleright:"\u25B7",wr:"\u2240",cap:"\u2229",cup:"\u222A",bigcap:"\u22C2",bigcup:"\u22C3",bigwedge:"\u22C0",bigvee:"\u22C1",bigsqcup:"\u2A06",biguplus:"\u2A04",bigoplus:"\u2A01",bigotimes:"\u2A02",bigodot:"\u2A00",setminus:"\u2216",in:"\u2208",notin:"\u2209",ni:"\u220B",subset:"\u2282",supset:"\u2283",subseteq:"\u2286",supseteq:"\u2287",sqsubset:"\u228F",sqsupset:"\u2290",sqsubseteq:"\u2291",sqsupseteq:"\u2292",prec:"\u227A",
490
+ preceq:"\u227C",succ:"\u227B",succeq:"\u227D",ll:"\u226A",gg:"\u226B",le:"\u2264",leq:"\u2264",leqslant:"\u2264",ge:"\u2265",geq:"\u2265",geqslant:"\u2265",ne:"\u2260",neq:"\u2260",equiv:"\u2261",approx:"\u2248",sim:"\u223C",simeq:"\u2243",cong:"\u2245",asymp:"\u224D",doteq:"\u2250",propto:"\u221D",parallel:"\u2225",perp:"\u22A5",mid:"\u2223",vdash:"\u22A2",dashv:"\u22A3",models:"\u22A8",Vdash:"\u22A9",Vvdash:"\u22AA",nvdash:"\u22AC",nvDash:"\u22AD",forall:"\u2200",exists:"\u2203",nexists:"\u2204",
491
+ neg:"\xAC",land:"\u2227",wedge:"\u2227",lor:"\u2228",vee:"\u2228",to:"\u2192",rightarrow:"\u2192",longrightarrow:"\u2192",leftarrow:"\u2190",longleftarrow:"\u2190",gets:"\u2190",leftrightarrow:"\u2194",longleftrightarrow:"\u2194",hookleftarrow:"\u21A9",hookrightarrow:"\u21AA",twoheadleftarrow:"\u219E",twoheadrightarrow:"\u21A0",leftharpoonup:"\u21BC",leftharpoondown:"\u21BD",rightharpoonup:"\u21C0",rightharpoondown:"\u21C1",rightleftharpoons:"\u21CC",leftrightharpoons:"\u21CB",nearrow:"\u2197",searrow:"\
492
+ \u2198",swarrow:"\u2199",nwarrow:"\u2196",rightsquigarrow:"\u21DD",leadsto:"\u21DD",Rightarrow:"\u21D2",Longrightarrow:"\u21D2",Leftarrow:"\u21D0",Longleftarrow:"\u21D0",Leftrightarrow:"\u21D4",Longleftrightarrow:"\u21D4",implies:"\u21D2",iff:"\u21D4",mapsto:"\u21A6",longmapsto:"\u21A6",uparrow:"\u2191",downarrow:"\u2193",partial:"\u2202",nabla:"\u2207",int:"\u222B",iint:"\u222C",iiint:"\u222D",oint:"\u222E",sum:"\u2211",prod:"\u220F",coprod:"\u2210",infty:"\u221E",emptyset:"\u2205",varnothing:"\
493
+ \u2205",angle:"\u2220",therefore:"\u2234",because:"\u2235",aleph:"\u2135",beth:"\u2136",gimel:"\u2137",daleth:"\u2138",top:"\u22A4",bot:"\u22A5",triangle:"\u25B3",square:"\u25A1",lozenge:"\u25CA",checkmark:"\u2713",complement:"\u2201",wp:"\u2118",prime:"\u2032",ldots:"\u2026",dots:"\u2026",cdots:"\u22EF",vdots:"\u22EE",ddots:"\u22F1",ell:"\u2113",hbar:"\u210F",Im:"\u2111",Re:"\u211C",langle:"\u27E8",rangle:"\u27E9",vert:"|",lvert:"|",rvert:"|",Vert:"\u2016",lVert:"\u2016",rVert:"\u2016",lbrace:"\
494
+ {",rbrace:"}",backslash:"\\",lfloor:"\u230A",rfloor:"\u230B",lceil:"\u2308",rceil:"\u2309",colon:":"},NAMED_OPERATORS=new Set(["arccos","arcsin","arctan","arg","cos","cosh","cot","coth","csc","deg","det","dim","exp","gcd","hom","inf","ker","lg","lim","liminf","limsup","ln","log","max","min","Pr","sec","sin","sinh","sup","tan","tanh"]),LIMIT_OPERATORS=new Set(["argmax","argmin","inf","injlim","lim","liminf","limsup","max","min","projlim","sup"]),DISPLAY_LIMIT_SYMBOLS=new Set(["bigcap","bigcup","b\
495
+ igodot","bigoplus","bigotimes","bigsqcup","biguplus","bigvee","bigwedge","coprod","int","iint","iiint","oint","prod","sum"]),RELATION_COMMANDS=new Set(["Leftarrow","Leftrightarrow","Longleftarrow","Longleftrightarrow","Longrightarrow","Rightarrow","Join","Vdash","Vvdash","approx","asymp","bowtie","cong","dashv","fullouterjoin","doteq","downarrow","equiv","ge","geq","geqslant","gets","gg","hookleftarrow","hookrightarrow","iff","implies","in","leadsto","le","leftarrow","leftharpoondown","leftharpo\
496
+ onup","leftrightarrow","leftrightharpoons","leftouterjoin","leq","leqslant","ll","longleftarrow","longleftrightarrow","longmapsto","longrightarrow","ltimes","mapsto","mid","models","ne","nearrow","neq","ni","notin","nvdash","nvDash","nwarrow","parallel","perp","prec","preceq","propto","rightharpoondown","rightharpoonup","rightleftharpoons","rightouterjoin","rightarrow","rightsquigarrow","rtimes","searrow","sim","simeq","sqsubset","sqsubseteq","sqsupset","sqsupseteq","subset","subseteq","succ","s\
497
+ ucceq","supset","supseteq","swarrow","to","triangleleft","triangleright","twoheadleftarrow","twoheadrightarrow","uparrow","vdash"]),NEGATED_SYMBOLS={"<":"\u226E",">":"\u226F","=":"\u2260","\u2208":"\u2209","\u220B":"\u220C","\u2223":"\u2224","\u2225":"\u2226","\u223C":"\u2241","\u2243":"\u2244","\u2245":"\u2247","\u2248":"\u2249","\u2261":"\u2262","\u2264":"\u2270","\u2265":"\u2271","\u227A":"\u2280","\u227B":"\u2281","\u2282":"\u2284","\u2283":"\u2285","\u2286":"\u2288","\u2287":"\u2289","\u22A2":"\
498
+ \u22AC","\u22A8":"\u22AD","\u2194":"\u21AE","\u2190":"\u219A","\u2192":"\u219B","\u21D2":"\u21CF","\u21D0":"\u21CD","\u21D4":"\u21CE","\u227C":"\u22E0","\u227D":"\u22E1"},BLACKBOARD={C:"\u2102",H:"\u210D",N:"\u2115",P:"\u2119",Q:"\u211A",R:"\u211D",Z:"\u2124"},SUPERSCRIPTS={0:"\u2070",1:"\xB9",2:"\xB2",3:"\xB3",4:"\u2074",5:"\u2075",6:"\u2076",7:"\u2077",8:"\u2078",9:"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\
499
+ \u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"},SUBSCRIPTS={0:"\u2080",1:"\u2081",2:"\u2082",3:"\u2083",4:"\u2084",5:"\u2085",6:"\u2086",7:"\u2087",8:"\u2088",9:"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",
500
+ o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"},SPACING_COMMANDS=new Set([",",":",";"," ",">","enspace","enskip","medspace","quad","qquad","thickspace","thinspace"]),NEGATIVE_SPACING_COMMANDS=new Set(["!","negmedspace","negthickspace","negthinspace"]),NEGATIVE_SPACE="\0",FONT_SWITCH_COMMANDS=new Set(["bf","cal","it","rm","sf","sl","tt"]),IGNORED_COMMANDS=new Set(["displaystyle","limits","nolimits","scriptstyle","scriptscriptstyle","textstyle"]),SIZE_COMMANDS=new Set(
501
+ ["big","Big","bigg","Bigg","bigl","Bigl","biggl","Biggl","bigr","Bigr","biggr","Biggr"]),PLAIN_WRAPPERS=new Set(["emph","mathcal","mathbf","mathfrak","mathit","mathrm","mathnormal","mathscr","mathsf","mathtt","mathup","mbox","overbrace","pmb","smash","substack","text","textbf","textit","textmd","textnormal","textrm","textsc","textsf","textsl","texttt","textup","underbrace","bm","boldsymbol"]),ACCENTS={acute:"\u0301",bar:"\u0305",breve:"\u0306",check:"\u030C",ddot:"\u0308",dot:"\u0307",grave:"\u0300",
502
+ hat:"\u0302",mathring:"\u030A",overleftarrow:"\u20D6",overleftrightarrow:"\u20E1",overline:"\u0305",overrightarrow:"\u20D7",tilde:"\u0303",underline:"\u0332",vec:"\u20D7",widehat:"\u0302",widetilde:"\u0303"};function replaceCharacters(value,replacements){let result="";for(let character of value){let replacement=replacements[character];if(replacement===void 0)return;result+=replacement}return result}function normalizeScriptValue(value){return value.trim().replace(/\s*([=+-])\s*/g,"$1")}function formatUnicodeScript(value,kind){
503
+ return replaceCharacters(normalizeScriptValue(value),kind==="sub"?SUBSCRIPTS:SUPERSCRIPTS)}function formatScript(value,kind){value=normalizeScriptValue(value);let unicode=formatUnicodeScript(value,kind);if(unicode!==void 0)return unicode;let prefix=kind==="sub"?"_":"^";return Array.from(value).length===1||kind==="sub"&&/^[A-Za-z]+$/.test(value)?`${prefix}${value}`:`${prefix}(${value})`}function formatFraction(numerator,denominator){numerator=numerator.trim(),denominator=denominator.trim();let simpleNumerator=/^[\p{L}\p{N}.]+$/u.
504
+ test(numerator),simpleDenominator=/^[\p{N}.]+$/u.test(denominator)||Array.from(denominator).length===1;return`${simpleNumerator?numerator:`(${numerator})`}/${simpleDenominator?denominator:`(${denominator})`}`}function formatRoot(value,symbol="\u221A"){return value=value.trim(),/^[\p{L}\p{N}.]+$/u.test(value)?`${symbol}${value}`:`${symbol}(${value})`}var NAMED_OPERATOR_START="\u{F0004}",NAMED_OPERATOR_END="\u{F0005}",NAMED_OPERATOR_LEFT_SPACING_PATTERN=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,
505
+ NAMED_OPERATOR_RIGHT_SPACING_PATTERN=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function normalizeOutput(value){return value.replace(NAMED_OPERATOR_LEFT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_START,"").replace(NAMED_OPERATOR_RIGHT_SPACING_PATTERN," ").replaceAll(NAMED_OPERATOR_END,"").split(`
506
+ `).map(line=>line.replace(/[ \t]+/g," ").trim()).filter((line,index,lines)=>line.length>0||index>0&&index<lines.length-1).join(`
507
+ `).trim()}var LAYOUT_MARKER_START="\u{F0000}",LAYOUT_MARKER_END="\u{F0001}",LAYOUT_MARKER_PATTERN=/\u{f0000}(\d+)\u{f0001}/gu,TRAILING_LAYOUT_MARKER_PATTERN=/\u{f0000}(\d+)\u{f0001}$/u,PROTECTED_SPACE="\u{F0002}";function padLayoutLine(line,width,centered=!1){let padding=Math.max(0,width-visibleWidth(line)),left=centered?Math.floor(padding/2):0;return`${" ".repeat(left)}${line}${" ".repeat(padding-left)}`}function joinLayouts(layouts){if(layouts.length===0)return{lines:[""],width:0,baseline:0};let baseline=Math.
508
+ max(...layouts.map(layout=>layout.baseline)),below=Math.max(...layouts.map(layout=>layout.lines.length-layout.baseline-1)),lines=[];for(let row=0;row<=baseline+below;row++){let line="";for(let layout of layouts){let sourceRow=row-baseline+layout.baseline;line+=sourceRow>=0&&sourceRow<layout.lines.length?padLayoutLine(layout.lines[sourceRow]??"",layout.width):" ".repeat(layout.width)}lines.push(line.trimEnd())}return{lines,width:layouts.reduce((width,layout)=>width+layout.width,0),baseline}}function renderLayout(source,nodes){
509
+ let renderedLines=[],firstBaseline=0;for(let sourceLine of source.split(`
510
+ `)){let layouts=[],position=0,previousNode;for(let match of sourceLine.matchAll(LAYOUT_MARKER_PATTERN)){let index=match.index,node=nodes[Number(match[1])];if(node){if(index>position){let sliced=sourceLine.slice(position,index),trimmed=(previousNode?sliced.trimStart():sliced).trimEnd(),preserveLeadingSpace=previousNode?.type==="matrix"&&/^\s/.test(sliced),preserveTrailingSpace=node.type==="matrix"&&/\s$/.test(sliced),text=trimmed?`${preserveLeadingSpace?" ":""}${trimmed}${preserveTrailingSpace?" ":
511
+ ""}`:preserveLeadingSpace||preserveTrailingSpace?" ":"";layouts.push({lines:[text],width:visibleWidth(text),baseline:0})}if(node.type==="fraction"){let numerator=renderLayout(node.numerator,nodes),denominator=renderLayout(node.denominator,nodes),contentWidth=Math.max(numerator.width,denominator.width,1),width=contentWidth+2;layouts.push({lines:[...numerator.lines.map(line=>padLayoutLine(line,width,!0)),` ${"\u2500".repeat(contentWidth)} `,...denominator.lines.map(line=>padLayoutLine(line,width,!0))],
512
+ width,baseline:numerator.lines.length})}else if(node.type==="operator"){let contentWidth=Math.max(visibleWidth(node.operator),node.lower===void 0?0:visibleWidth(node.lower),node.upper===void 0?0:visibleWidth(node.upper)),lines=[];node.upper!==void 0&&lines.push(`${padLayoutLine(node.upper,contentWidth,!0)} `),lines.push(`${padLayoutLine(node.operator,contentWidth,!0)} `),node.lower!==void 0&&lines.push(`${padLayoutLine(node.lower,contentWidth,!0)} `),layouts.push({lines,width:contentWidth+1,baseline:node.
513
+ upper===void 0?0:1})}else if(node.type==="script"){let upper=node.upper===void 0?void 0:renderLayout(node.upper,nodes),lower=node.lower===void 0?void 0:renderLayout(node.lower,nodes),width=Math.max(upper?.width??0,lower?.width??0);layouts.push({lines:[...upper?.lines.map(line=>padLayoutLine(line,width))??[]," ".repeat(width),...lower?.lines.map(line=>padLayoutLine(line,width))??[]],width,baseline:upper?.lines.length??0})}else{let width=Math.max(0,...node.lines.map(line=>visibleWidth(line)));layouts.
514
+ push({lines:node.lines.map(line=>padLayoutLine(line,width)),width,baseline:node.baseline})}position=index+match[0].length,previousNode=node}}if(position<sourceLine.length){let sliced=sourceLine.slice(position),trimmed=previousNode?sliced.trimStart():sliced,text=previousNode?.type==="matrix"&&/^\s/.test(sliced)?` ${trimmed}`:trimmed;layouts.push({lines:[text],width:visibleWidth(text),baseline:0})}let lineLayout=joinLayouts(layouts);renderedLines.length===0&&(firstBaseline=lineLayout.baseline),renderedLines.
515
+ push(...lineLayout.lines)}return{lines:renderedLines,width:Math.max(0,...renderedLines.map(line=>visibleWidth(line))),baseline:firstBaseline}}var LatexParser=class _LatexParser{source;layoutNodes;display;position=0;supported=!0;stackFractions=!0;scriptDepth=0;constructor(source,layoutNodes,display){this.source=source,this.layoutNodes=layoutNodes,this.display=display}render(){let rendered=this.parseSequence();if(!(!this.supported||this.position!==this.source.length))return normalizeOutput(rendered)}parseSequence(endCharacter){
516
+ let result="";for(;this.position<this.source.length;){let character=this.source[this.position];if(endCharacter&&character===endCharacter)return this.position++,result;if(character==="}")return this.supported=!1,result;if(character==="{"){this.position++,result+=this.parseSequence("}");continue}if(character==="\\"){let command=this.parseCommand();command===NEGATIVE_SPACE?(result=result.trimEnd(),result.endsWith(NAMED_OPERATOR_END)&&(result=result.slice(0,-NAMED_OPERATOR_END.length))):result+=command;
517
+ continue}if(character==="^"||character==="_"){this.position++,result=result.trimEnd();let script=this.parseScripts(character);result.endsWith(NAMED_OPERATOR_END)?result=`${result.slice(0,-NAMED_OPERATOR_END.length)}${script}${NAMED_OPERATOR_END}`:result+=script;continue}if(/\s/.test(character)){result+=this.parseWhitespace();continue}if(character==="="||character==="<"||character===">"){result=`${result.trimEnd()} ${character} `,this.position++;continue}if(character==="&"){this.position++;continue}
518
+ if(character==="~"){this.position++,result+=" ";continue}if(character==="."){let marker=TRAILING_LAYOUT_MARKER_PATTERN.exec(result),node=marker?this.layoutNodes[Number(marker[1])]:void 0;if(node?.type==="matrix"){let lastLine=node.lines.length-1;node.lines[lastLine]=`${node.lines[lastLine]??""}${character}`,this.position++;continue}}result+=character,this.position++}return endCharacter&&(this.supported=!1),result}parseScripts(initialMarker){let scripts={},order=[],parse=marker=>{let kind=marker===
519
+ "_"?"sub":"sup";this.scriptDepth++;try{scripts[kind]=this.parseRequiredArgument(!1)}finally{this.scriptDepth--}order.push(kind)};parse(initialMarker);let nextPosition=this.position;for(;nextPosition<this.source.length&&/\s/.test(this.source[nextPosition]??"");)nextPosition++;let nextMarker=this.source[nextPosition];(nextMarker==="^"||nextMarker==="_")&&nextMarker!==initialMarker&&(this.position=nextPosition+1,parse(nextMarker));let subUnicode=scripts.sub===void 0?void 0:formatUnicodeScript(scripts.
520
+ sub,"sub"),supUnicode=scripts.sup===void 0?void 0:formatUnicodeScript(scripts.sup,"sup"),canUseLayout=![scripts.sub,scripts.sup].some(value=>value!==void 0&&(value.includes("/")||!value.includes(LAYOUT_MARKER_START)&&Array.from(value).length>1&&!/[A-Z*∗]/.test(value)));if(!(this.display&&canUseLayout&&(this.scriptDepth>0||scripts.sub!==void 0&&subUnicode===void 0||scripts.sup!==void 0&&supUnicode===void 0)))return order.map(kind=>kind==="sub"?subUnicode??formatScript(scripts.sub??"",kind):supUnicode??
521
+ formatScript(scripts.sup??"",kind)).join("");let index=this.layoutNodes.push({type:"script",lower:scripts.sub===void 0?void 0:normalizeOutput(scripts.sub),upper:scripts.sup===void 0?void 0:normalizeOutput(scripts.sup)})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}parseWhitespace(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return" "}parseCommand(){if(this.position++,this.position>=this.source.length)return this.supported=!1,
522
+ "";let command="",first=this.source[this.position]??"";if(first===`
523
+ `||first==="\r")return this.position++,first==="\r"&&this.source[this.position]===`
524
+ `&&this.position++," ";if(/[A-Za-z]/.test(first)){let start=this.position;for(;this.position<this.source.length&&/[A-Za-z]/.test(this.source[this.position]??"");)this.position++;command=this.source.slice(start,this.position)}else command=first,this.position++;if(command==="\\")return`
525
+ `;if(SPACING_COMMANDS.has(command))return" ";if(NEGATIVE_SPACING_COMMANDS.has(command))return NEGATIVE_SPACE;if(FONT_SWITCH_COMMANDS.has(command)){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;return""}if(IGNORED_COMMANDS.has(command))return"";if(command==="{"||command==="}"||command==="$"||command==="%"||command==="#"||command==="_"||command==="&")return command;if(command==="|")return"\u2016";if(command==="not"){let value=this.parseRequiredArgument(
526
+ !1).trim(),negated=NEGATED_SYMBOLS[value];if(negated!==void 0)return` ${negated} `;let characters=Array.from(value);return characters.length===0?(this.supported=!1,""):` ${characters[0]}\u0338${characters.slice(1).join("")} `}if(LIMIT_OPERATORS.has(command))return this.parseOperator(command,"bracket",!0,!0);let symbol=SYMBOLS[command];if(symbol!==void 0)return DISPLAY_LIMIT_SYMBOLS.has(command)?this.parseOperator(symbol,"script",!0):command==="cdot"||command==="times"||RELATION_COMMANDS.has(command)?
527
+ ` ${symbol} `:symbol;if(NAMED_OPERATORS.has(command))return`${NAMED_OPERATOR_START}${command}${NAMED_OPERATOR_END}`;if(SIZE_COMMANDS.has(command))return"";if(command==="left"||command==="middle"||command==="right")return this.source[this.position]==="."&&this.position++,"";if(command==="frac"||command==="dfrac"||command==="tfrac"){let shouldStack=this.display&&this.stackFractions&&command!=="tfrac",numerator=this.parseRequiredArgument(!shouldStack),denominator=this.parseRequiredArgument(!shouldStack);
528
+ if(shouldStack){let index=this.layoutNodes.push({type:"fraction",numerator:normalizeOutput(numerator),denominator:normalizeOutput(denominator)})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}return formatFraction(numerator,denominator)}if(command==="sqrt"){let degree=this.parseOptionalArgument()?.trim(),value=this.parseRequiredArgument();return degree===void 0||degree==="2"?formatRoot(value):degree==="3"?formatRoot(value,"\u221B"):degree==="4"?formatRoot(value,"\u221C"):`${formatScript(
529
+ degree,"sup")}${formatRoot(value)}`}if(command==="boxed"||command==="fbox")return`[${this.parseRequiredArgument().trim()}]`;if(command==="binom"||command==="dbinom"||command==="tbinom")return`(${this.parseRequiredArgument()} choose ${this.parseRequiredArgument()})`;let accent=ACCENTS[command];if(accent!==void 0){let value=this.parseRequiredArgument();return Array.from(value).length===1?`${value}${accent}`:`${command}(${value})`}if(command==="mathbb"){let value=this.parseRequiredArgument();return Array.
530
+ from(value,character=>BLACKBOARD[character]??character).join("")}if(command==="operatorname"){let starred=this.source[this.position]==="*";starred&&this.position++;let operator=normalizeOutput(this.parseRequiredArgument()).trim();return this.parseOperator(operator,"bracket",starred,!0)}if(command==="mod"||command==="bmod")return" mod ";if(command==="pmod"||command==="pod"){let value=this.parseRequiredArgument().trim();return command==="pmod"?` (mod ${value})`:` (${value})`}if(command==="overset"||
531
+ command==="stackrel"){let upper=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${formatScript(upper,"sup")}`}if(command==="underset"){let lower=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${formatScript(lower,"sub")}`}if(PLAIN_WRAPPERS.has(command)){let value=this.parseRequiredArgument();return command.startsWith("text")||command==="mbox"?value:value.trim()}return command==="begin"?this.parseEnvironment():command==="end"?(this.supported=!1,
532
+ ""):(this.supported=!1,`\\${command}`)}parseOperator(operator,inlineLowerStyle,displayLimits,spaced=!1){let useDisplayLimits=displayLimits,modifierPosition=this.position;for(;modifierPosition<this.source.length&&/[ \t]/.test(this.source[modifierPosition]??"");)modifierPosition++;let modifier=/^\\(limits|nolimits)(?![A-Za-z])/.exec(this.source.slice(modifierPosition));modifier&&(useDisplayLimits=modifier[1]==="limits",this.position=modifierPosition+modifier[0].length);let lower,upper;for(;;){let scriptPosition=this.
533
+ position;for(;scriptPosition<this.source.length&&/[ \t]/.test(this.source[scriptPosition]??"");)scriptPosition++;let kind=this.source[scriptPosition];if(kind!=="_"&&kind!=="^")break;this.position=scriptPosition+1;let value=normalizeOutput(this.parseRequiredArgument(!1)).replaceAll(" ","");kind==="_"?(lower!==void 0&&(this.supported=!1),lower=value):(upper!==void 0&&(this.supported=!1),upper=value)}if(this.display&&useDisplayLimits&&(lower!==void 0||upper!==void 0)){let index=this.layoutNodes.push(
534
+ {type:"operator",operator,lower,upper})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}let rendered=operator;return lower!==void 0&&(rendered+=inlineLowerStyle==="bracket"?`[${lower}]`:formatScript(lower,"sub")),upper!==void 0&&(rendered+=formatScript(upper,"sup")),spaced?` ${rendered} `:rendered}parseRequiredArgument(stackFractions=!0){let previousStackFractions=this.stackFractions;this.stackFractions=previousStackFractions&&stackFractions;let value=this.parseRequiredArgumentValue();
535
+ return this.stackFractions=previousStackFractions,value}parseRequiredArgumentValue(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??"");)this.position++;if(this.position>=this.source.length)return this.supported=!1,"";if(this.source[this.position]==="{")return this.position++,this.parseSequence("}");if(this.source[this.position]==="\\")return this.parseCommand();let value=this.source[this.position]??"";return this.position++,value}parseOptionalArgument(){for(;this.position<
536
+ this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="[")return;let end=this.source.indexOf("]",this.position+1);if(end<0){this.supported=!1;return}let value=this.source.slice(this.position+1,end);return this.position=end+1,this.renderNested(value)}readRawGroup(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??"");)this.position++;if(this.source[this.position]!=="{"){this.supported=!1;return}let start=++this.
537
+ position,depth=1;for(;this.position<this.source.length;){let character=this.source[this.position];if(character==="\\"){this.position+=2;continue}if(character==="{"&&depth++,character==="}"&&depth--,depth===0){let value=this.source.slice(start,this.position);return this.position++,value}this.position++}this.supported=!1}splitEnvironmentRows(body){return body.split(/\\\\(?:\[[^\]\n]*\])?/)}parseEnvironment(){let environment=this.readRawGroup();if(!environment)return"";let endMarker=`\\end{${environment}\
538
+ }`,end=this.source.indexOf(endMarker,this.position);if(end<0)return this.supported=!1,"";let body=this.source.slice(this.position,end);if(this.position=end+endMarker.length,environment==="equation"||environment==="equation*"||environment==="displaymath")return this.renderNested(body).trim();if(environment==="aligned"||environment==="align"||environment==="align*"||environment==="alignedat"||environment==="alignat"||environment==="alignat*"||environment==="gather"||environment==="gathered"||environment===
539
+ "multline"||environment==="multline*"||environment==="split"){let alignedAt=["alignedat","alignat","alignat*"].includes(environment),alignedBody=alignedAt?body.replace(/^\s*\{[^}]*\}/,""):body;return this.splitEnvironmentRows(alignedBody).map(row=>{let cells=row.split("&"),source=alignedAt?Array.from({length:Math.ceil(cells.length/2)},(_2,index)=>cells.slice(index*2,index*2+2).join("")).join(" "):cells.join("");return this.renderNested(source).trim()}).filter(Boolean).join(`
540
+ `)}if(environment==="cases"||environment==="cases*")return this.renderCases(body);if(["array","matrix","smallmatrix","pmatrix","bmatrix","Bmatrix","vmatrix","Vmatrix"].includes(environment)){let matrixBody=environment==="array"?body.replace(/^\s*\{[^}]*\}/,""):body;return this.renderMatrix(environment,matrixBody)}return this.supported=!1,body}renderCases(body){let rows=this.splitEnvironmentRows(body).map(row=>row.split("&").map(cell=>this.renderNested(cell,!1).trim())).filter(row=>row.some(Boolean)),
541
+ valueWidth=Math.max(0,...rows.map(row=>visibleWidth((row[0]??"").replace(/,\s*$/,"")))),contents=rows.map(row=>{let value=(row[0]??"").replace(/,\s*$/,""),condition=row[1]??"";if(!condition)return value;let conditionPrefix=/^(?:if|when|for|otherwise)\b/i.test(condition)?" ":" if ";return`${value}${PROTECTED_SPACE.repeat(valueWidth-visibleWidth(value))}${conditionPrefix}${condition}`});if(contents.length<=1)return contents.length===0?"":`\u23A7 ${contents[0]}`;let middle=Math.floor(contents.length/
542
+ 2),visualRows=[...contents];contents.length%2===0&&visualRows.splice(middle,0,void 0);let lines=visualRows.map((content,index2)=>{let delimiter=index2===0?"\u23A7":index2===visualRows.length-1?"\u23A9":"\u23A8";return content===void 0?delimiter:`${delimiter} ${content}`}),index=this.layoutNodes.push({type:"matrix",lines,baseline:middle})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}renderMatrix(environment,body){let matrix=this.splitEnvironmentRows(body).map(row=>row.split("&").map(
543
+ cell=>this.renderNested(cell,!1).trim())).filter(row=>row.some(Boolean)),columnCount=Math.max(0,...matrix.map(row=>row.length)),columnWidths=Array.from({length:columnCount},(_2,column)=>Math.max(0,...matrix.map(row=>visibleWidth(row[column]??"")))),rows=matrix.map(row=>Array.from({length:columnCount},(_2,column)=>{let cell=row[column]??"";return`${cell}${PROTECTED_SPACE.repeat(Math.max(0,(columnWidths[column]??0)-visibleWidth(cell)))}`}).join(" \u2502 ")),lines;if(environment==="array"||environment===
544
+ "matrix"||environment==="smallmatrix")lines=rows;else{let delimiter={pmatrix:["\u239B","\u239E","\u239C","\u239F","\u239D","\u23A0"],bmatrix:["\u23A1","\u23A4","\u23A2","\u23A5","\u23A3","\u23A6"],Bmatrix:["\u23A7","\u23AB","\u23A8","\u23AC","\u23A9","\u23AD"],vmatrix:["\u2502","\u2502","\u2502","\u2502","\u2502","\u2502"],Vmatrix:["\u2551","\u2551","\u2551","\u2551","\u2551","\u2551"]}[environment];if(!delimiter)return this.supported=!1,rows.join(`
545
+ `);lines=rows.map((row,index2)=>{let left=index2===0?delimiter[0]:index2===rows.length-1?delimiter[4]:delimiter[2],right=index2===0?delimiter[1]:index2===rows.length-1?delimiter[5]:delimiter[3];return`${left} ${row} ${right}`})}if(lines.length<=1)return lines[0]??"";let index=this.layoutNodes.push({type:"matrix",lines,baseline:0})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}renderNested(source,stackFractions=!0){let rendered=new _LatexParser(source,this.layoutNodes,this.display&&
546
+ stackFractions).render();return rendered===void 0?(this.supported=!1,source):rendered}};function renderLatex(source,options={}){let layoutNodes=[],rendered=new LatexParser(source,layoutNodes,options.display===!0).render();if(rendered===void 0)return;if(layoutNodes.length===0)return rendered.replaceAll(PROTECTED_SPACE," ");let lines=renderLayout(rendered,layoutNodes).lines,indentation=Math.min(...lines.filter(line=>line.trim()).map(line=>line.length-line.trimStart().length));return lines.map(line=>line.
547
+ slice(indentation).trimEnd()).join(`
548
+ `).trimEnd().replaceAll(PROTECTED_SPACE," ")}var STRICT_STRIKETHROUGH_REGEX=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,SETEXT_UNDERLINE=/ {0,3}(?:=+|-+)[ \t]*(?:\n|$)/y,BLANK_LINE=/[^\S\n]*\n/y,SETEXT_LOOKAHEAD_LINES=64,setextGuard=!0;function mayStartSetextHeading(src){let lineBreak=src.indexOf(`
549
+ `);for(let lines=0;lineBreak!==-1;lines++){if(lines===SETEXT_LOOKAHEAD_LINES||(SETEXT_UNDERLINE.lastIndex=lineBreak+1,SETEXT_UNDERLINE.test(src)))return!0;if(BLANK_LINE.lastIndex=lineBreak+1,BLANK_LINE.test(src))return!1;lineBreak=src.indexOf(`
550
+ `,lineBreak+1)}return!1}var MarkdownTokenizer=class extends _{lheading(src){return!setextGuard||mayStartSetextHeading(src)?super.lheading(src):void 0}url(src){let token=super.url(src);if(!token)return;let punctuationIndex=token.raw.search(cjkPunctuationRegex);return punctuationIndex<0?token:super.url(token.raw.slice(0,punctuationIndex))}del(src){let match=STRICT_STRIKETHROUGH_REGEX.exec(src);if(!match)return;let text=match[2];return{type:"del",raw:match[0],text,tokens:this.lexer.inlineTokens(text)}}};
551
+ function isEscaped(source,index){let backslashes=0;for(let position=index-1;position>=0&&source[position]==="\\";position--)backslashes++;return backslashes%2===1}function findClosingDelimiter(source,closing,start){let index=source.indexOf(closing,start);for(;index>=0&&isEscaped(source,index);)index=source.indexOf(closing,index+closing.length);return index}function looksLikePendingDollarMath(source){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(source)}function tokenizeInlineLatex(source){
552
+ let opening="",closing="";if(source.startsWith("$$"))opening="$$",closing="$$";else if(source.startsWith("\\("))opening="\\(",closing="\\)";else if(source.startsWith("\\["))opening="\\[",closing="\\]";else if(source.startsWith("$")&&!/^\$\s/.test(source))opening="$",closing="$";else return;let closingIndex=findClosingDelimiter(source,closing,opening.length);if(closingIndex>=0&&opening==="$"&&(/\s$/.test(source.slice(opening.length,closingIndex))||/^\d/.test(source.slice(closingIndex+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.
553
+ test(source.slice(opening.length,closingIndex))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(source.slice(closingIndex+1))||source.slice(opening.length,closingIndex).includes("`")))return;if(closingIndex<0){let pendingSource=source.slice(opening.length);return opening.startsWith("\\")||looksLikePendingDollarMath(pendingSource)?{type:"latex",raw:source,text:pendingSource,pending:!0}:void 0}let text=source.slice(opening.length,closingIndex);return!text||text.includes(`
554
+ `)?void 0:{type:"latex",raw:source.slice(0,closingIndex+closing.length),text}}var TABLE_DELIMITER_ROW_REGEX=/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;function containsTableStart(source){let lines=source.split(`
555
+ `);for(let index=0;index<lines.length-1;index++){let delimiterRow=lines[index+1];if((delimiterRow.includes("|")||lines[index].includes("|"))&&TABLE_DELIMITER_ROW_REGEX.test(delimiterRow))return!0}return!1}function tokenizeBlockLatex(source){let dollarMatch=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source);if(dollarMatch?.[1]&&!containsTableStart(dollarMatch[1]))return{type:"latexBlock",raw:dollarMatch[0],text:dollarMatch[1].trim()};let bracketMatch=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.
556
+ exec(source);if(bracketMatch?.[1]&&!containsTableStart(bracketMatch[1]))return{type:"latexBlock",raw:bracketMatch[0],text:bracketMatch[1].trim()};let pendingBracket=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(source);if(pendingBracket?.[1]&&!containsTableStart(pendingBracket[1]))return{type:"latexBlock",raw:pendingBracket[0],text:pendingBracket[1],pending:!0};let pendingDollar=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(source);if(pendingDollar?.[1]&&looksLikePendingDollarMath(pendingDollar[1])&&!containsTableStart(
557
+ pendingDollar[1]))return{type:"latexBlock",raw:pendingDollar[0],text:pendingDollar[1],pending:!0}}var LATEX_MARKDOWN_EXTENSIONS=[{name:"latexBlock",level:"block",start(source){let match=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source);return match?match.index+(match[0].startsWith(`
558
+ `)?1:0):void 0},tokenizer:tokenizeBlockLatex},{name:"latex",level:"inline",start(source){let indices=[source.indexOf("$"),source.indexOf("\\("),source.indexOf("\\[")].filter(index=>index>=0);return indices.length>0?Math.min(...indices):void 0},tokenizer:tokenizeInlineLatex}];function trimPartialClosingFences(tokens){let token=tokens[tokens.length-1];if(token?.type==="list"){trimPartialClosingFences(token.items[token.items.length-1]?.tokens??[]);return}if(token?.type==="blockquote"){trimPartialClosingFences(
559
+ token.tokens??[]);return}if(token?.type!=="code")return;let marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1],lastLine=token.raw.slice(token.raw.lastIndexOf(`
560
+ `)+1);!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}var HTML_COMMENT_REGEX=/<!--[\s\S]*?(?:-->|$)/g;function stripHtmlComments(html){return html.replace(HTML_COMMENT_REGEX,"")}function withoutInlineHtmlComments(source,tokens){let result="",cursor=0;for(let token of tokens){let start=source.indexOf(token.raw,cursor);result+=source.slice(cursor,start),result+=token.type==="html"?
561
+ stripHtmlComments(token.raw):"tokens"in token&&token.tokens?.length?withoutInlineHtmlComments(token.raw,token.tokens):token.raw,cursor=start+token.raw.length}return result+source.slice(cursor)}var commentBlockViews=new WeakMap;function withoutHtmlCommentBlocks(tokens){let known=commentBlockViews.get(tokens);if(known)return known;let from=lexedFrom.get(tokens),rawPrevious=from?.tokens.deref(),previous=rawPrevious?commentBlockViews.get(rawPrevious):void 0,first=from&&previous&&previous===rawPrevious?
562
+ from.shared:0,view;for(let i=tokens.length-1;i>=first;i--){let token=tokens[i];token.type!=="html"||stripHtmlComments(token.raw).trim()!==""||(view??=Object.assign(tokens.slice(),{links:tokens.links}),view.splice(i,1),view[i]?.type==="space"&&(i===0||view[i-1]?.type==="space")?view.splice(i,1):i===view.length&&view[i-1]?.type==="space"&&view.splice(--i,1))}if(view&&previous){let shared=0;for(;shared<view.length&&shared<previous.length&&view[shared]===previous[shared];)shared++;lexedFrom.set(view,
563
+ {tokens:new WeakRef(previous),shared})}return commentBlockViews.set(tokens,view??tokens),view??tokens}var markdownParser;function getMarkdownParser(){return markdownParser||(markdownParser=new Y,markdownParser.setOptions({tokenizer:new MarkdownTokenizer}),markdownParser.use({tokenizer:{emStrong:markedCjkFriendly().tokenizer?.emStrong},extensions:[...LATEX_MARKDOWN_EXTENSIONS]})),markdownParser}var lexedInlines=new Map,nextLexedInlines=new Map;function inlineFlags(state){return(state.inLink?1:0)|
564
+ (state.inRawBlock?2:0)|(state.linkEmitted?4:0)}var InlineMemoLexer=class extends O{inlineDepth=0;lex(src){try{return super.lex(src)}finally{lexedInlines=nextLexedInlines,nextLexedInlines=new Map}}inlineTokens(src,tokens=[]){if(this.inlineDepth>0||tokens.length>0||src.includes("[")&&Object.keys(this.tokens.links??{}).length>0){this.inlineDepth++;try{return super.inlineTokens(src,tokens)}finally{this.inlineDepth--}}let state=this.state,flags=inlineFlags(state),next=nextLexedInlines.get(flags);next===
565
+ void 0&&(next=new Map,nextLexedInlines.set(flags,next));let lexed=next.get(src)??lexedInlines.get(flags)?.get(src);if(lexed===void 0){this.inlineDepth++;try{super.inlineTokens(src,tokens)}finally{this.inlineDepth--}lexed={tokens:tokens.slice(),inLink:state.inLink,inRawBlock:state.inRawBlock,linkEmitted:state.linkEmitted}}else{for(let token of lexed.tokens)tokens.push(token);state.inLink=lexed.inLink,state.inRawBlock=lexed.inRawBlock,state.linkEmitted=lexed.linkEmitted}return next.set(src,lexed),
566
+ tokens}},memos=!0;function lexTokens(source){return memos&&markdownCaching?new InlineMemoLexer(getMarkdownParser().defaults).lex(source):getMarkdownParser().lexer(source)}var lastLexed,lastEnd,lexedMarkdown=[],LEXED_MARKDOWN_KEPT=8,lexedFrom=new WeakMap;function hasLinkDefinitions(tokens){let links=tokens.links;return links!==void 0&&Object.keys(links).length>0}function ownString(text){return JSON.parse(JSON.stringify(text))}function sameTokens(a,b){if(a===b)return!0;if(typeof a!="object"||typeof b!=
567
+ "object"||a===null||b===null)return!1;if(Array.isArray(a)){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!sameTokens(a[i],b[i]))return!1;return!0}if(Array.isArray(b))return!1;let aFields=a,bFields=b,keys=Object.keys(aFields);if(keys.length!==Object.keys(bFields).length)return!1;for(let key of keys)if(!Object.hasOwn(bFields,key)||!sameTokens(aFields[key],bFields[key]))return!1;return!0}var fastPaths=!0,SELF_STARTING_BLOCKS=new Set(["code","heading","hr","list","\
568
+ blockquote","table","html"]);function lastBlockSettlesOneBefore(tokens,before,last){if(!fastPaths||before<0||!SELF_STARTING_BLOCKS.has(tokens[before].type))return!1;let raw=tokens[last].raw,text=raw.search(/\S/);return text>=0&&raw.includes(`
569
+ `,text)}function lexAddedMarkdown(previous,source,added){let last=previous.tokens.length,lastBlock=-1;for(let blocks=0;blocks<2;blocks++){for(last--;last>=0&&previous.tokens[last].type==="space";)last--;blocks===1&&lastBlock>=0&&lastBlockSettlesOneBefore(previous.tokens,last,lastBlock)&&(last=lastBlock),blocks===0&&(lastBlock=last)}if(last<=0)return;let offset=previous.source.length;for(let i=last;i<previous.tokens.length;i++)offset-=previous.tokens[i].raw.length;let kept=previous.end,end=ownString(
570
+ added!==void 0&&kept!==void 0&&offset>=kept.start?kept.text.slice(offset-kept.start)+added:source.slice(offset));lastEnd={start:offset,text:end};let lexedEnd=lexTokens(end);if(hasLinkDefinitions(lexedEnd))return;let tokens=previous.tokens.slice(0,last),length=offset,shared=last;for(let i=0;i<lexedEnd.length;i++){let token=lexedEnd[i],before=previous.tokens[last+i];fastPaths&&shared===last+i&&i<lexedEnd.length-1&&before!==void 0&&before.raw===token.raw&&sameTokens(before,token)&&(token=before,shared++),
571
+ tokens.push(token),length+=token.raw.length}if(length===source.length)return lexedFrom.set(tokens,{tokens:new WeakRef(previous.tokens),shared}),tokens}function lexMarkdown(source,complete=!0,extended){if(lastLexed=void 0,lastEnd=void 0,!markdownCaching){let tokens2=getMarkdownParser().lexer(source);return trimPartialClosingFences(tokens2),tokens2}let known=extended!==void 0&&lexedMarkdown.includes(extended.from)?extended.from:void 0,previous=-1;for(let i=lexedMarkdown.length-1;i>=0;i--){let entry=lexedMarkdown[i];
572
+ if(!(!complete&&known&&entry!==known&&entry.source.length===source.length&&lexedFrom.get(entry.tokens)?.tokens.deref()!==known.tokens)){if(entry.source.length===source.length&&entry!==known&&entry.source===source){if(lexedMarkdown.splice(i,1),complete&&entry.pieced)break;return lexedMarkdown.push(entry),lastLexed=entry,entry.tokens}!complete&&entry.resumable&&source.length>entry.source.length&&(previous<0||entry.source.length>lexedMarkdown[previous].source.length)&&(entry===known||startsWithText(
573
+ source,entry.source))&&(previous=i)}}let tokens=previous>=0?lexAddedMarkdown(lexedMarkdown[previous],source,lexedMarkdown[previous]===known?extended?.added:void 0):void 0,pieced=tokens!==void 0,resumable=pieced;if(!tokens){tokens=lexTokens(source),complete&&(lexedInlines=new Map);let length=0;for(let token of tokens)length+=token.raw.length;resumable=!hasLinkDefinitions(tokens)&&length===source.length}return trimPartialClosingFences(tokens),previous>=0&&lexedMarkdown.splice(previous,1),lastLexed=
574
+ {source,tokens,resumable,pieced,...pieced&&lastEnd!==void 0?{end:lastEnd}:{}},lexedMarkdown.push(lastLexed),lexedMarkdown.length>LEXED_MARKDOWN_KEPT&&lexedMarkdown.shift(),tokens}var textsWithoutTabs=[],TEXTS_WITHOUT_TABS_KEPT=4;function replaceTabs(text,grown,tabs){let none=()=>{};if(tabs===!1||tabs===void 0&&!text.includes(" "))return{text,remember:none};if(!markdownCaching)return{text:text.replace(/\t/g," "),remember:none};let replaced,extended,grownFrom=-1;if(grown!==void 0)for(let i=textsWithoutTabs.
575
+ length-1;i>=0&&grownFrom<0;i--)textsWithoutTabs[i].text===grown.from&&(grownFrom=i);for(let i=textsWithoutTabs.length-1;i>=0&&replaced===void 0;i--){let entry=textsWithoutTabs[i];if(grownFrom>=0?i===grownFrom:startsWithText(text,entry.text)){if(text.length===entry.text.length)replaced=entry.replaced;else{let added=ownString(grownFrom>=0&&grown!==void 0?grown.added:text.slice(entry.text.length)).replace(/\t/g," ");replaced=entry.replaced+added,entry.lexed!==void 0&&(extended={from:entry.lexed,added})}
576
+ textsWithoutTabs.splice(i,1)}}replaced??=text.replace(/\t/g," ");let kept={text,replaced};return textsWithoutTabs.push(kept),textsWithoutTabs.length>TEXTS_WITHOUT_TABS_KEPT&&textsWithoutTabs.shift(),{text:replaced,...extended===void 0?{}:{extended},remember:lexed=>{kept.lexed=lexed}}}function sameSettings(a,b){return a===b||a.generation===b.generation&&a.width===b.width&&a.paddingX===b.paddingX&&a.theme===b.theme&&a.color===b.color&&a.bgColor===b.bgColor&&a.bold===b.bold&&a.italic===b.italic&&
577
+ a.strikethrough===b.strikethrough&&a.underline===b.underline&&a.preserveOrderedListMarkers===b.preserveOrderedListMarkers&&a.preserveBackslashEscapes===b.preserveBackslashEscapes&&a.renderLatex===b.renderLatex&&a.renderCodeBlock===b.renderCodeBlock&&a.codeSources===b.codeSources&&a.codeBlockRevision===b.codeBlockRevision&&a.capabilities===b.capabilities}var renderedBlocks=new WeakMap,memoHolders=[],MEMO_HOLDERS_KEPT=16,renderedTokens=new WeakMap,markdownCaching=!0;var codeBlockRegions=new WeakMap;function appendRenderedLines(target,source){let regions=codeBlockRegions.get(source);if(regions){let shifted=regions.map(region=>({...region,y:region.y+target.length}));codeBlockRegions.set(target,[...codeBlockRegions.get(target)??[],...shifted])}for(let line of source)target.push(line)}function normalizeCodeInput(source,previous){let grows=previous!==void 0&&startsWithText(source,previous.source),start=grows?previous.source.length+(previous.source.endsWith("\r")&&
578
+ source[previous.source.length]===`
579
+ `?1:0):0,tail=source.slice(start).replace(/\r\n|\r/g,`
580
+ `).replace(/\t/g," "),added=grows?ownString(tail):tail,input={source,text:grows?previous.text+added:added},from=grows?previous.lexed?.deref():void 0;return{input,...from?{extended:{from,added}}:{}}}function codeSourceTail(tokens,shared,source){if(shared===0)return source;let length=0;for(let index=shared;index<tokens.length;index++)length+=tokens[index].raw.length;let start=source.length;for(;length>0&&start>0;)start--,length-=source[start]===" "?3:1,source[start]===`
581
+ `&&source[start-1]==="\r"&&start--;return ownString(source.slice(start))}function normalizedCodeSource(source){if(!/\t|\r\n/.test(source))return{text:source.replace(/\r/g,`
582
+ `)};let offsets=[];for(let original=0;original<source.length;original++){for(let count=source[original]===" "?3:1;count>0;count--)offsets.push(original);source[original]==="\r"&&source[original+1]===`
583
+ `&&original++}return offsets.push(source.length),{text:source.replace(/\r\n|\r/g,`
584
+ `).replace(/\t/g," "),offsets}}function stripCodeContainerPrefixes(source,prefixes){let{text,offsets}=normalizedCodeSource(source),result="",cursor=0;for(let match of text.matchAll(prefixes)){let end=match.index+match[0].length,remaining=0;if(offsets&&offsets[end]===offsets[end-1])for(;offsets[end+remaining]===offsets[end];)remaining++;result+=source.slice(cursor,offsets?.[match.index]??match.index)+" ".repeat(remaining),cursor=offsets?.[end+remaining]??end+remaining}return result+source.slice(
585
+ cursor)}function fencedCodeTokens(tokens){let blocks=[];for(let token of tokens)if(token.type==="code"&&token.codeBlockStyle!=="indented")blocks.push(token);else if(token.type==="blockquote")blocks.push(...fencedCodeTokens(token.tokens??[]));else if(token.type==="list")for(let item of token.items)blocks.push(...fencedCodeTokens(item.tokens));return blocks}function fencedCodeContents(raw){let opening=/^ {0,3}(`{3,}|~{3,})[^\r\n]*(?:\r\n|\n|\r|$)/.exec(raw);if(!opening)return;let body=raw.slice(opening[0].
586
+ length),fence=opening[1],closing=new RegExp(`^ {0,3}${fence[0]}{${fence.length},}[ \\t]*(?:\\r\\n|\\n|\\r|$)`,"m").exec(body);return{text:closing?body.slice(0,closing.index):body,fence}}var Markdown=class{text;rawText;sanitized;grown;facts;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;codeComponents=new WeakMap;codeSources=new WeakMap;lastRenderWidth=80;codeSourceText;codeOriginalText;codeSourceTransformed=!1;codeSourceTokens;codeInput;originalCodeInput;originalCodeSources=new WeakMap;codeOriginalSources=new WeakMap;codeBlockRevision=0;cachedText;cachedWidth;cachedLines;cachedTokens;blocks;blockHighlightedCode;wraps;nextWraps;paddedLines=new Map;nextPaddedLines=new Map;paddingGeneration=-1;paddingBackground;live={
587
+ array:new LiveLineArray,ends:[],substituted:!1};constructor(text,paddingX,paddingY,theme,defaultTextStyle,options){this.text=sanitizeTerminalText(text),options?.renderCodeBlock&&(this.rawText=text),this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme,this.defaultTextStyle=defaultTextStyle,this.options=options?{...options}:{}}setText(text){this.options.renderCodeBlock&&(this.rawText=text);let before=this.text;this.sanitized=sanitizeTerminalTextFrom(text,this.sanitized),this.text=this.sanitized.
588
+ text;let added=this.sanitized.added;this.grown!==void 0&&(added===void 0?this.grown=void 0:this.grown.added+=added);let facts=this.facts;this.facts=facts!==void 0&&added!==void 0&&facts.text===before?{text:this.text,visible:facts.visible||/\S/.test(added),tabs:facts.tabs||added.includes(" ")}:void 0,this.clearRenderCache()}invalidate(){this.clearRenderCache(),this.blocks=void 0,this.defaultStylePrefix=void 0,invalidateRenderedMarkdown()}clearRenderCache(){this.cachedText=void 0,this.cachedWidth=
589
+ void 0,this.cachedLines=void 0,reportRenderChange(this)}renderSettings(width){let style=this.defaultTextStyle;return{generation:renderedMarkdownGeneration(),width,paddingX:this.options.renderCodeBlock?Math.min(this.paddingX,Math.max(0,Math.floor((width-1)/2))):this.paddingX,theme:this.theme,color:style?.color,bgColor:style?.bgColor,bold:style?.bold,italic:style?.italic,strikethrough:style?.strikethrough,underline:style?.underline,preserveOrderedListMarkers:this.options.preserveOrderedListMarkers,
590
+ preserveBackslashEscapes:this.options.preserveBackslashEscapes,renderLatex:this.options.renderLatex,capabilities:getCapabilities(),renderCodeBlock:this.options.renderCodeBlock,codeSources:this.options.renderCodeBlock?this.codeSources:void 0,codeBlockRevision:this.codeBlockRevision}}wrapLine(line,width){if(!markdownCaching||!memos)return wrapTextWithAnsi(line,width);this.nextWraps??=new Map;let next=this.nextWraps.get(width);next===void 0&&(next=new Map,this.nextWraps.set(width,next));let wrapped=next.
591
+ get(line)??this.wraps?.get(width)?.get(line)??wrapTextWithAnsi(line,width);return next.set(line,wrapped),wrapped}renderBlock(token,nextTokenType,settings,contentWidth,reused){let shared=reused&&!codeBlockRegions.has(reused.lines)&&sameTokens(reused.token,token)?reused:void 0,known=markdownCaching?shared??renderedBlocks.get(token)?.deref():void 0;if(known&&known.nextTokenType===nextTokenType&&sameSettings(known.settings,settings))return renderedBlocks.set(token,new WeakRef(known)),known.lines;let highlightedCode=known?.
592
+ settings.generation===settings.generation&&known.settings.theme===settings.theme?known.highlightedCode:new Map;this.blockHighlightedCode=markdownCaching?highlightedCode:void 0;let width=settings.width,leftMargin=" ".repeat(settings.paddingX),rightMargin=" ".repeat(settings.paddingX),bgFn=this.defaultTextStyle?.bgColor;(this.paddingGeneration!==settings.generation||this.paddingBackground!==bgFn)&&(this.paddedLines.clear(),this.nextPaddedLines.clear(),this.paddingGeneration=settings.generation,this.
593
+ paddingBackground=bgFn);let previousPadding=this.paddedLines.get(width),nextPadding=this.nextPaddedLines.get(width)??new Map;this.nextPaddedLines.set(width,nextPadding);let lines=[],add=line=>{if(isImageLine(line)){lines.push(line);return}let lineWithMargins=leftMargin+line+rightMargin,padded=markdownCaching&&memos?nextPadding.get(lineWithMargins)??previousPadding?.get(lineWithMargins):void 0;if(padded===void 0){if(bgFn)padded=applyBackgroundToLine(lineWithMargins,width,bgFn);else{let visibleLen=visibleWidth(
594
+ lineWithMargins),paddingNeeded=Math.max(0,width-visibleLen);padded=lineWithMargins+" ".repeat(paddingNeeded)}line.length<=INTERNED_LINE_LENGTH&&(padded=internLine(padded))}markdownCaching&&memos&&nextPadding.set(lineWithMargins,padded),lines.push(padded)},rendered=this.renderToken(token,contentWidth,nextTokenType),regions=codeBlockRegions.get(rendered),shifted=[];for(let index=0;index<rendered.length;index++){let line=rendered[index];for(let region of regions??[])region.y===index&&shifted.push({
595
+ ...region,x:region.x+settings.paddingX,y:lines.length});if(isImageLine(line))add(line);else for(let wrappedLine of this.wrapLine(line,contentWidth))add(wrappedLine)}return this.blockHighlightedCode=void 0,flattenLines(lines),shifted.length&&codeBlockRegions.set(lines,shifted),markdownCaching&&renderedBlocks.set(token,new WeakRef({token,settings,nextTokenType,lines,highlightedCode})),lines}renderTokens(tokens,settings,contentWidth){let known=renderedTokens.get(tokens);if(known&&sameSettings(known.
596
+ settings,settings))return known.lines;let lines=[],ends=[],reused=0,from=lexedFrom.get(tokens),fromTokens=from?.tokens.deref(),fromRendered=fromTokens?renderedTokens.get(fromTokens):void 0;from&&fromTokens&&fromRendered&&sameSettings(fromRendered.settings,settings)&&(reused=from.shared,reused>0&&tokens[reused]?.type!==fromTokens[reused]?.type&&reused--,reused>0&&(lines=fromRendered.lines.slice(0,fromRendered.ends[reused-1]),ends=fromRendered.ends.slice(0,reused)));let reuseBlocks=!hasLinkDefinitions(
597
+ tokens),previousBlocks=this.blocks?.deref(),blocks=new Map;this.blocks=new WeakRef(blocks);for(let i=reused;i<tokens.length;i++){let token=tokens[i],block=reuseBlocks?blocks.get(token.raw)??previousBlocks?.get(token.raw):void 0;for(let line of this.renderBlock(token,tokens[i+1]?.type,settings,contentWidth,block))lines.push(line);let rendered=renderedBlocks.get(token)?.deref();reuseBlocks&&rendered&&blocks.set(token.raw,rendered),ends.push(lines.length)}return renderedTokens.set(tokens,{settings,
598
+ lines,ends}),lines}tokensFor(width){let padding=this.options.renderCodeBlock?Math.min(this.paddingX,Math.max(0,Math.floor((width-1)/2))):this.paddingX,contentWidth=Math.max(1,width-padding*2),text=this.options.transform?.(this.text,contentWidth)??this.text,transformed=text!==this.text,facts=transformed?void 0:this.textFacts();if(!text||!(facts?.visible??/\S/.test(text)))return;let grown=!transformed&&this.grown?.added?this.grown:void 0,native=this.options.renderCodeBlock?normalizeCodeInput(text,
599
+ this.codeInput):void 0,normalized=native?{text:native.input.text,extended:native.extended,remember:lexed=>{lexed&&(native.input.lexed=new WeakRef(lexed))}}:replaceTabs(text,grown,facts?.tabs),normalizedText=normalized.text,cached=this.cachedTokens?.deref(),tokens=cached?.source.length===normalizedText.length&&cached.source===normalizedText?cached.tokens:void 0;if(!tokens){let asIs=normalizedText===this.text,extended=normalized.extended??(asIs&&grown?.lexed!==void 0?{from:grown.lexed,added:grown.
600
+ added}:void 0);tokens=lexMarkdown(normalizedText,this.options.complete,extended);let lexed=lastLexed?.tokens===tokens?lastLexed:void 0;normalized.remember(lexed),this.grown=transformed?void 0:{from:this.text,added:"",...asIs&&lexed!==void 0?{lexed}:{}},this.cachedTokens=new WeakRef({source:normalizedText,tokens})}native&&(tokens===cached?.tokens&&(native.input.lexed=this.codeInput?.lexed),this.codeInput=native.input);let originalText=this.rawText??this.text;if(this.options.renderCodeBlock&&(tokens!==
601
+ cached?.tokens||this.codeSourceText!==text||this.codeOriginalText!==originalText)){let previousTokens=this.codeSourceTokens?.deref(),from=lexedFrom.get(tokens),appended=!transformed&&!this.codeSourceTransformed&&this.codeSourceText!==void 0&&this.codeOriginalText!==void 0&&startsWithText(text,this.codeSourceText)&&startsWithText(originalText,this.codeOriginalText),shared=appended&&previousTokens&&from?.tokens.deref()===previousTokens?from.shared:0,changed=shared>0?tokens.slice(shared):tokens,renderedBlocks2=fencedCodeTokens(
602
+ changed),previousBlocks=fencedCodeTokens(previousTokens?.slice(shared)??[]),growingBlock=fencedCodeTokens(previousTokens?.slice(-1)??[]).at(-1);renderedBlocks2.length>0&&this.rememberCodeSources(changed,codeSourceTail(tokens,shared,text));let originals=renderedBlocks2;if(text!==originalText){let normalized2=normalizeCodeInput(originalText,this.originalCodeInput),previous=this.originalCodeInput?.lexed?.deref()?.tokens,originalTokens=lexMarkdown(normalized2.input.text,this.options.complete,normalized2.
603
+ extended);lastLexed?.tokens===originalTokens&&(normalized2.input.lexed=new WeakRef(lastLexed)),this.originalCodeInput=normalized2.input;let originalFrom=lexedFrom.get(originalTokens),originalShared=shared>0&&previous&&originalFrom?.tokens.deref()===previous?originalFrom.shared:0,changedOriginals=originalShared>0?originalTokens.slice(originalShared):originalTokens;originals=fencedCodeTokens(changedOriginals),originals.length>0&&this.rememberCodeSources(changedOriginals,codeSourceTail(originalTokens,
604
+ originalShared,originalText),this.originalCodeSources)}let sourceMap=originals===renderedBlocks2?this.codeSources:this.originalCodeSources,used=new Set,matched=new Map;for(let block of renderedBlocks2){let candidates=originals===renderedBlocks2?[block]:originals.filter(candidate=>!used.has(candidate)&&sanitizeTerminalText(candidate.lang??"")===(block.lang??"")&&sanitizeTerminalText(candidate.text)===block.text),original=candidates[0];original&&candidates.every(candidate=>sourceMap.get(candidate)===
605
+ sourceMap.get(original))&&(used.add(original),matched.set(block,original))}let unmatched=originals.filter(original=>!used.has(original));for(let[index,block]of renderedBlocks2.entries()){let original=matched.get(block)??(unmatched.length===1&&originals.length===renderedBlocks2.length&&unmatched[0]?.lang===block.lang?unmatched[0]:void 0),source=appended&&block!==growingBlock&&this.codeOriginalSources.has(block)?this.codeOriginalSources.get(block):original?sourceMap.get(original):void 0,previous=previousBlocks[index];
606
+ if((this.codeOriginalSources.has(block)&&this.codeOriginalSources.get(block)!==source||previous?.raw===block.raw&&(this.codeOriginalSources.get(previous)!==source||this.codeSources.get(previous)!==this.codeSources.get(block)))&&(this.codeComponents.delete(block),this.codeBlockRevision++),!this.codeComponents.has(block)&&previous&&this.codeOriginalSources.get(previous)===source&&this.codeSources.get(previous)===this.codeSources.get(block)&&sameTokens(previous,block)){let component=this.codeComponents.
607
+ get(previous);component&&this.codeComponents.set(block,component)}this.codeOriginalSources.set(block,source)}this.codeSourceText=text,this.codeOriginalText=originalText,this.codeSourceTransformed=transformed,this.codeSourceTokens=new WeakRef(tokens)}return{tokens:withoutHtmlCommentBlocks(tokens),contentWidth}}rememberCodeSources(tokens,source,sources=this.codeSources){let{text:normalized,offsets}=normalizedCodeSource(source),cursor=0;for(let token of tokens){let start=normalized.indexOf(token.raw,
608
+ cursor),raw=start<0?token.raw:source.slice(offsets?.[start]??start,offsets?.[start+token.raw.length]??start+token.raw.length);if(start>=0&&(cursor=start+token.raw.length),token.type==="code")sources===this.codeSources&&sources.has(token)&&sources.get(token)!==raw&&(this.codeComponents.delete(token),this.codeBlockRevision++),start>=0?sources.set(token,raw):sources.delete(token);else if(token.type==="blockquote")this.rememberCodeSources(token.tokens??[],stripCodeContainerPrefixes(raw,/^ {0,3}> ?/gm),
609
+ sources);else if(token.type==="list"){let listSource=normalizedCodeSource(raw),itemCursor=0;for(let item of token.items){let marker=/^( {0,3}(?:[-+*]|\d+[.)])[ \t]+)/.exec(item.raw)?.[0]??"",itemStart=listSource.text.indexOf(item.raw,itemCursor),itemSource=itemStart<0?item.raw:raw.slice(listSource.offsets?.[itemStart]??itemStart,listSource.offsets?.[itemStart+item.raw.length]??itemStart+item.raw.length);itemStart>=0&&(itemCursor=itemStart+item.raw.length);let unindented=stripCodeContainerPrefixes(
610
+ itemSource,new RegExp(`^ {0,3}(?:[-+*]|\\d+[.)]) +|(?<=\\n) {1,${Math.max(1,marker.length)}}`,"g"));this.rememberCodeSources(item.tokens,unindented,sources)}}}}codeComponent(token){if(!this.options.renderCodeBlock||token.codeBlockStyle==="indented")return;let component=this.codeComponents.get(token);if(component)return component;let raw=this.codeSources.get(token)??token.raw,contents=fencedCodeContents(raw);if(!contents)return;let{text,fence}=contents,original=fencedCodeContents(this.codeOriginalSources.
611
+ get(token)??raw),lastLine=text.slice(text.lastIndexOf(`
612
+ `)+1),partialFence=this.options.complete===!1&&lastLine.length>0&&lastLine.length<fence.length&&lastLine===fence[0].repeat(lastLine.length),originalText=ownString(original?.text??text),displayText=partialFence?text.slice(0,-lastLine.length):text;return component=this.options.renderCodeBlock({wrapLine:(line,width)=>this.wrapLine(line,width),text:originalText,language:token.lang,displayText:displayText===originalText?void 0:ownString(displayText),copyUnavailable:this.codeOriginalSources.get(token)===
613
+ void 0}),this.codeComponents.set(token,component),component}getCodeBlockComponents(){let prepared=this.tokensFor(this.lastRenderWidth);return prepared?fencedCodeTokens(prepared.tokens).flatMap(token=>{let component=this.codeComponent(token);return component?[component]:[]}):[]}handleMouse(event){if(!this.options.renderCodeBlock)return;let prepared=this.tokensFor(event.width);if(!prepared)return;let settings=this.renderSettings(event.width),y2=this.paddingY;for(let index=0;index<prepared.tokens.length;index++){
614
+ let lines=this.renderBlock(prepared.tokens[index],prepared.tokens[index+1]?.type,settings,prepared.contentWidth);for(let region of codeBlockRegions.get(lines)??[]){let localY=event.y-y2-region.y,localX=event.x-region.x;if(localX>=0&&localX<region.width&&localY>=0&&localY<region.height)return dispatchMouseEvent(region.component,{...event,x:localX,y:localY,width:region.width,height:region.height})}y2+=lines.length}}textFacts(){let text=this.text,facts=this.facts;return facts?.text!==text&&(facts={
615
+ text,visible:/\S/.test(text),tabs:text.includes(" ")},this.facts=facts),facts}paddingLines(width){let bgFn=this.defaultTextStyle?.bgColor,emptyLine=" ".repeat(width),emptyLines=[];for(let i=0;i<this.paddingY;i++){let line=bgFn?applyBackgroundToLine(emptyLine,width,bgFn):emptyLine;emptyLines.push(internLine(line))}return flattenLines(emptyLines),emptyLines}keepWraps(){for(let[width,lines]of this.nextPaddedLines)this.paddedLines.delete(width),this.paddedLines.set(width,lines);for(;this.paddedLines.
616
+ size>2;)this.paddedLines.delete(this.paddedLines.keys().next().value);this.nextPaddedLines=new Map,this.nextWraps!==void 0&&this.nextWraps.size>0&&(this.wraps=this.nextWraps,this.nextWraps=void 0);let holders=memoHolders;if(holders[holders.length-1]===this)return;let index=holders.lastIndexOf(this);index!==-1&&holders.splice(index,1),holders.push(this),holders.length>MEMO_HOLDERS_KEPT&&holders.shift().dropMemos()}dropMemos(){this.wraps=void 0,this.paddedLines.clear(),this.nextPaddedLines.clear(),
617
+ this.options.complete!==!1&&(this.live.tokens=void 0,this.live.settings=void 0,this.grown=void 0)}render(width){if(this.lastRenderWidth=width,this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===width)return this.cachedLines;let rendered=this.cachedText===this.text&&this.cachedWidth===width,prepared=this.tokensFor(width);if(!prepared){this.blocks=void 0;let result2=[];return this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result2,result2}let{tokens,contentWidth}=prepared,
618
+ settings=this.renderSettings(width),contentLines;if(markdownCaching)contentLines=this.renderTokens(tokens,settings,contentWidth);else{contentLines=[];for(let i=0;i<tokens.length;i++)for(let line of this.renderBlock(tokens[i],tokens[i+1]?.type,settings,contentWidth))contentLines.push(line)}let emptyLines=this.paddingLines(width),result=emptyLines.concat(contentLines,emptyLines);return this.keepWraps(),this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=result,result.length>0||rendered?
619
+ result:(reportRenderChange(this),[""])}renderLive(width){this.lastRenderWidth=width;let live=this.live,lines=live.array,rendered=this.cachedText===this.text&&this.cachedWidth===width;if(rendered&&live.text===this.text&&live.width===width)return live.substituted&&(lines.edit(0),live.substituted=!1),lines;let prepared=this.tokensFor(width);if(live.text=this.text,live.width=width,this.cachedText=this.text,this.cachedWidth=width,this.cachedLines=void 0,!prepared)return this.blocks=void 0,lines.lines.
620
+ length>0&&lines.edit(0),live.tokens=void 0,live.settings=void 0,live.substituted=!1,lines;let{tokens,contentWidth}=prepared,settings=this.renderSettings(width),before=live.tokens,sameContent=markdownCaching&&before!==void 0&&!live.substituted&&live.settings!==void 0&&sameSettings(live.settings,settings);if(!(sameContent&&before===tokens)){let reused=0,from=sameContent?lexedFrom.get(tokens):void 0;from&&before!==void 0&&from.tokens.deref()===before&&(reused=from.shared,reused>0&&tokens[reused]?.type!==
621
+ before[reused]?.type&&reused--);let padding=this.paddingLines(width),ends=live.ends;if(reused>0)lines.edit(padding.length+ends[reused-1]),ends.length=reused;else{lines.edit(0),ends.length=0;for(let line of padding)lines.lines.push(line)}let contentLength=reused>0?ends[reused-1]:0,reuseBlocks=!hasLinkDefinitions(tokens),previousBlocks=this.blocks?.deref(),blocks=new Map;this.blocks=new WeakRef(blocks);for(let i=reused;i<tokens.length;i++){let token=tokens[i],block=reuseBlocks?blocks.get(token.raw)??
622
+ previousBlocks?.get(token.raw):void 0,blockLines=this.renderBlock(token,tokens[i+1]?.type,settings,contentWidth,block),rendered2=renderedBlocks.get(token)?.deref();reuseBlocks&&rendered2&&blocks.set(token.raw,rendered2);for(let line of blockLines)lines.lines.push(line);contentLength+=blockLines.length,ends.push(contentLength)}for(let line of padding)lines.lines.push(line);this.keepWraps()}return live.tokens=tokens,live.settings=settings,live.substituted=!1,lines.lines.length===0&&!rendered&&(lines.
623
+ edit(0),lines.lines.push(""),live.substituted=!0,reportRenderChange(this)),lines}applyDefaultStyle(text){if(!this.defaultTextStyle)return text;let styled=text;return this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.theme.underline(
624
+ styled)),styled}getDefaultStylePrefix(){if(!this.defaultTextStyle)return"";if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let sentinel="\0",styled=sentinel;this.defaultTextStyle.color&&(styled=this.defaultTextStyle.color(styled)),this.defaultTextStyle.bold&&(styled=this.theme.bold(styled)),this.defaultTextStyle.italic&&(styled=this.theme.italic(styled)),this.defaultTextStyle.strikethrough&&(styled=this.theme.strikethrough(styled)),this.defaultTextStyle.underline&&(styled=this.
625
+ theme.underline(styled));let sentinelIndex=styled.indexOf(sentinel);return this.defaultStylePrefix=sentinelIndex>=0?styled.slice(0,sentinelIndex):"",this.defaultStylePrefix}getStylePrefix(styleFn){let styled=styleFn("\0"),sentinelIndex=styled.indexOf("\0");return sentinelIndex>=0?styled.slice(0,sentinelIndex):""}getDefaultInlineStyleContext(){return{applyText:text=>this.applyDefaultStyle(text),stylePrefix:this.getDefaultStylePrefix()}}renderToken(token,width,nextTokenType,styleContext){let lines=[];
626
+ switch(token.type){case"heading":{let headingLevel=token.depth,headingPrefix=`${"#".repeat(headingLevel)} `,headingStyleFn;headingLevel===1?headingStyleFn=text=>this.theme.heading(this.theme.bold(this.theme.underline(text))):headingStyleFn=text=>this.theme.heading(this.theme.bold(text));let headingStyleContext={applyText:headingStyleFn,stylePrefix:this.getStylePrefix(headingStyleFn)},headingText=this.renderInlineTokens(token.tokens||[],headingStyleContext),styledHeading=headingLevel>=3?headingStyleFn(
627
+ headingPrefix)+headingText:headingText;lines.push(styledHeading),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"paragraph":{let paragraphText=this.renderInlineTokens(token.tokens||[],styleContext);lines.push(paragraphText),nextTokenType&&nextTokenType!=="list"&&nextTokenType!=="space"&&lines.push("");break}case"text":lines.push(this.renderInlineTokens([token],styleContext));break;case"latexBlock":{let latexToken=token,rendered=!latexToken.pending&&this.options.renderLatex!==!1?
628
+ renderLatex(latexToken.text,{display:!0}):void 0;(rendered===void 0||rendered.split(`
629
+ `).some(line=>visibleWidth(line)>width))&&(rendered=latexToken.raw.trim());for(let line of rendered.split(`
630
+ `))lines.push(this.applyDefaultStyle(line));nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"code":{let component=this.codeComponent(token);if(component){let rendered=component.render(width);codeBlockRegions.set(lines,[{component,x:0,y:0,width,height:rendered.length}]),appendRenderedLines(lines,rendered),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}let indent=this.theme.codeBlockIndent??" ";if(lines.push(this.theme.codeBlockBorder(`\`\`\`${token.lang||""}`)),this.
631
+ theme.highlightCode){let key=`${token.lang??""}\0${token.text}`,highlighted=this.blockHighlightedCode?.get(key);highlighted||(highlighted=this.theme.highlightCode(token.text,token.lang),this.blockHighlightedCode?.set(key,highlighted));for(let hlLine of highlighted)lines.push(`${indent}${hlLine}`)}else{let codeLines=token.text.split(`
632
+ `);for(let codeLine of codeLines)lines.push(`${indent}${this.theme.codeBlock(codeLine)}`)}lines.push(this.theme.codeBlockBorder("```")),nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"list":{let listLines=this.renderList(token,0,width,styleContext);appendRenderedLines(lines,listLines);break}case"table":{let tableLines=this.renderTable(token,width,nextTokenType,styleContext);lines.push(...tableLines);break}case"blockquote":{let quoteStyle=text=>this.theme.quote(this.theme.italic(
633
+ text)),quoteStylePrefix=this.getStylePrefix(quoteStyle),applyQuoteStyle=line=>{if(!quoteStylePrefix)return quoteStyle(line);let lineWithReappliedStyle=line.replace(/\x1b\[0m/g,`\x1B[0m${quoteStylePrefix}`);return quoteStyle(lineWithReappliedStyle)};if(width<3){let quoteTokens2=withoutHtmlCommentBlocks(token.tokens||[]);for(let i=0;i<quoteTokens2.length;i++)appendRenderedLines(lines,this.renderToken(quoteTokens2[i],width,quoteTokens2[i+1]?.type,styleContext));break}let quoteContentWidth=width-2,quoteInlineStyleContext={
634
+ applyText:text=>text,stylePrefix:quoteStylePrefix},quoteTokens=withoutHtmlCommentBlocks(token.tokens||[]),renderedQuoteLines=[];for(let i=0;i<quoteTokens.length;i++){let quoteToken=quoteTokens[i],nextQuoteToken=quoteTokens[i+1];appendRenderedLines(renderedQuoteLines,this.renderToken(quoteToken,quoteContentWidth,nextQuoteToken?.type,quoteInlineStyleContext))}for(;renderedQuoteLines.length>0&&renderedQuoteLines[renderedQuoteLines.length-1]==="";)renderedQuoteLines.pop();let quoteRegions=codeBlockRegions.
635
+ get(renderedQuoteLines),shiftedRegions=[];for(let index=0;index<renderedQuoteLines.length;index++){let quoteLine=renderedQuoteLines[index];for(let region of quoteRegions??[])region.y===index&&shiftedRegions.push({...region,x:region.x+2,y:lines.length});let styledLine=applyQuoteStyle(quoteLine),wrappedLines=this.wrapLine(styledLine,quoteContentWidth);for(let wrappedLine of wrappedLines)lines.push(this.theme.quoteBorder("\u2502 ")+wrappedLine)}shiftedRegions.length&&codeBlockRegions.set(lines,shiftedRegions),
636
+ nextTokenType&&nextTokenType!=="space"&&lines.push("");break}case"hr":lines.push(this.theme.hr("\u2500".repeat(Math.min(width,80)))),nextTokenType&&nextTokenType!=="space"&&lines.push("");break;case"html":if("raw"in token&&typeof token.raw=="string"){let visible=stripHtmlComments(token.raw).trim();visible&&lines.push(this.applyDefaultStyle(visible))}break;case"space":lines.push("");break;default:"text"in token&&typeof token.text=="string"&&lines.push(token.text)}return lines}renderInlineTokens(tokens,styleContext){
637
+ let result="",resolvedStyleContext=styleContext??this.getDefaultInlineStyleContext(),{applyText,stylePrefix}=resolvedStyleContext,applyTextWithNewlines=text=>text.split(`
638
+ `).map(segment=>applyText(segment)).join(`
639
+ `),dropLeadingSpace=!1;for(let i=0;i<tokens.length;i++){let token=tokens[i];switch(dropLeadingSpace&&token.type==="text"&&!token.tokens?.length&&/^[ \t]/.test(token.text)&&(token={...token,text:token.text.replace(/^[ \t]+/,"")}),dropLeadingSpace=!1,token.type){case"latex":{let latexToken=token,rendered=!latexToken.pending&&this.options.renderLatex!==!1?renderLatex(latexToken.text)??latexToken.raw:latexToken.raw;result+=applyTextWithNewlines(rendered);break}case"escape":result+=applyTextWithNewlines(
640
+ this.options.preserveBackslashEscapes?token.raw:token.text);break;case"text":token.tokens&&token.tokens.length>0?result+=this.renderInlineTokens(token.tokens,resolvedStyleContext):result+=applyTextWithNewlines(token.text);break;case"paragraph":result+=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);break;case"strong":{let boldContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.bold(boldContent)+stylePrefix;break}case"em":{let italicContent=this.
641
+ renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.italic(italicContent)+stylePrefix;break}case"codespan":result+=this.theme.code(token.text)+stylePrefix;break;case"link":{let linkText=this.renderInlineTokens(token.tokens||[],resolvedStyleContext),styledLink=this.theme.link(this.theme.underline(linkText));if(getCapabilities().hyperlinks)result+=(isWebLink(token.href)?hyperlink(styledLink,token.href):styledLink)+stylePrefix;else{let hrefForComparison=token.href.startsWith(
642
+ "mailto:")?token.href.slice(7):token.href;token.text===token.href||token.text===hrefForComparison?result+=styledLink+stylePrefix:result+=styledLink+this.theme.linkUrl(` (${token.href})`)+stylePrefix}break}case"br":result+=`
643
+ `;break;case"del":{let delContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.strikethrough(delContent)+stylePrefix;break}case"html":token.raw.startsWith("<!--")?dropLeadingSpace=i===0||/[ \t]$/.test(tokens[i-1].raw):result+=applyTextWithNewlines(token.raw);break;default:"text"in token&&typeof token.text=="string"&&(result+=applyTextWithNewlines(token.text))}}for(;stylePrefix&&result.endsWith(stylePrefix);)result=result.slice(0,-stylePrefix.length);return result}getOrderedListMarker(item){
644
+ let match=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(item.raw);return match?`${match[1]} `:void 0}getUnorderedListMarker(item){let match=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(item.raw);return match?`${match[1]} `:void 0}renderList(token,depth,width,styleContext){let lines=[],indent=" ".repeat(depth),startNumber=typeof token.start=="number"?token.start:1;for(let i=0;i<token.items.length;i++){let item=token.items[i],isLastItem=i===token.items.length-1,bullet=token.ordered?this.options.preserveOrderedListMarkers?
645
+ this.getOrderedListMarker(item)??`${startNumber+i}. `:`${startNumber+i}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(item)??"- ":"- ",taskMarker=item.task?`[${item.checked?"x":" "}] `:"",marker=bullet+taskMarker,firstPrefix=indent+this.theme.listBullet(marker),continuationPrefix=indent+" ".repeat(visibleWidth(marker)),itemWidth=Math.max(1,width-visibleWidth(firstPrefix)),renderedAnyLine=!1;for(let itemToken of withoutHtmlCommentBlocks(item.tokens)){if(itemToken.type==="\
646
+ list"){appendRenderedLines(lines,this.renderList(itemToken,depth+1,width,styleContext)),renderedAnyLine=!0;continue}let itemLines=this.renderToken(itemToken,itemWidth,void 0,styleContext),itemRegions=codeBlockRegions.get(itemLines);itemRegions&&codeBlockRegions.set(lines,[...codeBlockRegions.get(lines)??[],...itemRegions.map(region=>({...region,x:region.x+visibleWidth(continuationPrefix),y:region.y+lines.length}))]);for(let line of itemLines)for(let wrappedLine of this.wrapLine(line,itemWidth)){
647
+ let linePrefix=renderedAnyLine?continuationPrefix:firstPrefix;lines.push(linePrefix+wrappedLine),renderedAnyLine=!0}}renderedAnyLine||lines.push(firstPrefix),token.loose&&!isLastItem&&lines.push("")}return lines}getLongestWordWidth(text,maxWidth){let words=text.split(/\s+/).filter(word=>word.length>0),longest=0;for(let word of words)longest=Math.max(longest,visibleWidth(word));return maxWidth===void 0?longest:Math.min(longest,maxWidth)}wrapCellText(text,maxWidth,stylePrefix=""){let lines=wrapTextWithAnsi(
648
+ text,Math.max(1,maxWidth));return lines.map((line,index)=>{let styleReset=index<lines.length-1?"\x1B[22;23;24;25;27;28;29;39m":"";return`${line}${styleReset}${stylePrefix}`})}renderTable(token,availableWidth,nextTokenType,styleContext){let lines=[],numCols=token.header.length;if(numCols===0)return lines;let borderOverhead=3*numCols+1,availableForCells=availableWidth-borderOverhead;if(availableForCells<numCols){let source=token.raw.includes("<!--")?withoutInlineHtmlComments(token.raw,new O(getMarkdownParser().
649
+ defaults).inlineTokens(token.raw)):token.raw,fallbackLines=source?wrapTextWithAnsi(source,availableWidth):[];return nextTokenType&&nextTokenType!=="space"&&fallbackLines.push(""),fallbackLines}let maxUnbrokenWordWidth=30,naturalWidths=[],minWordWidths=[];for(let i=0;i<numCols;i++){let headerText=this.renderInlineTokens(token.header[i].tokens||[],styleContext);naturalWidths[i]=visibleWidth(headerText),minWordWidths[i]=Math.max(1,this.getLongestWordWidth(headerText,maxUnbrokenWordWidth))}for(let row of token.
650
+ rows)for(let i=0;i<row.length;i++){let cellText=this.renderInlineTokens(row[i].tokens||[],styleContext);naturalWidths[i]=Math.max(naturalWidths[i]||0,visibleWidth(cellText)),minWordWidths[i]=Math.max(minWordWidths[i]||1,this.getLongestWordWidth(cellText,maxUnbrokenWordWidth))}let minColumnWidths=minWordWidths,minCellsWidth=minColumnWidths.reduce((a,b)=>a+b,0);if(minCellsWidth>availableForCells){minColumnWidths=new Array(numCols).fill(1);let remaining=availableForCells-numCols;if(remaining>0){let totalWeight=minWordWidths.
651
+ reduce((total,width)=>total+Math.max(0,width-1),0),growth=minWordWidths.map(width=>{let weight=Math.max(0,width-1);return totalWeight>0?Math.floor(weight/totalWeight*remaining):0});for(let i=0;i<numCols;i++)minColumnWidths[i]+=growth[i]??0;let allocated=growth.reduce((total,width)=>total+width,0),leftover=remaining-allocated;for(let i=0;leftover>0&&i<numCols;i++)minColumnWidths[i]++,leftover--}minCellsWidth=minColumnWidths.reduce((a,b)=>a+b,0)}let totalNaturalWidth=naturalWidths.reduce((a,b)=>a+
652
+ b,0)+borderOverhead,columnWidths;if(totalNaturalWidth<=availableWidth)columnWidths=naturalWidths.map((width,index)=>Math.max(width,minColumnWidths[index]));else{let totalGrowPotential=naturalWidths.reduce((total,width,index)=>total+Math.max(0,width-minColumnWidths[index]),0),extraWidth=Math.max(0,availableForCells-minCellsWidth);columnWidths=minColumnWidths.map((minWidth,index)=>{let naturalWidth=naturalWidths[index],minWidthDelta=Math.max(0,naturalWidth-minWidth),grow=0;return totalGrowPotential>
653
+ 0&&(grow=Math.floor(minWidthDelta/totalGrowPotential*extraWidth)),minWidth+grow});let allocated=columnWidths.reduce((a,b)=>a+b,0),remaining=availableForCells-allocated;for(;remaining>0;){let grew=!1;for(let i=0;i<numCols&&remaining>0;i++)columnWidths[i]<naturalWidths[i]&&(columnWidths[i]++,remaining--,grew=!0);if(!grew)break}}let topBorderCells=columnWidths.map(w2=>"\u2500".repeat(w2));lines.push(`\u250C\u2500${topBorderCells.join("\u2500\u252C\u2500")}\u2500\u2510`);let headerCellLines=token.header.
654
+ map((cell,i)=>{let text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix)}),headerLineCount=Math.max(...headerCellLines.map(c=>c.length));for(let lineIdx=0;lineIdx<headerLineCount;lineIdx++){let rowParts=headerCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"",padded=text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)));return this.theme.bold(padded)});lines.push(`\u2502 ${rowParts.join(" \
655
+ \u2502 ")} \u2502`)}let separatorLine=`\u251C\u2500${columnWidths.map(w2=>"\u2500".repeat(w2)).join("\u2500\u253C\u2500")}\u2500\u2524`;lines.push(separatorLine);for(let rowIndex=0;rowIndex<token.rows.length;rowIndex++){let rowCellLines=token.rows[rowIndex].map((cell,i)=>{let text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix)}),rowLineCount=Math.max(...rowCellLines.map(c=>c.length));for(let lineIdx=0;lineIdx<rowLineCount;lineIdx++){
656
+ let rowParts=rowCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"";return text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)))});lines.push(`\u2502 ${rowParts.join(" \u2502 ")} \u2502`)}rowIndex<token.rows.length-1&&lines.push(separatorLine)}let bottomBorderCells=columnWidths.map(w2=>"\u2500".repeat(w2));return lines.push(`\u2514\u2500${bottomBorderCells.join("\u2500\u2534\u2500")}\u2500\u2518`),nextTokenType&&nextTokenType!=="space"&&lines.push(""),lines}};markStableRender(
657
+ Markdown);markReportsChanges(Markdown);markLiveRender(Markdown.prototype.render,function(width){return this.renderLive(width)});var Spacer=class{lines;renderedLines=[];renderedCount=0;constructor(lines=1){this.lines=lines}setLines(lines){this.lines=lines,reportRenderChange(this)}invalidate(){}render(_width){if(this.renderedCount!==this.lines){let result=[];for(let i=0;i<this.lines;i++)result.push("");this.renderedLines=result,this.renderedCount=this.lines}return this.renderedLines}};markStableRender(Spacer);markReportsChanges(Spacer);var TruncatedText=class{text;paddingX;paddingY;constructor(text,paddingX=0,paddingY=0){this.text=text,this.paddingX=paddingX,this.paddingY=paddingY}invalidate(){}render(width){let result=[],emptyLine=" ".repeat(width);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);let availableWidth=Math.max(1,width-this.paddingX*2),singleLineText=this.text,newlineIndex=this.text.indexOf(`
658
+ `);newlineIndex!==-1&&(singleLineText=this.text.substring(0,newlineIndex));let displayText=truncateToWidth(singleLineText,availableWidth),leftPadding=" ".repeat(this.paddingX),rightPadding=" ".repeat(this.paddingX),lineWithPadding=leftPadding+displayText+rightPadding,lineVisibleWidth=visibleWidth(lineWithPadding),paddingNeeded=Math.max(0,width-lineVisibleWidth),finalLine=lineWithPadding+" ".repeat(paddingNeeded);result.push(finalLine);for(let i=0;i<this.paddingY;i++)result.push(emptyLine);return result}};import*as fs from"node:fs";import*as path2 from"node:path";import{createRequire as createRequire2}from"node:module";import*as path from"node:path";import{createRequire}from"node:module";import{dirname as dirname2,join as join2}from"node:path";import{fileURLToPath}from"node:url";var moduleRequire=createRequire(import.meta.url),TUI_PACKAGE_NAME="@earendil-works/pi-tui";function getNativeModuleCandidates(nativePath,options={}){let moduleDir=dirname2(fileURLToPath(options.moduleUrl??import.meta.url)),candidates=[];try{let packageEntry=(options.resolvePackage??moduleRequire.resolve)(TUI_PACKAGE_NAME);candidates.push(join2(dirname2(packageEntry),
659
+ "..",nativePath))}catch{}return candidates.push(join2(moduleDir,"..",nativePath),join2(moduleDir,nativePath),join2(dirname2(options.execPath??process.execPath),nativePath)),Array.from(new Set(candidates))}var cjsRequire=createRequire2(import.meta.url),helpers=new Map;function loadNativePlatformHelper(platform,suffix=""){let arch=process.arch;if(arch!=="x64"&&arch!=="arm64")return;let nativePath=path.join("native",platform,"prebuilds",`${platform}-${arch}`,`${platform}-platform${suffix}.node`);if(helpers.has(nativePath))return helpers.get(nativePath);for(let modulePath of getNativeModuleCandidates(nativePath))try{let helper=cjsRequire(modulePath);if(typeof helper?.getText=="function"&&typeof helper.
660
+ getImage=="function")return helpers.set(nativePath,helper),helper}catch{}helpers.set(nativePath,void 0)}function getNativePlatformHelper(){if(!(process.platform!=="darwin"&&process.platform!=="win32"))return loadNativePlatformHelper(process.platform)}function getNativeClipboard(){if(process.platform!=="linux")return getNativePlatformHelper();if(process.env.DISPLAY)return loadNativePlatformHelper("linux","-x11")}function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}var PROGRAM_STATUS_QUERY="\x1B]7501;?\x1B\\";function isProgramStatusReply(sequence){return/^\x1b\]7501;\?[^\x07\x1b]*(?:\x07|\x1b\\)$/.test(sequence)}var APP_PATTERN=/^[A-Za-z0-9_.+-]{1,32}$/,MAX_MESSAGE_BYTES=2048;function truncateUtf8(text,maxBytes){if(Buffer.byteLength(text,"utf8")<=maxBytes)return text;let bytes=0,end=0;for(let char of text){let size=Buffer.byteLength(char,"utf8");if(bytes+size>maxBytes)break;bytes+=size,end+=char.length}return text.slice(0,end)}function formatProgramStatus(status){
661
+ let pairs=[`state=${status.state}`];status.app!==void 0&&APP_PATTERN.test(status.app)&&pairs.push(`app=${status.app}`),status.state==="blocked"&&status.kind&&pairs.push(`kind=${status.kind}`);let message=truncateUtf8(replaceControlCharacters(status.message??"").trim(),MAX_MESSAGE_BYTES);return message&&pairs.push(`msg=${Buffer.from(message,"utf8").toString("base64")}`),`\x1B]7501;${pairs.join(":")}\x1B\\`}import{EventEmitter}from"events";var ESC="\x1B",DEFAULT_SEQUENCE_TIMEOUT_MS=50,DEFAULT_ESCAPE_TIMEOUT_MS=10,BRACKETED_PASTE_START="\x1B[200~",BRACKETED_PASTE_END="\x1B[201~",TERMINAL_REPLY_HEADER_PATTERN=/^\x1b(?:\](?:1[01];|4;\d{1,3};|7501;\?)|P>\||_G(?:[a-z]=\d+,)*[a-z]=\d+;)/;function isControlString(data){return data.startsWith(`${ESC}]`)||data.startsWith(`${ESC}P`)||data.startsWith(`${ESC}_`)}function isCompleteSequence(data){if(!data.startsWith(ESC))return"not-escape";if(data.length===1)return"\
662
+ incomplete";let afterEsc=data.slice(1);return afterEsc.startsWith("[")?afterEsc.startsWith("[M")?data.length>=6?"complete":"incomplete":isCompleteCsiSequence(data):afterEsc.startsWith("]")?isCompleteOscSequence(data):afterEsc.startsWith("P")?isCompleteDcsSequence(data):afterEsc.startsWith("_")?isCompleteApcSequence(data):afterEsc.startsWith("O")?afterEsc.length>=2?"complete":"incomplete":(afterEsc.length===1,"complete")}function isCompleteCsiSequence(data){if(!data.startsWith(`${ESC}[`))return"c\
663
+ omplete";if(data.length<3)return"incomplete";let payload=data.slice(2),lastChar=payload[payload.length-1],lastCharCode=lastChar.charCodeAt(0);if(lastCharCode>=64&&lastCharCode<=126){if(payload.startsWith("<")){if(/^<\d+;\d+;\d+[Mm]$/.test(payload))return"complete";if(lastChar==="M"||lastChar==="m"){let parts=payload.slice(1,-1).split(";");if(parts.length===3&&parts.every(p=>/^\d+$/.test(p)))return"complete"}return"incomplete"}return"complete"}return"incomplete"}function isCompleteOscSequence(data){
664
+ return!data.startsWith(`${ESC}]`)||data.endsWith(`${ESC}\\`)||data.endsWith("\x07")?"complete":"incomplete"}function isCompleteDcsSequence(data){return!data.startsWith(`${ESC}P`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function isCompleteApcSequence(data){return!data.startsWith(`${ESC}_`)||data.endsWith(`${ESC}\\`)?"complete":"incomplete"}function parseUnmodifiedKittyPrintableCodepoint(sequence){let match=sequence.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!match)return;let codepoint=parseInt(
665
+ match[1],10);return codepoint>=32?codepoint:void 0}function extractCompleteSequences(buffer){let sequences=[],pos=0;for(;pos<buffer.length;){let remaining=buffer.slice(pos);if(remaining.startsWith(ESC)){let terminalReply=isControlString(remaining)&&TERMINAL_REPLY_HEADER_PATTERN.test(remaining),seqEnd=1;for(;seqEnd<=remaining.length;){if(terminalReply&&seqEnd>2){let char=remaining[seqEnd-1];if(char===""||char===""){pos+=seqEnd;break}if(char===ESC&&seqEnd<remaining.length&&remaining[seqEnd]!=="\\"){
666
+ pos+=seqEnd-1;break}}let candidate=remaining.slice(0,seqEnd),status=isCompleteSequence(candidate);if(status==="complete"){if(candidate==="\x1B\x1B"){let nextChar=remaining[seqEnd];if(nextChar==="["||nextChar==="]"||nextChar==="O"||nextChar==="P"||nextChar==="_"){sequences.push(ESC),pos+=1;break}}sequences.push(candidate),pos+=seqEnd;break}else if(status==="incomplete")seqEnd++;else{sequences.push(candidate),pos+=seqEnd;break}}if(seqEnd>remaining.length)return{sequences,remainder:remaining}}else sequences.
667
+ push(remaining[0]),pos++}return{sequences,remainder:""}}var StdinBuffer=class extends EventEmitter{buffer="";timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer="";pendingKittyPrintableCodepoint;constructor(options={}){super(),this.timeoutMs=options.timeout??DEFAULT_SEQUENCE_TIMEOUT_MS,this.escapeTimeoutMs=options.escapeTimeout??DEFAULT_ESCAPE_TIMEOUT_MS}process(data){this.timeout&&(clearTimeout(this.timeout),this.timeout=null);let str;if(Buffer.isBuffer(data))if(data.length===1&&data[0]>
668
+ 127){let byte=data[0]-128;str=`\x1B${String.fromCharCode(byte)}`}else str=data.toString();else str=data;if(str.length===0&&this.buffer.length===0){this.emitDataSequence("");return}if(this.buffer+=str,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.
669
+ pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let startIndex=this.buffer.indexOf(BRACKETED_PASTE_START);if(startIndex!==-1){if(startIndex>0){let beforePaste=this.buffer.slice(0,startIndex),result2=extractCompleteSequences(beforePaste);for(let sequence of result2.sequences)this.emitDataSequence(sequence)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(startIndex+BRACKETED_PASTE_START.length),this.
670
+ pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer="";let endIndex=this.pasteBuffer.indexOf(BRACKETED_PASTE_END);if(endIndex!==-1){let pastedContent=this.pasteBuffer.slice(0,endIndex),remaining=this.pasteBuffer.slice(endIndex+BRACKETED_PASTE_END.length);this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0,this.emit("paste",pastedContent),remaining.length>0&&this.process(remaining)}return}let result=extractCompleteSequences(this.buffer);this.buffer=result.remainder;
671
+ for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buffer.length>0){if(TERMINAL_REPLY_HEADER_PATTERN.test(this.buffer))return;let timeoutMs=this.buffer===ESC?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let flushed=this.flush();for(let sequence of flushed)sequence.length>2&&isControlString(sequence)?(this.emitDataSequence(sequence.slice(0,2)),this.process(sequence.slice(2))):this.emitDataSequence(sequence)},timeoutMs)}}emitDataSequence(sequence){let rawCodepoint=sequence.
672
+ length===1?sequence.codePointAt(0):void 0;if(rawCodepoint!==void 0&&rawCodepoint===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=parseUnmodifiedKittyPrintableCodepoint(sequence),this.emit("data",sequence)}flush(){if(this.timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer.length===0)return[];let sequences=[this.buffer];return this.buffer="",this.pendingKittyPrintableCodepoint=void 0,sequences}clear(){this.
673
+ timeout&&(clearTimeout(this.timeout),this.timeout=null),this.buffer="",this.pasteMode=!1,this.pasteBuffer="",this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};var TERMINAL_PROGRESS_KEEPALIVE_MS=1e3,TERMINAL_PROGRESS_ACTIVE_SEQUENCE="\x1B]9;4;3\x07",TERMINAL_PROGRESS_CLEAR_SEQUENCE="\x1B]9;4;0\x07",NATIVE_SHIFT_ENTER_SEQUENCE="\x1B[13;2u",DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS=7,KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS=150,KITTY_KEYBOARD_PROTOCOL_QUERY=`\x1B[>${DESIRED_KITTY_KEYBOARD_PROTOCOL_FLAGS}u\x1B[?u`,DEVICE_ATTRIBUTES_QUERY="\x1B[c";function parseKeyboardProtocolNegotiationSequence(sequence){let kittyFlags=sequence.match(/^\x1b\[\?(\d+)u$/);
674
+ if(kittyFlags)return{type:"kitty-flags",flags:Number.parseInt(kittyFlags[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(sequence))return{type:"device-attributes"}}function isKeyboardProtocolNegotiationSequencePrefix(sequence){return sequence==="\x1B["||/^\x1b\[\?[\d;]*$/.test(sequence)}function isAppleTerminalSession(){return process.platform==="darwin"&&process.env.TERM_PROGRAM==="Apple_Terminal"}function refreshTerminalDimensions(){if(!(process.platform==="win32"||process.pid<=0))try{process.kill(process.
675
+ pid,"SIGWINCH")}catch{}}function isNativeShiftEnterCandidate(data){return data==="\r"||data==="\x1B\r"}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&isNativeShiftEnterCandidate(data)&&isShiftPressed?NATIVE_SHIFT_ENTER_SEQUENCE:data}var DEFAULT_ESCAPE_TIMEOUT_MS2=10,DEFAULT_SSH_ESCAPE_TIMEOUT_MS=100;function resolveEscapeTimeoutMs(env=process.env){let configured=Number(env.HUMAIN_TERMINAL_TUI_ESC_TIMEOUT||env.PI_TUI_ESC_TIMEOUT);return Number.isFinite(configured)&&configured>0?configured:env.SSH_CONNECTION||env.SSH_TTY?DEFAULT_SSH_ESCAPE_TIMEOUT_MS:DEFAULT_ESCAPE_TIMEOUT_MS2}var ProcessTerminal=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer="";keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;programStatus;programStatusSupported=!1;programStatusQueryPending=!1;writeLogPath=(()=>{
676
+ let env=process.env.HUMAIN_TERMINAL_TUI_WRITE_LOG||process.env.PI_TUI_WRITE_LOG||"";if(!env)return"";try{if(fs.statSync(env).isDirectory()){let now=new Date,ts=`${now.getFullYear()}-${String(now.getMonth()+1).padStart(2,"0")}-${String(now.getDate()).padStart(2,"0")}_${String(now.getHours()).padStart(2,"0")}-${String(now.getMinutes()).padStart(2,"0")}-${String(now.getSeconds()).padStart(2,"0")}`;return path2.join(env,`tui-${ts}-${process.pid}.log`)}}catch{}return env})();get kittyProtocolActive(){
677
+ return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(onInput,onResize){this.inputHandler=onInput,this.resizeHandler=onResize,this.wasRaw=process.stdin.isRaw||!1,process.stdin.setRawMode&&process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),process.stdout.write("\x1B[?2004h"),process.stdout.on("resize",this.resizeHandler),refreshTerminalDimensions(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){
678
+ this.stdinBuffer=new StdinBuffer({escapeTimeout:resolveEscapeTimeoutMs()}),this.stdinBuffer.on("data",sequence=>{if(isProgramStatusReply(sequence)){this.programStatusQueryPending&&(this.programStatusQueryPending=!1,this.programStatusSupported=!0,this.writeProgramStatus());return}let negotiation=this.readKeyboardProtocolNegotiationSequence(sequence);if(negotiation==="pending"){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}negotiation&&this.handleKeyboardProtocolNegotiationSequence(
679
+ negotiation.parsed)||this.forwardInputSequence(negotiation?.sequence??sequence)}),this.stdinBuffer.on("paste",content=>{this.inputHandler&&this.inputHandler(`\x1B[200~${content}\x1B[201~`)}),this.stdinDataHandler=data=>{this.stdinBuffer.process(data)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on("data",this.stdinDataHandler),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer();let programStatusOverride=process.
680
+ env.HUMAIN_TERMINAL_PROGRAM_STATUS??process.env.PI_PROGRAM_STATUS;this.programStatusSupported=programStatusOverride==="1",this.programStatusQueryPending=programStatusOverride!=="1"&&programStatusOverride!=="0";let programStatusQuery=this.programStatusQueryPending?PROGRAM_STATUS_QUERY:"";process.stdout.write(`${KITTY_KEYBOARD_PROTOCOL_QUERY}${programStatusQuery}${DEVICE_ATTRIBUTES_QUERY}`),this.writeProgramStatus()}handleKeyboardProtocolNegotiationSequence(negotiationSequence){if(this.clearKeyboardProtocolNegotiationBuffer(),
681
+ negotiationSequence.type==="device-attributes"){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;this.pendingKeyboardProtocolDeviceAttributes-=1,this.pendingKeyboardProtocolDeviceAttributes===0&&(this.programStatusQueryPending=!1)}return negotiationSequence.type==="kitty-flags"?(negotiationSequence.flags!==0?(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,setKittyProtocolActive(!0))):this.enableModifyOtherKeys(),!0):(this._kittyProtocolActive||
682
+ this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(sequence){if(this.keyboardProtocolNegotiationBuffer){let bufferedSequence=this.keyboardProtocolNegotiationBuffer+sequence,negotiationSequence2=parseKeyboardProtocolNegotiationSequence(bufferedSequence);if(negotiationSequence2)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:negotiationSequence2,sequence:bufferedSequence};if(isKeyboardProtocolNegotiationSequencePrefix(bufferedSequence))return this.setKeyboardProtocolNegotiationBuffer(
683
+ bufferedSequence),"pending";this.flushKeyboardProtocolNegotiationBufferAsInput()}let negotiationSequence=parseKeyboardProtocolNegotiationSequence(sequence);if(negotiationSequence)return{parsed:negotiationSequence,sequence};if(isKeyboardProtocolNegotiationSequencePrefix(sequence))return this.setKeyboardProtocolNegotiationBuffer(sequence),"pending"}setKeyboardProtocolNegotiationBuffer(sequence){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=sequence}clearKeyboardProtocolNegotiationBuffer(){
684
+ this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=""}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let sequence=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(sequence)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(
685
+ ()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},KEYBOARD_PROTOCOL_RESPONSE_FRAGMENT_TIMEOUT_MS))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&(clearTimeout(this.keyboardProtocolBufferFlushTimer),this.keyboardProtocolBufferFlushTimer=void 0)}forwardInputSequence(sequence){if(!this.inputHandler)return;let shouldDetectNativeShiftEnter=isNativeShiftEnterCandidate(sequence)&&(isAppleTerminalSession()||
686
+ process.platform==="win32"),input=normalizeNativeShiftEnterInput(sequence,shouldDetectNativeShiftEnter,shouldDetectNativeShiftEnter&&isNativeModifierPressed("shift"));this.inputHandler(input)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write("\x1B[>4;2m"),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&(process.stdout.write("\x1B[>4;0m"),this._modifyOtherKeysActive=!1)}enableWindowsVTInput(){if(process.platform===
687
+ "win32")try{getNativePlatformHelper()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(maxMs=1e3,idleMs=50){let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys();let previousHandler=this.inputHandler;this.inputHandler=void 0;let lastDataTime=Date.
688
+ now(),onData=()=>{lastDataTime=Date.now()};process.stdin.on("data",onData);let endTime=Date.now()+maxMs;try{for(;;){let now=Date.now(),timeLeft=endTime-now;if(timeLeft<=0||now-lastDataTime>=idleMs)break;await new Promise(resolve=>setTimeout(resolve,Math.min(idleMs,timeLeft)))}}finally{process.stdin.removeListener("data",onData),this.inputHandler=previousHandler}}stop(){this.clearProgressInterval()&&process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE),this.programStatusSupported&&this.programStatus&&
689
+ process.stdout.write(formatProgramStatus({state:"clear"})),this.programStatusSupported=!1,this.programStatusQueryPending=!1,process.stdout.write("\x1B[?2004l");let shouldDisableKittyProtocol=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),shouldDisableKittyProtocol&&(process.stdout.write("\x1B[<u"),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,setKittyProtocolActive(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&(this.stdinBuffer.
690
+ destroy(),this.stdinBuffer=void 0),this.stdinDataHandler&&(process.stdin.removeListener("data",this.stdinDataHandler),this.stdinDataHandler=void 0),this.inputHandler=void 0,this.resizeHandler&&(process.stdout.removeListener("resize",this.resizeHandler),this.resizeHandler=void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw)}restoreOnExit(before,after){let sequence=before;this.progressInterval&&(sequence+=TERMINAL_PROGRESS_CLEAR_SEQUENCE),sequence+="\x1B[?2004\
691
+ l",(this.keyboardProtocolPushed||this._kittyProtocolActive)&&(sequence+="\x1B[<u"),this._modifyOtherKeysActive&&(sequence+="\x1B[>4;0m"),sequence+=after;try{fs.writeSync(process.stdout.fd,sequence)}catch{}}write(data){if(process.stdout.write(data),this.writeLogPath)try{fs.appendFileSync(this.writeLogPath,data,{encoding:"utf8"})}catch{}}get columns(){return process.stdout.columns||Number(process.env.COLUMNS)||80}get rows(){return process.stdout.rows||Number(process.env.LINES)||24}moveBy(lines){lines>
692
+ 0?process.stdout.write(`\x1B[${lines}B`):lines<0&&process.stdout.write(`\x1B[${-lines}A`)}hideCursor(){process.stdout.write("\x1B[?25l")}showCursor(){process.stdout.write("\x1B[?25h")}clearLine(){process.stdout.write("\x1B[K")}clearFromCursor(){process.stdout.write("\x1B[J")}clearScreen(){process.stdout.write("\x1B[2J\x1B[H")}setTitle(title){process.stdout.write(`\x1B]0;${replaceControlCharacters(title)}\x07`)}setProgramStatus(status){this.programStatus=status.state==="clear"?void 0:status,this.
693
+ programStatusSupported&&process.stdout.write(formatProgramStatus(status))}writeProgramStatus(){this.programStatusSupported&&this.programStatus&&process.stdout.write(formatProgramStatus(this.programStatus))}setProgress(active){active?(process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE),this.progressInterval||(this.progressInterval=setInterval(()=>{process.stdout.write(TERMINAL_PROGRESS_ACTIVE_SEQUENCE)},TERMINAL_PROGRESS_KEEPALIVE_MS))):(this.clearProgressInterval(),process.stdout.write(TERMINAL_PROGRESS_CLEAR_SEQUENCE))}clearProgressInterval(){
694
+ return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var KillRing=class{ring=[];push(text,opts){if(text)if(opts.accumulate&&this.ring.length>0){let last=this.ring.pop();this.ring.push(opts.prepend?text+last:last+text)}else this.ring.push(text)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let last=this.ring.pop();this.ring.unshift(last)}}get length(){return this.ring.length}};var UndoStack=class{stack=[];clone;constructor(clone=state=>structuredClone(state)){this.clone=clone}push(state){this.stack.push(this.clone(state))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};function findWordBackward(text,cursor,options){if(cursor<=0)return 0;let textBeforeCursor=text.slice(0,cursor),segmentFn=options?.segment,isAtomic=options?.isAtomicSegment,segments=segmentFn?[...segmentFn(textBeforeCursor)]:[...getWordSegmenter().segment(textBeforeCursor)],newCursor=cursor;for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&isWhitespaceChar(segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||0;if(segments.length===0)return newCursor;
695
+ let last=segments[segments.length-1];if(isAtomic?.(last.segment))newCursor-=last.segment.length;else if(last.isWordLike){let segment=last.segment,matches=[...segment.matchAll(new RegExp(PUNCTUATION_REGEX,"g"))];if(matches.length<=0)newCursor-=segment.length;else{let lastMatch=matches[matches.length-1];newCursor-=segment.length-(lastMatch.index+lastMatch[0].length)}}else for(;segments.length>0&&!isAtomic?.(segments[segments.length-1]?.segment||"")&&!segments[segments.length-1]?.isWordLike&&!isWhitespaceChar(
696
+ segments[segments.length-1]?.segment||"");)newCursor-=segments.pop()?.segment.length||0;return newCursor}function findWordForward(text,cursor,options){if(cursor>=text.length)return text.length;let textAfterCursor=text.slice(cursor),segmentFn=options?.segment,isAtomic=options?.isAtomicSegment,iterator=(segmentFn?segmentFn(textAfterCursor):getWordSegmenter().segment(textAfterCursor))[Symbol.iterator](),next=iterator.next(),newCursor=cursor;for(;!next.done&&!isAtomic?.(next.value.segment)&&isWhitespaceChar(
697
+ next.value.segment);)newCursor+=next.value.segment.length,next=iterator.next();if(next.done)return newCursor;if(isAtomic?.(next.value.segment))newCursor+=next.value.segment.length;else if(next.value.isWordLike)newCursor+=PUNCTUATION_REGEX.exec(next.value.segment)?.index??next.value.segment.length;else for(;!next.done&&!isAtomic?.(next.value.segment)&&!next.value.isWordLike&&!isWhitespaceChar(next.value.segment);)newCursor+=next.value.segment.length,next=iterator.next();return newCursor}var Input=class{value="";cursor=0;prompt;placeholder;placeholderStyle;mask;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer="";isInPaste=!1;killRing=new KillRing;lastAction=null;undoStack=new UndoStack;constructor(options={}){this.prompt=options.prompt??"> ",this.placeholder=options.placeholder??"",this.placeholderStyle=options.placeholderStyle??(text=>text)}getValue(){return this.value}setValue(value){this.value=value,this.cursor=Math.min(this.cursor,value.length)}setMask(mask){this.
698
+ mask=mask}reset(){this.value="",this.cursor=0,this.mask=void 0,this.pasteBuffer="",this.isInPaste=!1,this.killRing=new KillRing,this.lastAction=null,this.undoStack.clear()}handleInput(data){if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace("\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);this.handlePaste(pasteContent),this.isInPaste=
699
+ !1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining&&this.handleInput(remaining)}return}let kb=getKeybindings();if(kb.matches(data,"tui.select.cancel")){this.onEscape&&this.onEscape();return}if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(kb.matches(data,"tui.input.submit")||data===`
700
+ `){this.onSubmit&&this.onSubmit(this.value);return}if(kb.matches(data,"tui.editor.deleteCharBackward")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToLineStart();return}if(kb.matches(data,"tui.e\
701
+ ditor.deleteToLineEnd")){this.deleteToLineEnd();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.cursorLeft")){if(this.lastAction=null,this.cursor>0){let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...getGraphemeSegmenter().segment(beforeCursor)],lastGrapheme=graphemes[graphemes.length-1];this.cursor-=lastGrapheme?lastGrapheme.segment.length:1}return}if(kb.matches(data,"tui.\
702
+ editor.cursorRight")){if(this.lastAction=null,this.cursor<this.value.length){let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...getGraphemeSegmenter().segment(afterCursor)][0];this.cursor+=firstGrapheme?firstGrapheme.segment.length:1}return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.lastAction=null,this.cursor=0;return}if(kb.matches(data,"tui.editor.cursorLineEnd")){this.lastAction=null,this.cursor=this.value.length;return}if(kb.matches(data,"tui.editor.cursorWordLeft")){
703
+ this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}let kittyPrintable=decodeKittyPrintable(data);if(kittyPrintable!==void 0){this.insertCharacter(kittyPrintable);return}[...data].some(ch=>{let code=ch.charCodeAt(0);return code<32||code===127||code>=128&&code<=159})||this.insertCharacter(data)}handleMouse(event){if(event.type!=="press"||event.button!=="left"||event.y!==0)return;let visibleColumn=Math.max(0,event.x-2),targetColumn=this.
704
+ renderedStartColumn+visibleColumn,currentColumn=0;this.cursor=this.value.length;for(let grapheme of getGraphemeSegmenter().segment(this.value)){let nextColumn=currentColumn+visibleWidth(this.mask??grapheme.segment);if(targetColumn<nextColumn){this.cursor=grapheme.index;break}currentColumn=nextColumn}return this.lastAction=null,{handled:!0,focus:!0}}insertCharacter(char){(isWhitespaceChar(char)||this.lastAction!=="type-word")&&this.pushUndo(),this.lastAction="type-word",this.value=this.value.slice(
705
+ 0,this.cursor)+char+this.value.slice(this.cursor),this.cursor+=char.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...getGraphemeSegmenter().segment(beforeCursor)],lastGrapheme=graphemes[graphemes.length-1],graphemeLength=lastGrapheme?lastGrapheme.segment.length:1;this.value=this.value.slice(0,this.cursor-graphemeLength)+this.value.slice(this.cursor),this.cursor-=graphemeLength}}handleForwardDelete(){if(this.
706
+ lastAction=null,this.cursor<this.value.length){this.pushUndo();let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...getGraphemeSegmenter().segment(afterCursor)][0],graphemeLength=firstGrapheme?firstGrapheme.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+graphemeLength)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let deletedText=this.value.slice(0,this.cursor);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction===
707
+ "kill"}),this.lastAction="kill",this.value=this.value.slice(this.cursor),this.cursor=0}deleteToLineEnd(){if(this.cursor>=this.value.length)return;this.pushUndo();let deletedText=this.value.slice(this.cursor);this.killRing.push(deletedText,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let wasKill=this.lastAction==="kill";this.pushUndo();let oldCursor=this.cursor;this.moveWordBackwards();
708
+ let deleteFrom=this.cursor;this.cursor=oldCursor;let deletedText=this.value.slice(deleteFrom,this.cursor);this.killRing.push(deletedText,{prepend:!0,accumulate:wasKill}),this.lastAction="kill",this.value=this.value.slice(0,deleteFrom)+this.value.slice(this.cursor),this.cursor=deleteFrom}deleteWordForward(){if(this.cursor>=this.value.length)return;let wasKill=this.lastAction==="kill";this.pushUndo();let oldCursor=this.cursor;this.moveWordForwards();let deleteTo=this.cursor;this.cursor=oldCursor;let deletedText=this.
709
+ value.slice(this.cursor,deleteTo);this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.value=this.value.slice(0,this.cursor)+this.value.slice(deleteTo)}yank(){let text=this.killRing.peek();text&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+text+this.value.slice(this.cursor),this.cursor+=text.length,this.lastAction="yank")}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndo();let prevText=this.killRing.peek()||"";
710
+ this.value=this.value.slice(0,this.cursor-prevText.length)+this.value.slice(this.cursor),this.cursor-=prevText.length,this.killRing.rotate();let text=this.killRing.peek()||"";this.value=this.value.slice(0,this.cursor)+text+this.value.slice(this.cursor),this.cursor+=text.length,this.lastAction="yank"}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let snapshot=this.undoStack.pop();snapshot&&(this.value=snapshot.value,this.cursor=snapshot.cursor,this.lastAction=null)}moveWordBackwards(){
711
+ this.cursor!==0&&(this.lastAction=null,this.cursor=findWordBackward(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=findWordForward(this.value,this.cursor))}handlePaste(pastedText){this.lastAction=null,this.pushUndo();let cleanText=pastedText.replace(/\r\n/g,"").replace(/\r/g,"").replace(/\n/g,"").replace(/\t/g," ");this.value=this.value.slice(0,this.cursor)+cleanText+this.value.slice(this.cursor),this.cursor+=cleanText.length}invalidate(){}render(width){
712
+ let displayValue=this.mask?[...getGraphemeSegmenter().segment(this.value)].map(()=>this.mask).join(""):this.value,displayCursor=this.mask?[...getGraphemeSegmenter().segment(this.value.slice(0,this.cursor))].length*this.mask.length:this.cursor,availableWidth=width-visibleWidth(this.prompt);if(availableWidth<=0)return[truncateToWidth(this.prompt,width,"")];if(this.value.length===0&&this.placeholder){let placeholder=truncateToWidth(this.placeholder,availableWidth,""),atCursor2=[...getGraphemeSegmenter().
713
+ segment(placeholder)][0]?.segment??" ",afterCursor2=placeholder.slice(atCursor2.length),marker2=this.focused?CURSOR_MARKER:"",cursorChar2=renderFakeCursor(this.placeholderStyle(atCursor2)),textWithCursor2=marker2+cursorChar2+this.placeholderStyle(afterCursor2),padding2=" ".repeat(Math.max(0,availableWidth-visibleWidth(textWithCursor2)));return[this.prompt+textWithCursor2+padding2]}let visibleText="",cursorDisplay=displayCursor;this.renderedStartColumn=0;let totalWidth=visibleWidth(displayValue);
714
+ if(totalWidth<availableWidth)visibleText=displayValue;else{let scrollWidth=this.cursor===this.value.length?availableWidth-1:availableWidth,cursorCol=visibleWidth(displayValue.slice(0,displayCursor));if(scrollWidth>0){let halfWidth=Math.floor(scrollWidth/2),startCol=0;cursorCol<halfWidth?startCol=0:cursorCol>totalWidth-halfWidth?startCol=Math.max(0,totalWidth-scrollWidth):startCol=Math.max(0,cursorCol-halfWidth),this.renderedStartColumn=startCol,visibleText=sliceByColumn(displayValue,startCol,scrollWidth,
715
+ !0),cursorDisplay=sliceByColumn(displayValue,startCol,Math.max(0,cursorCol-startCol),!0).length}else visibleText="",cursorDisplay=0}let cursorGrapheme=[...getGraphemeSegmenter().segment(visibleText.slice(cursorDisplay))][0],beforeCursor=visibleText.slice(0,cursorDisplay),atCursor=cursorGrapheme?.segment??" ",afterCursor=visibleText.slice(cursorDisplay+atCursor.length),marker=this.focused?CURSOR_MARKER:"",cursorChar=renderFakeCursor(atCursor),textWithCursor=beforeCursor+marker+cursorChar+afterCursor,
716
+ visualLength=visibleWidth(textWithCursor),padding=" ".repeat(Math.max(0,availableWidth-visualLength));return[this.prompt+textWithCursor+padding]}};var PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines,corpus={text:"",spans:[],rowTextStarts:[],rowSpanStarts:[]},startRow=0){let textLength=corpus.rowTextStarts[startRow]??corpus.text.length,chunks=[corpus.text.slice(0,textLength)],spans=corpus.spans;spans.length=corpus.rowSpanStarts[startRow]??spans.length,corpus.rowTextStarts.length=startRow,corpus.rowSpanStarts.length=startRow;let pendingSeparator=textLength>0,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=
717
+ 1,pendingSeparator=!1)};for(let row=startRow;row<lines.length;row++){corpus.rowTextStarts.push(textLength),corpus.rowSpanStarts.push(spans.length);let line=stripTerminalSequences(lines[row]??""),column=0;if(PRINTABLE_ASCII.test(line)){let index=0;for(;index<line.length;){if(line.charCodeAt(index)===32){textLength>0&&(pendingSeparator=!0),column+=1,index+=1;continue}let end=index+1;for(;end<line.length&&line.charCodeAt(end)!==32;)end+=1;appendSeparator();let text=line.slice(index,end);chunks.push(
718
+ text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+text.length,linearColumns:!0}),textLength+=text.length,column+=text.length,index=end}}else for(let grapheme of getGraphemeSegmenter().segment(line)){let text=grapheme.segment,width=visibleWidth(text);if(/^\s+$/u.test(text)){textLength>0&&(pendingSeparator=!0),column+=width;continue}appendSeparator(),chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,
719
+ endCol:column+width,linearColumns:!1}),textLength+=text.length,column+=width}textLength>0&&(pendingSeparator=!0)}return corpus.text=chunks.join(""),corpus}function normalizeQuery(query){return query.replace(/\s+/gu," ").trim()}function escapeRegExp(text){return text.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function findSearchCorpusMatches(corpus,normalizedQuery,startRow=0,matches=[]){if(!normalizedQuery)return[];let expression=new RegExp(escapeRegExp(normalizedQuery),"giu");expression.lastIndex=corpus.
720
+ rowTextStarts[startRow]??corpus.text.length;let spanIndex=corpus.rowSpanStarts[startRow]??corpus.spans.length;for(let match of corpus.text.matchAll(expression)){let start=match.index,end=start+match[0].length;for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=start;)spanIndex+=1;let segments=[];for(let index=spanIndex;index<corpus.spans.length;index++){let span=corpus.spans[index];if(span.textStart>=end)break;if(span.textEnd<=start)continue;let startCol=span.linearColumns?span.
721
+ startCol+Math.max(start,span.textStart)-span.textStart:span.startCol,endCol=span.linearColumns?span.startCol+Math.min(end,span.textEnd)-span.textStart:span.endCol,previous=segments[segments.length-1];previous&&previous.row===span.row&&startCol<=previous.endCol?previous.endCol=Math.max(previous.endCol,endCol):segments.push({row:span.row,startCol,endCol})}for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=end;)spanIndex+=1;segments.length>0&&matches.push({segments})}return matches}
722
+ var AltScreenSearchIndex=class{sourceLines;live;revision=-1;corpus;normalizedQuery;matches=[];search(lines,query,live){let changedFrom=0;if(live)changedFrom=live===this.live?live.changedSince(this.revision):0,this.sourceLines=void 0;else{let sourceChanged2=this.sourceLines?.length!==lines.length;if(!sourceChanged2&&this.sourceLines){for(let index=0;index<lines.length;index++)if(this.sourceLines[index]!==lines[index]){sourceChanged2=!0;break}}sourceChanged2?this.sourceLines=Array.from(lines):changedFrom=
723
+ Number.POSITIVE_INFINITY}let sourceChanged=changedFrom!==Number.POSITIVE_INFINITY,startRow=0;!this.corpus||changedFrom===0?this.corpus=buildSearchCorpus(lines):sourceChanged&&(startRow=Math.min(changedFrom,this.corpus.rowTextStarts.length,lines.length),this.corpus=buildSearchCorpus(lines,this.corpus,startRow)),this.live=live,this.revision=live?.revision??-1;let normalizedQuery=normalizeQuery(query),changed=sourceChanged||normalizedQuery!==this.normalizedQuery;if(changed){if(live&&startRow>0&&normalizedQuery===
724
+ this.normalizedQuery&&normalizedQuery&&!normalizedQuery.includes(" ")){let retained=this.matches.length;for(;retained>0&&this.matches[retained-1].segments[0].row>=startRow;)retained--;this.matches=findSearchCorpusMatches(this.corpus,normalizedQuery,startRow,this.matches.slice(0,retained))}else this.matches=findSearchCorpusMatches(this.corpus,normalizedQuery);this.normalizedQuery=normalizedQuery}return{matches:this.matches,changed}}};function getAltScreenSearchMatchKey(match){let first=match.segments[0],last=match.segments[match.segments.length-1];return first&&last?`${first.row}:${first.startCol}:${last.row}:${last.endCol}`:""}var AltScreenSearchComponent=class{input=new Input({prompt:" ",placeholder:"Find in transcript",placeholderStyle:text=>`\x1B[2m${text}\x1B[22m`});onQueryChange;navigationButtonStyle;resultCount=0;resultIndex=-1;previousButtonStart=-1;previousButtonEnd=-1;nextButtonStart=-1;nextButtonEnd=-1;hoveredNavigationDirection;_focused=!1;constructor(onQueryChange,navigationButtonStyle=text=>text){
725
+ this.onQueryChange=onQueryChange,this.navigationButtonStyle=navigationButtonStyle}get focused(){return this._focused}set focused(value){this._focused=value,this.input.focused=value}setResult(index,count){this.resultIndex=index,this.resultCount=count}getNavigationDirectionAt(row,column){if(row===2){if(column>=this.previousButtonStart&&column<this.previousButtonEnd)return-1;if(column>=this.nextButtonStart&&column<this.nextButtonEnd)return 1}}setHoveredNavigationDirection(direction){return direction===
726
+ this.hoveredNavigationDirection?!1:(this.hoveredNavigationDirection=direction,!0)}handleInput(data){let previous=this.input.getValue();this.input.handleInput(data);let query=this.input.getValue();query!==previous&&this.onQueryChange(query)}invalidate(){this.input.invalidate()}render(width){let safeWidth=Math.max(1,width),innerWidth=Math.max(0,safeWidth-2),formatKey=key=>key?key.split("+").map(part=>process.platform==="darwin"&&part.toLowerCase()==="alt"?"Option":part.charAt(0).toUpperCase()+part.
727
+ slice(1)).join("+"):"Unbound",keybindings=getKeybindings(),previousKey=formatKey(keybindings.getKeys("tui.altScreen.searchPrevious")[0]),nextKey=formatKey(keybindings.getKeys("tui.altScreen.searchNext")[0]),result=this.input.getValue()?this.resultCount===0?"No matches":`${this.resultIndex+1}/${this.resultCount}`:"",resultSpace=Math.max(0,innerWidth-3),visibleResult=truncateToWidth(result,resultSpace,""),resultText=visibleResult?`\x1B[2m ${visibleResult} \x1B[22m`:"",inputWidth=Math.max(0,innerWidth-
728
+ visibleWidth(resultText)),inputLine=truncateToWidth(this.input.render(Math.max(1,inputWidth))[0]??"",inputWidth,""),inputPadding=" ".repeat(Math.max(0,inputWidth-visibleWidth(inputLine))),content=`${inputLine}${inputPadding}${resultText}`,previousButton=`\u2191 ${previousKey}`,nextButton=`\u2193 ${nextKey}`,separator=" \xB7 ",outerGapWidth=1,availableControlsWidth=Math.max(0,innerWidth-outerGapWidth*2-1),controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton);
729
+ controlsWidth>availableControlsWidth&&(previousButton="\u2191",nextButton="\u2193",separator=" ",controlsWidth=visibleWidth(previousButton)+visibleWidth(separator)+visibleWidth(nextButton));let showButtons=controlsWidth<=availableControlsWidth,renderedButtons=showButtons?this.navigationButtonStyle(previousButton,this.hoveredNavigationDirection===-1)+separator+this.navigationButtonStyle(nextButton,this.hoveredNavigationDirection===1):"",outerGapsWidth=showButtons?outerGapWidth*2:0,rightRuleWidth=renderedButtons&&
730
+ innerWidth>controlsWidth+outerGapsWidth?1:0,leftRuleWidth=Math.max(0,innerWidth-(showButtons?controlsWidth:0)-outerGapsWidth-rightRuleWidth),previousStart=1+leftRuleWidth+outerGapWidth;return this.previousButtonStart=showButtons?previousStart:-1,this.previousButtonEnd=showButtons?previousStart+visibleWidth(previousButton):-1,this.nextButtonStart=showButtons?this.previousButtonEnd+visibleWidth(separator):-1,this.nextButtonEnd=showButtons?this.nextButtonStart+visibleWidth(nextButton):-1,safeWidth===
731
+ 1?["\u250C","\u2502","\u2514"]:[`\u250C${"\u2500".repeat(innerWidth)}\u2510`,`\u2502${content}\u2502`,`\u2514${"\u2500".repeat(leftRuleWidth)}${renderedButtons?" ":""}${renderedButtons}${renderedButtons?" ":""}${"\u2500".repeat(rightRuleWidth)}\u2518`]}};var DEFAULT_DURATION_MS=1e3,AltScreenFlashContainer=class{entries=[];nextId=0;requestRender;constructor(requestRender){this.requestRender=requestRender}flash(message,durationMs=DEFAULT_DURATION_MS){let id=this.nextId++,timer=setTimeout(()=>{let index=this.entries.findIndex(entry=>entry.id===id);index!==-1&&(this.entries.splice(index,1),this.requestRender())},Math.max(0,durationMs));timer.unref(),this.entries.push({id,message,timer}),this.requestRender()}dispose(){for(let entry of this.entries)clearTimeout(
732
+ entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var LAYOUT_NODE=Symbol.for("@earendil-works/pi-tui/layout-node");function getLayoutNode(component){let layoutNode=component[LAYOUT_NODE];return typeof layoutNode=="function"?layoutNode.call(component):void 0}var ScrollView=class extends Container{child;followEnd;primary;overscroll;scrollbarTrackStyle;scrollbarThumbStyle;currentScrollbar;scrollbarHideDelayMs;currentScrollTop=0;contentHeight=0;currentViewportHeight=0;followingEnd;followSuppressedAtEnd=!1;requestRenderCallback;transientScrollbarVisible=!1;scrollbarActive=!1;scrollbarHideTimer;constructor(component,options={}){if(super(),options.axis!==void 0&&options.axis!=="vertical")throw new Error(`Unsupported ScrollView axis: ${options.axis}`);this.
733
+ child=component,this.children.push(component),this.followEnd=(options.follow??"none")==="end",this.followingEnd=this.followEnd,this.primary=options.primary??!1,this.overscroll=options.overscroll??"chain",this.currentScrollbar=options.scrollbar??"hidden",this.scrollbarTrackStyle=options.scrollbarTrackStyle??(text=>`\x1B[90m${text}\x1B[39m`),this.scrollbarThumbStyle=options.scrollbarThumbStyle??(text=>`\x1B[37m${text}\x1B[39m`),this.scrollbarHideDelayMs=Math.max(0,Math.floor(options.scrollbarHideDelayMs??
734
+ 1e3))}get scrollTop(){return this.currentScrollTop}get isFollowingEnd(){return this.followingEnd}get viewportHeight(){return this.currentViewportHeight}get scrollbar(){return this.currentScrollbar}get isScrollbarVisible(){return this.scrollbar==="always"?this.currentViewportHeight>0:this.scrollbar==="auto"&&this.contentHeight>this.currentViewportHeight&&this.transientScrollbarVisible}get isScrollbarActive(){return this.scrollbarActive}setScrollbar(scrollbar){scrollbar!==this.currentScrollbar&&(this.
735
+ currentScrollbar=scrollbar,scrollbar!=="auto"?this.hideTransientScrollbar():this.scrollbarActive&&this.markScrollbarActivity(),this.requestRenderCallback?.())}getContentWidth(width){return this.scrollbar==="always"&&width>1?width-1:width}markScrollbarActivity(){this.scrollbar!=="auto"||this.contentHeight<=this.currentViewportHeight||(this.transientScrollbarVisible=!0,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0),!this.scrollbarActive&&(this.scrollbarHideTimer=
736
+ setTimeout(()=>{this.scrollbarHideTimer=void 0,this.transientScrollbarVisible=!1,this.requestRenderCallback?.()},this.scrollbarHideDelayMs),this.scrollbarHideTimer.unref()))}hideTransientScrollbar(){this.transientScrollbarVisible=!1,this.scrollbarHideTimer&&(clearTimeout(this.scrollbarHideTimer),this.scrollbarHideTimer=void 0)}setScrollbarActive(active){active!==this.scrollbarActive&&(this.scrollbarActive=active,this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollTo(scrollTop,options={}){
737
+ let requested=Number.isFinite(scrollTop)?Math.trunc(scrollTop):this.currentScrollTop,maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight),next=Math.max(0,Math.min(maxScrollTop,requested)),nextFollowSuppressedAtEnd=options.disableFollow===!0&&next===maxScrollTop,nextFollowingEnd=!nextFollowSuppressedAtEnd&&this.followEnd&&next===maxScrollTop;if(next===this.currentScrollTop&&nextFollowingEnd===this.followingEnd&&nextFollowSuppressedAtEnd===this.followSuppressedAtEnd)return;let moved=next!==
738
+ this.currentScrollTop;this.currentScrollTop=next,this.followingEnd=nextFollowingEnd,this.followSuppressedAtEnd=nextFollowSuppressedAtEnd,moved&&this.markScrollbarActivity(),this.requestRenderCallback?.()}scrollBy(lines){let requested=Number.isFinite(lines)?Math.trunc(lines):0;if(requested===0)return 0;let maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight),start=this.followingEnd?maxScrollTop:this.currentScrollTop,next=Math.max(0,Math.min(maxScrollTop,start+requested)),moved=next-
739
+ start,wasFollowingEnd=this.followingEnd;return this.currentScrollTop=next,this.followingEnd=this.followEnd&&next===maxScrollTop,this.followSuppressedAtEnd=!1,moved!==0&&this.markScrollbarActivity(),(moved!==0||this.followingEnd!==wasFollowingEnd)&&this.requestRenderCallback?.(),requested-moved}scrollToStart(){let changed=this.currentScrollTop!==0||this.followingEnd!==(this.followEnd&&this.contentHeight<=this.currentViewportHeight);this.currentScrollTop=0,this.followingEnd=this.followEnd&&this.contentHeight<=
740
+ this.currentViewportHeight,this.followSuppressedAtEnd=!1,changed&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}scrollToEnd(){let next=Math.max(0,this.contentHeight-this.currentViewportHeight),changed=this.currentScrollTop!==next||this.followingEnd!==this.followEnd;this.currentScrollTop=next,this.followingEnd=this.followEnd,this.followSuppressedAtEnd=!1,changed&&(this.markScrollbarActivity(),this.requestRenderCallback?.())}updateLayout(contentHeight,viewportHeight,requestRender){
741
+ this.contentHeight=Math.max(0,Math.floor(contentHeight)),this.currentViewportHeight=Math.max(0,Math.floor(viewportHeight)),this.requestRenderCallback=requestRender;let maxScrollTop=Math.max(0,this.contentHeight-this.currentViewportHeight);this.followingEnd?this.currentScrollTop=maxScrollTop:this.currentScrollTop=Math.max(0,Math.min(this.currentScrollTop,maxScrollTop)),this.currentScrollTop<maxScrollTop&&(this.followSuppressedAtEnd=!1),this.followEnd&&this.currentScrollTop===maxScrollTop&&!this.followSuppressedAtEnd&&
742
+ (this.followingEnd=!0),this.contentHeight<=this.currentViewportHeight&&this.hideTransientScrollbar()}addChild(_component){throw new Error("ScrollView has exactly one child")}removeChild(_component){throw new Error("ScrollView child cannot be removed")}clear(){throw new Error("ScrollView child cannot be cleared")}render(width){let contentWidth=this.getContentWidth(width),lines=this.child.render(contentWidth);return contentWidth===width?lines:lines.map(line=>`${line} `)}[LAYOUT_NODE](){return{type:"\
743
+ scroll",component:this.child,state:this}}};function isStackEntry(child){return!("render"in child)}function normalizeSize(value,fallback){return value===void 0||!Number.isFinite(value)?fallback:Math.max(0,Math.floor(value))}var Stack=class extends Container{entries=[];gap;align;constructor(children=[],options={}){super(),this.gap=normalizeSize(options.gap,0),this.align=options.align??"stretch";for(let child of children)isStackEntry(child)?this.addChild(child.component,child):this.addChild(child)}addChild(component,options={}){super.addChild(
744
+ component),this.entries.push({component,...options.basis===void 0?{}:{basis:options.basis},...options.grow===void 0?{}:{grow:normalizeSize(options.grow,0)},...options.shrink===void 0?{}:{shrink:normalizeSize(options.shrink,1)},...options.minSize===void 0?{}:{minSize:normalizeSize(options.minSize,0)},...options.maxSize===void 0?{}:{maxSize:normalizeSize(options.maxSize,Number.MAX_SAFE_INTEGER)},...options.visible===void 0?{}:{visible:options.visible}})}removeChild(component){super.removeChild(component);
745
+ let index=this.entries.findIndex(entry=>entry.component===component);index!==-1&&this.entries.splice(index,1)}clear(){super.clear(),this.entries.length=0}[LAYOUT_NODE](){return{type:this.layoutType,entries:this.entries,gap:this.gap,align:this.align}}};function visibleStackEntries(entries,viewport){let visible=[];for(let index=0;index<entries.length;index++){let entry=entries[index];(entry.visible?.(viewport)??!0)&&visible.push(entry)}return visible}function clampSize(size,entry){let min=Math.max(
746
+ 0,Math.floor(entry.minSize??0)),max=Math.max(min,Math.floor(entry.maxSize??Number.MAX_SAFE_INTEGER));return Math.max(min,Math.min(max,Math.max(0,Math.floor(size))))}function distribute(sizes,entries,amount,mode){let remaining=amount,candidates=[];for(;remaining>0;){candidates.length=0;for(let index=0;index<entries.length;index++){let entry=entries[index];(mode==="grow"?(entry.grow??0)>0&&sizes[index]<(entry.maxSize??Number.MAX_SAFE_INTEGER):(entry.shrink??1)>0&&sizes[index]>(entry.minSize??0))&&
747
+ candidates.push(index)}if(candidates.length===0)return;let totalWeight=0;for(let i=0;i<candidates.length;i++){let index=candidates[i],entry=entries[index];totalWeight+=mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index])}let distributed=0;for(let i=0;i<candidates.length;i++){let index=candidates[i],entry=entries[index];if(remaining<=0)break;let weight=mode==="grow"?entry.grow??0:(entry.shrink??1)*Math.max(1,sizes[index]),proposed=Math.max(1,Math.floor(remaining*weight/totalWeight)),
748
+ capacity=mode==="grow"?(entry.maxSize??Number.MAX_SAFE_INTEGER)-sizes[index]:sizes[index]-(entry.minSize??0),delta=Math.min(remaining,proposed,capacity);delta<=0||(sizes[index]=sizes[index]+(mode==="grow"?delta:-delta),remaining-=delta,distributed+=delta)}if(distributed===0)return}}function allocateStackSizes(entries,intrinsicSizes,availableSize,gap){let sizes=new Array(entries.length);for(let index=0;index<entries.length;index++){let entry=entries[index];sizes[index]=clampSize(entry.basis===void 0||
749
+ entry.basis==="auto"?intrinsicSizes[index]??0:entry.basis,entry)}if(availableSize===void 0)return sizes;let contentSize=Math.max(0,Math.floor(availableSize)-Math.max(0,entries.length-1)*gap),total=0;for(let index=0;index<sizes.length;index++)total+=sizes[index];return total<contentSize?distribute(sizes,entries,contentSize-total,"grow"):total>contentSize&&distribute(sizes,entries,total-contentSize,"shrink"),sizes}var VStack=class extends Stack{layoutType="vstack";constructor(children=[],options={}){super(children,options)}render(width){let viewport={width:Math.max(1,width),height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport),rendered=entries.map(entry=>entry.component.render(viewport.width)),sizes=allocateStackSizes(entries,rendered.map(lines2=>lines2.length),void 0,this.gap),lines=[];for(let index=0;index<entries.length;index++){if(index>0)for(let gap=0;gap<this.gap;gap++)lines.
750
+ push("");let childLines=rendered[index].slice(0,sizes[index]);lines.push(...childLines);for(let padding=childLines.length;padding<sizes[index];padding++)lines.push("")}return lines}measureHeight(width,heightOf){let viewport={width:Math.max(1,width),height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport),heights=new Array(entries.length);for(let index=0;index<entries.length;index++){let entry=entries[index];heights[index]=typeof entry.basis=="number"?0:heightOf(entry.component,
751
+ viewport.width)}let sizes=allocateStackSizes(entries,heights,void 0,this.gap),height=Math.max(0,entries.length-1)*this.gap;for(let index=0;index<sizes.length;index++)height+=sizes[index];return height}};var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a,b){let x2=Math.max(a.x,b.x),y2=Math.max(a.y,b.y),right=Math.min(a.x+a.width,b.x+b.width),bottom=Math.min(a.y+a.height,b.y+b.height);return{x:x2,y:y2,width:Math.max(0,right-x2),height:Math.max(0,bottom-y2)}}function renderCached(context,component,width){let safeWidth=Math.max(1,Math.floor(width)),known=context.renderCache.get(component);if(known!==void 0){if(known.width===safeWidth)return known;let other=known.others?.
752
+ get(safeWidth);if(other!==void 0)return other}let live=renderLiveLines(component,safeWidth),lines=live?.lines??renderSharedLines(component,safeWidth),rendered={width:safeWidth,lines,live};return known===void 0?context.renderCache.set(component,rendered):(known.others??=new Map,known.others.set(safeWidth,rendered)),rendered}function measureHeight(context,component,width){return component instanceof VStack&&component.render===VStack.prototype.render?component.measureHeight(Math.max(1,Math.floor(width)),
753
+ context.heightOf):renderCached(context,component,width).lines.length}function measureWidth(context,component,width){return renderCached(context,component,width).lines.reduce((max,line)=>Math.max(max,visibleWidth(line)),0)}function withParent(box,parent){return box.parent=parent,box}function translateBox(box,deltaY){box.rect.y+=deltaY;let children=box.children;for(let i=0;i<children.length;i++)translateBox(children[i],deltaY)}function updateClips(box,parentClip){box.clip=intersect(parentClip,box.
754
+ rect);let children=box.children;for(let i=0;i<children.length;i++)updateClips(children[i],box.clip)}function layoutComponent(context,component,x2,y2,width,height,clip){let safeWidth=Math.max(1,Math.floor(width)),node=getLayoutNode(component);if(!node){let lines=renderCached(context,component,safeWidth).lines,allocatedHeight2=height===void 0?lines.length:Math.max(0,Math.floor(height)),lineOffset=0;if(lines.length>allocatedHeight2&&allocatedHeight2>0){let cursorLine=lines.findIndex(line=>line.includes(
755
+ CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y:y2,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y:y2,width:safeWidth,height:allocatedHeight2}),children:[],lines,lineOffset,layer:0}}if(node.type==="scroll"){let previousScrollTop=node.state.scrollTop,contentWidth=node.state.getContentWidth(safeWidth),childBox=layoutComponent(context,node.component,x2,y2-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.
756
+ rect.height,viewportHeight=height===void 0?contentHeight:Math.max(0,Math.floor(height));node.state.updateLayout(contentHeight,viewportHeight,context.requestRender),translateBox(childBox,previousScrollTop-node.state.scrollTop);let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y:y2,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),content=renderCached(context,node.component,contentWidth),box2={component,
757
+ rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:content.lines,scrollContentLive:content.live,layer:0};return childBox.parent=box2,updateClips(childBox,childClip),box2}let entries=visibleStackEntries(node.entries,context.viewport),gapTotal=Math.max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=new Array(entries.length);for(let index=0;index<entries.length;index++){let entry=entries[index];intrinsicHeights2[index]=typeof entry.basis=="numbe\
758
+ r"?entry.basis:measureHeight(context,entry.component,safeWidth)}let sizes=allocateStackSizes(entries,intrinsicHeights2,height,node.gap),sizesTotal=0;for(let index=0;index<sizes.length;index++)sizesTotal+=sizes[index];let naturalHeight=sizesTotal+gapTotal,allocatedHeight2=height===void 0?naturalHeight:Math.max(0,Math.floor(height)),rect2={x:x2,y:y2,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y2;for(let index=0;index<entries.
759
+ length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],box2.clip),box2)),childY+=sizes[index]+node.gap;return box2}let intrinsicWidths=entries.map(entry=>typeof entry.basis=="number"?entry.basis:measureWidth(context,entry.component,safeWidth)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,node.gap),intrinsicHeights=entries.map((entry,index)=>measureHeight(context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===
760
+ void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y:y2,width:safeWidth,height:allocatedHeight},box={component,rect,clip:intersect(clip,rect),children:[],layer:0},childX=x2;for(let index=0;index<entries.length;index++){let naturalChildHeight=intrinsicHeights[index],childHeight=node.align==="stretch"?allocatedHeight:Math.min(allocatedHeight,naturalChildHeight),childY=y2;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/
761
+ 2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.push({component:entries[index].component,rect:{x:childX,y:childY,width:0,height:childHeight},clip:{x:childX,y:childY,width:0,height:0},children:[],parent:box,layer:0}):box.children.push(withParent(layoutComponent(context,entries[index].component,childX,childY,childWidth,childHeight,box.clip),box)),childX+=childWidth+node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){
762
+ if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(line,column),start=graphemeRange?.start??column,end=graphemeRange?.end??column+1,before=sliceByColumn(line,0,start,!0),target=sliceByColumn(line,start,end-start,!0),after=sliceByColumn(line,end,Math.max(0,totalWidth-end),!0),targetPrefix="",targetIndex=0;for(;targetIndex<target.length;){let ansi=extractAnsiCode(target,targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.
763
+ max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.max(0,column-start)),cellPaddingAfter=" ".repeat(Math.max(0,end-column-1)),targetStyle=`\x1B[0m\x1B]8;;\x07${preserveTargetBackground?getActiveBackgroundAnsi(targetPrefix):""}`;return`${before}${beforePadding}${targetStyle}${cellPaddingBefore}${replacement}${cellPaddingAfter}${after}`}function getScrollbarGeometry(box,includeHiddenAuto=!1){if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.
764
+ rect.height??box.scrollContentLines?.length??0,trackHeight=box.rect.height,canRevealHiddenAuto=includeHiddenAuto&&box.scrollView.scrollbar==="auto"&&contentHeight>trackHeight;if(!box.scrollView.isScrollbarVisible&&!canRevealHiddenAuto)return;let minThumbHeight=Math.min(2,trackHeight),thumbHeight=Math.max(minThumbHeight,Math.min(trackHeight,Math.round(trackHeight*trackHeight/contentHeight))),maxScrollTop=Math.max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===
765
+ 0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),column=box.rect.x+box.rect.width-1;if(!(column<box.clip.x||column>=box.clip.x+box.clip.width))return{column,trackTop:box.rect.y,trackHeight,thumbTop:box.rect.y+thumbOffset,thumbHeight,maxScrollTop}}function paintScrollbar(box,screen,totalWidth){let geometry=getScrollbarGeometry(box);if(!(!geometry||!box.scrollView))for(let offset=0;offset<geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.
766
+ y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=geometry.thumbTop&&row<geometry.thumbTop+geometry.thumbHeight?box.scrollView.scrollbarThumbStyle(box.scrollView.isScrollbarActive?"\u2588":"\u2503"):box.scrollView.scrollbarTrackStyle("\u2502");screen[row]=replaceScrollbarCell(screen[row]??"",geometry.column,totalWidth,replacement,box.scrollView.scrollbar!=="always")}}function paintBox(box,screen,totalWidth){if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.
767
+ rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.y+box.clip.height,screen.length);for(let row=firstRow;row<lastRow;row++){let sourceLine=box.lines[offset+row-box.rect.y];if(sourceLine===void 0)continue;let line=sourceLine.charCodeAt(0)===27&&sourceLine.startsWith("\x1B]133;")?sourceLine.replace(OSC133_ZONE_PREFIX,""):sourceLine,imageMetadata=getKittyImageMetadata(line);if(imageMetadata){let clipBottom=Math.min(screen.length,box.clip.y+box.clip.height),visibleRows=Math.min(
768
+ imageMetadata.rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=cropKittyImageLine(line,0,visibleRows))}box.rect.x===0&&box.rect.width>=totalWidth&&(!screen[row]||isImageLine(line))?screen[row]=line:screen[row]=compositeTuiLine(screen[row]??"",line,box.rect.x,box.rect.width,totalWidth)}}let children=box.children;for(let i=0;i<children.length;i++)paintBox(children[i],screen,totalWidth);if(box.scrollView&&box.scrollContentLines&&box.scrollView.scrollTop>0&&box.rect.height>0){let scrollTop=box.
769
+ scrollView.scrollTop,minRow=Math.max(0,scrollTop-getMaxKittyImageRows());for(let imageRow=scrollTop-1;imageRow>=minRow;imageRow--){let imageLine=box.scrollContentLines[imageRow]??"";if(!isImageLine(imageLine))continue;let metadata=getKittyImageMetadata(imageLine);if(!metadata)continue;let hiddenRows=scrollTop-imageRow;if(hiddenRows<metadata.rows){let visibleRows=Math.min(box.rect.height,metadata.rows-hiddenRows),cropped=cropKittyImageLine(imageLine,hiddenRows,visibleRows);box.rect.x===0&&box.rect.
770
+ width>=totalWidth&&(screen[box.rect.y]=cropped)}break}}paintScrollbar(box,screen,totalWidth)}function renderLayoutFrame(root,width,height,requestRender){let safeWidth=Math.max(1,Math.floor(width)),safeHeight=Math.max(1,Math.floor(height)),context={viewport:{width:safeWidth,height:safeHeight},renderCache:new Map,heightOf:(component,width2)=>measureHeight(context,component,width2),requestRender,primaryScrollView:void 0},rootBox=layoutComponent(context,root,0,0,safeWidth,safeHeight,{x:0,y:0,width:safeWidth,
771
+ height:safeHeight}),lines=[];for(let row=0;row<safeHeight;row++)lines.push("");return paintBox(rootBox,lines,safeWidth),{root:rootBox,width:safeWidth,height:safeHeight,lines,...context.primaryScrollView===void 0?{}:{primaryScrollView:context.primaryScrollView}}}function containsPoint(rect,x2,y2){return x2>=rect.x&&x2<rect.x+rect.width&&y2>=rect.y&&y2<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){result.push({box,depth});
772
+ for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b)=>b.box.layer-a.box.layer||b.depth-a.depth),result.map(({box})=>box)}function getScrollViewBox(frame,scrollView){let visit=box=>{if(box.scrollView===scrollView)return box;for(let child of box.children){let match=visit(child);if(match)return match}};return visit(frame.root)}function getScrollViewsAt(frame,x2,y2){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y2)){box.scrollView&&containsPoint(
773
+ box.rect,x2,y2)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a,b)=>b.depth-a.depth),result.map(entry=>entry.scrollView)}function terminalAcceleratesWheel(){let env=process.env;return process.platform==="darwin"&&env.SSH_CONNECTION===void 0&&env.SSH_CLIENT===void 0&&env.SSH_TTY===void 0}var WheelScrollAccelerator=class{lines;accelerate;lastTime=Number.NEGATIVE_INFINITY;lastDirection=0;averageGap;carry=0;constructor(lines="auto",accelerate=!terminalAcceleratesWheel()){this.lines=lines,this.accelerate=accelerate}setLines(lines){this.lines=lines,this.reset()}next(direction,now){if(this.lines!=="auto")return Number.isFinite(
774
+ this.lines)?Math.max(1,Math.floor(this.lines)):1;if(!this.accelerate)return 1;let gap=now-this.lastTime,sameGesture=direction===this.lastDirection&&gap<=200;if(this.lastTime=now,this.lastDirection=direction,!sameGesture)return this.averageGap=void 0,this.carry=0,1;if(gap<5)return 1;this.averageGap=this.averageGap===void 0?gap:(this.averageGap+gap)/2;let lines=Math.min(6,Math.max(1,100/this.averageGap))+this.carry,whole=Math.floor(lines);return this.carry=lines-whole,whole}reset(){this.lastTime=Number.
775
+ NEGATIVE_INFINITY,this.lastDirection=0,this.averageGap=void 0,this.carry=0}};var ENTER_ALT_SCREEN="\x1B[?1049h",EXIT_ALT_SCREEN="\x1B[?1049l",DISABLE_AUTOWRAP="\x1B[?7l",ENABLE_AUTOWRAP="\x1B[?7h",ENABLE_BUTTON_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1004h\x1B[?1006h",ENABLE_ALL_MOTION_MOUSE="\x1B[?1000h\x1B[?1002h\x1B[?1003h\x1B[?1004h\x1B[?1006h",DISABLE_MOUSE="\x1B[?1006l\x1B[?1004l\x1B[?1003l\x1B[?1002l\x1B[?1000l",FOCUS_IN="\x1B[I",FOCUS_OUT="\x1B[O",BEGIN_SYNCHRONIZED_OUTPUT="\x1B[?2026h",END_SYNCHRONIZED_OUTPUT="\x1B[?2026l",MIN_ROWS_SAVED_BY_SCROLLING=3,OSC133_ZONE_PREFIX2=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,
776
+ OSC133_PROMPT_START=/^\x1b\]133;A(?:\x07|\x1b\\)/,PAGE_SCROLL_OVERLAP=4,ALT_WHEEL_SCROLL_MULTIPLIER=5,MAX_CACHED_OFFSCREEN_KITTY_IMAGES=16,MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES=32*1024*1024,MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES=64*1024*1024,DOUBLE_CLICK_INTERVAL_MS=500,COPY_ERROR_FLASH_DURATION_MS=5e3,TERMINAL_WORD_SELECTION_JOINERS=new Set(["/","-","+","\\","~","_","."]),TuiAltScreen=class extends TuiBase{mode="fullscreen";[VIEWPORT_TUI]=!0;previousScreen=[];lastDocument=[];previousScreenWidth=0;previousScreenHeight=0;finishedRows=new Map;finishedRowsWidth=0;imageRows=new Set;resolvedRows=new Map;resolvedRowsCursor=!1;layoutRoot;currentLayout;implicitDocument;implicitScrollView;flashes;altScreenActive=!1;imageProtocol=null;savedCapabilities;uploadedKittyImages=new Map;selectionAnchor;selectionFocus;selectionGranularity="\
777
+ character";selectionInitialRange;lastClick;selectionDragPointer;selectionAutoScrollDirection=0;selectionAutoScrollTimer;selectionPressActive=!1;scrollbarDrag;scrollbarHover;scrollToEndIndicatorRect;activeSearch;pressedUrl;selectionDragged=!1;mouseCapture;mousePressTarget;mousePressPoint;mousePressMoved=!1;lastComponentClick;wheelScroll;mouseEnabled;searchMatchStyle;searchCurrentMatchStyle;searchNavigationButtonStyle;scrollToEndIndicator;openUrl;onRightClickPaste;copyOnSelect;copySelection;constructor(terminal,showHardwareCursor,logDirectory,options={}){
778
+ super(terminal,showHardwareCursor,logDirectory),this.implicitDocument={render:width=>super.renderShared(width),handleMouse:event=>super.handleMouse(event),invalidate:()=>{for(let child of this.children)child.invalidate()}},markLiveRender(this.implicitDocument.render,width=>Container.renderLive(this,width)),this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(
779
+ options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=options.searchMatchStyle??(text=>`\x1B[4m${text}\x1B[24m`),this.searchCurrentMatchStyle=options.searchCurrentMatchStyle??(text=>`\x1B[1;7m${text}\x1B[22;27m`),this.searchNavigationButtonStyle=options.searchNavigationButtonStyle??(text=>text),this.scrollToEndIndicator=options.scrollToEndIndicator,this.openUrl=options.openUrl,this.onRightClickPaste=options.onRightClickPaste,this.copyOnSelect=options.copyOnSelect??
780
+ !0,this.copySelection=options.copySelection,this.addInputListener(data=>this.handleViewportInput(data))}get viewportTop(){return this.getPrimaryScrollView().scrollTop}get isFollowingOutput(){return this.getPrimaryScrollView().isFollowingEnd}setWheelScrollLines(lines){this.wheelScroll.setLines(lines)}getCopyOnSelect(){return this.copyOnSelect}setCopyOnSelect(enabled){this.copyOnSelect=enabled}hasActiveSelection(){return this.getActiveSelectionText()!==void 0}async copyActiveSelectionToClipboard(){
781
+ let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}resetTextSelection(){this.clearTextSelection(),this.lastClick=void 0}getScreenLines(){return[...this.previousScreen]}setLayoutRoot(component){this.layoutRoot!==component&&(this.layoutRoot=component,this.currentLayout=void 0,this.requestRender())}render(width){return this.layoutRoot?.render(width)??super.render(width)}getMountedRoots(){return this.layoutRoot?[this.layoutRoot]:this.children}getPrimaryScrollView(){
782
+ return this.currentLayout?.primaryScrollView??this.implicitScrollView}beforeTerminalStart(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.flashes.dispose(),this.altScreenActive=!0;let capabilities=getCapabilities();this.imageProtocol=capabilities.images,this.uploadedKittyImages.clear(),capabilities.images==="iterm2"&&(this.savedCapabilities=capabilities,setCapabilities({...capabilities,images:null}),this.invalidate()),this.lastDocument=
783
+ [],this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,this.resetRenderState();let term=process.env.TERM?.toLowerCase()??"",mouseSequence=process.env.TMUX!==void 0||process.env.ZELLIJ!==void 0||process.env.STY!==void 0||term.startsWith("tmux")||term.startsWith("screen")?ENABLE_BUTTON_MOTION_MOUSE:
784
+ ENABLE_ALL_MOTION_MOUSE;this.terminal.write(`${ENTER_ALT_SCREEN}${DISABLE_AUTOWRAP}${this.mouseEnabled?mouseSequence:""}\x1B[2J\x1B[H\x1B[?25l`)}beforeTerminalStop(_options){this.closeSearch(),this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.stopScrollbarHover(),this.stopScrollbarDrag(),this.clearComponentMouseGesture(),this.flashes.dispose(),this.altScreenActive&&(this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${this.deleteKittyImages()}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${END_SYNCHRONIZED_OUTPUT}`),
785
+ this.uploadedKittyImages.clear())}afterTerminalStop(options){if(this.altScreenActive){if(this.altScreenActive=!1,options.preserveScreen)this.terminal.write(`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}\x1B[?25h${END_SYNCHRONIZED_OUTPUT}`);else{let width=Math.max(1,this.terminal.columns),documentLines=this.resolveFakeCursors(this.render(width)).map(line=>line.replace(OSC133_ZONE_PREFIX2,""));this.lastDocument=this.applyLineResets(documentLines.map(line=>line.replaceAll(CURSOR_MARKER,""))).map(line=>isImageLine(
786
+ line)||visibleWidth(line)<=width?line:sliceByColumn(line,0,width,!0));let buffer=`${BEGIN_SYNCHRONIZED_OUTPUT}${EXIT_ALT_SCREEN}${DISABLE_AUTOWRAP}`;for(let row=0;row<this.lastDocument.length;row++)row>0&&(buffer+=`\r
787
+ `),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
788
+ \x1B[?25h${END_SYNCHRONIZED_OUTPUT}`,this.terminal.write(buffer)}this.savedCapabilities&&(setCapabilities(this.savedCapabilities),this.savedCapabilities=void 0)}}getExitRestorePrefix(){let prefix=super.getExitRestorePrefix();return this.altScreenActive?`${END_SYNCHRONIZED_OUTPUT}${this.mouseEnabled?DISABLE_MOUSE:""}${ENABLE_AUTOWRAP}${prefix}`:prefix}getExitRestoreSuffix(){return`${super.getExitRestoreSuffix()}${this.altScreenActive?`${EXIT_ALT_SCREEN}\x1B[?25h`:""}`}deleteKittyImages(){return this.
789
+ imageProtocol==="kitty"?deleteAllKittyImages():""}prepareKittyScreen(screen){let visibleImageIds=new Set,lines=screen.map(line=>{let placement=getKittyImagePlacement(line);if(!placement)return line;visibleImageIds.add(placement.imageId);let cachedImage=this.uploadedKittyImages.get(placement.imageId),nextCachedImage={transmissionGeneration:placement.transmissionGeneration,transmissionBytes:placement.transmissionBytes,estimatedDecodedBytes:placement.estimatedDecodedBytes};return cachedImage&&this.
790
+ uploadedKittyImages.delete(placement.imageId),this.uploadedKittyImages.set(placement.imageId,nextCachedImage),cachedImage?.transmissionGeneration===placement.transmissionGeneration?placement.replacementLine:line}),cachedOffscreenImageCount=0,cachedOffscreenTransmissionBytes=0,cachedOffscreenDecodedBytes=0;for(let[imageId,cachedImage]of this.uploadedKittyImages)visibleImageIds.has(imageId)||(cachedOffscreenImageCount+=1,cachedOffscreenTransmissionBytes+=cachedImage.transmissionBytes,cachedOffscreenDecodedBytes+=
791
+ cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,cachedImage]of this.uploadedKittyImages){if(cachedOffscreenImageCount<=MAX_CACHED_OFFSCREEN_KITTY_IMAGES&&cachedOffscreenTransmissionBytes<=MAX_CACHED_OFFSCREEN_KITTY_TRANSMISSION_BYTES&&cachedOffscreenDecodedBytes<=MAX_CACHED_OFFSCREEN_KITTY_DECODED_BYTES)break;visibleImageIds.has(imageId)||(evictedImageDeletion+=deleteKittyImage(imageId),this.uploadedKittyImages.delete(imageId),cachedOffscreenImageCount-=1,cachedOffscreenTransmissionBytes-=
792
+ cachedImage.transmissionBytes,cachedOffscreenDecodedBytes-=cachedImage.estimatedDecodedBytes)}return{lines,evictedImageDeletion}}resetRenderState(){this.previousScreen=[],this.finishedRows=new Map,this.imageRows=new Set,this.previousScreenWidth=0,this.previousScreenHeight=0,this.currentLayout=void 0}scrollBy(lines){this.getPrimaryScrollView().scrollBy(lines),this.requestRender()}scrollToTop(){this.getPrimaryScrollView().scrollToStart(),this.requestRender()}scrollToBottom(){this.getPrimaryScrollView().
793
+ scrollToEnd(),this.requestRender()}scrollToPrompt(direction){if(!this.currentLayout)return;let scrollView=this.getPrimaryScrollView(),lines=getScrollViewBox(this.currentLayout,scrollView)?.scrollContentLines;if(lines){for(let row=scrollView.scrollTop+direction;row>=0&&row<lines.length;row+=direction)if(OSC133_PROMPT_START.test(lines[row]??"")){scrollView.scrollTo(row),this.requestRender();return}}}toggleSearch(){if(this.activeSearch){this.closeSearch();return}let component=new AltScreenSearchComponent(
794
+ query=>this.updateSearchQuery(query),this.searchNavigationButtonStyle),search={component,index:new AltScreenSearchIndex,query:"",matches:[],selectedIndex:-1,anchorRow:this.getPrimaryScrollView().scrollTop,selectionMode:"query"};this.activeSearch=search,search.overlay=this.showOverlay(component,{anchor:"top-right",width:"40%",minWidth:32,margin:1})}closeSearch(){let search=this.activeSearch;search&&(this.activeSearch=void 0,search.overlay?.hide(),this.requestRender())}updateSearchQuery(query){let search=this.
795
+ activeSearch;if(!search||query===search.query)return;let selected=search.matches[search.selectedIndex];search.anchorRow=selected?.segments[0]?.row??this.getPrimaryScrollView().scrollTop,search.query=query,search.selectionMode="query",search.component.setResult(-1,0),this.requestRender()}navigateSearch(direction){let search=this.activeSearch;search?.query&&(search.selectionMode=direction<0?"previous":"next",this.requestRender())}getSearchNavigationDirectionAt(x2,y2){let search=this.activeSearch,bounds=search?.
796
+ overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y2<bounds.row||y2>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y2-bounds.row,x2-bounds.col)}handleSearchMouseEvent(event){let search=this.activeSearch;if(!search)return!1;let direction=this.getSearchNavigationDirectionAt(event.x,event.y);return search.component.setHoveredNavigationDirection(direction)&&this.requestRender(),direction===void 0||event.release||(event.button&32)!==
797
+ 0||(event.button&3)!==0?!1:(this.navigateSearch(direction),!0)}refreshSearch(layout){let search=this.activeSearch;if(!search)return!1;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView),lines=box?.scrollContentLines;if(!lines||!search.query.trim())return search.matches=[],search.selectedIndex=-1,search.selectedKey=void 0,search.selectionMode="retain",search.component.setResult(-1,0),!1;let shouldRevealSelection=search.selectionMode!=="retain",
798
+ result=search.index.search(lines,search.query,box?.scrollContentLive),matches=result.matches;if(search.matches=matches,!result.changed&&search.selectionMode==="retain")return!1;let exactIndex=result.changed?search.selectedKey?matches.findIndex(match=>getAltScreenSearchMatchKey(match)===search.selectedKey):-1:search.selectedIndex,selectedIndex=-1;if(matches.length>0)if(search.selectionMode==="query"){let low=0,high=matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2);(matches[middle].
799
+ segments[0]?.row??0)<search.anchorRow?low=middle+1:high=middle}selectedIndex=low<matches.length?low:0}else if(search.selectionMode==="next"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?0:(baseIndex+1)%matches.length}else if(search.selectionMode==="previous"){let baseIndex=exactIndex>=0?exactIndex:Math.min(search.selectedIndex,matches.length-1);selectedIndex=baseIndex<0?matches.length-1:(baseIndex-1+matches.length)%matches.length}else
800
+ selectedIndex=exactIndex>=0?exactIndex:Math.min(Math.max(0,search.selectedIndex),matches.length-1);if(search.selectedIndex=selectedIndex,search.selectedKey=selectedIndex>=0?getAltScreenSearchMatchKey(matches[selectedIndex]):void 0,search.selectionMode="retain",search.component.setResult(selectedIndex,matches.length),!shouldRevealSelection)return!1;let selected=matches[selectedIndex],firstSegment=selected?.segments[0],lastSegment=selected?.segments[selected.segments.length-1];if(!box||!firstSegment||
801
+ !lastSegment||scrollView.viewportHeight<=0)return!1;let before=scrollView.scrollTop,visibleBottom=before+scrollView.viewportHeight-1,target=before;return(firstSegment.row<before||lastSegment.row>visibleBottom)&&(target=firstSegment.row-Math.floor(scrollView.viewportHeight/3)),scrollView.scrollTo(target,{disableFollow:!0}),scrollView.scrollTop!==before}flash(message,durationMs){this.flashes.flash(message,durationMs)}shouldDeferViewportInput(){return this.getFocusedComponent()?.capturesViewportInput?
802
+ !0:this.isOverlayFocused()&&this.activeSearch?.overlay?.isFocused()!==!0}clearComponentMouseGesture(){this.mouseCapture=void 0,this.mousePressTarget=void 0,this.mousePressPoint=void 0,this.mousePressMoved=!1}handleViewportInput(data){if(data===FOCUS_OUT){let hadActiveSelection=this.selectionPressActive,hadNonEmptyActiveSelection=hadActiveSelection&&this.getSelectionBounds()!==void 0;return this.selectionPressActive=!1,this.stopSelectionAutoScroll(),this.stopScrollbarHover(),this.activeSearch?.component.
803
+ setHoveredNavigationDirection(void 0)&&this.requestRender(),this.stopScrollbarDrag(),this.pressedUrl=void 0,this.selectionDragged=!1,this.clearComponentMouseGesture(),this.lastComponentClick=void 0,hadActiveSelection&&(this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,hadNonEmptyActiveSelection&&this.requestRender()),this.lastClick=void 0,{consume:!0}}if(data===FOCUS_IN)return{consume:!0};let wheelEvent=this.parseWheelEvent(
804
+ data);if(wheelEvent){let lines=this.wheelScroll.next(wheelEvent.direction,performance.now()),wheelDelta=wheelEvent.direction*((wheelEvent.button&8)!==0?lines*ALT_WHEEL_SCROLL_MULTIPLIER:lines),event=this.createMouseEvent("wheel",wheelEvent.button,wheelEvent.x,wheelEvent.y,{wheelDelta}),overlay=this.dispatchMouseToOverlay(event),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));return result?(this.applyMouseDispatchResult(event,result)&&this.requestRender(),{consume:!0}):
805
+ (this.routeWheel(wheelEvent,wheelDelta),{consume:!0})}let mouseEvent=this.parseSgrMouseEvent(data);if(mouseEvent)return this.handleMouseEvent(mouseEvent),{consume:!0};if(this.isMouseSequence(data))return{consume:!0};let keybindings=getKeybindings(),isRelease=isKeyRelease(data);if(keybindings.matches(data,"tui.altScreen.search"))return isRelease||this.toggleSearch(),{consume:!0};if(this.activeSearch?.overlay?.isFocused()){if(keybindings.matches(data,"tui.altScreen.searchNext"))return isRelease||this.
806
+ navigateSearch(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchPrevious"))return isRelease||this.navigateSearch(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.searchClose"))return isRelease||this.closeSearch(),{consume:!0}}if(!this.shouldDeferViewportInput()){if(keybindings.matches(data,"tui.altScreen.pageUp"))return isRelease||this.scrollBy(-Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.alt\
807
+ Screen.pageDown"))return isRelease||this.scrollBy(Math.max(1,this.getPrimaryScrollView().viewportHeight-PAGE_SCROLL_OVERLAP)),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageUp"))return isRelease||this.scrollBy(-Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(data,"tui.altScreen.halfPageDown"))return isRelease||this.scrollBy(Math.max(1,Math.floor(this.getPrimaryScrollView().viewportHeight/2))),{consume:!0};if(keybindings.matches(
808
+ data,"tui.altScreen.lineUp"))return isRelease||this.scrollBy(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.lineDown"))return isRelease||this.scrollBy(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.previousPrompt"))return isRelease||this.scrollToPrompt(-1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.nextPrompt"))return isRelease||this.scrollToPrompt(1),{consume:!0};if(keybindings.matches(data,"tui.altScreen.top"))return isRelease||this.scrollToTop(),{consume:!0};
809
+ if(keybindings.matches(data,"tui.altScreen.bottom"))return isRelease||this.scrollToBottom(),{consume:!0}}}decodeMouseButton(button){switch(button&3){case 0:return"left";case 1:return"middle";case 2:return"right";default:return"none"}}createMouseEvent(type,button,x2,y2,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y:y2,screenX:x2,screenY:y2,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,
810
+ ctrl:(button&16)!==0,...extra.wheelDelta===void 0?{}:{wheelDelta:extra.wheelDelta},...extra.clickCount===void 0?{}:{clickCount:extra.clickCount}}}dispatchMouseToLayout(event){if(!this.currentLayout)return;let visited=new Set,boxes=getLayoutBoxesAt(this.currentLayout,event.screenX,event.screenY);for(let box of boxes){if(visited.has(box.component)||getLayoutNode(box.component)&&box.component.handleMouse===Container.prototype.handleMouse)continue;visited.add(box.component);let result=dispatchMouseEvent(
811
+ box.component,{...event,x:event.screenX-box.rect.x,y:event.screenY-box.rect.y,width:box.rect.width,height:box.rect.height});if(result)return result}}applyMouseDispatchResult(event,result){let focusTarget=this.resolveMouseFocusTarget(result.focusTarget??result.target.component),focusChanged=result.focus===!0&&this.getFocusedComponent()!==focusTarget;return result.focus&&this.setFocus(focusTarget),result.capture&&(this.mouseCapture=result.target),result.render??(focusChanged||event.type==="press"||
812
+ event.type==="click"||event.type==="drag"||event.type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y2){let now=Date.now(),previous=this.lastComponentClick,count=previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.component===target.component&&previous.x===x2&&previous.y===y2?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,
813
+ x:x2,y:y2},count}clearTextSelection(){this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.pressedUrl=void 0,this.selectionDragged=!1}handleMouseEvent(raw){let isMotion=(raw.button&32)!==0,type=raw.release?"release":isMotion?this.decodeMouseButton(raw.button)==="none"?"move":"drag":"press",event=this.createMouseEvent(type,raw.button,raw.x,raw.y);if(this.mouseCapture||
814
+ this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;this.mousePressPoint&&(raw.x!==this.mousePressPoint.x||raw.y!==this.mousePressPoint.y)&&(this.mousePressMoved=!0,this.lastComponentClick=void 0);let render=!1,targetResult=this.dispatchMouseToTarget(event,target);if(targetResult&&(render=this.applyMouseDispatchResult(event,targetResult)),raw.release){if(!this.mousePressMoved&&this.mousePressPoint?.x===raw.x&&this.mousePressPoint.y===raw.y){let clickEvent=this.createMouseEvent(
815
+ "click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(target,raw.x,raw.y)}),clickResult=this.dispatchMouseToTarget(clickEvent,target);clickResult&&(render=this.applyMouseDispatchResult(clickEvent,clickResult)||render)}this.clearComponentMouseGesture()}render&&this.requestRender();return}if(this.handleSearchMouseEvent(raw))return;let overlay=this.dispatchMouseToOverlay(event);if(overlay.hit)this.stopScrollbarHover();else{if(this.handleScrollToEndIndicatorMouseEvent(raw))return;let scrollbarHandled=this.
816
+ handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||this.updateScrollbarHover(raw.x,raw.y),scrollbarHandled)return}let result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(event));if(result){let render=this.applyMouseDispatchResult(event,result);type==="press"&&(this.clearTextSelection(),this.mousePressTarget=result.target,this.mousePressPoint={x:raw.x,y:raw.y},this.mousePressMoved=!1),render&&this.requestRender();return}this.handleRightClickPaste(raw)||this.handleSelectionMouseEvent(
817
+ raw)}parseWheelEvent(data){let sgr=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.exec(data);if(sgr){let button=Number.parseInt(sgr[1],10);if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===0?-1:1,x:Number.parseInt(sgr[2],10)-1,y:Number.parseInt(sgr[3],10)-1,button}}if(data.length===6&&data.startsWith("\x1B[M")){let button=data.charCodeAt(3)-32;if((button&64)===0)return;let direction=button&3;return direction!==0&&direction!==1?void 0:{direction:direction===
818
+ 0?-1:1,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33,button}}}routeWheel(event,delta){let remaining=delta,seen=new Set;for(let scrollView of this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y):[])if(seen.add(scrollView),remaining=scrollView.scrollBy(remaining),remaining===0||scrollView.overscroll==="contain")break;let primary=this.getPrimaryScrollView();remaining!==0&&!seen.has(primary)&&primary.scrollBy(remaining),this.updateScrollbarHover(event.x,event.y),this.requestRender()}parseSgrMouseEvent(data){
819
+ let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(match)return{button:Number.parseInt(match[1],10),x:Number.parseInt(match[2],10)-1,y:Number.parseInt(match[3],10)-1,release:match[4]==="m"}}handleRightClickPaste(event){if(!this.onRightClickPaste||process.platform!=="win32"||process.env.TERM_PROGRAM?.toLowerCase()==="vscode"||event.release||event.button!==2)return!1;try{this.onRightClickPaste()}catch{}return!0}handleScrollToEndIndicatorMouseEvent(event){let rect=this.scrollToEndIndicatorRect;
820
+ return!rect||event.release||(event.button&32)!==0||(event.button&3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y2,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y2)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y2>=geometry.
821
+ trackTop&&y2<geometry.trackTop+geometry.trackHeight)return{scrollView,geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y2){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y2,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.
822
+ trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.min(maxThumbOffset,pointerY-geometry.trackTop-grabOffset)),scrollTop=maxThumbOffset===0?0:Math.round(thumbOffset/maxThumbOffset*geometry.maxScrollTop);scrollView.scrollTo(scrollTop)}handleScrollbarMouseEvent(event){if(this.scrollbarDrag){if(event.release)return this.stopScrollbarDrag(),!0;let box=this.currentLayout?getScrollViewBox(this.currentLayout,this.scrollbarDrag.scrollView):void 0,geometry=box?getScrollbarGeometry(box):void 0;return geometry&&
823
+ this.scrollScrollbarToPointer(this.scrollbarDrag.scrollView,geometry,event.y,this.scrollbarDrag.grabOffset),!0}if(event.release||(event.button&32)!==0||(event.button&3)!==0)return!1;let target=this.getScrollbarTargetAt(event.x,event.y);if(!target)return!1;this.stopSelectionAutoScroll(),this.selectionPressActive=!1,this.selectionAnchor=void 0,this.selectionFocus=void 0,this.selectionGranularity="character",this.selectionInitialRange=void 0,this.lastClick=void 0,this.pressedUrl=void 0,this.selectionDragged=
824
+ !1,this.setScrollbarHover(target.scrollView);let onThumb=event.y>=target.geometry.thumbTop&&event.y<target.geometry.thumbTop+target.geometry.thumbHeight,grabOffset=onThumb?event.y-target.geometry.thumbTop:Math.floor(target.geometry.thumbHeight/2);return onThumb||this.scrollScrollbarToPointer(target.scrollView,target.geometry,event.y,grabOffset),this.scrollbarDrag={scrollView:target.scrollView,grabOffset},!0}stopScrollbarDrag(){this.scrollbarDrag=void 0}getScrollSelectionPoint(scrollView,x2,y2){if(!this.
825
+ currentLayout)return;let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0)return;let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(visibleBottom<visibleTop)return;let pointerRow=Math.max(visibleTop,Math.min(visibleBottom,y2)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.
826
+ scrollTop+pointerRow-box.rect.y)),col:Math.max(0,Math.min(box.rect.width-1,x2-box.rect.x)),scrollView}}getSelectionPoint(event,scrollView){if(scrollView){let point=this.getScrollSelectionPoint(scrollView,event.x,event.y);if(point)return point}return{row:Math.max(0,Math.min(this.terminal.rows-1,event.y)),col:Math.max(0,Math.min(this.terminal.columns-1,event.x))}}getSelectionSourceLine(point){if(point.scrollView&&this.currentLayout){let lines=getScrollViewBox(this.currentLayout,point.scrollView)?.
827
+ scrollContentLines;if(lines)return lines[point.row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of getWordSegmenter().segment(line)){let end=start+visibleWidth(segment.segment),joiner=TERMINAL_WORD_SELECTION_JOINERS.has(segment.segment);segments.push({start,end,selectable:segment.isWordLike===!0||joiner,joiner}),start=end}let clickedSegmentIndex=segments.findIndex(segment=>point.
828
+ col>=segment.start&&point.col<segment.end);if(clickedSegmentIndex<0)return;let canJoin=(left,right)=>left.selectable&&right.selectable&&(left.joiner||right.joiner),selectionStart=segments[clickedSegmentIndex].start,selectionEnd=segments[clickedSegmentIndex].end;for(let index=clickedSegmentIndex;index>0&&canJoin(segments[index-1],segments[index]);index--)selectionStart=segments[index-1].start;for(let index=clickedSegmentIndex;index<segments.length-1&&canJoin(segments[index],segments[index+1]);index++)
829
+ selectionEnd=segments[index+1].end;return{start:{...point,col:selectionStart},end:{...point,col:selectionEnd,boundary:!0}}}getLineSelection(point){return{start:{...point,col:0},end:{...point,col:visibleWidth(this.getSelectionSourceLine(point)),boundary:!0}}}updateSelectionFocus(point){if(this.selectionGranularity==="character"||!this.selectionInitialRange){this.selectionFocus=point;return}let range=this.selectionGranularity==="word"?this.getWordSelection(point):this.getLineSelection(point);if(!range)
830
+ return;let initial=this.selectionInitialRange;range.start.row<initial.start.row||range.start.row===initial.start.row&&range.start.col<initial.start.col?(this.selectionAnchor=initial.end,this.selectionFocus=range.start):(this.selectionAnchor=initial.start,this.selectionFocus=range.end)}getClickCount(point,word){let now=Date.now(),previous=this.lastClick,count=word&&previous&&now-previous.timestamp<=DOUBLE_CLICK_INTERVAL_MS&&previous.row===point.row&&previous.scrollView===point.scrollView&&previous.
831
+ wordStart===word.start.col&&previous.wordEnd===word.end.col?previous.count%3+1:1;return this.lastClick=word?{timestamp:now,count,row:point.row,scrollView:point.scrollView,wordStart:word.start.col,wordEnd:word.end.col}:void 0,count}updateSelectionAutoScroll(event){let scrollView=this.selectionAnchor?.scrollView;if(!scrollView||!this.currentLayout){this.stopSelectionAutoScroll();return}let box=getScrollViewBox(this.currentLayout,scrollView);if(!box||box.rect.height<=0||box.clip.height<=0){this.stopSelectionAutoScroll();
832
+ return}let visibleTop=Math.max(0,box.rect.y,box.clip.y),visibleBottom=Math.min(this.terminal.rows-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1);if(this.selectionDragPointer={x:event.x,y:event.y},this.selectionAutoScrollDirection=event.y<=visibleTop?-1:event.y>=visibleBottom?1:0,this.selectionAutoScrollDirection===0){this.stopSelectionAutoScroll();return}this.selectionAutoScrollTimer||(this.selectionAutoScrollTimer=setInterval(()=>this.autoScrollSelection(),50),this.selectionAutoScrollTimer.
833
+ unref())}autoScrollSelection(){let scrollView=this.selectionAnchor?.scrollView,pointer=this.selectionDragPointer,direction=this.selectionAutoScrollDirection;if(!scrollView||!pointer||direction===0){this.stopSelectionAutoScroll();return}if(scrollView.scrollBy(direction)===direction){this.stopSelectionAutoScroll();return}let point=this.getScrollSelectionPoint(scrollView,pointer.x,pointer.y);point&&this.updateSelectionFocus(point),this.requestRender()}stopSelectionAutoScroll(){this.selectionAutoScrollTimer&&
834
+ (clearInterval(this.selectionAutoScrollTimer),this.selectionAutoScrollTimer=void 0),this.selectionAutoScrollDirection=0,this.selectionDragPointer=void 0}handleSelectionMouseEvent(event){let button=event.button&3;if(button!==0&&!(event.release&&button===3))return;let anchorScrollView=this.selectionAnchor?.scrollView,point=this.getSelectionPoint(event,anchorScrollView);if(event.release){if(!this.selectionPressActive||(this.selectionPressActive=!1,this.stopSelectionAutoScroll(),!this.selectionAnchor))
835
+ return;this.updateSelectionFocus(point);let isClick=!this.selectionDragged&&this.selectionAnchor.scrollView===point.scrollView&&this.selectionAnchor.row===point.row&&this.selectionAnchor.col===point.col,clickedUrl=isClick?this.pressedUrl:void 0;if(this.pressedUrl=void 0,clickedUrl&&this.openUrl){this.selectionAnchor=void 0,this.selectionFocus=void 0;try{this.openUrl(clickedUrl)}catch{}this.requestRender();return}if(isClick){let clickEvent=this.createMouseEvent("click",event.button,event.x,event.
836
+ y,{clickCount:this.lastClick?.count??1}),overlay=this.dispatchMouseToOverlay(clickEvent),result=overlay.result??(overlay.hit?void 0:this.dispatchMouseToLayout(clickEvent));if(result){let render=this.applyMouseDispatchResult(clickEvent,result);this.clearTextSelection(),render&&this.requestRender();return}}this.copyOnSelect&&this.copySelectionToClipboard(),this.requestRender();return}if((event.button&32)!==0){if(!this.selectionPressActive||!this.selectionAnchor)return;this.selectionDragged=!0,this.
837
+ lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(point),this.updateSelectionAutoScroll(event),this.requestRender();return}this.stopSelectionAutoScroll(),this.selectionPressActive=!0;let scrollView=!this.hasOverlay()&&this.currentLayout?getScrollViewsAt(this.currentLayout,event.x,event.y)[0]:void 0,anchor=this.getSelectionPoint(event,scrollView),word=this.getWordSelection(anchor),clickCount=this.getClickCount(anchor,word),range=clickCount===2?word:clickCount===3?this.getLineSelection(
838
+ anchor):void 0;this.selectionGranularity=range?clickCount===2?"word":"line":"character",this.selectionInitialRange=range,this.selectionAnchor=range?.start??anchor,this.selectionFocus=range?.end??anchor,this.selectionDragged=!1,this.pressedUrl=range?void 0:getOsc8LinkAtColumn(this.previousScreen[Math.max(0,Math.min(this.terminal.rows-1,event.y))]??"",Math.max(0,Math.min(this.terminal.columns-1,event.x))),this.requestRender()}getSelectionBounds(){if(!this.selectionAnchor||!this.selectionFocus||this.
839
+ selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let anchorBeforeFocus=this.selectionAnchor.row<this.selectionFocus.row||this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col<this.selectionFocus.col;if(!(this.selectionAnchor.row===this.selectionFocus.row&&this.selectionAnchor.col===this.selectionFocus.col))return anchorBeforeFocus?{start:this.selectionAnchor,end:this.selectionFocus}:{start:this.selectionFocus,end:this.selectionAnchor}}getSelectionColumns(line,row,selection,minColumn=0,maxColumn=visibleWidth(
840
+ line)){let lineWidth=visibleWidth(line),start=Math.max(0,minColumn),end=Math.min(lineWidth,maxColumn);return row===selection.start.row&&(start=getGraphemeCellRange(line,selection.start.col)?.start??Math.min(selection.start.col,lineWidth)),row===selection.end.row&&(end=selection.end.boundary?Math.min(selection.end.col,lineWidth):getGraphemeCellRange(line,selection.end.col)?.end??Math.min(selection.end.col+1,lineWidth)),{start:Math.max(minColumn,start),end:Math.min(maxColumn,end)}}getActiveSelectionText(){
841
+ let selection=this.getSelectionBounds();if(!selection)return;let sourceLines=this.previousScreen;if(selection.start.scrollView){if(!this.currentLayout)return;let box=getScrollViewBox(this.currentLayout,selection.start.scrollView);if(!box?.scrollContentLines)return;sourceLines=box.scrollContentLines}let lines=[];for(let row=selection.start.row;row<=selection.end.row;row++){let line=sourceLines[row]??"",columns=this.getSelectionColumns(line,row,selection);lines.push(stripTerminalSequences(sliceByColumn(
842
+ line,columns.start,Math.max(0,columns.end-columns.start),!0)).trimEnd())}let text=lines.join(`
843
+ `);return text.length===0?void 0:text}async copySelectionToClipboard(){let text=this.getActiveSelectionText();return text?this.copyTextToClipboard(text):!1}async copyTextToClipboard(text){if(this.copySelection){let result=await this.copySelection(text),ok=result===!0;return this.flash(ok?"Copied!":typeof result=="string"?result:"Copy failed",ok?void 0:COPY_ERROR_FLASH_DURATION_MS),ok}return this.terminal.write(`\x1B]52;c;${Buffer.from(text).toString("base64")}\x07`),this.flash("Copied!"),!0}applySearchTextHighlight(text,current){
844
+ let style=current?this.searchCurrentMatchStyle:this.searchMatchStyle,result="",plainStart=0,index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){index+=1;continue}index>plainStart&&(result+=style(text.slice(plainStart,index))),result+=ansi.code,index+=ansi.length,plainStart=index}return plainStart<text.length&&(result+=style(text.slice(plainStart))),result}applySearchHighlights(screen,layout){let search=this.activeSearch;if(!search||search.selectedIndex<0||search.matches.
845
+ length===0)return screen;let scrollView=layout.primaryScrollView??this.implicitScrollView,box=getScrollViewBox(layout,scrollView);if(!box)return screen;let rangesByRow=new Map,scrollbarColumn=getScrollbarGeometry(box)?.column,minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length,box.rect.y+box.rect.height,box.clip.y+box.clip.height),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width,scrollbarColumn??
846
+ Number.POSITIVE_INFINITY),minContentRow=scrollView.scrollTop+minRow-box.rect.y,maxContentRow=scrollView.scrollTop+maxRow-box.rect.y-1,low=0,high=search.matches.length;for(;low<high;){let middle=low+Math.floor((high-low)/2),match=search.matches[middle];(match.segments[match.segments.length-1]?.row??-1)<minContentRow?low=middle+1:high=middle}for(let matchIndex=low;matchIndex<search.matches.length;matchIndex++){let match=search.matches[matchIndex];if((match.segments[0]?.row??0)>maxContentRow)break;
847
+ for(let segment of match.segments){let row=box.rect.y+segment.row-scrollView.scrollTop;if(row<minRow||row>=maxRow)continue;let startCol=Math.max(minColumn,box.rect.x+segment.startCol),endCol=Math.min(maxColumn,box.rect.x+segment.endCol);if(endCol<=startCol)continue;let ranges=rangesByRow.get(row)??[];ranges.push({startCol,endCol,current:matchIndex===search.selectedIndex}),rangesByRow.set(row,ranges)}}let result=[...screen];for(let[row,ranges]of rangesByRow){let line=result[row]??"";if(isImageLine(
848
+ line))continue;let lineWidth=visibleWidth(line);for(let range of ranges.sort((a,b)=>b.startCol-a.startCol)){let startCol=Math.min(range.startCol,lineWidth),endCol=Math.min(range.endCol,lineWidth);if(endCol<=startCol)continue;let before=sliceByColumn(line,0,startCol,!0),highlighted=sliceByColumn(line,startCol,endCol-startCol,!0),after=sliceByColumn(line,endCol,Math.max(0,lineWidth-endCol),!0);line=`${before}${this.applySearchTextHighlight(highlighted,range.current)}${after}`}result[row]=line}return result}applySelectionHighlight(text){
849
+ let result="\x1B[7m",index=0;for(;index<text.length;){let ansi=extractAnsiCode(text,index);if(!ansi){result+=text[index],index+=1;continue}result+=ansi.code,ansi.code.endsWith("m")&&(result+="\x1B[7m"),index+=ansi.length}return`${result}\x1B[27m`}applySelection(screen,layout=this.currentLayout){let selection=this.getSelectionBounds();if(!selection)return screen;let screenSelection=selection,minRow=0,maxRow=screen.length-1,minColumn=0,maxColumn=this.terminal.columns;if(selection.start.scrollView){
850
+ if(!layout)return screen;let box=getScrollViewBox(layout,selection.start.scrollView);if(!box)return screen;minRow=Math.max(0,box.rect.y,box.clip.y),maxRow=Math.min(screen.length-1,box.rect.y+box.rect.height-1,box.clip.y+box.clip.height-1),minColumn=Math.max(0,box.rect.x,box.clip.x),maxColumn=Math.min(this.terminal.columns,box.rect.x+box.rect.width,box.clip.x+box.clip.width),screenSelection={start:{...selection.start,row:box.rect.y+selection.start.row-selection.start.scrollView.scrollTop,col:box.
851
+ rect.x+selection.start.col},end:{...selection.end,row:box.rect.y+selection.end.row-selection.start.scrollView.scrollTop,col:box.rect.x+selection.end.col}}}return screen.map((line,row)=>{if(row<minRow||row>maxRow||row<screenSelection.start.row||row>screenSelection.end.row||isImageLine(line))return line;let lineWidth=visibleWidth(line),columns=this.getSelectionColumns(line,row,screenSelection,minColumn,maxColumn);if(columns.end<=columns.start)return line;let before=sliceByColumn(line,0,columns.start,
852
+ !0),selected=sliceByColumn(line,columns.start,columns.end-columns.start,!0),after=sliceByColumn(line,columns.end,Math.max(0,lineWidth-columns.end),!0);return`${before}${this.applySelectionHighlight(selected)}${after}`})}isMouseSequence(data){return/^\x1b\[<\d+;\d+;\d+[Mm]$/.test(data)||data.length===6&&data.startsWith("\x1B[M")}compositeScrollToEndIndicator(screen,layout,width){this.scrollToEndIndicatorRect=void 0;let scrollView=layout.primaryScrollView??this.implicitScrollView;if(!this.scrollToEndIndicator||
853
+ !scrollView.followEnd||scrollView.isFollowingEnd)return screen;let box=getScrollViewBox(layout,scrollView),clip=box?.clip;if(!clip||clip.width<=0||clip.height<=0)return screen;let row=clip.y+clip.height-1;if(row>=screen.length||isImageLine(screen[row]??""))return screen;let scrollbarColumn=box?getScrollbarGeometry(box)?.column:void 0,label=truncateToWidth(this.scrollToEndIndicator(),clip.width,""),labelWidth=visibleWidth(label),column=clip.x+Math.floor((clip.width-labelWidth)/2),rightEdge=scrollbarColumn??
854
+ clip.x+clip.width,availableWidth=Math.max(0,rightEdge-column),text=truncateToWidth(label,availableWidth,""),textWidth=visibleWidth(text);if(textWidth===0)return screen;let result=[...screen];return result[row]=compositeTuiLine(result[row]??"",text,column,textWidth,width),this.scrollToEndIndicatorRect={row,column,width:textWidth},result}compositeFlashes(screen,width,height){let flashLines=this.flashes.render(width).slice(-height);if(flashLines.length===0)return screen;let result=[...screen];for(;result.
855
+ length<height;)result.push("");for(let row=0;row<flashLines.length;row++){let line=flashLines[row],flashWidth=visibleWidth(line);flashWidth!==0&&(result[row]=compositeTuiLine(result[row]??"",line,width-flashWidth,flashWidth,width))}return result}findMovedRows(screen,height,images){let previous=this.previousScreen,top=0;for(;top<height&&screen[top]===previous[top];)top++;let bottom=height-1;for(;bottom>top&&screen[bottom]===previous[bottom];)bottom--;let span=bottom-top+1;if(span<=MIN_ROWS_SAVED_BY_SCROLLING)
856
+ return;let changed=0;for(let row=top;row<=bottom;row++){let line=screen[row];if(line!==previous[row]&&(changed++,images&&(isImageLine(line)||isImageLine(previous[row]??""))))return}if(changed<=MIN_ROWS_SAVED_BY_SCROLLING)return;let best=0,up=0;for(let distance=1;span-distance>best;distance++){let sameUp=0,sameDown=0;for(let row=top;row+distance<=bottom;row++)screen[row]===previous[row+distance]&&sameUp++,screen[row+distance]===previous[row]&&sameDown++;sameUp>best&&(best=sameUp,up=distance),sameDown>
857
+ best&&(best=sameDown,up=-distance)}if(!(changed-(span-best)<MIN_ROWS_SAVED_BY_SCROLLING)){if(images){for(let row=top;row<=bottom;row++)if(isImageLine(previous[row]??""))return}return{top,bottom,up}}}doRender(){if(this.stopped||!this.altScreenActive)return;let width=Math.max(1,this.terminal.columns),height=Math.max(1,this.terminal.rows),root=this.layoutRoot??this.implicitScrollView,nextLayout=renderLayoutFrame(root,width,height,()=>this.requestRender());this.refreshSearch(nextLayout)&&(nextLayout=
858
+ renderLayoutFrame(root,width,height,()=>this.requestRender()));let showHardwareCursor=this.getShowHardwareCursor(),knownResolved=this.resolvedRowsCursor===showHardwareCursor?this.resolvedRows:void 0,resolvedRows=new Map,single=[""],screen=nextLayout.lines.map(line=>{let resolved=knownResolved?.get(line);return resolved===void 0&&(single[0]=line.startsWith("\x1B]133;")?line.replace(OSC133_ZONE_PREFIX2,""):line,resolved=this.resolveFakeCursors(single)[0]),resolvedRows.set(line,resolved),resolved});
859
+ this.resolvedRows=resolvedRows,this.resolvedRowsCursor=showHardwareCursor,screen=this.applySearchHighlights(screen,nextLayout),screen=this.compositeScrollToEndIndicator(screen,nextLayout,width),screen=this.compositeOverlays(screen,width,height),screen.length>height&&(screen=screen.slice(screen.length-height)),screen=this.applySelection(screen,nextLayout),screen=this.compositeFlashes(screen,width,height);let cursorPos=this.extractCursorPosition(screen,height),knownRows=this.finishedRowsWidth===width?
860
+ this.finishedRows:void 0,previousImageRows=this.imageRows,finishedRows=new Map,imageRows=new Set;screen=screen.map(line=>{let finished=knownRows?.get(line);return finished===void 0?(finished=this.applyLineResets([line])[0],isImageLine(finished)?imageRows.add(finished):visibleWidth(finished)>width&&(finished=sliceByColumn(finished,0,width,!0))):previousImageRows.has(finished)&&imageRows.add(finished),finishedRows.set(line,finished),finished}),this.finishedRows=finishedRows,this.finishedRowsWidth=
861
+ width,this.imageRows=imageRows;let fullRedraw=this.previousScreen.length===0||this.previousScreenWidth!==width||this.previousScreenHeight!==height,imageAnchorsNeedRedraw=(imageRows.size>0||previousImageRows.size>0)&&screen.some((line,row)=>line!==this.previousScreen[row]&&(imageRows.has(line)||previousImageRows.has(this.previousScreen[row]??""))),imageCellsNeedRedraw=!imageAnchorsNeedRedraw&&this.imageProtocol==="kitty"&&imageRows.size>0&&screen.some((line,row)=>{if(!imageRows.has(line))return!1;
862
+ let placementRows=getKittyImagePlacementRows(line);if(placementRows===void 0)return!1;for(let coveredRow=row;coveredRow<row+placementRows;coveredRow++)if(coveredRow<screen.length&&screen[coveredRow]!==this.previousScreen[coveredRow])return!0;return!1}),imagesNeedRedraw=imageAnchorsNeedRedraw||imageCellsNeedRedraw,redrawImages=fullRedraw||imagesNeedRedraw,hadUploadedKittyImages=this.uploadedKittyImages.size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):
863
+ {lines:screen,evictedImageDeletion:""},buffer=BEGIN_SYNCHRONIZED_OUTPUT;if(fullRedraw){this.fullRedrawCount+=1;let clearImages=this.imageProtocol==="kitty"&&hadUploadedKittyImages?deleteAllKittyPlacements():this.deleteKittyImages();buffer+=`${clearImages}\x1B[2J`}else imagesNeedRedraw&&(this.imageProtocol==="iterm2"?buffer+="\x1B[2J":this.imageProtocol==="kitty"&&(buffer+=deleteAllKittyPlacements()));if(buffer+=preparedKittyScreen.evictedImageDeletion,redrawImages&&this.imageProtocol==="kitty"&&
864
+ imageRows.size>0){for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||(buffer+=`\x1B[${row+1};1H\x1B[2K`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.lines[row]??"")||(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`);for(let row=0;row<height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.
865
+ lines[row]??"")&&(buffer+=`\x1B[${row+1};1H${preparedKittyScreen.lines[row]??""}`)}else{let moved=fullRedraw||redrawImages||(process.env.HUMAIN_TERMINAL_TUI_SCROLL_ROWS||process.env.PI_TUI_SCROLL_ROWS)==="0"?void 0:this.findMovedRows(screen,height,imageRows.size>0||previousImageRows.size>0);moved&&(buffer+=`\x1B[${moved.top+1};${moved.bottom+1}r`,buffer+=moved.up>0?`\x1B[${moved.bottom+1};1H${`
866
+ `.repeat(moved.up)}`:`\x1B[${moved.top+1};1H${"\x1BM".repeat(-moved.up)}`,buffer+="\x1B[r");for(let row=0;row<height;row++){if(!fullRedraw&&!imagesNeedRedraw){let shown=this.previousScreen[row];if(moved&&row>=moved.top&&row<=moved.bottom){let from=row+moved.up;shown=from>=moved.top&&from<=moved.bottom?this.previousScreen[from]:void 0}if(screen[row]===shown)continue}buffer+=`\x1B[${row+1};1H\x1B[2K${preparedKittyScreen.lines[row]??""}`}}cursorPos?(buffer+=`\x1B[${cursorPos.row+1};${Math.min(width,
867
+ cursorPos.col)+1}H`,buffer+=this.getShowHardwareCursor()?"\x1B[?25h":"\x1B[?25l"):buffer+="\x1B[?25l",buffer+=END_SYNCHRONIZED_OUTPUT,this.terminal.write(buffer),this.previousScreen=screen,this.previousScreenWidth=width,this.previousScreenHeight=height,this.currentLayout=nextLayout}};import*as fs2 from"node:fs";import*as os from"node:os";import*as path3 from"node:path";var OSC133_ZONE_PREFIX3=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/,KITTY_SEQUENCE_PREFIX="\x1B_G",MAX_RENDER_WRITE_CHARS=1024*1024,CURSOR_SHOW="\x1B[?25h",CURSOR_HIDE="\x1B[?25l",BoundedTerminalWriter=class{buffer="";writtenChars=0;write;constructor(write){this.write=write}append(value){let offset=0;for(;offset<value.length;){let capacity=MAX_RENDER_WRITE_CHARS-this.buffer.length;if(capacity===0){this.flush();continue}let end=Math.min(value.length,offset+capacity);if(end<value.length&&value.charCodeAt(
868
+ end-1)>=55296&&value.charCodeAt(end-1)<=56319&&value.charCodeAt(end)>=56320&&value.charCodeAt(end)<=57343&&end--,end===offset){this.flush();continue}this.buffer+=value.slice(offset,end),offset=end,this.buffer.length===MAX_RENDER_WRITE_CHARS&&this.flush()}}flush(){this.buffer&&(this.write(this.buffer),this.writtenChars+=this.buffer.length,this.buffer="")}get length(){return this.writtenChars+this.buffer.length}};function parseKittyImageHeader(line){let sequenceStart=line.indexOf(KITTY_SEQUENCE_PREFIX);
869
+ if(sequenceStart===-1)return;let paramsStart=sequenceStart+KITTY_SEQUENCE_PREFIX.length,paramsEnd=line.indexOf(";",paramsStart);if(paramsEnd===-1)return;let ids=[],rows=1;for(let param of line.slice(paramsStart,paramsEnd).split(",")){let[key,value]=param.split("=",2);if(value===void 0)continue;let numberValue=Number(value);!Number.isInteger(numberValue)||numberValue<=0||numberValue>4294967295||(key==="i"?ids.push(numberValue):key==="r"&&(rows=numberValue))}return{ids,rows}}function extractKittyImageIds(line){
870
+ return parseKittyImageHeader(line)?.ids??[]}function extractKittyImageRows(line){return parseKittyImageHeader(line)?.rows??1}function isTermuxSession(){return!!process.env.TERMUX_VERSION}var TuiMainScreen=class extends TuiBase{mode="regular";shownLength=0;restoredLines;previousKittyImageIds=new Set;previousWidth=0;previousHeight=0;cursorRow=0;hardwareCursorRow=0;maxLinesRendered=0;previousViewportTop=0;captureRenderState(){let previousLines=new Array(this.shownLength);for(let i=0;i<this.shownLength;i++)
871
+ previousLines[i]=this.shownLine(i);return{previousLines,previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.frameLive=void 0,this.restoredLines=state.previousLines.map(line=>isImageLine(line)?"":line),this.shownLength=this.restoredLines.length,this.previousKittyImageIds=new Set,this.previousWidth=state.
872
+ previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.cursorRow,this.hardwareCursorRow=state.hardwareCursorRow,this.maxLinesRendered=state.maxLinesRendered,this.previousViewportTop=state.previousViewportTop}resetRenderState(){this.frameLive=void 0,this.restoredLines=void 0,this.shownLength=0,this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}beforeTerminalStop(options){if(options.preserveScreen||
873
+ this.shownLength===0)return;this.terminal.write(" ");let lineDiff=this.shownLength-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
874
+ `)}shownLinesForTest(){return this.captureRenderState().previousLines}unresolvedLines=[];resolvedLines=[];resolvedWithHardwareCursor=!1;resolveFrameFakeCursors(lines,unchanged){let showHardwareCursor=this.getShowHardwareCursor(),previous=showHardwareCursor===this.resolvedWithHardwareCursor?this.unresolvedLines:[],previousResolved=this.resolvedLines,from=previous.length===0?0:Math.min(unchanged,previous.length,lines.length),resolved=from>0?previousResolved.slice(0,from):[];resolved.length=lines.length;
875
+ let single=[""];for(let i=from;i<lines.length;i++){let line=lines[i];i<previous.length&&line===previous[i]?resolved[i]=previousResolved[i]:(single[0]=line.replace(OSC133_ZONE_PREFIX3,""),resolved[i]=this.resolveFakeCursors(single)[0])}return this.unresolvedLines=lines,this.resolvedLines=resolved,this.resolvedWithHardwareCursor=showHardwareCursor,resolved.slice()}rawLines=[];rawImageRows=[];frameLive;singleLine=[""];writtenLine(line){let single=this.singleLine;single[0]=line;let written=this.applyLineResets(
876
+ single)[0];return single[0]="",written}shownLine(row){return this.restoredLines!==void 0?this.restoredLines[row]:this.writtenLine(this.rawLines[row])}finishLines(raw,unchanged,previousRawTail){let previousRawLength=previousRawTail===void 0?this.rawLines.length:unchanged+previousRawTail.length,previousRaw=this.rawLines,from=Math.min(unchanged,previousRawLength,raw.length),previousRows=this.rawImageRows,imageRows=previousRows.filter(row=>row<from),next=imageRows.length;for(let i=from;i<raw.length;i++){
877
+ let line=raw[i],image;if(i<previousRawLength&&line===(previousRawTail===void 0?previousRaw[i]:previousRawTail[i-unchanged])){for(;next<previousRows.length&&previousRows[next]<i;)next++;image=previousRows[next]===i}else image=isImageLine(line);image&&imageRows.push(i)}return this.rawLines=raw,this.rawImageRows=imageRows,{imageLines:imageRows.length}}renderChangedLines(live,root,unchanged,height){let resolved=this.resolvedLines,raw=this.rawLines;if(unchanged<=0||this.unresolvedLines!==root||resolved.
878
+ length!==root.length||raw===resolved||raw===root||raw.length<unchanged||this.restoredLines!==void 0||this.shownLength!==raw.length)return;let source=live.lines,rootTail=root.slice(unchanged);root.length=unchanged;for(let i=unchanged;i<source.length;i++)root.push(source[i]);let resolvedTail=resolved.slice(unchanged);resolved.length=unchanged;let single=[""];for(let i=unchanged;i<root.length;i++){let line=root[i],k=i-unchanged;k<rootTail.length&&line===rootTail[k]?resolved.push(resolvedTail[k]):(single[0]=
879
+ line.replace(OSC133_ZONE_PREFIX3,""),resolved.push(this.resolveFakeCursors(single)[0]))}let rawTail=raw.slice(unchanged);raw.length=unchanged;for(let i=unchanged;i<resolved.length;i++)raw.push(resolved[i]);let cursorPos=this.extractCursorPosition(raw,height),finished=this.finishLines(raw,unchanged,rawTail);return{raw,previousRawTail:rawTail,imageLines:finished.imageLines,cursorPos}}collectKittyImageIds(rows){let ids=new Set;for(let i=0;i<rows.length;i++)for(let id of extractKittyImageIds(rows.source(
880
+ i)))ids.add(id);return ids}deleteKittyImages(ids){let buffer="";for(let id of ids)buffer+=deleteKittyImage(id);return buffer}getKittyImageReservedRows(rows,index,maxIndex=rows.length-1){let imageRows=extractKittyImageRows(index<rows.length?rows.written(index):"");if(imageRows<=1)return 1;let maxRows=Math.min(imageRows,maxIndex-index+1,rows.length-index),reservedRows=1;for(;reservedRows<maxRows;){let line=index+reservedRows<rows.length?rows.written(index+reservedRows):"";if(isImageLine(line)||visibleWidth(
881
+ line)>0)break;reservedRows++}return reservedRows}expandChangedRangeForKittyImages(firstChanged,lastChanged,shown,frame){let expandedFirstChanged=firstChanged,expandedLastChanged=lastChanged,expandForLines=rows=>{for(let i=0;i<rows.length;i++){if(extractKittyImageIds(rows.source(i)).length===0)continue;let blockEnd=i+this.getKittyImageReservedRows(rows,i)-1;(i>=firstChanged||i<=lastChanged&&blockEnd>=firstChanged)&&(expandedFirstChanged=Math.min(expandedFirstChanged,i),expandedLastChanged=Math.max(
882
+ expandedLastChanged,blockEnd))}};return expandForLines(shown),expandForLines(frame),{firstChanged:expandedFirstChanged,lastChanged:expandedLastChanged}}deleteChangedKittyImages(firstChanged,lastChanged,shown){if(firstChanged<0||lastChanged<firstChanged||this.previousKittyImageIds.size===0)return"";let ids=new Set,maxLine=Math.min(lastChanged,shown.length-1);for(let i=firstChanged;i<=maxLine;i++)for(let id of extractKittyImageIds(shown.source(i)))ids.add(id);return this.deleteKittyImages(ids)}noteShown(length){
883
+ this.restoredLines=void 0,this.shownLength=length}doRender(){if(this.stopped)return;let width=this.terminal.columns,height=this.terminal.rows,widthChanged=this.previousWidth!==0&&this.previousWidth!==width,heightChanged=this.previousHeight!==0&&this.previousHeight!==height,previousBufferLength=this.previousHeight>0?this.previousViewportTop+this.previousHeight:height,prevViewportTop=heightChanged?Math.max(0,previousBufferLength-height):this.previousViewportTop,viewportTop=prevViewportTop,hardwareCursorRow=this.
884
+ hardwareCursorRow,computeLineDiff=targetRow=>{let currentScreenRow=hardwareCursorRow-prevViewportTop;return targetRow-viewportTop-currentScreenRow},shownLength=this.shownLength,shownRaw=this.rawLines,restoredLines=this.restoredLines,live=renderLiveLines(this,width),before=this.frameLive,unchanged=0;live!==void 0&&before?.live===live&&before.width===width&&this.previousWidth===width&&this.previousHeight===height&&this.getShowHardwareCursor()===this.resolvedWithHardwareCursor&&!this.hasOverlayEntries&&
885
+ (unchanged=Math.min(live.changedSince(before.revision),before.lines.length,live.lines.length-height,shownLength-height)),unchanged=Math.max(0,unchanged);let changed=live!==void 0&&before!==void 0&&unchanged>0?this.renderChangedLines(live,before.lines,unchanged,height):void 0,raw,cursorPos,finished,shownRawTail;if(changed!==void 0)this.frameLive={live,revision:live.revision,width,lines:before.lines},raw=changed.raw,shownRawTail=changed.previousRawTail,cursorPos=changed.cursorPos,finished=changed;else{
886
+ let root=live===void 0?renderSharedLines(this,width):before?.live===live&&before.width===width&&before.revision===live.revision?before.lines:live.lines.slice();this.frameLive=live===void 0?void 0:{live,revision:live.revision,width,lines:root},raw=this.resolveFrameFakeCursors(root,unchanged),this.hasOverlayEntries&&(raw=this.compositeOverlays(raw,width,height)),cursorPos=this.extractCursorPosition(raw,height),finished=this.finishLines(raw,unchanged)}let frameLength=raw.length,frame={length:frameLength,
887
+ written:row=>this.writtenLine(raw[row]),source:row=>raw[row]},shownSource=row=>restoredLines!==void 0?restoredLines[row]:shownRawTail!==void 0&&row>=unchanged?shownRawTail[row-unchanged]:shownRaw[row],shown={length:shownLength,written:row=>restoredLines!==void 0?restoredLines[row]:this.writtenLine(shownSource(row)),source:shownSource},imagesShown=finished.imageLines>0||this.previousKittyImageIds.size>0,collectKittyImageIds=rows=>imagesShown?this.collectKittyImageIds(rows):new Set,fullRender=clear=>{
888
+ this.fullRedrawCount+=1;let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),clear&&(output2.append(this.deleteKittyImages(this.previousKittyImageIds)),output2.append("\x1B[2J\x1B[H\x1B[3J"));for(let i=0;i<frameLength;i++){i>0&&output2.append(`\r
889
+ `);let line=frame.written(i),imageReservedRows=isImageLine(line)?this.getKittyImageReservedRows(frame,i):1;if(imageReservedRows>1&&imageReservedRows<=height){for(let row=1;row<imageReservedRows;row++)output2.append(`\r
890
+ `);output2.append(`\x1B[${imageReservedRows-1}A`),output2.append(line),output2.append(`\x1B[${imageReservedRows-1}B`),i+=imageReservedRows-1;continue}output2.append(line)}output2.append("\x1B[?2026l"),this.cursorRow=Math.max(0,frameLength-1),this.hardwareCursorRow=this.cursorRow,clear?this.maxLinesRendered=frameLength:this.maxLinesRendered=Math.max(this.maxLinesRendered,frameLength);let bufferLength=Math.max(height,frameLength);this.previousViewportTop=Math.max(0,bufferLength-height),this.positionHardwareCursor(
891
+ cursorPos,frameLength,output2),this.noteShown(frameLength),this.previousKittyImageIds=collectKittyImageIds(frame),this.previousWidth=width,this.previousHeight=height},redrawLogDirectory=(process.env.HUMAIN_TERMINAL_TUI_DEBUG_REDRAW??process.env.PI_TUI_DEBUG_REDRAW)==="1"?this.logDirectory:void 0,logRedraw=reason=>{if(redrawLogDirectory===void 0)return;let logPath=path3.join(redrawLogDirectory,"humain-tui-debug.log"),msg=`[${new Date().toISOString()}] fullRender: ${reason} (prev=${shownLength}, n\
892
+ ew=${frameLength}, height=${height})
893
+ `;fs2.mkdirSync(path3.dirname(logPath),{recursive:!0}),fs2.appendFileSync(logPath,msg)};if(shownLength===0&&!widthChanged&&!heightChanged){logRedraw("first render"),fullRender(!1);return}if(widthChanged){logRedraw(`terminal width changed (${this.previousWidth} -> ${width})`),fullRender(!0);return}if(heightChanged&&!isTermuxSession()){logRedraw(`terminal height changed (${this.previousHeight} -> ${height})`),fullRender(!0);return}if(this.getClearOnShrink()&&frameLength<this.maxLinesRendered&&!this.
894
+ hasOverlayEntries){logRedraw(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),fullRender(!0);return}let firstChanged=-1,lastChanged=-1,maxLines=Math.max(frameLength,shownLength);for(let i=Math.min(unchanged,shownLength);i<maxLines;i++){let same;if(i>=shownLength||i>=frameLength)same=restoredLines!==void 0&&i<shownLength&&restoredLines[i]==="";else if(restoredLines!==void 0)same=restoredLines[i]===frame.written(i);else{let before2=shownSource(i),after=raw[i];same=before2===after||this.
895
+ writtenLine(before2)===this.writtenLine(after)}if(!same){if(firstChanged===-1&&(firstChanged=i,i<prevViewportTop&&i<frameLength&&!imagesShown)){lastChanged=i;break}lastChanged=i}}let appendedLines=frameLength>shownLength;if(appendedLines&&(firstChanged===-1&&(firstChanged=shownLength),lastChanged=frameLength-1),firstChanged!==-1&&imagesShown){let expandedRange=this.expandChangedRangeForKittyImages(firstChanged,lastChanged,shown,frame);firstChanged=expandedRange.firstChanged,lastChanged=expandedRange.
896
+ lastChanged}let appendStart=appendedLines&&firstChanged===shownLength&&firstChanged>0;if(firstChanged===-1){this.positionHardwareCursor(cursorPos,frameLength,new BoundedTerminalWriter(data=>this.terminal.write(data))),this.previousViewportTop=prevViewportTop,this.previousHeight=height,restoredLines===void 0&&this.noteShown(frameLength);return}if(firstChanged>=frameLength){let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));if(shownLength>frameLength){output2.append("\x1B[?2026h"),
897
+ output2.append(this.deleteChangedKittyImages(firstChanged,lastChanged,shown));let targetRow=Math.max(0,frameLength-1);if(targetRow<prevViewportTop){logRedraw(`deleted lines moved viewport up (${targetRow} < ${prevViewportTop})`),fullRender(!0);return}let lineDiff2=computeLineDiff(targetRow);lineDiff2>0?output2.append(`\x1B[${lineDiff2}B`):lineDiff2<0&&output2.append(`\x1B[${-lineDiff2}A`),output2.append("\r");let extraLines=shownLength-frameLength;if(extraLines>height){logRedraw(`extraLines > he\
898
+ ight (${extraLines} > ${height})`),fullRender(!0);return}let clearStartOffset=frameLength===0?0:1;extraLines>0&&clearStartOffset>0&&output2.append(`\x1B[${clearStartOffset}B`);for(let i=0;i<extraLines;i++)output2.append("\r\x1B[2K"),i<extraLines-1&&output2.append("\x1B[1B");let moveBack=Math.max(0,extraLines-1+clearStartOffset);moveBack>0&&output2.append(`\x1B[${moveBack}A`),output2.append("\x1B[?2026l"),this.cursorRow=targetRow,this.hardwareCursorRow=targetRow}this.positionHardwareCursor(cursorPos,
899
+ frameLength,output2),this.noteShown(frameLength),this.previousKittyImageIds=collectKittyImageIds(frame),this.previousWidth=width,this.previousHeight=height,this.previousViewportTop=prevViewportTop;return}if(firstChanged<prevViewportTop){logRedraw(`firstChanged < viewportTop (${firstChanged} < ${prevViewportTop})`),fullRender(!0);return}let output=new BoundedTerminalWriter(data=>this.terminal.write(data));output.append("\x1B[?2026h"),output.append(this.deleteChangedKittyImages(firstChanged,lastChanged,
900
+ shown));let prevViewportBottom=prevViewportTop+height-1,moveTargetRow=appendStart?firstChanged-1:firstChanged;if(moveTargetRow>prevViewportBottom){let currentScreenRow=Math.max(0,Math.min(height-1,hardwareCursorRow-prevViewportTop)),moveToBottom=height-1-currentScreenRow;moveToBottom>0&&output.append(`\x1B[${moveToBottom}B`);let scroll=moveTargetRow-prevViewportBottom;output.append(`\r
901
+ `.repeat(scroll)),prevViewportTop+=scroll,viewportTop+=scroll,hardwareCursorRow=moveTargetRow}let lineDiff=computeLineDiff(moveTargetRow);lineDiff>0?output.append(`\x1B[${lineDiff}B`):lineDiff<0&&output.append(`\x1B[${-lineDiff}A`),output.append(appendStart?`\r
902
+ `:"\r");let renderEnd=Math.min(lastChanged,frameLength-1);for(let i=firstChanged;i<=renderEnd;i++){i>firstChanged&&output.append(`\r
903
+ `);let line=frame.written(i),isImage=isImageLine(line),imageReservedRows=isImage?this.getKittyImageReservedRows(frame,i,renderEnd):1;if(imageReservedRows>1){let imageStartScreenRow=i-viewportTop;if(imageStartScreenRow<0||imageStartScreenRow+imageReservedRows>height){logRedraw(`kitty image pre-clear would scroll (${imageStartScreenRow} + ${imageReservedRows} > ${height})`),fullRender(!0);return}output.append("\x1B[2K");for(let row=1;row<imageReservedRows;row++)output.append(`\r
904
+ \x1B[2K`);output.append(`\x1B[${imageReservedRows-1}A`),output.append(line),output.append(`\x1B[${imageReservedRows-1}B`),i+=imageReservedRows-1;continue}if(output.append("\x1B[2K"),!isImage&&visibleWidth(line)>width){let crashLogPath=path3.join(this.logDirectory??os.tmpdir(),"humain-tui-crash.log"),crashData=[`Crash at ${new Date().toISOString()}`,`Terminal width: ${width}`,`Line ${i} visible width: ${visibleWidth(line)}`,"","=== All rendered lines ===",...Array.from({length:frameLength},(_2,idx)=>{
905
+ let l3=frame.written(idx);return`[${idx}] (w=${visibleWidth(l3)}) ${l3}`}),""].join(`
906
+ `);fs2.mkdirSync(path3.dirname(crashLogPath),{recursive:!0}),fs2.writeFileSync(crashLogPath,crashData),this.stop();let errorMsg=[`Rendered line ${i} exceeds terminal width (${visibleWidth(line)} > ${width}).`,"","This is likely caused by a custom TUI component not truncating its output.","Use visibleWidth() to measure and truncateToWidth() to truncate lines.","",`Debug log written to: ${crashLogPath}`].join(`
907
+ `);throw new Error(errorMsg)}output.append(line)}let finalCursorRow=renderEnd;if(shownLength>frameLength){if(renderEnd<frameLength-1){let moveDown=frameLength-1-renderEnd;output.append(`\x1B[${moveDown}B`),finalCursorRow=frameLength-1}let extraLines=shownLength-frameLength;for(let i=frameLength;i<shownLength;i++)output.append(`\r
908
+ \x1B[2K`);output.append(`\x1B[${extraLines}A`)}if(output.append("\x1B[?2026l"),(process.env.HUMAIN_TERMINAL_TUI_DEBUG??process.env.PI_TUI_DEBUG)==="1"){let debugDir="/tmp/tui";fs2.mkdirSync(debugDir,{recursive:!0});let debugPath=path3.join(debugDir,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),debugData=[`firstChanged: ${firstChanged}`,`viewportTop: ${viewportTop}`,`cursorRow: ${this.cursorRow}`,`height: ${height}`,`lineDiff: ${lineDiff}`,`hardwareCursorRow: ${hardwareCursorRow}`,
909
+ `renderEnd: ${renderEnd}`,`finalCursorRow: ${finalCursorRow}`,`cursorPos: ${JSON.stringify(cursorPos)}`,`newLines.length: ${frameLength}`,`previousLines.length: ${shownLength}`,"","=== newLines ===",JSON.stringify(Array.from({length:frameLength},(_2,idx)=>frame.written(idx)),null,2),"","=== previousLines ===",JSON.stringify(Array.from({length:shownLength},(_2,idx)=>shown.written(idx)),null,2),"","=== buffer ===",`[${output.length} chars written in bounded chunks]`].join(`
910
+ `);fs2.writeFileSync(debugPath,debugData)}this.cursorRow=Math.max(0,frameLength-1),this.hardwareCursorRow=finalCursorRow,this.maxLinesRendered=Math.max(this.maxLinesRendered,frameLength),this.previousViewportTop=Math.max(prevViewportTop,finalCursorRow-height+1),this.positionHardwareCursor(cursorPos,frameLength,output),this.noteShown(frameLength),this.previousKittyImageIds=collectKittyImageIds(frame),this.previousWidth=width,this.previousHeight=height}positionHardwareCursor(cursorPos,totalLines,output){
911
+ let terminal=this.terminal,together=terminal.write===ProcessTerminal.prototype.write&&terminal.showCursor===ProcessTerminal.prototype.showCursor&&terminal.hideCursor===ProcessTerminal.prototype.hideCursor;together||output.flush();let showCursor=visible=>{if(!together){visible?terminal.showCursor():terminal.hideCursor();return}output.append(visible?CURSOR_SHOW:CURSOR_HIDE),output.flush()};if(!cursorPos||totalLines<=0){showCursor(!1);return}let targetRow=Math.max(0,Math.min(cursorPos.row,totalLines-
912
+ 1)),targetCol=Math.max(0,cursorPos.col),rowDelta=targetRow-this.hardwareCursorRow,buffer="";rowDelta>0?buffer+=`\x1B[${rowDelta}B`:rowDelta<0&&(buffer+=`\x1B[${-rowDelta}A`),buffer+=`\x1B[${targetCol+1}G`,buffer&&(together?output.append(buffer):terminal.write(buffer)),this.hardwareCursorRow=targetRow,showCursor(this.getShowHardwareCursor())}};var dist_exports={};__export(dist_exports,{Box:()=>Box,CURSOR_MARKER:()=>CURSOR_MARKER,CancellableLoader:()=>CancellableLoader,CombinedAutocompleteProvider:()=>CombinedAutocompleteProvider,Container:()=>Container,Editor:()=>Editor,HStack:()=>HStack,Image:()=>Image,Input:()=>Input,Key:()=>Key,KeybindingsManager:()=>KeybindingsManager,LiveLineArray:()=>LiveLineArray,Loader:()=>Loader,Markdown:()=>Markdown,Marked:()=>Y,MouseRegion:()=>MouseRegion,ProcessTerminal:()=>ProcessTerminal,ScrollView:()=>ScrollView,
913
+ SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,applyBackgroundToLine:()=>applyBackgroundToLine,backgroundAnsi:()=>backgroundAnsi,calculateImageRows:()=>calculateImageRows,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,
914
+ colorToRgb:()=>colorToRgb,compositeTuiLine:()=>compositeTuiLine,decodeKittyPrintable:()=>decodeKittyPrintable,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,foregroundAnsi:()=>foregroundAnsi,formatProgramStatus:()=>formatProgramStatus,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,
915
+ getGifDimensions:()=>getGifDimensions,getImageDimensions:()=>getImageDimensions,getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getSelectPageIndex:()=>getSelectPageIndex,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,invalidateRenderedMarkdown:()=>invalidateRenderedMarkdown,
916
+ isAppleTerminalSession:()=>isAppleTerminalSession,isFocusable:()=>isFocusable,isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isStableRender:()=>isStableRender,isViewportTUI:()=>isViewportTUI,isWebLink:()=>isWebLink,markLiveRender:()=>markLiveRender,markReportsChanges:()=>markReportsChanges,markStableRender:()=>markStableRender,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,
917
+ oklchColor:()=>oklchColor,onCapabilitiesChange:()=>onCapabilitiesChange,parseColor:()=>parseColor,parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,renderChildLines:()=>renderChildLines,renderFakeCursor:()=>renderFakeCursor,renderImage:()=>renderImage,renderLatex:()=>renderLatex,renderLiveLines:()=>renderLiveLines,renderSharedLines:()=>renderSharedLines,renderedMarkdownGeneration:()=>renderedMarkdownGeneration,replaceControlCharacters:()=>replaceControlCharacters,
918
+ reportRenderChange:()=>reportRenderChange,reportsChanges:()=>reportsChanges,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,sanitizeTerminalText:()=>sanitizeTerminalText,sanitizeTerminalTextFrom:()=>sanitizeTerminalTextFrom,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setChangeReportsForTest:()=>setChangeReportsForTest,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,
919
+ setKittyProtocolActive:()=>setKittyProtocolActive,setRenderClockForTest:()=>setRenderClockForTest,setRenderOwner:()=>setRenderOwner,setSubtreeReportsChanges:()=>setSubtreeReportsChanges,sliceByColumn:()=>sliceByColumn,startsWithText:()=>startsWithText,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});var Box=class{childList=[];paddingX;paddingY;bgFn;backgroundReported=!1;cache;rendered;emptyLines=[];constructor(paddingX=1,paddingY=1,bgFn){this.paddingX=paddingX,this.paddingY=paddingY,this.bgFn=bgFn}get children(){return reportRenderChange(this),this.childList}set children(children){this.childList=children,reportRenderChange(this)}ownChildren(){return Object.hasOwn(this,"children")?this.children:this.childList}addChild(component){this.ownChildren().push(component),this.invalidateCache()}removeChild(component){
920
+ let children=this.ownChildren(),index=children.indexOf(component);index!==-1&&(children.splice(index,1),this.invalidateCache())}clear(){Object.hasOwn(this,"children")?this.children=[]:this.childList=[],this.invalidateCache()}setBgFn(bgFn){this.bgFn=bgFn,reportRenderChange(this)}setBackgroundReported(reported){this.backgroundReported=reported,reportRenderChange(this)}setPaddingX(paddingX){this.paddingX!==paddingX&&(this.paddingX=paddingX,this.invalidateCache())}invalidateCache(){this.cache=void 0,
921
+ this.rendered=void 0,reportRenderChange(this)}invalidate(){this.invalidateCache();for(let child of this.ownChildren())child.invalidate?.()}handleMouse(event){let contentWidth=Math.max(1,event.width-this.paddingX*2),contentY=event.y-this.paddingY,contentX=event.x-this.paddingX;if(contentY<0||contentX<0||contentX>=contentWidth)return;let rendered=this.rendered?.width===contentWidth?this.rendered:void 0,children=rendered?.children??this.ownChildren(),childY=0;for(let i=0;i<children.length;i++){let child=children[i],
922
+ childHeight=rendered?rendered.heights[i]:child.render(contentWidth).length;if(contentY>=childY&&contentY<childY+childHeight)return dispatchMouseEvent(child,{...event,x:contentX,y:contentY-childY,width:contentWidth,height:childHeight});childY+=childHeight}}render(width){let children=this.ownChildren();if(children.length===0)return setSubtreeReportsChanges(this,children===this.childList),this.emptyLines;let contentWidth=Math.max(1,width-this.paddingX*2),leftPad=" ".repeat(this.paddingX),rendered=renderChildren(
923
+ children,contentWidth,this.rendered);this.rendered=rendered;let reports=children===this.childList&&(this.bgFn===void 0||this.backgroundReported);for(let child of children)setRenderOwner(child,this),reportsChanges(child)||(reports=!1);setSubtreeReportsChanges(this,reports);let childLines=rendered.lines;if(childLines.length===0)return this.emptyLines;let bgSample=this.bgFn?this.bgFn("test"):void 0,cache=this.cache&&this.cache.width===width&&this.cache.bgSample===bgSample?this.cache:void 0;if(cache?.
924
+ childLines===childLines)return cache.lines;let result=[],reused=cache!==void 0&&cache.childLines.length===childLines.length;for(let i=0;i<this.paddingY;i++)result.push(cache?cache.lines[i]:this.applyBg("",width));for(let i=0;i<childLines.length;i++){let line=childLines[i];cache!==void 0&&i<cache.childLines.length&&cache.childLines[i]===line?result.push(cache.lines[this.paddingY+i]):(reused=!1,result.push(this.applyBg(leftPad+line,width)))}for(let i=0;i<this.paddingY;i++)result.push(cache?cache.lines[cache.
925
+ lines.length-this.paddingY+i]:this.applyBg("",width));return reused?(cache.childLines=childLines,cache.lines):(flattenLines(result),this.cache={childLines,width,bgSample,lines:result},result)}applyBg(line,width){let visLen=visibleWidth(line),padNeeded=Math.max(0,width-visLen),padded=line+" ".repeat(padNeeded),result=this.bgFn?this.bgFn(padded):padded;return line.length<=INTERNED_LINE_LENGTH?internLine(result):result}};markStableRender(Box);markReportsChanges(Box);var DEFAULT_FRAMES=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],DEFAULT_INTERVAL_MS=80,STEP_FRAME_DELAY_MS=40,Loader=class extends Text{frames=[...DEFAULT_FRAMES];intervalMs=DEFAULT_INTERVAL_MS;currentFrame=0;intervalId=null;ui=null;renderIndicatorVerbatim=!1;spinnerColorFn;messageColorFn;message="Loading...";displayText="";constructor(ui,spinnerColorFn,messageColorFn,message="Loading...",indicator){super("",1,0),this.ui=ui,this.spinnerColorFn=spinnerColorFn,
926
+ this.messageColorFn=messageColorFn,this.message=message,this.setIndicator(indicator)}render(width){return["",...super.render(width)]}start(){this.updateDisplay(),this.restartAnimation()}stop(){this.intervalId&&(clearInterval(this.intervalId),this.intervalId=null)}setText(text){this.displayText=text,super.setText(text)}getDisplayText(){return this.displayText}setMessage(message){this.message=message,this.updateDisplay()}invalidate(){super.invalidate(),this.updateDisplay()}setIndicator(indicator){
927
+ this.renderIndicatorVerbatim=indicator!==void 0,this.frames=indicator?.frames!==void 0?[...indicator.frames]:[...DEFAULT_FRAMES],this.intervalMs=indicator?.intervalMs&&indicator.intervalMs>0?indicator.intervalMs:DEFAULT_INTERVAL_MS,this.currentFrame=0,this.start()}restartAnimation(){this.stop(),!(this.frames.length<=1)&&(this.intervalId=setInterval(()=>{this.currentFrame=(this.currentFrame+1)%this.frames.length,this.updateDisplay(Math.min(STEP_FRAME_DELAY_MS,this.intervalMs/2))},this.intervalMs))}getRenderedIndicator(){
928
+ let frame=this.frames[this.currentFrame]??"";return this.renderIndicatorVerbatim?frame:this.spinnerColorFn(frame)}updateDisplay(frameDelayMs){let renderedFrame=this.getRenderedIndicator(),indicator=renderedFrame.length>0?`${renderedFrame} `:"";this.setText(`${indicator}${this.messageColorFn(this.message)}`),this.ui&&(frameDelayMs!==void 0&&this.ui.requestRenderWithin?this.ui.requestRenderWithin(frameDelayMs):this.ui.requestRender())}};var CancellableLoader=class extends Loader{abortController=new AbortController;onAbort;get signal(){return this.abortController.signal}get aborted(){return this.abortController.signal.aborted}handleInput(data){getKeybindings().matches(data,"tui.select.cancel")&&(this.abortController.abort(),this.onAbort?.())}dispose(){this.stop()}};var PASTE_MARKER_REGEX=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,PASTE_MARKER_SINGLE=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function isPasteMarker(segment){return segment.length>=10&&PASTE_MARKER_SINGLE.test(segment)}function segmentWithMarkers(text,baseSegmenter,validIds){if(validIds.size===0||!text.includes("[paste #"))return baseSegmenter.segment(text);let markers=[];for(let m of text.matchAll(PASTE_MARKER_REGEX)){let id=Number.parseInt(m[1],10);validIds.has(id)&&markers.push({start:m.
929
+ index,end:m.index+m[0].length})}if(markers.length===0)return baseSegmenter.segment(text);let baseSegments=baseSegmenter.segment(text),result=[],markerIdx=0;for(let seg of baseSegments){for(;markerIdx<markers.length&&markers[markerIdx].end<=seg.index;)markerIdx++;let marker=markerIdx<markers.length?markers[markerIdx]:null;if(marker&&seg.index>=marker.start&&seg.index<marker.end){if(seg.index===marker.start){let markerText=text.slice(marker.start,marker.end);result.push({segment:markerText,index:marker.
930
+ start,input:text})}}else result.push(seg)}return result}function graphemeAt(text,index){let code=text.charCodeAt(index);if(code>=55296&&code<=56319){let next=text.charCodeAt(index+1);if(next>=56320&&next<=57343)return getGraphemeSegmenter().segment(text).containing(index+1)}return getGraphemeSegmenter().segment(text).containing(index)}function wordWrapLine(line,maxWidth,preSegmented){if(!line||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(!preSegmented){let standaloneWidth=standaloneTextWidth(
931
+ line);if(canWrapStandalone(line,standaloneWidth,maxWidth))return wordWrapStandaloneLine(line,maxWidth,standaloneWidth)}if(visibleWidth(line)<=maxWidth)return[{text:line,startIndex:0,endIndex:line.length}];let chunks=[],segments=preSegmented??[...getGraphemeSegmenter().segment(line)],currentWidth=0,chunkStart=0,wrapOppIndex=-1,wrapOppWidth=0;for(let i=0;i<segments.length;i++){let seg=segments[i],grapheme=seg.segment,gWidth=visibleWidth(grapheme),charIndex=seg.index,isWs=!isPasteMarker(grapheme)&&
932
+ isWhitespaceChar(grapheme);if(currentWidth+gWidth>maxWidth&&(wrapOppIndex>=0&&currentWidth-wrapOppWidth+gWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<charIndex&&(chunks.push({text:line.slice(chunkStart,charIndex),startIndex:chunkStart,endIndex:charIndex}),chunkStart=charIndex,currentWidth=0),wrapOppIndex=-1),gWidth>maxWidth&&preSegmented){let subChunks=wordWrapLine(
933
+ grapheme,maxWidth);for(let j2=0;j2<subChunks.length-1;j2++){let sc=subChunks[j2];chunks.push({text:sc.text,startIndex:charIndex+sc.startIndex,endIndex:charIndex+sc.endIndex})}let last=subChunks[subChunks.length-1];chunkStart=charIndex+last.startIndex,currentWidth=visibleWidth(last.text),wrapOppIndex=-1;continue}currentWidth+=gWidth;let next=segments[i+1];if(isWs&&next&&(isPasteMarker(next.segment)||!isWhitespaceChar(next.segment)))wrapOppIndex=next.index,wrapOppWidth=currentWidth;else if(!isWs&&
934
+ next&&!isWhitespaceChar(next.segment)){let isCjk=!isPasteMarker(grapheme)&&cjkBreakRegex.test(grapheme),nextIsCjk=!isPasteMarker(next.segment)&&cjkBreakRegex.test(next.segment);(isCjk||nextIsCjk)&&(wrapOppIndex=next.index,wrapOppWidth=currentWidth)}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:line.length}),chunks}function standaloneCharWidth(code){return code<12288?code>=32&&code<=126||code>=160&&code<=767&&code!==173||code>=8208&&code<=8231||code>=8592&&code<=
935
+ 8959||code>=9472&&code<=9724?1:0:code<=12329||code>=12353&&code<=12438||code>=12445&&code<=12447||code>=12449&&code<=12543||code>=13312&&code<=19903||code>=19968&&code<=40959||code>=44032&&code<=55203||code>=65281&&code<=65376||code>=65504&&code<=65510?2:0}function standaloneTextWidth(text){let width=0;for(let i=0;i<text.length;i++){let charWidth=standaloneCharWidth(text.charCodeAt(i));if(charWidth===0)return-1;width+=charWidth}return width}function canWrapStandalone(line,lineWidth,maxWidth){return lineWidth>=
936
+ 0&&(maxWidth>=2||lineWidth===line.length)}function editorLineWidth(line){let width=standaloneTextWidth(line);return width>=0?width:visibleWidth(line)}function isStandaloneWhitespace(line,i,code){return code===32||code>126&&isWhitespaceChar(line[i])}function wordWrapStandaloneLine(line,maxWidth,lineWidth){let length=line.length;if(length===0||maxWidth<=0)return[{text:"",startIndex:0,endIndex:0}];if(lineWidth<=maxWidth)return[{text:line,startIndex:0,endIndex:length}];let chunks=[],currentWidth=0,chunkStart=0,
937
+ wrapOppIndex=-1,wrapOppWidth=0,code=line.charCodeAt(0),isWs=isStandaloneWhitespace(line,0,code);for(let i=0;i<length;i++){let charWidth=code<12288?1:2;if(currentWidth+charWidth>maxWidth&&(wrapOppIndex>=0&&currentWidth-wrapOppWidth+charWidth<=maxWidth?(chunks.push({text:line.slice(chunkStart,wrapOppIndex),startIndex:chunkStart,endIndex:wrapOppIndex}),chunkStart=wrapOppIndex,currentWidth-=wrapOppWidth):chunkStart<i&&(chunks.push({text:line.slice(chunkStart,i),startIndex:chunkStart,endIndex:i}),chunkStart=
938
+ i,currentWidth=0),wrapOppIndex=-1),currentWidth+=charWidth,i+1<length){let nextCode=line.charCodeAt(i+1),nextIsWs=isStandaloneWhitespace(line,i+1,nextCode);isWs?nextIsWs||(wrapOppIndex=i+1,wrapOppWidth=currentWidth):!nextIsWs&&(code>126||nextCode>126)&&(cjkBreakRegex.test(line[i])||cjkBreakRegex.test(line[i+1]))&&(wrapOppIndex=i+1,wrapOppWidth=currentWidth),code=nextCode,isWs=nextIsWs}}return chunks.push({text:line.slice(chunkStart),startIndex:chunkStart,endIndex:length}),chunks}function cloneEditorSnapshot(snapshot){
939
+ return{state:{lines:[...snapshot.state.lines],cursorLine:snapshot.state.cursorLine,cursorCol:snapshot.state.cursorCol},pastes:new Map(snapshot.pastes),pasteCounter:snapshot.pasteCounter}}var SLASH_COMMAND_SELECT_LIST_LAYOUT={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS=20,DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS=["@","#"],unquotedAutocompleteSuffixRegex=new RegExp(`(?:(?!${autocompleteSeparatorRegex.source}).)*`,"u"),autocompleteTokenStartSource=`${autocompleteBoundaryRegex.
940
+ source}[([{<\`]*`;function escapeCharacterClass(value){return value.replace(/[\\^$.*+?()[\]{}|-]/g,"\\$&")}function buildTriggerPattern(triggerCharacters){return new RegExp(`${autocompleteTokenStartSource}(?:@"[^"]*|[${triggerCharacters.map(escapeCharacterClass).join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function buildDebouncePattern(triggerCharacters){let escapedWithoutAt=triggerCharacters.filter(character=>character!=="@").map(escapeCharacterClass);return new RegExp(`${autocompleteTokenStartSource}\
941
+ (?:@(?:"[^"]*|${unquotedAutocompleteSuffixRegex.source})|[${escapedWithoutAt.join("")}]${unquotedAutocompleteSuffixRegex.source})$`,"u")}function createScrollBorder(direction,hiddenLineCount,width){let availableWidth=Math.max(0,width),label=` ${direction} ${hiddenLineCount} more `,labelWidth=visibleWidth(label);if(labelWidth+2<=availableWidth){let leftWidth=Math.floor((availableWidth-labelWidth)/2);return"\u2500".repeat(leftWidth)+label+"\u2500".repeat(availableWidth-leftWidth-labelWidth)}let indicator=`\
942
+ \u2500\u2500\u2500 ${direction} ${hiddenLineCount} more `,remaining=availableWidth-visibleWidth(indicator);if(remaining>=0)return indicator+"\u2500".repeat(remaining);let ellipsis="...".slice(0,availableWidth),indicatorWidth=availableWidth-visibleWidth(ellipsis);return sliceByColumn(indicator,0,indicatorWidth,!0)+ellipsis}var Editor=class{state={lines:[""],cursorLine:0,cursorCol:0};focused=!1;get capturesViewportInput(){return this.autocompleteState!==null}tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[
943
+ ...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];autocompleteTriggerPattern=buildTriggerPattern(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=buildDebouncePattern(this.autocompleteTriggerCharacters);autocompleteList;autocompleteState=null;autocompletePrefix="";autocompleteMaxVisible=5;autocompleteAbort;autocompleteDebounceTimer;autocompleteRequestTask=Promise.resolve();autocompleteStartToken=0;autocompleteRequestId=0;pastes=new Map;pasteCounter=0;pasteBuffer="";isInPaste=!1;history=[];historyIndex=-1;historyDraft=null;killRing=new KillRing;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new UndoStack(
944
+ cloneEditorSnapshot);onSubmit;onChange;disableSubmit=!1;constructor(tui,theme,options={}){this.tui=tui,this.theme=theme,this.borderColor=theme.borderColor;let paddingX=options.paddingX??0;this.paddingX=Number.isFinite(paddingX)?Math.max(0,Math.floor(paddingX)):0;let maxVisible=options.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5}wrapCache={width:-1,pasteIds:"",lines:[]};wrapCacheFor(width){let pasteIds=[...this.
945
+ pastes.keys()].join(","),cache=this.wrapCache;return cache.width!==width||cache.pasteIds!==pasteIds?this.wrapCache={width,pasteIds,lines:[]}:cache.lines.length>this.state.lines.length&&(cache.lines.length=this.state.lines.length),this.wrapCache.lines}wrapLine(cache,index,line,width){let known=cache[index];if(known!==void 0&&known.text===line)return known.chunks;let standaloneWidth=this.hasNoPasteMarkers(line)?standaloneTextWidth(line):-1,chunks=canWrapStandalone(line,standaloneWidth,width)?wordWrapStandaloneLine(
946
+ line,width,standaloneWidth):wordWrapLine(line,width,[...this.segment(line,"grapheme")]);return cache[index]={text:line,chunks},chunks}validPasteIds(){return new Set(this.pastes.keys())}segment(text,mode){return segmentWithMarkers(text,mode==="word"?getWordSegmenter():getGraphemeSegmenter(),this.validPasteIds())}hasNoPasteMarkers(text){return this.pastes.size===0||!text.includes("[paste #")}firstGrapheme(text){return this.hasNoPasteMarkers(text)?graphemeAt(text,0):[...this.segment(text,"grapheme")][0]}lastGrapheme(text){
947
+ if(this.hasNoPasteMarkers(text))return graphemeAt(text,text.length-1);let graphemes=[...this.segment(text,"grapheme")];return graphemes[graphemes.length-1]}graphemeContaining(text,index){if(!(index<0||index>=text.length)){if(this.hasNoPasteMarkers(text))return graphemeAt(text,index);for(let seg of this.segment(text,"grapheme")){if(seg.index>index)break;if(index<seg.index+seg.segment.length)return seg}}}getPaddingX(){return this.paddingX}setPaddingX(padding){let newPadding=Number.isFinite(padding)?
948
+ Math.max(0,Math.floor(padding)):0;this.paddingX!==newPadding&&(this.paddingX=newPadding,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(maxVisible){let newMaxVisible=Number.isFinite(maxVisible)?Math.max(3,Math.min(20,Math.floor(maxVisible))):5;this.autocompleteMaxVisible!==newMaxVisible&&(this.autocompleteMaxVisible=newMaxVisible,this.tui.requestRender())}setAutocompleteProvider(provider){this.cancelAutocomplete(),this.autocompleteProvider=
949
+ provider,this.setAutocompleteTriggerCharacters(provider.triggerCharacters??[])}addToHistory(text){let trimmed=text.trim();trimmed&&(this.history.length>0&&this.history[0]===trimmed||(this.history.unshift(trimmed),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===""}isOnFirstVisualLine(){let visualLines=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===0}isOnLastVisualLine(){let visualLines=this.
950
+ buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(visualLines)===visualLines.length-1}navigateHistory(direction){if(this.lastAction=null,this.history.length===0)return;let newIndex=this.historyIndex-direction;if(!(newIndex<-1||newIndex>=this.history.length))if(this.historyIndex===-1&&newIndex>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=newIndex,this.historyIndex===-1){let draft=this.historyDraft;this.historyDraft=null,draft?(this.
951
+ state=draft,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal("")}else this.setTextInternal(this.history[this.historyIndex]||"",direction===-1?"start":"end")}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(text,cursorPlacement="end"){let lines=text.split(`
952
+ `);this.state.lines=lines.length===0?[""]:lines,this.state.cursorLine=cursorPlacement==="start"?0:this.state.lines.length-1,this.setCursorCol(cursorPlacement==="start"?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){this.renderedText=void 0}renderTopBorder(width,hiddenLineCount){let border=hiddenLineCount>0?createScrollBorder("\u2191",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderBottomBorder(width,hiddenLineCount){
953
+ let border=hiddenLineCount>0?createScrollBorder("\u2193",hiddenLineCount,width):"\u2500".repeat(width);return this.borderColor(border)}renderedText;isRenderedText(known,width,terminalRows,pasteIds){let lines=this.state.lines;if(known.width!==width||known.paddingX!==this.paddingX||known.terminalRows!==terminalRows||known.focused!==this.focused||known.pasteIds!==pasteIds||known.cursorLine!==this.state.cursorLine||known.cursorCol!==this.state.cursorCol||known.scrollOffset!==this.scrollOffset||known.
954
+ lines.length!==lines.length)return!1;for(let i=0;i<lines.length;i++)if(known.lines[i]!==lines[i])return!1;return!0}render(width){let maxPadding=Math.max(0,Math.floor((width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),contentWidth=Math.max(1,width-paddingX*2),layoutWidth=Math.max(1,contentWidth-(paddingX?0:1));this.lastWidth=layoutWidth;let terminalRows=this.tui.terminal.rows,showAutocomplete=!!(this.autocompleteState&&this.autocompleteList),known=this.renderedText;if(!showAutocomplete&&known!==
955
+ void 0){let pasteIds=this.pastes.size===0?"":[...this.pastes.keys()].join(",");if(this.isRenderedText(known,width,terminalRows,pasteIds)){this.renderedVisibleLineCount=known.visibleLineCount,this.renderedAutocompleteHeight=0;let top=this.renderTopBorder(width,this.scrollOffset),bottom=this.renderBottomBorder(width,known.linesBelow),result2=known.result;if(top===result2[0]&&bottom===result2[result2.length-1])return result2.slice();let lines=[top,...known.textLines,bottom];return known.result=lines,
956
+ lines.slice()}}this.renderedText=void 0;let layoutLines=this.layoutText(layoutWidth),maxVisibleLines=Math.max(5,Math.floor(terminalRows*.3)),cursorLineIndex=layoutLines.findIndex(line=>line.hasCursor);cursorLineIndex===-1&&(cursorLineIndex=0),cursorLineIndex<this.scrollOffset?this.scrollOffset=cursorLineIndex:cursorLineIndex>=this.scrollOffset+maxVisibleLines&&(this.scrollOffset=cursorLineIndex-maxVisibleLines+1);let maxScrollOffset=Math.max(0,layoutLines.length-maxVisibleLines);this.scrollOffset=
957
+ Math.max(0,Math.min(this.scrollOffset,maxScrollOffset));let visibleLines=layoutLines.slice(this.scrollOffset,this.scrollOffset+maxVisibleLines);this.renderedVisibleLineCount=visibleLines.length;let result=[],leftPadding=" ".repeat(paddingX),rightPadding=leftPadding;result.push(this.renderTopBorder(width,this.scrollOffset));let emitCursorMarker=this.focused;for(let layoutLine of visibleLines){let displayText=layoutLine.text,lineVisibleWidth=visibleWidth(layoutLine.text),cursorInPadding=!1;if(layoutLine.
958
+ hasCursor&&layoutLine.cursorPos!==void 0){let before=displayText.slice(0,layoutLine.cursorPos),after=displayText.slice(layoutLine.cursorPos),marker=emitCursorMarker?CURSOR_MARKER:"";if(after.length>0){let firstGrapheme=this.firstGrapheme(after)?.segment||"",restAfter=after.slice(firstGrapheme.length),cursor=renderFakeCursor(firstGrapheme);displayText=before+marker+cursor+restAfter}else{let cursor=renderFakeCursor(" ");displayText=before+marker+cursor,lineVisibleWidth=lineVisibleWidth+1,lineVisibleWidth>
959
+ contentWidth&&paddingX>0&&(cursorInPadding=!0)}}let padding=" ".repeat(Math.max(0,contentWidth-lineVisibleWidth)),lineRightPadding=cursorInPadding?rightPadding.slice(1):rightPadding;result.push(`${leftPadding}${displayText}${padding}${lineRightPadding}`)}let linesBelow=layoutLines.length-(this.scrollOffset+visibleLines.length);if(result.push(this.renderBottomBorder(width,linesBelow)),showAutocomplete||(this.renderedText={width,paddingX:this.paddingX,terminalRows,focused:this.focused,pasteIds:this.
960
+ pastes.size===0?"":[...this.pastes.keys()].join(","),lines:this.state.lines.slice(),cursorLine:this.state.cursorLine,cursorCol:this.state.cursorCol,scrollOffset:this.scrollOffset,visibleLineCount:visibleLines.length,linesBelow,textLines:result.slice(1,-1),result:result.slice()}),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let autocompleteResult=this.autocompleteList.render(contentWidth);this.renderedAutocompleteHeight=autocompleteResult.length;for(let line of autocompleteResult){
961
+ let lineWidth=visibleWidth(line),linePadding=" ".repeat(Math.max(0,contentWidth-lineWidth));result.push(`${leftPadding}${line}${linePadding}${rightPadding}`)}}return result}handleMouse(event){let autocompleteStartRow=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&event.y>=autocompleteStartRow&&event.y<autocompleteStartRow+this.renderedAutocompleteHeight){let maxPadding2=Math.max(0,Math.floor((event.width-1)/2)),paddingX2=Math.min(this.paddingX,maxPadding2),contentWidth=Math.
962
+ max(1,event.width-paddingX2*2),result=this.autocompleteList.handleMouse?.({...event,x:event.x-paddingX2,y:event.y-autocompleteStartRow,width:contentWidth,height:this.renderedAutocompleteHeight});return result?{...result,focus:!0}:void 0}if(event.type!=="click"||event.button!=="left")return;if(event.y<=0||event.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let visualLines=this.buildVisualLineMap(this.lastWidth),visualLineIndex=this.scrollOffset+event.y-1,visualLine=visualLines[visualLineIndex];
963
+ if(!visualLine)return{handled:!0,focus:!0};let logicalLine=this.state.lines[visualLine.logicalLine]??"",chunkEnd=visualLine.startCol+visualLine.length,chunk=logicalLine.slice(visualLine.startCol,chunkEnd),maxPadding=Math.max(0,Math.floor((event.width-1)/2)),paddingX=Math.min(this.paddingX,maxPadding),targetColumn=Math.max(0,event.x-paddingX),visibleColumn=0,targetIndex=chunk.length,lastGraphemeIndex=0;for(let grapheme of this.segment(chunk,"grapheme")){let nextColumn=visibleColumn+visibleWidth(grapheme.
964
+ segment);if(lastGraphemeIndex=grapheme.index,targetColumn<nextColumn){targetIndex=grapheme.index;break}visibleColumn=nextColumn}return!(visualLineIndex===visualLines.length-1||visualLines[visualLineIndex+1]?.logicalLine!==visualLine.logicalLine)&&targetIndex===chunk.length&&chunk.length>0&&(targetIndex=lastGraphemeIndex),this.state.cursorLine=visualLine.logicalLine,this.setCursorCol(visualLine.startCol+targetIndex),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),
965
+ {handled:!0,focus:!0}}handleInput(data){let kb=getKeybindings();if(this.jumpMode!==null){if(kb.matches(data,"tui.editor.jumpForward")||kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode=null;return}let printable2=decodePrintableKey(data)??(data.charCodeAt(0)>=32?data:void 0);if(printable2!==void 0){let direction=this.jumpMode;this.jumpMode=null,this.jumpToChar(printable2,direction);return}this.jumpMode=null}if(data.includes("\x1B[200~")&&(this.isInPaste=!0,this.pasteBuffer="",data=data.replace(
966
+ "\x1B[200~","")),this.isInPaste){this.pasteBuffer+=data;let endIndex=this.pasteBuffer.indexOf("\x1B[201~");if(endIndex!==-1){let pasteContent=this.pasteBuffer.substring(0,endIndex);pasteContent.length>0&&this.handlePaste(pasteContent),this.isInPaste=!1;let remaining=this.pasteBuffer.substring(endIndex+6);this.pasteBuffer="",remaining.length>0&&this.handleInput(remaining);return}return}if(kb.matches(data,"tui.input.copy"))return;if(kb.matches(data,"tui.editor.undo")){this.undo();return}if(this.autocompleteState&&
967
+ this.autocompleteList){if(kb.matches(data,"tui.select.cancel")){this.cancelAutocomplete();return}if(kb.matches(data,"tui.select.up")||kb.matches(data,"tui.select.down")||kb.matches(data,"tui.select.pageUp")||kb.matches(data,"tui.select.pageDown")){this.autocompleteList.handleInput(data);return}if(kb.matches(data,"tui.input.tab")){let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.
968
+ applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(kb.matches(data,"tui.select.confirm")){let selected=this.autocompleteList.getSelectedItem();if(selected&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.
969
+ applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);if(this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.autocompletePrefix.startsWith("/"))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(kb.matches(data,"tui.input.tab")&&!this.autocompleteState){this.handleTabCompletion();return}if(kb.matches(data,"tui.editor.de\
970
+ leteToLineEnd")){this.deleteToEndOfLine();return}if(kb.matches(data,"tui.editor.deleteToLineStart")){this.deleteToStartOfLine();return}if(kb.matches(data,"tui.editor.deleteWordBackward")){this.deleteWordBackwards();return}if(kb.matches(data,"tui.editor.deleteWordForward")){this.deleteWordForward();return}if(kb.matches(data,"tui.editor.deleteCharBackward")||matchesKey(data,"shift+backspace")){this.handleBackspace();return}if(kb.matches(data,"tui.editor.deleteCharForward")||matchesKey(data,"shift+\
971
+ delete")){this.handleForwardDelete();return}if(kb.matches(data,"tui.editor.yank")){this.yank();return}if(kb.matches(data,"tui.editor.yankPop")){this.yankPop();return}if(kb.matches(data,"tui.editor.historyPrevious")){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(kb.matches(data,"tui.editor.historyNext")){this.cancelAutocomplete(),this.navigateHistory(1);return}if(kb.matches(data,"tui.editor.cursorLineStart")){this.moveToLineStart();return}if(kb.matches(data,"tui.editor.cursorLineEn\
972
+ d")){this.moveToLineEnd();return}if(kb.matches(data,"tui.editor.cursorWordLeft")){this.moveWordBackwards();return}if(kb.matches(data,"tui.editor.cursorWordRight")){this.moveWordForwards();return}if(kb.matches(data,"tui.input.newLine")||data.charCodeAt(0)===10&&data.length>1||data==="\x1B\r"||data==="\x1B[13;2~"||data.length>1&&data.includes("\x1B")&&data.includes("\r")||data===`
973
+ `&&data.length===1){if(this.shouldSubmitOnBackslashEnter(data,kb)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(kb.matches(data,"tui.input.submit")){if(this.disableSubmit)return;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0&&currentLine[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(kb.matches(data,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||
974
+ this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(kb.matches(data,"tui.editor.cursorDown")){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(kb.matches(data,"tui.editor.cursorRight")){this.moveCursor(0,1);return}if(kb.matches(data,"tui.editor.cursorLeft")){this.moveCursor(0,-1);return}if(kb.matches(
975
+ data,"tui.editor.pageUp")){this.pageScroll(-1);return}if(kb.matches(data,"tui.editor.pageDown")){this.pageScroll(1);return}if(kb.matches(data,"tui.editor.jumpForward")){this.jumpMode="forward";return}if(kb.matches(data,"tui.editor.jumpBackward")){this.jumpMode="backward";return}if(matchesKey(data,"shift+space")){this.insertCharacter(" ");return}let printable=decodePrintableKey(data);if(printable!==void 0){this.insertCharacter(printable);return}data.charCodeAt(0)>=32&&this.insertCharacter(data)}layoutText(contentWidth){
976
+ let layoutLines=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]==="")return layoutLines.push({text:"",hasCursor:!0,cursorPos:0}),layoutLines;let wrapCache=this.wrapCacheFor(contentWidth);for(let i=0;i<this.state.lines.length;i++){let line=this.state.lines[i]||"",isCurrentLine=i===this.state.cursorLine;if(editorLineWidth(line)<=contentWidth)isCurrentLine?layoutLines.push({text:line,hasCursor:!0,cursorPos:this.state.cursorCol}):layoutLines.push({text:line,hasCursor:!1});else{
977
+ let chunks=this.wrapLine(wrapCache,i,line,contentWidth);for(let chunkIndex=0;chunkIndex<chunks.length;chunkIndex++){let chunk=chunks[chunkIndex];if(!chunk)continue;let cursorPos=this.state.cursorCol,isLastChunk=chunkIndex===chunks.length-1,hasCursorInChunk=!1,adjustedCursorPos=0;isCurrentLine&&(isLastChunk?(hasCursorInChunk=cursorPos>=chunk.startIndex,adjustedCursorPos=cursorPos-chunk.startIndex):(hasCursorInChunk=cursorPos>=chunk.startIndex&&cursorPos<chunk.endIndex,hasCursorInChunk&&(adjustedCursorPos=
978
+ cursorPos-chunk.startIndex,adjustedCursorPos>chunk.text.length&&(adjustedCursorPos=chunk.text.length)))),hasCursorInChunk?layoutLines.push({text:chunk.text,hasCursor:!0,cursorPos:adjustedCursorPos}):layoutLines.push({text:chunk.text,hasCursor:!1})}}}return layoutLines}getText(){return this.state.lines.join(`
979
+ `)}expandPasteMarkers(text){let result=text;for(let[pasteId,pasteContent]of this.pastes){let markerRegex=new RegExp(`\\[paste #${pasteId}( (\\+\\d+ lines|\\d+ chars))?\\]`,"g");result=result.replace(markerRegex,()=>pasteContent)}return result}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
980
+ `))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(text){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let normalized=this.normalizeText(text);this.getText()!==normalized&&this.pushUndoSnapshot(),this.pastes.clear(),this.pasteCounter=0,this.setTextInternal(normalized)}insertTextAtCursor(text){text&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.
981
+ insertTextAtCursorInternal(text))}normalizeText(text){return text.replace(/\r\n/g,`
982
+ `).replace(/\r/g,`
983
+ `).replace(/\t/g," ")}insertTextAtCursorInternal(text){if(!text)return;let normalized=this.normalizeText(text),insertedLines=normalized.split(`
984
+ `),currentLine=this.state.lines[this.state.cursorLine]||"",beforeCursor=currentLine.slice(0,this.state.cursorCol),afterCursor=currentLine.slice(this.state.cursorCol);insertedLines.length===1?(this.state.lines[this.state.cursorLine]=beforeCursor+normalized+afterCursor,this.setCursorCol(this.state.cursorCol+normalized.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),beforeCursor+insertedLines[0],...insertedLines.slice(1,-1),insertedLines[insertedLines.length-1]+afterCursor,
985
+ ...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=insertedLines.length-1,this.setCursorCol((insertedLines[insertedLines.length-1]||"").length)),this.onChange&&this.onChange(this.getText())}insertCharacter(char,skipUndoCoalescing){this.exitHistoryBrowsing(),skipUndoCoalescing||((isWhitespaceChar(char)||this.lastAction!=="type-word")&&this.pushUndoSnapshot(),this.lastAction="type-word");let line=this.state.lines[this.state.cursorLine]||"",before=line.slice(0,this.state.cursorCol),
986
+ after=line.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=before+char+after,this.setCursorCol(this.state.cursorCol+char.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(char==="/"&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.matchesAutocompleteTrigger(
987
+ textBeforeCursor)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(char)||cjkBreakRegex.test(char)){let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.matchesAutocompleteTrigger(textBeforeCursor)&&this.tryTriggerAutocomplete()}}handlePaste(pastedText){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let decodedText=pastedText.
988
+ replace(/\x1b\[(\d+);5u/g,(match,code)=>{let cp=Number(code);return cp>=97&&cp<=122?String.fromCharCode(cp-96):cp>=65&&cp<=90?String.fromCharCode(cp-64):match}),filteredText=this.normalizeText(decodedText).split("").filter(char=>char===`
989
+ `||char.charCodeAt(0)>=32).join("");if(/^[/~.]/.test(filteredText)){let currentLine=this.state.lines[this.state.cursorLine]||"",charBeforeCursor=this.state.cursorCol>0?currentLine[this.state.cursorCol-1]:"";charBeforeCursor&&/\w/.test(charBeforeCursor)&&(filteredText=` ${filteredText}`)}let pastedLines=filteredText.split(`
990
+ `),totalChars=filteredText.length;if(pastedLines.length>10||totalChars>1e3){this.pasteCounter++;let pasteId=this.pasteCounter;this.pastes.set(pasteId,filteredText);let marker=pastedLines.length>10?`[paste #${pasteId} +${pastedLines.length} lines]`:`[paste #${pasteId} ${totalChars} chars]`;this.insertTextAtCursorInternal(marker);return}if(pastedLines.length===1){this.insertTextAtCursorInternal(filteredText);return}this.insertTextAtCursorInternal(filteredText)}addNewLine(){this.cancelAutocomplete(),
991
+ this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before,this.state.lines.splice(this.state.cursorLine+1,0,after),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(data,kb){if(this.disableSubmit||!matchesKey(data,"\
992
+ enter"))return!1;let submitKeys=kb.getKeys("tui.input.submit");if(!(submitKeys.includes("shift+enter")||submitKeys.includes("shift+return")))return!1;let currentLine=this.state.lines[this.state.cursorLine]||"";return this.state.cursorCol>0&&currentLine[this.state.cursorCol-1]==="\\"}submitValue(){this.cancelAutocomplete();let result=this.expandPasteMarkers(this.state.lines.join(`
993
+ `)).trim();this.state={lines:[""],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(""),this.onSubmit&&this.onSubmit(result)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let line=this.state.lines[this.state.cursorLine]||"",beforeCursor=line.slice(0,this.state.cursorCol),lastGrapheme=this.lastGrapheme(
994
+ beforeCursor),graphemeLength=lastGrapheme?lastGrapheme.segment.length:1,isPastedSegmented=PASTE_MARKER_SINGLE.exec(lastGrapheme.segment);if(isPastedSegmented){let targetId=Number(isPastedSegmented[1]);this.pastes.delete(targetId),this.pasteCounter--;let higherIds=[...this.pastes.keys()].filter(id=>id>targetId).sort((a,b)=>a-b);for(let id of higherIds)this.pastes.set(id-1,this.pastes.get(id)),this.pastes.delete(id);this.state.lines=this.state.lines.map(line2=>line2.replace(PASTE_MARKER_REGEX,(fullMatch,idGroup,suffixGroup)=>{
995
+ let x2=Number(idGroup);return x2<=targetId?fullMatch:`[paste #${x2-1}${suffixGroup??""}]`}))}line=this.state.lines[this.state.cursorLine]||"";let before=line.slice(0,this.state.cursorCol-graphemeLength),after=line.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-graphemeLength)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let currentLine=this.state.lines[this.state.cursorLine]||"",previousLine=this.state.lines[this.
996
+ state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.matchesAutocompleteTrigger(
997
+ textBeforeCursor)&&this.tryTriggerAutocomplete()}}setCursorCol(col){this.state.cursorCol=col,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(visualLines,currentVisualLine,targetVisualLine){let currentVL=visualLines[currentVisualLine],targetVL=visualLines[targetVisualLine];if(!(currentVL&&targetVL))return;let currentVisualCol;if(this.snappedFromCursorCol!==null){let vlIndex=this.findVisualLineAt(visualLines,currentVL.logicalLine,this.snappedFromCursorCol);currentVisualCol=
998
+ this.snappedFromCursorCol-visualLines[vlIndex].startCol}else currentVisualCol=this.state.cursorCol-currentVL.startCol;let sourceMaxVisualCol=currentVisualLine===visualLines.length-1||visualLines[currentVisualLine+1]?.logicalLine!==currentVL.logicalLine?currentVL.length:Math.max(0,currentVL.length-1),targetMaxVisualCol=targetVisualLine===visualLines.length-1||visualLines[targetVisualLine+1]?.logicalLine!==targetVL.logicalLine?targetVL.length:Math.max(0,targetVL.length-1),moveToVisualCol=this.computeVerticalMoveColumn(
999
+ currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol);this.state.cursorLine=targetVL.logicalLine;let targetCol=targetVL.startCol+moveToVisualCol,logicalLine=this.state.lines[targetVL.logicalLine]||"";this.state.cursorCol=Math.min(targetCol,logicalLine.length);let seg=this.graphemeContaining(logicalLine,this.state.cursorCol);if(seg&&seg.segment.length>1){let isContinuation=seg.index<targetVL.startCol,isMovingDown=targetVisualLine>currentVisualLine;if(isContinuation&&isMovingDown){let segEnd=seg.
1000
+ index+seg.segment.length,next=targetVisualLine+1;for(;next<visualLines.length&&visualLines[next].logicalLine===targetVL.logicalLine&&visualLines[next].startCol<segEnd;)next++;if(next<visualLines.length){this.moveToVisualLine(visualLines,currentVisualLine,next);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=seg.index;return}this.snappedFromCursorCol=null}computeVerticalMoveColumn(currentVisualCol,sourceMaxVisualCol,targetMaxVisualCol){let hasPreferred=this.preferredVisualCol!==
1001
+ null,cursorInMiddle=currentVisualCol<sourceMaxVisualCol,targetTooShort=targetMaxVisualCol<currentVisualCol;if(!hasPreferred||cursorInMiddle)return targetTooShort?(this.preferredVisualCol=currentVisualCol,targetMaxVisualCol):(this.preferredVisualCol=null,currentVisualCol);let targetCantFitPreferred=targetMaxVisualCol<this.preferredVisualCol;if(targetTooShort||targetCantFitPreferred)return targetMaxVisualCol;let result=this.preferredVisualCol;return this.preferredVisualCol=null,result}moveToLineStart(){
1002
+ this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(currentLine.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>0){this.pushUndoSnapshot();let deletedText=currentLine.slice(0,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.
1003
+ state.lines[this.state.cursorLine]=currentLine.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
1004
+ `,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.
1005
+ length){this.pushUndoSnapshot();let deletedText=currentLine.slice(this.state.cursorCol);this.killRing.push(deletedText,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
1006
+ `,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(
1007
+ `
1008
+ `,{prepend:!0,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let previousLine=this.state.lines[this.state.cursorLine-1]||"";this.state.lines[this.state.cursorLine-1]=previousLine+currentLine,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(previousLine.length)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordBackwards();let deleteFrom=this.state.cursorCol;this.setCursorCol(oldCursorCol);
1009
+ let deletedText=currentLine.slice(deleteFrom,this.state.cursorCol);this.killRing.push(deletedText,{prepend:!0,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,deleteFrom)+currentLine.slice(this.state.cursorCol),this.setCursorCol(deleteFrom)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){if(this.
1010
+ state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
1011
+ `,{prepend:!1,accumulate:this.lastAction==="kill"}),this.lastAction="kill";let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let wasKill=this.lastAction==="kill",oldCursorCol=this.state.cursorCol;this.moveWordForwards();let deleteTo=this.state.cursorCol;this.setCursorCol(oldCursorCol);let deletedText=currentLine.slice(this.state.cursorCol,deleteTo);
1012
+ this.killRing.push(deletedText,{prepend:!1,accumulate:wasKill}),this.lastAction="kill",this.state.lines[this.state.cursorLine]=currentLine.slice(0,this.state.cursorCol)+currentLine.slice(deleteTo)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol<currentLine.length){this.pushUndoSnapshot();let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=this.
1013
+ firstGrapheme(afterCursor),graphemeLength=firstGrapheme?firstGrapheme.segment.length:1,before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol+graphemeLength);this.state.lines[this.state.cursorLine]=before+after}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let nextLine=this.state.lines[this.state.cursorLine+1]||"";this.state.lines[this.state.cursorLine]=currentLine+nextLine,this.state.lines.splice(this.state.cursorLine+1,1)}
1014
+ if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(textBeforeCursor)?this.tryTriggerAutocomplete():this.matchesAutocompleteTrigger(textBeforeCursor)&&this.tryTriggerAutocomplete()}}buildVisualLineMap(width){let visualLines=[],wrapCache=this.wrapCacheFor(width);for(let i=0;i<this.state.lines.length;i++){let line=this.state.
1015
+ lines[i]||"",lineVisWidth=editorLineWidth(line);if(line.length===0)visualLines.push({logicalLine:i,startCol:0,length:0});else if(lineVisWidth<=width)visualLines.push({logicalLine:i,startCol:0,length:line.length});else{let chunks=this.wrapLine(wrapCache,i,line,width);for(let chunk of chunks)visualLines.push({logicalLine:i,startCol:chunk.startIndex,length:chunk.endIndex-chunk.startIndex})}}return visualLines}findVisualLineAt(visualLines,line,col){for(let i=0;i<visualLines.length;i++){let vl=visualLines[i];
1016
+ if(!vl||vl.logicalLine!==line)continue;let offset=col-vl.startCol,isLastSegmentOfLine=i===visualLines.length-1||visualLines[i+1]?.logicalLine!==vl.logicalLine;if(offset>=0&&(offset<vl.length||isLastSegmentOfLine&&offset===vl.length))return i}return visualLines.length-1}findCurrentVisualLine(visualLines){return this.findVisualLineAt(visualLines,this.state.cursorLine,this.state.cursorCol)}moveCursor(deltaLine,deltaCol){this.lastAction=null;let visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.
1017
+ findCurrentVisualLine(visualLines);if(deltaLine!==0){let targetVisualLine=currentVisualLine+deltaLine;targetVisualLine>=0&&targetVisualLine<visualLines.length&&this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}if(deltaCol!==0){let currentLine=this.state.lines[this.state.cursorLine]||"";if(deltaCol>0)if(this.state.cursorCol<currentLine.length){let afterCursor=currentLine.slice(this.state.cursorCol),firstGrapheme=this.firstGrapheme(afterCursor);this.setCursorCol(this.state.cursorCol+
1018
+ (firstGrapheme?firstGrapheme.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let currentVL=visualLines[currentVisualLine];currentVL&&(this.preferredVisualCol=this.state.cursorCol-currentVL.startCol)}else if(this.state.cursorCol>0){let beforeCursor=currentLine.slice(0,this.state.cursorCol),lastGrapheme=this.lastGrapheme(beforeCursor);this.setCursorCol(this.state.cursorCol-(lastGrapheme?lastGrapheme.segment.length:1))}else if(this.
1019
+ state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(direction){this.lastAction=null;let terminalRows=this.tui.terminal.rows,pageSize=Math.max(5,Math.floor(terminalRows*.3)),visualLines=this.buildVisualLineMap(this.lastWidth),currentVisualLine=this.findCurrentVisualLine(visualLines),targetVisualLine=Math.max(0,Math.min(visualLines.length-1,currentVisualLine+
1020
+ direction*pageSize));this.moveToVisualLine(visualLines,currentVisualLine,targetVisualLine)}moveWordBackwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let prevLine=this.state.lines[this.state.cursorLine]||"";this.setCursorCol(prevLine.length)}return}this.setCursorCol(findWordBackward(currentLine,this.state.cursorCol,{segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}yank(){
1021
+ if(this.killRing.length===0)return;this.pushUndoSnapshot();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}yankPop(){if(this.lastAction!=="yank"||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let text=this.killRing.peek();this.insertYankedText(text),this.lastAction="yank"}insertYankedText(text){this.exitHistoryBrowsing();let lines=text.split(`
1022
+ `);if(lines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+text+after,this.setCursorCol(this.state.cursorCol+text.length)}else{let currentLine=this.state.lines[this.state.cursorLine]||"",before=currentLine.slice(0,this.state.cursorCol),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+(lines[0]||
1023
+ "");for(let i=1;i<lines.length-1;i++)this.state.lines.splice(this.state.cursorLine+i,0,lines[i]||"");let lastLineIndex=this.state.cursorLine+lines.length-1;this.state.lines.splice(lastLineIndex,0,(lines[lines.length-1]||"")+after),this.state.cursorLine=lastLineIndex,this.setCursorCol((lines[lines.length-1]||"").length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let yankedText=this.killRing.peek();if(!yankedText)return;let yankLines=yankedText.split(`
1024
+ `);if(yankLines.length===1){let currentLine=this.state.lines[this.state.cursorLine]||"",deleteLen=yankedText.length,before=currentLine.slice(0,this.state.cursorCol-deleteLen),after=currentLine.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=before+after,this.setCursorCol(this.state.cursorCol-deleteLen)}else{let startLine=this.state.cursorLine-(yankLines.length-1),startCol=(this.state.lines[startLine]||"").length-(yankLines[0]||"").length,afterCursor=(this.state.lines[this.state.
1025
+ cursorLine]||"").slice(this.state.cursorCol),beforeYank=(this.state.lines[startLine]||"").slice(0,startCol);this.state.lines.splice(startLine,yankLines.length,beforeYank+afterCursor),this.state.cursorLine=startLine,this.setCursorCol(startCol)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let snapshot=this.undoStack.pop();snapshot&&(Object.assign(this.state,
1026
+ snapshot.state),this.pastes=snapshot.pastes,this.pasteCounter=snapshot.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(char,direction){this.lastAction=null;let isForward=direction==="forward",lines=this.state.lines,end=isForward?lines.length:-1,step=isForward?1:-1;for(let lineIdx=this.state.cursorLine;lineIdx!==end;lineIdx+=step){let line=lines[lineIdx]||"",searchFrom=lineIdx===this.state.cursorLine?isForward?this.state.cursorCol+
1027
+ 1:this.state.cursorCol-1:void 0,idx=isForward?line.indexOf(char,searchFrom):line.lastIndexOf(char,searchFrom);if(idx!==-1){this.state.cursorLine=lineIdx,this.setCursorCol(idx);return}}}moveWordForwards(){this.lastAction=null;let currentLine=this.state.lines[this.state.cursorLine]||"";if(this.state.cursorCol>=currentLine.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(findWordForward(currentLine,this.state.cursorCol,
1028
+ {segment:text=>this.segment(text,"word"),isAtomicSegment:isPasteMarker}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return beforeCursor.trim()===""||beforeCursor.trim()==="/"}matchesAutocompleteTrigger(textBeforeCursor){let triggerCharacters=this.autocompleteTriggerCharacters;for(let i=0;i<triggerCharacters.length;i++)if(textBeforeCursor.
1029
+ includes(triggerCharacters[i]))return this.autocompleteTriggerPattern.test(textBeforeCursor);return!1}isInSlashCommandContext(textBeforeCursor){return this.isSlashMenuAllowed()&&textBeforeCursor.trimStart().startsWith("/")}getBestAutocompleteMatchIndex(items,prefix){if(!prefix)return-1;let firstPrefixIndex=-1;for(let i=0;i<items.length;i++){let value=items[i].value;if(value===prefix)return i;firstPrefixIndex===-1&&value.startsWith(prefix)&&(firstPrefixIndex=i)}return firstPrefixIndex}createAutocompleteList(prefix,items){
1030
+ let layout=prefix.startsWith("/")?SLASH_COMMAND_SELECT_LIST_LAYOUT:void 0,list=new SelectList(items,this.autocompleteMaxVisible,this.theme.selectList,layout);return list.onSelect=selected=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,selected,this.autocompletePrefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(
1031
+ result.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},list}tryTriggerAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!1,explicitTab})}handleTabCompletion(){if(!this.autocompleteProvider)return;let beforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);this.isInSlashCommandContext(beforeCursor)&&!beforeCursor.trimStart().includes(" ")?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){
1032
+ this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(explicitTab=!1){this.requestAutocomplete({force:!0,explicitTab})}requestAutocomplete(options){if(!this.autocompleteProvider||options.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let startToken=++this.autocompleteStartToken,debounceMs=this.getAutocompleteDebounceMs(
1033
+ options);if(debounceMs>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(startToken,options)},debounceMs);return}this.startAutocompleteRequest(startToken,options)}async startAutocompleteRequest(startToken,options){let previousTask=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await previousTask,startToken!==this.autocompleteStartToken||!this.autocompleteProvider)return;let controller=new AbortController;
1034
+ this.autocompleteAbort=controller;let requestId=++this.autocompleteRequestId,snapshotText=this.getText(),snapshotLine=this.state.cursorLine,snapshotCol=this.state.cursorCol;await this.runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(triggerCharacters){let next=[...DEFAULT_AUTOCOMPLETE_TRIGGER_CHARACTERS];for(let character of triggerCharacters)character.length!==1||character==="/"||isWhitespaceChar(
1035
+ character)||next.includes(character)||next.push(character);this.autocompleteTriggerCharacters=next,this.autocompleteTriggerPattern=buildTriggerPattern(next),this.autocompleteDebouncePattern=buildDebouncePattern(next)}getAutocompleteDebounceMs(options){if(options.explicitTab||options.force)return 0;let textBeforeCursor=(this.state.lines[this.state.cursorLine]||"").slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(textBeforeCursor)?ATTACHMENT_AUTOCOMPLETE_DEBOUNCE_MS:0}async runAutocompleteRequest(requestId,controller,snapshotText,snapshotLine,snapshotCol,options){
1036
+ if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:controller.signal,force:options.force});if(this.isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol)){if(this.autocompleteAbort=void 0,!suggestions||!Array.isArray(suggestions.items)||suggestions.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(options.force&&options.
1037
+ explicitTab&&suggestions.items.length===1){let item=suggestions.items[0];this.pushUndoSnapshot(),this.lastAction=null;let result=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,item,suggestions.prefix);this.state.lines=result.lines,this.state.cursorLine=result.cursorLine,this.setCursorCol(result.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(suggestions,options.force?"\
1038
+ force":"regular"),this.tui.requestRender()}}isAutocompleteRequestCurrent(requestId,controller,snapshotText,snapshotLine,snapshotCol){return!controller.signal.aborted&&requestId===this.autocompleteRequestId&&this.getText()===snapshotText&&this.state.cursorLine===snapshotLine&&this.state.cursorCol===snapshotCol}applyAutocompleteSuggestions(suggestions,state){this.autocompletePrefix=suggestions.prefix,this.autocompleteList=this.createAutocompleteList(suggestions.prefix,suggestions.items);let bestMatchIndex=this.
1039
+ getBestAutocompleteMatchIndex(suggestions.items,suggestions.prefix);bestMatchIndex>=0&&this.autocompleteList.setSelectedIndex(bestMatchIndex),this.autocompleteState=state}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&(clearTimeout(this.autocompleteDebounceTimer),this.autocompleteDebounceTimer=void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=
1040
+ ""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};var HStack=class extends Stack{layoutType="hstack";constructor(children=[],options={}){super(children,options)}render(width){let safeWidth=Math.max(1,width),viewport={width:safeWidth,height:Number.MAX_SAFE_INTEGER},entries=visibleStackEntries(this.entries,viewport);if(entries.length===0)return[];let intrinsicWidths=entries.map(entry=>entry.component.render(safeWidth).reduce((max,line)=>Math.max(max,visibleWidth(line)),0)),widths=allocateStackSizes(entries,intrinsicWidths,safeWidth,this.gap),rendered=entries.
1041
+ map((entry,index)=>widths[index]===0?[]:entry.component.render(widths[index])),height=rendered.reduce((max,lines)=>Math.max(max,lines.length),0),result=Array.from({length:height},()=>""),x2=0;for(let index=0;index<rendered.length;index++){let lines=rendered[index],childWidth=widths[index],offset=0;this.align==="center"?offset=Math.floor((height-lines.length)/2):this.align==="end"&&(offset=height-lines.length);for(let row=0;row<lines.length;row++){let target=row+offset;target<0||target>=result.length||
1042
+ (result[target]=compositeTuiLine(result[target],lines[row],x2,childWidth,safeWidth))}x2+=childWidth+this.gap}return result}};var imageTranscoder,pngCache=new Map;function setImageTranscoder(transcoder){imageTranscoder=transcoder,pngCache.clear()}function toPng(base64Data,mimeType){if(!imageTranscoder)return null;let cached=pngCache.get(base64Data),png=cached===void 0?imageTranscoder(base64Data,mimeType):cached;return pngCache.delete(base64Data),pngCache.set(base64Data,png),pngCache.size>32&&pngCache.delete(pngCache.keys().next().value),png}var Image=class{base64Data;mimeType;dimensions;theme;options;imageId;pngData;cachedLines;cachedWidth;constructor(base64Data,mimeType,theme,options={},dimensions){
1043
+ this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme,this.options=options,this.dimensions=dimensions||getImageDimensions(base64Data,mimeType)||{widthPx:800,heightPx:600},this.imageId=options.imageId}getImageId(){return this.imageId}invalidate(){this.cachedLines=void 0,this.cachedWidth=void 0,reportRenderChange(this)}render(width){if(this.cachedLines&&this.cachedWidth===width)return this.cachedLines;let maxWidth=Math.max(1,Math.min(width-2,this.options.maxWidthCells??60)),cellDimensions2=getCellDimensions(),
1044
+ defaultMaxHeight=Math.max(1,Math.ceil(maxWidth*cellDimensions2.widthPx/cellDimensions2.heightPx)),maxHeight=this.options.maxHeightCells??defaultMaxHeight,caps=getCapabilities(),data=this.base64Data,dimensions=this.dimensions;caps.images==="kitty"&&this.mimeType!=="image/png"&&(this.pngData??=toPng(this.base64Data,this.mimeType)??void 0,data=this.pngData??null,data&&(dimensions=getPngDimensions(data)??dimensions));let lines;if(caps.images&&data){caps.images==="kitty"&&this.imageId===void 0&&(this.
1045
+ imageId=allocateImageId());let result=renderImage(data,dimensions,{maxWidthCells:maxWidth,maxHeightCells:maxHeight,imageId:this.imageId,moveCursor:!1});if(result)if(result.imageId&&(this.imageId=result.imageId),caps.images==="kitty"){lines=[result.sequence];for(let i=0;i<result.rows-1;i++)lines.push("")}else{lines=[];for(let i=0;i<result.rows-1;i++)lines.push("");let rowOffset=result.rows-1,moveUp=rowOffset>0?`\x1B[${rowOffset}A`:"";lines.push(moveUp+result.sequence)}else{let fallback=imageFallback(
1046
+ this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}}else{let fallback=imageFallback(this.mimeType,this.dimensions,this.options.filename);lines=[truncateToWidth(this.theme.fallbackColor(fallback),width)]}return this.cachedLines=lines,this.cachedWidth=width,lines}};markStableRender(Image);markReportsChanges(Image);var MouseRegion=class{child;onMouse;copiedLines;constructor(child,onMouse){this.child=child,this.onMouse=onMouse}render(width){let lines=renderChildLines(this,this.child,width);if(setSubtreeReportsChanges(this,reportsChanges(this.child)),isStableRender(this.child))return lines;let copied=this.copiedLines;return copied!==void 0&&copied.length===lines.length&&copied.every((line,i)=>line===lines[i])?copied:(this.copiedLines=lines.slice(),this.copiedLines)}handleMouse(event){return dispatchMouseEvent(
1047
+ this.child,event)??this.onMouse(event)}invalidate(){this.copiedLines=void 0,this.child.invalidate(),reportRenderChange(this)}static renderLive(region,width){setRenderOwner(region.child,region);let lines=renderLiveLines(region.child,width);return setSubtreeReportsChanges(region,reportsChanges(region.child)),lines}};markStableRender(MouseRegion);markReportsChanges(MouseRegion);markLiveRender(MouseRegion.prototype.render,function(width){return MouseRegion.renderLive(this,width)});var SettingsList=class{capturesViewportInput=!0;items;filteredItems;theme;selectedIndex=0;mousePressedIndex;maxVisible;onChange;onCancel;searchInput;searchEnabled;submenuComponent=null;submenuItemIndex=null;navigateAfterClose=null;constructor(items,maxVisible,theme,onChange,onCancel,options={}){this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme,this.onChange=onChange,this.onCancel=onCancel,this.searchEnabled=options.enableSearch??!1,this.searchEnabled&&(this.searchInput=
1048
+ new Input)}updateValue(id,newValue){let item=this.items.find(i=>i.id===id);item&&(item.currentValue=newValue)}selectItem(id){let index=(this.searchEnabled?this.filteredItems:this.items).findIndex(i=>i.id===id);index!==-1&&(this.selectedIndex=index)}invalidate(){this.submenuComponent?.invalidate?.()}render(width){return this.submenuComponent?this.submenuComponent.render(width):this.renderMainList(width)}renderMainList(width){let lines=[];if(this.searchEnabled&&this.searchInput&&(lines.push(...this.
1049
+ searchInput.render(width)),lines.push("")),this.items.length===0)return lines.push(this.theme.hint(" No settings available")),this.searchEnabled&&this.addHintLine(lines,width),lines;let displayItems=this.getDisplayItems();if(displayItems.length===0)return lines.push(truncateToWidth(this.theme.hint(" No matching settings"),width)),this.addHintLine(lines,width),lines;let{startIndex,endIndex}=this.getVisibleRange(displayItems),maxLabelWidth=Math.min(36,Math.max(...this.items.map(item=>visibleWidth(
1050
+ item.label))));for(let i=startIndex;i<endIndex;i++){let item=displayItems[i];if(!item)continue;let isSelected=i===this.selectedIndex,prefix=isSelected?this.theme.cursor:" ",prefixWidth=visibleWidth(prefix),labelPadded=item.label+" ".repeat(Math.max(0,maxLabelWidth-visibleWidth(item.label))),labelText=this.theme.label(labelPadded,isSelected),separator=" ",usedWidth=prefixWidth+maxLabelWidth+visibleWidth(separator),valueMaxWidth=width-usedWidth-2,valueText=this.theme.value(truncateToWidth(item.currentValue,
1051
+ valueMaxWidth,""),isSelected);lines.push(truncateToWidth(prefix+labelText+separator+valueText,width))}if(startIndex>0||endIndex<displayItems.length){let scrollText=` (${this.selectedIndex+1}/${displayItems.length})`;lines.push(this.theme.hint(truncateToWidth(scrollText,width-2,"")))}let selectedItem=displayItems[this.selectedIndex];if(selectedItem?.description){lines.push("");let wrappedDesc=wrapTextWithAnsi(selectedItem.description,width-4);for(let line of wrappedDesc)lines.push(this.theme.description(
1052
+ ` ${line}`))}return this.addHintLine(lines,width),lines}handleMouse(event){if(this.submenuComponent){let result=this.submenuComponent.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(this.searchEnabled&&this.searchInput){if(event.y===0){let result=this.searchInput.handleMouse?.(event);return result?{...result,focus:!0}:void 0}if(event.y===1)return}let displayItems=this.getDisplayItems();if(displayItems.length===0)return;if(event.type==="wheel"&&event.wheelDelta){let delta=event.
1053
+ wheelDelta<0?-1:1,previousIndex=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(displayItems.length-1,this.selectedIndex+delta)),{handled:!0,render:this.selectedIndex!==previousIndex}}if(event.button!=="left"||event.type!=="press"&&event.type!=="click")return;let rowOffset=this.searchEnabled?2:0,{startIndex,endIndex}=this.getVisibleRange(displayItems),itemIndex=startIndex+event.y-rowOffset;if(!(itemIndex<startIndex||itemIndex>=endIndex)){if(event.type==="press")return this.mousePressedIndex=
1054
+ itemIndex,this.selectedIndex=itemIndex,{handled:!0,focus:!0};if(event.type==="click")return this.selectedIndex=this.mousePressedIndex??itemIndex,this.mousePressedIndex=void 0,this.activateItem(),{handled:!0}}}handleInput(data){if(this.submenuComponent){this.submenuComponent.handleInput?.(data);return}let kb=getKeybindings(),displayItems=this.getDisplayItems(),pageIndex=getSelectPageIndex(kb,data,this.selectedIndex,displayItems.length,this.maxVisible);if(kb.matches(data,"tui.select.up")){if(displayItems.
1055
+ length===0)return;this.selectedIndex=this.selectedIndex===0?displayItems.length-1:this.selectedIndex-1}else if(kb.matches(data,"tui.select.down")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===displayItems.length-1?0:this.selectedIndex+1}else if(pageIndex!==void 0){if(displayItems.length===0)return;this.selectedIndex=pageIndex}else kb.matches(data,"tui.select.confirm")||data===" "&&(!this.searchEnabled||this.searchInput?.getValue().length===0)?this.activateItem():kb.matches(
1056
+ data,"tui.select.cancel")?this.onCancel():this.searchEnabled&&this.searchInput&&(this.searchInput.handleInput(data),this.applyFilter(this.searchInput.getValue()))}getDisplayItems(){return this.searchEnabled?this.filteredItems:this.items}getVisibleRange(displayItems){let startIndex=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),displayItems.length-this.maxVisible));return{startIndex,endIndex:Math.min(startIndex+this.maxVisible,displayItems.length)}}activateItem(){let item=this.
1057
+ getDisplayItems()[this.selectedIndex];if(item){if(item.submenu)this.submenuItemIndex=this.selectedIndex,this.submenuComponent=item.submenu(item.currentValue,(selectedValue,options)=>{selectedValue!==void 0&&(item.currentValue=selectedValue,this.onChange(item.id,selectedValue)),options?.navigateTo&&(this.navigateAfterClose=options.navigateTo),this.closeSubmenu()});else if(item.values&&item.values.length>0){let nextIndex=(item.values.indexOf(item.currentValue)+1)%item.values.length,newValue=item.values[nextIndex];
1058
+ item.currentValue=newValue,this.onChange(item.id,newValue)}}}closeSubmenu(){if(this.submenuComponent=null,this.navigateAfterClose!==null){let id=this.navigateAfterClose;this.navigateAfterClose=null,this.submenuItemIndex=null,this.selectItem(id),this.activateItem()}else this.submenuItemIndex!==null&&(this.selectedIndex=this.submenuItemIndex,this.submenuItemIndex=null)}applyFilter(query){this.filteredItems=fuzzyFilter(this.items,query,item=>item.label),this.selectedIndex=0}addHintLine(lines,width){
1059
+ lines.push(""),lines.push(truncateToWidth(this.theme.hint(this.searchEnabled?" Type to search \xB7 Enter/Space to change \xB7 Esc to cancel":" Enter/Space to change \xB7 Esc to cancel"),width))}};export{Y,fuzzyMatch,fuzzyFilter,visibleWidth,stripTerminalSequences,sanitizeTerminalText,startsWithText,sanitizeTerminalTextFrom,replaceControlCharacters,wrapTextWithAnsi,applyBackgroundToLine,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,oklabToOkhslLightness,indexedColor,rgbColor,oklchColor,okhslColor,colorToOkhsl,parseColor,colorToRgb,colorToOklch,colorToHex,mixColors,foregroundAnsi,backgroundAnsi,styleText,styleTextWithAnsi,Key,matchesKey,renderedMarkdownGeneration,onCapabilitiesChange,
1060
+ detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,hyperlink,imageFallback,CURSOR_MARKER,markStableRender,LiveLineArray,markLiveRender,markReportsChanges,reportsChanges,setSubtreeReportsChanges,renderChildLines,reportRenderChange,Container,isViewportTUI,Box,TUI_KEYBINDINGS,KeybindingsManager,setKeybindings,getKeybindings,getSelectPageIndex,Text,Loader,CancellableLoader,SelectList,Editor,setImageTranscoder,Image,Input,Markdown,MouseRegion,ScrollView,
1061
+ SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports};