@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
@@ -1,1336 +0,0 @@
1
- import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
2
- import{source_default}from"./chunk-XQRYOCHA.js";import{require_core}from"./chunk-DNGJMRJW.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-KM4GQ2BU.js";import{__export,__toESM}from"./chunk-JXWJOIH4.js";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,
3
- 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,
4
- 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,
5
- 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,
6
- 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,
7
- 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,
8
- 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||
9
- 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(
10
- "^(?:\\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\
11
- 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])`,
12
- "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.
13
- 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&&
14
- (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="\
15
- \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===
16
- 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.
17
- test(char))width+=1,followsMark=!1;else if(markCharRegex.test(char))followsMark=!0;else if(!nonPrintingCharRegex.test(char)){let c3=char.codePointAt(0);followsMark||c3>=65280&&c3<=65519?width+=eastAsianWidth(c3):(c3===3635||c3===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(" ")&&
18
- (clean=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>=
19
- WIDTH_CACHE_SIZE){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;
20
- function sanitizeTerminalText(text){return TERMINAL_CONTROL_REGEX.lastIndex=0,TERMINAL_CONTROL_REGEX.test(text)?text.replace(TERMINAL_SEQUENCE_GLOBAL_REGEX,match=>match==="\r"?`
21
- `:""):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,
22
- 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;
23
- 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+=`
24
- `),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)}
25
- 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){
26
- 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;
27
- 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=
28
- 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]===
29
- " "?" ":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}
30
- 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 c3=str.charCodeAt(j2);if(c3===109||c3===71||c3===75||c3===72||c3===74)return j2+1-pos}return 0}if(next==="]"||next==="_"){for(let j2=pos+2;j2<str.length;j2++){let c3=str.charCodeAt(j2);if(c3===7)return j2+1-pos;if(c3===27&&str[j2+1]==="\\")return j2+2-pos}return 0}return 0}function parseOsc8Hyperlink(ansiCode){if(!ansiCode.
31
- startsWith("\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){
32
- 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){
33
- 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.
34
- 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.
35
- 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(){
36
- 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(
37
- 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="";
38
- 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),
39
- 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&&
40
- 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(
41
- 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),
42
- 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}function flattenLines(lines){for(let line of lines)Number(line)}function wrapTextWithAnsi(text,width){if(!text)return[""];if(text.indexOf(`
43
- `)===-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:[""]}function wrapSingleLine(line,width){
44
- if(!line)return[""];if(visibleWidth(line)<=width)return[line];let wrapped=[],tracker=new AnsiCodeTracker,widths=[],tokens=splitIntoTokensWithAnsi(line,widths),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.
45
- getLineEndReset();lineEndReset&&(currentLine+=lineEndReset),wrapped.push(currentLine),currentLine="",currentVisibleLength=0}let broken=breakLongWord(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(
46
- token),updateTrackerFromText(token,tracker));let lineEndReset=tracker.getLineEndReset();if(lineEndReset&&(lineToWrap+=lineEndReset),wrapped.push(lineToWrap),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(
47
- token,tracker)}return currentLine&&wrapped.push(currentLine),wrapped.length>0?wrapped.map(line2=>line2.trimEnd()):[""]}var PUNCTUATION_REGEX=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;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){
48
- 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){
49
- 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(
50
- 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)
51
- 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,
52
- 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]!==" "&&
53
- !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(
54
- 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+=
55
- pendingAnsi+ansi.code,pendingAnsi=""):currentCol<startCol&&(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+=w2),currentCol+=w2,currentCol>=
56
- 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<beforeEnd?pendingAnsiBefore+=
57
- 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+=w2):currentCol>=afterStart&&
58
- 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}}var multiply=(m,[x2,y,z2])=>m.map(row=>row[0]*x2+row[1]*y+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,
59
- -.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,
60
- .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(
61
- 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(a3,b){return[LAB_TO_LMS[0],LAB_TO_LMS[1],LAB_TO_LMS[2]].map(row=>row[1]*a3+row[2]*b)}function maxSaturation(a3,b){let channel=SATURATION_FIT.findIndex(([[x2,y]],index)=>index===2||x2*a3+y*b>1),[k0,k1,k2,k3,k4]=SATURATION_FIT[channel][1],
62
- weights=LMS_TO_LINEAR_SRGB[channel],saturation=k0+k1*a3+k2*b+k3*a3*a3+k4*a3*b,slopes=lmsSlopes(a3,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(a3,b){let saturation=maxSaturation(a3,b),lightness=Math.cbrt(1/Math.max(...oklabToLinearSrgb(
63
- [1,saturation*a3,saturation*b])));return[lightness,lightness*saturation]}function maxChroma(a3,b,lightness,[cuspL,cuspC]){if(lightness<=cuspL)return cuspC*lightness/cuspL;let t=cuspC*(lightness-1)/(cuspL-1),slopes=lmsSlopes(a3,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(
64
- row=>{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,a3,b){let peak=cusp(a3,b),cMax=maxChroma(a3,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+a3*(-2.19557347+1.75198401*b+a3*(-2.13704948-10.02301043*b+a3*(-4.24894561+5.38770819*b+4.69891013*a3)))),midT=.11239642+1/(1.6132032-.68124379*b+a3*(.40370612+.90148123*
65
- b+a3*(-.27087943+.6122399*b+a3*(.00299215-.45399568*b-.14661872*a3)))),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,a3=Math.cos(angle),b=Math.sin(angle),[c0,cMid,cMax]=chromaStops(L2,a3,b),chroma;if(saturation<.8){let t=1.25*saturation,k1=.8*
66
- c0;chroma=t*k1/(1-(1-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*a3,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),
67
- saturation;if(chroma<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.
68
- freeze({kind:"rgb",r,g,b})}function oklchColor(l,c3,h){if(requireFinite(l,"l"),requireFinite(c3,"c"),requireFinite(h,"h"),l<0||l>1)throw new Error(`l must be between 0 and 1: ${l}`);if(c3<0)throw new Error(`c must not be negative: ${c3}`);return Object.freeze({kind:"oklch",l,c:c3,h:(h%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*\\)$`,
69
- "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(h,s,l){if(requireFinite(h,"h"),requireFinite(s,"s"),requireFinite(l,"l"),s<0||s>1)throw new Error(`s must be between 0 and 1: ${s}`);if(l<0||l>1)throw new Error(`\
70
- l must be between 0 and 1: ${l}`);let key=`${Object.is(h,-0)?"-0":h} ${Object.is(s,-0)?"-0":s} ${Object.is(l,-0)?"-0":l}`,cached=okhslColors.get(key);if(cached)return cached;let{r,g,b}=okhslToRgb(h,s,l);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(value))}
71
- 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]))}let okhsl=OKHSL_PATTERN.
72
- 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},{r:0,g:0,b:255},{r:255,
73
- 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>=-1e-7&&
74
- channel<=1+1e-7)}function oklchToRgb({l,c:c3,h}){let radians=h*Math.PI/180,cos=Math.cos(radians),sin=Math.sin(radians),atChroma=chroma=>oklabToLinearSrgb([l,chroma*cos,chroma*sin]),direct=atChroma(c3);if(isInSrgbGamut(direct))return linearSrgbToRgb(direct);let linear=atChroma(0),low=0,high=c3;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){
75
- 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[l,a3,b]=rgbToOklab(colorToRgb(color));return{l,c:Math.hypot(a3,b),h:(Math.atan2(b,a3)*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(
76
- 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 a4=colorToRgb(first),b2=colorToRgb(second);return rgbColor(a4.r+(b2.r-a4.r)*amount,a4.g+(b2.g-a4.g)*amount,a4.b+(b2.b-a4.b)*amount)}let a3=colorToOklch(first),b=colorToOklch(second),firstHue=a3.c<1e-7?b.h:a3.h,hueDelta=((b.c<1e-7?firstHue:b.h)-firstHue+540)%360-180;return oklchColor(a3.l+(b.
77
- l-a3.l)*amount,a3.c+(b.c-a3.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(
78
- 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(
79
- 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){
80
- 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.
81
- 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:"\
82
- 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}`,
83
- 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=>`\
84
- 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,
85
- 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],
86
- [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>=
87
- 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",
88
- "\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~"]},
89
- 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\
90
- 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+\
91
- 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":"\
92
- 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(
93
- ":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){
94
- 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$/);
95
- 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),
96
- 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.
97
- 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}}
98
- 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={
99
- 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.
100
- 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(
101
- 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(
102
- 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(){
103
- 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}
104
- 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);
105
- 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.
106
- 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}+`));
107
- 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(
108
- "\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)
109
- 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)||
110
- 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.
111
- enter,MODIFIERS.shift)||matchesKittySequence(data,CODEPOINTS.kpEnter,MODIFIERS.shift)||matchesModifyOtherKeys(data,CODEPOINTS.enter,MODIFIERS.shift)?!0:_kittyProtocolActive?data==="\x1B\r"||data===`
112
- `:!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===`
113
- `||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===
114
- 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(
115
- 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===
116
- 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.
117
- 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(
118
- 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"\
119
- 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.
120
- 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&&
121
- 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"\
122
- 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.
123
- 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(
124
- 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){
125
- 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=
126
- "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.
127
- 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.
128
- 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?.
129
- 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===`
130
- `))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===`
131
- `||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&&
132
- 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"||
133
- 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);
134
- 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),
135
- 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.
136
- codepoint<32))try{return String.fromCodePoint(parsed.codepoint)}catch{return}}function decodePrintableKey(data){return decodeKittyPrintable(data)??decodeModifyOtherKeysPrintable(data)}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:"\
137
- 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\
138
- 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\
139
- 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\
140
- 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\
141
- 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.\
142
- 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\
143
- 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\
144
- 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=
145
- 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.
146
- 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.
147
- 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(
148
- 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 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,
149
- 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,
150
- 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,
151
- 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,
152
- 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,
153
- 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,
154
- reportRenderChange:()=>reportRenderChange,reportsChanges:()=>reportsChanges,resetCapabilitiesCache:()=>resetCapabilitiesCache,rgbColor:()=>rgbColor,sanitizeTerminalText:()=>sanitizeTerminalText,sanitizeTerminalTextFrom:()=>sanitizeTerminalTextFrom,setCapabilities:()=>setCapabilities,setCapabilityOverrides:()=>setCapabilityOverrides,setCellDimensions:()=>setCellDimensions,setChangeReportsForTest:()=>setChangeReportsForTest,setImageTranscoder:()=>setImageTranscoder,setKeybindings:()=>setKeybindings,
155
- setKittyProtocolActive:()=>setKittyProtocolActive,setRenderClockForTest:()=>setRenderClockForTest,setRenderOwner:()=>setRenderOwner,setSubtreeReportsChanges:()=>setSubtreeReportsChanges,sliceByColumn:()=>sliceByColumn,startsWithText:()=>startsWithText,stripTerminalSequences:()=>stripTerminalSequences,styleText:()=>styleText,styleTextWithAnsi:()=>styleTextWithAnsi,truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function H(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var S=H();function se(a3){S=a3}var B={exec:()=>null};function D(a3){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=a3(n),e[n]=s),s}}function c(a3,e=""){let t=typeof a3=="string"?a3:a3.source,n={replace:(s,r)=>{let o=typeof r=="string"?r:r.source;return o=o.replace(T.caret,"$1"),t=t.replace(s,o),n},getRegex:()=>new RegExp(t,e)};return n}
156
- var Te=((a3="")=>{try{return!!new RegExp("(?<=1)(?<!1)"+a3)}catch{return!1}})(),T={codeRemoveIndent:/^(?: {0,3}\t| {1,4})/gm,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]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,
157
- 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:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,
158
- 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,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,
159
- 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:a3=>new RegExp(`^( {0,3}${a3})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:D(a3=>new RegExp(`^ {0,${a3}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:D(
160
- a3=>new RegExp(`^ {0,${a3}}((?:-[ ]*){3,}|(?:_[ ]*){3,}|(?:\\*[ ]*){3,})(?:\\n+|$)`)),fencesBeginRegex:D(a3=>new RegExp(`^ {0,${a3}}(?:\`\`\`|~~~)`)),headingBeginRegex:D(a3=>new RegExp(`^ {0,${a3}}#{1,6}(?:\\s|$)`)),pedanticHeadingBeginRegex:D(a3=>new RegExp(`^ {0,${a3}}#`)),htmlBeginRegex:D(a3=>new RegExp(`^ {0,${a3}}(?:</?(?:${K})(?: +|$|/?>)|<(?:(?:script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)`,"i")),blockquoteBeginRegex:D(a3=>new RegExp(`^ {0,${a3}}>`))},ve=/^(?:[ \t]*(?:\n|$))+/,
161
- Ze=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,He=/^ {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+|$)/,je=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,oe=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,Oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |fences|blockquote|heading|hr|html|table))+?)\n {0,3}(=+|-+)[ \t]*(?:\n+|$)/,we=c(
162
- Oe).replace(/bull/g,oe).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(),Ge=c(Oe).replace(/bull/g,oe).replace(/blockCode/g,/(?: {4}| {0,3}\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,
163
- / {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(),ae=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,Ne=/^[^\n]+/,le=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\\n]|\n(?![ \t]*\n))+/,Fe=c(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace("la\
164
- bel",le).replace("title",/(?:"(?:\\[\s\S]|[^"\\])*"|'(?:\\[\s\S]|[^'\\\n]|\n(?!\n))*'|\((?:\\[\s\S]|[^()\\])*\))/).getRegex(),Qe=c(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,oe).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|section|summary\
165
- |table|tbody|td|tfoot|th|thead|title|tr|track|ul",ue=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,Ue=c("^ {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-]*\\s*>(?=[ \\\
166
- t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))","i").replace("comment",ue).replace("tag",K).replace("attribute",/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Pe=a3=>c(ae).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",a3).replace("html"," {0,3}(?:</?(?:tag)(?: +|\\n|/?>)|<(?:(?:\
167
- script|pre|style|textarea)(?:[\\s>]|$)|!--)|<\\?|<![A-Za-z]|<!\\[CDATA\\[)").replace("tag",K).getRegex(),We=Pe(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),Ke=Pe(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Xe=c(/^( {0,3}> ?(?:(?![ \t]*(?:\n|$))(paragraph)|[^\n]*)(?:\n|$))+/).replace("paragraph",Ke).getRegex(),pe={blockquote:Xe,code:Ze,def:Fe,fences:He,heading:je,hr:W,html:Ue,lheading:we,list:Qe,newline:ve,paragraph:We,table:B,text:Ne},xe=c("^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\\
168
- | *)?)(?:\\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("tag",K).getRegex(),
169
- Ve={...pe,lheading:Ge,table:xe,paragraph:c(ae).replace("hr",W).replace("heading"," {0,3}#{1,6}(?:\\s|$)").replace("|lheading","").replace("table",xe).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()},Je={...pe,html:c(`^ *\
170
- (?:comment(?: *\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1>(?: *\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?>(?: *\\n{2,}|\\s*$))`).replace("comment",ue).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:B,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,
171
- paragraph:c(ae).replace("hr",W).replace("heading",` *#{1,6} *[^
172
- ]`).replace("lheading",we).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()},Ye=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,et=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,Se=/^( {2,}|\\)\n(?!\s*$)[ \t]*/,tt=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,$=/[\p{P}\p{S}]/u,j=/[\s\p{P}\p{S}]/u,X=/[^\s\p{P}\p{S}]/u,nt=c(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,j).getRegex(),
173
- rt=/[\p{Pi}\p{Ps}"']/u,ye=/(?!~)[\p{P}\p{S}]/u,st=/(?!~)[\s\p{P}\p{S}]/u,it=/(?:[^\s\p{P}\p{S}]|~)/u,ot=c(/link|precode-code|html/,"g").replace("link",/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace("precode-",Te?"(?<!`)()":"(^^|[^`])").replace("code",/(?<b>`+)[^`]+\k<b>(?!`)/).replace("html",/<(?! )[^<>]*?>/).getRegex(),_e=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,at=c(_e,"u").replace(/punct/g,$).getRegex(),lt=c(
174
- _e,"u").replace(/punct/g,ye).getRegex(),ut=/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,pt=c(ut,"u").replace(/openQuote/g,rt).replace(/punct/g,$).getRegex(),$e="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)",ct=c($e,"gu").replace(/notPunctSpace/g,
175
- X).replace(/punctSpace/g,j).replace(/punct/g,$).getRegex(),ht=c($e,"gu").replace(/notPunctSpace/g,it).replace(/punctSpace/g,st).replace(/punct/g,ye).getRegex(),dt="^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)",gt=c(dt,"gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,
176
- j).replace(/punct/g,$).getRegex(),kt=c("^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,j).replace(/punct/g,$).getRegex(),ft="^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!\
177
- _)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)",mt=c(ft,"gu").replace(/notPunctSpace/g,X).replace(/punctSpace/g,j).replace(/punct/g,$).getRegex(),xt=c(/^~~?(?:((?!~)punct)|[^\s~])/,"u").replace(/punct/g,$).getRegex(),bt="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)",Rt=c(bt,"gu").replace(
178
- /notPunctSpace/g,X).replace(/punctSpace/g,j).replace(/punct/g,$).getRegex(),Tt=c(/\\(punct)/,"gu").replace(/punct/g,$).getRegex(),Ot=c(/(`+)(?:[^`]|[^`][\s\S]*?[^`])\1(?!`)|`+|\\(punct)/,"gu").replace(/punct/g,$).getRegex(),wt=c(/^<(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(),Pt=c(ue).replace(
179
- "(?:-->|$)","-->").getRegex(),St=c("^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",Pt).replace("attribute",/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),Le=/\[(?:\\[\s\S]|[^\[\]\\])*\]/,re=c(/(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/).replace("brackets",Le).getRegex(),
180
- yt=c(/^!?\[(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(),_t=c(/^!?\[(label)\]\[(ref)\]/).replace("label",re).replace("ref",le).getRegex(),$t=c(/^!?\[(ref)\](?:\[\])?/).replace("ref",le).getRegex(),be=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\]){1,999}/,Lt=c(/(?:[^\[\]\\`]*(?:\[(?:brackets|\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\]))){0,999}?[^\[\]\\`]*?/).
181
- replace("brackets",Le).getRegex(),Ct=c("reflink|nolink(?!\\()","g").replace("reflink",c(/^!?\[(label)\]\[(ref)\]/).replace("label",Lt).replace("ref",be).getRegex()).replace("nolink",c(/^!?\[(ref)\](?:\[\])?/).replace("ref",be).getRegex()).getRegex(),Re=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,It=/[A-Za-z0-9._+-]+@[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![\w-])/,At=c(/(?:mailto:email|xmpp:email(?:\/[A-Za-z0-9@.]+)?)/).replace(/email/g,It).getRegex(),ce={_backpedal:B,anyPunctuation:Tt,anyPunctuationOutsideCode:Ot,
182
- autolink:wt,blockSkip:ot,br:Se,code:et,del:B,delLDelim:B,delRDelim:B,emStrongLDelim:at,emStrongRDelimAst:ct,emStrongRDelimUnd:kt,escape:Ye,link:yt,nolink:$t,punctuation:nt,reflink:_t,reflinkSearch:Ct,tag:St,text:tt,url:B},Et={...ce,emStrongLDelim:pt,emStrongRDelimAst:gt,emStrongRDelimUnd:mt,link:c(/^!?\[(label)\]\((.*?)\)/).replace("label",re).getRegex(),reflink:c(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace("label",re).getRegex()},ie={...ce,emStrongRDelimAst:ht,emStrongLDelim:lt,delLDelim:xt,delRDelim:Rt,
183
- url:c(/^emailProtocol|^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace("emailProtocol",At).replace("protocol",Re).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:c(/^(?:[^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.!#$%&'*+\/=?_`{\|}~-]+@))))/).
184
- replace("protocol",Re).replace(/emailProtocol/g,/(?:mailto|xmpp):/).replace("wwwStart",Te?"(?<![^\\s*_~(])www\\.":"www\\.").getRegex()},zt={...ie,br:c(Se).replace("{2,}","*").getRegex(),text:c(ie.text).replace("\\b_","\\b_| {2,}\\n").replace(/\{2,\}/g,"*").getRegex()},V={normal:pe,gfm:Ve,pedantic:Je},G={normal:ce,gfm:ie,breaks:zt,pedantic:Et},Mt={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},Ce=a3=>Mt[a3];function P(a3,e){if(e){if(T.escapeTest.test(a3))return a3.replace(T.escapeReplace,
185
- Ce)}else if(T.escapeTestNoEncode.test(a3))return a3.replace(T.escapeReplaceNoEncode,Ce);return a3}function Ie(a3){return T.numericCharacterReference.test(a3)?a3.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)}):a3}function he(a3){try{a3=encodeURI(a3).replace(T.percentDecode,"%")}catch{return null}
186
- return a3}function de(a3,e){let t=a3.replace(T.findPipe,(r,o,i)=>{let l=!1,p=o;for(;--p>=0&&i[p]==="\\";)l=!l;return l?"|":" |"}),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(a3,e,t){let n=a3.length;if(n===0)return"";let s=0;for(;s<n;){let r=a3.charAt(n-s-1);if(r===e&&!t)s++;else if(r!==e&&t)s++;else break}return a3.
187
- slice(0,n-s)}function ge(a3){let e=a3.split(`
188
- `),t=e.length-1;for(;t>=0&&T.blankLine.test(e[t]);)t--;return e.length-t<=2?a3:e.slice(0,t+1).join(`
189
- `)}function F(a3){return a3.trim().replace(T.multipleSpaceGlobal," ").toLowerCase().toUpperCase().toLowerCase()}function ke(a3,e){if(a3.indexOf(e[0])===-1&&a3.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<a3.length;n++)if(a3[n]==="\\")n++;else if(a3[n]===e[0])t++;else if(a3[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}var N=new WeakMap;function fe(a3){let e={"*":-1,_:-1},t=-1,n=a3.length;for(let s=0;s<n;s++){let r=a3[s];if(r!=="*"&&r!=="_"&&r!=="~")continue;let o=s===0?`
190
- `:a3[s-1],i=s+1;for(;i<n&&a3[i]===r;)i++;o!==" "&&o!==" "&&o!==`
191
- `&&o!=="\r"&&o!=="\f"&&(r==="~"?t=s:e[r]=s),s=i-1}return{maskedSrc:a3,lastPossibleEmStrongCloserIndex:e,lastPossibleDelCloserIndex:t}}function Ae(a3,e){let t=fe(e),n=N.get(a3);n?n.push(t):N.set(a3,[t])}function Ee(a3){let e=N.get(a3);e&&(e.pop(),e.length===0&&N.delete(a3))}function ze(a3,e,t){let n=N.get(a3)?.at(-1);return n&&n.maskedSrc===e?n.lastPossibleEmStrongCloserIndex[t]:fe(e).lastPossibleEmStrongCloserIndex[t]}function Me(a3,e){let t=N.get(a3)?.at(-1);return t&&t.maskedSrc===e?t.lastPossibleDelCloserIndex:
192
- fe(e).lastPossibleDelCloserIndex}function J(a3,e=0){let t=e,n="";for(let s of a3)if(s===" "){let r=4-t%4;n+=" ".repeat(r),t+=r}else n+=s,t++;return n}function De(a3,e,t,n,s){let r=e.href,o=e.title||null,i=a3[1].replace(s.other.outputLinkReplace,"$1"),l=a3[0].charAt(0)==="!",p=n.state.inLink,h=n.state.linkEmitted,u=n.state.inRawBlock;n.state.inLink=!0,n.state.linkEmitted=!1;let d=n.inlineTokens(i),k=n.state.linkEmitted;if(n.state.linkEmitted=h,n.state.inLink=p,!l){if(k){n.state.inRawBlock=u;return}
193
- n.state.linkEmitted=!0}return{type:l?"image":"link",raw:t,href:r,title:o,text:i,tokens:d}}function Dt(a3,e,t){let n=a3.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(`
194
- `).map(r=>{let o=r.match(t.other.beginningSpace);if(o===null)return r;let[i]=o;return r.slice(Math.min(i.length,s.length))}).join(`
195
- `)}function Be(a3,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 i=n.inline.code.exec(e.slice(s));if(i){s+=i[0].length-1;continue}}if(e[s]!=="<")continue;let r=a3.slice(t+s),o=n.inline.tag.exec(r)||n.inline.autolink.exec(r);if(o){if(o[0].length>e.length-s)return!0;s+=o[0].length-1}}return!1}var _=class{options;rules;lexer;constructor(e){this.options=e||S}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"\
196
- space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:ge(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=Dt(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.
197
- 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],`
198
- `),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],`
199
- `)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=L(t[0],`
200
- `).split(`
201
- `),s="",r="",o=[];for(;n.length>0;){let i=!1,l=[],p;for(p=0;p<n.length;p++)if(this.rules.other.blockquoteStart.test(n[p]))l.push(n[p]),i=!0;else if(!i)l.push(n[p]);else break;n=n.slice(p);let h=l.join(`
202
- `),u=h.replace(this.rules.other.blockquoteMarkerWhitespace,(g,b,m)=>b+J(m,b.length)).replace(this.rules.other.blockquoteSetextReplace,`
203
- $1`).replace(this.rules.other.blockquoteSetextReplace2,"");s=s?`${s}
204
- ${h}`:h,r=r?`${r}
205
- ${u}`:u;let d=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(u,o,!0),this.lexer.state.top=d,n.length===0)break;let k=o.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(`
206
- `),m=g.raw+`
207
- `+b.replace(this.rules.other.blockquoteSetextReplace2,""),f=this.blockquote(m);o[o.length-1]=f;let y=m.substring(f.raw.length).replace(/^\n/,""),R=y?y.split(`
208
- `).length:0,A=R?n.slice(0,-R):n;if(A.length>0&&(s=`${s}
209
- ${A.join(`
210
- `)}`),r=r.substring(0,r.length-g.text.length)+f.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+`
211
- `+n.join(`
212
- `),m=this.list(b);o[o.length-1]=m;let f=m.raw.length>g.raw.length?b.slice(g.raw.length+1,m.raw.length).split(`
213
- `).length:0;if(f>0){let y=n.slice(0,f).join(`
214
- `);s=`${s}
215
- ${y}`,r=`${r}
216
- ${y}`}n=n.slice(f);continue}}return{type:"blockquote",raw:s,tokens:o,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=e,s=()=>n.length-e.length,r=t[1].trim(),o=r.length>1,i={type:"list",raw:"",ordered:o,start:o?+r.slice(0,-1):"",loose:!1,items:[]};r=o?`\\d{1,9}\\${r.slice(-1)}`:`\\${r}`,this.options.pedantic&&(r=o?r:"[*+-]");let l=this.rules.other.listItemRegex(r),p=!1;for(;e;){let u=!1,d="";if(!(t=l.exec(e))||this.rules.block.hr.test(e))break;let k=s();e=e.substring(t[0].length);
217
- let g=t[2].split(`
218
- `,1)[0],b=t[1].length,m=this.options.pedantic?J(g,b):g.replace(this.rules.other.leadingSpaceTab,v=>J(v,b)),f=e.split(`
219
- `,1)[0],y=!m.trim(),R=0;if(this.options.pedantic?(R=2,d=m.trimStart()):y?R=b+1:(R=m.search(this.rules.other.nonSpaceChar),R=R>4?1:R,d=m.slice(R),R+=b),y&&this.rules.other.blankLine.test(f)&&(e=e.substring(f.length+1),u=!0),!u){let v=this.rules.other.nextBulletRegex(R),Q=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.
220
- blockquoteBeginRegex(R);for(;e;){let U=e.split(`
221
- `,1)[0],Z;if(f=U,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),Z=f):Z=f.replace(this.rules.other.leadingSpaceTab,me=>J(me)),ee.test(f)||te.test(f)||M.test(f)||ne.test(f)||v.test(f)||Q.test(f))break;if(Z.search(this.rules.other.nonSpaceChar)>=R||!f.trim())d+=`
222
- `+Z.slice(R);else{if(y||m.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||ee.test(m)||te.test(m)||M.test(m)||Q.test(m))break;let qe=!this.options.pedantic&&/^ {0,3}(?:=+|-+) *$/.test(f)&&this.rules.block.lheading.test(`${m}
223
- ${f}`)?` ${Z.replace(/^ {0,3}/,"")}`:f;d+=`
224
- `+qe}y=!f.trim(),e=e.substring(U.length+1),m=Z.slice(R)}}let A=n.slice(k,s());i.loose||(p?i.loose=!0:this.rules.other.doubleBlankLine.test(A)&&(p=!0)),i.items.push({type:"list_item",raw:A,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:!1,text:d,tokens:[]})}let h=i.items.at(-1);if(h)h.raw=h.raw.trimEnd(),h.text=h.text.trimEnd();else return;i.raw=n.slice(0,s()).trimEnd();for(let u of i.items)if(this.lexer.state.top=!1,u.tokens=this.lexer.blockTokens(u.text,[]),!i.loose){let d=u.
225
- tokens.filter(g=>g.type==="space"),k=d.length>0&&d.some(g=>this.rules.other.anyLine.test(g.raw));i.loose=k}for(let u of i.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.
226
- 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,i.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",
227
- raw:g.raw,text:g.raw,tokens:[g]}):u.tokens.unshift(g)}}else u.task&&(u.task=!1)}if(i.loose)for(let u of i.items){u.loose=!0;for(let d of u.tokens)d.type==="text"&&(d.type="paragraph")}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=ge(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])&&ke(t[2],"()")!==-1)return;let n=F(t[1]),s=t[2]?t[2].
228
- replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",r=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],`
229
- `),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=de(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,"").split(`
230
- `):[],o={type:"table",raw:L(t[0],`
231
- `),header:[],align:[],rows:[]};if(n.length===s.length){for(let i of s)this.rules.other.tableAlignRight.test(i)?o.align.push("right"):this.rules.other.tableAlignCenter.test(i)?o.align.push("center"):this.rules.other.tableAlignLeft.test(i)?o.align.push("left"):o.align.push(null);for(let i=0;i<n.length;i++)o.header.push({text:n[i],tokens:this.lexer.inline(n[i]),header:!0,align:o.align[i]});for(let i of r)o.rows.push(de(i,o.header.length).map((l,p)=>({text:l,tokens:this.lexer.inline(l),header:!1,align:o.
232
- align[p]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:"heading",raw:L(t[0],`
233
- `),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)===`
234
- `?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.
235
- 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.
236
- options.pedantic&&Be(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 l=L(s.slice(0,-1),"\\");if((s.length-l.length)%2===0)return}else{let l=ke(t[2],"()");if(l===-2)return;if(l>-1){let h=(t[0].indexOf("!")===0?5:4)+t[1].length+l;t[2]=t[2].substring(0,l),t[0]=t[0].substring(0,h).trim(),t[3]=""}}let r=L(t[0].slice(0,-1),"\\");if((t[0].length-r.length)%2===0)return;let o=t[2],
237
- i="";if(this.options.pedantic){let l=this.rules.other.pedanticHrefTitle.exec(o);l&&(o=l[1],i=l[3])}else i=t[3]?t[3].slice(1,-1):"";return o=o.trim(),this.rules.other.startAngleBracket.test(o)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?o=o.slice(1):o=o.slice(1,-1)),De(t,{href:o&&o.replace(this.rules.inline.anyPunctuation,"$1"),title:i&&i.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))||
238
- (n=this.rules.inline.nolink.exec(e))){let s=n[0].charAt(0)==="!"?2:1;if(!this.options.pedantic&&Be(e,n[1],s,this.rules))return;let r=t[F(n[2]||n[1])];if(!r){let o=n[0].charAt(0);return{type:"text",raw:o,text:o}}return De(n,r,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 r=s[0][0],o=n===r,i=t.length-e.length,l=i;for(;!this.options.pedantic&&l>0&&t[l-1]===r;)l--;let p=[...t.slice(Math.max(0,l-2),l)].at(-1)??
239
- "",h=p==="*"||p==="_"||!!this.rules.inline.punctuation.exec(p);l<i&&(n=p);let u=l<i?h:!!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,m=k,f=0,y=i-l+k,R=!this.options.pedantic&&!!p.trim()&&(!!d||r==="*"&&!h);if(r!=="*"&&r!=="_")return;let A=r==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd,v=ze(this,t,r),Q=t.length-e.length+k;if(v<Q)return;t=t.slice(-1*
240
- e.length+k);let ee=v-Q;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]){m+=b;continue}else if(s[5]||s[6]||R){if(o&&(s[5]||s[6]))break;if(y%3&&!((y+b)%3)){f+=b;continue}}if(m-=b,m>0)continue;b=Math.min(b,b+m+f);let te=[...s[0]][0].length,M=e.slice(0,k+s.index+te+b);if(Math.min(k,b)%2){let U=M.slice(1,-1);return{type:"em",raw:M,text:U,tokens:this.lexer.inlineTokens(U)}}let ne=M.slice(2,-2);return{type:"strong",
241
- 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),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(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.delLDelim.exec(e);
242
- if(s&&(!s[1]||!n||this.rules.inline.punctuation.exec(n))){let o=[...s[0]].length-1,i,l,p=o,h=this.rules.inline.delRDelim,u=Me(this,t),d=t.length-e.length+o;if(u<d)return;t=t.slice(-1*e.length+o);let k=u-d;for(h.lastIndex=0;(s=h.exec(t))!==null&&!(s.index>k);){if(i=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!i||(l=[...i].length,l!==o))continue;if(s[3]||s[4]){p+=l;continue}if(p-=l,p>0)continue;l=Math.min(l,l+p);let g=[...s[0]][0].length,b=e.slice(0,o+s.index+g+l),m=b.slice(o,-o);return{type:"del",raw:b,text:m,
243
- tokens:this.lexer.inlineTokens(m)}}}}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 r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??"";while(r!==t[0]);n=t[0],t[1]==="www."?s="http://"+t[0]:s=t[0]}return{type:"link",raw:t[0],
244
- 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]:Ie(t[0]),escaped:n}}}},O=class a{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||S,this.options.tokenizer=this.options.tokenizer||new _,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=
245
- this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,linkParenPossible:!0,top:!0};let t={other:T,block:V.normal,inline:G.normal};this.options.pedantic?(t.block=V.pedantic,t.inline=G.pedantic):this.options.gfm&&(t.block=V.gfm,this.options.breaks?t.inline=G.breaks:t.inline=G.gfm),this.tokenizer.rules=t}static get rules(){return{block:V,inline:G}}static lex(e,t){return new a(t).lex(e)}static lexInline(e,t){return new a(t).inlineTokens(e)}lex(e){e=e.replace(T.carriageReturn,`
246
- `),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,this.options.pedantic&&(e=e.replace(T.tabCharGlobal," ").replace(T.spaceLine,""));let s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(i=>(r=i.call({lexer:this},
247
- 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 i=t.at(-1);r.raw.length===1&&i!==void 0?i.raw+=`
248
- `:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="paragraph"||i?.type==="text"?(i.raw+=(i.raw.endsWith(`
249
- `)?"":`
250
- `)+r.raw,i.text+=`
251
- `+r.text,this.inlineQueue.at(-1).src=i.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.
252
- length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let i=t.at(-1);i?.type==="paragraph"||i?.type==="text"?(i.raw+=(i.raw.endsWith(`
253
- `)?"":`
254
- `)+r.raw,i.text+=`
255
- `+r.raw,this.inlineQueue.at(-1).src=i.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 i=1/0,l=e.slice(1),p;this.options.extensions.startBlock.forEach(h=>{p=h.call({lexer:this},l),typeof p=="number"&&p>=0&&(i=Math.min(i,p))}),i<1/0&&
256
- i>=0&&(o=e.substring(0,i+1))}if(this.state.top&&(r=this.tokenizer.paragraph(o))){let i=t.at(-1);n&&i?.type==="paragraph"?(i.raw+=(i.raw.endsWith(`
257
- `)?"":`
258
- `)+r.raw,i.text+=`
259
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.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 i=t.at(-1);i?.type==="text"?(i.raw+=(i.raw.endsWith(`
260
- `)?"":`
261
- `)+r.raw,i.text+=`
262
- `+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=i.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,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.reflinkSearch)){let s=n[0],
263
- r=s.lastIndexOf("[");if(!(s.charAt(0)==="!"||!Object.hasOwn(this.tokens.links,F(s.slice(r+1,-1))))&&!(r>1&&this.linkInText(s.slice(1,r-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!==_.prototype.emStrong||this.
264
- tokenizer.del!==_.prototype.del?this.#n(e):e;Ae(this.tokenizer,n);try{return this.#t(e,n,t)}finally{Ee(this.tokenizer)}}#t(e,t,n){let s=!1,r="",o=1/0;for(;e;){if(e.length<o)o=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}s||(r=""),s=!1;let i;if(this.options.extensions?.inline?.some(p=>(i=p.call({lexer:this},e,n))?(e=e.substring(i.raw.length),n.push(i),!0):!1))continue;if(i=this.tokenizer.escape(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.tag(e)){e=e.substring(
265
- i.raw.length),n.push(i);continue}if(i=this.tokenizer.link(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(i.raw.length);let p=n.at(-1);i.type==="text"&&p?.type==="text"?(p.raw+=i.raw,p.text+=i.text):n.push(i);continue}if(i=this.tokenizer.emStrong(e,t,r)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.codespan(e)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.br(e)){e=e.substring(i.raw.length),
266
- n.push(i);continue}if(i=this.tokenizer.del(e,t,r)){e=e.substring(i.raw.length),n.push(i);continue}if(i=this.tokenizer.autolink(e)){e=e.substring(i.raw.length),n.push(i);continue}if(!this.state.inLink&&(i=this.tokenizer.url(e))){e=e.substring(i.raw.length),n.push(i);continue}let l=e;if(this.options.extensions?.startInline){let p=1/0,h=e.slice(1),u;this.options.extensions.startInline.forEach(d=>{u=d.call({lexer:this},h),typeof u=="number"&&u>=0&&(p=Math.min(p,u))}),p<1/0&&p>=0&&(l=e.substring(0,p+
267
- 1))}if(i=this.tokenizer.inlineText(l)){e=e.substring(i.raw.length),i.raw.slice(-1)!=="_"&&(r=i.raw.slice(-1)),s=!0;let p=n.at(-1);p?.type==="text"?(p.raw+=i.raw,p.text+=i.text):n.push(i);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return n}#n(e){let t=e;if(this.tokens.links&&e.includes("[")){let n=this.tokenizer.rules.inline.reflinkSearch,s=r=>{let o=r.lastIndexOf("[");if(!Object.hasOwn(this.tokens.links,F(r.slice(o+1,-1))))return r;if(o>1&&r.charAt(0)!=="!"){let i=r.slice(1,o-
268
- 1);if(this.linkInText(i))return"["+i.replace(n,s)+"]["+"a".repeat(r.length-o-2)+"]"}return"["+"a".repeat(r.length-2)+"]"};t=t.replace(n,s)}return t=t.replace(this.tokenizer.rules.inline.anyPunctuationOutsideCode,(n,s,r)=>r?"+".repeat(n.length):s?s+n.slice(s.length,-s.length).replace(/`/g,"+")+s:n),t=t.replace(this.tokenizer.rules.inline.blockSkip,(n,s,r)=>{let o=r?r.length:0;return n.slice(0,o)+"["+"a".repeat(n.length-o-2)+"]"}),t=this.options.hooks?.emStrongMask?.call({lexer:this},t)??t,t}infiniteLoopError(e){
269
- 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||S}space(e){return""}code({text:e,lang:t,escaped:n}){let s=(t||"").match(T.notSpaceStart)?.[0],r=e?e.replace(T.endingNewline,"")+`
270
- `:"";return s?'<pre><code class="language-'+P(s)+'">'+(n?r:P(r,!0))+`</code></pre>
271
- `:"<pre><code>"+(n?r:P(r,!0))+`</code></pre>
272
- `}blockquote({tokens:e}){return`<blockquote>
273
- ${this.parser.parse(e)}</blockquote>
274
- `}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
275
- `}hr(e){return`<hr>
276
- `}list(e){let t=e.ordered,n=e.start,s="";for(let i=0;i<e.items.length;i++){let l=e.items[i];s+=this.listitem(l)}let r=t?"ol":"ul",o=t&&n!==1?' start="'+n+'"':"";return"<"+r+o+`>
277
- `+s+"</"+r+`>
278
- `}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
279
- `}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
280
- `}table(e){let t="",n="";for(let r=0;r<e.header.length;r++)n+=this.tablecell(e.header[r]);t+=this.tablerow({text:n});let s="";for(let r=0;r<e.rows.length;r++){let o=e.rows[r];n="";for(let i=0;i<o.length;i++)n+=this.tablecell(o[i]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),`<table>
281
- <thead>
282
- `+t+`</thead>
283
- `+s+`</table>
284
- `}tablerow({text:e}){return`<tr>
285
- ${e}</tr>
286
- `}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?"th":"td";return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
287
- `}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:r}){let o=r?P(n,!0):this.parser.parseInline(s),i=he(e);if(i===null)return o;e=P(i,r);let l='<a href="'+e+'"';return t&&(l+=' title="'+P(t)+'"'),l+=">"+o+"</a>",l}image({href:e,title:t,
288
- text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=he(e);if(r===null)return P(n);e=r;let o=`<img src="${P(e)}" alt="${P(n)}"`;return t&&(o+=` title="${P(t)}"`),o+=">",o}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,
289
- 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""}checkbox({raw:e}){return e}},w=class a2{options;renderer;textRenderer;constructor(e){this.options=e||S,this.options.renderer=this.options.renderer||new C,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,
290
- this.textRenderer=new E,this.textRenderer.parser=this}static parse(e,t){return new a2(t).parse(e)}static parseInline(e,t){return new a2(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.extensions?.renderers?.[s.type]){let o=s,i=this.options.extensions.renderers[o.type].call({parser:this},o);if(i!==!1||!["space","hr","heading","code","table","blockquote","list","checkbox","html","def","paragraph","text"].includes(o.type)){t+=i||"";
291
- continue}}let r=s;switch(r.type){case"space":{t+=this.renderer.space(r);break}case"hr":{t+=this.renderer.hr(r);break}case"heading":{t+=this.renderer.heading(r);break}case"code":{t+=this.renderer.code(r);break}case"table":{t+=this.renderer.table(r);break}case"blockquote":{t+=this.renderer.blockquote(r);break}case"list":{t+=this.renderer.list(r);break}case"checkbox":{t+=this.renderer.checkbox(r);break}case"html":{t+=this.renderer.html(r);break}case"def":{t+=this.renderer.def(r);break}case"paragrap\
292
- h":{t+=this.renderer.paragraph(r);break}case"text":{t+=this.renderer.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 t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n="";for(let s=0;s<e.length;s++){let r=e[s];if(this.options.extensions?.renderers?.[r.type]){let i=this.options.extensions.renderers[r.type].call({parser:this},r);if(i!==!1||!["escape","html","link","image","checkbo\
293
- x","strong","em","codespan","br","del","text"].includes(r.type)){n+=i||"";continue}}let o=r;switch(o.type){case"escape":{n+=t.text(o);break}case"html":{n+=t.html(o);break}case"link":{n+=t.link(o);break}case"image":{n+=t.image(o);break}case"checkbox":{n+=t.checkbox(o);break}case"strong":{n+=t.strong(o);break}case"em":{n+=t.em(o);break}case"codespan":{n+=t.codespan(o);break}case"br":{n+=t.br(o);break}case"del":{n+=t.del(o);break}case"text":{n+=t.text(o);break}default:{let i='Token with "'+o.type+'\
294
- " type was not found.';if(this.options.silent)return console.error(i),"";throw new Error(i)}}}return n}},I=class{options;block;constructor(e){this.options=e||S}static passThroughHooks=new Set(["preprocess","postprocess","processAllTokens","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.
295
- block){return e?w.parse:w.parseInline}};function z(a3,e){if(Array.isArray(e))for(let t=0;t<e.length;t++)a3.push(e[t]);else a3.push(e)}var Y=class{defaults=H();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.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 r=s;for(let o of r.header)z(n,this.walkTokens(o.tokens,t));for(let o of r.
296
- rows)for(let i of o)z(n,this.walkTokens(i.tokens,t));break}case"list":{let r=s;z(n,this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(o=>{let i=r[o].flat(1/0);z(n,this.walkTokens(i,t))}):r.tokens&&z(n,this.walkTokens(r.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.
297
- async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error("extension name required");if("renderer"in r){let o=t.renderers[r.name];o?t.renderers[r.name]=function(...i){let l=r.renderer.apply(this,i);return l===!1&&(l=o.apply(this,i)),l}:t.renderers[r.name]=r.renderer}if("tokenizer"in r){if(!r.level||r.level!=="block"&&r.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");let o=t[r.level];o?o.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&
298
- (r.level==="block"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level==="inline"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}"childTokens"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new C(this.defaults);for(let o in n.renderer){if(!(o in r))throw new Error(`renderer '${o}' does not exist`);if(["options","parser"].includes(o))continue;let i=o,l=n.renderer[i],p=r[i];r[i]=(...h)=>{
299
- let u=l.apply(r,h);return u===!1&&(u=p.apply(r,h)),u===!1?"":u??""}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new _(this.defaults);for(let o in n.tokenizer){if(!(o in r))throw new Error(`tokenizer '${o}' does not exist`);if(["options","rules","lexer"].includes(o))continue;let i=o,l=n.tokenizer[i],p=r[i];r[i]=(...h)=>{let u=l.apply(r,h);return u===!1&&(u=p.apply(r,h)),u}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new I;for(let o in n.hooks){if(!(o in r))throw new Error(
300
- `hook '${o}' does not exist`);if(["options","block"].includes(o))continue;let i=o,l=n.hooks[i],p=r[i];I.passThroughHooks.has(o)?r[i]=h=>{if(r.options.async&&I.passThroughHooksRespectAsync.has(o))return(async()=>{let d=await l.call(r,h);return p.call(r,d)})();let u=l.call(r,h);return p.call(r,u)}:r[i]=(...h)=>{if(r.options.async)return(async()=>{let d=await l.apply(r,h);return d===!1&&(d=await p.apply(r,h)),d})();let u=l.apply(r,h);return u===!1&&(u=p.apply(r,h)),u}}s.hooks=r}if(n.walkTokens){let r=this.
301
- defaults.walkTokens,o=n.walkTokens;s.walkTokens=function(i){let l=[];return z(l,o.call(this,i)),r&&z(l,r.call(this,i)),l}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...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 r={...s},o={...this.defaults,...r},i=this.onError(!!o.silent,!!o.async);if(this.defaults.async===!0&&r.async===!1)return i(new Error("marked():\
302
- 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 i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(o.hooks&&(o.hooks.options=o,o.hooks.block=e),o.async)return(async()=>{let l=o.hooks?await o.hooks.preprocess(n):n,h=await(o.hooks?await o.hooks.
303
- provideLexer(e):e?O.lex:O.lexInline)(l,o),u=o.hooks?await o.hooks.processAllTokens(h):h;o.walkTokens&&await Promise.all(this.walkTokens(u,o.walkTokens));let k=await(o.hooks?await o.hooks.provideParser(e):e?w.parse:w.parseInline)(u,o);return o.hooks?await o.hooks.postprocess(k):k})().catch(i);try{o.hooks&&(n=o.hooks.preprocess(n));let p=(o.hooks?o.hooks.provideLexer(e):e?O.lex:O.lexInline)(n,o);o.hooks&&(p=o.hooks.processAllTokens(p)),o.walkTokens&&this.walkTokens(p,o.walkTokens);let u=(o.hooks?o.
304
- hooks.provideParser(e):e?w.parse:w.parseInline)(p,o);return o.hooks&&(u=o.hooks.postprocess(u)),u}catch(l){return i(l)}}}onError(e,t){return n=>{if(n.message+=`
305
- 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(a3,e){return q.parse(a3,e)}x.options=x.setOptions=function(a3){return q.setOptions(a3),x.defaults=q.defaults,se(x.defaults),x};x.getDefaults=H;x.defaults=S;function Bt(...a3){return q.use(...a3),x.defaults=q.defaults,se(x.defaults),x}x.use=Bt;x.walkTokens=function(a3,e){return q.walkTokens(
306
- a3,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 _n=x.options,$n=x.setOptions,Ln=x.walkTokens,Cn=x.parseInline;var An=w.parse,En=O.lex;import{spawn}from"child_process";import{readdirSync,statSync}from"fs";import{homedir}from"os";import{basename,dirname,join}from"path";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.
307
- 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.
308
- 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.
309
- 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;
310
- 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((a3,b)=>a3.totalScore-b.totalScore),results.map(r=>r.item)}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.
311
- 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){
312
- 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.
313
- 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}:
314
- prefix.startsWith("@")?{rawPrefix:prefix.slice(1),isAtPrefix:!0,isQuotedPrefix:!1}:{rawPrefix:prefix,isAtPrefix:!1,isQuotedPrefix:!1}}function buildCompletionValue(path5,options){let needsQuotes=options.isQuotedPrefix||autocompleteSeparatorRegex.test(path5),prefix=options.isAtPrefix?"@":"";return needsQuotes?`${`${prefix}"`}${path5}"`:`${prefix}${path5}`}async function walkDirectoryWithFd(baseDir,fdPath,query,maxResults,signal,maxDepth){return(await runFdWalk(baseDir,fdPath,query,maxResults,signal,
315
- 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),
316
- 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?.
317
- 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+=
318
- chunk}))return;if(!stdout)return{entries:[],lineCount:0};let lines=stdout.trim().split(`
319
- `).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(`
320
- `);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 path5=entry.isDirectory?entry.path.slice(0,-1):entry.path,slash=path5.lastIndexOf("/"),name=path5.slice(slash+1);return{path:entry.path,isDirectory:entry.isDirectory,name,topLevel:slash===
321
- -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),
322
- 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(){
323
- 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,
324
- 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&&
325
- !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};
326
- 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.
327
- 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(" ");
328
- 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(
329
- 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);
330
- 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,
331
- 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.
332
- 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.
333
- 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(
334
- '"'),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+
335
- 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(
336
- lastDelimiterIndex===-1?text:text.slice(lastDelimiterIndex+1));return forceExtract||pathPrefix.includes("/")||pathPrefix.startsWith(".")||pathPrefix.startsWith("~/")||pathPrefix===""&&text!==""&&tokenStartRegex.test(text)?pathPrefix:null}expandHomePath(path5){if(path5.startsWith("~/")){let expandedPath=join(homedir(),path5.slice(2));return path5.endsWith("/")&&!expandedPath.endsWith("/")?`${expandedPath}/`:expandedPath}else if(path5==="~")return homedir();return path5}resolveScopedFuzzyQuery(rawQuery){
337
- 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){
338
- 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==="\
339
- /"||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=
340
- 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+
341
- 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
342
- 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((a3,b)=>{let aIsDir=a3.label.endsWith("/"),bIsDir=b.label.endsWith("/");return aIsDir&&!bIsDir?-1:!aIsDir&&bIsDir?1:a3.label.localeCompare(b.label)}),suggestions}catch{
343
- return[]}}scoreEntry(filePath,query,isDirectory){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,
344
- query,100,signal,1)}async getFuzzyFileSuggestions(query,options){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.
345
- recursiveEntries,fdQuery,scopedQuery,options)}catch{return[]}}async runFdForQuery(fdBaseDir,fdQuery,signal){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)
346
- this.fdIndexes.delete(fdBaseDir);else if(index=new FdFolderIndex(this.fdPath,fdBaseDir),this.fdIndexes.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());
347
- let ready=index.readyListFor(fdQuery);if(ready)return this.filterFdList(index,ready,fdQuery);let fdAbort=new AbortController,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:[]};
348
- if("list"in first)return fdAbort.abort(),this.filterFdList(index,first.list,fdQuery);let{results}=first;return results.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}),
349
- selectFdResults(matches,FD_MAX_RESULTS)}rankFdResults(baseDirEntries,recursiveEntries,fdQuery,scopedQuery,options){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((a3,b)=>{let scoreDiff=b.
350
- score-a3.score;if(scoreDiff!==0)return scoreDiff;let aDepth=toDisplayPath(a3.path).split("/").filter(Boolean).length,bDepth=toDisplayPath(b.path).split("/").filter(Boolean).length,depthDiff=aDepth-bDepth;if(depthDiff!==0)return depthDiff;let lengthDiff=a3.path.length-b.path.length;return lengthDiff!==0?lengthDiff:a3.path.localeCompare(b.path)});let topEntries=scoredEntries.slice(0,20),suggestions=[];for(let{path:entryPath,isDirectory}of topEntries){let pathWithoutSlash=isDirectory?entryPath.slice(
351
- 0,-1):entryPath,displayPath=scopedQuery?this.scopedPathForDisplay(scopedQuery.displayBase,pathWithoutSlash):pathWithoutSlash,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]||
352
- "").slice(0,cursorCol);return!(textBeforeCursor.trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};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)+$/;
353
- 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.
354
- 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)
355
- return match[1]==="2"?"light":"dark"}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!==
356
- 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(
357
- 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){
358
- 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")?
359
- {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\
360
- 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"||termProgram==="vscode"||termProgram==="ze\
361
- d"?{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(process.env.HUMAIN_TERMINAL_HYPERLINKS??process.env.PI_HYPERLINKS),
362
- 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);return{...detected,...images!==void 0?{images}:{},...trueColor!==
363
- 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()){return capabilities.
364
- 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=caps,cachedBeforeTmuxAnswer=
365
- !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.rows&&params.push(`r=${options.
366
- 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}return chunks.join("")}function deleteKittyImage(imageId){
367
- 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}`),options.name){let nameBase64=Buffer.from(options.name).
368
- 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=!0,kittyImageMetadata.delete(metadata.imageId),kittyImageMetadata.
369
- 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}}function getMaxKittyImageRows(){return maxKittyImageRows}function getRegisteredKittyImageMetadataFromControls(controls){
370
- 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){let value=/(?:^|,)r=(\d+)(?:,|$)/.exec(controls)?.[1];if(value===void 0)return;let rows=Number.parseInt(
371
- 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(["i","p","x","y","w","h","X","Y","c","r","C","U","z","P","Q","H","V"]);function getKittyImagePlacementRows(line){
372
- 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);if(!metadata)return;let commandStart=match.index,commandControls=match.controls,transmissionEnd;for(;;){let terminator=line.
373
- 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.length,controlsEnd)}let sequence=`\x1B_Ga=p,q=2,${match.controls.split(",").filter(control=>KITTY_PLACEMENT_CONTROL_KEYS.
374
- 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.slice(transmissionEnd)}`}}function cropKittyImageLine(line,hiddenRows,visibleRows){let metadata=getKittyImageMetadata(line),
375
- 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.rows),sourceHeight=Math.max(1,Math.min(metadata.heightPx,sourceEnd)-sourceY),controls=match.controls.split(",").filter(
376
- 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/upperCount);return Math.max(lowerCount/idealCount,idealCount/lowerCount)<upperDistortion?lowerCount:upperCount}
377
- 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.widthPx/imageWidth,heightScale=maxHeight===void 0?widthScale:maxHeight*cellDimensions2.heightPx/
378
- 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<=heightScale){let idealRows=columns*cellDimensions2.widthPx*imageHeight/(imageWidth*cellDimensions2.
379
- 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,void 0,cellDimensions2).rows}function getPngDimensions(base64Data){try{let buffer=Buffer.from(
380
- 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<buffer.length-9;){if(buffer[offset]!==255){offset++;continue}let marker=buffer[offset+
381
- 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.slice(0,6).toString("ascii");if(sig!=="GIF87a"&&sig!=="GIF89a")return null;let width=buffer.
382
- 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==="VP8 "){if(buffer.length<30)return null;let width=buffer.readUInt16LE(26)&16383,height=buffer.
383
- 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,heightPx:height}}return null}catch{return null}}function getImageDimensions(base64Data,mimeType){
384
- 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(imageDimensions,maxWidth,options.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.
385
- 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==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options.
386
- 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){let parts=[];if(filename){let display=shortenImagePath(filename);getCapabilities().hyperlinks&&isAbsolute(
387
- 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(" ")}]`}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){
388
- 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$/;
389
- 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)}
390
- 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<
391
- 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;
392
- 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.
393
- 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)));
394
- 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.
395
- 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&&
396
- 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)}
397
- 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);
398
- 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!==
399
- 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<
400
- 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.
401
- 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=
402
- 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=
403
- !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.
404
- 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?.
405
- 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.
406
- 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(
407
- 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((a3,b)=>a3-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(
408
- 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,
409
- 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&&
410
- 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+
411
- 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.
412
- 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,
413
- 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]}}
414
- 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){
415
- 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);
416
- 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.
417
- 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(){
418
- 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=
419
- !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(){
420
- 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,
421
- 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=
422
- 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.
423
- 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=
424
- {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(){
425
- 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){
426
- 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?
427
- {}:{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();
428
- 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(
429
- 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.
430
- 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(
431
- 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.
432
- 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>=
433
- 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.
434
- 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(
435
- 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(
436
- 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.
437
- 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&&
438
- (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,
439
- 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(){
440
- 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()-
441
- 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(
442
- 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&&
443
- !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&&
444
- (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.
445
- 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){
446
- 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){
447
- 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.
448
- 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,
449
- 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,
450
- 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!==
451
- 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(
452
- (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.
453
- overlayStack)entry.bounds=void 0;let rendered=[],minLinesNeeded=result.length,visibleEntries=this.overlayStack.filter(e=>this.isOverlayVisible(e));visibleEntries.sort((a3,b)=>a3.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));
454
- let{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.
455
- push("");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];
456
- isImageLine(line)||(lines[i]=normalizeTerminalOutput(line)+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(0,markerIndex),col=visibleWidth(
457
- beforeMarker);return lines[row]=line.slice(0,markerIndex)+line.slice(markerIndex+CURSOR_MARKER.length),{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},
458
- ()=>{}),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 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){
459
- 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,
460
- 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],
461
- 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(
462
- 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?.
463
- 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.
464
- 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);return this.bgFn?this.bgFn(padded):padded}};markStableRender(Box);markReportsChanges(Box);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(
465
- 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(
466
- 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);
467
- 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_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,
468
- 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){
469
- 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(){
470
- 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 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;
471
- 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(
472
- 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(
473
- 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 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,theme2,layout={}){this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme2,
474
- this.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();
475
- for(let i=startIndex;i<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,"")))}
476
- return lines}handleMouse(event){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.
477
- getVisibleRange(),itemIndex=startIndex+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.
478
- filteredItems[this.selectedIndex];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.
479
- length-1?0:this.selectedIndex+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(
480
- 0,Math.min(this.selectedIndex-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-
481
- PRIMARY_COLUMN_GAP),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.
482
- selectedText(`${prefix}${truncatedValue2}${spacing}${truncatedDesc}`);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,
483
- visibleWidth(this.getDisplayValue(item))+PRIMARY_COLUMN_GAP),0);return clamp(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.
484
- getDisplayValue(item),truncatedValue=this.layout.truncatePrimary?this.layout.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.
485
- selectedIndex]||null}};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.
486
- 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.
487
- 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(
488
- 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)&&
489
- 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(
490
- 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&&
491
- 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<=
492
- 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>=
493
- 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,
494
- 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=
495
- 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){
496
- 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.
497
- 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}\
498
- (?:@(?:"[^"]*|${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=`\
499
- \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=[
500
- ...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(
501
- cloneEditorSnapshot);onSubmit;onChange;disableSubmit=!1;constructor(tui,theme2,options={}){this.tui=tui,this.theme=theme2,this.borderColor=theme2.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.
502
- 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(
503
- 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){
504
- 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)?
505
- 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=
506
- 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.
507
- 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.
508
- 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(`
509
- `);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){
510
- 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.
511
- 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!==
512
- 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,
513
- 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=
514
- 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.
515
- 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>
516
- 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.
517
- 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){
518
- 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.
519
- 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];
520
- 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.
521
- 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(),
522
- {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(
523
- "\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&&
524
- 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.
525
- 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.
526
- 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\
527
- 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+\
528
- 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\
529
- 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===`
530
- `&&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()||
531
- 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(
532
- 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){
533
- 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{
534
- 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=
535
- 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(`
536
- `)}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(`
537
- `))}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.
538
- insertTextAtCursorInternal(text))}normalizeText(text){return text.replace(/\r\n/g,`
539
- `).replace(/\r/g,`
540
- `).replace(/\t/g," ")}insertTextAtCursorInternal(text){if(!text)return;let normalized=this.normalizeText(text),insertedLines=normalized.split(`
541
- `),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,
542
- ...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),
543
- 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(
544
- 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.
545
- 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===`
546
- `||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(`
547
- `),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(),
548
- 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,"\
549
- 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(`
550
- `)).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(
551
- 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((a3,b)=>a3-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)=>{
552
- 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.state.
553
- 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(
554
- 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=
555
- 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(
556
- 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.
557
- 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!==
558
- 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(){
559
- 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.
560
- state.lines[this.state.cursorLine]=currentLine.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
561
- `,{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.
562
- 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(`
563
- `,{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(
564
- `
565
- `,{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);
566
- 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.
567
- state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
568
- `,{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);
569
- 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.
570
- 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)}
571
- 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.
572
- 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];
573
- 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.
574
- 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+
575
- (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.
576
- 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+
577
- 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(){
578
- 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(`
579
- `);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]||
580
- "");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(`
581
- `);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.
582
- 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,
583
- 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+
584
- 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,
585
- {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.
586
- 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){
587
- 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(
588
- 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(){
589
- 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(
590
- 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;
591
- 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(
592
- 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){
593
- 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.
594
- 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?"\
595
- 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.
596
- 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=
597
- ""}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState==="force",explicitTab:!1})}};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}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(
598
- 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);
599
- 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(
600
- 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))&&
601
- 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)),
602
- 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||
603
- 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 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.
604
- 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||
605
- (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,theme2,options={},dimensions){
606
- this.base64Data=base64Data,this.mimeType=mimeType,this.theme=theme2,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(),
607
- 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.
608
- 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(
609
- 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 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.
610
- 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=
611
- !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===`
612
- `){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\
613
- 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.\
614
- 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")){
615
- 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.
616
- 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(
617
- 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.
618
- 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===
619
- "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();
620
- 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.
621
- 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()||"";
622
- 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(){
623
- 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){
624
- 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().
625
- 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);
626
- 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,
627
- !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,
628
- visualLength=visibleWidth(textWithCursor),padding=" ".repeat(Math.max(0,availableWidth-visualLength));return[this.prompt+textWithCursor+padding]}};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\
629
- }\\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(
630
- `[${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){
631
- 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})|(?!\
632
- ~)${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(
633
- 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(
634
- 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(
635
- 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){
636
- 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(
637
- 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&&
638
- 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(
639
- 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+
640
- 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(
641
- 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+=
642
- 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",
643
- 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",
644
- 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",
645
- 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",
646
- 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:"\
647
- \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:"\
648
- \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:"\
649
- {",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\
650
- 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\
651
- 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\
652
- 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":"\
653
- \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:"\
654
- \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",
655
- 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(
656
- ["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",
657
- 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){
658
- 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.
659
- 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,
660
- 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(`
661
- `).map(line=>line.replace(/[ \t]+/g," ").trim()).filter((line,index,lines)=>line.length>0||index>0&&index<lines.length-1).join(`
662
- `).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.
663
- 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(source2,nodes){
664
- let renderedLines=[],firstBaseline=0;for(let sourceLine of source2.split(`
665
- `)){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?" ":
666
- ""}`: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))],
667
- 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.
668
- 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.
669
- 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.
670
- 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(source2,layoutNodes,display){this.source=source2,this.layoutNodes=layoutNodes,this.display=display}render(){let rendered=this.parseSequence();if(!(!this.supported||this.position!==this.source.length))return normalizeOutput(rendered)}parseSequence(endCharacter){
671
- 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;
672
- 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}
673
- 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===
674
- "_"?"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.
675
- 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??
676
- 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,
677
- "";let command="",first=this.source[this.position]??"";if(first===`
678
- `||first==="\r")return this.position++,first==="\r"&&this.source[this.position]===`
679
- `&&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`
680
- `;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(
681
- !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)?
682
- ` ${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);
683
- 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(
684
- 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.
685
- from(value,character=>BLACKBOARD[character]??character).join("")}if(command==="operatorname"){let starred=this.source[this.position]==="*";starred&&this.position++;let operator2=normalizeOutput(this.parseRequiredArgument()).trim();return this.parseOperator(operator2,"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==="overse\
686
- t"||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=
687
- !1,""):(this.supported=!1,`\\${command}`)}parseOperator(operator2,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(;;){
688
- let scriptPosition=this.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.
689
- layoutNodes.push({type:"operator",operator:operator2,lower,upper})-1;return`${LAYOUT_MARKER_START}${index}${LAYOUT_MARKER_END}`}let rendered=operator2;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.
690
- parseRequiredArgumentValue();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(){
691
- for(;this.position<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;
692
- return}let start=++this.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=`\
693
- \\end{${environment}}`,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===
694
- "gathered"||environment==="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("&"),source2=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(source2).trim()}).filter(Boolean).
695
- join(`
696
- `)}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)),
697
- 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/
698
- 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(
699
- 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===
700
- "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(`
701
- `);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(source2,stackFractions=!0){let rendered=new _LatexParser(source2,this.layoutNodes,this.display&&
702
- stackFractions).render();return rendered===void 0?(this.supported=!1,source2):rendered}};function renderLatex(source2,options={}){let layoutNodes=[],rendered=new LatexParser(source2,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.
703
- slice(indentation).trimEnd()).join(`
704
- `).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(`
705
- `);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(`
706
- `,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)}}};
707
- function isEscaped(source2,index){let backslashes=0;for(let position=index-1;position>=0&&source2[position]==="\\";position--)backslashes++;return backslashes%2===1}function findClosingDelimiter(source2,closing,start){let index=source2.indexOf(closing,start);for(;index>=0&&isEscaped(source2,index);)index=source2.indexOf(closing,index+closing.length);return index}function looksLikePendingDollarMath(source2){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(source2)}function tokenizeInlineLatex(source2){
708
- let opening="",closing="";if(source2.startsWith("$$"))opening="$$",closing="$$";else if(source2.startsWith("\\("))opening="\\(",closing="\\)";else if(source2.startsWith("\\["))opening="\\[",closing="\\]";else if(source2.startsWith("$")&&!/^\$\s/.test(source2))opening="$",closing="$";else return;let closingIndex=findClosingDelimiter(source2,closing,opening.length);if(closingIndex>=0&&opening==="$"&&(/\s$/.test(source2.slice(opening.length,closingIndex))||/^\d/.test(source2.slice(closingIndex+1))||
709
- /^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(source2.slice(opening.length,closingIndex))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(source2.slice(closingIndex+1))||source2.slice(opening.length,closingIndex).includes("`")))return;if(closingIndex<0){let pendingSource=source2.slice(opening.length);return opening.startsWith("\\")||looksLikePendingDollarMath(pendingSource)?{type:"latex",raw:source2,text:pendingSource,pending:!0}:void 0}let text=source2.slice(opening.length,closingIndex);return!text||text.includes(
710
- `
711
- `)?void 0:{type:"latex",raw:source2.slice(0,closingIndex+closing.length),text}}var TABLE_DELIMITER_ROW_REGEX=/^ {0,3}\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;function containsTableStart(source2){let lines=source2.split(`
712
- `);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(source2){let dollarMatch=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(source2);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|$)/.
713
- exec(source2);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(source2);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(source2);if(pendingDollar?.[1]&&looksLikePendingDollarMath(pendingDollar[1])&&
714
- !containsTableStart(pendingDollar[1]))return{type:"latexBlock",raw:pendingDollar[0],text:pendingDollar[1],pending:!0}}var LATEX_MARKDOWN_EXTENSIONS=[{name:"latexBlock",level:"block",start(source2){let match=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(source2);return match?match.index+(match[0].startsWith(`
715
- `)?1:0):void 0},tokenizer:tokenizeBlockLatex},{name:"latex",level:"inline",start(source2){let indices=[source2.indexOf("$"),source2.indexOf("\\("),source2.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(
716
- token.tokens??[]);return}if(token?.type!=="code")return;let marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1],lastLine=token.raw.slice(token.raw.lastIndexOf(`
717
- `)+1);!marker||!lastLine||lastLine.length>=marker.length||lastLine!==marker[0]?.repeat(lastLine.length)||(token.text=token.text.slice(0,-lastLine.length).replace(/\n$/,""))}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;
718
- function inlineFlags(state){return(state.inLink?1:0)|(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(
719
- state),next=nextLexedInlines.get(flags);next===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=
720
- lexed.linkEmitted}return next.set(src,lexed),tokens}},memos=!0;function lexTokens(source2){return memos&&markdownCaching?new InlineMemoLexer(getMarkdownParser().defaults).lex(source2):getMarkdownParser().lexer(source2)}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(a3,b){
721
- if(a3===b)return!0;if(typeof a3!="object"||typeof b!="object"||a3===null||b===null)return!1;if(Array.isArray(a3)){if(!Array.isArray(b)||a3.length!==b.length)return!1;for(let i=0;i<a3.length;i++)if(!sameTokens(a3[i],b[i]))return!1;return!0}if(Array.isArray(b))return!1;let aFields=a3,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(
722
- ["code","heading","hr","list","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(`
723
- `,text)}function lexAddedMarkdown(previous,source2,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(
724
- added!==void 0&&kept!==void 0&&offset>=kept.start?kept.text.slice(offset-kept.start)+added:source2.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++),
725
- tokens.push(token),length+=token.raw.length}if(length===source2.length)return lexedFrom.set(tokens,{tokens:new WeakRef(previous.tokens),shared}),tokens}function lexMarkdown(source2,complete=!0,extended){if(lastLexed=void 0,lastEnd=void 0,!markdownCaching){let tokens2=getMarkdownParser().lexer(source2);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];
726
- if(!(!complete&&known&&entry!==known&&entry.source.length===source2.length&&lexedFrom.get(entry.tokens)?.tokens.deref()!==known.tokens)){if(entry.source.length===source2.length&&entry!==known&&entry.source===source2){if(lexedMarkdown.splice(i,1),complete&&entry.pieced)break;return lexedMarkdown.push(entry),lastLexed=entry,entry.tokens}!complete&&entry.resumable&&source2.length>entry.source.length&&(previous<0||entry.source.length>lexedMarkdown[previous].source.length)&&(entry===known||startsWithText(
727
- source2,entry.source))&&(previous=i)}}let tokens=previous>=0?lexAddedMarkdown(lexedMarkdown[previous],source2,lexedMarkdown[previous]===known?extended?.added:void 0):void 0,pieced=tokens!==void 0,resumable=pieced;if(!tokens){tokens=lexTokens(source2),complete&&(lexedInlines=new Map);let length=0;for(let token of tokens)length+=token.raw.length;resumable=!hasLinkDefinitions(tokens)&&length===source2.length}return trimPartialClosingFences(tokens),previous>=0&&lexedMarkdown.splice(previous,1),lastLexed=
728
- {source:source2,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.
729
- 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})}
730
- 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(a3,b){return a3===b||a3.generation===b.generation&&a3.width===b.width&&a3.paddingX===b.paddingX&&a3.theme===b.theme&&a3.color===b.color&&a3.bgColor===b.bgColor&&a3.bold===b.bold&&a3.italic===
731
- b.italic&&a3.strikethrough===b.strikethrough&&a3.underline===b.underline&&a3.preserveOrderedListMarkers===b.preserveOrderedListMarkers&&a3.preserveBackslashEscapes===b.preserveBackslashEscapes&&a3.renderLatex===b.renderLatex&&a3.renderCodeBlock===b.renderCodeBlock&&a3.codeSources===b.codeSources&&a3.codeBlockRevision===b.codeBlockRevision&&a3.capabilities===b.capabilities}var renderedBlocks=new WeakMap,memoHolders=[],MEMO_HOLDERS_KEPT=16,renderedTokens=new WeakMap,markdownCaching=!0;var codeBlockRegions=new WeakMap;function appendRenderedLines(target,source2){let regions=codeBlockRegions.get(source2);if(regions){let shifted=regions.map(region=>({...region,y:region.y+target.length}));codeBlockRegions.set(target,[...codeBlockRegions.get(target)??[],...shifted])}for(let line of source2)target.push(line)}function normalizeCodeInput(source2,previous){let grows=previous!==void 0&&startsWithText(source2,previous.source),start=grows?previous.source.length+(previous.source.endsWith(
732
- "\r")&&source2[previous.source.length]===`
733
- `?1:0):0,tail=source2.slice(start).replace(/\r\n|\r/g,`
734
- `).replace(/\t/g," "),added=grows?ownString(tail):tail,input={source:source2,text:grows?previous.text+added:added},from=grows?previous.lexed?.deref():void 0;return{input,...from?{extended:{from,added}}:{}}}function codeSourceTail(tokens,shared,source2){if(shared===0)return source2;let length=0;for(let index=shared;index<tokens.length;index++)length+=tokens[index].raw.length;let start=source2.length;for(;length>0&&start>0;)start--,length-=source2[start]===" "?3:1,source2[start]===`
735
- `&&source2[start-1]==="\r"&&start--;return ownString(source2.slice(start))}function normalizedCodeSource(source2){if(!/\t|\r\n/.test(source2))return{text:source2.replace(/\r/g,`
736
- `)};let offsets=[];for(let original=0;original<source2.length;original++){for(let count=source2[original]===" "?3:1;count>0;count--)offsets.push(original);source2[original]==="\r"&&source2[original+1]===`
737
- `&&original++}return offsets.push(source2.length),{text:source2.replace(/\r\n|\r/g,`
738
- `).replace(/\t/g," "),offsets}}function stripCodeContainerPrefixes(source2,prefixes){let{text,offsets}=normalizedCodeSource(source2),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+=source2.slice(cursor,offsets?.[match.index]??match.index)+" ".repeat(remaining),cursor=offsets?.[end+remaining]??end+remaining}return result+source2.slice(
739
- 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].
740
- 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={
741
- array:new LiveLineArray,ends:[],substituted:!1};constructor(text,paddingX,paddingY,theme2,defaultTextStyle,options){this.text=sanitizeTerminalText(text),options?.renderCodeBlock&&(this.rawText=text),this.paddingX=paddingX,this.paddingY=paddingY,this.theme=theme2,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.
742
- sanitized.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=
743
- 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,
744
- 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.
745
- 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)?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?.settings.
746
- 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.paddingBackground=
747
- 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(lineWithMargins),
748
- paddingNeeded=Math.max(0,width-visibleLen);padded=lineWithMargins+" ".repeat(paddingNeeded)}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({...region,x:region.x+settings.paddingX,y:lines.length});if(isImageLine(line))add(
749
- 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({settings,nextTokenType,lines,highlightedCode})),lines}renderTokens(tokens,settings,contentWidth){let known=renderedTokens.get(tokens);if(known&&sameSettings(known.settings,settings))return known.lines;let lines=[],ends=[],reused=0,from=lexedFrom.get(
750
- 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(tokens),previousBlocks=this.blocks?.deref(),blocks=new Map;this.blocks=new WeakRef(
751
- 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,lines,ends}),lines}tokensFor(width){let padding=this.options.renderCodeBlock?Math.min(
752
- 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,this.codeInput):void 0,normalized=native?{text:native.input.text,extended:native.extended,
753
- 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.added}:void 0);tokens=lexMarkdown(normalizedText,this.options.complete,extended);let lexed=lastLexed?.
754
- 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!==cached?.tokens||this.codeSourceText!==text||this.codeOriginalText!==originalText)){let previousTokens=this.
755
- 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(changed),previousBlocks=fencedCodeTokens(previousTokens?.slice(shared)??[]),growingBlock=fencedCodeTokens(
756
- 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.extended);lastLexed?.tokens===originalTokens&&(normalized2.input.lexed=new WeakRef(lastLexed)),this.originalCodeInput=
757
- 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,originalShared,originalText),this.originalCodeSources)}let sourceMap=originals===renderedBlocks2?this.codeSources:this.
758
- 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)===sourceMap.get(original))&&(used.add(original),matched.set(block,original))}let unmatched=originals.filter(original=>!used.
759
- 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),source2=appended&&block!==growingBlock&&this.codeOriginalSources.has(block)?this.codeOriginalSources.get(block):original?sourceMap.get(original):void 0,previous=previousBlocks[index];if((this.codeOriginalSources.has(block)&&this.codeOriginalSources.get(block)!==source2||previous?.raw===
760
- block.raw&&(this.codeOriginalSources.get(previous)!==source2||this.codeSources.get(previous)!==this.codeSources.get(block)))&&(this.codeComponents.delete(block),this.codeBlockRevision++),!this.codeComponents.has(block)&&previous&&this.codeOriginalSources.get(previous)===source2&&this.codeSources.get(previous)===this.codeSources.get(block)&&sameTokens(previous,block)){let component=this.codeComponents.get(previous);component&&this.codeComponents.set(block,component)}this.codeOriginalSources.set(block,
761
- source2)}this.codeSourceText=text,this.codeOriginalText=originalText,this.codeSourceTransformed=transformed,this.codeSourceTokens=new WeakRef(tokens)}return{tokens,contentWidth}}rememberCodeSources(tokens,source2,sources=this.codeSources){let{text:normalized,offsets}=normalizedCodeSource(source2),cursor=0;for(let token of tokens){let start=normalized.indexOf(token.raw,cursor),raw=start<0?token.raw:source2.slice(offsets?.[start]??start,offsets?.[start+token.raw.length]??start+token.raw.length);if(start>=
762
- 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),sources);else if(token.type==="list"){let listSource=normalizedCodeSource(raw),itemCursor=0;for(let item of token.items){let marker=/^( {0,3}(?:[-+*]|\d+[.)])[ \t]+)/.
763
- 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(itemSource,new RegExp(`^ {0,3}(?:[-+*]|\\d+[.)]) +|(?<=\\n) {1,${Math.max(1,marker.length)}}`,"g"));this.rememberCodeSources(item.tokens,unindented,sources)}}}}codeComponent(token){
764
- 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.get(token)??raw),lastLine=text.slice(text.lastIndexOf(`
765
- `)+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)===
766
- 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),y=this.paddingY;for(let index=0;index<prepared.tokens.length;index++){
767
- 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-y-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})}y+=lines.length}}textFacts(){let text=this.text,facts=this.facts;return facts?.text!==text&&(facts={text,
768
- 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(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.size>2;)this.paddedLines.
769
- 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(),this.options.complete!==
770
- !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,settings=this.renderSettings(
771
- 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?result:(reportRenderChange(
772
- 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.length>0&&lines.edit(0),live.
773
- 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!==before[reused]?.type&&reused--);
774
- 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)??previousBlocks?.get(token.raw):
775
- 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.edit(0),lines.lines.push(""),
776
- 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(styled)),styled}getDefaultStylePrefix(){
777
- 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.theme.underline(styled));let sentinelIndex=styled.
778
- 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=[];switch(token.type){case"heading":{let headingLevel=token.
779
- 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(headingPrefix)+headingText:headingText;lines.push(styledHeading),
780
- 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?renderLatex(latexToken.text,{display:!0}):void 0;(rendered===void 0||
781
- rendered.split(`
782
- `).some(line=>visibleWidth(line)>width))&&(rendered=latexToken.raw.trim());for(let line of rendered.split(`
783
- `))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.
784
- 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(`
785
- `);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(
786
- 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=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={applyText:text=>text,
787
- stylePrefix:quoteStylePrefix},quoteTokens=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.get(renderedQuoteLines),shiftedRegions=[];
788
- 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),nextTokenType&&nextTokenType!==
789
- "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":"raw"in token&&typeof token.raw=="string"&&lines.push(this.applyDefaultStyle(token.raw.trim()));break;case"space":lines.push("");break;default:"text"in token&&typeof token.text=="string"&&lines.push(token.text)}return lines}renderInlineTokens(tokens,styleContext){let result="",resolvedStyleContext=styleContext??this.getDefaultInlineStyleContext(),
790
- {applyText,stylePrefix}=resolvedStyleContext,applyTextWithNewlines=text=>text.split(`
791
- `).map(segment=>applyText(segment)).join(`
792
- `);for(let token of tokens)switch(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(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.
793
- 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.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.
794
- 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("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":
795
- result+=`
796
- `;break;case"del":{let delContent=this.renderInlineTokens(token.tokens||[],resolvedStyleContext);result+=this.theme.strikethrough(delContent)+stylePrefix;break}case"html":"raw"in token&&typeof token.raw=="string"&&(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){let match=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.
797
- 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?this.getOrderedListMarker(
798
- 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 item.tokens){if(itemToken.type==="list"){appendRenderedLines(lines,this.renderList(itemToken,
799
- 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)){let linePrefix=renderedAnyLine?continuationPrefix:firstPrefix;
800
- 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(text,Math.max(1,maxWidth));return lines.map((line,index)=>{
801
- 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 fallbackLines=token.raw?wrapTextWithAnsi(token.raw,availableWidth):[];return nextTokenType&&nextTokenType!=="space"&&fallbackLines.push(""),fallbackLines}
802
- 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.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]=
803
- Math.max(minWordWidths[i]||1,this.getLongestWordWidth(cellText,maxUnbrokenWordWidth))}let minColumnWidths=minWordWidths,minCellsWidth=minColumnWidths.reduce((a3,b)=>a3+b,0);if(minCellsWidth>availableForCells){minColumnWidths=new Array(numCols).fill(1);let remaining=availableForCells-numCols;if(remaining>0){let totalWeight=minWordWidths.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*
804
- 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((a3,b)=>a3+b,0)}let totalNaturalWidth=naturalWidths.reduce((a3,b)=>a3+b,0)+borderOverhead,columnWidths;if(totalNaturalWidth<=availableWidth)columnWidths=naturalWidths.map((width,index)=>Math.max(width,minColumnWidths[index]));else{let totalGrowPotential=naturalWidths.
805
- 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>0&&(grow=Math.floor(minWidthDelta/totalGrowPotential*extraWidth)),minWidth+grow});let allocated=columnWidths.reduce((a3,b)=>a3+b,0),remaining=availableForCells-allocated;for(;remaining>0;){let grew=!1;
806
- 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.map((cell,i)=>{let text=this.renderInlineTokens(cell.tokens||[],styleContext);return this.wrapCellText(text,columnWidths[i],styleContext?.stylePrefix)}),headerLineCount=Math.max(...headerCellLines.
807
- map(c3=>c3.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(" \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.
808
- 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(c3=>c3.length));for(let lineIdx=0;lineIdx<rowLineCount;lineIdx++){let rowParts=rowCellLines.map((cellLines,colIdx)=>{let text=cellLines[lineIdx]||"";return text+" ".repeat(Math.max(0,columnWidths[colIdx]-visibleWidth(text)))});lines.push(`\u2502 ${rowParts.
809
- 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(Markdown);markReportsChanges(Markdown);markLiveRender(Markdown.prototype.render,function(width){return this.renderLive(width)});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(
810
- 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 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.
811
- 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??
812
- 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.
813
- 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=
814
- 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={}){
815
- 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!==
816
- 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-
817
- 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<=
818
- 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){
819
- 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&&
820
- (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:"\
821
- scroll",component:this.child,state:this}}};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,theme2,onChange,onCancel,options={}){this.items=items,this.filteredItems=items,this.maxVisible=maxVisible,this.theme=theme2,this.onChange=onChange,this.onCancel=onCancel,this.searchEnabled=options.enableSearch??!1,this.searchEnabled&&(this.
822
- searchInput=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.
823
- push(...this.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(
824
- 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,
825
- 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(
826
- ` ${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.
827
- 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=
828
- 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.
829
- 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(
830
- 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.
831
- 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];
832
- 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){
833
- 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))}};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(`
834
- `);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}};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.
835
- 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,
836
- 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}};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),
837
- "..",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.
838
- 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")}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){
839
- 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"\
840
- 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\
841
- 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){
842
- 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(
843
- 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]!=="\\"){
844
- 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.
845
- 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]>
846
- 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.
847
- 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.
848
- 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;
849
- 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.
850
- 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.
851
- 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()}};import*as fs from"node:fs";import*as path2 from"node:path";function isNativeModifierPressed(key){let helper=getNativePlatformHelper();if(!helper?.isModifierPressed)return!1;try{return helper.isModifierPressed(key)===!0}catch{return!1}}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$/);
852
- 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.
853
- 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=(()=>{
854
- 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(){
855
- 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(){
856
- 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(
857
- 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.
858
- 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(),
859
- 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||
860
- 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(
861
- 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(){
862
- 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(
863
- ()=>{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()||
864
- 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===
865
- "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.
866
- 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&&
867
- 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.
868
- 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\
869
- 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>
870
- 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.
871
- 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(){
872
- return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};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+=
873
- 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(
874
- 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,
875
- 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){if(!normalizedQuery)return[];let expression=new RegExp(escapeRegExp(normalizedQuery),"giu"),matches=[],spanIndex=0;for(let match of corpus.
876
- 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.startCol+Math.max(start,span.textStart)-span.textStart:span.startCol,endCol=span.linearColumns?span.startCol+Math.min(end,span.textEnd)-
877
- 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}var AltScreenSearchIndex=class{sourceLines;live;revision=-1;corpus;normalizedQuery;matches=[];search(lines,query,live){let changedFrom=0;
878
- 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=Number.POSITIVE_INFINITY}let sourceChanged=changedFrom!==Number.POSITIVE_INFINITY;if(!this.corpus||changedFrom===0)this.corpus=buildSearchCorpus(
879
- lines);else if(sourceChanged){let 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;return changed&&(this.normalizedQuery=normalizedQuery,this.matches=findSearchCorpusMatches(this.corpus,normalizedQuery)),{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){
880
- 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===
881
- 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.
882
- 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-
883
- 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);
884
- 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&&
885
- 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===
886
- 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(
887
- entry.timer);this.entries.length=0}invalidate(){}render(width){return this.entries.map(entry=>`\x1B[7m${truncateToWidth(` ${entry.message} `,width,"")}\x1B[27m`)}};var OSC133_ZONE_PREFIX=/^(?:\x1b\]133;[ABC](?:\x07|\x1b\\))+/;function intersect(a3,b){let x2=Math.max(a3.x,b.x),y=Math.max(a3.y,b.y),right=Math.min(a3.x+a3.width,b.x+b.width),bottom=Math.min(a3.y+a3.height,b.y+b.height);return{x:x2,y,width:Math.max(0,right-x2),height:Math.max(0,bottom-y)}}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?.
888
- 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)),
889
- 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.
890
- rect);let children=box.children;for(let i=0;i<children.length;i++)updateClips(children[i],box.clip)}function layoutComponent(context,component,x2,y,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(
891
- CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=cursorLine-allocatedHeight2+1)}return{component,rect:{x:x2,y,width:safeWidth,height:allocatedHeight2},clip:intersect(clip,{x:x2,y,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,y-previousScrollTop,contentWidth,void 0,clip),contentHeight=childBox.
892
- 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,width:safeWidth,height:viewportHeight},childClip=intersect(clip,rect2),content=renderCached(context,node.component,contentWidth),box2={component,
893
- 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\
894
- 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,width:safeWidth,height:allocatedHeight2},box2={component,rect:rect2,clip:intersect(clip,rect2),children:[],layer:0},childY=y;for(let index=0;index<entries.
895
- 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===
896
- void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,y,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=y;node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):
897
- 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){
898
- 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.
899
- 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]?.
900
- 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===
901
- 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.
902
- 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.
903
- 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(
904
- 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.
905
- 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.
906
- 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,
907
- 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,y){return x2>=rect.x&&x2<rect.x+rect.width&&y>=rect.y&&y<rect.y+rect.height}function getLayoutBoxesAt(frame,x2,y){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y)){result.push({box,depth});for(let child of box.
908
- children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.box.layer-a3.box.layer||b.depth-a3.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,y){let result=[],visit=(box,depth)=>{if(containsPoint(box.clip,x2,y)){box.scrollView&&containsPoint(box.rect,x2,
909
- y)&&result.push({scrollView:box.scrollView,depth});for(let child of box.children)visit(child,depth+1)}};return visit(frame.root,0),result.sort((a3,b)=>b.depth-a3.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(
910
- 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.
911
- 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\\))+/,
912
- 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="\
913
- 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={}){
914
- 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(
915
- 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??
916
- !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(){
917
- 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(){
918
- 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=
919
- [],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:
920
- 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}`),
921
- 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(
922
- 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
923
- `),buffer+=`\r\x1B[2K${this.lastDocument[row]??""}`;buffer+=`\x1B[0m${ENABLE_AUTOWRAP}\r
924
- \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.
925
- 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.
926
- 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+=
927
- 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-=
928
- 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().
929
- 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(
930
- 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.
931
- 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,y){let search=this.activeSearch,bounds=search?.
932
- overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||y<bounds.row||y>=bounds.row+bounds.height))return search.component.getNavigationDirectionAt(y-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)!==0||
933
- (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",result=search.
934
- 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].segments[0]?.
935
- 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 selectedIndex=
936
- 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||!lastSegment||
937
- 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?!0:this.isOverlayFocused()&&
938
- 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.setHoveredNavigationDirection(
939
- 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(data);if(wheelEvent){let lines=this.
940
- 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}):(this.routeWheel(wheelEvent,wheelDelta),
941
- {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.navigateSearch(1),{consume:!0};if(keybindings.
942
- 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.altScreen.pageDown"))return isRelease||this.scrollBy(
943
- 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(data,"tui.altScreen.lineUp"))return isRelease||
944
- 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};if(keybindings.matches(data,"tui.altScreen.\
945
- 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,y,extra={}){return{type,button:type==="wheel"?"none":this.decodeMouseButton(button),x:x2,y,screenX:x2,screenY:y,width:Math.max(1,this.terminal.columns),height:Math.max(1,this.terminal.rows),shift:(button&4)!==0,alt:(button&8)!==0,ctrl:(button&16)!==0,...extra.wheelDelta===void 0?
946
- {}:{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(box.component,{...event,x:event.screenX-box.rect.
947
- 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"||event.type==="click"||event.type==="drag"||event.
948
- type==="wheel")}dispatchMouseToTarget(event,target){return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,y){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===y?previous.count%3+1:1;return this.lastComponentClick={timestamp:now,count,component:target.component,x:x2,y},count}clearTextSelection(){this.stopSelectionAutoScroll(),
949
- 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||this.mousePressTarget){let target=this.mouseCapture??this.mousePressTarget;
950
- 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("click",raw.button,raw.x,raw.y,{clickCount:this.getComponentClickCount(
951
- 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.handleScrollbarMouseEvent(raw);if(this.scrollbarDrag||
952
- 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(raw)}parseWheelEvent(data){let sgr=/^\x1b\[<(\d+);(\d+);(\d+)[Mm]$/.
953
- 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===0?-1:1,x:data.charCodeAt(4)-33,y:data.charCodeAt(5)-33,button}}}routeWheel(event,delta){
954
- 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){let match=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(data);if(match)
955
- 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;return!rect||event.release||(event.button&32)!==0||(event.button&
956
- 3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,y,includeHiddenAuto=!1){if(!(this.hasOverlay()||!this.currentLayout))for(let scrollView of getScrollViewsAt(this.currentLayout,x2,y)){let box=getScrollViewBox(this.currentLayout,scrollView),geometry=box?getScrollbarGeometry(box,includeHiddenAuto):void 0;if(geometry&&x2===geometry.column&&y>=geometry.trackTop&&y<geometry.trackTop+geometry.trackHeight)return{scrollView,
957
- geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,y){this.setScrollbarHover(this.getScrollbarTargetAt(x2,y,!0)?.scrollView)}stopScrollbarHover(){this.setScrollbarHover(void 0)}scrollScrollbarToPointer(scrollView,geometry,pointerY,grabOffset){let maxThumbOffset=geometry.trackHeight-geometry.thumbHeight,thumbOffset=Math.max(0,Math.
958
- 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&&this.scrollScrollbarToPointer(this.scrollbarDrag.
959
- 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=!1,this.setScrollbarHover(target.scrollView);
960
- 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,y){if(!this.currentLayout)return;let box=getScrollViewBox(
961
- 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,y)),maxContentRow=Math.max(0,(box.scrollContentLines?.length??1)-1);return{row:Math.max(0,Math.min(maxContentRow,scrollView.scrollTop+pointerRow-box.rect.y)),col:Math.max(
962
- 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)?.scrollContentLines;if(lines)return lines[point.
963
- 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.col>=segment.start&&point.col<segment.
964
- 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++)selectionEnd=segments[index+1].end;
965
- 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)return;let initial=this.selectionInitialRange;
966
- 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.wordStart===word.start.col&&previous.wordEnd===
967
- 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();return}let visibleTop=Math.
968
- 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.unref())}autoScrollSelection(){
969
- 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&&(clearInterval(this.selectionAutoScrollTimer),
970
- 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))return;this.updateSelectionFocus(point);let isClick=!this.
971
- 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.y,{clickCount:this.lastClick?.count??1}),overlay=this.dispatchMouseToOverlay(
972
- 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.lastClick=void 0,this.pressedUrl=void 0,this.updateSelectionFocus(point),this.
973
- 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(anchor):void 0;this.selectionGranularity=range?clickCount===2?"word":"lin\
974
- e":"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.selectionAnchor.scrollView!==this.selectionFocus.scrollView)return;let anchorBeforeFocus=this.
975
- 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(line)){let lineWidth=visibleWidth(line),
976
- 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(){let selection=this.getSelectionBounds();
977
- 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(line,columns.start,Math.max(0,columns.
978
- end-columns.start),!0)).trimEnd())}let text=lines.join(`
979
- `);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){
980
- 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.
981
- 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??
982
- 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;
983
- 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(
984
- line))continue;let lineWidth=visibleWidth(line);for(let range of ranges.sort((a3,b)=>b.startCol-a3.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){
985
- 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){
986
- 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.
987
- 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,
988
- !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||
989
- !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??
990
- 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.
991
- 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)
992
- 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>
993
- 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=
994
- 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});
995
- 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?
996
- 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=
997
- 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]??""))),isWezTerm=!!process.env.WEZTERM_PANE||process.env.TERM_PROGRAM?.toLowerCase()==="wezterm",imageCellsNeedRedraw=!imageAnchorsNeedRedraw&&isWezTerm&&this.
998
- imageProtocol==="kitty"&&imageRows.size>0&&screen.some((line,row)=>{if(!imageRows.has(line))return!1;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.
999
- size>0,preparedKittyScreen=redrawImages&&this.imageProtocol==="kitty"?this.prepareKittyScreen(screen):{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()));
1000
- if(buffer+=preparedKittyScreen.evictedImageDeletion,redrawImages&&this.imageProtocol==="kitty"&&imageRows.size>0&&isWezTerm){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<
1001
- height;row++)!fullRedraw&&!imagesNeedRedraw&&screen[row]===this.previousScreen[row]||isImageLine(preparedKittyScreen.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+
1002
- 1};1H${`
1003
- `.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,
1004
- 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,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(end-1)>=55296&&value.charCodeAt(end-1)<=56319&&
1005
- 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);if(sequenceStart===-1)return;let paramsStart=sequenceStart+
1006
- 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){return parseKittyImageHeader(line)?.ids??[]}function extractKittyImageRows(line){
1007
- 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++)previousLines[i]=this.shownLine(i);return{previousLines,previousWidth:this.
1008
- 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.previousWidth,this.previousHeight=state.previousHeight,this.cursorRow=state.
1009
- 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||this.shownLength===0)return;this.terminal.write(" ");let lineDiff=this.
1010
- shownLength-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
1011
- `)}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;
1012
- 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(
1013
- 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++){
1014
- 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.
1015
- length!==root.length||raw===resolved||raw===root||raw.length<unchanged||this.restoredLines!==void 0||this.shownLength!==raw.length)return;let source2=live.lines,rootTail=root.slice(unchanged);root.length=unchanged;for(let i=unchanged;i<source2.length;i++)root.push(source2[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]):
1016
- (single[0]=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(
1017
- rows.source(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(
1018
- line)||visibleWidth(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=
1019
- Math.max(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(
1020
- ids)}noteShown(length){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,
1021
- hardwareCursorRow=this.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&&
1022
- !this.hasOverlayEntries&&(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,
1023
- finished=changed;else{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,
1024
- frame={length:frameLength,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):
1025
- new Set,fullRender=clear=>{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
1026
- `);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
1027
- `);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"),output2.flush(),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),
1028
- this.positionHardwareCursor(cursorPos,frameLength),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} (pr\
1029
- ev=${shownLength}, new=${frameLength}, height=${height})
1030
- `;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.
1031
- 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.
1032
- 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.
1033
- lastChanged}let appendStart=appendedLines&&firstChanged===shownLength&&firstChanged>0;if(firstChanged===-1){this.positionHardwareCursor(cursorPos,frameLength),this.previousViewportTop=prevViewportTop,this.previousHeight=height,restoredLines===void 0&&this.noteShown(frameLength);return}if(firstChanged>=frameLength){if(shownLength>frameLength){let output2=new BoundedTerminalWriter(data=>this.terminal.write(data));output2.append("\x1B[?2026h"),output2.append(this.deleteChangedKittyImages(firstChanged,
1034
- 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 > height (${extraLines} > ${height})`),fullRender(!0);return}let clearStartOffset=frameLength===
1035
- 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"),output2.flush(),this.cursorRow=targetRow,this.hardwareCursorRow=targetRow}this.positionHardwareCursor(cursorPos,frameLength),this.noteShown(frameLength),this.previousKittyImageIds=collectKittyImageIds(
1036
- 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,shown));let prevViewportBottom=prevViewportTop+height-1,moveTargetRow=appendStart?firstChanged-
1037
- 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
1038
- `.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
1039
- `:"\r");let renderEnd=Math.min(lastChanged,frameLength-1);for(let i=firstChanged;i<=renderEnd;i++){i>firstChanged&&output.append(`\r
1040
- `);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
1041
- \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)=>{
1042
- let l=frame.written(idx);return`[${idx}] (w=${visibleWidth(l)}) ${l}`}),""].join(`
1043
- `);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(`
1044
- `);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
1045
- \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}`,
1046
- `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(`
1047
- `);fs2.writeFileSync(debugPath,debugData)}output.flush(),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),this.noteShown(frameLength),this.previousKittyImageIds=collectKittyImageIds(frame),this.previousWidth=width,this.previousHeight=height}positionHardwareCursor(cursorPos,totalLines){
1048
- if(!cursorPos||totalLines<=0){this.terminal.hideCursor();return}let targetRow=Math.max(0,Math.min(cursorPos.row,totalLines-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&&this.terminal.write(buffer),this.hardwareCursorRow=targetRow,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};import*as fs3 from"node:fs";import*as path4 from"node:path";import{watch}from"node:fs";var FS_WATCH_RETRY_DELAY_MS=5e3;function closeWatcher(watcher){if(watcher)try{watcher.close()}catch{}}function watchWithErrorHandler(path5,listener,onError){try{let watcher=watch(path5,listener);return watcher.on("error",onError),watcher}catch{return onError(),null}}var import_core=__toESM(require_core(),1);var core_default=import_core.default;function bash(hljs2){let regex=hljs2.regex,VAR={},BRACED_VAR={begin:/\$\{/,end:/\}/,contains:["self",{begin:/:-/,contains:[VAR]}]};Object.assign(VAR,{className:"variable",variants:[{begin:regex.concat(/\$[\w\d#@][\w\d_]*/,"(?![\\w\\d])(?![$])")},BRACED_VAR]});let SUBST={className:"subst",begin:/\$\(/,end:/\)/,contains:[hljs2.BACKSLASH_ESCAPE]},COMMENT=hljs2.inherit(hljs2.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:"comment"}}),HERE_DOC={begin:/<<-?\s*(?=\w+)/,starts:{contains:[hljs2.END_SAME_AS_BEGIN(
1049
- {begin:/(\w+)/,end:/(\w+)/,className:"string"})]}},QUOTE_STRING={className:"string",begin:/"/,end:/"/,contains:[hljs2.BACKSLASH_ESCAPE,VAR,SUBST]};SUBST.contains.push(QUOTE_STRING);let ESCAPED_QUOTE={match:/\\"/},APOS_STRING={className:"string",begin:/'/,end:/'/},ESCAPED_APOS={match:/\\'/},ARITHMETIC={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:"number"},hljs2.NUMBER_MODE,VAR]},SH_LIKE_SHELLS=["fish","bash","zsh","sh","csh","ksh","tcsh","dash","scsh"],KNOWN_SHEBANG=hljs2.
1050
- SHEBANG({binary:`(${SH_LIKE_SHELLS.join("|")})`,relevance:10}),FUNCTION={className:"function",begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[hljs2.inherit(hljs2.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},KEYWORDS3=["if","then","else","elif","fi","time","for","while","until","in","do","done","case","esac","coproc","function","select"],LITERALS3=["true","false"],PATH_MODE={match:/(\/[a-z._-]+)+/},SHELL_BUILT_INS=["break","cd","continue","eval","exec","exit","export","getopts","hash",
1051
- "pwd","readonly","return","shift","test","times","trap","umask","unset"],BASH_BUILT_INS=["alias","bind","builtin","caller","command","declare","echo","enable","help","let","local","logout","mapfile","printf","read","readarray","source","sudo","type","typeset","ulimit","unalias"],ZSH_BUILT_INS=["autoload","bg","bindkey","bye","cap","chdir","clone","comparguments","compcall","compctl","compdescribe","compfiles","compgroups","compquote","comptags","comptry","compvalues","dirs","disable","disown","e\
1052
- chotc","echoti","emulate","fc","fg","float","functions","getcap","getln","history","integer","jobs","kill","limit","log","noglob","popd","print","pushd","pushln","rehash","sched","setcap","setopt","stat","suspend","ttyctl","unfunction","unhash","unlimit","unsetopt","vared","wait","whence","where","which","zcompile","zformat","zftp","zle","zmodload","zparseopts","zprof","zpty","zregexparse","zsocket","zstyle","ztcp"],GNU_CORE_UTILS=["chcon","chgrp","chown","chmod","cp","dd","df","dir","dircolors",
1053
- "ln","ls","mkdir","mkfifo","mknod","mktemp","mv","realpath","rm","rmdir","shred","sync","touch","truncate","vdir","b2sum","base32","base64","cat","cksum","comm","csplit","cut","expand","fmt","fold","head","join","md5sum","nl","numfmt","od","paste","ptx","pr","sha1sum","sha224sum","sha256sum","sha384sum","sha512sum","shuf","sort","split","sum","tac","tail","tr","tsort","unexpand","uniq","wc","arch","basename","chroot","date","dirname","du","echo","env","expr","factor","groups","hostid","id","link",
1054
- "logname","nice","nohup","nproc","pathchk","pinky","printenv","printf","pwd","readlink","runcon","seq","sleep","stat","stdbuf","stty","tee","test","timeout","tty","uname","unlink","uptime","users","who","whoami","yes"];return{name:"Bash",aliases:["sh","zsh"],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:KEYWORDS3,literal:LITERALS3,built_in:[...SHELL_BUILT_INS,...BASH_BUILT_INS,"set","shopt",...ZSH_BUILT_INS,...GNU_CORE_UTILS]},contains:[KNOWN_SHEBANG,hljs2.SHEBANG(),FUNCTION,ARITHMETIC,COMMENT,
1055
- HERE_DOC,PATH_MODE,QUOTE_STRING,ESCAPED_QUOTE,APOS_STRING,ESCAPED_APOS,VAR]}}function c2(hljs2){let regex=hljs2.regex,C_LINE_COMMENT_MODE=hljs2.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),DECLTYPE_AUTO_RE="decltype\\(auto\\)",NAMESPACE_RE="[a-zA-Z_]\\w*::",FUNCTION_TYPE_RE="("+DECLTYPE_AUTO_RE+"|"+regex.optional(NAMESPACE_RE)+"[a-zA-Z_]\\w*"+regex.optional("<[^<>]+>")+")",ATOMIC_TYPES=regex.concat(/\batomic_/,regex.either("bool","char","schar","uchar","short","ushort","int","uint","long","ulong","llong","ullong","char16_t","char32_t","wchar_t","int_least8_t","uint_leas\
1056
- t8_t","int_least16_t","uint_least16_t","int_least32_t","uint_least32_t","int_least64_t","uint_least64_t","int_fast8_t","uint_fast8_t","int_fast16_t","uint_fast16_t","int_fast32_t","uint_fast32_t","int_fast64_t","uint_fast64_t","intptr_t","uintptr_t","size_t","ptrdiff_t","intmax_t","uintmax_t"),/\b/),TYPES3={className:"type",variants:[{begin:"\\b[a-z\\d_]*_t\\b"},{match:ATOMIC_TYPES}]},STRINGS={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[hljs2.BACKSLASH_ESCAPE]},
1057
- {begin:"(u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},hljs2.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\\s"]{0,16})\(/,end:/\)([^()\\\s"]{0,16})"/})]},NUMBERS={className:"number",variants:[{match:/\b(0b[01']+)/},{match:/(-?)\b([\d']+(\.[\d']*)?|\.[\d']+)((ll|LL|l|L)(u|U)?|(u|U)(ll|LL|l|L)?|f|F|b|B)/},{match:/(-?)\b(0[xX][a-fA-F0-9]+(?:'[a-fA-F0-9]+)*(?:\.[a-fA-F0-9]*(?:'[a-fA-F0-9]*)*)?(?:[pP][-+]?[0-9]+)?(l|L)?(u|U)?)/},{match:/(-?)\b\d+(?:'\d+)*(?:\.\d*(?:'\d*)*)?(?:[eE][-+]?\d+)?/}],
1058
- relevance:0},PREPROCESSOR_INCLUDE={scope:"meta",begin:/#\s*include\b/,end:/$/,keywords:{keyword:"include"},contains:[{begin:/\\\n/},STRINGS,{scope:"string",begin:/<.*?>/},C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},PREPROCESSOR={className:"meta",begin:/#\s*[a-z]+\b/,end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef elifdef elifndef include"},contains:[{begin:/\\\n/,relevance:0},hljs2.inherit(STRINGS,{className:"string"}),C_LINE_COMMENT_MODE,
1059
- hljs2.C_BLOCK_COMMENT_MODE]},PREPROCESSORS=[PREPROCESSOR_INCLUDE,PREPROCESSOR],TITLE_MODE={className:"title",begin:regex.optional(NAMESPACE_RE)+hljs2.IDENT_RE,relevance:0},FUNCTION_TITLE=regex.optional(NAMESPACE_RE)+hljs2.IDENT_RE+"\\s*\\(",MAX_FUNCTION_TYPE_TOKENS=12,KEYWORDS3={keyword:["asm","auto","break","case","continue","default","do","else","enum","extern","for","fortran","goto","if","inline","register","restrict","return","sizeof","typeof","typeof_unqual","struct","switch","typedef","uni\
1060
- on","volatile","while","_Alignas","_Alignof","_Atomic","_Generic","_Noreturn","_Static_assert","_Thread_local","alignas","alignof","noreturn","static_assert","thread_local","_Pragma"],type:["float","double","signed","unsigned","int","short","long","char","void","_Bool","_BitInt","_Complex","_Imaginary","_Decimal32","_Decimal64","_Decimal96","_Decimal128","_Decimal64x","_Decimal128x","_Float16","_Float32","_Float64","_Float128","_Float32x","_Float64x","_Float128x","const","static","constexpr","co\
1061
- mplex","bool","imaginary"],literal:"true false NULL",built_in:"std string wstring cin cout cerr clog stdin stdout stderr stringstream istringstream ostringstream auto_ptr deque list queue stack vector map set pair bitset multiset multimap unordered_set unordered_map unordered_multiset unordered_multimap priority_queue make_pair array shared_ptr abort terminate abs acos asin atan2 atan calloc ceil cosh cos exit exp fabs floor fmod fprintf fputs free frexp fscanf future isalnum isalpha iscntrl isd\
1062
- igit isgraph islower isprint ispunct isspace isupper isxdigit tolower toupper labs ldexp log10 log malloc realloc memchr memcmp memcpy memset modf pow printf putchar puts scanf sinh sin snprintf sprintf sqrt sscanf strcat strchr strcmp strcpy strcspn strlen strncat strncmp strncpy strpbrk strrchr strspn strstr tanh tan vfprintf vprintf vsprintf endl initializer_list unique_ptr"},EXPRESSION_CONTAINS=[...PREPROCESSORS,TYPES3,C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,NUMBERS,STRINGS],EXPRESSION_CONTEXT={
1063
- variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:KEYWORDS3,contains:EXPRESSION_CONTAINS.concat([{begin:/\(/,end:/\)/,keywords:KEYWORDS3,contains:EXPRESSION_CONTAINS.concat(["self"]),relevance:0}]),relevance:0},FUNCTION_DECLARATION={begin:"("+FUNCTION_TYPE_RE+"[\\*&\\s]+){1,"+MAX_FUNCTION_TYPE_TOKENS+"}"+FUNCTION_TITLE,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:KEYWORDS3,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:DECLTYPE_AUTO_RE,
1064
- keywords:KEYWORDS3,relevance:0},{begin:FUNCTION_TITLE,returnBegin:!0,contains:[hljs2.inherit(TITLE_MODE,{className:"title.function"})],relevance:0},{relevance:0,match:/,/},{className:"params",begin:/\(/,end:/\)/,keywords:KEYWORDS3,relevance:0,contains:[C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,STRINGS,NUMBERS,TYPES3,{begin:/\(/,end:/\)/,keywords:KEYWORDS3,relevance:0,contains:["self",C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,STRINGS,NUMBERS,TYPES3]}]},TYPES3,C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,
1065
- ...PREPROCESSORS]};return{name:"C",aliases:["h"],keywords:KEYWORDS3,disableAutodetect:!0,illegal:"</",contains:[].concat(EXPRESSION_CONTEXT,FUNCTION_DECLARATION,EXPRESSION_CONTAINS,[...PREPROCESSORS,{begin:hljs2.IDENT_RE+"::",keywords:KEYWORDS3},{className:"class",beginKeywords:"enum class struct union",end:/[{;:<>=]/,contains:[{beginKeywords:"final class struct"},hljs2.TITLE_MODE]}]),exports:{preprocessor:PREPROCESSOR,strings:STRINGS,keywords:KEYWORDS3}}}function cpp(hljs2){let regex=hljs2.regex,C_LINE_COMMENT_MODE=hljs2.COMMENT("//","$",{contains:[{begin:/\\\n/}]}),DECLTYPE_AUTO_RE="decltype\\(auto\\)",NAMESPACE_RE="[a-zA-Z_]\\w*::",FUNCTION_TYPE_RE="(?!struct)("+DECLTYPE_AUTO_RE+"|"+regex.optional(NAMESPACE_RE)+"[a-zA-Z_]\\w*"+regex.optional("<[^<>]+>")+")",CPP_PRIMITIVE_TYPES={className:"type",begin:"\\b[a-z\\d_]*_t\\b"},STRINGS={className:"string",variants:[{begin:'(u8?|U|L)?"',end:'"',illegal:"\\n",contains:[hljs2.BACKSLASH_ESCAPE]},{begin:"\
1066
- (u8?|U|L)?'("+"\\\\(x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4,8}|[0-7]{3}|\\S)"+"|.)",end:"'",illegal:"."},hljs2.END_SAME_AS_BEGIN({begin:/(?:u8?|U|L)?R"([^()\\\s"]{0,16})\(/,end:/\)([^()\\\s"]{0,16})"/})]},NUMBERS={className:"number",variants:[{begin:"[+-]?(?:(?:\\b[0-9](?:'?[0-9])*\\.(?:[0-9](?:'?[0-9])*)?|\\.[0-9](?:'?[0-9])*)(?:[Ee][+-]?[0-9](?:'?[0-9])*)?|\\b[0-9](?:'?[0-9])*[Ee][+-]?[0-9](?:'?[0-9])*|\\b0[Xx](?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*(?:\\.(?:[0-9A-Fa-f](?:'?[0-9A-Fa-f])*)?)?|\\.[0-9A-Fa-f](?:'?[0-9A-\
1067
- Fa-f])*)[Pp][+-]?[0-9](?:'?[0-9])*)(?:[Ff](?:16|32|64|128)?|(BF|bf)16|[Ll]|)"},{begin:"[+-]?\\b(?:0[Bb][01](?:'?[01])*|0[Xx][0-9A-Fa-f](?:'?[0-9A-Fa-f])*|0(?:'?[0-7])*|[1-9](?:'?[0-9])*)(?:[Uu](?:LL?|ll?)|[Uu][Zz]?|(?:LL?|ll?)[Uu]?|[Zz][Uu]|)"}],relevance:0},PREPROCESSOR_INCLUDE={scope:"meta",begin:/#\s*include\b/,end:/$/,keywords:{keyword:"include"},contains:[{begin:/\\\n/},STRINGS,{scope:"string",begin:/<.*?>/},C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},PREPROCESSOR={className:"meta",begin:/#\s*[a-z]+\b/,
1068
- end:/$/,keywords:{keyword:"if else elif endif define undef warning error line pragma _Pragma ifdef ifndef include"},contains:[{begin:/\\\n/,relevance:0},hljs2.inherit(STRINGS,{className:"string"}),C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},PREPROCESSORS=[PREPROCESSOR_INCLUDE,PREPROCESSOR],TITLE_MODE={className:"title",begin:regex.optional(NAMESPACE_RE)+hljs2.IDENT_RE,relevance:0},FUNCTION_TITLE=regex.optional(NAMESPACE_RE)+hljs2.IDENT_RE+"\\s*\\(",MAX_FUNCTION_TYPE_TOKENS=12,RESERVED_KEYWORDS=[
1069
- "alignas","alignof","and","and_eq","asm","atomic_cancel","atomic_commit","atomic_noexcept","auto","bitand","bitor","break","case","catch","class","co_await","co_return","co_yield","compl","concept","const_cast|10","consteval","constexpr","constinit","continue","decltype","default","delete","do","dynamic_cast|10","else","enum","explicit","export","extern","false","final","for","friend","goto","if","import","inline","module","mutable","namespace","new","noexcept","not","not_eq","nullptr","operator",
1070
- "or","or_eq","override","private","protected","public","reflexpr","register","reinterpret_cast|10","requires","return","sizeof","static_assert","static_cast|10","struct","switch","synchronized","template","this","thread_local","throw","transaction_safe","transaction_safe_dynamic","true","try","typedef","typeid","typename","union","using","virtual","volatile","while","xor","xor_eq"],RESERVED_TYPES=["bool","char","char16_t","char32_t","char8_t","double","float","int","long","short","void","wchar_t",
1071
- "unsigned","signed","const","static"],TYPE_HINTS=["any","auto_ptr","barrier","binary_semaphore","bitset","complex","condition_variable","condition_variable_any","counting_semaphore","deque","false_type","flat_map","flat_set","future","imaginary","initializer_list","istringstream","jthread","latch","lock_guard","multimap","multiset","mutex","optional","ostringstream","packaged_task","pair","promise","priority_queue","queue","recursive_mutex","recursive_timed_mutex","scoped_lock","set","shared_fut\
1072
- ure","shared_lock","shared_mutex","shared_timed_mutex","shared_ptr","stack","string_view","stringstream","timed_mutex","thread","true_type","tuple","unique_lock","unique_ptr","unordered_map","unordered_multimap","unordered_multiset","unordered_set","variant","vector","weak_ptr","wstring","wstring_view"],FUNCTION_HINTS=["abort","abs","acos","apply","as_const","asin","atan","atan2","calloc","ceil","cerr","cin","clog","cos","cosh","cout","declval","endl","exchange","exit","exp","fabs","floor","fmod",
1073
- "forward","fprintf","fputs","free","frexp","fscanf","future","invoke","isalnum","isalpha","iscntrl","isdigit","isgraph","islower","isprint","ispunct","isspace","isupper","isxdigit","labs","launder","ldexp","log","log10","make_pair","make_shared","make_shared_for_overwrite","make_tuple","make_unique","malloc","memchr","memcmp","memcpy","memset","modf","move","pow","printf","putchar","puts","realloc","scanf","sin","sinh","snprintf","sprintf","sqrt","sscanf","std","stderr","stdin","stdout","strcat",
1074
- "strchr","strcmp","strcpy","strcspn","strlen","strncat","strncmp","strncpy","strpbrk","strrchr","strspn","strstr","swap","tan","tanh","terminate","to_underlying","tolower","toupper","vfprintf","visit","vprintf","vsprintf"],CPP_KEYWORDS={type:RESERVED_TYPES,keyword:RESERVED_KEYWORDS,literal:["NULL","false","nullopt","nullptr","true"],built_in:["_Pragma"],_type_hints:TYPE_HINTS},FUNCTION_DISPATCH={className:"function.dispatch",relevance:0,keywords:{_hint:FUNCTION_HINTS},begin:regex.concat(/\b/,`(?\
1075
- !${RESERVED_KEYWORDS.join("|")})`,hljs2.IDENT_RE,regex.lookahead(/(<[^<>]+>|)\s*\(/))},EXPRESSION_CONTAINS=[FUNCTION_DISPATCH,...PREPROCESSORS,CPP_PRIMITIVE_TYPES,C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,NUMBERS,STRINGS],EXPRESSION_CONTEXT={variants:[{begin:/=/,end:/;/},{begin:/\(/,end:/\)/},{beginKeywords:"new throw return else",end:/;/}],keywords:CPP_KEYWORDS,contains:EXPRESSION_CONTAINS.concat([{begin:/\(/,end:/\)/,keywords:CPP_KEYWORDS,contains:EXPRESSION_CONTAINS.concat(["self"]),relevance:0}]),
1076
- relevance:0},FUNCTION_DECLARATION={className:"function",begin:"("+FUNCTION_TYPE_RE+"[\\*&\\s]+){1,"+MAX_FUNCTION_TYPE_TOKENS+"}"+FUNCTION_TITLE,returnBegin:!0,end:/[{;=]/,excludeEnd:!0,keywords:CPP_KEYWORDS,illegal:/[^\w\s\*&:<>.]/,contains:[{begin:DECLTYPE_AUTO_RE,keywords:CPP_KEYWORDS,relevance:0},{begin:FUNCTION_TITLE,returnBegin:!0,contains:[TITLE_MODE],relevance:0},{begin:/::/,relevance:0},{begin:/:/,endsWithParent:!0,contains:[STRINGS,NUMBERS]},{relevance:0,match:/,/},{className:"params",begin:/\(/,
1077
- end:/\)/,keywords:CPP_KEYWORDS,relevance:0,contains:[C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,STRINGS,NUMBERS,CPP_PRIMITIVE_TYPES,{begin:/\(/,end:/\)/,keywords:CPP_KEYWORDS,relevance:0,contains:["self",C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,STRINGS,NUMBERS,CPP_PRIMITIVE_TYPES]}]},CPP_PRIMITIVE_TYPES,C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,...PREPROCESSORS]};return{name:"C++",aliases:["cc","c++","h++","hpp","hh","hxx","cxx"],keywords:CPP_KEYWORDS,illegal:"</",classNameAliases:{
1078
- "function.dispatch":"built_in"},contains:[].concat(EXPRESSION_CONTEXT,FUNCTION_DECLARATION,FUNCTION_DISPATCH,EXPRESSION_CONTAINS,[...PREPROCESSORS,{begin:"\\b(deque|list|queue|priority_queue|pair|stack|vector|map|set|bitset|multiset|multimap|unordered_map|unordered_set|unordered_multiset|unordered_multimap|array|tuple|optional|variant|function|flat_map|flat_set)\\s*<(?!<)",end:">",keywords:CPP_KEYWORDS,contains:["self",CPP_PRIMITIVE_TYPES]},{begin:hljs2.IDENT_RE+"::",keywords:CPP_KEYWORDS},{match:[
1079
- /\b(?:enum(?:\s+(?:class|struct))?|class|struct|union)/,/\s+/,/\w+/],className:{1:"keyword",3:"title.class"}}])}}function csharp(hljs2){let BUILT_IN_KEYWORDS=["bool","byte","char","decimal","delegate","double","dynamic","enum","float","int","long","nint","nuint","object","sbyte","short","string","ulong","uint","ushort"],FUNCTION_MODIFIERS=["public","private","protected","static","internal","protected","abstract","async","extern","override","unsafe","virtual","new","sealed","partial"],LITERAL_KEYWORDS=["default","false","null","true"],NORMAL_KEYWORDS=["abstract","as","base","break","case","catch","class","c\
1080
- onst","continue","do","else","event","explicit","extern","finally","fixed","for","foreach","goto","if","implicit","in","interface","internal","is","lock","namespace","new","operator","out","override","params","private","protected","public","readonly","record","ref","return","scoped","sealed","sizeof","stackalloc","static","struct","switch","this","throw","try","typeof","unchecked","unsafe","using","virtual","void","volatile","while"],CONTEXTUAL_KEYWORDS=["add","alias","and","ascending","args","a\
1081
- sync","await","by","descending","dynamic","equals","file","from","get","global","group","init","into","join","let","nameof","not","notnull","on","or","orderby","partial","record","remove","required","scoped","select","set","unmanaged","value|0","var","when","where","with","yield"],KEYWORDS3={keyword:NORMAL_KEYWORDS.concat(CONTEXTUAL_KEYWORDS),built_in:BUILT_IN_KEYWORDS,literal:LITERAL_KEYWORDS},TITLE_MODE=hljs2.inherit(hljs2.TITLE_MODE,{begin:"[a-zA-Z](\\.?\\w)*"}),DIGITS="\\d(_*\\d)*",INTEGER_SUFFIX="\
1082
- ([uU][lL]?|[lL][uU]?)?",NUMBERS={className:"number",variants:[{begin:"\\b0[bB]_*[01](_*[01])*"+INTEGER_SUFFIX},{begin:"(-?)\\b0[xX]_*[a-fA-F0-9](_*[a-fA-F0-9])*"+INTEGER_SUFFIX},{begin:"(-?)(\\b"+DIGITS+"(\\.("+DIGITS+")?)?|\\."+DIGITS+")([eE][-+]?"+DIGITS+")?"+"([fFdDmM]|[uU][lL]?|[lL][uU]?)?"}],relevance:0},RAW_STRING={className:"string",begin:/"""("*)(?!")(.|\n)*?"""\1/,relevance:1},VERBATIM_STRING={className:"string",begin:'@"',end:'"',contains:[{begin:'""'}]},VERBATIM_STRING_NO_LF=hljs2.inherit(
1083
- VERBATIM_STRING,{illegal:/\n/}),SUBST={className:"subst",begin:/\{/,end:/\}/,keywords:KEYWORDS3},SUBST_NO_LF=hljs2.inherit(SUBST,{illegal:/\n/}),INTERPOLATED_STRING={className:"string",begin:/\$"/,end:'"',illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},hljs2.BACKSLASH_ESCAPE,SUBST_NO_LF]},INTERPOLATED_VERBATIM_STRING={className:"string",begin:/\$@"/,end:'"',contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},SUBST]},INTERPOLATED_VERBATIM_STRING_NO_LF=hljs2.inherit(INTERPOLATED_VERBATIM_STRING,
1084
- {illegal:/\n/,contains:[{begin:/\{\{/},{begin:/\}\}/},{begin:'""'},SUBST_NO_LF]});SUBST.contains=[INTERPOLATED_VERBATIM_STRING,INTERPOLATED_STRING,VERBATIM_STRING,hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE,NUMBERS,hljs2.C_BLOCK_COMMENT_MODE],SUBST_NO_LF.contains=[INTERPOLATED_VERBATIM_STRING_NO_LF,INTERPOLATED_STRING,VERBATIM_STRING_NO_LF,hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE,NUMBERS,hljs2.inherit(hljs2.C_BLOCK_COMMENT_MODE,{illegal:/\n/})];let STRING={variants:[RAW_STRING,INTERPOLATED_VERBATIM_STRING,
1085
- INTERPOLATED_STRING,VERBATIM_STRING,hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE]},GENERIC_MODIFIER={begin:"<",end:">",contains:[{beginKeywords:"in out"},TITLE_MODE]},TYPE_IDENT_RE=hljs2.IDENT_RE+"(<"+hljs2.IDENT_RE+"(\\s*,\\s*"+hljs2.IDENT_RE+")*>)?(\\[\\])?",AT_IDENTIFIER={begin:"@"+hljs2.IDENT_RE,relevance:0};return{name:"C#",aliases:["cs","c#"],keywords:KEYWORDS3,illegal:/::/,contains:[hljs2.COMMENT("///","$",{returnBegin:!0,contains:[{className:"doctag",variants:[{begin:"///",relevance:0},
1086
- {begin:"<!--|-->"},{begin:"</?",end:">"}]}]}),hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,{className:"meta",begin:"#",end:"$",keywords:{keyword:"if else elif endif define undef warning error line region endregion pragma checksum"}},STRING,NUMBERS,{beginKeywords:"class interface",relevance:0,end:/[{;=]/,illegal:/[^\s:,]/,contains:[{beginKeywords:"where class"},TITLE_MODE,GENERIC_MODIFIER,hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},{beginKeywords:"namespace",relevance:0,end:/[{;=]/,
1087
- illegal:/[^\s:]/,contains:[TITLE_MODE,hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},{beginKeywords:"record",relevance:0,end:/[{;=]/,illegal:/[^\s:]/,contains:[TITLE_MODE,GENERIC_MODIFIER,hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},{className:"meta",begin:"^\\s*\\[(?=[\\w])",excludeBegin:!0,end:"\\]",excludeEnd:!0,contains:[{className:"string",begin:/"/,end:/"/}]},{beginKeywords:"new return throw await else",relevance:0},{className:"function",begin:"("+TYPE_IDENT_RE+"\\s+)+"+hljs2.
1088
- IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,end:/\s*[{;=]/,excludeEnd:!0,keywords:KEYWORDS3,contains:[{beginKeywords:FUNCTION_MODIFIERS.join(" "),relevance:0},{begin:hljs2.IDENT_RE+"\\s*(<[^=]+>\\s*)?\\(",returnBegin:!0,contains:[hljs2.TITLE_MODE,GENERIC_MODIFIER],relevance:0},{match:/\(\)/},{className:"params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS3,relevance:0,contains:[STRING,NUMBERS,hljs2.C_BLOCK_COMMENT_MODE]},hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},
1089
- AT_IDENTIFIER]}}function dart(hljs2){let regex=hljs2.regex,SUBST={className:"subst",variants:[{begin:"\\$[A-Za-z0-9_]+"}]},BRACED_SUBST={className:"subst",variants:[{begin:/\$\{/,end:/\}/}],keywords:"true false null this is new super"},NUMBER={className:"number",relevance:0,variants:[{match:/\b[0-9][0-9_]*(\.[0-9][0-9_]*)?([eE][+-]?[0-9][0-9_]*)?\b/},{match:/\b0[xX][0-9A-Fa-f][0-9A-Fa-f_]*\b/}]},STRING={className:"string",variants:[{begin:"r'''",end:"'''"},{begin:'r"""',end:'"""'},{begin:"r'",end:"'",illegal:"\\\
1090
- n"},{begin:'r"',end:'"',illegal:"\\n"},{begin:"'''",end:"'''",contains:[hljs2.BACKSLASH_ESCAPE,SUBST,BRACED_SUBST]},{begin:'"""',end:'"""',contains:[hljs2.BACKSLASH_ESCAPE,SUBST,BRACED_SUBST]},{begin:"'",end:"'",illegal:"\\n",contains:[hljs2.BACKSLASH_ESCAPE,SUBST,BRACED_SUBST]},{begin:'"',end:'"',illegal:"\\n",contains:[hljs2.BACKSLASH_ESCAPE,SUBST,BRACED_SUBST]}]};BRACED_SUBST.contains=[NUMBER,STRING];let BUILT_IN_TYPES=["Comparable","DateTime","Duration","Function","Iterable","Iterator","List",
1091
- "Map","Match","Object","Pattern","RegExp","Set","Stopwatch","String","StringBuffer","StringSink","Symbol","Type","Uri","bool","double","int","num","Element","ElementList"],NULLABLE_BUILT_IN_TYPES=BUILT_IN_TYPES.map(e=>`${e}?`),KEYWORDS3={keyword:["abstract","as","assert","async","await","base","break","case","catch","class","const","continue","covariant","default","deferred","do","dynamic","else","enum","export","extends","extension","external","factory","false","final","finally","for","Function",
1092
- "get","hide","if","implements","import","in","interface","is","late","library","mixin","new","null","on","operator","part","required","rethrow","return","sealed","set","show","static","super","switch","sync","this","throw","true","try","typedef","var","void","when","while","with","yield"],built_in:BUILT_IN_TYPES.concat(NULLABLE_BUILT_IN_TYPES).concat(["Never","Null","dynamic","print","document","querySelector","querySelectorAll","window"]),$pattern:/[A-Za-z][A-Za-z0-9_]*\??/},CLASS_REFERENCE={match:regex.
1093
- concat(/\b_?/,regex.either(/(?:[A-Z]+[a-z0-9]+)+/,/(?:[A-Z]+[a-z0-9]+)+[A-Z]+/),/(?![A-Za-z0-9_])/),scope:"title.class"},FUNCTION_REFERENCE={match:/\b(?!(?:assert|catch|for|if|switch|while)\b)[a-z_][A-Za-z0-9_]*(?=\()/,scope:"title.function"};return{name:"Dart",keywords:KEYWORDS3,contains:[STRING,hljs2.COMMENT(/\/\*\*(?!\/)/,/\*\//,{subLanguage:"markdown",relevance:0}),hljs2.COMMENT(/\/{3,} ?/,/$/,{contains:[{subLanguage:"markdown",begin:".",end:"$",relevance:0}]}),hljs2.C_LINE_COMMENT_MODE,hljs2.
1094
- C_BLOCK_COMMENT_MODE,{className:"class",beginKeywords:"class interface",end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},hljs2.UNDERSCORE_TITLE_MODE]},CLASS_REFERENCE,FUNCTION_REFERENCE,NUMBER,{className:"meta",begin:"@[A-Za-z]+"}]}}function go(hljs2){let KEYWORDS3={keyword:["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"],type:["bool","byte","complex64","complex128","error","float32","float64","int8","int16","int32","int64","string","uint8","uint16","uint32","uint64","int","uint","uintptr","rune"],literal:["true","false","iota","nil"],built_in:["append","cap","close","c\
1095
- omplex","copy","imag","len","make","new","panic","print","println","real","recover","delete"]};return{name:"Go",aliases:["golang"],keywords:KEYWORDS3,illegal:"</",contains:[hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,{className:"string",variants:[hljs2.QUOTE_STRING_MODE,hljs2.APOS_STRING_MODE,{begin:"`",end:"`"}]},{className:"number",variants:[{match:/-?\b0[xX]\.[a-fA-F0-9](_?[a-fA-F0-9])*[pP][+-]?\d(_?\d)*i?/,relevance:0},{match:/-?\b0[xX](_?[a-fA-F0-9])+((\.([a-fA-F0-9](_?[a-fA-F0-9])*)?)?[pP][+-]?\d(_?\d)*)?i?/,
1096
- relevance:0},{match:/-?\b0[oO](_?[0-7])*i?/,relevance:0},{match:/-?\b0[bB](_?[01])*i?/,relevance:0},{match:/-?\.\d(_?\d)*([eE][+-]?\d(_?\d)*)?i?/,relevance:0},{match:/-?\b\d(_?\d)*(\.(\d(_?\d)*)?)?([eE][+-]?\d(_?\d)*)?i?/,relevance:0}]},{begin:/:=/},{className:"function",beginKeywords:"func",end:"\\s*(\\{|$)",excludeEnd:!0,contains:[hljs2.TITLE_MODE,{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:KEYWORDS3,illegal:/["']/}]}]}}var decimalDigits="[0-9](_*[0-9])*",frac=`\\.(${decimalDigits})`,hexDigits="[0-9a-fA-F](_*[0-9a-fA-F])*",NUMERIC={className:"number",variants:[{begin:`(\\b(${decimalDigits})((${frac})|\\.)?|(${frac}))[eE][+-]?(${decimalDigits})[fFdD]?\\b`},{begin:`\\b(${decimalDigits})((${frac})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${frac})[fFdD]?\\b`},{begin:`\\b(${decimalDigits})[fFdD]\\b`},{begin:`\\b0[xX]((${hexDigits})\\.?|(${hexDigits})?\\.(${hexDigits}))[pP][+-]?(${decimalDigits})[fFdD]?\\b`},{begin:"\\b(\
1097
- 0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${hexDigits})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function variants(variants2,obj={}){return obj.variants=variants2,obj}function groovy(hljs2){let regex=hljs2.regex,IDENT_RE3="[A-Za-z0-9_$]+",COMMENT=variants([hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,hljs2.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]})]),REGEXP={
1098
- className:"regexp",begin:/~?\/[^\/\n]+\//,contains:[hljs2.BACKSLASH_ESCAPE]},NUMBER=NUMERIC,STRING=variants([{begin:/"""/,end:/"""/},{begin:/'''/,end:/'''/},{begin:"\\$/",end:"/\\$",relevance:10},hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE],{className:"string"}),CLASS_DEFINITION={match:[/(class|interface|trait|enum|record|extends|implements)/,/\s+/,hljs2.UNDERSCORE_IDENT_RE],scope:{1:"keyword",3:"title.class"}};return{name:"Groovy",keywords:{"variable.language":"this super",literal:"true fals\
1099
- e null",type:["byte","short","char","int","long","boolean","float","double","void"],keyword:["def","as","in","assert","trait","abstract","static","volatile","transient","public","private","protected","synchronized","final","class","interface","enum","if","else","for","while","switch","case","break","default","continue","throw","throws","try","catch","finally","implements","extends","new","import","package","return","instanceof","var"]},contains:[hljs2.SHEBANG({binary:"groovy",relevance:10}),COMMENT,
1100
- STRING,REGEXP,NUMBER,CLASS_DEFINITION,{className:"meta",begin:"@[A-Za-z]+",relevance:0},{className:"attr",begin:IDENT_RE3+"[ ]*:",relevance:0},{begin:/\?/,end:/:/,relevance:0,contains:[COMMENT,STRING,REGEXP,NUMBER,"self"]},{className:"symbol",begin:"^[ ]*"+regex.lookahead(IDENT_RE3+":"),excludeBegin:!0,end:IDENT_RE3+":",relevance:0}],illegal:/#|<\//}}var decimalDigits2="[0-9](_*[0-9])*",frac2=`\\.(${decimalDigits2})`,hexDigits2="[0-9a-fA-F](_*[0-9a-fA-F])*",NUMERIC2={className:"number",variants:[{begin:`(\\b(${decimalDigits2})((${frac2})|\\.)?|(${frac2}))[eE][+-]?(${decimalDigits2})[fFdD]?\\b`},{begin:`\\b(${decimalDigits2})((${frac2})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${frac2})[fFdD]?\\b`},{begin:`\\b(${decimalDigits2})[fFdD]\\b`},{begin:`\\b0[xX]((${hexDigits2})\\.?|(${hexDigits2})?\\.(${hexDigits2}))[pP][+-]?(${decimalDigits2})[fFdD]?\
1101
- \\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${hexDigits2})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function recurRegex(re2,substitution,depth){return depth===-1?"":re2.replace(substitution,_2=>recurRegex(re2,substitution,depth-1))}function java(hljs2){let regex=hljs2.regex,JAVA_IDENT_RE="[\xC0-\u02B8a-zA-Z_$][\xC0-\u02B8a-zA-Z_$0-9]*",ARRAY_BRACKETS_OPTIONAL_RE="(?:(?:\\s*\\[\\s*])+)?",SIMPLE_TYPE_RE=JAVA_IDENT_RE+"<@@@\
1102
- >"+ARRAY_BRACKETS_OPTIONAL_RE,TYPE_ARG_RE="(?:"+("\\?(?:\\s+(?:extends|super)\\s+"+SIMPLE_TYPE_RE+")?")+"|"+SIMPLE_TYPE_RE+")",TYPE_ARGS_OPTIONAL_RE=recurRegex("(?:\\s*<\\s*"+TYPE_ARG_RE+"(?:\\s*,\\s*"+TYPE_ARG_RE+")*\\s*>)?",/<@@@>/g,2),KEYWORDS3={keyword:["synchronized","abstract","private","var","static","if","const ","for","while","strictfp","finally","protected","import","native","final","void","enum","else","break","transient","catch","instanceof","volatile","case","assert","package","defa\
1103
- ult","public","try","switch","continue","throws","protected","public","private","module","requires","exports","do","sealed","yield","permits","goto","when"],literal:["false","true","null"],type:["char","boolean","long","float","int","byte","short","double"],built_in:["super","this"]},ANNOTATION={className:"meta",begin:"@"+JAVA_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:["self"]}]},PARAMS={className:"params",begin:/\(/,end:/\)/,keywords:KEYWORDS3,relevance:0,contains:[hljs2.C_BLOCK_COMMENT_MODE],
1104
- endsParent:!0};return{name:"Java",aliases:["jsp"],keywords:KEYWORDS3,illegal:/<\/|#/,contains:[hljs2.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{begin:/\w+@/,relevance:0},{className:"doctag",begin:"@[A-Za-z]+"}]}),{begin:/import java\.[a-z]+\./,keywords:"import",relevance:2},hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,{begin:/"""/,end:/"""/,className:"string",contains:[hljs2.BACKSLASH_ESCAPE]},hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE,{match:[/\b(?:class|interface|enum|extends|implements|new)/,
1105
- /\s+/,JAVA_IDENT_RE],className:{1:"keyword",3:"title.class"}},{match:/non-sealed/,scope:"keyword"},{beginKeywords:"new throw return else yield assert",relevance:0},{begin:[JAVA_IDENT_RE,regex.concat(TYPE_ARGS_OPTIONAL_RE,ARRAY_BRACKETS_OPTIONAL_RE,/\s+/),JAVA_IDENT_RE,ARRAY_BRACKETS_OPTIONAL_RE,/\s*/,/=(?!=)/],className:{1:"type",3:"variable",6:"operator"}},{begin:[/record/,/\s+/,JAVA_IDENT_RE],className:{1:"keyword",3:"title.class"},contains:[PARAMS,hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},
1106
- {begin:[JAVA_IDENT_RE,regex.concat(TYPE_ARGS_OPTIONAL_RE,ARRAY_BRACKETS_OPTIONAL_RE,/\s+/),JAVA_IDENT_RE,/\s*(?=\()/],className:{1:"type",3:"title.function"},keywords:KEYWORDS3,contains:[{className:"params",begin:/\(/,end:/\)/,keywords:KEYWORDS3,relevance:0,contains:[ANNOTATION,hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE,NUMERIC2,hljs2.C_BLOCK_COMMENT_MODE]},hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},NUMERIC2,ANNOTATION]}}var IDENT_RE="[A-Za-z$_][0-9A-Za-z$_]*",KEYWORDS=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],LITERALS=["true","false","null","undefined","NaN","Infinity"],TYPES=["Object","Function","Boolean","Symbol","Math","Date","Number","BigInt",
1107
- "String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],ERROR_TYPES=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],BUILT_IN_GLOBALS=[
1108
- "setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],BUILT_IN_VARIABLES=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],BUILT_INS=[].concat(BUILT_IN_GLOBALS,TYPES,ERROR_TYPES);function javascript(hljs2){let regex=hljs2.regex,hasClosingTag=(match,{after})=>{let tag="</"+
1109
- match[0].slice(1);return match.input.indexOf(tag,after)!==-1},IDENT_RE$1=IDENT_RE,FRAGMENT={begin:"<>",end:"</>"},XML_SELF_CLOSING=/<[A-Za-z0-9\\._:-]+\s*\/>/,XML_TAG={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(match,response)=>{let afterMatchIndex=match[0].length+match.index,nextChar=match.input[afterMatchIndex];if(nextChar==="<"||nextChar===","){response.ignoreMatch();return}nextChar===">"&&(hasClosingTag(match,{after:afterMatchIndex})||response.ignoreMatch());
1110
- let m,afterMatch=match.input.substring(afterMatchIndex);if(m=afterMatch.match(/^\s*=/)){response.ignoreMatch();return}if((m=afterMatch.match(/^\s+extends\s+/))&&m.index===0){response.ignoreMatch();return}}},KEYWORDS$1={$pattern:IDENT_RE,keyword:KEYWORDS,literal:LITERALS,built_in:BUILT_INS,"variable.language":BUILT_IN_VARIABLES},decimalDigits4="[0-9](_?[0-9])*",frac4=`\\.(${decimalDigits4})`,decimalInteger="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",NUMBER={className:"number",variants:[{begin:`(\\b(${decimalInteger}\
1111
- )((${frac4})|\\.)?|(${frac4}))[eE][+-]?(${decimalDigits4})\\b`},{begin:`\\b(${decimalInteger})\\b((${frac4})\\b|\\.)?|(${frac4})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},SUBST={className:"subst",begin:"\\$\\{",end:"\\}",keywords:KEYWORDS$1,contains:[]},HTML_TEMPLATE={begin:".?html`",end:"",starts:{end:"`",returnEnd:!1,contains:[
1112
- hljs2.BACKSLASH_ESCAPE,SUBST],subLanguage:"xml"}},CSS_TEMPLATE={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[hljs2.BACKSLASH_ESCAPE,SUBST],subLanguage:"css"}},GRAPHQL_TEMPLATE={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[hljs2.BACKSLASH_ESCAPE,SUBST],subLanguage:"graphql"}},TEMPLATE_STRING={className:"string",begin:"`",end:"`",contains:[hljs2.BACKSLASH_ESCAPE,SUBST]},COMMENT={className:"comment",variants:[hljs2.COMMENT(/\/\*\*(?!\/)/,"\\*/",{relevance:0,contains:[
1113
- {begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:IDENT_RE$1+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),hljs2.C_BLOCK_COMMENT_MODE,hljs2.C_LINE_COMMENT_MODE]},SUBST_INTERNALS=[hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE,HTML_TEMPLATE,CSS_TEMPLATE,GRAPHQL_TEMPLATE,TEMPLATE_STRING,{match:/\$\d+/},NUMBER];SUBST.contains=
1114
- SUBST_INTERNALS.concat({begin:/\{/,end:/\}/,keywords:KEYWORDS$1,contains:["self"].concat(SUBST_INTERNALS)});let SUBST_AND_COMMENTS=[].concat(COMMENT,SUBST.contains),PARAMS_CONTAINS=SUBST_AND_COMMENTS.concat([{begin:/(\s*)\(/,end:/\)/,keywords:KEYWORDS$1,contains:["self"].concat(SUBST_AND_COMMENTS)}]),PARAMS={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS$1,contains:PARAMS_CONTAINS},CLASS_OR_EXTENDS={variants:[{match:[/class/,/\s+/,IDENT_RE$1,/\s+/,/extends/,
1115
- /\s+/,regex.concat(IDENT_RE$1,"(",regex.concat(/\./,IDENT_RE$1),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,IDENT_RE$1],scope:{1:"keyword",3:"title.class"}}]},CLASS_REFERENCE={relevance:0,match:regex.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...TYPES,...ERROR_TYPES]}},USE_STRICT={label:"use_strict",
1116
- className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},FUNCTION_DEFINITION={variants:[{match:[/function/,/\s+/,IDENT_RE$1,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[PARAMS],illegal:/%/},UPPER_CASE_CONSTANT={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function noneOf(list){return regex.concat("(?!",list.join("|"),")")}let FUNCTION_CALL={match:regex.concat(/\b/,noneOf([...BUILT_IN_GLOBALS,
1117
- "super","import","await"].map(x2=>`${x2}\\s*\\(`)),IDENT_RE$1,regex.lookahead(/\s*\(/)),className:"title.function",relevance:0},PROPERTY_ACCESS={begin:regex.concat(/\./,regex.lookahead(regex.concat(IDENT_RE$1,/(?![0-9A-Za-z$_(])/))),end:IDENT_RE$1,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},GETTER_OR_SETTER={match:[/get|set/,/\s+/,IDENT_RE$1,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},PARAMS]},FUNC_LEAD_IN_RE="(\\([^()]*(\\([^()]*(\\([^()\
1118
- ]*\\)[^()]*)*\\)[^()]*)*\\)|"+hljs2.UNDERSCORE_IDENT_RE+")\\s*=>",FUNCTION_VARIABLE={match:[/const|var|let/,/\s+/,IDENT_RE$1,/\s*/,/=\s*/,/(async\s*)?/,regex.lookahead(FUNC_LEAD_IN_RE)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[PARAMS]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:KEYWORDS$1,exports:{PARAMS_CONTAINS,CLASS_REFERENCE},illegal:/#(?![$_A-Za-z])/,contains:[hljs2.SHEBANG({label:"shebang",binary:"node",relevance:5}),USE_STRICT,hljs2.APOS_STRING_MODE,
1119
- hljs2.QUOTE_STRING_MODE,HTML_TEMPLATE,CSS_TEMPLATE,GRAPHQL_TEMPLATE,TEMPLATE_STRING,COMMENT,{match:/\$\d+/},NUMBER,CLASS_REFERENCE,{scope:"attr",match:IDENT_RE$1+regex.lookahead(":"),relevance:0},FUNCTION_VARIABLE,{begin:"("+hljs2.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[COMMENT,hljs2.REGEXP_MODE,{className:"function",begin:FUNC_LEAD_IN_RE,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[{begin:hljs2.UNDERSCORE_IDENT_RE,
1120
- relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS$1,contains:PARAMS_CONTAINS}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:FRAGMENT.begin,end:FRAGMENT.end},{match:XML_SELF_CLOSING},{begin:XML_TAG.begin,"on:begin":XML_TAG.isTrulyOpeningTag,end:XML_TAG.end}],subLanguage:"xml",contains:[{begin:XML_TAG.begin,end:XML_TAG.end,skip:!0,contains:["self"]}]}]},FUNCTION_DEFINITION,{beginKeywords:"while \
1121
- if switch catch for"},{begin:"\\b(?!function)"+hljs2.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[PARAMS,hljs2.inherit(hljs2.TITLE_MODE,{begin:IDENT_RE$1,className:"title.function"})]},{match:/\.\.\./,relevance:0},PROPERTY_ACCESS,{match:"\\$"+IDENT_RE$1,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[PARAMS]},FUNCTION_CALL,UPPER_CASE_CONSTANT,CLASS_OR_EXTENDS,GETTER_OR_SETTER,
1122
- {match:/\$[(.]/}]}}var EXTENDED_NUMBER_RE="([-+]?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)|NaN|[-+]?Infinity",EXTENDED_NUMBER_MODE={scope:"number",match:EXTENDED_NUMBER_RE,relevance:0};function json(hljs2){let ATTRIBUTE={className:"attr",begin:/(("(\\.|[^\\"\r\n])*")|('(\\.|[^\\'\r\n])*'))(?=\s*:)/,relevance:1.01},PUNCTUATION={match:/[{}[\],:]/,className:"punctuation",relevance:0},LITERALS3=["true","false","null"],LITERALS_MODE={scope:"literal",beginKeywords:LITERALS3.join(" ")};return{name:"\
1123
- JSON",aliases:["jsonc","json5"],keywords:{literal:LITERALS3},contains:[ATTRIBUTE,PUNCTUATION,hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE,LITERALS_MODE,EXTENDED_NUMBER_MODE,hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE],illegal:"\\S"}}var decimalDigits3="[0-9](_*[0-9])*",frac3=`\\.(${decimalDigits3})`,hexDigits3="[0-9a-fA-F](_*[0-9a-fA-F])*",NUMERIC3={className:"number",variants:[{begin:`(\\b(${decimalDigits3})((${frac3})|\\.)?|(${frac3}))[eE][+-]?(${decimalDigits3})[fFdD]?\\b`},{begin:`\\b(${decimalDigits3})((${frac3})[fFdD]?\\b|\\.([fFdD]\\b)?)`},{begin:`(${frac3})[fFdD]?\\b`},{begin:`\\b(${decimalDigits3})[fFdD]\\b`},{begin:`\\b0[xX]((${hexDigits3})\\.?|(${hexDigits3})?\\.(${hexDigits3}))[pP][+-]?(${decimalDigits3})[fFdD]?\
1124
- \\b`},{begin:"\\b(0|[1-9](_*[0-9])*)[lL]?\\b"},{begin:`\\b0[xX](${hexDigits3})[lL]?\\b`},{begin:"\\b0(_*[0-7])*[lL]?\\b"},{begin:"\\b0[bB][01](_*[01])*[lL]?\\b"}],relevance:0};function kotlin(hljs2){let KEYWORDS3={keyword:"abstract as val var vararg get set class object open private protected public noinline crossinline dynamic final enum if else do while for when throw try catch finally import package is in fun override companion reified inline lateinit init interface annotation data sealed int\
1125
- ernal infix operator out by constructor super tailrec where const inner suspend typealias external expect actual",built_in:"Byte Short Char Int Long Boolean Float Double Void Unit Nothing",literal:"true false null"},KEYWORDS_WITH_LABEL={className:"keyword",begin:/\b(break|continue|return|this)\b/,starts:{contains:[{className:"symbol",begin:/@\w+/}]}},LABEL={className:"symbol",begin:hljs2.UNDERSCORE_IDENT_RE+"@"},SUBST={className:"subst",begin:/\$\{/,end:/\}/,contains:[hljs2.C_NUMBER_MODE]},VARIABLE={
1126
- className:"variable",begin:"\\$"+hljs2.UNDERSCORE_IDENT_RE},STRING={className:"string",variants:[{begin:'"""',end:'"""(?=[^"])',contains:[VARIABLE,SUBST]},{begin:"'",end:"'",illegal:/\n/,contains:[hljs2.BACKSLASH_ESCAPE]},{begin:'"',end:'"',illegal:/\n/,contains:[hljs2.BACKSLASH_ESCAPE,VARIABLE,SUBST]}]};SUBST.contains.push(STRING);let ANNOTATION_USE_SITE={className:"meta",begin:"@(?:file|property|field|get|set|receiver|param|setparam|delegate)\\s*:(?:\\s*"+hljs2.UNDERSCORE_IDENT_RE+")?"},ANNOTATION={
1127
- className:"meta",begin:"@"+hljs2.UNDERSCORE_IDENT_RE,contains:[{begin:/\(/,end:/\)/,contains:[hljs2.inherit(STRING,{className:"string"}),"self"]}]},KOTLIN_NUMBER_MODE=NUMERIC3,KOTLIN_NESTED_COMMENT=hljs2.COMMENT("/\\*","\\*/",{contains:[hljs2.C_BLOCK_COMMENT_MODE]}),KOTLIN_PAREN_TYPE={variants:[{className:"type",begin:hljs2.UNDERSCORE_IDENT_RE},{begin:/\(/,end:/\)/,contains:[]}]},KOTLIN_PAREN_TYPE2=KOTLIN_PAREN_TYPE;return KOTLIN_PAREN_TYPE2.variants[1].contains=[KOTLIN_PAREN_TYPE],KOTLIN_PAREN_TYPE.
1128
- variants[1].contains=[KOTLIN_PAREN_TYPE2],{name:"Kotlin",aliases:["kt","kts","ktm","ktx"],keywords:KEYWORDS3,contains:[hljs2.COMMENT("/\\*\\*","\\*/",{relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"}]}),hljs2.C_LINE_COMMENT_MODE,KOTLIN_NESTED_COMMENT,KEYWORDS_WITH_LABEL,LABEL,ANNOTATION_USE_SITE,ANNOTATION,{className:"function",beginKeywords:"fun",end:"[(]|$",returnBegin:!0,excludeEnd:!0,keywords:KEYWORDS3,relevance:5,contains:[{begin:hljs2.UNDERSCORE_IDENT_RE+"\\s*\\(",returnBegin:!0,
1129
- relevance:0,contains:[hljs2.UNDERSCORE_TITLE_MODE]},{className:"type",begin:/</,end:/>/,keywords:"reified",relevance:0},{className:"params",begin:/\(/,end:/\)/,endsParent:!0,keywords:KEYWORDS3,relevance:0,contains:[{begin:/:/,end:/[=,\/]/,endsWithParent:!0,contains:[KOTLIN_PAREN_TYPE,hljs2.C_LINE_COMMENT_MODE,KOTLIN_NESTED_COMMENT],relevance:0},hljs2.C_LINE_COMMENT_MODE,KOTLIN_NESTED_COMMENT,ANNOTATION_USE_SITE,ANNOTATION,STRING,hljs2.C_NUMBER_MODE]},KOTLIN_NESTED_COMMENT]},{begin:[/class|interface|trait/,
1130
- /\s+/,hljs2.UNDERSCORE_IDENT_RE],beginScope:{3:"title.class"},keywords:"class interface trait",end:/[:\{(]|$/,excludeEnd:!0,illegal:"extends implements",contains:[{beginKeywords:"public protected internal private constructor"},hljs2.UNDERSCORE_TITLE_MODE,{className:"type",begin:/</,end:/>/,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:"type",begin:/[,:]\s*/,end:/[<\(,){\s]|$/,excludeBegin:!0,returnEnd:!0},ANNOTATION_USE_SITE,ANNOTATION]},STRING,{className:"meta",begin:"^#!/usr/bin/env",end:"\
1131
- $",illegal:`
1132
- `},KOTLIN_NUMBER_MODE]}}function lua(hljs2){let OPENING_LONG_BRACKET="\\[=*\\[",CLOSING_LONG_BRACKET="\\]=*\\]",LONG_BRACKETS={begin:OPENING_LONG_BRACKET,end:CLOSING_LONG_BRACKET,contains:["self"]},COMMENTS=[hljs2.COMMENT("--(?!"+OPENING_LONG_BRACKET+")","$"),hljs2.COMMENT("--"+OPENING_LONG_BRACKET,CLOSING_LONG_BRACKET,{contains:[LONG_BRACKETS],relevance:10})];return{name:"Lua",aliases:["pluto"],keywords:{$pattern:hljs2.UNDERSCORE_IDENT_RE,literal:"true false nil",keyword:"and break do else elseif end for goto if in lo\
1133
- cal global not or repeat return then until while",built_in:"_G _ENV _VERSION __index __newindex __mode __call __metatable __tostring __len __gc __add __sub __mul __div __mod __pow __concat __unm __eq __lt __le assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawset require select setfenv setmetatable tonumber tostring type unpack xpcall arg self coroutine resume yield status wrap create running debug getupvalue \
1134
- debug sethook getmetatable gethook setmetatable setlocal traceback setfenv getinfo setupvalue getlocal getregistry getfenv io lines write close flush open output type read stderr stdin input stdout popen tmpfile math log max acos huge ldexp pi cos tanh pow deg tan cosh sinh random randomseed frexp ceil floor rad abs sqrt modf asin min mod fmod log10 atan2 exp sin atan os exit setlocale date getenv difftime remove time clock tmpname rename execute package preload loadlib loaded loaders cpath conf\
1135
- ig path seeall string sub upper len gfind rep find match char dump gmatch reverse byte format gsub lower table setn insert getn foreachi maxn foreach concat sort remove"},contains:COMMENTS.concat([{className:"function",beginKeywords:"function",end:"\\)",contains:[hljs2.inherit(hljs2.TITLE_MODE,{begin:"([_a-zA-Z]\\w*\\.)*([_a-zA-Z]\\w*:)?[_a-zA-Z]\\w*"}),{className:"params",begin:"\\(",endsWithParent:!0,contains:COMMENTS}].concat(COMMENTS)},hljs2.C_NUMBER_MODE,hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE,
1136
- {className:"string",begin:OPENING_LONG_BRACKET,end:CLOSING_LONG_BRACKET,contains:[LONG_BRACKETS],relevance:5}])}}function nix(hljs2){let regex=hljs2.regex,KEYWORDS3={keyword:["assert","else","if","in","inherit","let","or","rec","then","with"],literal:["true","false","null"],built_in:["abort","baseNameOf","builtins","derivation","derivationStrict","dirOf","fetchGit","fetchMercurial","fetchTarball","fetchTree","fromTOML","import","isNull","map","placeholder","removeAttrs","scopedImport","throw","toString"]},BUILTINS={scope:"built_in",match:regex.either(...["abort","add","addDrvOutputDependencies","addErrorCo\
1137
- ntext","all","any","appendContext","attrNames","attrValues","baseNameOf","bitAnd","bitOr","bitXor","break","builtins","catAttrs","ceil","compareVersions","concatLists","concatMap","concatStringsSep","convertHash","currentSystem","currentTime","deepSeq","derivation","derivationStrict","dirOf","div","elem","elemAt","false","fetchGit","fetchMercurial","fetchTarball","fetchTree","fetchurl","filter","filterSource","findFile","flakeRefToString","floor","foldl'","fromJSON","fromTOML","functionArgs","ge\
1138
- nList","genericClosure","getAttr","getContext","getEnv","getFlake","groupBy","hasAttr","hasContext","hashFile","hashString","head","import","intersectAttrs","isAttrs","isBool","isFloat","isFunction","isInt","isList","isNull","isPath","isString","langVersion","length","lessThan","listToAttrs","map","mapAttrs","match","mul","nixPath","nixVersion","null","parseDrvName","parseFlakeRef","partition","path","pathExists","placeholder","readDir","readFile","readFileType","removeAttrs","replaceStrings","s\
1139
- copedImport","seq","sort","split","splitVersion","storeDir","storePath","stringLength","sub","substring","tail","throw","toFile","toJSON","toPath","toString","toXML","trace","traceVerbose","true","tryEval","typeOf","unsafeDiscardOutputDependency","unsafeDiscardStringContext","unsafeGetAttrPos","warn","zipAttrsWith"].map(b=>`builtins\\.${b}`)),relevance:10},IDENTIFIER_REGEX="[A-Za-z_][A-Za-z0-9_'-]*",LOOKUP_PATH={scope:"symbol",match:new RegExp(`<${IDENTIFIER_REGEX}(/${IDENTIFIER_REGEX})*>`)},PATH_PIECE="\
1140
- [A-Za-z0-9_\\+\\.-]+",PATH={scope:"symbol",match:new RegExp(`(\\.\\.|\\.|~)?/(${PATH_PIECE})?(/${PATH_PIECE})*(?=[\\s;])`)},OPERATOR_WITHOUT_MINUS_REGEX=regex.either("==","=","\\+\\+","\\+","<=","<\\|","<",">=",">","->","//","/","!=","!","\\|\\|","\\|>","\\?","\\*","&&"),OPERATOR={scope:"operator",match:regex.concat(OPERATOR_WITHOUT_MINUS_REGEX,/(?!-)/),relevance:0},NUMBER={scope:"number",match:new RegExp(`${hljs2.NUMBER_RE}(?!-)`),relevance:0},MINUS_OPERATOR={variants:[{scope:"operator",beforeMatch:/\s/,
1141
- begin:/-(?!>)/},{begin:[new RegExp(`${hljs2.NUMBER_RE}`),/-/,/(?!>)/],beginScope:{1:"number",2:"operator"}},{begin:[OPERATOR_WITHOUT_MINUS_REGEX,/-/,/(?!>)/],beginScope:{1:"operator",2:"operator"}}],relevance:0},ATTRS={beforeMatch:/(^|\{|;)\s*/,begin:new RegExp(`${IDENTIFIER_REGEX}(\\.${IDENTIFIER_REGEX})*\\s*=(?!=)`),returnBegin:!0,relevance:0,contains:[{scope:"attr",match:new RegExp(`${IDENTIFIER_REGEX}(\\.${IDENTIFIER_REGEX})*(?=\\s*=)`),relevance:.2}]},NORMAL_ESCAPED_DOLLAR={scope:"char.esca\
1142
- pe",match:/\\\$/},INDENTED_ESCAPED_DOLLAR={scope:"char.escape",match:/''\$/},ANTIQUOTE={scope:"subst",begin:/\$\{/,end:/\}/,keywords:KEYWORDS3},ESCAPED_DOUBLEQUOTE={scope:"char.escape",match:/'''/},ESCAPED_LITERAL={scope:"char.escape",match:/\\(?!\$)./},STRING={scope:"string",variants:[{begin:"''",end:"''",contains:[INDENTED_ESCAPED_DOLLAR,ANTIQUOTE,ESCAPED_DOUBLEQUOTE,ESCAPED_LITERAL]},{begin:'"',end:'"',contains:[NORMAL_ESCAPED_DOLLAR,ANTIQUOTE,ESCAPED_LITERAL]}]},FUNCTION_PARAMS={scope:"param\
1143
- s",match:new RegExp(`${IDENTIFIER_REGEX}\\s*:(?=\\s)`)},EXPRESSIONS=[NUMBER,hljs2.HASH_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,hljs2.COMMENT(/\/\*\*(?!\/)/,/\*\//,{subLanguage:"markdown",relevance:0}),BUILTINS,STRING,LOOKUP_PATH,PATH,FUNCTION_PARAMS,ATTRS,MINUS_OPERATOR,OPERATOR];ANTIQUOTE.contains=EXPRESSIONS;let REPL=[{scope:"meta.prompt",match:/^nix-repl>(?=\s)/,relevance:10},{scope:"meta",beforeMatch:/\s+/,begin:/:([a-z]+|\?)/}];return{name:"Nix",aliases:["nixos"],keywords:KEYWORDS3,contains:EXPRESSIONS.
1144
- concat(REPL)}}function perl(hljs2){let regex=hljs2.regex,KEYWORDS3=["abs","accept","alarm","and","atan2","bind","binmode","bless","break","caller","chdir","chmod","chomp","chop","chown","chr","chroot","class","close","closedir","connect","continue","cos","crypt","dbmclose","dbmopen","defined","delete","die","do","dump","each","else","elsif","endgrent","endhostent","endnetent","endprotoent","endpwent","endservent","eof","eval","exec","exists","exit","exp","fcntl","field","fileno","flock","for","foreach","fork",
1145
- "format","formline","getc","getgrent","getgrgid","getgrnam","gethostbyaddr","gethostbyname","gethostent","getlogin","getnetbyaddr","getnetbyname","getnetent","getpeername","getpgrp","getpriority","getprotobyname","getprotobynumber","getprotoent","getpwent","getpwnam","getpwuid","getservbyname","getservbyport","getservent","getsockname","getsockopt","given","glob","gmtime","goto","grep","gt","hex","if","index","int","ioctl","join","keys","kill","last","lc","lcfirst","length","link","listen","loca\
1146
- l","localtime","log","lstat","lt","ma","map","method","mkdir","msgctl","msgget","msgrcv","msgsnd","my","ne","next","no","not","oct","open","opendir","or","ord","our","pack","package","pipe","pop","pos","print","printf","prototype","push","q|0","qq","quotemeta","qw","qx","rand","read","readdir","readline","readlink","readpipe","recv","redo","ref","rename","require","reset","return","reverse","rewinddir","rindex","rmdir","say","scalar","seek","seekdir","select","semctl","semget","semop","send","se\
1147
- tgrent","sethostent","setnetent","setpgrp","setpriority","setprotoent","setpwent","setservent","setsockopt","shift","shmctl","shmget","shmread","shmwrite","shutdown","sin","sleep","socket","socketpair","sort","splice","split","sprintf","sqrt","srand","stat","state","study","sub","substr","symlink","syscall","sysopen","sysread","sysseek","system","syswrite","tell","telldir","tie","tied","time","times","tr","truncate","uc","ucfirst","umask","undef","unless","unlink","unpack","unshift","untie","unt\
1148
- il","use","utime","values","vec","wait","waitpid","wantarray","warn","when","while","write","x|0","xor","y|0"],REGEX_MODIFIERS=/[dualxmsipngr]{0,12}/,PERL_KEYWORDS={$pattern:/[\w.]+/,keyword:KEYWORDS3.join(" ")},SUBST={className:"subst",begin:"[$@]\\{",end:"\\}",keywords:PERL_KEYWORDS},METHOD={begin:/->\{/,end:/\}/},ATTR={scope:"attr",match:/\s+:\s*\w+(\s*\(.*?\))?/},VAR={scope:"variable",variants:[{begin:/\$\d/},{begin:regex.concat(/[$%@](?!")(\^\w\b|#\w+(::\w+)*|\{\w+\}|\w+(::\w*)*)/,"(?![A-Za\
1149
- -z])(?![@$%])")},{begin:/[$%@](?!")[^\s\w{=]|\$=/,relevance:0}],contains:[ATTR]},NUMBER={className:"number",variants:[{match:/0?\.[0-9][0-9_]+\b/},{match:/\bv?(0|[1-9][0-9_]*(\.[0-9_]+)?|[1-9][0-9_]*)\b/},{match:/\b0[0-7][0-7_]*\b/},{match:/\b0x[0-9a-fA-F][0-9a-fA-F_]*\b/},{match:/\b0b[0-1][0-1_]*\b/}],relevance:0},STRING_CONTAINS=[hljs2.BACKSLASH_ESCAPE,SUBST,VAR],REGEX_DELIMS=[/!/,/\//,/\|/,/\?/,/'/,/"/,/#/],PAIRED_DOUBLE_RE=(prefix,open,close="\\1")=>{let middle=close==="\\1"?close:regex.concat(
1150
- close,open);return regex.concat(regex.concat("(?:",prefix,")"),open,/(?:\\.|[^\\\/])*?/,middle,/(?:\\.|[^\\\/])*?/,close,REGEX_MODIFIERS)},PAIRED_RE=(prefix,open,close)=>regex.concat(regex.concat("(?:",prefix,")"),open,/(?:\\.|[^\\\/])*?/,close,REGEX_MODIFIERS),PERL_DEFAULT_CONTAINS=[VAR,hljs2.HASH_COMMENT_MODE,hljs2.COMMENT(/^=\w/,/=cut/,{endsWithParent:!0}),METHOD,{className:"string",contains:STRING_CONTAINS,variants:[{begin:"q[qwxr]?\\s*\\(",end:"\\)",relevance:5},{begin:"q[qwxr]?\\s*\\[",end:"\
1151
- \\]",relevance:5},{begin:"q[qwxr]?\\s*\\{",end:"\\}",relevance:5},{begin:"q[qwxr]?\\s*\\|",end:"\\|",relevance:5},{begin:"q[qwxr]?\\s*<",end:">",relevance:5},{begin:"qw\\s+q",end:"q",relevance:5},{begin:"'",end:"'",contains:[hljs2.BACKSLASH_ESCAPE]},{begin:'"',end:'"'},{begin:"`",end:"`",contains:[hljs2.BACKSLASH_ESCAPE]},{begin:/\{\w+\}/,relevance:0},{begin:"-?\\w+\\s*=>",relevance:0}]},NUMBER,{begin:"(\\/\\/|"+hljs2.RE_STARTERS_RE+"|\\b(split|return|print|reverse|grep)\\b)\\s*",keywords:"split\
1152
- return print reverse grep",relevance:0,contains:[hljs2.HASH_COMMENT_MODE,{className:"regexp",variants:[{begin:PAIRED_DOUBLE_RE("s|tr|y",regex.either(...REGEX_DELIMS,{capture:!0}))},{begin:PAIRED_DOUBLE_RE("s|tr|y","\\(","\\)")},{begin:PAIRED_DOUBLE_RE("s|tr|y","\\[","\\]")},{begin:PAIRED_DOUBLE_RE("s|tr|y","\\{","\\}")}],relevance:2},{className:"regexp",variants:[{begin:/(m|qr)\/\//,relevance:0},{begin:PAIRED_RE("(?:m|qr)?",/\//,/\//)},{begin:PAIRED_RE("m|qr",regex.either(...REGEX_DELIMS,{capture:!0}),
1153
- /\1/)},{begin:PAIRED_RE("m|qr",/\(/,/\)/)},{begin:PAIRED_RE("m|qr",/\[/,/\]/)},{begin:PAIRED_RE("m|qr",/\{/,/\}/)}]}]},{className:"function",beginKeywords:"sub method",end:"(\\s*\\(.*?\\))?[;{]",excludeEnd:!0,relevance:5,contains:[hljs2.TITLE_MODE,ATTR]},{className:"class",beginKeywords:"class",end:"[;{]",excludeEnd:!0,relevance:5,contains:[hljs2.TITLE_MODE,ATTR,NUMBER]},{begin:"-\\w\\b",relevance:0},{begin:"^__DATA__$",end:"^__END__$",subLanguage:"mojolicious",contains:[{begin:"^@@.*",end:"$",className:"\
1154
- comment"}]}];return SUBST.contains=PERL_DEFAULT_CONTAINS,METHOD.contains=PERL_DEFAULT_CONTAINS,{name:"Perl",aliases:["pl","pm"],keywords:PERL_KEYWORDS,contains:PERL_DEFAULT_CONTAINS}}function php(hljs2){let regex=hljs2.regex,NOT_PERL_ETC=/(?![A-Za-z0-9])(?![$])/,IDENT_RE3=regex.concat(/[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/,NOT_PERL_ETC),PASCAL_CASE_CLASS_NAME_RE=regex.concat(/(\\?[A-Z][a-z0-9_\x7f-\xff]+|\\?[A-Z]+(?=[A-Z][a-z0-9_\x7f-\xff])){1,}/,NOT_PERL_ETC),UPCASE_NAME_RE=regex.concat(/[A-Z]+/,NOT_PERL_ETC),VARIABLE={scope:"variable",match:"\\$+"+IDENT_RE3},PREPROCESSOR={scope:"meta",variants:[{begin:/<\?php/,relevance:10},{begin:/<\?=/},{begin:/<\?/,relevance:.1},{begin:/\?>/}]},
1155
- SUBST={scope:"subst",variants:[{begin:/\$\w+/},{begin:/\{\$/,end:/\}/}]},SINGLE_QUOTED=hljs2.inherit(hljs2.APOS_STRING_MODE,{illegal:null}),DOUBLE_QUOTED=hljs2.inherit(hljs2.QUOTE_STRING_MODE,{illegal:null,contains:hljs2.QUOTE_STRING_MODE.contains.concat(SUBST)}),HEREDOC={begin:/<<<[ \t]*(?:(\w+)|"(\w+)")\n/,end:/[ \t]*(\w+)\b/,contains:hljs2.QUOTE_STRING_MODE.contains.concat(SUBST),"on:begin":(m,resp)=>{resp.data._beginMatch=m[1]||m[2]},"on:end":(m,resp)=>{resp.data._beginMatch!==m[1]&&resp.ignoreMatch()}},
1156
- NOWDOC=hljs2.END_SAME_AS_BEGIN({begin:/<<<[ \t]*'(\w+)'\n/,end:/[ \t]*(\w+)\b/}),WHITESPACE=`[
1157
- ]`,STRING={scope:"string",variants:[DOUBLE_QUOTED,SINGLE_QUOTED,HEREDOC,NOWDOC]},NUMBER={scope:"number",variants:[{begin:"\\b0[bB][01]+(?:_[01]+)*\\b"},{begin:"\\b0[oO][0-7]+(?:_[0-7]+)*\\b"},{begin:"\\b0[xX][\\da-fA-F]+(?:_[\\da-fA-F]+)*\\b"},{begin:"(?:\\b\\d+(?:_\\d+)*(\\.(?:\\d+(?:_\\d+)*))?|\\B\\.\\d+)(?:[eE][+-]?\\d+)?"}],relevance:0},LITERALS3=["false","null","true"],KWS=["__CLASS__","__DIR__","__FILE__","__FUNCTION__","__COMPILER_HALT_OFFSET__","__LINE__","__METHOD__","__NAMESPACE__","__\
1158
- TRAIT__","die","echo","exit","include","include_once","print","require","require_once","array","abstract","and","as","binary","bool","boolean","break","callable","case","catch","class","clone","const","continue","declare","default","do","double","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","extends","final","finally","float","for","foreach","from","global","goto","if","implements","instanceof","insteadof","int","integer","interface","iss\
1159
- et","iterable","list","match|0","mixed","new","never","object","or","private","protected","public","readonly","real","return","string","switch","throw","trait","try","unset","use","var","void","while","xor","yield"],BUILT_INS3=["Error|0","AppendIterator","ArgumentCountError","ArithmeticError","ArrayIterator","ArrayObject","AssertionError","BadFunctionCallException","BadMethodCallException","CachingIterator","CallbackFilterIterator","CompileError","Countable","DirectoryIterator","DivisionByZeroEr\
1160
- ror","DomainException","EmptyIterator","ErrorException","Exception","FilesystemIterator","FilterIterator","GlobIterator","InfiniteIterator","InvalidArgumentException","IteratorIterator","LengthException","LimitIterator","LogicException","MultipleIterator","NoRewindIterator","OutOfBoundsException","OutOfRangeException","OuterIterator","OverflowException","ParentIterator","ParseError","RangeException","RecursiveArrayIterator","RecursiveCachingIterator","RecursiveCallbackFilterIterator","RecursiveD\
1161
- irectoryIterator","RecursiveFilterIterator","RecursiveIterator","RecursiveIteratorIterator","RecursiveRegexIterator","RecursiveTreeIterator","RegexIterator","RuntimeException","SeekableIterator","SplDoublyLinkedList","SplFileInfo","SplFileObject","SplFixedArray","SplHeap","SplMaxHeap","SplMinHeap","SplObjectStorage","SplObserver","SplPriorityQueue","SplQueue","SplStack","SplSubject","SplTempFileObject","TypeError","UnderflowException","UnexpectedValueException","UnhandledMatchError","ArrayAccess",
1162
- "BackedEnum","Closure","Fiber","Generator","Iterator","IteratorAggregate","Serializable","Stringable","Throwable","Traversable","UnitEnum","WeakReference","WeakMap","Directory","__PHP_Incomplete_Class","parent","php_user_filter","self","static","stdClass"],KEYWORDS3={keyword:KWS,literal:(items=>{let result=[];return items.forEach(item=>{result.push(item),item.toLowerCase()===item?result.push(item.toUpperCase()):result.push(item.toLowerCase())}),result})(LITERALS3),built_in:BUILT_INS3},normalizeKeywords=items=>items.
1163
- map(item=>item.replace(/\|\d+$/,"")),CONSTRUCTOR_CALL={variants:[{match:[/new/,regex.concat(WHITESPACE,"+"),regex.concat("(?!",normalizeKeywords(BUILT_INS3).join("\\b|"),"\\b)"),PASCAL_CASE_CLASS_NAME_RE],scope:{1:"keyword",4:"title.class"}}]},CONSTANT_REFERENCE=regex.concat(IDENT_RE3,"\\b(?!\\()"),LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON={variants:[{match:[regex.concat(/::/,regex.lookahead(/(?!class\b)/)),CONSTANT_REFERENCE],scope:{2:"variable.constant"}},{match:[/::/,/class/],scope:{2:"variable.lan\
1164
- guage"}},{match:[PASCAL_CASE_CLASS_NAME_RE,regex.concat(/::/,regex.lookahead(/(?!class\b)/)),CONSTANT_REFERENCE],scope:{1:"title.class",3:"variable.constant"}},{match:[PASCAL_CASE_CLASS_NAME_RE,regex.concat("::",regex.lookahead(/(?!class\b)/))],scope:{1:"title.class"}},{match:[PASCAL_CASE_CLASS_NAME_RE,/::/,/class/],scope:{1:"title.class",3:"variable.language"}}]},NAMED_ARGUMENT={scope:"attr",match:regex.concat(IDENT_RE3,regex.lookahead(":"),regex.lookahead(/(?!::)/))},PARAMS_MODE={relevance:0,begin:/\(/,
1165
- end:/\)/,keywords:KEYWORDS3,contains:[NAMED_ARGUMENT,VARIABLE,LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,hljs2.C_BLOCK_COMMENT_MODE,hljs2.C_LINE_COMMENT_MODE,hljs2.HASH_COMMENT_MODE,STRING,NUMBER,CONSTRUCTOR_CALL]},FUNCTION_INVOKE={relevance:0,match:[/\b/,regex.concat("(?!fn\\b|function\\b|",normalizeKeywords(KWS).join("\\b|"),"|",normalizeKeywords(BUILT_INS3).join("\\b|"),"\\b)"),IDENT_RE3,regex.concat(WHITESPACE,"*"),regex.lookahead(/(?=\()/)],scope:{3:"title.function.invoke"},contains:[PARAMS_MODE]};
1166
- PARAMS_MODE.contains.push(FUNCTION_INVOKE);let ATTRIBUTE_CONTAINS=[NAMED_ARGUMENT,LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,hljs2.C_BLOCK_COMMENT_MODE,hljs2.C_LINE_COMMENT_MODE,hljs2.HASH_COMMENT_MODE,STRING,NUMBER,CONSTRUCTOR_CALL],ATTRIBUTES={begin:regex.concat(/#\[\s*\\?/,regex.either(PASCAL_CASE_CLASS_NAME_RE,UPCASE_NAME_RE)),beginScope:"meta",end:/]/,endScope:"meta",keywords:{literal:LITERALS3,keyword:["new","array"]},contains:[{begin:/\[/,end:/]/,keywords:{literal:LITERALS3,keyword:["new","array"]},
1167
- contains:["self",...ATTRIBUTE_CONTAINS]},...ATTRIBUTE_CONTAINS,{scope:"meta",variants:[{match:PASCAL_CASE_CLASS_NAME_RE},{match:UPCASE_NAME_RE}]}]};return{case_insensitive:!1,keywords:KEYWORDS3,contains:[ATTRIBUTES,hljs2.HASH_COMMENT_MODE,hljs2.COMMENT("//","$"),hljs2.COMMENT("/\\*","\\*/",{contains:[{scope:"doctag",match:"@[A-Za-z]+"}]}),{match:/__halt_compiler\(\);/,keywords:"__halt_compiler",starts:{scope:"comment",end:hljs2.MATCH_NOTHING_RE,contains:[{match:/\?>/,scope:"meta",endsParent:!0}]}},
1168
- PREPROCESSOR,{scope:"variable.language",match:/\$this\b/},VARIABLE,FUNCTION_INVOKE,LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,{match:[/const/,/\s/,IDENT_RE3],scope:{1:"keyword",3:"variable.constant"}},CONSTRUCTOR_CALL,{scope:"function",relevance:0,beginKeywords:"fn function",end:/[;{]/,excludeEnd:!0,illegal:"[$%\\[]",contains:[{beginKeywords:"use"},hljs2.UNDERSCORE_TITLE_MODE,{begin:"=>",endsParent:!0},{scope:"params",begin:"\\(",end:"\\)",excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS3,contains:["sel\
1169
- f",ATTRIBUTES,VARIABLE,LEFT_AND_RIGHT_SIDE_OF_DOUBLE_COLON,hljs2.C_BLOCK_COMMENT_MODE,hljs2.C_LINE_COMMENT_MODE,hljs2.HASH_COMMENT_MODE,STRING,NUMBER]}]},{scope:"class",variants:[{beginKeywords:"enum",illegal:/[($"]/},{beginKeywords:"class interface trait",illegal:/[:($"]/}],relevance:0,end:/\{/,excludeEnd:!0,contains:[{beginKeywords:"extends implements"},hljs2.UNDERSCORE_TITLE_MODE]},{beginKeywords:"namespace",relevance:0,end:";",illegal:/[.']/,contains:[hljs2.inherit(hljs2.UNDERSCORE_TITLE_MODE,
1170
- {scope:"title.class"})]},{beginKeywords:"use",relevance:0,end:";",contains:[{match:/\b(as|const|function)\b/,scope:"keyword"},hljs2.UNDERSCORE_TITLE_MODE]},STRING,NUMBER]}}function python(hljs2){let regex=hljs2.regex,IDENT_RE3=new RegExp("[\\p{XID_Start}_]\\p{XID_Continue}*","u"),RESERVED_WORDS=["and","as","assert","async","await","break","case","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","lazy","match","nonlocal|10","not","or","pass","raise","return","try","while","with","yield"],KEYWORDS3={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:RESERVED_WORDS,built_in:["__import__","abs","aiter","all","an\
1171
- ext","any","ascii","bin","bool","breakpoint","bytearray","bytes","callable","chr","classmethod","compile","complex","delattr","dict","dir","divmod","enumerate","eval","exec","filter","float","format","frozendict","frozenset","getattr","globals","hasattr","hash","help","hex","id","input","int","isinstance","issubclass","iter","len","list","locals","map","max","memoryview","min","next","object","oct","open","ord","pow","print","property","range","repr","reversed","round","sentinel","set","setattr",
1172
- "slice","sorted","staticmethod","str","sum","super","tuple","type","vars","zip"],literal:["__debug__","Ellipsis","False","None","NotImplemented","True"],type:["Any","Callable","Coroutine","Dict","List","Literal","Generic","Optional","Sequence","Set","Tuple","Type","Union"]},PROMPT={className:"meta",begin:/^(>>>|\.\.\.) /},SUBST={className:"subst",begin:/\{/,end:/\}/,keywords:KEYWORDS3,illegal:/#/},LITERAL_BRACKET={begin:/\{\{/,relevance:0},STRING={className:"string",contains:[hljs2.BACKSLASH_ESCAPE],
1173
- variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[hljs2.BACKSLASH_ESCAPE,PROMPT],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[hljs2.BACKSLASH_ESCAPE,PROMPT],relevance:10},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'''/,end:/'''/,contains:[hljs2.BACKSLASH_ESCAPE,PROMPT,LITERAL_BRACKET,SUBST]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"""/,end:/"""/,contains:[hljs2.BACKSLASH_ESCAPE,PROMPT,LITERAL_BRACKET,SUBST]},{begin:/([uU]|[rR])'/,end:/'/,
1174
- relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'/,end:/'/,contains:[hljs2.BACKSLASH_ESCAPE,LITERAL_BRACKET,SUBST]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"/,end:/"/,contains:[hljs2.BACKSLASH_ESCAPE,LITERAL_BRACKET,SUBST]},hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE]},digitpart="[0-9](_?[0-9])*",pointfloat=`(\\b(${digitpart}))?\\.(${digitpart})|\\b(${digitpart}\
1175
- )\\.`,lookahead2=`\\b|${RESERVED_WORDS.join("|")}`,NUMBER={className:"number",relevance:0,variants:[{begin:`(\\b(${digitpart})|(${pointfloat}))[eE][+-]?(${digitpart})[jJ]?(?=${lookahead2})`},{begin:`(${pointfloat})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${lookahead2})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${lookahead2})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${lookahead2})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${lookahead2})`},{begin:`\\b(${digitpart})[jJ](?=${lookahead2})`}]},COMMENT_TYPE={
1176
- className:"comment",begin:regex.lookahead(/# type:/),end:/$/,keywords:KEYWORDS3,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},PARAMS={className:"params",variants:[{className:"",begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS3,contains:["self",PROMPT,NUMBER,STRING,hljs2.HASH_COMMENT_MODE]}]};return SUBST.contains=[STRING,NUMBER,PROMPT],{name:"Python",aliases:["py","gyp","ipython"],unicodeRegex:!0,keywords:KEYWORDS3,illegal:/(<\/|\?)|=>/,
1177
- contains:[PROMPT,NUMBER,{scope:"variable.language",match:/\bself\b/},{beginKeywords:"if",relevance:0},{match:/\bor\b/,scope:"keyword"},STRING,COMMENT_TYPE,hljs2.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,IDENT_RE3],scope:{1:"keyword",3:"title.function"},contains:[PARAMS]},{variants:[{match:[/\bclass/,/\s+/,IDENT_RE3,/\s*/,/\(\s*/,IDENT_RE3,/\s*\)/]},{match:[/\bclass/,/\s+/,IDENT_RE3]}],scope:{1:"keyword",3:"title.class",6:"title.class.inherited"}},{className:"meta",begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[
1178
- NUMBER,PARAMS,STRING]}]}}function ruby(hljs2){let regex=hljs2.regex,RUBY_METHOD_RE="([a-zA-Z_]\\w*[!?=]?|[-+~]@|<<|>>|=~|===?|<=>|[<>]=?|\\*\\*|[-/+%^&*~`|]|\\[\\]=?)",CLASS_NAME_RE=regex.either(/\b([A-Z]+[a-z0-9]+)+/,/\b([A-Z]+[a-z0-9]+)+[A-Z]+/),CLASS_NAME_WITH_NAMESPACE_RE=regex.concat(CLASS_NAME_RE,/(::\w+)*/),RUBY_KEYWORDS={"variable.constant":["__FILE__","__LINE__","__ENCODING__"],"variable.language":["self","super"],keyword:["alias","and","begin","BEGIN","break","case","class","defined","do","else","elsif","end",
1179
- "END","ensure","for","if","in","module","next","not","or","redo","require","rescue","retry","return","then","undef","unless","until","when","while","yield",...["include","extend","prepend","public","private","protected","raise","throw"]],built_in:["proc","lambda","attr_accessor","attr_reader","attr_writer","define_method","private_constant","module_function"],literal:["true","false","nil"]},YARDOCTAG={className:"doctag",begin:"@[A-Za-z]+"},IRB_OBJECT={begin:"#<",end:">"},COMMENT_MODES=[hljs2.COMMENT(
1180
- "#","$",{contains:[YARDOCTAG]}),hljs2.COMMENT("^=begin","^=end",{contains:[YARDOCTAG],relevance:10}),hljs2.COMMENT("^__END__",hljs2.MATCH_NOTHING_RE)],SUBST={className:"subst",begin:/#\{/,end:/\}/,keywords:RUBY_KEYWORDS},STRING={className:"string",contains:[hljs2.BACKSLASH_ESCAPE,SUBST],variants:[{begin:/'/,end:/'/},{begin:/"/,end:/"/},{begin:/`/,end:/`/},{begin:/%[qQwWx]?\(/,end:/\)/},{begin:/%[qQwWx]?\[/,end:/\]/},{begin:/%[qQwWx]?\{/,end:/\}/},{begin:/%[qQwWx]?</,end:/>/},{begin:/%[qQwWx]?\//,
1181
- end:/\//},{begin:/%[qQwWx]?%/,end:/%/},{begin:/%[qQwWx]?-/,end:/-/},{begin:/%[qQwWx]?\|/,end:/\|/},{begin:/\B\?(\\\d{1,3})/},{begin:/\B\?(\\x[A-Fa-f0-9]{1,2})/},{begin:/\B\?(\\u\{?[A-Fa-f0-9]{1,6}\}?)/},{begin:/\B\?(\\M-\\C-|\\M-\\c|\\c\\M-|\\M-|\\C-\\M-)[\x20-\x7e]/},{begin:/\B\?\\(c|C-)[\x20-\x7e]/},{begin:/\B\?\\?\S/},{begin:regex.concat(/<<[-~]?'?/,regex.lookahead(/(\w+)(?=\W)[^\n]*\n(?:[^\n]*\n)*?\s*\1\b/)),contains:[hljs2.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,contains:[hljs2.BACKSLASH_ESCAPE,
1182
- SUBST]})]}]},decimal="[1-9](_?[0-9])*|0",digits="[0-9](_?[0-9])*",NUMBER={className:"number",relevance:0,variants:[{begin:`\\b(${decimal})(\\.(${digits}))?([eE][+-]?(${digits})|r)?i?\\b`},{begin:"\\b0[dD][0-9](_?[0-9])*r?i?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*r?i?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*r?i?\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*r?i?\\b"},{begin:"\\b0(_?[0-7])+r?i?\\b"}]},PARAMS={variants:[{match:/\(\)/},{className:"params",begin:/\(/,end:/(?=\))/,excludeBegin:!0,endsParent:!0,
1183
- keywords:RUBY_KEYWORDS}]},RUBY_DEFAULT_CONTAINS=[STRING,{variants:[{match:[/class\s+/,CLASS_NAME_WITH_NAMESPACE_RE,/\s+<\s+/,CLASS_NAME_WITH_NAMESPACE_RE]},{match:[/\b(class|module)\s+/,CLASS_NAME_WITH_NAMESPACE_RE]}],scope:{2:"title.class",4:"title.class.inherited"},keywords:RUBY_KEYWORDS},{match:[/(include|extend)\s+/,CLASS_NAME_WITH_NAMESPACE_RE],scope:{2:"title.class"},keywords:RUBY_KEYWORDS},{relevance:0,match:[CLASS_NAME_WITH_NAMESPACE_RE,/\.new[. (]/],scope:{1:"title.class"}},{relevance:0,
1184
- match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"},{relevance:0,match:CLASS_NAME_RE,scope:"title.class"},{match:[/def/,/\s+/,RUBY_METHOD_RE],scope:{1:"keyword",3:"title.function"},contains:[PARAMS]},{begin:"::"},{className:"symbol",begin:hljs2.UNDERSCORE_IDENT_RE+"(!|\\?)?:",relevance:0},{className:"symbol",begin:":(?!\\s)",contains:[STRING,{begin:RUBY_METHOD_RE}],relevance:0},NUMBER,{className:"variable",begin:"(\\$\\W)|((\\$|@@?)(\\w+))(?=[^@$?])(?![A-Za-z])(?![@$?'])"},{className:"par\
1185
- ams",begin:/\|(?!=)/,end:/\|/,excludeBegin:!0,excludeEnd:!0,relevance:0,keywords:RUBY_KEYWORDS},{begin:"("+hljs2.RE_STARTERS_RE+"|unless)\\s*",keywords:"unless",contains:[{className:"regexp",contains:[hljs2.BACKSLASH_ESCAPE,SUBST],illegal:/\n/,variants:[{begin:"/",end:"/[a-z]*"},{begin:/%r\{/,end:/\}[a-z]*/},{begin:"%r\\(",end:"\\)[a-z]*"},{begin:"%r!",end:"![a-z]*"},{begin:"%r\\[",end:"\\][a-z]*"}]}].concat(IRB_OBJECT,COMMENT_MODES),relevance:0}].concat(IRB_OBJECT,COMMENT_MODES);SUBST.contains=
1186
- RUBY_DEFAULT_CONTAINS,PARAMS.contains=RUBY_DEFAULT_CONTAINS;let IRB_DEFAULT=[{begin:/^\s*=>/,starts:{end:"$",contains:RUBY_DEFAULT_CONTAINS}},{className:"meta.prompt",begin:"^("+"[>?]>"+"|"+"[\\w#]+\\(\\w+\\):\\d+:\\d+[>*]"+"|"+"(\\w+-)?\\d+\\.\\d+\\.\\d+(p\\d+)?[^\\d][^>]+>"+")(?=[ ])",starts:{end:"$",keywords:RUBY_KEYWORDS,contains:RUBY_DEFAULT_CONTAINS}}];return COMMENT_MODES.unshift(IRB_OBJECT),{name:"Ruby",aliases:["rb","gemspec","podspec","thor","irb"],keywords:RUBY_KEYWORDS,illegal:/\/\*/,
1187
- contains:[hljs2.SHEBANG({binary:"ruby"})].concat(IRB_DEFAULT).concat(COMMENT_MODES).concat(RUBY_DEFAULT_CONTAINS)}}function rust(hljs2){let regex=hljs2.regex,RAW_IDENTIFIER=/(r#)?/,UNDERSCORE_IDENT_RE=regex.concat(RAW_IDENTIFIER,hljs2.UNDERSCORE_IDENT_RE),IDENT_RE3=regex.concat(RAW_IDENTIFIER,hljs2.IDENT_RE),FUNCTION_INVOKE={scope:"title.function.invoke",relevance:0,begin:regex.concat(/\b/,/(?!(?:let|for|while|if|else|match)\b)/,IDENT_RE3,regex.lookahead(/\s*\(/))},NUMBER_SUFFIX="([ui](8|16|32|64|128|size)|f(16|32|64|128))?",KEYWORDS3=["abstract","as","async","await","become","box","break","const","continue",
1188
- "crate","do","dyn","else","enum","extern","false","final","fn","for","if","impl","in","let","loop","macro","match","mod","move","mut","override","priv","pub","raw","ref","return","self","Self","static","struct","super","trait","true","try","type","typeof","union","unsafe","unsized","use","virtual","where","while","yield"],LITERALS3=["true","false","Some","None","Ok","Err"],BUILTINS=["drop ","Copy","Send","Sized","Sync","Drop","Fn","FnMut","FnOnce","ToOwned","Clone","Debug","PartialEq","PartialOr\
1189
- d","Eq","Ord","AsRef","AsMut","Into","From","Default","Iterator","Extend","IntoIterator","DoubleEndedIterator","ExactSizeIterator","SliceConcatExt","ToString","assert!","assert_eq!","bitflags!","bytes!","cfg!","col!","concat!","concat_idents!","debug_assert!","debug_assert_eq!","env!","eprintln!","panic!","file!","format!","format_args!","include_bytes!","include_str!","line!","local_data_key!","module_path!","option_env!","print!","println!","select!","stringify!","try!","unimplemented!","unrea\
1190
- chable!","vec!","write!","writeln!","macro_rules!","assert_ne!","debug_assert_ne!"],TYPES3=["i8","i16","i32","i64","i128","isize","u8","u16","u32","u64","u128","usize","f16","f32","f64","f128","str","char","bool","Box","Option","Result","String","Vec"];return{name:"Rust",aliases:["rs"],keywords:{$pattern:hljs2.IDENT_RE+"!?",type:TYPES3,keyword:KEYWORDS3,literal:LITERALS3,built_in:BUILTINS},illegal:"</",contains:[hljs2.C_LINE_COMMENT_MODE,hljs2.COMMENT("/\\*","\\*/",{contains:["self"]}),hljs2.inherit(
1191
- hljs2.QUOTE_STRING_MODE,{begin:/b?"/,illegal:null}),{scope:"symbol",begin:/'[a-zA-Z_][a-zA-Z0-9_]*(?!')/},{scope:"string",variants:[{begin:/b?r(#*)"(.|\n)*?"\1(?!#)/},{begin:/b?'/,end:/'/,contains:[{scope:"char.escape",match:/\\('|"|\\|\w|x\w{2}|u\w{4}|U\w{8})/}]}]},{scope:"number",variants:[{begin:"\\b0b([01_]+)"+NUMBER_SUFFIX},{begin:"\\b0o([0-7_]+)"+NUMBER_SUFFIX},{begin:"\\b0x([A-Fa-f0-9_]+)"+NUMBER_SUFFIX},{begin:"\\b(\\d[\\d_]*(\\.[0-9_]+)?([eE][+-]?[0-9_]+)?)"+NUMBER_SUFFIX}],relevance:0},
1192
- {begin:[/\bsafe/,/\s+/,/extern/],scope:{1:"keyword",3:"keyword"}},{begin:[/fn/,/\s+/,UNDERSCORE_IDENT_RE],scope:{1:"keyword",3:"title.function"}},{scope:"meta",begin:"#!?\\[",end:"\\]",contains:[{scope:"string",begin:/"/,end:/"/,contains:[hljs2.BACKSLASH_ESCAPE]}]},{begin:[/let/,/\s+/,/(?:mut\s+)?/,UNDERSCORE_IDENT_RE],scope:{1:"keyword",3:"keyword",4:"variable"}},{begin:[/for/,/\s+/,UNDERSCORE_IDENT_RE,/\s+/,/in/],scope:{1:"keyword",3:"variable",5:"keyword"}},{begin:[/type/,/\s+/,UNDERSCORE_IDENT_RE],
1193
- scope:{1:"keyword",3:"title.class"}},{begin:[/(?:trait|enum|struct|union|impl|for)/,/\s+/,UNDERSCORE_IDENT_RE],scope:{1:"keyword",3:"title.class"}},{begin:hljs2.IDENT_RE+"::",keywords:{keyword:"Self",built_in:BUILTINS,type:TYPES3}},{scope:"punctuation",begin:"->"},FUNCTION_INVOKE]}}function scala(hljs2){let regex=hljs2.regex,ANNOTATION={className:"meta",begin:"@[A-Za-z]+"},SUBST={className:"subst",variants:[{begin:"\\$[A-Za-z0-9_]+"},{begin:/\$\{/,end:/\}/}]},STRING={className:"string",variants:[{begin:'"""',end:'"""'},{begin:'"',end:'"',illegal:"\\n",contains:[hljs2.BACKSLASH_ESCAPE]},{begin:'[a-z]+"',end:'"',illegal:"\\n",contains:[hljs2.BACKSLASH_ESCAPE,SUBST]},{className:"string",begin:'[a-z]+"""',end:'"""',contains:[SUBST],relevance:10}]},TYPE={className:"type",begin:"\
1194
- \\b[A-Z][A-Za-z0-9_]*",relevance:0},NAME={className:"title",begin:/[^0-9\n\t "'(),.`{}\[\]:;][^\n\t "'(),.`{}\[\]:;]+|[^0-9\n\t "'(),.`{}\[\]:;=]/,relevance:0},CLASS={className:"class",beginKeywords:"class object trait type",end:/[:={\[\n;]/,excludeEnd:!0,contains:[hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,{beginKeywords:"extends with",relevance:10},{begin:/\[/,end:/\]/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[TYPE,hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},{className:"\
1195
- params",begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,relevance:0,contains:[TYPE,hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE]},NAME]},METHOD={className:"function",beginKeywords:"def",end:regex.lookahead(/[:={\[(\n;]/),contains:[NAME]},EXTENSION={begin:[/^\s*/,"extension",/\s+(?=[[(])/],beginScope:{2:"keyword"}},END={begin:[/^\s*/,/end/,/\s+/,/(extension\b)?/],beginScope:{2:"keyword",4:"keyword"}},INLINE_MODES=[{match:/\.inline\b/},{begin:/\binline(?=\s)/,keywords:"inline"}],USING_PARAM_CLAUSE={
1196
- begin:[/\(\s*/,/using/,/\s+(?!\))/],beginScope:{2:"keyword"}};return{name:"Scala",keywords:{literal:"true false null",keyword:"type yield lazy override def with val var sealed abstract private trait object if then forSome for while do throw finally protected extends import final return else break new catch super class case package default try this match continue throws implicit export enum given transparent"},contains:[{begin:["//>",/\s+/,/using/,/\s+/,/\S+/],beginScope:{1:"comment",3:"keyword",
1197
- 5:"type"},end:/$/,contains:[{className:"string",begin:/\S+/}]},hljs2.C_LINE_COMMENT_MODE,hljs2.C_BLOCK_COMMENT_MODE,STRING,TYPE,METHOD,CLASS,hljs2.C_NUMBER_MODE,EXTENSION,END,...INLINE_MODES,USING_PARAM_CLAUSE,ANNOTATION]}}function source(re2){return re2?typeof re2=="string"?re2:re2.source:null}function lookahead(re2){return concat("(?=",re2,")")}function concat(...args){return args.map(x2=>source(x2)).join("")}function stripOptionsFromArgs(args){let opts=args[args.length-1];return typeof opts=="object"&&opts.constructor===Object?(args.splice(args.length-1,1),opts):{}}function either(...args){return"("+(stripOptionsFromArgs(args).capture?"":"?:")+args.map(x2=>source(x2)).join("|")+")"}new RegExp(either(/\[(?:[^\\\]]|\\.)*\]/,
1198
- /\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./));var keywordWrapper=keyword=>concat(/\b/,keyword,/\w$/.test(keyword)?/\b/:/\B/),dotKeywords=["Protocol","Type"].map(keywordWrapper),optionalDotKeywords=["init","self"].map(keywordWrapper),keywordTypes=["Any","Self"],keywords=["actor","any","associatedtype","async","await",/as\?/,/as!/,"as","borrowing","break","case","catch","class","consume","consuming","continue","convenience","copy","default","defer","deinit","didSet","distri\
1199
- buted","do","dynamic","each","else","enum","extension","fallthrough",/fileprivate\(set\)/,"fileprivate","final","for","func","get","guard","if","import","indirect","infix",/init\?/,/init!/,"inout",/internal\(set\)/,"internal","in","is","isolated","nonisolated","lazy","let","macro","mutating","nonmutating",/open\(set\)/,"open","operator","optional","override","package","postfix","precedencegroup","prefix",/private\(set\)/,"private","protocol",/public\(set\)/,"public","repeat","required","rethrows",
1200
- "return","set","some","static","struct","subscript","super","switch","throws","throw",/try\?/,/try!/,"try","typealias",/unowned\(safe\)/,/unowned\(unsafe\)/,"unowned","var","weak","where","while","willSet"],literals=["false","nil","true"],precedencegroupKeywords=["assignment","associativity","higherThan","left","lowerThan","none","right"],numberSignKeywords=["#colorLiteral","#column","#dsohandle","#else","#elseif","#endif","#error","#file","#fileID","#fileLiteral","#filePath","#function","#if","\
1201
- #imageLiteral","#keyPath","#line","#selector","#sourceLocation","#warning"],builtIns=["abs","all","any","assert","assertionFailure","debugPrint","dump","fatalError","getVaList","isKnownUniquelyReferenced","max","min","numericCast","pointwiseMax","pointwiseMin","precondition","preconditionFailure","print","readLine","repeatElement","sequence","stride","swap","swift_unboxFromSwiftValueWithType","transcode","type","unsafeBitCast","unsafeDowncast","withExtendedLifetime","withUnsafeMutablePointer","w\
1202
- ithUnsafePointer","withVaList","withoutActuallyEscaping","zip"],operatorHead=either(/[/=\-+!*%<>&|^~?]/,/[\u00A1-\u00A7]/,/[\u00A9\u00AB]/,/[\u00AC\u00AE]/,/[\u00B0\u00B1]/,/[\u00B6\u00BB\u00BF\u00D7\u00F7]/,/[\u2016-\u2017]/,/[\u2020-\u2027]/,/[\u2030-\u203E]/,/[\u2041-\u2053]/,/[\u2055-\u205E]/,/[\u2190-\u23FF]/,/[\u2500-\u2775]/,/[\u2794-\u2BFF]/,/[\u2E00-\u2E7F]/,/[\u3001-\u3003]/,/[\u3008-\u3020]/,/[\u3030]/),operatorCharacter=either(operatorHead,/[\u0300-\u036F]/,/[\u1DC0-\u1DFF]/,/[\u20D0-\u20FF]/,
1203
- /[\uFE00-\uFE0F]/,/[\uFE20-\uFE2F]/),operator=concat(operatorHead,operatorCharacter,"*"),identifierHead=either(/[a-zA-Z_]/,/[\u00A8\u00AA\u00AD\u00AF\u00B2-\u00B5\u00B7-\u00BA]/,/[\u00BC-\u00BE\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u00FF]/,/[\u0100-\u02FF\u0370-\u167F\u1681-\u180D\u180F-\u1DBF]/,/[\u1E00-\u1FFF]/,/[\u200B-\u200D\u202A-\u202E\u203F-\u2040\u2054\u2060-\u206F]/,/[\u2070-\u20CF\u2100-\u218F\u2460-\u24FF\u2776-\u2793]/,/[\u2C00-\u2DFF\u2E80-\u2FFF]/,/[\u3004-\u3007\u3021-\u302F\u3031-\u303F\u3040-\uD7FF]/,
1204
- /[\uF900-\uFD3D\uFD40-\uFDCF\uFDF0-\uFE1F\uFE30-\uFE44]/,/[\uFE47-\uFEFE\uFF00-\uFFFD]/),identifierCharacter=either(identifierHead,/\d/,/[\u0300-\u036F\u1DC0-\u1DFF\u20D0-\u20FF\uFE20-\uFE2F]/),identifier=concat(identifierHead,identifierCharacter,"*"),typeIdentifier=concat(/[A-Z]/,identifierCharacter,"*"),keywordAttributes=["attached","autoclosure",concat(/convention\(/,either("swift","block","c"),/\)/),"discardableResult","dynamicCallable","dynamicMemberLookup","escaping","freestanding","frozen",
1205
- "GKInspectable","IBAction","IBDesignable","IBInspectable","IBOutlet","IBSegueAction","inlinable","main","nonobjc","NSApplicationMain","NSCopying","NSManaged",concat(/objc\(/,identifier,/\)/),"objc","objcMembers","propertyWrapper","requires_stored_property_inits","resultBuilder","Sendable","testable","UIApplicationMain","unchecked","unknown","usableFromInline","warn_unqualified_access"],availabilityKeywords=["iOS","iOSApplicationExtension","macOS","macOSApplicationExtension","macCatalyst","macCat\
1206
- alystApplicationExtension","watchOS","watchOSApplicationExtension","tvOS","tvOSApplicationExtension","swift"];function swift(hljs2){let WHITESPACE={match:/\s+/,relevance:0},BLOCK_COMMENT=hljs2.COMMENT("/\\*","\\*/",{contains:["self"]}),COMMENTS=[hljs2.C_LINE_COMMENT_MODE,BLOCK_COMMENT],DOT_KEYWORD={match:[/\./,either(...dotKeywords,...optionalDotKeywords)],className:{2:"keyword"}},KEYWORD_GUARD={match:concat(/\./,either(...keywords)),relevance:0},PLAIN_KEYWORDS=keywords.filter(kw=>typeof kw=="st\
1207
- ring").concat(["_|0"]),REGEX_KEYWORDS=keywords.filter(kw=>typeof kw!="string").concat(keywordTypes).map(keywordWrapper),KEYWORD={variants:[{className:"keyword",match:either(...REGEX_KEYWORDS,...optionalDotKeywords)}]},KEYWORDS3={$pattern:either(/\b\w+/,/#\w+/),keyword:PLAIN_KEYWORDS.concat(numberSignKeywords),literal:literals},KEYWORD_MODES=[DOT_KEYWORD,KEYWORD_GUARD,KEYWORD],BUILT_IN_GUARD={match:concat(/\./,either(...builtIns)),relevance:0},BUILT_IN={className:"built_in",match:concat(/\b/,either(
1208
- ...builtIns),/(?=\()/)},BUILT_INS3=[BUILT_IN_GUARD,BUILT_IN],OPERATOR_GUARD={match:/->/,relevance:0},OPERATOR={className:"operator",relevance:0,variants:[{match:operator},{match:`\\.(\\.|${operatorCharacter})+`}]},OPERATORS=[OPERATOR_GUARD,OPERATOR],decimalDigits4="([0-9]_*)+",hexDigits4="([0-9a-fA-F]_*)+",NUMBER={className:"number",relevance:0,variants:[{match:`\\b(${decimalDigits4})(\\.(${decimalDigits4}))?([eE][+-]?(${decimalDigits4}))?\\b`},{match:`\\b0x(${hexDigits4})(\\.(${hexDigits4}))?([\
1209
- pP][+-]?(${decimalDigits4}))?\\b`},{match:/\b0o([0-7]_*)+\b/},{match:/\b0b([01]_*)+\b/}]},ESCAPED_CHARACTER=(rawDelimiter="")=>({className:"subst",variants:[{match:concat(/\\/,rawDelimiter,/[0\\tnr"']/)},{match:concat(/\\/,rawDelimiter,/u\{[0-9a-fA-F]{1,8}\}/)}]}),ESCAPED_NEWLINE=(rawDelimiter="")=>({className:"subst",match:concat(/\\/,rawDelimiter,/[\t ]*(?:[\r\n]|\r\n)/)}),INTERPOLATION=(rawDelimiter="")=>({className:"subst",label:"interpol",begin:concat(/\\/,rawDelimiter,/\(/),end:/\)/}),MULTILINE_STRING=(rawDelimiter="")=>({
1210
- begin:concat(rawDelimiter,/"""/),end:concat(/"""/,rawDelimiter),contains:[ESCAPED_CHARACTER(rawDelimiter),ESCAPED_NEWLINE(rawDelimiter),INTERPOLATION(rawDelimiter)]}),SINGLE_LINE_STRING=(rawDelimiter="")=>({begin:concat(rawDelimiter,/"/),end:concat(/"/,rawDelimiter),contains:[ESCAPED_CHARACTER(rawDelimiter),INTERPOLATION(rawDelimiter)]}),STRING={className:"string",variants:[MULTILINE_STRING(),MULTILINE_STRING("#"),MULTILINE_STRING("##"),MULTILINE_STRING("###"),SINGLE_LINE_STRING(),SINGLE_LINE_STRING(
1211
- "#"),SINGLE_LINE_STRING("##"),SINGLE_LINE_STRING("###")]},REGEXP_CONTENTS=[hljs2.BACKSLASH_ESCAPE,{begin:/\[/,end:/\]/,relevance:0,contains:[hljs2.BACKSLASH_ESCAPE]}],BARE_REGEXP_LITERAL={begin:/\/[^\s](?=[^/\n]*\/)/,end:/\//,contains:REGEXP_CONTENTS},EXTENDED_REGEXP_LITERAL=rawDelimiter=>{let begin=concat(rawDelimiter,/\//),end=concat(/\//,rawDelimiter);return{begin,end,contains:[...REGEXP_CONTENTS,{scope:"comment",begin:`#(?!.*${end})`,end:/$/}]}},REGEXP={scope:"regexp",variants:[EXTENDED_REGEXP_LITERAL(
1212
- "###"),EXTENDED_REGEXP_LITERAL("##"),EXTENDED_REGEXP_LITERAL("#"),BARE_REGEXP_LITERAL]},QUOTED_IDENTIFIER={match:concat(/`/,identifier,/`/)},IMPLICIT_PARAMETER={className:"variable",match:/\$\d+/},PROPERTY_WRAPPER_PROJECTION={className:"variable",match:`\\$${identifierCharacter}+`},IDENTIFIERS=[QUOTED_IDENTIFIER,IMPLICIT_PARAMETER,PROPERTY_WRAPPER_PROJECTION],AVAILABLE_ATTRIBUTE={match:/(@|#(un)?)available/,scope:"keyword",starts:{contains:[{begin:/\(/,end:/\)/,keywords:availabilityKeywords,contains:[
1213
- ...OPERATORS,NUMBER,STRING]}]}},KEYWORD_ATTRIBUTE={scope:"keyword",match:concat(/@/,either(...keywordAttributes),lookahead(either(/\(/,/\s+/)))},USER_DEFINED_ATTRIBUTE={scope:"meta",match:concat(/@/,identifier)},ATTRIBUTES=[AVAILABLE_ATTRIBUTE,KEYWORD_ATTRIBUTE,USER_DEFINED_ATTRIBUTE],TYPE={match:lookahead(/\b[A-Z]/),relevance:0,contains:[{className:"type",match:concat(/(AV|CA|CF|CG|CI|CL|CM|CN|CT|MK|MP|MTK|MTL|NS|SCN|SK|UI|WK|XC)/,identifierCharacter,"+")},{className:"type",match:typeIdentifier,
1214
- relevance:0},{match:/[?!]+/,relevance:0},{match:/\.\.\./,relevance:0},{match:concat(/\s+&\s+/,lookahead(typeIdentifier)),relevance:0}]},GENERIC_ARGUMENTS={begin:/</,end:/>/,keywords:KEYWORDS3,contains:[...COMMENTS,...KEYWORD_MODES,...ATTRIBUTES,OPERATOR_GUARD,TYPE]};TYPE.contains.push(GENERIC_ARGUMENTS);let TUPLE_ELEMENT_NAME={match:concat(identifier,/\s*:/),keywords:"_|0",relevance:0},TUPLE={begin:/\(/,end:/\)/,relevance:0,keywords:KEYWORDS3,contains:["self",TUPLE_ELEMENT_NAME,...COMMENTS,REGEXP,
1215
- ...KEYWORD_MODES,...BUILT_INS3,...OPERATORS,NUMBER,STRING,...IDENTIFIERS,...ATTRIBUTES,TYPE]},GENERIC_PARAMETERS={begin:/</,end:/>/,keywords:"repeat each",contains:[...COMMENTS,TYPE]},FUNCTION_PARAMETER_NAME={begin:either(lookahead(concat(identifier,/\s*:/)),lookahead(concat(identifier,/\s+/,identifier,/\s*:/))),end:/:/,relevance:0,contains:[{className:"keyword",match:/\b_\b/},{className:"params",match:identifier}]},FUNCTION_PARAMETERS={begin:/\(/,end:/\)/,keywords:KEYWORDS3,contains:[FUNCTION_PARAMETER_NAME,
1216
- ...COMMENTS,...KEYWORD_MODES,...OPERATORS,NUMBER,STRING,...ATTRIBUTES,TYPE,TUPLE],endsParent:!0,illegal:/["']/},FUNCTION_OR_MACRO={match:[/(func|macro)/,/\s+/,either(QUOTED_IDENTIFIER.match,identifier,operator)],className:{1:"keyword",3:"title.function"},contains:[GENERIC_PARAMETERS,FUNCTION_PARAMETERS,WHITESPACE],illegal:[/\[/,/%/]},INIT_SUBSCRIPT={match:[/\b(?:subscript|init[?!]?)/,/\s*(?=[<(])/],className:{1:"keyword"},contains:[GENERIC_PARAMETERS,FUNCTION_PARAMETERS,WHITESPACE],illegal:/\[|%/},
1217
- OPERATOR_DECLARATION={match:[/operator/,/\s+/,operator],className:{1:"keyword",3:"title"}},PRECEDENCEGROUP={begin:[/precedencegroup/,/\s+/,typeIdentifier],className:{1:"keyword",3:"title"},contains:[TYPE],keywords:[...precedencegroupKeywords,...literals],end:/}/},CLASS_FUNC_DECLARATION={match:[/class\b/,/\s+/,/func\b/,/\s+/,/\b[A-Za-z_][A-Za-z0-9_]*\b/],scope:{1:"keyword",3:"keyword",5:"title.function"}},CLASS_VAR_DECLARATION={match:[/class\b/,/\s+/,/var\b/],scope:{1:"keyword",3:"keyword"}},TYPE_DECLARATION={
1218
- begin:[/(struct|protocol|class|extension|enum|actor)/,/\s+/,identifier,/\s*/],beginScope:{1:"keyword",3:"title.class"},keywords:KEYWORDS3,contains:[GENERIC_PARAMETERS,...KEYWORD_MODES,{begin:/:/,end:/\{/,keywords:KEYWORDS3,contains:[{scope:"title.class.inherited",match:typeIdentifier},...KEYWORD_MODES],relevance:0}]};for(let variant of STRING.variants){let interpolation=variant.contains.find(mode=>mode.label==="interpol");interpolation.keywords=KEYWORDS3;let submodes=[...KEYWORD_MODES,...BUILT_INS3,
1219
- ...OPERATORS,NUMBER,STRING,...IDENTIFIERS];interpolation.contains=[...submodes,{begin:/\(/,end:/\)/,contains:["self",...submodes]}]}return{name:"Swift",keywords:KEYWORDS3,contains:[...COMMENTS,FUNCTION_OR_MACRO,INIT_SUBSCRIPT,CLASS_FUNC_DECLARATION,CLASS_VAR_DECLARATION,TYPE_DECLARATION,OPERATOR_DECLARATION,PRECEDENCEGROUP,{beginKeywords:"import",end:/$/,contains:[...COMMENTS],relevance:0},REGEXP,...KEYWORD_MODES,...BUILT_INS3,...OPERATORS,NUMBER,STRING,...IDENTIFIERS,...ATTRIBUTES,TYPE,TUPLE]}}var IDENT_RE2="[A-Za-z$_][0-9A-Za-z$_]*",KEYWORDS2=["as","in","of","if","for","while","finally","var","new","function","do","return","void","else","break","catch","instanceof","with","throw","case","default","try","switch","continue","typeof","delete","let","yield","const","class","debugger","async","await","static","import","from","export","extends","using"],LITERALS2=["true","false","null","undefined","NaN","Infinity"],TYPES2=["Object","Function","Boolean","Symbol","Math","Date","Number","BigI\
1220
- nt","String","RegExp","Array","Float32Array","Float64Array","Int8Array","Uint8Array","Uint8ClampedArray","Int16Array","Int32Array","Uint16Array","Uint32Array","BigInt64Array","BigUint64Array","Set","Map","WeakSet","WeakMap","ArrayBuffer","SharedArrayBuffer","Atomics","DataView","JSON","Promise","Generator","GeneratorFunction","AsyncFunction","Reflect","Proxy","Intl","WebAssembly"],ERROR_TYPES2=["Error","EvalError","InternalError","RangeError","ReferenceError","SyntaxError","TypeError","URIError"],
1221
- BUILT_IN_GLOBALS2=["setInterval","setTimeout","clearInterval","clearTimeout","require","exports","eval","isFinite","isNaN","parseFloat","parseInt","decodeURI","decodeURIComponent","encodeURI","encodeURIComponent","escape","unescape"],BUILT_IN_VARIABLES2=["arguments","this","super","console","window","document","localStorage","sessionStorage","module","self","global"],BUILT_INS2=[].concat(BUILT_IN_GLOBALS2,TYPES2,ERROR_TYPES2);function javascript2(hljs2){let regex=hljs2.regex,hasClosingTag=(match,{
1222
- after})=>{let tag="</"+match[0].slice(1);return match.input.indexOf(tag,after)!==-1},IDENT_RE$1=IDENT_RE2,FRAGMENT={begin:"<>",end:"</>"},XML_SELF_CLOSING=/<[A-Za-z0-9\\._:-]+\s*\/>/,XML_TAG={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(match,response)=>{let afterMatchIndex=match[0].length+match.index,nextChar=match.input[afterMatchIndex];if(nextChar==="<"||nextChar===","){response.ignoreMatch();return}nextChar===">"&&(hasClosingTag(match,{after:afterMatchIndex})||
1223
- response.ignoreMatch());let m,afterMatch=match.input.substring(afterMatchIndex);if(m=afterMatch.match(/^\s*=/)){response.ignoreMatch();return}if((m=afterMatch.match(/^\s+extends\s+/))&&m.index===0){response.ignoreMatch();return}}},KEYWORDS$1={$pattern:IDENT_RE2,keyword:KEYWORDS2,literal:LITERALS2,built_in:BUILT_INS2,"variable.language":BUILT_IN_VARIABLES2},decimalDigits4="[0-9](_?[0-9])*",frac4=`\\.(${decimalDigits4})`,decimalInteger="0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*",NUMBER={className:"numbe\
1224
- r",variants:[{begin:`(\\b(${decimalInteger})((${frac4})|\\.)?|(${frac4}))[eE][+-]?(${decimalDigits4})\\b`},{begin:`\\b(${decimalInteger})\\b((${frac4})\\b|\\.)?|(${frac4})\\b`},{begin:"\\b(0|[1-9](_?[0-9])*)n\\b"},{begin:"\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b"},{begin:"\\b0[bB][0-1](_?[0-1])*n?\\b"},{begin:"\\b0[oO][0-7](_?[0-7])*n?\\b"},{begin:"\\b0[0-7]+n?\\b"}],relevance:0},SUBST={className:"subst",begin:"\\$\\{",end:"\\}",keywords:KEYWORDS$1,contains:[]},HTML_TEMPLATE={begin:".?html`",end:"",
1225
- starts:{end:"`",returnEnd:!1,contains:[hljs2.BACKSLASH_ESCAPE,SUBST],subLanguage:"xml"}},CSS_TEMPLATE={begin:".?css`",end:"",starts:{end:"`",returnEnd:!1,contains:[hljs2.BACKSLASH_ESCAPE,SUBST],subLanguage:"css"}},GRAPHQL_TEMPLATE={begin:".?gql`",end:"",starts:{end:"`",returnEnd:!1,contains:[hljs2.BACKSLASH_ESCAPE,SUBST],subLanguage:"graphql"}},TEMPLATE_STRING={className:"string",begin:"`",end:"`",contains:[hljs2.BACKSLASH_ESCAPE,SUBST]},COMMENT={className:"comment",variants:[hljs2.COMMENT(/\/\*\*(?!\/)/,
1226
- "\\*/",{relevance:0,contains:[{begin:"(?=@[A-Za-z]+)",relevance:0,contains:[{className:"doctag",begin:"@[A-Za-z]+"},{className:"type",begin:"\\{",end:"\\}",excludeEnd:!0,excludeBegin:!0,relevance:0},{className:"variable",begin:IDENT_RE$1+"(?=\\s*(-)|$)",endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),hljs2.C_BLOCK_COMMENT_MODE,hljs2.C_LINE_COMMENT_MODE]},SUBST_INTERNALS=[hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE,HTML_TEMPLATE,CSS_TEMPLATE,GRAPHQL_TEMPLATE,TEMPLATE_STRING,{
1227
- match:/\$\d+/},NUMBER];SUBST.contains=SUBST_INTERNALS.concat({begin:/\{/,end:/\}/,keywords:KEYWORDS$1,contains:["self"].concat(SUBST_INTERNALS)});let SUBST_AND_COMMENTS=[].concat(COMMENT,SUBST.contains),PARAMS_CONTAINS=SUBST_AND_COMMENTS.concat([{begin:/(\s*)\(/,end:/\)/,keywords:KEYWORDS$1,contains:["self"].concat(SUBST_AND_COMMENTS)}]),PARAMS={className:"params",begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS$1,contains:PARAMS_CONTAINS},CLASS_OR_EXTENDS={variants:[{match:[
1228
- /class/,/\s+/,IDENT_RE$1,/\s+/,/extends/,/\s+/,regex.concat(IDENT_RE$1,"(",regex.concat(/\./,IDENT_RE$1),")*")],scope:{1:"keyword",3:"title.class",5:"keyword",7:"title.class.inherited"}},{match:[/class/,/\s+/,IDENT_RE$1],scope:{1:"keyword",3:"title.class"}}]},CLASS_REFERENCE={relevance:0,match:regex.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:"title.class",keywords:{_:[...TYPES2,...ERROR_TYPES2]}},
1229
- USE_STRICT={label:"use_strict",className:"meta",relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},FUNCTION_DEFINITION={variants:[{match:[/function/,/\s+/,IDENT_RE$1,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:"keyword",3:"title.function"},label:"func.def",contains:[PARAMS],illegal:/%/},UPPER_CASE_CONSTANT={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:"variable.constant"};function noneOf(list){return regex.concat("(?!",list.join("|"),")")}let FUNCTION_CALL={match:regex.concat(
1230
- /\b/,noneOf([...BUILT_IN_GLOBALS2,"super","import","await"].map(x2=>`${x2}\\s*\\(`)),IDENT_RE$1,regex.lookahead(/\s*\(/)),className:"title.function",relevance:0},PROPERTY_ACCESS={begin:regex.concat(/\./,regex.lookahead(regex.concat(IDENT_RE$1,/(?![0-9A-Za-z$_(])/))),end:IDENT_RE$1,excludeBegin:!0,keywords:"prototype",className:"property",relevance:0},GETTER_OR_SETTER={match:[/get|set/,/\s+/,IDENT_RE$1,/(?=\()/],className:{1:"keyword",3:"title.function"},contains:[{begin:/\(\)/},PARAMS]},FUNC_LEAD_IN_RE="\
1231
- (\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|"+hljs2.UNDERSCORE_IDENT_RE+")\\s*=>",FUNCTION_VARIABLE={match:[/const|var|let/,/\s+/,IDENT_RE$1,/\s*/,/=\s*/,/(async\s*)?/,regex.lookahead(FUNC_LEAD_IN_RE)],keywords:"async",className:{1:"keyword",3:"title.function"},contains:[PARAMS]};return{name:"JavaScript",aliases:["js","jsx","mjs","cjs"],keywords:KEYWORDS$1,exports:{PARAMS_CONTAINS,CLASS_REFERENCE},illegal:/#(?![$_A-Za-z])/,contains:[hljs2.SHEBANG({label:"shebang",binary:"node",relevance:5}),
1232
- USE_STRICT,hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE,HTML_TEMPLATE,CSS_TEMPLATE,GRAPHQL_TEMPLATE,TEMPLATE_STRING,COMMENT,{match:/\$\d+/},NUMBER,CLASS_REFERENCE,{scope:"attr",match:IDENT_RE$1+regex.lookahead(":"),relevance:0},FUNCTION_VARIABLE,{begin:"("+hljs2.RE_STARTERS_RE+"|\\b(case|return|throw)\\b)\\s*",keywords:"return throw case",relevance:0,contains:[COMMENT,hljs2.REGEXP_MODE,{className:"function",begin:FUNC_LEAD_IN_RE,returnBegin:!0,end:"\\s*=>",contains:[{className:"params",variants:[
1233
- {begin:hljs2.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:KEYWORDS$1,contains:PARAMS_CONTAINS}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:FRAGMENT.begin,end:FRAGMENT.end},{match:XML_SELF_CLOSING},{begin:XML_TAG.begin,"on:begin":XML_TAG.isTrulyOpeningTag,end:XML_TAG.end}],subLanguage:"xml",contains:[{begin:XML_TAG.begin,end:XML_TAG.end,skip:!0,contains:["self"]}]}]},FUNCTION_DEFINITION,
1234
- {beginKeywords:"while if switch catch for"},{begin:"\\b(?!function)"+hljs2.UNDERSCORE_IDENT_RE+"\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{",returnBegin:!0,label:"func.def",contains:[PARAMS,hljs2.inherit(hljs2.TITLE_MODE,{begin:IDENT_RE$1,className:"title.function"})]},{match:/\.\.\./,relevance:0},PROPERTY_ACCESS,{match:"\\$"+IDENT_RE$1,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:"title.function"},contains:[PARAMS]},FUNCTION_CALL,UPPER_CASE_CONSTANT,CLASS_OR_EXTENDS,
1235
- GETTER_OR_SETTER,{match:/\$[(.]/}]}}function typescript(hljs2){let regex=hljs2.regex,tsLanguage=javascript2(hljs2),IDENT_RE$1=IDENT_RE2,TYPES3=["any","void","number","boolean","string","object","never","symbol","bigint","unknown"],NAMESPACE={begin:[/namespace/,/\s+/,hljs2.IDENT_RE],beginScope:{1:"keyword",3:"title.class"}},INTERFACE={beginKeywords:"interface",end:/\{/,excludeEnd:!0,keywords:{keyword:"interface extends",built_in:TYPES3},contains:[tsLanguage.exports.CLASS_REFERENCE]},USE_STRICT={className:"\
1236
- meta",relevance:10,begin:/^\s*['"]use strict['"]/},TS_SPECIFIC_KEYWORDS=["type","interface","public","private","protected","implements","declare","abstract","readonly","enum","override","satisfies"],KEYWORDS$1={$pattern:IDENT_RE2,keyword:KEYWORDS2.concat(TS_SPECIFIC_KEYWORDS),literal:LITERALS2,built_in:BUILT_INS2.concat(TYPES3),"variable.language":BUILT_IN_VARIABLES2},DECORATOR={className:"meta",begin:"@"+IDENT_RE$1},swapMode=(mode,label,replacement)=>{let indx=mode.contains.findIndex(m=>m.label===
1237
- label);if(indx===-1)throw new Error("can not find mode to replace");mode.contains.splice(indx,1,replacement)};Object.assign(tsLanguage.keywords,KEYWORDS$1),tsLanguage.exports.PARAMS_CONTAINS.push(DECORATOR);let ATTRIBUTE_HIGHLIGHT=tsLanguage.contains.find(c3=>c3.scope==="attr"),OPTIONAL_KEY_OR_ARGUMENT=Object.assign({},ATTRIBUTE_HIGHLIGHT,{match:regex.concat(IDENT_RE$1,regex.lookahead(/\s*\?:/))});tsLanguage.exports.PARAMS_CONTAINS.push([tsLanguage.exports.CLASS_REFERENCE,ATTRIBUTE_HIGHLIGHT,OPTIONAL_KEY_OR_ARGUMENT]),
1238
- tsLanguage.contains=tsLanguage.contains.concat([DECORATOR,NAMESPACE,INTERFACE,OPTIONAL_KEY_OR_ARGUMENT]),swapMode(tsLanguage,"shebang",hljs2.SHEBANG()),swapMode(tsLanguage,"use_strict",USE_STRICT);let functionDeclaration=tsLanguage.contains.find(m=>m.label==="func.def");return functionDeclaration.relevance=0,Object.assign(tsLanguage,{name:"TypeScript",aliases:["ts","tsx","mts","cts"]}),tsLanguage}function decodeCodePoint(codePoint){if(!(!Number.isInteger(codePoint)||codePoint<0||codePoint>1114111))return String.fromCodePoint(codePoint)}function decodeHtmlEntity(entity){switch(entity){case"amp":return"&";case"lt":return"<";case"gt":return">";case"quot":return'"';case"apos":return"'"}if(entity.startsWith("#x")||entity.startsWith("#X"))return decodeCodePoint(Number.parseInt(entity.slice(2),16));if(entity.startsWith("#"))return decodeCodePoint(Number.parseInt(entity.slice(1),10))}function decodeHtmlEntityAt(html,index){
1239
- let semicolonIndex=html.indexOf(";",index+1);if(semicolonIndex===-1||semicolonIndex-index>16)return;let entity=html.slice(index+1,semicolonIndex),decoded=decodeHtmlEntity(entity);if(decoded!==void 0)return{text:decoded,length:semicolonIndex-index+1}}var eagerLanguages={python,java,go,javascript,json,cpp,typescript,php,ruby,c:c2,csharp,nix,bash,rust,scala,kotlin,swift,dart,groovy,perl,lua},hljs=core_default,eagerLanguagesRegistered=!1;function registerEagerLanguages(){if(!eagerLanguagesRegistered){eagerLanguagesRegistered=!0;for(let[name,language]of Object.entries(eagerLanguages))hljs.registerLanguage(name,language)}}var allLanguagesPromise,allLanguagesLoaded=!1;function loadAllHighlightLanguages(){return registerEagerLanguages(),allLanguagesPromise||
1240
- (allLanguagesPromise=new Promise(resolve=>{setImmediate(()=>{import("./es-YEFEOGR3.js").then(module=>{hljs=module.default,allLanguagesLoaded=!0,resolve()},()=>{allLanguagesLoaded=!0,resolve()})})})),allLanguagesPromise}var SPAN_CLOSE="</span>",HIGHLIGHT_CLASS_PREFIX="hljs-";function getScopeFromSpanTag(tag){let match=/\sclass\s*=\s*(?:"([^"]*)"|'([^']*)')/.exec(tag),classValue=match?.[1]??match?.[2];if(classValue){for(let className of classValue.split(/\s+/))if(className.startsWith(HIGHLIGHT_CLASS_PREFIX))
1241
- return className.slice(HIGHLIGHT_CLASS_PREFIX.length)}}function getScopeFormatter(scope,theme2){let exact=theme2[scope];if(exact)return exact;let dotIndex=scope.indexOf(".");if(dotIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dotIndex)];if(prefixFormatter)return prefixFormatter}let dashIndex=scope.indexOf("-");if(dashIndex!==-1){let prefixFormatter=theme2[scope.slice(0,dashIndex)];if(prefixFormatter)return prefixFormatter}}function getActiveFormatter(scopes,theme2){for(let i=scopes.length-
1242
- 1;i>=0;i--){let scope=scopes[i];if(!scope)continue;let formatter=getScopeFormatter(scope,theme2);if(formatter)return formatter}return theme2.default}function isSpanOpenTagStart(html,index){if(!html.startsWith("<span",index))return!1;let nextChar=html[index+5];return nextChar===">"||nextChar===" "||nextChar===" "||nextChar===`
1243
- `||nextChar==="\r"}function renderHighlightedHtml(html,theme2={}){let output="",textBuffer="",scopes=[],specialCharacter=/[<&]/g,flushText=()=>{if(!textBuffer)return;let formatter=getActiveFormatter(scopes,theme2);output+=formatter?textBuffer.includes(`
1244
- `)?textBuffer.split(`
1245
- `).map(line=>line&&formatter(line)).join(`
1246
- `):formatter(textBuffer):textBuffer,textBuffer=""},index=0;for(;index<html.length;){if(isSpanOpenTagStart(html,index)){let tagEndIndex=html.indexOf(">",index+5);if(tagEndIndex!==-1){flushText();let tag=html.slice(index,tagEndIndex+1),scope=getScopeFromSpanTag(tag);scopes.push(scope),index=tagEndIndex+1;continue}}if(html.startsWith(SPAN_CLOSE,index)){flushText(),scopes.length>0&&scopes.pop(),index+=SPAN_CLOSE.length;continue}if(html[index]==="&"){let decoded=decodeHtmlEntityAt(html,index);if(decoded){
1247
- textBuffer+=decoded.text,index+=decoded.length;continue}}specialCharacter.lastIndex=index+1;let textEnd=specialCharacter.exec(html)?.index??html.length;textBuffer+=html.slice(index,textEnd),index=textEnd}return flushText(),output}var HTML_SPECIAL=/[&<>"']/;function escapeHtml(text){return HTML_SPECIAL.test(text)?text.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#x27;"):text}function spanClass(node,classPrefix){if(node.scope){if(node.scope.
1248
- startsWith("language:"))return node.scope.replace("language:","language-");if(node.scope.includes(".")){let pieces=node.scope.split(".");return[`${classPrefix}${pieces.shift()}`,...pieces.map((piece,index)=>`${piece}${"_".repeat(index+1)}`)].join(" ")}return`${classPrefix}${node.scope}`}}function tokenTreeHtml(node,classPrefix){if(typeof node=="string")return escapeHtml(node);if(!node.children)return"";let className=spanClass(node,classPrefix),html=className===void 0?"":`<span class="${className}\
1249
- ">`;for(let child of node.children)html+=tokenTreeHtml(child,classPrefix);return className===void 0?html:`${html}${SPAN_CLOSE}`}var emittedHtml=new WeakMap,fastEmitterInstalled=!1;function installFastHtmlEmitter(){if(fastEmitterInstalled)return;fastEmitterInstalled=!0;let base=hljs.highlightAuto("",[])._emitter.constructor;if(base.name!=="TokenTreeEmitter"||typeof base.prototype.toHTML!="function")return;class FastHtmlEmitter extends base{toHTML(){let classPrefix=this.options.classPrefix,html=tokenTreeHtml(
1250
- this.rootNode,classPrefix);return emittedHtml.set(this,{html,classPrefix}),html}}hljs.configure({__emitter:FastHtmlEmitter})}var scopesOfClasses=new Map;function renderHighlightedTree(root,classPrefix,theme2){let output="",textBuffer="",scopes=[],flushText=()=>{if(!textBuffer)return;let formatter=getActiveFormatter(scopes,theme2);formatter?textBuffer.includes(`
1251
- `)?output+=textBuffer.split(`
1252
- `).map(line=>line&&formatter(line)).join(`
1253
- `):output+=formatter(textBuffer):output+=textBuffer,textBuffer=""},walk=node=>{if(typeof node=="string")return textBuffer+=node,!0;if(!node.children)return!0;let className=spanClass(node,classPrefix);if(className!==void 0){if(className.includes(">"))return!1;let scope=scopesOfClasses.get(className);scope===void 0&&!scopesOfClasses.has(className)&&(scope=getScopeFromSpanTag(`<span class="${className}">`),scopesOfClasses.set(className,scope)),flushText(),scopes.push(scope)}for(let child of node.children)
1254
- if(!walk(child))return!1;return className!==void 0&&(flushText(),scopes.pop()),!0};if(walk(root))return flushText(),output}function highlight(code,options={}){registerEagerLanguages(),installFastHtmlEmitter();let result=options.language?hljs.highlight(code,{language:options.language,ignoreIllegals:options.ignoreIllegals}):hljs.highlightAuto(code,options.languageSubset),emitter=result._emitter,emitted=emittedHtml.get(emitter);if(emitted!==void 0&&emitted.html===result.value){let rendered=renderHighlightedTree(
1255
- emitter.rootNode,emitted.classPrefix,options.theme??{});if(rendered!==void 0)return rendered}return renderHighlightedHtml(result.value,options.theme)}var onDemandLoaded,askedBeforeOnDemand=!1,missedLanguages=new Set;function loadOnDemand(){loadAllHighlightLanguages().then(()=>{let languages=new Set([...missedLanguages].filter(name=>hljs.getLanguage(name)!==void 0));missedLanguages.clear(),languages.size>0&&onDemandLoaded?.(languages)})}function loadAllHighlightLanguagesOnDemand(onLoaded){onDemandLoaded=
1256
- onLoaded,askedBeforeOnDemand&&!allLanguagesPromise&&loadOnDemand()}function supportsLanguage(name){return registerEagerLanguages(),hljs.getLanguage(name)!==void 0?!0:(allLanguagesLoaded||missedLanguages.add(name.toLowerCase()),onDemandLoaded?allLanguagesPromise||loadOnDemand():askedBeforeOnDemand=!0,!1)}function getHighlightLanguageCount(){return registerEagerLanguages(),hljs.listLanguages().length}var SYSTEM_THEME_NAME="system",FAMILIES={neutral:{hue:231.49,saturation:{min:.02,max:.08},slot:8},blue:{hue:231.49,saturation:{min:.1,max:.68},slot:4},green:{hue:158.68,saturation:{min:.1,max:.76},slot:2},red:{hue:20,saturation:{min:.1,max:.92},slot:1},yellow:{hue:82.36,saturation:{min:.5,max:1},slot:3},orange:{hue:52,saturation:{min:.12,max:.85},slot:3},violet:{hue:295,saturation:{min:.2,max:.6},slot:5},calamine:{hue:202.43,saturation:{min:.1,max:.74},slot:6},thinkingSlate:{hue:231.49,saturation:{
1257
- min:.08,max:.2},slot:4},thinkingBlue:{hue:231.49,saturation:{min:.2,max:.45},slot:4},thinkingPeriwinkle:{hue:263.25,saturation:{min:.3,max:.6},slot:6},thinkingViolet:{hue:295,saturation:{min:.4,max:.75},slot:5},thinkingMagenta:{hue:337.5,saturation:{min:.5,max:.85},slot:13},thinkingRed:{hue:20,saturation:{min:.95,max:1},slot:1}},TOKEN_FAMILIES={selectedBg:"blue",searchMatchBg:"orange",userMessageBg:"blue",customMessageBg:"violet",toolPendingBg:"neutral",toolSuccessBg:"green",toolErrorBg:"red",text:"\
1258
- neutral",userMessageText:"neutral",customMessageText:"neutral",toolTitle:"neutral",syntaxOperator:"neutral",syntaxPunctuation:"neutral",muted:"neutral",dim:"neutral",thinkingText:"neutral",toolOutput:"neutral",mdLinkUrl:"neutral",mdQuote:"neutral",mdQuoteBorder:"neutral",mdHr:"neutral",mdCodeBlockBorder:"neutral",toolDiffContext:"neutral",syntaxComment:"neutral",scrollbarTrack:"neutral",scrollbarThumb:"neutral",searchMatchText:"neutral",borderMuted:"neutral",accent:"violet",borderAccent:"violet",
1259
- customMessageLabel:"violet",mdCode:"violet",mdListBullet:"violet",syntaxType:"violet",border:"blue",mdLink:"blue",syntaxKeyword:"blue",syntaxVariable:"calamine",success:"green",mdCodeBlock:"green",toolDiffAdded:"green",bashMode:"green",syntaxNumber:"green",error:"red",toolDiffRemoved:"red",warning:"yellow",mdHeading:"yellow",syntaxFunction:"yellow",syntaxString:"orange",thinkingOff:"neutral",thinkingMinimal:"thinkingSlate",thinkingLow:"thinkingBlue",thinkingMedium:"thinkingPeriwinkle",thinkingHigh:"\
1260
- thinkingViolet",thinkingXhigh:"thinkingMagenta",thinkingMax:"thinkingRed"},TOKEN_SLOTS={syntaxString:2,syntaxNumber:5,searchMatchBg:3},LEVELS={panel:{dark:{coefficients:[.29131,-.39746,2.33185,-.85524,-1.2076,.86276],reachable:[0,.979]},light:{coefficients:[-3.74073,27.94549,-78.44258,112.6798,-79.60015,22.11277],reachable:[.348,1]}},track:{dark:{coefficients:[.39028,-.23015,.83573,2.43829,-4.38292,2.01582],reachable:[0,.946]},light:{coefficients:[-5.24921,38.37322,-107.28833,152.10005,-106.17127,
1261
- 29.18061],reachable:[.368,1]}},thinking0:{dark:{coefficients:[.52988,-.05809,-.30924,4.63567,-6.52933,2.89108],reachable:[0,.873]},light:{coefficients:[-28.27749,182.85284,-469.62416,603.15916,-384.59976,97.35147],reachable:[.51,1]}},thinking1:{dark:{coefficients:[.55278,-.03667,-.45659,4.95347,-6.90265,3.0706],reachable:[0,.858]},light:{coefficients:[-37.10484,235.86282,-596.62344,754.3633,-474.00763,118.3551],reachable:[.535,1]}},thinking2:{dark:{coefficients:[.57486,-.01765,-.58987,5.25227,-7.27175,
1262
- 3.25532],reachable:[0,.842]},light:{coefficients:[-59.89653,377.05024,-945.07843,1182.03145,-734.96375,181.68658],reachable:[.556,1]}},thinking3:{dark:{coefficients:[.59621,-62e-5,-.71148,5.53588,-7.6392,3.44606],reachable:[0,.827]},light:{coefficients:[-72.07122,445.84082,-1099.57352,1353.88793,-829.53392,202.26164],reachable:[.58,1]}},thinking4:{dark:{coefficients:[.61691,.01462,-.82288,5.80651,-8.00641,3.64333],reachable:[0,.811]},light:{coefficients:[-110.14338,674.21488,-1645.75941,2004.32367,
1263
- -1215.15899,293.3183],reachable:[.6,1]}},thinking5:{dark:{coefficients:[.63702,.02826,-.92498,6.06465,-8.37246,3.84651],reachable:[0,.795]},light:{coefficients:[-175.47701,1063.54495,-2570.70594,3098.80776,-1860.15527,444.76392],reachable:[.62,1]}},thinking6:{dark:{coefficients:[.65658,.04044,-1.01835,6.30989,-8.73529,4.05439],reachable:[0,.779]},light:{coefficients:[-183.81712,1094.70055,-2602.68539,3088.71276,-1826.91131,430.75931],reachable:[.643,1]}},subtle:{dark:{coefficients:[.56762,-.02475,
1264
- -.5383,5.12628,-7.10931,3.17324],reachable:[0,.848]},light:{coefficients:[-232.85459,1376.54473,-3249.11801,3827.91186,-2248.29472,526.55751],reachable:[.657,1]}},thumb:{dark:{coefficients:[.60323,.00278,-.73328,5.57157,-7.68067,3.46933],reachable:[0,.823]},light:{coefficients:[-82.89897,511.01355,-1255.98095,1540.76821,-940.68087,228.58523],reachable:[.586,1]}},readable:{dark:{coefficients:[.66937,.04704,-1.06871,6.43941,-8.9332,4.17229],reachable:[0,.77]},light:{coefficients:[-1554.52576,8733.56817,
1265
- -19604.93507,21977.72696,-12300.99599,2749.81288],reachable:[.751,1]}},emphasis:{dark:{coefficients:[.7303,.07695,-1.31626,7.1681,-10.14436,4.92846],reachable:[0,.712]},light:{coefficients:[-4948.31942,26870.91986,-58334.48399,63280.17197,-34298.01053,7430.30146],reachable:[.811,1]}},textOnPanel:{dark:{coefficients:[.86713,.05232,-.89428,4.79014,-5.5432,1.75023],reachable:[0,.542]},light:{coefficients:[-8570.89457,43954.60805,-90084.00702,92220.6791,-47152.15802,9632.27113],reachable:[.867,1]}},
1266
- text:{dark:{coefficients:[.89242,.02311,-.44862,2.34417,-.06084,-2.63844],reachable:[0,.5]},light:{coefficients:[-2004.67048,6664.47299,-6060.70202,-1792.61209,5133.82359,-1939.85583],reachable:[.894,1]}}},TOOL_PANELS=["toolPendingBg","toolSuccessBg","toolErrorBg"],MESSAGE_PANELS=["userMessageBg","customMessageBg"],PANELS=["userMessageBg","toolPendingBg","toolSuccessBg","toolErrorBg","selectedBg","searchMatchBg","customMessageBg"],THINKING=["thinkingOff","thinkingMinimal","thinkingLow","thinking\
1267
- Medium","thinkingHigh","thinkingXhigh","thinkingMax"],THINKING_LEVELS=["thinking0","thinking1","thinking2","thinking3","thinking4","thinking5","thinking6"],each=(tokens,on,level)=>tokens.map(token=>({token,on,level})),RULES=[...each(PANELS,["background"],"panel"),{token:"text",on:["background"],level:"text"},{token:"text",on:["selectedBg"],level:"textOnPanel"},{token:"userMessageText",on:["userMessageBg"],level:"textOnPanel"},{token:"toolTitle",on:TOOL_PANELS,level:"textOnPanel"},...each(["accen\
1268
- t","success","error","warning"],["background","selectedBg",...TOOL_PANELS],"readable"),{token:"muted",on:["background","selectedBg","customMessageBg",...TOOL_PANELS],level:"readable"},{token:"dim",on:["background","selectedBg","customMessageBg",...TOOL_PANELS],level:"subtle"},{token:"thinkingText",on:["background"],level:"readable"},{token:"customMessageText",on:["customMessageBg",...TOOL_PANELS],level:"readable"},{token:"customMessageLabel",on:["background","customMessageBg","selectedBg",...TOOL_PANELS],
1269
- level:"readable"},{token:"toolOutput",on:["background",...TOOL_PANELS],level:"readable"},...each(["mdHeading","mdLink","mdLinkUrl","mdCode","mdQuote","mdCodeBlockBorder","mdListBullet"],["background",...MESSAGE_PANELS],"readable"),{token:"mdCodeBlock",on:["background",...MESSAGE_PANELS,...TOOL_PANELS],level:"readable"},...each(["toolDiffAdded","toolDiffRemoved","toolDiffContext"],["background",...TOOL_PANELS],"readable"),...each(["syntaxComment","syntaxKeyword","syntaxFunction","syntaxVariable",
1270
- "syntaxString","syntaxNumber","syntaxType","syntaxOperator","syntaxPunctuation"],["background",...MESSAGE_PANELS,...TOOL_PANELS],"readable"),{token:"searchMatchText",on:["searchMatchBg"],level:"readable"},...each(["bashMode","border","borderAccent"],["background"],"readable"),{token:"borderMuted",on:["background"],level:"subtle"},...each(["mdQuoteBorder","mdHr"],["background",...MESSAGE_PANELS,...TOOL_PANELS],"readable"),{token:"scrollbarTrack",on:["background"],level:"track"},{token:"scrollbarT\
1271
- humb",on:["scrollbarTrack"],level:"thumb"},...THINKING.map((token,index)=>({token,on:["background"],level:THINKING_LEVELS[index]}))],READABLE_FLOOR={dark:"readable",light:"subtle"},FOREGROUND_LEVEL="emphasis",FOREGROUND_TOKENS=["text","userMessageText","toolTitle"],TEXT_MINIMUM_WCAG_CONTRAST=4.5,SOLVE_ORDER=(()=>{let order=[],visit=token=>{if(!order.includes(token)){for(let rule of RULES)if(rule.token===token)for(let surface of rule.on)surface!=="background"&&visit(surface);order.push(token)}};for(let rule of RULES)
1272
- visit(rule.token);return order})();function oklabLightness(color){return colorToOklch(rgbColor(color.r,color.g,color.b)).l}function relativeLuminance({r,g,b}){let linear=channel=>{let value=channel/255;return value<=.04045?value/12.92:((value+.055)/1.055)**2.4};return .2126*linear(r)+.7152*linear(g)+.0722*linear(b)}function wcagContrast(first,second){let a3=relativeLuminance(first),b=relativeLuminance(second);return(Math.max(a3,b)+.05)/(Math.min(a3,b)+.05)}function terminalAppearance(background,foreground){
1273
- let white={r:255,g:255,b:255},black={r:0,g:0,b:0},whiteContrast=wcagContrast(white,background),blackContrast=wcagContrast(black,background);if(foreground){let foregroundL=oklabLightness(foreground),backgroundL=oklabLightness(background);if(Math.abs(foregroundL-backgroundL)>.05){let appearance=foregroundL>backgroundL?"dark":"light";if((appearance==="dark"?whiteContrast:blackContrast)>=TEXT_MINIMUM_WCAG_CONTRAST)return appearance}}return whiteContrast>=blackContrast?"dark":"light"}var clamp2=(value,min,max)=>Math.
1274
- min(max,Math.max(min,value));function hexOf({r,g,b}){return`#${[r,g,b].map(channel=>Math.round(channel).toString(16).padStart(2,"0")).join("")}`}function bellWeight(lightness){let gaussian=x2=>Math.exp(-((x2-.5)**2)/.125);return(gaussian(lightness)-gaussian(0))/(1-gaussian(0))}function saturationCurve({saturation:{min,max}},lightness){let floor=max>0?min/max:1;return floor+(1-floor)*bellWeight(lightness)}function levelTarget(level,appearance,surfaceL){let curve=LEVELS[level][appearance];if(!(surfaceL<
1275
- curve.reachable[0]||surfaceL>curve.reachable[1]))return curve.coefficients.reduce((sum,coefficient,power)=>sum+coefficient*surfaceL**power,0)}function generateSystemThemeColors(input){let saturation=clamp2(input.saturation??1,0,1),{background,foreground}=input;if(!background)return indexedColors(saturation,input.appearanceHint);let palette=input.palette?.length===16?input.palette.map(sourceOf):void 0,appearance=terminalAppearance(background,foreground),lighter=appearance==="dark",extreme=lighter?
1276
- 1:0,backgroundL=oklabLightness(background),paint=(token,oklabL)=>{let lightness=oklabToOkhslLightness(oklabL),family=FAMILIES[TOKEN_FAMILIES[token]];if(!palette){let{min,max}=family.saturation;return okhslColor(family.hue,(min+(max-min)*bellWeight(lightness))*saturation,lightness)}return anchored(palette[TOKEN_SLOTS[token]??family.slot],family,lightness,saturation)},target=(level,surfaceL,t)=>{let reached=levelTarget(level,appearance,surfaceL);if(reached===void 0&&t===0)return;let distance=(reached??
1277
- extreme)-surfaceL,floor=(levelTarget(READABLE_FLOOR[appearance],appearance,surfaceL)??extreme)-surfaceL,compressed=Math.abs(distance)>Math.abs(floor)?distance-(distance-floor)*Math.min(t,1):distance;return surfaceL+compressed*(1-Math.max(0,t-1))},extremeText=lighter?{r:255,g:255,b:255}:{r:0,g:0,b:0},readable=color=>wcagContrast(extremeText,color)>=TEXT_MINIMUM_WCAG_CONTRAST,limitPanel=(token,l)=>{let color=paint(token,l);if(readable(color))return color;let[low,high]=[backgroundL,l];for(let index=0;index<
1278
- 20;index++){let middle=(low+high)/2;readable(paint(token,middle))?low=middle:high=middle}return paint(token,low)},solve=t=>{let colors2=new Map([["background",background]]);for(let token of SOLVE_ORDER){let targets=[];for(let rule of RULES)if(rule.token===token)for(let surface of rule.on){let value=target(rule.level,oklabLightness(colors2.get(surface)??background),t);if(value===void 0||value<0||value>1)return;targets.push(value)}let l=lighter?Math.max(...targets):Math.min(...targets);colors2.set(
1279
- token,PANELS.includes(token)?limitPanel(token,l):paint(token,l))}return colors2},relaxation=0,colors=solve(0);if(!colors){let[low,high]=[0,2];colors=solve(high);for(let index=0;index<20;index++){let middle=(low+high)/2,attempt=solve(middle);attempt?[high,colors]=[middle,attempt]:low=middle}relaxation=high}let solved=colors??new Map,surfacesOf=token=>RULES.filter(rule=>rule.token===token).flatMap(rule=>rule.on.map(surface=>solved.get(surface)??background)),result={};for(let token of Object.keys(TOKEN_FAMILIES)){
1280
- let color=solved.get(token);result[token]=color?hexOf(color):""}for(let token of FOREGROUND_TOKENS){let surfaces=surfacesOf(token),text=solved.get(token);if(foreground){let targets=surfaces.map(surface=>target(FOREGROUND_LEVEL,oklabLightness(surface),relaxation));if(targets.every(value=>value!==void 0&&value>=0&&value<=1)){let needed=lighter?Math.max(...targets):Math.min(...targets),foregroundL=oklabLightness(foreground);if(lighter?foregroundL>=needed:foregroundL<=needed){result[token]="";continue}
1281
- text=anchored(sourceOf(foreground),FAMILIES.neutral,oklabToOkhslLightness(needed),saturation)}}text&&(result[token]=hexOf(withTextContrast(text,surfaces,lighter)))}return{colors:result,dim:[],appearance}}function okhslOf({r,g,b}){return colorToOkhsl(rgbColor(r,g,b))}function sourceOf(color){return{...okhslOf(color),chroma:colorToOklch(rgbColor(color.r,color.g,color.b)).c}}function anchored(source2,family,lightness,saturation){let anchor=saturationCurve(family,source2.l),falloff=anchor>0?Math.min(
1282
- 1,saturationCurve(family,lightness)/anchor):1,color=okhslColor(source2.h,source2.s*falloff*saturation,lightness),cap=source2.chroma*falloff*saturation,{l,c:c3}=colorToOklch(color);return c3<=cap?color:colorToRgb(oklchColor(l,cap,source2.h))}function withTextContrast(color,surfaces,lighter){let meets=candidate=>surfaces.every(surface=>wcagContrast(candidate,surface)>=TEXT_MINIMUM_WCAG_CONTRAST);if(meets(color))return color;let{h,s,l}=okhslOf(color),at2=lightness=>okhslColor(h,s,lightness),extreme=lighter?
1283
- 1:0;if(!meets(at2(extreme)))return at2(extreme);let[low,high]=[l,extreme];for(let index=0;index<20;index++){let middle=(low+high)/2;meets(at2(middle))?high=middle:low=middle}return at2(high)}function indexedColors(saturation,appearance){let colors={},dim=[];for(let[token,familyName]of Object.entries(TOKEN_FAMILIES)){if(PANELS.includes(token)){colors[token]="";continue}let neutral=familyName==="neutral";colors[token]=!neutral&&saturation>0?TOKEN_SLOTS[token]??FAMILIES[familyName].slot:"",neutral&&
1284
- !FOREGROUND_TOKENS.includes(token)&&dim.push(token)}return{colors,dim,appearance}}function defineThemeTokens(tokens){for(let[name,descriptor]of Object.entries(tokens)){if(descriptor.fallback===void 0)continue;let fallback=tokens[descriptor.fallback];if(fallback===void 0)throw new Error(`Theme token ${name} has unknown fallback ${descriptor.fallback}`);if(fallback.slot!==descriptor.slot)throw new Error(`Theme token ${name} has fallback ${descriptor.fallback} in a different color slot`)}return tokens}var THEME_TOKENS=defineThemeTokens({accent:{slot:"foreground",description:"Pri\
1285
- mary accent color (logo, selected items, cursor)"},border:{slot:"foreground",description:"Normal borders"},borderAccent:{slot:"foreground",description:"Highlighted borders"},borderMuted:{slot:"foreground",description:"Subtle borders"},success:{slot:"foreground",description:"Success states"},error:{slot:"foreground",description:"Error states"},warning:{slot:"foreground",description:"Warning states"},muted:{slot:"foreground",description:"Secondary/dimmed text"},dim:{slot:"foreground",description:"\
1286
- Very dimmed text (more subtle than muted)"},text:{slot:"foreground",description:"Default text color (usually empty string)"},thinkingText:{slot:"foreground",description:"Thinking block text color"},scrollbarTrack:{slot:"foreground",description:"Fullscreen scrollbar track foreground (falls back to muted when omitted)",fallback:"muted"},scrollbarThumb:{slot:"foreground",description:"Fullscreen scrollbar thumb foreground (falls back to text when omitted)",fallback:"text"},selectedBg:{slot:"backgrou\
1287
- nd",description:"Selected item background"},searchMatchBg:{slot:"background",description:"Transcript search match background and current-match text (falls back to selectedBg when omitted)",fallback:"selectedBg"},searchMatchText:{slot:"foreground",description:"Transcript search match text and current-match background (falls back to text when omitted)",fallback:"text"},userMessageBg:{slot:"background",description:"User message background"},userMessageText:{slot:"foreground",description:"User messa\
1288
- ge text color"},customMessageBg:{slot:"background",description:"Custom message background (hook-injected messages)"},customMessageText:{slot:"foreground",description:"Custom message text color"},customMessageLabel:{slot:"foreground",description:"Custom message type label color"},toolPendingBg:{slot:"background",description:"Tool execution box (pending state)"},toolSuccessBg:{slot:"background",description:"Tool execution box (success state)"},toolErrorBg:{slot:"background",description:"Tool execu\
1289
- tion box (error state)"},toolTitle:{slot:"foreground",description:"Tool execution box title color"},toolOutput:{slot:"foreground",description:"Tool execution box output text color"},mdHeading:{slot:"foreground",description:"Markdown heading text"},mdLink:{slot:"foreground",description:"Markdown link text"},mdLinkUrl:{slot:"foreground",description:"Markdown link URL"},mdCode:{slot:"foreground",description:"Markdown inline code"},mdCodeBlock:{slot:"foreground",description:"Markdown code block cont\
1290
- ent"},mdCodeBlockBorder:{slot:"foreground",description:"Markdown code block fences"},mdQuote:{slot:"foreground",description:"Markdown blockquote text"},mdQuoteBorder:{slot:"foreground",description:"Markdown blockquote border"},mdHr:{slot:"foreground",description:"Markdown horizontal rule"},mdListBullet:{slot:"foreground",description:"Markdown list bullets/numbers"},toolDiffAdded:{slot:"foreground",description:"Added lines in tool diffs"},toolDiffRemoved:{slot:"foreground",description:"Removed li\
1291
- nes in tool diffs"},toolDiffContext:{slot:"foreground",description:"Context lines in tool diffs"},syntaxComment:{slot:"foreground",description:"Syntax highlighting: comments"},syntaxKeyword:{slot:"foreground",description:"Syntax highlighting: keywords"},syntaxFunction:{slot:"foreground",description:"Syntax highlighting: function names"},syntaxVariable:{slot:"foreground",description:"Syntax highlighting: variable names"},syntaxString:{slot:"foreground",description:"Syntax highlighting: string lit\
1292
- erals"},syntaxNumber:{slot:"foreground",description:"Syntax highlighting: number literals"},syntaxType:{slot:"foreground",description:"Syntax highlighting: type names"},syntaxOperator:{slot:"foreground",description:"Syntax highlighting: operators"},syntaxPunctuation:{slot:"foreground",description:"Syntax highlighting: punctuation"},thinkingOff:{slot:"foreground",description:"Thinking level border: off"},thinkingMinimal:{slot:"foreground",description:"Thinking level border: minimal"},thinkingLow:{
1293
- slot:"foreground",description:"Thinking level border: low"},thinkingMedium:{slot:"foreground",description:"Thinking level border: medium"},thinkingHigh:{slot:"foreground",description:"Thinking level border: high"},thinkingXhigh:{slot:"foreground",description:"Thinking level border: xhigh"},thinkingMax:{slot:"foreground",description:"Thinking level border: max (falls back to thinkingXhigh when omitted)",fallback:"thinkingXhigh"},bashMode:{slot:"foreground",description:"Editor border color in bash\
1294
- mode"}});var DEFAULT_THEME_NAME="humain-dark",themeJsonValidator;function setThemeJsonValidator(validator){themeJsonValidator=validator}function resolveVarRefs(value,vars,visited=new Set){if(typeof value=="number"||value===""||value.startsWith("#")||/^ok(lch|hsl)\(/i.test(value))return value;if(visited.has(value))throw new Error(`Circular variable reference detected: ${value}`);if(!(value in vars))throw new Error(`Variable reference not found: ${value}`);return visited.add(value),resolveVarRefs(vars[value],
1295
- vars,visited)}function resolveThemeColors(colors,vars={}){let resolved={};for(let[key,value]of Object.entries(colors))resolved[key]=resolveVarRefs(value,vars);return resolved}function withThemeTokenFallbacks(values){let resolved={...values};for(let[rawName,descriptor]of Object.entries(THEME_TOKENS)){if(!("fallback"in descriptor))continue;let name=rawName;if(resolved[name]!==void 0)continue;let fallback=descriptor.fallback,fallbackValue=resolved[fallback];if(fallbackValue===void 0)throw new Error(
1296
- `Theme token ${rawName} has unresolved fallback ${descriptor.fallback}`);resolved[name]=fallbackValue}return resolved}var terminalColors={},terminalColorsPending=!1,terminalColorScheme;function setTerminalColors(colors){terminalColors={...colors},terminalColorsPending=!1}function setTerminalColorScheme(scheme){terminalColorScheme=scheme}function markTerminalColorsPending(){terminalColorsPending=!0}var GUESSED_DEFAULT_COLORS={dark:{foreground:parseColor("#e5e5e7"),background:parseColor("#000000")},
1297
- light:{foreground:parseColor("#000000"),background:parseColor("#ffffff")}};function averageLightness(colors){let fixed=colors.filter(color=>color.kind!=="indexed"||color.index>=16);if(fixed.length!==0)return fixed.reduce((sum,color)=>sum+colorToOklch(color).l,0)/fixed.length}function detectAppearance(foregrounds,backgrounds){let fg=averageLightness(foregrounds),bg=averageLightness(backgrounds);if(fg!==void 0&&bg!==void 0)return bg<fg?"dark":"light";if(bg!==void 0)return bg<.5?"dark":"light";if(fg!==
1298
- void 0)return fg>.5?"dark":"light"}var Theme=class{name;sourcePath;sourceInfo;mode;fgAnsi=new Map;bgAnsi=new Map;concreteColors={};defaultForegroundTokens=[];defaultBackgroundTokens=[];dimTokens;ownAppearance;resolvedColors;constructor(fgColors,bgColors,mode,options={}){this.name=options.name,this.sourcePath=options.sourcePath,this.sourceInfo=options.sourceInfo,this.mode=mode,this.dimTokens=new Set(options.dim);let{fgColors:foregrounds,bgColors:backgrounds}=splitThemeColors(withThemeTokenFallbacks(
1299
- {...fgColors,...bgColors})),concreteForegrounds=[],concreteBackgrounds=[],addToken=(token,value,isBackground)=>{if(value==="")return(isBackground?this.defaultBackgroundTokens:this.defaultForegroundTokens).push(token),isBackground?"\x1B[49m":"\x1B[39m";let color=parseColor(value);return this.concreteColors[token]=color,(isBackground?concreteBackgrounds:concreteForegrounds).push(color),isBackground?backgroundAnsi(color,mode):foregroundAnsi(color,mode)};for(let[token,value]of Object.entries(foregrounds))
1300
- this.fgAnsi.set(token,addToken(token,value,!1));for(let[token,value]of Object.entries(backgrounds))this.bgAnsi.set(token,addToken(token,value,!0));this.ownAppearance=options.appearance??detectAppearance(concreteForegrounds,concreteBackgrounds)}get appearance(){return this.ownAppearance??getTerminalTheme()}get colors(){let terminal=terminalColors;if(this.resolvedColors?.terminal!==terminal){let guess=GUESSED_DEFAULT_COLORS[this.appearance],toColor=(rgb,fallback)=>rgb?rgbColor(rgb.r,rgb.g,rgb.b):fallback,
1301
- foreground=toColor(terminal.foreground,guess.foreground),background=toColor(terminal.background,guess.background),colors={...this.concreteColors};for(let token of this.defaultForegroundTokens)colors[token]=foreground;for(let token of this.defaultBackgroundTokens)colors[token]=background;for(let token of this.dimTokens){let color=colors[token];color&&(colors[token]=mixColors(color,background,.4))}this.resolvedColors={terminal,colors:Object.freeze(colors)}}return this.resolvedColors.colors}style(text,options){
1302
- let{fg,bg}=options;return typeof fg=="string"&&this.dimTokens.has(fg)&&(options={...options,dim:!0}),styleTextWithAnsi(text,fg===void 0?void 0:typeof fg=="string"?this.tokenAnsi(this.fgAnsi,fg):foregroundAnsi(fg,this.mode),bg===void 0?void 0:typeof bg=="string"?this.tokenAnsi(this.bgAnsi,bg):backgroundAnsi(bg,this.mode),options)}fg(color,text){let ansi=this.tokenAnsi(this.fgAnsi,color);return this.dimTokens.has(color)?`${ansi}\x1B[2m${text}\x1B[22;39m`:`${ansi}${text}\x1B[39m`}bg(color,text){return`${this.
1303
- tokenAnsi(this.bgAnsi,color)}${text}\x1B[49m`}tokenAnsi(ansi,token){let value=ansi.get(token);if(value===void 0)throw new Error(`Unknown theme color: ${token}`);return value}bold(text){return source_default.bold(text)}italic(text){return source_default.italic(text)}underline(text){return source_default.underline(text)}inverse(text){return source_default.inverse(text)}strikethrough(text){return source_default.strikethrough(text)}getFgAnsi(color){let ansi=this.tokenAnsi(this.fgAnsi,color);return this.
1304
- dimTokens.has(color)?`${ansi}\x1B[2m`:ansi}getBgAnsi(color){return this.tokenAnsi(this.bgAnsi,color)}getColorMode(){return this.mode}getThinkingBorderColor(level){switch(level){case"off":return str=>this.fg("thinkingOff",str);case"minimal":return str=>this.fg("thinkingMinimal",str);case"low":return str=>this.fg("thinkingLow",str);case"medium":return str=>this.fg("thinkingMedium",str);case"high":return str=>this.fg("thinkingHigh",str);case"xhigh":return str=>this.fg("thinkingXhigh",str);case"max":
1305
- return str=>this.fg("thinkingMax",str);default:return str=>this.fg("thinkingOff",str)}}getBashModeBorderColor(){return str=>this.fg("bashMode",str)}},BUILTIN_THEMES;function getBuiltinThemes(){if(!BUILTIN_THEMES){let themesDir=getThemesDir(),darkPath=path4.join(themesDir,"dark.json"),lightPath=path4.join(themesDir,"light.json"),humainDarkPath=path4.join(themesDir,"humain-dark.json"),humainLightPath=path4.join(themesDir,"humain-light.json");BUILTIN_THEMES={dark:JSON.parse(stripBom(fs3.readFileSync(
1306
- darkPath,"utf-8"))),light:JSON.parse(stripBom(fs3.readFileSync(lightPath,"utf-8"))),"humain-dark":JSON.parse(stripBom(fs3.readFileSync(humainDarkPath,"utf-8"))),"humain-light":JSON.parse(stripBom(fs3.readFileSync(humainLightPath,"utf-8")))}}return BUILTIN_THEMES}function getAvailableThemes(){return getAvailableThemesWithPaths().map(({name})=>name)}function getAvailableThemesWithPaths(){let themesDir=getThemesDir(),result=[],seen=new Set,addTheme=themeInfo=>{seen.has(themeInfo.name)||(seen.add(themeInfo.
1307
- name),result.push(themeInfo))};addTheme({name:SYSTEM_THEME_NAME,path:void 0});for(let name of Object.keys(getBuiltinThemes()))addTheme({name,path:path4.join(themesDir,`${name}.json`)});for(let themeInfo of getCustomThemeInfos())addTheme(themeInfo);for(let[name,theme2]of registeredThemes.entries())addTheme({name,path:theme2.sourcePath});return result.sort((a3,b)=>a3.name===SYSTEM_THEME_NAME?-1:b.name===SYSTEM_THEME_NAME?1:a3.name.localeCompare(b.name))}function getCustomThemeInfos(){let customThemesDir=getCustomThemesDir(),
1308
- result=[];if(!fs3.existsSync(customThemesDir))return result;for(let file of fs3.readdirSync(customThemesDir)){if(!file.endsWith(".json"))continue;let themePath=path4.join(customThemesDir,file);try{let customTheme=loadThemeFromPath(themePath);customTheme.name&&result.push({name:customTheme.name,path:themePath})}catch{}}return result}function assertThemeNameIsValid(name){if(name.includes("/"))throw new Error(`Invalid theme name "${name}": theme names cannot contain "/" because it is reserved for a\
1309
- utomatic light/dark theme settings.`)}function parseThemeJson(label,json2){if(themeJsonValidator)return themeJsonValidator(label,json2);if(typeof json2!="object"||json2===null||!("colors"in json2))throw new Error(`Invalid theme "${label}": expected an object with a "colors" map.`);return json2}function parseThemeJsonContent(label,content){let json2;try{json2=JSON.parse(stripBom(content))}catch(error){throw new Error(`Failed to parse theme ${label}: ${error}`)}return parseThemeJson(label,json2)}function loadThemeJson(name){
1310
- let builtinThemes=getBuiltinThemes();if(name in builtinThemes)return builtinThemes[name];let registeredTheme=registeredThemes.get(name);if(registeredTheme?.sourcePath){let content2=fs3.readFileSync(registeredTheme.sourcePath,"utf-8");return parseThemeJsonContent(registeredTheme.sourcePath,content2)}if(registeredTheme)throw new Error(`Theme "${name}" does not have a source path for export`);let customThemesDir=getCustomThemesDir(),themePath=path4.join(customThemesDir,`${name}.json`);if(!fs3.existsSync(
1311
- themePath))throw new Error(`Theme not found: ${name}`);let content=fs3.readFileSync(themePath,"utf-8");return parseThemeJsonContent(name,content)}function splitThemeColors(colors){let fgColors={},bgColors={};for(let[key,value]of Object.entries(colors))THEME_TOKENS[key].slot==="background"?bgColors[key]=value:fgColors[key]=value;return{fgColors,bgColors}}function createTheme(themeJson,mode,sourcePath){let colorMode=mode??getTerminalColorMode(),resolvedColors=withThemeTokenFallbacks(resolveThemeColors(
1312
- themeJson.colors,themeJson.vars)),{fgColors,bgColors}=splitThemeColors(resolvedColors);return new Theme(fgColors,bgColors,colorMode,{name:themeJson.name,sourcePath,appearance:themeJson.appearance})}function createSystemTheme(mode){let generated=generateSystemThemeColors({...terminalColors,saturation:terminalColorsPending?0:1,appearanceHint:getTerminalTheme()}),{fgColors,bgColors}=splitThemeColors(withThemeTokenFallbacks(generated.colors));return new Theme(fgColors,bgColors,mode??getTerminalColorMode(),
1313
- {name:SYSTEM_THEME_NAME,appearance:generated.appearance,dim:generated.dim})}function loadThemeFromPath(themePath,mode){let content=fs3.readFileSync(themePath,"utf-8"),themeJson=parseThemeJsonContent(themePath,content);return createTheme(themeJson,mode,themePath)}function loadTheme(name,mode){if(name===SYSTEM_THEME_NAME)return createSystemTheme(mode);let registeredTheme=registeredThemes.get(name);if(registeredTheme)return registeredTheme;let themeJson=loadThemeJson(name);return createTheme(themeJson,
1314
- mode)}function getThemeByName(name){try{return loadTheme(name)}catch{return}}function parseAutoThemeSetting(themeSetting){if(!themeSetting)return;let slashIndex=themeSetting.indexOf("/");if(slashIndex===-1||themeSetting.indexOf("/",slashIndex+1)!==-1)return;let lightTheme=themeSetting.slice(0,slashIndex).trim(),darkTheme=themeSetting.slice(slashIndex+1).trim();if(!(!lightTheme||!darkTheme))return{lightTheme,darkTheme}}function resolveThemeSetting(themeSetting,terminalTheme){let autoTheme=parseAutoThemeSetting(
1315
- themeSetting);if(autoTheme)return terminalTheme==="light"?autoTheme.lightTheme:autoTheme.darkTheme;if(!themeSetting?.includes("/")&&typeof themeSetting=="string")return themeSetting}function detectColorFgBgTheme(env=process.env){let bg=env.COLORFGBG?.split(";").at(-1)?.trim();if(!bg||!/^\d{1,2}$/.test(bg))return;let index=Number(bg);if(!(index>15))return index<=6||index===8?"dark":"light"}function detectTerminalTheme(colors={},reportedScheme,env=process.env){let{background,foreground}=colors;return background?
1316
- terminalAppearance(background,foreground):reportedScheme??detectColorFgBgTheme(env)??"dark"}function getTerminalTheme(){return detectTerminalTheme(terminalColors,terminalColorScheme)}var THEME_KEY=Symbol.for("humain-terminal:theme"),THEME_KEY_LEGACY_EARENDIL=Symbol.for("@earendil-works/pi-coding-agent:theme"),THEME_KEY_LEGACY_MARIO=Symbol.for("@mariozechner/pi-coding-agent:theme"),theme=new Proxy({},{get(_target,prop){let t=globalThis[THEME_KEY];if(!t)throw new Error("Theme not initialized. Call\
1317
- initTheme() first.");return t[prop]}});function getThemeInstance(){return globalThis[THEME_KEY]}function setGlobalTheme(t){globalThis[THEME_KEY]=t,globalThis[THEME_KEY_LEGACY_EARENDIL]=t,globalThis[THEME_KEY_LEGACY_MARIO]=t}var currentThemeName,themeWatcher,themeReloadTimer,onThemeChangeCallback,registeredThemes=new Map;function setRegisteredThemes(themes){registeredThemes.clear();for(let theme2 of themes)theme2.name&&(assertThemeNameIsValid(theme2.name),registeredThemes.set(theme2.name,theme2))}
1318
- function initTheme(themeName,enableWatcher=!1){let name=themeName??DEFAULT_THEME_NAME;currentThemeName=name;try{setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher()}catch{currentThemeName=SYSTEM_THEME_NAME,setGlobalTheme(loadTheme(SYSTEM_THEME_NAME))}}function setTheme(name,enableWatcher=!1){currentThemeName=name;try{return setGlobalTheme(loadTheme(name)),enableWatcher&&startThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback(),{success:!0}}catch(error){return currentThemeName=
1319
- SYSTEM_THEME_NAME,setGlobalTheme(loadTheme(SYSTEM_THEME_NAME)),{success:!1,error:error instanceof Error?error.message:String(error)}}}function setThemeInstance(themeInstance){setGlobalTheme(themeInstance),currentThemeName="<in-memory>",stopThemeWatcher(),onThemeChangeCallback&&onThemeChangeCallback()}function onThemeChange(callback){onThemeChangeCallback=callback}function startThemeWatcher(){if(stopThemeWatcher(),!currentThemeName||currentThemeName==="dark"||currentThemeName==="light"||currentThemeName===
1320
- SYSTEM_THEME_NAME)return;let customThemesDir=getCustomThemesDir(),watchedThemeName=currentThemeName,watchedFileName=`${watchedThemeName}.json`,themeFile=path4.join(customThemesDir,watchedFileName);if(!fs3.existsSync(themeFile))return;let scheduleReload=()=>{themeReloadTimer&&clearTimeout(themeReloadTimer),themeReloadTimer=setTimeout(()=>{if(themeReloadTimer=void 0,currentThemeName===watchedThemeName&&fs3.existsSync(themeFile))try{let reloadedTheme=loadThemeFromPath(themeFile);registeredThemes.set(
1321
- watchedThemeName,reloadedTheme),setGlobalTheme(reloadedTheme),onThemeChangeCallback&&onThemeChangeCallback()}catch{}},100)};themeWatcher=watchWithErrorHandler(customThemesDir,(_eventType,filename)=>{if(currentThemeName===watchedThemeName){if(!filename){scheduleReload();return}filename===watchedFileName&&scheduleReload()}},()=>{closeWatcher(themeWatcher),themeWatcher=void 0})??void 0}function stopThemeWatcher(){themeReloadTimer&&(clearTimeout(themeReloadTimer),themeReloadTimer=void 0),closeWatcher(
1322
- themeWatcher),themeWatcher=void 0}function getResolvedThemeColors(themeName){let colors=loadTheme(themeName??currentThemeName??SYSTEM_THEME_NAME).colors;return Object.fromEntries(Object.entries(colors).map(([token,color])=>[token,colorToHex(color)]))}function getThemeExportColors(themeName){let name=themeName??currentThemeName??SYSTEM_THEME_NAME;if(name===SYSTEM_THEME_NAME)return{};try{let themeJson=loadThemeJson(name),exportSection=themeJson.export;if(!exportSection)return{};let vars=themeJson.vars??{},resolve=value=>{if(value===void 0)return;let resolved=resolveVarRefs(value,vars);if(typeof resolved=="number")return colorToHex(indexedColor(resolved));if(resolved!=="")return/^okhsl\(/i.test(resolved)?colorToHex(parseColor(resolved)):resolved};
1323
- return{pageBg:resolve(exportSection.pageBg),cardBg:resolve(exportSection.cardBg),infoBg:resolve(exportSection.infoBg)}}catch{return{}}}var cachedHighlightThemeFor,cachedCliHighlightTheme;function buildCliHighlightTheme(t){return{keyword:s=>t.fg("syntaxKeyword",s),built_in:s=>t.fg("syntaxType",s),literal:s=>t.fg("syntaxNumber",s),number:s=>t.fg("syntaxNumber",s),regexp:s=>t.fg("syntaxString",s),string:s=>t.fg("syntaxString",s),subst:s=>t.fg("text",s),comment:s=>t.fg("syntaxComment",s),doctag:s=>t.
1324
- fg("syntaxComment",s),meta:s=>t.fg("muted",s),function:s=>t.fg("syntaxFunction",s),title:s=>t.fg("syntaxFunction",s),class:s=>t.fg("syntaxType",s),type:s=>t.fg("syntaxType",s),tag:s=>t.fg("syntaxPunctuation",s),name:s=>t.fg("syntaxKeyword",s),attr:s=>t.fg("syntaxVariable",s),variable:s=>t.fg("syntaxVariable",s),params:s=>t.fg("syntaxVariable",s),operator:s=>t.fg("syntaxOperator",s),punctuation:s=>t.fg("syntaxPunctuation",s),emphasis:s=>t.italic(s),strong:s=>t.bold(s),link:s=>t.underline(s),addition:s=>t.
1325
- fg("toolDiffAdded",s),deletion:s=>t.fg("toolDiffRemoved",s)}}function getCliHighlightTheme(t){return(cachedHighlightThemeFor!==t||!cachedCliHighlightTheme)&&(cachedHighlightThemeFor=t,cachedCliHighlightTheme=buildCliHighlightTheme(t)),cachedCliHighlightTheme}function highlightCode(code,lang){let validLang=lang&&supportsLanguage(lang)?lang:void 0;if(!validLang)return code.split(`
1326
- `).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(getThemeInstance()??theme)};try{return highlight(code,opts).split(`
1327
- `)}catch{return code.split(`
1328
- `).map(line=>theme.fg("mdCodeBlock",line))}}var CodeHighlighter=class{last;highlight(code,lang){let currentTheme=getThemeInstance(),languageCount=getHighlightLanguageCount(),last=this.last;if(last?.code===code&&last.lang===lang&&last.theme===currentTheme&&last.languageCount===languageCount)return last.lines;let lines=highlightCode(code,lang);return this.last={code,lang,theme:currentTheme,languageCount,lines},lines}};function getLanguageFromPath(filePath){let ext=filePath.split(".").pop()?.toLowerCase();
1329
- return ext?{ts:"typescript",tsx:"typescript",js:"javascript",jsx:"javascript",mjs:"javascript",cjs:"javascript",py:"python",rb:"ruby",rs:"rust",go:"go",java:"java",kt:"kotlin",swift:"swift",c:"c",h:"c",cpp:"cpp",cc:"cpp",cxx:"cpp",hpp:"cpp",cs:"csharp",php:"php",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",html:"html",htm:"html",css:"css",scss:"scss",sass:"sass",less:"less",json:"json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"\
1330
- dockerfile",makefile:"makefile",cmake:"cmake",lua:"lua",perl:"perl",r:"r",scala:"scala",clj:"clojure",ex:"elixir",exs:"elixir",erl:"erlang",hs:"haskell",ml:"ocaml",vim:"vim",graphql:"graphql",proto:"protobuf",tf:"hcl",hcl:"hcl"}[ext]:void 0}function getMarkdownTheme(){return{heading:text=>theme.fg("mdHeading",text),link:text=>theme.fg("mdLink",text),linkUrl:text=>theme.fg("mdLinkUrl",text),code:text=>theme.fg("mdCode",text),codeBlock:text=>theme.fg("mdCodeBlock",text),codeBlockBorder:text=>theme.
1331
- fg("mdCodeBlockBorder",text),quote:text=>theme.fg("mdQuote",text),quoteBorder:text=>theme.fg("mdQuoteBorder",text),hr:text=>theme.fg("mdHr",text),listBullet:text=>theme.fg("mdListBullet",text),bold:text=>theme.bold(text),italic:text=>theme.italic(text),underline:text=>theme.underline(text),strikethrough:text=>theme.strikethrough(text),highlightCode}}function getSelectListTheme(){return{selectedPrefix:text=>theme.fg("accent",text),selectedText:text=>theme.fg("accent",text),description:text=>theme.
1332
- fg("muted",text),scrollInfo:text=>theme.fg("muted",text),noMatch:text=>theme.fg("muted",text)}}function getEditorTheme(){return{borderColor:text=>theme.fg("borderMuted",text),selectList:getSelectListTheme()}}function getSettingsListTheme(){return{label:(text,selected)=>selected?theme.fg("accent",text):text,value:(text,selected)=>selected?theme.fg("accent",text):theme.fg("muted",text),description:text=>theme.fg("dim",text),cursor:theme.fg("accent","\u2192 "),hint:text=>theme.fg("dim",text)}}function formatKeyPart(part,options){let displayPart=process.platform==="darwin"&&part.toLowerCase()==="alt"?"option":part;return options.capitalize?displayPart.charAt(0).toUpperCase()+displayPart.slice(1):displayPart}function formatKeyText(key,options={}){return key.split("/").map(k=>k.split("+").map(part=>formatKeyPart(part,options)).join("+")).join("/")}function formatKeys(keys,options={}){return keys.length===0?"":formatKeyText(keys.join("/"),options)}function keyText(keybinding){return formatKeys(
1333
- getKeybindings().getKeys(keybinding))}function keyDisplayText(keybinding){return formatKeys(getKeybindings().getKeys(keybinding),{capitalize:!0})}function keyHint(keybinding,description){return theme.fg("dim",keyText(keybinding))+theme.fg("muted",` ${description}`)}function rawKeyHint(key,description){return theme.fg("dim",formatKeyText(key))+theme.fg("muted",` ${description}`)}export{Y,fuzzyMatch,fuzzyFilter,visibleWidth,stripTerminalSequences,sanitizeTerminalText,startsWithText,sanitizeTerminalTextFrom,replaceControlCharacters,wrapTextWithAnsi,applyBackgroundToLine,truncateToWidth,sliceByColumn,CombinedAutocompleteProvider,indexedColor,rgbColor,parseColor,colorToRgb,mixColors,foregroundAnsi,backgroundAnsi,styleText,Key,matchesKey,renderedMarkdownGeneration,onCapabilitiesChange,detectCapabilities,getCapabilities,getTerminalColorMode,setCapabilityOverrides,getImageDimensions,
1334
- hyperlink,imageFallback,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,SettingsList,Spacer,TruncatedText,VStack,getNativeClipboard,ProcessTerminal,TuiAltScreen,TuiMainScreen,dist_exports,
1335
- FS_WATCH_RETRY_DELAY_MS,closeWatcher,watchWithErrorHandler,loadAllHighlightLanguagesOnDemand,supportsLanguage,SYSTEM_THEME_NAME,THEME_TOKENS,DEFAULT_THEME_NAME,setThemeJsonValidator,setTerminalColors,setTerminalColorScheme,markTerminalColorsPending,Theme,getAvailableThemes,getAvailableThemesWithPaths,loadThemeFromPath,getThemeByName,parseAutoThemeSetting,resolveThemeSetting,getTerminalTheme,theme,getThemeInstance,setRegisteredThemes,initTheme,setTheme,setThemeInstance,onThemeChange,stopThemeWatcher,
1336
- getResolvedThemeColors,getThemeExportColors,highlightCode,CodeHighlighter,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,keyDisplayText,keyHint,rawKeyHint};