@humain/humain-code 0.5.4 → 0.6.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +170 -0
- package/dist/bundle/agent-monitor.js +1 -1
- package/dist/bundle/chunks/anthropic-messages-FGFIMZUF.js +66 -0
- package/dist/bundle/chunks/azure-openai-responses-6JNTC7KO.js +15 -0
- package/dist/bundle/chunks/bedrock-converse-stream.js +261 -237
- package/dist/bundle/chunks/chunk-2H3LUS62.js +1966 -0
- package/dist/bundle/chunks/{chunk-GEISZXXH.js → chunk-4ZBGTJJM.js} +1 -1
- package/dist/bundle/chunks/{chunk-QWXPGBAG.js → chunk-5JSLXC2A.js} +1 -1
- package/dist/bundle/chunks/{chunk-L2VKM23Q.js → chunk-6DE7LJKV.js} +21 -21
- package/dist/bundle/chunks/{chunk-V62QBESW.js → chunk-6E6RHNOU.js} +11 -10
- package/dist/bundle/chunks/chunk-7RZ5BS7U.js +2 -0
- package/dist/bundle/chunks/chunk-AHSNQWZU.js +24 -0
- package/dist/bundle/chunks/{chunk-UJLCKIMZ.js → chunk-AOH2O5CP.js} +3469 -3133
- package/dist/bundle/chunks/{chunk-ODJUBJK2.js → chunk-B7NJMF7B.js} +11 -11
- package/dist/bundle/chunks/chunk-BQ3TMEWD.js +7 -0
- package/dist/bundle/chunks/{chunk-KKCMWB63.js → chunk-C6VERWRZ.js} +1 -1
- package/dist/bundle/chunks/{chunk-CN3Q5UNB.js → chunk-CFHOPLW5.js} +658 -574
- package/dist/bundle/chunks/chunk-CVC2GV26.js +1986 -0
- package/dist/bundle/chunks/{chunk-DU6POZ7E.js → chunk-DHW3REC5.js} +1 -1
- package/dist/bundle/chunks/{chunk-UTNHGOFS.js → chunk-EDONIPUJ.js} +38 -38
- package/dist/bundle/chunks/{chunk-FO2NYB6O.js → chunk-FDGW5ZTG.js} +1147 -1110
- package/dist/bundle/chunks/{chunk-XQX7S3GM.js → chunk-GICL5V54.js} +1 -1
- package/dist/bundle/chunks/chunk-H7Y4QY7K.js +11 -0
- package/dist/bundle/chunks/chunk-HW6HMUXS.js +188 -0
- package/dist/bundle/chunks/chunk-I6AQOITY.js +53 -0
- package/dist/bundle/chunks/{chunk-ZI7TK7HM.js → chunk-IADQJFNH.js} +21 -17
- package/dist/bundle/chunks/chunk-J7AP2BUJ.js +3 -0
- package/dist/bundle/chunks/chunk-JFE52VSN.js +120 -0
- package/dist/bundle/chunks/{chunk-MIJHJNNQ.js → chunk-LDGCU6PD.js} +127 -3
- package/dist/bundle/chunks/{chunk-PS7DGA7B.js → chunk-M4CHQBAI.js} +1 -1
- package/dist/bundle/chunks/{chunk-YDBNMIA3.js → chunk-NN53K2QQ.js} +19 -1
- package/dist/bundle/chunks/{chunk-RTXDU3AA.js → chunk-ONR6Q3II.js} +255 -195
- package/dist/bundle/chunks/{chunk-Y3OPKKDR.js → chunk-P4P7OZ7R.js} +34 -32
- package/dist/bundle/chunks/{chunk-OZNC2W4B.js → chunk-PCTLFSQG.js} +444 -411
- package/dist/bundle/chunks/{chunk-YFBDR4IW.js → chunk-PNGNZXOI.js} +3 -3
- package/dist/bundle/chunks/{chunk-UDB6NI4G.js → chunk-RGUZULEE.js} +593 -481
- package/dist/bundle/chunks/chunk-RO5YPAJH.js +23 -0
- package/dist/bundle/chunks/{chunk-A6B2QMA7.js → chunk-RU7ADKA7.js} +176 -162
- package/dist/bundle/chunks/{chunk-JCXXRCP6.js → chunk-T3KDZFM4.js} +16 -16
- package/dist/bundle/chunks/{chunk-HT5YN3LX.js → chunk-TEOMXMW6.js} +3 -3
- package/dist/bundle/chunks/{chunk-HIZWUSPN.js → chunk-VEGJT52D.js} +77 -77
- package/dist/bundle/chunks/{chunk-IDU5BNNI.js → chunk-XMZGB3H4.js} +12 -3
- package/dist/bundle/chunks/chunk-YEPHPMQC.js +647 -0
- package/dist/bundle/chunks/{chunk-XA7CJAYH.js → chunk-YRUIJ5AH.js} +48 -42
- package/dist/bundle/chunks/{cli-ENEFJH2B.js → cli-BNCWK54K.js} +21 -17
- package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-T7TPP7SQ.js → cloudflare-workers-ai-system-one-KI6W3USX.js} +1 -1
- package/dist/bundle/chunks/codemode-worker.js +81 -75
- package/dist/bundle/chunks/compat-I5VPOXFT.js +13 -0
- package/dist/bundle/chunks/dist-J5IUPLMH.js +37 -0
- package/dist/bundle/chunks/{dist-RKNCFFGM.js → dist-SKBR3C7C.js} +720 -696
- package/dist/bundle/chunks/dist-TVRQXUY6.js +8 -0
- package/dist/bundle/chunks/{dist-cjs-HTASUQXQ.js → dist-cjs-2SKN226B.js} +77 -77
- package/dist/bundle/chunks/{easter-egg-3d-YOPLCOVW.js → easter-egg-3d-673VRP6Y.js} +1 -1
- package/dist/bundle/chunks/{esm-R6HJ4QEG.js → esm-WPALMLUO.js} +3 -3
- package/dist/bundle/chunks/{event-streams-BR2IL6C5.js → event-streams-7YGFEPBZ.js} +1 -1
- package/dist/bundle/chunks/{execute-2JXEKQ2X.js → execute-PIUR5MUV.js} +23 -23
- package/dist/bundle/chunks/{extract-OTCGZGTL.js → extract-4O5Z5725.js} +74 -71
- package/dist/bundle/chunks/github-copilot.js +50 -51
- package/dist/bundle/chunks/google-generative-ai-635YZEHN.js +22 -0
- package/dist/bundle/chunks/google-vertex-I3ZJ3SB2.js +26 -0
- package/dist/bundle/chunks/host-OQOEIWHK.js +2 -0
- package/dist/bundle/chunks/image-resize-worker.js +3 -2
- package/dist/bundle/chunks/kimi-coding.js +13 -14
- package/dist/bundle/chunks/{llama-cpp-classify-B3G57LVR.js → llama-cpp-classify-PP63BYDF.js} +1 -1
- package/dist/bundle/chunks/meta.js +10 -10
- package/dist/bundle/chunks/mistral-conversations-OKG5GKXR.js +42 -0
- package/dist/bundle/chunks/{node-VSA4ZN7D.js → node-UGQUSQE6.js} +1 -1
- package/dist/bundle/chunks/{node-SJPZTR4K.js → node-UNHECG4X.js} +168 -157
- package/dist/bundle/chunks/openai-codex-responses-6JYZIFT4.js +100 -0
- package/dist/bundle/chunks/openai-completions-YBNI6CAP.js +82 -0
- package/dist/bundle/chunks/{openai-decisions-WOWUC65P.js → openai-decisions-5G5YBFRQ.js} +1 -1
- package/dist/bundle/chunks/openai-responses-C3APJ6MK.js +27 -0
- package/dist/bundle/chunks/{openrouter-images-5K47HDAT.js → openrouter-images-FCJT7C7I.js} +2 -2
- package/dist/bundle/chunks/{pdfjs-EK6K7CXX.js → pdfjs-AKD6EBKN.js} +196 -175
- package/dist/bundle/chunks/pdfjs-decoders-OFXX4HDZ.js +2 -0
- package/dist/bundle/chunks/pdfjs-jbig2-TXR26KRI.js +278 -0
- package/dist/bundle/chunks/pdfjs-jbig2_nowasm_fallback-FH3KJM4H.js +326 -0
- package/dist/bundle/chunks/pdfjs-openjpeg-SKR7C34X.js +671 -0
- package/dist/bundle/chunks/pdfjs-openjpeg_nowasm_fallback-VUBL7UEE.js +974 -0
- package/dist/bundle/chunks/pi-messages-UHYZYEOC.js +25 -0
- package/dist/bundle/chunks/radius.js +8 -8
- package/dist/bundle/chunks/{runtime-K3F2QDQP.js → runtime-KE3HDSRT.js} +1 -1
- package/dist/bundle/chunks/{turndown.cjs-U7XOXH4O.js → turndown.cjs-WKGZX7NZ.js} +1 -1
- package/dist/bundle/chunks/{typesafe-system-one-43OCHGKP.js → typesafe-system-one-VYVAMWQV.js} +1 -1
- package/dist/bundle/chunks/{undici-EK3EUI2E.js → undici-C6S56CGI.js} +1 -1
- package/dist/bundle/chunks/virtual-modules-KDUZIB3W.js +23 -0
- package/dist/bundle/cli-runtime.js +3 -3
- package/dist/bundle/flow/package.json +5 -5
- package/dist/bundle/index.js +10 -10
- package/dist/bundle/rpc-entry.js +3 -3
- package/dist/cli/args.d.ts.map +1 -1
- package/dist/cli/args.js +9 -8
- package/dist/cli/args.js.map +1 -1
- package/dist/config.d.ts +12 -0
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +29 -5
- package/dist/config.js.map +1 -1
- package/dist/coordination/adapter/tool.d.ts +8 -5
- package/dist/coordination/adapter/tool.d.ts.map +1 -1
- package/dist/coordination/adapter/tool.js +32 -6
- package/dist/coordination/adapter/tool.js.map +1 -1
- package/dist/coordination/client/client.d.ts.map +1 -1
- package/dist/coordination/client/client.js +19 -1
- package/dist/coordination/client/client.js.map +1 -1
- package/dist/core/agent-session-runtime.js +3 -3
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/agent-session.d.ts +23 -3
- package/dist/core/agent-session.d.ts.map +1 -1
- package/dist/core/agent-session.js +142 -39
- package/dist/core/agent-session.js.map +1 -1
- package/dist/core/anthropic-subscription-usage.d.ts +4 -0
- package/dist/core/anthropic-subscription-usage.d.ts.map +1 -1
- package/dist/core/anthropic-subscription-usage.js +71 -1
- package/dist/core/anthropic-subscription-usage.js.map +1 -1
- package/dist/core/bug-report.d.ts +4 -4
- package/dist/core/codex-reset.d.ts +45 -0
- package/dist/core/codex-reset.d.ts.map +1 -0
- package/dist/core/codex-reset.js +190 -0
- package/dist/core/codex-reset.js.map +1 -0
- package/dist/core/codex-usage.d.ts +4 -2
- package/dist/core/codex-usage.d.ts.map +1 -1
- package/dist/core/codex-usage.js +9 -4
- package/dist/core/codex-usage.js.map +1 -1
- package/dist/core/compaction/branch-summarization.d.ts +3 -1
- package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
- package/dist/core/compaction/branch-summarization.js +25 -10
- package/dist/core/compaction/branch-summarization.js.map +1 -1
- package/dist/core/compaction/compaction.d.ts +37 -3
- package/dist/core/compaction/compaction.d.ts.map +1 -1
- package/dist/core/compaction/compaction.js +274 -65
- package/dist/core/compaction/compaction.js.map +1 -1
- package/dist/core/compaction/utils.d.ts +19 -6
- package/dist/core/compaction/utils.d.ts.map +1 -1
- package/dist/core/compaction/utils.js +49 -11
- package/dist/core/compaction/utils.js.map +1 -1
- package/dist/core/exec.d.ts +9 -1
- package/dist/core/exec.d.ts.map +1 -1
- package/dist/core/exec.js +105 -61
- package/dist/core/exec.js.map +1 -1
- package/dist/core/export-html/template.css +9 -0
- package/dist/core/export-html/template.html +2 -0
- package/dist/core/export-html/template.js +200 -62
- package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
- package/dist/core/export-html/tool-renderer.js +3 -0
- package/dist/core/export-html/tool-renderer.js.map +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/extensions/loader.d.ts.map +1 -1
- package/dist/core/extensions/loader.js +7 -6
- package/dist/core/extensions/loader.js.map +1 -1
- package/dist/core/extensions/pi-ai-extension-view.d.ts +19 -0
- package/dist/core/extensions/pi-ai-extension-view.d.ts.map +1 -0
- package/dist/core/extensions/pi-ai-extension-view.js +22 -0
- package/dist/core/extensions/pi-ai-extension-view.js.map +1 -0
- package/dist/core/extensions/types.d.ts +27 -4
- package/dist/core/extensions/types.d.ts.map +1 -1
- package/dist/core/extensions/types.js.map +1 -1
- package/dist/core/extensions/virtual-modules.d.ts.map +1 -1
- package/dist/core/extensions/virtual-modules.js +8 -7
- package/dist/core/extensions/virtual-modules.js.map +1 -1
- package/dist/core/http-dispatcher.d.ts +7 -0
- package/dist/core/http-dispatcher.d.ts.map +1 -1
- package/dist/core/http-dispatcher.js +107 -0
- package/dist/core/http-dispatcher.js.map +1 -1
- package/dist/core/keybindings.d.ts +56 -0
- package/dist/core/keybindings.d.ts.map +1 -1
- package/dist/core/keybindings.js +14 -2
- package/dist/core/keybindings.js.map +1 -1
- package/dist/core/mcp-servers.d.ts +9 -4
- package/dist/core/mcp-servers.d.ts.map +1 -1
- package/dist/core/mcp-servers.js +15 -5
- package/dist/core/mcp-servers.js.map +1 -1
- package/dist/core/model-config.d.ts +1691 -2042
- package/dist/core/model-config.d.ts.map +1 -1
- package/dist/core/model-config.js +2 -3
- package/dist/core/model-config.js.map +1 -1
- package/dist/core/model-registry.d.ts +35 -4
- package/dist/core/model-registry.d.ts.map +1 -1
- package/dist/core/model-registry.js +70 -8
- package/dist/core/model-registry.js.map +1 -1
- package/dist/core/model-resolver.d.ts.map +1 -1
- package/dist/core/model-resolver.js +16 -10
- package/dist/core/model-resolver.js.map +1 -1
- package/dist/core/model-runtime.d.ts.map +1 -1
- package/dist/core/model-runtime.js +21 -17
- package/dist/core/model-runtime.js.map +1 -1
- package/dist/core/package-manager.d.ts +29 -0
- package/dist/core/package-manager.d.ts.map +1 -1
- package/dist/core/package-manager.js +311 -60
- package/dist/core/package-manager.js.map +1 -1
- package/dist/core/pi-ai-schemas.d.ts +164 -0
- package/dist/core/pi-ai-schemas.d.ts.map +1 -0
- package/dist/core/pi-ai-schemas.js +21 -0
- package/dist/core/pi-ai-schemas.js.map +1 -0
- package/dist/core/pi-manifest.d.ts +1 -0
- package/dist/core/pi-manifest.d.ts.map +1 -1
- package/dist/core/pi-manifest.js +4 -0
- package/dist/core/pi-manifest.js.map +1 -1
- package/dist/core/project-trust.js +1 -1
- package/dist/core/project-trust.js.map +1 -1
- package/dist/core/resource-loader.d.ts +4 -1
- package/dist/core/resource-loader.d.ts.map +1 -1
- package/dist/core/resource-loader.js +38 -23
- package/dist/core/resource-loader.js.map +1 -1
- package/dist/core/sdk.d.ts.map +1 -1
- package/dist/core/sdk.js +4 -1
- package/dist/core/sdk.js.map +1 -1
- package/dist/core/session-manager.d.ts +7 -0
- package/dist/core/session-manager.d.ts.map +1 -1
- package/dist/core/session-manager.js +66 -26
- package/dist/core/session-manager.js.map +1 -1
- package/dist/core/settings-defaults.d.ts +2 -0
- package/dist/core/settings-defaults.d.ts.map +1 -1
- package/dist/core/settings-defaults.js +2 -0
- package/dist/core/settings-defaults.js.map +1 -1
- package/dist/core/settings-manager.d.ts +19 -8
- package/dist/core/settings-manager.d.ts.map +1 -1
- package/dist/core/settings-manager.js +70 -16
- package/dist/core/settings-manager.js.map +1 -1
- package/dist/core/settings-schema.d.ts +15 -2
- package/dist/core/settings-schema.d.ts.map +1 -1
- package/dist/core/settings-schema.js +37 -3
- package/dist/core/settings-schema.js.map +1 -1
- package/dist/core/skills.d.ts.map +1 -1
- package/dist/core/skills.js +6 -14
- package/dist/core/skills.js.map +1 -1
- package/dist/core/slash-commands.js +2 -2
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/core/source-info.d.ts +9 -0
- package/dist/core/source-info.d.ts.map +1 -1
- package/dist/core/source-info.js +13 -0
- package/dist/core/source-info.js.map +1 -1
- package/dist/core/subscription-credits.d.ts +14 -0
- package/dist/core/subscription-credits.d.ts.map +1 -0
- package/dist/core/subscription-credits.js +10 -0
- package/dist/core/subscription-credits.js.map +1 -0
- package/dist/core/subscription-reset-status.d.ts +10 -0
- package/dist/core/subscription-reset-status.d.ts.map +1 -0
- package/dist/core/subscription-reset-status.js +2 -0
- package/dist/core/subscription-reset-status.js.map +1 -0
- package/dist/core/system-prompt.d.ts.map +1 -1
- package/dist/core/system-prompt.js +5 -6
- package/dist/core/system-prompt.js.map +1 -1
- package/dist/core/tools/bash.d.ts +2 -2
- package/dist/core/tools/bash.d.ts.map +1 -1
- package/dist/core/tools/bash.js.map +1 -1
- package/dist/core/tools/edit.d.ts +3 -3
- package/dist/core/tools/edit.d.ts.map +1 -1
- package/dist/core/tools/edit.js +2 -4
- package/dist/core/tools/edit.js.map +1 -1
- package/dist/core/tools/find.d.ts +2 -2
- package/dist/core/tools/find.d.ts.map +1 -1
- package/dist/core/tools/find.js.map +1 -1
- package/dist/core/tools/grep.d.ts +2 -2
- package/dist/core/tools/grep.d.ts.map +1 -1
- package/dist/core/tools/grep.js +7 -3
- package/dist/core/tools/grep.js.map +1 -1
- package/dist/core/tools/ls.d.ts +2 -2
- package/dist/core/tools/ls.d.ts.map +1 -1
- package/dist/core/tools/ls.js.map +1 -1
- package/dist/core/tools/read.d.ts +2 -2
- package/dist/core/tools/read.d.ts.map +1 -1
- package/dist/core/tools/read.js.map +1 -1
- package/dist/core/tools/render-utils.d.ts +4 -0
- package/dist/core/tools/render-utils.d.ts.map +1 -1
- package/dist/core/tools/render-utils.js +42 -12
- package/dist/core/tools/render-utils.js.map +1 -1
- package/dist/core/tools/renderers/edit.d.ts.map +1 -1
- package/dist/core/tools/renderers/edit.js +3 -3
- package/dist/core/tools/renderers/edit.js.map +1 -1
- package/dist/core/tools/renderers/write.d.ts.map +1 -1
- package/dist/core/tools/renderers/write.js +37 -29
- package/dist/core/tools/renderers/write.js.map +1 -1
- package/dist/core/tools/subagent.d.ts +9 -8
- package/dist/core/tools/subagent.d.ts.map +1 -1
- package/dist/core/tools/subagent.js +8 -5
- package/dist/core/tools/subagent.js.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts +11 -1
- package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
- package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
- package/dist/core/tools/write.d.ts +2 -2
- package/dist/core/tools/write.d.ts.map +1 -1
- package/dist/core/tools/write.js.map +1 -1
- package/dist/core/trust-manager.d.ts.map +1 -1
- package/dist/core/trust-manager.js +14 -8
- package/dist/core/trust-manager.js.map +1 -1
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +2 -0
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/extensions/codemode/renderer.d.ts.map +1 -1
- package/dist/extensions/codemode/renderer.js +17 -9
- package/dist/extensions/codemode/renderer.js.map +1 -1
- package/dist/extensions/codemode/tool.d.ts +2 -1
- package/dist/extensions/codemode/tool.d.ts.map +1 -1
- package/dist/extensions/codemode/tool.js +33 -8
- package/dist/extensions/codemode/tool.js.map +1 -1
- package/dist/extensions/llama/ui.d.ts.map +1 -1
- package/dist/extensions/llama/ui.js +16 -4
- package/dist/extensions/llama/ui.js.map +1 -1
- package/dist/extensions/mcp/cli.d.ts.map +1 -1
- package/dist/extensions/mcp/cli.js +34 -8
- package/dist/extensions/mcp/cli.js.map +1 -1
- package/dist/extensions/mcp/index.js +4 -3
- package/dist/extensions/mcp/index.js.map +1 -1
- package/dist/extensions/mcp/oauth.d.ts +1 -1
- package/dist/extensions/mcp/oauth.d.ts.map +1 -1
- package/dist/extensions/mcp/oauth.js +7 -3
- package/dist/extensions/mcp/oauth.js.map +1 -1
- package/dist/extensions/mcp/ui.d.ts +1 -0
- package/dist/extensions/mcp/ui.d.ts.map +1 -1
- package/dist/extensions/mcp/ui.js +56 -28
- package/dist/extensions/mcp/ui.js.map +1 -1
- package/dist/extensions/tool-search/tool.d.ts +21 -6
- package/dist/extensions/tool-search/tool.d.ts.map +1 -1
- package/dist/extensions/tool-search/tool.js +104 -36
- package/dist/extensions/tool-search/tool.js.map +1 -1
- package/dist/extensions/usage/confirmation.d.ts +40 -0
- package/dist/extensions/usage/confirmation.d.ts.map +1 -0
- package/dist/extensions/usage/confirmation.js +198 -0
- package/dist/extensions/usage/confirmation.js.map +1 -0
- package/dist/extensions/usage/index.d.ts +4 -4
- package/dist/extensions/usage/index.d.ts.map +1 -1
- package/dist/extensions/usage/index.js +352 -33
- package/dist/extensions/usage/index.js.map +1 -1
- package/dist/extensions/usage/overview.d.ts +8 -1
- package/dist/extensions/usage/overview.d.ts.map +1 -1
- package/dist/extensions/usage/overview.js +54 -11
- package/dist/extensions/usage/overview.js.map +1 -1
- package/dist/extensions/usage/popup.d.ts +37 -6
- package/dist/extensions/usage/popup.d.ts.map +1 -1
- package/dist/extensions/usage/popup.js +396 -45
- package/dist/extensions/usage/popup.js.map +1 -1
- package/dist/humain/bedrock-provider/vendor/index.bundle.mjs +564 -130
- package/dist/humain/node-provider.d.ts.map +1 -1
- package/dist/humain/node-provider.js +1 -0
- package/dist/humain/node-provider.js.map +1 -1
- package/dist/humain/web-access/host.d.ts +2 -1
- package/dist/humain/web-access/host.d.ts.map +1 -1
- package/dist/humain/web-access/host.js +1 -1
- package/dist/humain/web-access/host.js.map +1 -1
- package/dist/humain/web-access/vendor/brave-rate-limit.d.ts +2 -0
- package/dist/humain/web-access/vendor/brave-rate-limit.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/brave-rate-limit.js +2 -2
- package/dist/humain/web-access/vendor/brave-rate-limit.js.map +1 -1
- package/dist/humain/web-access/vendor/cloudflare-search.d.ts +5 -0
- package/dist/humain/web-access/vendor/cloudflare-search.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/cloudflare-search.js +230 -0
- package/dist/humain/web-access/vendor/cloudflare-search.js.map +1 -0
- package/dist/humain/web-access/vendor/curator-page.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/curator-page.js +18 -1
- package/dist/humain/web-access/vendor/curator-page.js.map +1 -1
- package/dist/humain/web-access/vendor/curator-server.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/curator-server.js +12 -0
- package/dist/humain/web-access/vendor/curator-server.js.map +1 -1
- package/dist/humain/web-access/vendor/duckduckgo-rate-limit.d.ts +33 -0
- package/dist/humain/web-access/vendor/duckduckgo-rate-limit.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/duckduckgo-rate-limit.js +84 -0
- package/dist/humain/web-access/vendor/duckduckgo-rate-limit.js.map +1 -0
- package/dist/humain/web-access/vendor/duckduckgo.d.ts +3 -0
- package/dist/humain/web-access/vendor/duckduckgo.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/duckduckgo.js +54 -49
- package/dist/humain/web-access/vendor/duckduckgo.js.map +1 -1
- package/dist/humain/web-access/vendor/exa.d.ts +8 -3
- package/dist/humain/web-access/vendor/exa.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/exa.js +129 -14
- package/dist/humain/web-access/vendor/exa.js.map +1 -1
- package/dist/humain/web-access/vendor/extract.d.ts +1 -1
- package/dist/humain/web-access/vendor/extract.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/extract.js +68 -10
- package/dist/humain/web-access/vendor/extract.js.map +1 -1
- package/dist/humain/web-access/vendor/fetch-params.d.ts +2 -1
- package/dist/humain/web-access/vendor/fetch-params.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/fetch-params.js +2 -2
- package/dist/humain/web-access/vendor/fetch-params.js.map +1 -1
- package/dist/humain/web-access/vendor/field-extract.d.ts +38 -0
- package/dist/humain/web-access/vendor/field-extract.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/field-extract.js +350 -0
- package/dist/humain/web-access/vendor/field-extract.js.map +1 -0
- package/dist/humain/web-access/vendor/gemini-search.d.ts +15 -4
- package/dist/humain/web-access/vendor/gemini-search.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/gemini-search.js +198 -16
- package/dist/humain/web-access/vendor/gemini-search.js.map +1 -1
- package/dist/humain/web-access/vendor/github-api.js +1 -1
- package/dist/humain/web-access/vendor/github-api.js.map +1 -1
- package/dist/humain/web-access/vendor/github-extract.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/github-extract.js +3 -2
- package/dist/humain/web-access/vendor/github-extract.js.map +1 -1
- package/dist/humain/web-access/vendor/index.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/index.js +137 -118
- package/dist/humain/web-access/vendor/index.js.map +1 -1
- package/dist/humain/web-access/vendor/mistral-search.js +1 -1
- package/dist/humain/web-access/vendor/mistral-search.js.map +1 -1
- package/dist/humain/web-access/vendor/ninerouter.d.ts +4 -0
- package/dist/humain/web-access/vendor/ninerouter.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/ninerouter.js +110 -0
- package/dist/humain/web-access/vendor/ninerouter.js.map +1 -0
- package/dist/humain/web-access/vendor/offtopic-judge.d.ts +27 -0
- package/dist/humain/web-access/vendor/offtopic-judge.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/offtopic-judge.js +61 -0
- package/dist/humain/web-access/vendor/offtopic-judge.js.map +1 -0
- package/dist/humain/web-access/vendor/openai-search.d.ts +1 -1
- package/dist/humain/web-access/vendor/openai-search.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/openai-search.js +39 -13
- package/dist/humain/web-access/vendor/openai-search.js.map +1 -1
- package/dist/humain/web-access/vendor/outcrawl.d.ts +4 -0
- package/dist/humain/web-access/vendor/outcrawl.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/outcrawl.js +196 -0
- package/dist/humain/web-access/vendor/outcrawl.js.map +1 -0
- package/dist/humain/web-access/vendor/page-query.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/page-query.js +13 -3
- package/dist/humain/web-access/vendor/page-query.js.map +1 -1
- package/dist/humain/web-access/vendor/pdf-extract.d.ts +1 -3
- package/dist/humain/web-access/vendor/pdf-extract.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/pdf-extract.js +0 -2
- package/dist/humain/web-access/vendor/pdf-extract.js.map +1 -1
- package/dist/humain/web-access/vendor/perplexity.d.ts +3 -0
- package/dist/humain/web-access/vendor/perplexity.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/perplexity.js.map +1 -1
- package/dist/humain/web-access/vendor/query-rewrite.d.ts +2 -2
- package/dist/humain/web-access/vendor/query-rewrite.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/query-rewrite.js +39 -13
- package/dist/humain/web-access/vendor/query-rewrite.js.map +1 -1
- package/dist/humain/web-access/vendor/searchapi.d.ts +4 -0
- package/dist/humain/web-access/vendor/searchapi.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/searchapi.js +195 -0
- package/dist/humain/web-access/vendor/searchapi.js.map +1 -0
- package/dist/humain/web-access/vendor/sofya.d.ts +4 -0
- package/dist/humain/web-access/vendor/sofya.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/sofya.js +193 -0
- package/dist/humain/web-access/vendor/sofya.js.map +1 -0
- package/dist/humain/web-access/vendor/source-check.d.ts +5 -1
- package/dist/humain/web-access/vendor/source-check.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/source-check.js +34 -16
- package/dist/humain/web-access/vendor/source-check.js.map +1 -1
- package/dist/humain/web-access/vendor/ssrf-protection.d.ts +7 -0
- package/dist/humain/web-access/vendor/ssrf-protection.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/ssrf-protection.js +24 -1
- package/dist/humain/web-access/vendor/ssrf-protection.js.map +1 -1
- package/dist/humain/web-access/vendor/summary-model-scope.d.ts +8 -3
- package/dist/humain/web-access/vendor/summary-model-scope.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/summary-model-scope.js +15 -1
- package/dist/humain/web-access/vendor/summary-model-scope.js.map +1 -1
- package/dist/humain/web-access/vendor/summary-review.d.ts +7 -2
- package/dist/humain/web-access/vendor/summary-review.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/summary-review.js +32 -28
- package/dist/humain/web-access/vendor/summary-review.js.map +1 -1
- package/dist/humain/web-access/vendor/tabstack.d.ts +6 -0
- package/dist/humain/web-access/vendor/tabstack.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/tabstack.js +236 -0
- package/dist/humain/web-access/vendor/tabstack.js.map +1 -0
- package/dist/humain/web-access/vendor/tool-arguments.js +1 -1
- package/dist/humain/web-access/vendor/tool-arguments.js.map +1 -1
- package/dist/humain/web-access/vendor/upgrade-notice.d.ts +8 -0
- package/dist/humain/web-access/vendor/upgrade-notice.d.ts.map +1 -0
- package/dist/humain/web-access/vendor/upgrade-notice.js +46 -0
- package/dist/humain/web-access/vendor/upgrade-notice.js.map +1 -0
- package/dist/humain/web-access/vendor/utils.d.ts +9 -0
- package/dist/humain/web-access/vendor/utils.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/utils.js +113 -27
- package/dist/humain/web-access/vendor/utils.js.map +1 -1
- package/dist/humain/web-access/vendor/web-tool-contract.d.ts +4 -0
- package/dist/humain/web-access/vendor/web-tool-contract.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/web-tool-contract.js.map +1 -1
- package/dist/humain/web-access/vendor/web-tool-core.d.ts +17 -1
- package/dist/humain/web-access/vendor/web-tool-core.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/web-tool-core.js +99 -22
- package/dist/humain/web-access/vendor/web-tool-core.js.map +1 -1
- package/dist/humain/web-access/vendor/xai-search.d.ts +1 -1
- package/dist/humain/web-access/vendor/xai-search.d.ts.map +1 -1
- package/dist/humain/web-access/vendor/xai-search.js +6 -5
- package/dist/humain/web-access/vendor/xai-search.js.map +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/main.d.ts.map +1 -1
- package/dist/main.js +20 -9
- package/dist/main.js.map +1 -1
- package/dist/modes/interactive/components/assistant-code-block.d.ts +34 -0
- package/dist/modes/interactive/components/assistant-code-block.d.ts.map +1 -0
- package/dist/modes/interactive/components/assistant-code-block.js +160 -0
- package/dist/modes/interactive/components/assistant-code-block.js.map +1 -0
- package/dist/modes/interactive/components/assistant-message.d.ts +31 -10
- package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/assistant-message.js +276 -73
- package/dist/modes/interactive/components/assistant-message.js.map +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/compaction-summary-message.js +2 -1
- package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
- package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/config-selector.js +4 -17
- package/dist/modes/interactive/components/config-selector.js.map +1 -1
- package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-editor.js +7 -0
- package/dist/modes/interactive/components/custom-editor.js.map +1 -1
- package/dist/modes/interactive/components/custom-entry.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-entry.js +2 -1
- package/dist/modes/interactive/components/custom-entry.js.map +1 -1
- package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/custom-message.js +2 -1
- package/dist/modes/interactive/components/custom-message.js.map +1 -1
- package/dist/modes/interactive/components/diff.d.ts.map +1 -1
- package/dist/modes/interactive/components/diff.js +3 -1
- package/dist/modes/interactive/components/diff.js.map +1 -1
- package/dist/modes/interactive/components/extension-editor.d.ts +2 -0
- package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
- package/dist/modes/interactive/components/extension-editor.js +4 -0
- package/dist/modes/interactive/components/extension-editor.js.map +1 -1
- package/dist/modes/interactive/components/footer.d.ts +4 -1
- package/dist/modes/interactive/components/footer.d.ts.map +1 -1
- package/dist/modes/interactive/components/footer.js +6 -5
- package/dist/modes/interactive/components/footer.js.map +1 -1
- package/dist/modes/interactive/components/login-dialog.d.ts +5 -0
- package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
- package/dist/modes/interactive/components/login-dialog.js +107 -11
- package/dist/modes/interactive/components/login-dialog.js.map +1 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts +2 -1
- package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -1
- package/dist/modes/interactive/components/markdown-transform.js +3 -2
- package/dist/modes/interactive/components/markdown-transform.js.map +1 -1
- package/dist/modes/interactive/components/mermaid.d.ts.map +1 -1
- package/dist/modes/interactive/components/mermaid.js +18 -6
- package/dist/modes/interactive/components/mermaid.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts +1 -0
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +17 -6
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.d.ts +1 -0
- package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/oauth-selector.js +13 -4
- package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.d.ts +1 -0
- package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/scoped-models-selector.js +14 -3
- package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
- package/dist/modes/interactive/components/session-selector-search.d.ts +4 -0
- package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector-search.js +86 -22
- package/dist/modes/interactive/components/session-selector-search.js.map +1 -1
- package/dist/modes/interactive/components/session-selector.d.ts +2 -1
- package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/session-selector.js +16 -24
- package/dist/modes/interactive/components/session-selector.js.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -1
- package/dist/modes/interactive/components/settings-submenu.js +2 -0
- package/dist/modes/interactive/components/settings-submenu.js.map +1 -1
- package/dist/modes/interactive/components/tool-execution.d.ts +2 -0
- package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
- package/dist/modes/interactive/components/tool-execution.js +15 -5
- package/dist/modes/interactive/components/tool-execution.js.map +1 -1
- package/dist/modes/interactive/components/tree-selector.d.ts +1 -0
- package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/tree-selector.js +5 -6
- package/dist/modes/interactive/components/tree-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.d.ts +1 -0
- package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message-selector.js +9 -1
- package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
- package/dist/modes/interactive/components/user-message.d.ts +4 -3
- package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
- package/dist/modes/interactive/components/user-message.js +20 -18
- package/dist/modes/interactive/components/user-message.js.map +1 -1
- package/dist/modes/interactive/external-editor.d.ts +1 -0
- package/dist/modes/interactive/external-editor.d.ts.map +1 -1
- package/dist/modes/interactive/external-editor.js +16 -4
- package/dist/modes/interactive/external-editor.js.map +1 -1
- package/dist/modes/interactive/interactive-mode.d.ts +6 -0
- package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-mode.js +259 -83
- package/dist/modes/interactive/interactive-mode.js.map +1 -1
- package/dist/modes/interactive/model-search.d.ts +10 -0
- package/dist/modes/interactive/model-search.d.ts.map +1 -1
- package/dist/modes/interactive/model-search.js +21 -0
- package/dist/modes/interactive/model-search.js.map +1 -1
- package/dist/modes/interactive/oauth-account-format.d.ts +10 -1
- package/dist/modes/interactive/oauth-account-format.d.ts.map +1 -1
- package/dist/modes/interactive/oauth-account-format.js +42 -0
- package/dist/modes/interactive/oauth-account-format.js.map +1 -1
- package/dist/modes/interactive/theme/theme.d.ts +10 -0
- package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
- package/dist/modes/interactive/theme/theme.js +28 -24
- package/dist/modes/interactive/theme/theme.js.map +1 -1
- package/dist/modes/print-mode.d.ts.map +1 -1
- package/dist/modes/print-mode.js +3 -2
- package/dist/modes/print-mode.js.map +1 -1
- package/dist/package-manager-cli.d.ts.map +1 -1
- package/dist/package-manager-cli.js +55 -4
- package/dist/package-manager-cli.js.map +1 -1
- package/dist/utils/ansi.d.ts.map +1 -1
- package/dist/utils/ansi.js +5 -2
- package/dist/utils/ansi.js.map +1 -1
- package/dist/utils/clipboard-command.d.ts.map +1 -1
- package/dist/utils/clipboard-command.js +4 -0
- package/dist/utils/clipboard-command.js.map +1 -1
- package/dist/utils/clipboard-image.d.ts +8 -0
- package/dist/utils/clipboard-image.d.ts.map +1 -1
- package/dist/utils/clipboard-image.js +31 -1
- package/dist/utils/clipboard-image.js.map +1 -1
- package/dist/utils/git.d.ts +1 -1
- package/dist/utils/git.d.ts.map +1 -1
- package/dist/utils/git.js.map +1 -1
- package/dist/utils/image-resize-core.d.ts.map +1 -1
- package/dist/utils/image-resize-core.js +5 -3
- package/dist/utils/image-resize-core.js.map +1 -1
- package/dist/utils/open-browser.d.ts.map +1 -1
- package/dist/utils/open-browser.js +96 -6
- package/dist/utils/open-browser.js.map +1 -1
- package/dist/utils/paths.d.ts +17 -0
- package/dist/utils/paths.d.ts.map +1 -1
- package/dist/utils/paths.js +42 -1
- package/dist/utils/paths.js.map +1 -1
- package/dist/utils/shell.d.ts +2 -1
- package/dist/utils/shell.d.ts.map +1 -1
- package/dist/utils/shell.js +12 -2
- package/dist/utils/shell.js.map +1 -1
- package/dist/utils/syntax-highlight.d.ts +5 -0
- package/dist/utils/syntax-highlight.d.ts.map +1 -1
- package/dist/utils/syntax-highlight.js +156 -11
- package/dist/utils/syntax-highlight.js.map +1 -1
- package/dist/utils/tools-manager.d.ts.map +1 -1
- package/dist/utils/tools-manager.js +30 -35
- package/dist/utils/tools-manager.js.map +1 -1
- package/docs/cli.md +22 -12
- package/docs/compaction.md +32 -8
- package/docs/coordination.md +2 -0
- package/docs/custom-provider.md +4 -2
- package/docs/environment-variables.md +2 -0
- package/docs/extensions.md +3169 -229
- package/docs/flow.md +2 -0
- package/docs/keybindings.md +24 -2
- package/docs/llama-cpp.md +30 -19
- package/docs/mcp.md +4 -2
- package/docs/message-types.md +7 -7
- package/docs/packages.md +27 -1
- package/docs/sessions.md +11 -3
- package/docs/settings.md +21 -9
- package/docs/slash-commands.md +51 -11
- package/docs/terminal-setup.md +3 -1
- package/docs/tmux.md +6 -0
- package/docs/tui.md +3 -1
- package/docs/windows.md +27 -0
- package/examples/extensions/README.md +2 -1
- package/examples/extensions/custom-provider-anthropic/index.ts +27 -31
- package/examples/extensions/custom-provider-anthropic/package-lock.json +7 -7
- package/examples/extensions/custom-provider-anthropic/package.json +2 -2
- package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
- package/examples/extensions/debug-provider.ts +2 -2
- package/examples/extensions/gondolin/package-lock.json +14 -24
- package/examples/extensions/gondolin/package.json +2 -2
- package/examples/extensions/preset.ts +2 -0
- package/examples/extensions/reload-runtime.ts +17 -5
- package/examples/extensions/todo.ts +7 -0
- package/examples/extensions/tools.ts +2 -0
- package/examples/extensions/with-deps/package-lock.json +2 -2
- package/examples/extensions/with-deps/package.json +1 -1
- package/examples/tsconfig.json +252 -0
- package/npm-shrinkwrap.json +289 -277
- package/package.json +29 -29
- package/schemas/keybindings.schema.json +28 -0
- package/schemas/models.schema.json +36 -36
- package/schemas/settings.schema.json +49 -0
- package/src/humain/ponytail/UPSTREAM.md +16 -2
- package/src/humain/ponytail/upstream.json +4 -4
- package/src/humain/web-access/UPSTREAM.md +48 -1
- package/src/humain/web-access/upstream.json +9 -6
- package/src/humain/web-access/vendor/CHANGELOG.md +1223 -0
- package/dist/bundle/chunks/anthropic-messages-ZP5KUK52.js +0 -67
- package/dist/bundle/chunks/azure-openai-responses-QJFYQ3DF.js +0 -15
- package/dist/bundle/chunks/chunk-2GCMACT4.js +0 -1956
- package/dist/bundle/chunks/chunk-AO6FF5JL.js +0 -21
- package/dist/bundle/chunks/chunk-EY3LZOUP.js +0 -1963
- package/dist/bundle/chunks/chunk-M74U5X4S.js +0 -119
- package/dist/bundle/chunks/chunk-N7CQ3UV3.js +0 -80
- package/dist/bundle/chunks/chunk-OR25QDSS.js +0 -365
- package/dist/bundle/chunks/chunk-PH7UP57J.js +0 -6
- package/dist/bundle/chunks/chunk-QW6PTCAB.js +0 -10
- package/dist/bundle/chunks/chunk-ROZV2IYD.js +0 -125
- package/dist/bundle/chunks/chunk-YFOLLX5D.js +0 -23
- package/dist/bundle/chunks/chunk-ZR4GF4WU.js +0 -54
- package/dist/bundle/chunks/compat-CJBWWYHE.js +0 -13
- package/dist/bundle/chunks/dist-IBUWEKEE.js +0 -24
- package/dist/bundle/chunks/dist-YFMJEHPH.js +0 -8
- package/dist/bundle/chunks/google-generative-ai-HVPCGIZ6.js +0 -21
- package/dist/bundle/chunks/google-vertex-UM5MAALA.js +0 -25
- package/dist/bundle/chunks/host-ZHEL5XQW.js +0 -2
- package/dist/bundle/chunks/mistral-conversations-AH72RLXK.js +0 -44
- package/dist/bundle/chunks/openai-codex-responses-L366637C.js +0 -98
- package/dist/bundle/chunks/openai-completions-ZP62QXJX.js +0 -83
- package/dist/bundle/chunks/openai-responses-DXUGSUTN.js +0 -26
- package/dist/bundle/chunks/pi-messages-MOQQDZBK.js +0 -23
- package/dist/bundle/chunks/virtual-modules-5D6QIJPN.js +0 -5
- package/examples/extensions/sandbox/index.ts +0 -321
- package/examples/extensions/sandbox/package-lock.json +0 -66
- package/examples/extensions/sandbox/package.json +0 -19
|
@@ -1,100 +1,114 @@
|
|
|
1
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-
|
|
2
|
+
import{source_default}from"./chunk-XQRYOCHA.js";import{require_core}from"./chunk-DNGJMRJW.js";import{getCustomThemesDir,getThemesDir,stripBom}from"./chunk-IADQJFNH.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
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
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
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
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
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
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
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
(?:\\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
|
-
hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){let result2="",width2=0;for(let{segment}of
|
|
14
|
-
",width+=3,i++;continue}let end=i;for(;end<text.length&&text[end]!==" "&&!extractAnsiCode(text,end);)end++;for(let{segment}of
|
|
15
|
-
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
|
|
16
|
-
if(
|
|
17
|
-
width+=eastAsianWidth(
|
|
18
|
-
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
|
|
19
|
-
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}
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
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){
|
|
26
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.
|
|
27
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.
|
|
28
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(){
|
|
29
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(
|
|
30
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="";
|
|
31
|
-
return this.underline&&(result+="\x1B[24m"),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),
|
|
32
|
-
for(let{segment}of
|
|
33
|
-
|
|
34
|
-
|
|
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&¤tKind!==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(`
|
|
35
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){
|
|
36
|
-
if(!line)return[""];if(visibleWidth(line)<=width)return[line];let wrapped=[],tracker=new AnsiCodeTracker,tokens=splitIntoTokensWithAnsi(line),currentLine="",currentVisibleLength=0;for(let
|
|
37
|
-
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}
|
|
38
|
-
token
|
|
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&¤tVisibleLength>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){
|
|
39
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){
|
|
40
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(
|
|
41
|
-
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
|
|
42
|
-
keepContiguousPrefix=!0,overflowed=!1,exhaustedInput=!1,hasAnsi=text.includes("\x1B"),hasTabs=text.includes(" ");if(!hasAnsi&&!hasTabs){for(let{segment}of
|
|
43
|
-
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]!==" "
|
|
44
|
-
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(
|
|
45
|
-
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&¤tCol<endCol?(result+=
|
|
46
|
-
line,textEnd);)textEnd++;for(let{segment}of
|
|
47
|
-
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+=
|
|
48
|
-
line,textEnd);)textEnd++;for(let{segment}of
|
|
49
|
-
beforeEnd:currentCol>=afterEnd)break}if(i=textEnd,afterLen<=0?currentCol>=beforeEnd:currentCol>=afterEnd)break}return{before,beforeWidth,after,afterWidth}}var multiply=(m,[x2,
|
|
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&¤tCol<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&¤tCol<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&¤tCol<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&¤tCol+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,
|
|
50
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,
|
|
51
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(
|
|
52
|
-
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,
|
|
53
|
-
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),
|
|
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(
|
|
54
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(
|
|
55
|
-
row=>{let
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
freeze({kind:"rgb",r,g,b})}function oklchColor(l,
|
|
60
|
-
"i"),OKHSL_PATTERN=new RegExp(`^okhsl\\(\\s*(${NUMBER_PATTERN})(?:deg)?\\s+(${NUMBER_PATTERN})(%)?\\s+(${NUMBER_PATTERN})(%)?\\s*\\)$`,"i");function okhslColor(
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
g:
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
function
|
|
69
|
-
{r:
|
|
70
|
-
|
|
71
|
-
options.
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
[
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
"\
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
codepoint=
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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===`
|
|
98
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===`
|
|
99
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===
|
|
100
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(
|
|
@@ -105,21 +119,21 @@ data,FUNCTIONAL_CODEPOINTS.pageDown,0):matchesLegacyModifierSequence(data,"pageD
|
|
|
105
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.
|
|
106
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&&
|
|
107
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"\
|
|
108
|
-
f1":case"f2":case"f3":case"f4":case"f5":case"f6":case"f7":case"f8":case"f9":case"f10":case"f11":case"f12":return modifier
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
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=
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
keyName,modifier)}function parseKey(data){let kitty=parseKittySequence(data);if(kitty){let logicalShiftedSymbol=getLogicalShiftedSymbolCandidate(kitty.shiftedKey,kitty.modifier,SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.
|
|
115
|
-
modifier,SHIFTED_SYMBOL_KEYS);return formatParsedKey(logicalShiftedSymbol?.codepoint??modifyOtherKeys.codepoint,logicalShiftedSymbol?.modifier??modifyOtherKeys.modifier)}if(_kittyProtocolActive&&(data==="\x1B\r"||data===`
|
|
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===`
|
|
116
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===`
|
|
117
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&&
|
|
118
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"||
|
|
119
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);
|
|
120
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),
|
|
121
|
-
effectiveCodepoint=normalizeKittyFunctionalCodepoint(effectiveCodepoint),!(!Number.isFinite(effectiveCodepoint)||effectiveCodepoint<32))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.
|
|
122
|
-
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:"\
|
|
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:"\
|
|
123
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\
|
|
124
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\
|
|
125
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\
|
|
@@ -131,156 +145,169 @@ p":{defaultKeys:"ctrl+home",description:"Scroll viewport to top"},"tui.altScreen
|
|
|
131
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.
|
|
132
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.
|
|
133
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(
|
|
134
|
-
TUI_KEYBINDINGS)),globalKeybindings}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:()=>
|
|
135
|
-
SelectList:()=>SelectList,SettingsList:()=>SettingsList,Spacer:()=>Spacer,StdinBuffer:()=>StdinBuffer,TUI_KEYBINDINGS:()=>TUI_KEYBINDINGS,Text:()=>Text,TruncatedText:()=>TruncatedText,TuiAltScreen:()=>TuiAltScreen,TuiMainScreen:()=>TuiMainScreen,VStack:()=>VStack,allocateImageId:()=>allocateImageId,backgroundAnsi:()=>backgroundAnsi,calculateImageRows:()=>calculateImageRows,colorToHex:()=>colorToHex,colorToOkhsl:()=>colorToOkhsl,colorToOklch:()=>colorToOklch,
|
|
136
|
-
decodeKittyPrintable:()=>decodeKittyPrintable,deleteAllKittyImages:()=>deleteAllKittyImages,deleteKittyImage:()=>deleteKittyImage,detectCapabilities:()=>detectCapabilities,encodeITerm2:()=>encodeITerm2,encodeKitty:()=>encodeKitty,foregroundAnsi:()=>foregroundAnsi,formatProgramStatus:()=>formatProgramStatus,fuzzyFilter:()=>fuzzyFilter,fuzzyMatch:()=>fuzzyMatch,getCapabilities:()=>getCapabilities,getCellDimensions:()=>getCellDimensions,
|
|
137
|
-
getJpegDimensions:()=>getJpegDimensions,getKeybindings:()=>getKeybindings,getNativeClipboard:()=>getNativeClipboard,getOsc8LinkAtColumn:()=>getOsc8LinkAtColumn,getPngDimensions:()=>getPngDimensions,getTerminalColorMode:()=>getTerminalColorMode,getWebpDimensions:()=>getWebpDimensions,hyperlink:()=>hyperlink,imageFallback:()=>imageFallback,indexedColor:()=>indexedColor,invalidateRenderedMarkdown:()=>invalidateRenderedMarkdown,
|
|
138
|
-
isKeyRelease:()=>isKeyRelease,isKeyRepeat:()=>isKeyRepeat,isKittyProtocolActive:()=>isKittyProtocolActive,isStableRender:()=>isStableRender,isViewportTUI:()=>isViewportTUI,markLiveRender:()=>markLiveRender,markReportsChanges:()=>markReportsChanges,markStableRender:()=>markStableRender,matchesKey:()=>matchesKey,mixColors:()=>mixColors,okhslColor:()=>okhslColor,oklabToOkhslLightness:()=>oklabToOkhslLightness,
|
|
139
|
-
parseKey:()=>parseKey,parseTerminalColorSchemeReport:()=>parseTerminalColorSchemeReport,renderChildLines:()=>renderChildLines,renderFakeCursor:()=>renderFakeCursor,renderImage:()=>renderImage,renderLatex:()=>renderLatex,renderLiveLines:()=>renderLiveLines,renderSharedLines:()=>renderSharedLines,
|
|
140
|
-
|
|
141
|
-
truncateToWidth:()=>truncateToWidth,visibleWidth:()=>visibleWidth,wrapTextWithAnsi:()=>wrapTextWithAnsi});function
|
|
142
|
-
var
|
|
143
|
-
blockquoteSetextReplace:/\n {0,3}((?:=+|-+) *)(?=\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\[[ xX]\] +\S/,listReplaceTask:/^\[[ xX]\] +/,listTaskCheckbox:/\[[ xX]\]/,anyLine:/\n.*\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\||\| *$/g,tableRowBlankLine:/\n[ \t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,
|
|
144
|
-
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,
|
|
145
|
-
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(
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|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
|
|
151
|
-
|pre|style|textarea)(
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
heading:/^(#{1,6})(.*)(?:\n+|$)/,fences:
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
_)(?=
|
|
163
|
-
/notPunctSpace/g,
|
|
164
|
-
"(
|
|
165
|
-
|
|
166
|
-
replace("
|
|
167
|
-
|
|
168
|
-
url:
|
|
169
|
-
replace("protocol",
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
`)
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
`)
|
|
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={"&":"&","<":"<",">":">",'"':""","'":"'"},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"&";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?"&":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],`
|
|
181
200
|
`).split(`
|
|
182
|
-
`),
|
|
183
|
-
`),
|
|
184
|
-
$1`).replace(this.rules.other.blockquoteSetextReplace2,"");
|
|
185
|
-
${
|
|
186
|
-
${
|
|
187
|
-
`),
|
|
188
|
-
`+
|
|
189
|
-
`).length:0,
|
|
190
|
-
${
|
|
191
|
-
`)}`),r=r.substring(0,r.length-
|
|
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+`
|
|
192
211
|
`+n.join(`
|
|
193
|
-
`),
|
|
194
|
-
`)
|
|
195
|
-
`
|
|
196
|
-
`,
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
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],`
|
|
209
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)===`
|
|
210
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.
|
|
211
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.
|
|
212
|
-
options.pedantic&&
|
|
213
|
-
exec(
|
|
214
|
-
options.pedantic&&
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
let
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
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(`
|
|
224
249
|
`)?"":`
|
|
225
|
-
`)+r.raw,
|
|
226
|
-
`+r.text,this.inlineQueue.at(-1).src=
|
|
227
|
-
length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let
|
|
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(`
|
|
228
253
|
`)?"":`
|
|
229
|
-
`)+r.raw,
|
|
230
|
-
`+r.raw,this.inlineQueue.at(-1).src=
|
|
231
|
-
|
|
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(`
|
|
232
257
|
`)?"":`
|
|
233
|
-
`)+r.raw,
|
|
234
|
-
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=
|
|
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(`
|
|
235
260
|
`)?"":`
|
|
236
|
-
`)+r.raw,
|
|
237
|
-
`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=
|
|
238
|
-
r=
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
"")+`
|
|
245
|
-
`:"";return
|
|
246
|
-
`:"<pre><code>"+(n?r:
|
|
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>
|
|
247
272
|
`}blockquote({tokens:e}){return`<blockquote>
|
|
248
273
|
${this.parser.parse(e)}</blockquote>
|
|
249
274
|
`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
250
275
|
`}hr(e){return`<hr>
|
|
251
|
-
`}list(e){let t=e.ordered,n=e.start,
|
|
252
|
-
`+
|
|
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+`>
|
|
253
278
|
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
254
279
|
`}checkbox({checked:e}){return"<input "+(e?'checked="" ':"")+'disabled="" type="checkbox"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
255
|
-
`}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
|
|
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>
|
|
256
281
|
<thead>
|
|
257
282
|
`+t+`</thead>
|
|
258
|
-
`+
|
|
283
|
+
`+s+`</table>
|
|
259
284
|
`}tablerow({text:e}){return`<tr>
|
|
260
285
|
${e}</tr>
|
|
261
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}>
|
|
262
|
-
`}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>${
|
|
263
|
-
text:n,tokens:
|
|
264
|
-
text:e}){return
|
|
265
|
-
options.extensions?.renderers?.[
|
|
266
|
-
r);break}case"
|
|
267
|
-
renderer){this.renderer.parser=this;let n="";for(let
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
parseMarkdown(!1);Parser=
|
|
271
|
-
type].forEach(o=>{let
|
|
272
|
-
this,
|
|
273
|
-
extensions=t),n.renderer){let r=this.defaults.renderer||new
|
|
274
|
-
|
|
275
|
-
call(r,d)})();let
|
|
276
|
-
this}lexer(e,t){return
|
|
277
|
-
"string")return
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
lastMatchIndex===i-1?(consecutiveMatches++,score-=consecutiveMatches*5):(consecutiveMatches=0,lastMatchIndex>=0&&(score+=(i-lastMatchIndex-1)*2)),
|
|
282
|
-
|
|
283
|
-
|
|
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.
|
|
284
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){
|
|
285
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.
|
|
286
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}:
|
|
@@ -322,98 +349,101 @@ if("list"in first)return fdAbort.abort(),this.filterFdList(index,first.list,fdQu
|
|
|
322
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.
|
|
323
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(
|
|
324
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]||
|
|
325
|
-
"").slice(0,cursorCol);return!(textBeforeCursor.trim().startsWith("/")&&!textBeforeCursor.trim().includes(" "))}};
|
|
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)+$/;
|
|
326
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.
|
|
327
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)
|
|
328
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!==
|
|
329
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(
|
|
330
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){
|
|
331
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")?
|
|
332
|
-
{images:null,trueColor:hasTrueColorHint,hyperlinks:!1}:termProgram==="herdr"?{images:"kitty",trueColor:hasTrueColorHint,hyperlinks:!0}:termProgram==="rex"?{images:"kitty",trueColor:!0,hyperlinks:!0}:process.env.
|
|
333
|
-
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==="
|
|
334
|
-
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),
|
|
335
|
-
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!==
|
|
336
|
-
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.
|
|
337
|
-
|
|
338
|
-
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&¶ms.push("C=1"),options.columns&¶ms.push(`c=${options.columns}`),options.rows&¶ms.push(`r=${options.
|
|
339
|
-
|
|
340
|
-
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&¶ms.push(`width=${options.width}`),options.height!==void 0&¶ms.push(`height=${options.height}`),options.name){let nameBase64=Buffer.from(options.name).
|
|
341
|
-
|
|
342
|
-
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
|
|
343
|
-
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(
|
|
344
|
-
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){
|
|
345
|
-
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.
|
|
346
|
-
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.
|
|
347
|
-
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),
|
|
348
|
-
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(
|
|
349
|
-
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}
|
|
350
|
-
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/
|
|
351
|
-
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.
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
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){
|
|
357
|
-
if(!caps.images)return null;let maxWidth=options.maxWidthCells??80,size=calculateImageCellSize(imageDimensions,maxWidth,options.maxHeightCells,getCellDimensions(),caps.images==="kitty");return caps.
|
|
358
|
-
moveCursor}),columns:size.columns,rows:size.rows,imageId:options.imageId}):caps.images==="iterm2"?{sequence:encodeITerm2(base64Data,{width:size.columns,height:"auto",preserveAspectRatio:options.
|
|
359
|
-
|
|
360
|
-
|
|
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&¶ms.push("C=1"),options.columns&¶ms.push(`c=${options.columns}`),options.rows&¶ms.push(`r=${options.
|
|
366
|
+
rows}`),options.imageId&¶ms.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&¶ms.push(`width=${options.width}`),options.height!==void 0&¶ms.push(`height=${options.height}`),options.name){let nameBase64=Buffer.from(options.name).
|
|
368
|
+
toString("base64");params.push(`name=${nameBase64}`)}return options.preserveAspectRatio===!1&¶ms.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&®isterKittyImageMetadata({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$/;
|
|
361
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)}
|
|
362
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<
|
|
363
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;
|
|
364
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.
|
|
365
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)));
|
|
366
|
-
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
|
|
367
|
-
return
|
|
368
|
-
component
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
before.
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
return
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
this.requestRender()
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
this.
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
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&¬ifyOwner(owner,component)}else{let owner=owners.deref();owner!==void 0&¬ifyOwner(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){
|
|
417
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.
|
|
418
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,
|
|
419
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,
|
|
@@ -431,46 +461,46 @@ this.rendered=void 0,reportRenderChange(this)}invalidate(){this.invalidateCache(
|
|
|
431
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(
|
|
432
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?.
|
|
433
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.
|
|
434
|
-
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){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(
|
|
435
|
-
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(
|
|
436
|
-
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);
|
|
437
|
-
" ".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,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,
|
|
438
|
-
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){
|
|
439
|
-
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()},this.intervalMs))}getRenderedIndicator(){
|
|
440
|
-
renderIndicatorVerbatim?frame:this.spinnerColorFn(frame)}updateDisplay(){let renderedFrame=this.getRenderedIndicator(),indicator=renderedFrame.length>0?`${renderedFrame} `:"";this.setText(`${indicator}${this.messageColorFn(this.message)}`),this.ui&&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}};
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
next.value.segment)
|
|
444
|
-
|
|
445
|
-
this.filteredItems=this.
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
next
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
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&¤tWidth-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&¤tWidth-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=[
|
|
470
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(
|
|
471
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.
|
|
472
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(
|
|
473
|
-
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"?
|
|
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){
|
|
474
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)?
|
|
475
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=
|
|
476
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.
|
|
@@ -491,12 +521,12 @@ if(!visualLine)return{handled:!0,focus:!0};let logicalLine=this.state.lines[visu
|
|
|
491
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(),
|
|
492
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(
|
|
493
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&&
|
|
494
|
-
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")){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.
|
|
495
|
-
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.
|
|
496
|
-
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.
|
|
497
|
-
"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
|
|
498
|
-
|
|
499
|
-
|
|
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===`
|
|
500
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&¤tLine[this.state.cursorCol-1]==="\\"){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(kb.matches(data,"tui.editor.cursorUp")){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||
|
|
501
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(
|
|
502
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){
|
|
@@ -564,38 +594,38 @@ if(!this.autocompleteProvider)return;let suggestions=await this.autocompleteProv
|
|
|
564
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?"\
|
|
565
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.
|
|
566
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=
|
|
567
|
-
""}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
|
|
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(
|
|
568
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);
|
|
569
|
-
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){
|
|
570
|
-
return Math.max(min,Math.min(max,Math.max(0,Math.floor(size))))}function distribute(sizes,entries,amount,mode){let remaining=amount;for(;remaining>0;){let
|
|
571
|
-
shrink??1)*Math.max(1,sizes[index])
|
|
572
|
-
delta)}if(distributed===0)return}}function allocateStackSizes(entries,intrinsicSizes,availableSize,gap){let sizes=entries.
|
|
573
|
-
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.
|
|
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.
|
|
574
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||
|
|
575
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){
|
|
576
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(),
|
|
577
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.
|
|
578
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(
|
|
579
|
-
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
|
|
580
|
-
|
|
581
|
-
|
|
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===`
|
|
582
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\
|
|
583
|
-
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=[...
|
|
584
|
-
|
|
585
|
-
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.
|
|
586
|
-
currentColumn=0;this.cursor=this.value.length;for(let grapheme of
|
|
587
|
-
this.cursor+=char.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let beforeCursor=this.value.slice(0,this.cursor),graphemes=[...
|
|
588
|
-
let afterCursor=this.value.slice(this.cursor),firstGrapheme=[...
|
|
589
|
-
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();
|
|
590
|
-
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.
|
|
591
|
-
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()||"";
|
|
592
|
-
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(){
|
|
593
|
-
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){
|
|
594
|
-
mask?[...
|
|
595
|
-
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);
|
|
596
|
-
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
|
|
597
|
-
startCol),!0).length}else visibleText="",cursorDisplay=0}let cursorGrapheme=[...
|
|
598
|
-
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\
|
|
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\
|
|
599
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(
|
|
600
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){
|
|
601
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})|(?!\
|
|
@@ -671,72 +701,111 @@ cell=>this.renderNested(cell,!1).trim())).filter(row=>row.some(Boolean)),columnC
|
|
|
671
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&&
|
|
672
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.
|
|
673
703
|
slice(indentation).trimEnd()).join(`
|
|
674
|
-
`).trimEnd().replaceAll(PROTECTED_SPACE," ")}var STRICT_STRIKETHROUGH_REGEX=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/,
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
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
|
+
`
|
|
678
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(`
|
|
679
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|$)/.
|
|
680
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])&&
|
|
681
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(`
|
|
682
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(
|
|
683
716
|
token.tokens??[]);return}if(token?.type!=="code")return;let marker=/^(`{3,}|~{3,})/.exec(token.raw)?.[1],lastLine=token.raw.slice(token.raw.lastIndexOf(`
|
|
684
|
-
`)+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=new
|
|
685
|
-
inRawBlock?2:0)|(state.linkEmitted?4:0)}var InlineMemoLexer=class extends
|
|
686
|
-
(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=
|
|
687
|
-
memos=!0;function lexTokens(source2){return memos&&markdownCaching?new InlineMemoLexer(
|
|
688
|
-
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(
|
|
689
|
-
|
|
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(`
|
|
690
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(
|
|
691
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++),
|
|
692
|
-
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=
|
|
693
|
-
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||
|
|
694
|
-
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=
|
|
695
|
-
LEXED_MARKDOWN_KEPT&&lexedMarkdown.shift(),tokens}var textsWithoutTabs=[],TEXTS_WITHOUT_TABS_KEPT=4;function replaceTabs(text){let none=()=>{};if(
|
|
696
|
-
let added=ownString(text.slice(entry.text.length)).replace(/\t/g," ");replaced=entry.replaced+added,entry.lexed!==void 0&&(extended={from:entry.lexed,added})}
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
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){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]===`
|
|
736
|
+
`&&original++}return offsets.push(source2.length),{text:source2.replace(/\r\n|\r/g,`
|
|
737
|
+
`).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[end]===offsets[end-1])for(;offsets[end+remaining]===offsets[end];)remaining++;result+=source2.slice(cursor,offsets[match.index])+" ".repeat(remaining),cursor=offsets[end+remaining]}return result+source2.slice(cursor)}function fencedCodeTokens(tokens){
|
|
738
|
+
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].length),fence=opening[1],closing=new RegExp(
|
|
739
|
+
`^ {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={
|
|
740
|
+
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.
|
|
741
|
+
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=
|
|
742
|
+
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,
|
|
743
|
+
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.
|
|
744
|
+
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.
|
|
745
|
+
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=
|
|
746
|
+
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),
|
|
747
|
+
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(
|
|
748
|
+
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(
|
|
749
|
+
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(
|
|
750
|
+
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(
|
|
751
|
+
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,
|
|
752
|
+
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?.
|
|
753
|
+
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.
|
|
754
|
+
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(
|
|
755
|
+
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=
|
|
756
|
+
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.
|
|
757
|
+
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.
|
|
758
|
+
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===
|
|
759
|
+
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,
|
|
760
|
+
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],offsets[start+token.raw.length]);if(start>=0&&(cursor=start+token.raw.
|
|
761
|
+
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]+)/.
|
|
762
|
+
exec(item.raw)?.[0]??"",itemStart=listSource.text.indexOf(item.raw,itemCursor),itemSource=itemStart<0?item.raw:raw.slice(listSource.offsets[itemStart],listSource.offsets[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){if(!this.options.renderCodeBlock||
|
|
763
|
+
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(`
|
|
764
|
+
`)+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)===
|
|
765
|
+
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++){
|
|
766
|
+
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,
|
|
767
|
+
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.
|
|
768
|
+
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!==
|
|
769
|
+
!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(
|
|
770
|
+
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(
|
|
771
|
+
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.
|
|
772
|
+
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--);
|
|
773
|
+
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):
|
|
774
|
+
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(""),
|
|
775
|
+
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(){
|
|
776
|
+
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.
|
|
777
|
+
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.
|
|
778
|
+
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),
|
|
779
|
+
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||
|
|
780
|
+
rendered.split(`
|
|
781
|
+
`).some(line=>visibleWidth(line)>width))&&(rendered=latexToken.raw.trim());for(let line of rendered.split(`
|
|
782
|
+
`))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.
|
|
783
|
+
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(`
|
|
784
|
+
`);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(
|
|
785
|
+
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,
|
|
786
|
+
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=[];
|
|
787
|
+
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!==
|
|
788
|
+
"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(),
|
|
789
|
+
{applyText,stylePrefix}=resolvedStyleContext,applyTextWithNewlines=text=>text.split(`
|
|
722
790
|
`).map(segment=>applyText(segment)).join(`
|
|
723
791
|
`);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.
|
|
724
792
|
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.
|
|
725
|
-
renderInlineTokens(token.tokens||[],resolvedStyleContext),styledLink=this.theme.link(this.theme.underline(linkText));if(getCapabilities().hyperlinks)result+=hyperlink(styledLink,token.href)+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":
|
|
793
|
+
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":
|
|
794
|
+
result+=`
|
|
726
795
|
`;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]+/.
|
|
727
796
|
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(
|
|
728
|
-
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"){lines
|
|
729
|
-
1,width,styleContext)),renderedAnyLine=!0;continue}let itemLines=this.renderToken(itemToken,itemWidth,void 0,styleContext);for(let line of itemLines)for(let wrappedLine of this.wrapLine(line,itemWidth)){let linePrefix=renderedAnyLine?continuationPrefix:firstPrefix;
|
|
730
|
-
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)=>{
|
|
731
|
-
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}
|
|
732
|
-
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]=
|
|
733
|
-
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*
|
|
734
|
-
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.
|
|
735
|
-
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;
|
|
736
|
-
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.
|
|
737
|
-
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.
|
|
738
|
-
...rowCellLines.map(
|
|
739
|
-
\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(
|
|
797
|
+
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,
|
|
798
|
+
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;
|
|
799
|
+
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)=>{
|
|
800
|
+
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}
|
|
801
|
+
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]=
|
|
802
|
+
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*
|
|
803
|
+
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.
|
|
804
|
+
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;
|
|
805
|
+
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.
|
|
806
|
+
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.
|
|
807
|
+
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.
|
|
808
|
+
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(
|
|
740
809
|
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.
|
|
741
810
|
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??
|
|
742
811
|
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.
|
|
@@ -748,24 +817,25 @@ start,wasFollowingEnd=this.followingEnd;return this.currentScrollTop=next,this.f
|
|
|
748
817
|
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){
|
|
749
818
|
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&&
|
|
750
819
|
(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:"\
|
|
751
|
-
scroll",component:this.child,state:this}}};var SettingsList=class{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.
|
|
752
|
-
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.
|
|
753
|
-
"")),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(
|
|
754
|
-
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,
|
|
755
|
-
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(
|
|
756
|
-
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.
|
|
757
|
-
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=
|
|
758
|
-
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();if(kb.matches(data,"tui.select.up")){if(displayItems.
|
|
759
|
-
matches(data,"tui.select.down")){if(displayItems.length===0)return;this.selectedIndex=this.selectedIndex===displayItems.length-1?0:this.selectedIndex+1}else kb.matches(data,"tui.select.confirm")||data===" "&&(!this.searchEnabled||this.searchInput?.getValue().length===0)?this.activateItem():kb.matches(
|
|
760
|
-
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.
|
|
761
|
-
(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];
|
|
762
|
-
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){
|
|
820
|
+
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.
|
|
821
|
+
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.
|
|
822
|
+
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(
|
|
823
|
+
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,
|
|
824
|
+
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(
|
|
825
|
+
` ${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.
|
|
826
|
+
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=
|
|
827
|
+
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.
|
|
828
|
+
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(
|
|
829
|
+
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.
|
|
830
|
+
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];
|
|
831
|
+
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){
|
|
832
|
+
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(`
|
|
763
833
|
`);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.
|
|
764
|
-
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),
|
|
765
|
-
length-1)*this.gap;for(let
|
|
834
|
+
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,
|
|
835
|
+
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),
|
|
766
836
|
"..",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.
|
|
767
|
-
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}$/,
|
|
768
|
-
|
|
837
|
+
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){
|
|
838
|
+
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"\
|
|
769
839
|
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\
|
|
770
840
|
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){
|
|
771
841
|
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(
|
|
@@ -779,7 +849,7 @@ for(let sequence of result.sequences)this.emitDataSequence(sequence);if(this.buf
|
|
|
779
849
|
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.
|
|
780
850
|
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$/);
|
|
781
851
|
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.
|
|
782
|
-
pid,"SIGWINCH")}catch{}}function normalizeNativeShiftEnterInput(data,shouldDetectNativeShiftEnter,isShiftPressed){return shouldDetectNativeShiftEnter&&data
|
|
852
|
+
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=(()=>{
|
|
783
853
|
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(){
|
|
784
854
|
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(){
|
|
785
855
|
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(
|
|
@@ -789,20 +859,20 @@ negotiationSequence.type==="device-attributes"){if(this.pendingKeyboardProtocolD
|
|
|
789
859
|
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(
|
|
790
860
|
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(){
|
|
791
861
|
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(
|
|
792
|
-
()=>{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=sequence
|
|
793
|
-
|
|
794
|
-
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.
|
|
795
|
-
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&&
|
|
796
|
-
{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.
|
|
797
|
-
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[?
|
|
798
|
-
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>
|
|
799
|
-
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;${title}\x07`)}setProgramStatus(status){this.programStatus=status.state==="clear"?void 0:status,this.
|
|
800
|
-
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(){
|
|
801
|
-
progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
862
|
+
()=>{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()||
|
|
863
|
+
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===
|
|
864
|
+
"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.
|
|
865
|
+
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&&
|
|
866
|
+
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.
|
|
867
|
+
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\
|
|
868
|
+
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>
|
|
869
|
+
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.
|
|
870
|
+
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(){
|
|
871
|
+
return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};var PRINTABLE_ASCII=/^[\x20-\x7e]*$/;function buildSearchCorpus(lines){let chunks=[],spans=[],textLength=0,pendingSeparator=!1,appendSeparator=()=>{pendingSeparator&&(chunks.push(" "),textLength+=1,pendingSeparator=!1)};for(let row=0;row<lines.length;row++){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<
|
|
872
|
+
line.length&&line.charCodeAt(end)!==32;)end+=1;appendSeparator();let text=line.slice(index,end);chunks.push(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(),
|
|
873
|
+
chunks.push(text),spans.push({textStart:textLength,textEnd:textLength+text.length,row,startCol:column,endCol:column+width,linearColumns:!1}),textLength+=text.length,column+=width}textLength>0&&(pendingSeparator=!0)}return{text:chunks.join(""),spans}}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(
|
|
874
|
+
escapeRegExp(normalizedQuery),"giu"),matches=[],spanIndex=0;for(let match of corpus.text.matchAll(expression)){let start=match.index,end=start+match[0].length;for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=start;)spanIndex+=1;let segments=[];for(let index=spanIndex;index<corpus.spans.length;index++){let span=corpus.spans[index];if(span.textStart>=end)break;if(span.textEnd<=start)continue;let startCol=span.linearColumns?span.startCol+Math.max(start,span.textStart)-span.textStart:
|
|
875
|
+
span.startCol,endCol=span.linearColumns?span.startCol+Math.min(end,span.textEnd)-span.textStart:span.endCol,previous=segments[segments.length-1];previous&&previous.row===span.row&&startCol<=previous.endCol?previous.endCol=Math.max(previous.endCol,endCol):segments.push({row:span.row,startCol,endCol})}for(;spanIndex<corpus.spans.length&&corpus.spans[spanIndex].textEnd<=end;)spanIndex+=1;segments.length>0&&matches.push({segments})}return matches}var AltScreenSearchIndex=class{sourceLines;corpus;normalizedQuery;matches=[];search(lines,query){
|
|
806
876
|
let sourceChanged=this.sourceLines?.length!==lines.length;if(!sourceChanged&&this.sourceLines){for(let index=0;index<lines.length;index++)if(this.sourceLines[index]!==lines[index]){sourceChanged=!0;break}}(sourceChanged||!this.corpus)&&(this.sourceLines=Array.from(lines),this.corpus=buildSearchCorpus(lines));let normalizedQuery=normalizeQuery(query),changed=sourceChanged||normalizedQuery!==this.normalizedQuery;return changed&&(this.normalizedQuery=normalizedQuery,this.matches=findSearchCorpusMatches(
|
|
807
877
|
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){
|
|
808
878
|
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===
|
|
@@ -812,30 +882,32 @@ visibleWidth(resultText)),inputLine=truncateToWidth(this.input.render(Math.max(1
|
|
|
812
882
|
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&&
|
|
813
883
|
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===
|
|
814
884
|
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(
|
|
815
|
-
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),
|
|
816
|
-
get(safeWidth);return lines
|
|
817
|
-
context,component,width).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;for(let
|
|
818
|
-
component);if(!node){let lines=renderCached(context,component,safeWidth),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(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=
|
|
819
|
-
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,
|
|
820
|
-
let scrollView=node.state;(node.state.primary||!context.primaryScrollView)&&(context.primaryScrollView=scrollView);let rect2={x:x2,y
|
|
821
|
-
max(0,entries.length-1)*node.gap;if(node.type==="vstack"){let intrinsicHeights2=entries.
|
|
822
|
-
rect2),children:[],layer:0},childY=
|
|
823
|
-
context,entry.component,Math.max(1,widths[index]))),allocatedHeight=height===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,
|
|
824
|
-
node.align==="center"?childY+=Math.floor((allocatedHeight-childHeight)/2):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.
|
|
825
|
-
node.gap}return box}function replaceScrollbarCell(line,column,totalWidth,replacement,preserveTargetBackground){if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(
|
|
826
|
-
targetIndex);if(!ansi)break;targetPrefix+=ansi.code,targetIndex+=ansi.length}let beforePadding=" ".repeat(Math.max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.
|
|
827
|
-
if(!box.scrollView||box.rect.width<=0||box.rect.height<=0)return;let contentHeight=box.children[0]?.rect.height??box.scrollContentLines?.length??0,trackHeight=box.
|
|
828
|
-
max(0,contentHeight-trackHeight),maxThumbTop=trackHeight-thumbHeight,thumbOffset=maxScrollTop===0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),
|
|
829
|
-
geometry.trackHeight;offset++){let row=geometry.trackTop+offset;if(row<box.clip.y||row>=box.clip.y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=
|
|
830
|
-
if(box.lines){let offset=box.lineOffset??0,firstRow=Math.max(box.rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
let
|
|
834
|
-
|
|
835
|
-
|
|
885
|
+
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.lines;let other=known.
|
|
886
|
+
others?.get(safeWidth);if(other!==void 0)return other}let lines=renderLiveLines(component,safeWidth)?.lines??renderSharedLines(component,safeWidth);return known===void 0?context.renderCache.set(component,{width:safeWidth,lines}):(known.others??=new Map,known.others.set(safeWidth,lines)),lines}function measureHeight(context,component,width){return component instanceof VStack&&component.render===VStack.prototype.render?component.measureHeight(Math.max(1,Math.floor(width)),context.heightOf):renderCached(
|
|
887
|
+
context,component,width).length}function measureWidth(context,component,width){return renderCached(context,component,width).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.rect);let children=box.children;for(let i=0;i<
|
|
888
|
+
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),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(CURSOR_MARKER));cursorLine>=allocatedHeight2&&(lineOffset=
|
|
889
|
+
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.rect.height,viewportHeight=height===void 0?contentHeight:
|
|
890
|
+
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),box2={component,rect:rect2,clip:childClip,children:[childBox],scrollView,scrollContentLines:renderCached(context,node.component,
|
|
891
|
+
contentWidth),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=="number"?entry.basis:measureHeight(context,entry.component,safeWidth)}let sizes=allocateStackSizes(entries,intrinsicHeights2,
|
|
892
|
+
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.length;index++)box2.children.push(withParent(layoutComponent(context,entries[index].component,x2,childY,safeWidth,sizes[index],
|
|
893
|
+
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===void 0?intrinsicHeights.reduce((max,childHeight)=>Math.max(max,childHeight),0):Math.max(0,height),rect={x:x2,
|
|
894
|
+
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):node.align==="end"&&(childY+=allocatedHeight-childHeight);let childWidth=widths[index];childWidth===0?box.children.
|
|
895
|
+
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){if(isImageLine(line))return line;let graphemeRange=getGraphemeCellRange(
|
|
896
|
+
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.max(0,start-visibleWidth(before))),cellPaddingBefore=" ".repeat(Math.
|
|
897
|
+
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]?.rect.height??box.scrollContentLines?.length??0,trackHeight=box.
|
|
898
|
+
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===0?0:Math.round(box.scrollView.scrollTop/maxScrollTop*maxThumbTop),
|
|
899
|
+
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.y+box.clip.height||row<0||row>=screen.length)continue;let replacement=row>=
|
|
900
|
+
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.rect.y,box.clip.y,0),lastRow=Math.min(box.rect.y+box.rect.height,box.clip.
|
|
901
|
+
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(imageMetadata.rows,clipBottom-row);visibleRows<imageMetadata.rows&&(line=
|
|
902
|
+
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.scrollView.scrollTop,minRow=Math.max(0,scrollTop-getMaxKittyImageRows());
|
|
903
|
+
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.width>=totalWidth&&(screen[box.rect.y]=cropped)}break}}paintScrollbar(box,
|
|
904
|
+
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,height:safeHeight}),lines=[];for(let row=0;row<safeHeight;row++)lines.
|
|
905
|
+
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.children)visit(child,depth+1)}};return visit(frame.
|
|
906
|
+
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,y)&&result.push({scrollView:box.scrollView,depth});
|
|
907
|
+
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(
|
|
836
908
|
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.
|
|
837
909
|
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\\))+/,
|
|
838
|
-
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(["/","-"]),
|
|
910
|
+
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="\
|
|
839
911
|
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={}){
|
|
840
912
|
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()}},this.implicitScrollView=new ScrollView(this.implicitDocument,{follow:"end",primary:!0}),this.flashes=new AltScreenFlashContainer(()=>this.requestRender()),this.wheelScroll=new WheelScrollAccelerator(options.wheelScrollLines??1),this.mouseEnabled=options.mouse??!0,this.searchMatchStyle=
|
|
841
913
|
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??!0,this.copySelection=options.copySelection,this.addInputListener(data=>this.handleViewportInput(
|
|
@@ -854,41 +926,41 @@ cachedImage.estimatedDecodedBytes);let evictedImageDeletion="";for(let[imageId,c
|
|
|
854
926
|
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().
|
|
855
927
|
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(
|
|
856
928
|
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.
|
|
857
|
-
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,
|
|
858
|
-
overlay?.getBounds();if(!(!search||!bounds)&&!(x2<bounds.col||x2>=bounds.col+bounds.width||
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
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(void 0)&&
|
|
865
|
-
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.
|
|
866
|
-
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),
|
|
867
|
-
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.
|
|
868
|
-
|
|
869
|
-
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||
|
|
870
|
-
-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
|
|
871
|
-
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,
|
|
872
|
-
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.
|
|
873
|
-
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.
|
|
874
|
-
return dispatchMouseEvent(target.component,retargetMouseEvent(event,target))}getComponentClickCount(target,x2,
|
|
875
|
-
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;
|
|
876
|
-
(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(
|
|
877
|
-
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||
|
|
878
|
-
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]$/.
|
|
879
|
-
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){
|
|
929
|
+
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?.
|
|
930
|
+
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||
|
|
931
|
+
(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.
|
|
932
|
+
index.search(lines,search.query),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]?.row??0)<search.anchorRow?
|
|
933
|
+
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=exactIndex>=0?exactIndex:
|
|
934
|
+
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||scrollView.viewportHeight<=
|
|
935
|
+
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()&&this.activeSearch?.
|
|
936
|
+
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(void 0)&&
|
|
937
|
+
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.
|
|
938
|
+
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),
|
|
939
|
+
{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.
|
|
940
|
+
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(
|
|
941
|
+
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||
|
|
942
|
+
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.\
|
|
943
|
+
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?
|
|
944
|
+
{}:{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.
|
|
945
|
+
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.
|
|
946
|
+
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(),
|
|
947
|
+
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;
|
|
948
|
+
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(
|
|
949
|
+
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||
|
|
950
|
+
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]$/.
|
|
951
|
+
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){
|
|
880
952
|
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)
|
|
881
953
|
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&
|
|
882
|
-
3)!==0||event.y!==rect.row||event.x<rect.column||event.x>=rect.column+rect.width?!1:(this.scrollToBottom(),!0)}getScrollbarTargetAt(x2,
|
|
883
|
-
geometry}}}setScrollbarHover(scrollView){scrollView!==this.scrollbarHover&&(this.scrollbarHover?.setScrollbarActive(!1),this.scrollbarHover=scrollView,this.scrollbarHover?.setScrollbarActive(!0))}updateScrollbarHover(x2,
|
|
954
|
+
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,
|
|
955
|
+
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.
|
|
884
956
|
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.
|
|
885
957
|
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);
|
|
886
|
-
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,
|
|
887
|
-
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,
|
|
958
|
+
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(
|
|
959
|
+
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(
|
|
888
960
|
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.
|
|
889
|
-
row]??""}return this.previousScreen[point.row]??""}getWordSelection(point){let line=stripTerminalSequences(this.getSelectionSourceLine(point)),segments=[],start=0;for(let segment of
|
|
890
|
-
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;
|
|
891
|
-
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;
|
|
961
|
+
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.
|
|
962
|
+
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;
|
|
963
|
+
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;
|
|
892
964
|
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===
|
|
893
965
|
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.
|
|
894
966
|
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(){
|
|
@@ -914,57 +986,63 @@ rect.x+selection.start.col},end:{...selection.end,row:box.rect.y+selection.end.r
|
|
|
914
986
|
!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||
|
|
915
987
|
!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??
|
|
916
988
|
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.
|
|
917
|
-
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){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)
|
|
918
|
-
return;let changed=0;for(let row=top;row<=bottom;row++){let line=screen[row];if(line!==previous[row]&&(changed++,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>
|
|
919
|
-
(best=sameDown,up=-distance)}if(!(changed-(span-best)<MIN_ROWS_SAVED_BY_SCROLLING)){for(let row=top;row<=bottom;row++)if(isImageLine(previous[row]??""))return
|
|
920
|
-
root,width,height,()=>this.requestRender()));let
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
"")||(buffer+=`\x1B[${row+1};1H
|
|
927
|
-
bottom+1}r`,buffer+=moved.up>0?`\x1B[${moved.bottom+
|
|
989
|
+
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)
|
|
990
|
+
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>
|
|
991
|
+
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=
|
|
992
|
+
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});
|
|
993
|
+
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?
|
|
994
|
+
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=
|
|
995
|
+
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.
|
|
996
|
+
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.
|
|
997
|
+
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()));
|
|
998
|
+
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<
|
|
999
|
+
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+
|
|
1000
|
+
1};1H${`
|
|
928
1001
|
`.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,
|
|
929
|
-
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 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&&
|
|
930
|
-
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+
|
|
931
|
-
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){
|
|
932
|
-
line)?.rows??1}function isTermuxSession(){return!!process.env.TERMUX_VERSION}var TuiMainScreen=class extends TuiBase{mode="regular";
|
|
933
|
-
maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(state){this.frameLive=void 0,this.
|
|
934
|
-
frameLive=void 0,this.
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
line
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
let
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
length},
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1002
|
+
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&&
|
|
1003
|
+
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+
|
|
1004
|
+
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){
|
|
1005
|
+
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.
|
|
1006
|
+
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.
|
|
1007
|
+
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.
|
|
1008
|
+
shownLength-this.hardwareCursorRow;lineDiff>0?this.terminal.write(`\x1B[${lineDiff}B`):lineDiff<0&&this.terminal.write(`\x1B[${-lineDiff}A`),this.terminal.write(`\r
|
|
1009
|
+
`)}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;
|
|
1010
|
+
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(
|
|
1011
|
+
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++){
|
|
1012
|
+
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.
|
|
1013
|
+
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]):
|
|
1014
|
+
(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(
|
|
1015
|
+
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(
|
|
1016
|
+
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=
|
|
1017
|
+
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(
|
|
1018
|
+
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,
|
|
1019
|
+
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&&
|
|
1020
|
+
!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,
|
|
1021
|
+
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,
|
|
1022
|
+
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):
|
|
1023
|
+
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
|
|
1024
|
+
`);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
|
|
1025
|
+
`);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),
|
|
1026
|
+
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\
|
|
1027
|
+
ev=${shownLength}, new=${frameLength}, height=${height})
|
|
1028
|
+
`;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.
|
|
1029
|
+
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.
|
|
1030
|
+
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.
|
|
1031
|
+
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,
|
|
1032
|
+
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===
|
|
1033
|
+
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(
|
|
1034
|
+
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-
|
|
1035
|
+
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
|
|
958
1036
|
`.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
|
|
959
|
-
`:"\r");let renderEnd=Math.min(lastChanged,
|
|
960
|
-
`);let line=
|
|
961
|
-
\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(),"
|
|
962
|
-
l)}) ${l}`),""].join(`
|
|
1037
|
+
`:"\r");let renderEnd=Math.min(lastChanged,frameLength-1);for(let i=firstChanged;i<=renderEnd;i++){i>firstChanged&&output.append(`\r
|
|
1038
|
+
`);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
|
|
1039
|
+
\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)=>{
|
|
1040
|
+
let l=frame.written(idx);return`[${idx}] (w=${visibleWidth(l)}) ${l}`}),""].join(`
|
|
963
1041
|
`);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(`
|
|
964
|
-
`);throw new Error(errorMsg)}output.append(line)}let finalCursorRow=renderEnd;if(
|
|
965
|
-
\x1B[2K`);output.append(`\x1B[${extraLines}A`)}if(output.append("\x1B[?2026l"),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}
|
|
966
|
-
|
|
967
|
-
`);fs2.writeFileSync(debugPath,debugData)}output.flush(),this.cursorRow=Math.max(0,
|
|
1042
|
+
`);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
|
|
1043
|
+
\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}`,
|
|
1044
|
+
`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(`
|
|
1045
|
+
`);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){
|
|
968
1046
|
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(
|
|
969
1047
|
{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.
|
|
970
1048
|
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",
|
|
@@ -972,8 +1050,8 @@ SHEBANG({binary:`(${SH_LIKE_SHELLS.join("|")})`,relevance:10}),FUNCTION={classNa
|
|
|
972
1050
|
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",
|
|
973
1051
|
"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",
|
|
974
1052
|
"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,
|
|
975
|
-
HERE_DOC,PATH_MODE,QUOTE_STRING,ESCAPED_QUOTE,APOS_STRING,ESCAPED_APOS,VAR]}}function
|
|
976
|
-
|
|
1053
|
+
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\
|
|
1054
|
+
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]},
|
|
977
1055
|
{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+)?/}],
|
|
978
1056
|
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,
|
|
979
1057
|
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\
|
|
@@ -1154,18 +1232,26 @@ USE_STRICT,hljs2.APOS_STRING_MODE,hljs2.QUOTE_STRING_MODE,HTML_TEMPLATE,CSS_TEMP
|
|
|
1154
1232
|
{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,
|
|
1155
1233
|
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:"\
|
|
1156
1234
|
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===
|
|
1157
|
-
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(
|
|
1235
|
+
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]),
|
|
1158
1236
|
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){
|
|
1159
|
-
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,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||
|
|
1237
|
+
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||
|
|
1160
1238
|
(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))
|
|
1161
1239
|
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-
|
|
1162
1240
|
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===`
|
|
1163
|
-
`||nextChar==="\r"}function renderHighlightedHtml(html,theme2={}){let output="",textBuffer="",scopes=[],flushText=()=>{if(!textBuffer)return;let formatter=getActiveFormatter(scopes,theme2);output+=formatter?textBuffer.
|
|
1241
|
+
`||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(`
|
|
1242
|
+
`)?textBuffer.split(`
|
|
1164
1243
|
`).map(line=>line&&formatter(line)).join(`
|
|
1165
|
-
`):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){
|
|
1166
|
-
text,index+=decoded.length;continue}}textBuffer+=html
|
|
1167
|
-
()
|
|
1168
|
-
|
|
1244
|
+
`):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){
|
|
1245
|
+
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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"):text}function spanClass(node,classPrefix){if(node.scope){if(node.scope.
|
|
1246
|
+
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}\
|
|
1247
|
+
">`;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(
|
|
1248
|
+
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(`
|
|
1249
|
+
`)?output+=textBuffer.split(`
|
|
1250
|
+
`).map(line=>line&&formatter(line)).join(`
|
|
1251
|
+
`):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)
|
|
1252
|
+
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(
|
|
1253
|
+
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=
|
|
1254
|
+
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:{
|
|
1169
1255
|
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:"\
|
|
1170
1256
|
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",
|
|
1171
1257
|
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:"\
|
|
@@ -1191,7 +1277,7 @@ extreme)-surfaceL,floor=(levelTarget(READABLE_FLOOR[appearance],appearance,surfa
|
|
|
1191
1277
|
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)){
|
|
1192
1278
|
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}
|
|
1193
1279
|
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(
|
|
1194
|
-
1,saturationCurve(family,lightness)/anchor):1,color=okhslColor(source2.h,source2.s*falloff*saturation,lightness),cap=source2.chroma*falloff*saturation,{l,c:
|
|
1280
|
+
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?
|
|
1195
1281
|
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&&
|
|
1196
1282
|
!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\
|
|
1197
1283
|
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:"\
|
|
@@ -1235,16 +1321,14 @@ themeWatcher),themeWatcher=void 0}function getResolvedThemeColors(themeName){let
|
|
|
1235
1321
|
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.
|
|
1236
1322
|
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.
|
|
1237
1323
|
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(`
|
|
1238
|
-
`).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(theme)};try{return highlight(code,opts).split(`
|
|
1239
|
-
`)}catch{return code.split(`
|
|
1240
|
-
`)}}function getLanguageFromPath(filePath){let ext=filePath.split(".").pop()?.toLowerCase();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:"\
|
|
1241
|
-
json",yaml:"yaml",yml:"yaml",toml:"toml",xml:"xml",md:"markdown",markdown:"markdown",dockerfile:"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.
|
|
1242
|
-
fg("mdCode",text),codeBlock:text=>theme.fg("mdCodeBlock",text),codeBlockBorder:text=>theme.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:(code,lang)=>{let validLang=lang&&supportsLanguage(lang)?lang:
|
|
1243
|
-
void 0;if(!validLang)return code.split(`
|
|
1244
|
-
`).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(theme)};try{return highlight(code,opts).split(`
|
|
1324
|
+
`).map(line=>theme.fg("mdCodeBlock",line));let opts={language:validLang,ignoreIllegals:!0,theme:getCliHighlightTheme(getThemeInstance()??theme)};try{return highlight(code,opts).split(`
|
|
1245
1325
|
`)}catch{return code.split(`
|
|
1246
|
-
`).map(line=>theme.fg("mdCodeBlock",line))}}
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1326
|
+
`).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();
|
|
1327
|
+
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:"\
|
|
1328
|
+
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.
|
|
1329
|
+
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.
|
|
1330
|
+
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(
|
|
1331
|
+
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,
|
|
1332
|
+
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,
|
|
1333
|
+
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,
|
|
1334
|
+
getResolvedThemeColors,getThemeExportColors,highlightCode,CodeHighlighter,getLanguageFromPath,getMarkdownTheme,getSelectListTheme,getEditorTheme,getSettingsListTheme,formatKeyText,keyText,keyDisplayText,keyHint,rawKeyHint};
|