agents 0.25.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -9
- package/dist/{agent-routing-0DR0Tk2v.d.ts → agent-routing-Bhdbvf7s.d.ts} +13 -8
- package/dist/agent-routing.d.ts +1 -1
- package/dist/agent-tool-types.d.ts +1 -1
- package/dist/{agent-tools-YrATZJu2.d.ts → agent-tools-bJZwBMfq.d.ts} +2 -2
- package/dist/agent-tools.d.ts +1 -1
- package/dist/ai-sdk-OoGkFy3s.js +2444 -0
- package/dist/ai-sdk-OoGkFy3s.js.map +1 -0
- package/dist/apply-chunks-1FheRb9W.js +99 -0
- package/dist/apply-chunks-1FheRb9W.js.map +1 -0
- package/dist/broadcast-state-CEyI4uAK.js +69 -0
- package/dist/broadcast-state-CEyI4uAK.js.map +1 -0
- package/dist/browser/ai-sdk.d.ts +1 -1
- package/dist/browser/ai-sdk.js +2 -2
- package/dist/browser/ai-sdk.js.map +1 -1
- package/dist/browser/index.d.ts +1 -1
- package/dist/browser/tanstack-ai.d.ts +1 -1
- package/dist/browser/tanstack-ai.js +1 -1
- package/dist/{browser-DE3d-RLk.d.ts → browser-tmkcAAI3.d.ts} +2 -2
- package/dist/{browser-tool-DuNdlwZ9.d.ts → browser-tool-Bn-nzJQI.d.ts} +3 -3
- package/dist/{browser-tool-CQ10e6Kj.js → browser-tool-CBqs6hqa.js} +58 -18
- package/dist/browser-tool-CBqs6hqa.js.map +1 -0
- package/dist/capability-B4WbF81e.js.map +1 -1
- package/dist/{capability-runner-DBAnGr6L.d.ts → capability-runner-O5VbQzqg.d.ts} +9 -1
- package/dist/channel-Bak_6zDP.d.ts +333 -0
- package/dist/chat/index.d.ts +11 -9
- package/dist/chat/index.js +5 -194
- package/dist/chat/index.js.map +1 -1
- package/dist/chat/react.d.ts +2 -4
- package/dist/chat/react.js +3 -1
- package/dist/chat/react.js.map +1 -1
- package/dist/chat-sdk/index.d.ts +1 -1
- package/dist/chat-sdk/index.js +1 -1
- package/dist/cli.js +144 -0
- package/dist/{client-fyQrLGkD.js → client-1tEQ1Oqz.js} +27 -2
- package/dist/{client-fyQrLGkD.js.map → client-1tEQ1Oqz.js.map} +1 -1
- package/dist/{client-je3koD9Z.d.ts → client-DS3Dz9l0.d.ts} +2 -2
- package/dist/client-tools-aIBO0Fk7.d.ts +53 -0
- package/dist/client.d.ts +1 -1
- package/dist/conversations-DH0ut_8n.d.ts +192 -0
- package/dist/{current-agent-vAk_5JMt.d.ts → current-agent-C07C5o5Y.d.ts} +3 -3
- package/dist/daemon-core-Buubj-y1.js +481 -0
- package/dist/daemon-core-Buubj-y1.js.map +1 -0
- package/dist/daemon-core-CbohVPAu.d.ts +132 -0
- package/dist/{do-oauth-client-provider-Tmf1vgKz.d.ts → do-oauth-client-provider-DfsUcpc3.d.ts} +7 -1
- package/dist/{durable-object-lifecycle-HhgOMWq9.d.ts → durable-object-lifecycle-DRqp475_.d.ts} +2 -2
- package/dist/{channels/email.d.ts → experimental/channels/email/index.d.ts} +25 -12
- package/dist/{channels/email.js → experimental/channels/email/index.js} +13 -35
- package/dist/experimental/channels/email/index.js.map +1 -0
- package/dist/experimental/channels/index.d.ts +270 -0
- package/dist/experimental/channels/index.js +1186 -0
- package/dist/experimental/channels/index.js.map +1 -0
- package/dist/{channels/slack.d.ts → experimental/channels/slack/index.d.ts} +19 -9
- package/dist/experimental/channels/slack/index.js +267 -0
- package/dist/experimental/channels/slack/index.js.map +1 -0
- package/dist/{channels/telegram.d.ts → experimental/channels/telegram/index.d.ts} +19 -9
- package/dist/experimental/channels/telegram/index.js +198 -0
- package/dist/experimental/channels/telegram/index.js.map +1 -0
- package/dist/experimental/channels/web/ai-sdk.d.ts +55 -0
- package/dist/experimental/channels/web/ai-sdk.js +266 -0
- package/dist/experimental/channels/web/ai-sdk.js.map +1 -0
- package/dist/experimental/channels/web/client.d.ts +97 -0
- package/dist/experimental/channels/web/client.js +349 -0
- package/dist/experimental/channels/web/client.js.map +1 -0
- package/dist/experimental/channels/web/index.d.ts +189 -0
- package/dist/experimental/channels/web/index.js +332 -0
- package/dist/experimental/channels/web/index.js.map +1 -0
- package/dist/gateway-BDC07gYO.d.ts +100 -0
- package/dist/handle-zAzh0UW2.d.ts +460 -0
- package/dist/harness/ai-sdk/index.d.ts +175 -0
- package/dist/harness/ai-sdk/index.js +605 -0
- package/dist/harness/ai-sdk/index.js.map +1 -0
- package/dist/harness/container/daemon/index.d.ts +76 -0
- package/dist/harness/container/daemon/index.js +3 -0
- package/dist/harness/container/index.d.ts +740 -0
- package/dist/harness/container/index.js +2152 -0
- package/dist/harness/container/index.js.map +1 -0
- package/dist/harness/container/runtime/index.d.ts +144 -0
- package/dist/harness/container/runtime/index.js +1082 -0
- package/dist/harness/container/runtime/index.js.map +1 -0
- package/dist/harness/opencode/index.d.ts +369 -0
- package/dist/harness/opencode/index.js +1072 -0
- package/dist/harness/opencode/index.js.map +1 -0
- package/dist/{harnesses → harness}/pi/index.d.ts +85 -88
- package/dist/{harnesses → harness}/pi/index.js +196 -77
- package/dist/harness/pi/index.js.map +1 -0
- package/dist/harness/store/index.d.ts +24 -0
- package/dist/harness/store/index.js +2 -0
- package/dist/harness/think/index.d.ts +821 -0
- package/dist/harness/think/index.js +2529 -0
- package/dist/harness/think/index.js.map +1 -0
- package/dist/harness-B6B9S3rb.d.ts +203 -0
- package/dist/{images-iiTDSyRu.js → images-Ce9SCu3X.js} +2 -248
- package/dist/images-Ce9SCu3X.js.map +1 -0
- package/dist/{index-BreL0YrQ.d.ts → index-D0A5tbWu.d.ts} +2 -2
- package/dist/index-Ib_4dwOo.d.ts +200 -0
- package/dist/index.d.ts +5 -5
- package/dist/index.js +2 -2
- package/dist/ingress-EFbrS547.js +9 -0
- package/dist/ingress-EFbrS547.js.map +1 -0
- package/dist/input-schema-DNrpTu49.js +23 -0
- package/dist/input-schema-DNrpTu49.js.map +1 -0
- package/dist/internal-kmw70xwR.js +46 -0
- package/dist/internal-kmw70xwR.js.map +1 -0
- package/dist/internal_context.d.ts +1 -1
- package/dist/lifecycle/index.d.ts +3 -3
- package/dist/mcp/client/do-oauth-client-provider.d.ts +1 -1
- package/dist/mcp/client/do-oauth-client-provider.js +9 -0
- package/dist/mcp/client/do-oauth-client-provider.js.map +1 -1
- package/dist/mcp/client/index.d.ts +1 -1
- package/dist/mcp/client/index.js +1 -1
- package/dist/mcp/client/x402.d.ts +35 -4
- package/dist/mcp/client/x402.js +24 -3
- package/dist/mcp/client/x402.js.map +1 -1
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +2 -2
- package/dist/models/ai-sdk/index.d.ts +16 -14
- package/dist/models/ai-sdk/index.js +1 -2442
- package/dist/models/opencode/index.d.ts +65 -0
- package/dist/models/opencode/index.js +285 -0
- package/dist/models/opencode/index.js.map +1 -0
- package/dist/models/pi-ai/index.d.ts +23 -21
- package/dist/models/pi-ai/index.js +7 -6
- package/dist/models/pi-ai/index.js.map +1 -1
- package/dist/options-pwTNq9z6.d.ts +134 -0
- package/dist/protocol-BEgrJYC5.d.ts +331 -0
- package/dist/protocol-CukuI73M.d.ts +386 -0
- package/dist/protocol-cOklVBBD.js +227 -0
- package/dist/protocol-cOklVBBD.js.map +1 -0
- package/dist/{protocol-kHsr-f0X.js → protocol-eXeJxhgu.js} +2 -67
- package/dist/protocol-eXeJxhgu.js.map +1 -0
- package/dist/protocol-y2sSY584.js +148 -0
- package/dist/protocol-y2sSY584.js.map +1 -0
- package/dist/queue/index.d.ts +1 -1
- package/dist/react.d.ts +2 -2
- package/dist/routing/index.d.ts +2 -2
- package/dist/{scheduler-RdACNXDP.d.ts → scheduler-CrFCnv_J.d.ts} +2 -2
- package/dist/schedules/index.d.ts +1 -1
- package/dist/serializable.d.ts +1 -1
- package/dist/sessions/index.d.ts +11 -434
- package/dist/sessions/index.js +1 -2271
- package/dist/sessions-B9pNuxdT.js +2272 -0
- package/dist/sessions-B9pNuxdT.js.map +1 -0
- package/dist/settings-C45hDliX.js +253 -0
- package/dist/settings-C45hDliX.js.map +1 -0
- package/dist/{transport-PfFnt-Ld.d.ts → settings-NgGwF7Qt.d.ts} +14 -208
- package/dist/{src-BZeu-SCD.js → src-DgCbZtIR.js} +4 -4
- package/dist/{src-BZeu-SCD.js.map → src-DgCbZtIR.js.map} +1 -1
- package/dist/stall-watchdog-BpRF2uwG.js +195 -0
- package/dist/stall-watchdog-BpRF2uwG.js.map +1 -0
- package/dist/state/index.d.ts +1 -1
- package/dist/store-DLeqKuj3.d.ts +310 -0
- package/dist/store-vgcPYo8K.js +432 -0
- package/dist/store-vgcPYo8K.js.map +1 -0
- package/dist/streams/index.d.ts +1 -1
- package/dist/streams/index.js +1 -1
- package/dist/{streams-DW-UCOUc.js → streams-CITClVer.js} +16 -3
- package/dist/streams-CITClVer.js.map +1 -0
- package/dist/{streams-Cmkj9QfW.d.ts → streams-fbG61qM8.d.ts} +2 -2
- package/dist/sub-routing.d.ts +1 -1
- package/dist/tasks/index.d.ts +1 -1
- package/dist/tasks/index.js +1 -1
- package/dist/{tasks-68DESxf0.js → tasks-CkTZNaV1.js} +2 -1
- package/dist/tasks-CkTZNaV1.js.map +1 -0
- package/dist/{tasks-9YxYtByh.d.ts → tasks-PtlB4Uyn.d.ts} +2 -2
- package/dist/tool-3PA8xjB_.js +421 -0
- package/dist/tool-3PA8xjB_.js.map +1 -0
- package/dist/tool-BPJEbwaX.d.ts +278 -0
- package/dist/transport-k2mFrtL8.d.ts +200 -0
- package/dist/turns-DCV3ycDl.js +317 -0
- package/dist/turns-DCV3ycDl.js.map +1 -0
- package/dist/voice/client.js +1 -1
- package/dist/voice/index.d.ts +2 -2
- package/dist/voice/index.js +1 -1
- package/dist/websearch/index.d.ts +58 -0
- package/dist/websearch/index.js +2 -0
- package/dist/websearch/tools/ai-sdk.d.ts +77 -0
- package/dist/websearch/tools/ai-sdk.js +46 -0
- package/dist/websearch/tools/ai-sdk.js.map +1 -0
- package/dist/websearch/tools/pi.d.ts +82 -0
- package/dist/websearch/tools/pi.js +89 -0
- package/dist/websearch/tools/pi.js.map +1 -0
- package/dist/websearch/tools/tanstack-ai.d.ts +71 -0
- package/dist/websearch/tools/tanstack-ai.js +46 -0
- package/dist/websearch/tools/tanstack-ai.js.map +1 -0
- package/dist/websockets/index.d.ts +12 -296
- package/dist/websockets/index.js +1 -1
- package/dist/{websockets-Ci-LZFHH.js → websockets-CmENGb-Z.js} +18 -4
- package/dist/websockets-CmENGb-Z.js.map +1 -0
- package/dist/{wire-types-CrjKvDyi.d.ts → wire-types-Cv0iwjk5.d.ts} +3 -51
- package/dist/workflow-types.d.ts +1 -1
- package/dist/workflows.d.ts +1 -1
- package/dist/workflows.js +1 -1
- package/docs/browse-the-web.md +3 -0
- package/docs/harnesses/pi.md +114 -32
- package/docs/harnesses/think.md +215 -0
- package/docs/index.md +4 -3
- package/docs/lifecycle.md +40 -0
- package/docs/models-pi-ai.md +5 -5
- package/docs/search-the-web.md +133 -0
- package/package.json +126 -47
- package/dist/browser-tool-CQ10e6Kj.js.map +0 -1
- package/dist/channel-Bnm4S7T2.d.ts +0 -491
- package/dist/channels/ai-sdk.d.ts +0 -46
- package/dist/channels/ai-sdk.js +0 -120
- package/dist/channels/ai-sdk.js.map +0 -1
- package/dist/channels/email.js.map +0 -1
- package/dist/channels/index.d.ts +0 -233
- package/dist/channels/index.js +0 -608
- package/dist/channels/index.js.map +0 -1
- package/dist/channels/slack.js +0 -614
- package/dist/channels/slack.js.map +0 -1
- package/dist/channels/tanstack-ai.d.ts +0 -39
- package/dist/channels/tanstack-ai.js +0 -17
- package/dist/channels/tanstack-ai.js.map +0 -1
- package/dist/channels/telegram.js +0 -427
- package/dist/channels/telegram.js.map +0 -1
- package/dist/channels/voice.d.ts +0 -45
- package/dist/channels/voice.js +0 -122
- package/dist/channels/voice.js.map +0 -1
- package/dist/harnesses/pi/index.js.map +0 -1
- package/dist/images-iiTDSyRu.js.map +0 -1
- package/dist/index-BB0kqhIz.d.ts +0 -101
- package/dist/ingress-BfetZbMO.js +0 -83
- package/dist/ingress-BfetZbMO.js.map +0 -1
- package/dist/internal-CYlgHl1l.js +0 -59
- package/dist/internal-CYlgHl1l.js.map +0 -1
- package/dist/models/ai-sdk/index.js.map +0 -1
- package/dist/protocol-kHsr-f0X.js.map +0 -1
- package/dist/sessions/index.js.map +0 -1
- package/dist/streams-DW-UCOUc.js.map +0 -1
- package/dist/surface-bZZJqBka.js +0 -17
- package/dist/surface-bZZJqBka.js.map +0 -1
- package/dist/tasks-68DESxf0.js.map +0 -1
- package/dist/tool-schema-CBjGPrsQ.js +0 -31
- package/dist/tool-schema-CBjGPrsQ.js.map +0 -1
- package/dist/websockets-Ci-LZFHH.js.map +0 -1
- package/docs/channels.md +0 -323
package/dist/cli.js
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{createRequire as e}from"node:module";import{execSync as t,spawn as n}from"node:child_process";import{performance as r}from"node:perf_hooks";import*as i from"node:os";import*as a from"node:path";import{dirname as o,join as s}from"node:path";import{fileURLToPath as c}from"node:url";import{EventEmitter as l}from"events";import*as u from"node:fs";var d=Object.create,f=Object.defineProperty,p=Object.getOwnPropertyDescriptor,m=Object.getOwnPropertyNames,h=Object.getPrototypeOf,g=Object.prototype.hasOwnProperty,_=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),v=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=m(t),a=0,o=i.length,s;a<o;a++)s=i[a],!g.call(e,s)&&s!==n&&f(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=p(t,s))||r.enumerable});return e},y=(e,t,n)=>(n=e==null?{}:d(h(e)),v(t||!e||!e.__esModule?f(n,`default`,{value:e,enumerable:!0}):n,e));function b(e){return`cf-access-token`in e||`cf-access-client-id`in e||/(?:^|;\s*)CF_Authorization=/.test(e.cookie??``)}async function x(e,t,n=C){if(b(t))return{};let r=new URL(e);r.protocol=r.protocol===`ws:`?`http:`:`https:`,r.search=``;let i=r.toString();if(!await S(i,n))return{};let a=async()=>{let{code:e,stdout:t}=await n.run(`cloudflared`,[`access`,`token`,`-app=${i}`],!1),r=t.trim();return e===0&&/^[\w-]+\.[\w-]+\.[\w-]+$/.test(r)?r:void 0},o=await a();if(o===void 0&&(n.log(`${i} is behind Cloudflare Access; logging in.`),await n.run(`cloudflared`,[`access`,`login`,i],!0),o=await a()),o===void 0)throw Error(`Could not get a Cloudflare Access token for ${i}. Run \`cloudflared access login ${i}\`, or pass --header cf-access-token=<token>.`);return{"cf-access-token":o}}async function S(e,t){try{let n=await t.fetch(e,{redirect:`manual`}),r=n.headers.get(`location`);return n.status<300||n.status>=400||!r?!1:new URL(r,e).hostname.endsWith(`.cloudflareaccess.com`)}catch{return!1}}const C={fetch:(e,t)=>fetch(e,t),run:(e,t,r)=>new Promise((i,a)=>{let o=n(e,t,{stdio:r?`inherit`:[`ignore`,`pipe`,`ignore`]}),s=``;o.stdout?.on(`data`,e=>{s+=e.toString()}),o.on(`error`,e=>{a(e.code===`ENOENT`?Error(`This URL is behind Cloudflare Access. Install cloudflared, or pass --header cf-access-token=<token>.`):e)}),o.on(`close`,e=>i({code:e??1,stdout:s}))}),log:e=>console.error(e)},w=`Usage: agents tui <url> [--as <participant>] [--header <name=value>]...
|
|
3
|
+
|
|
4
|
+
<url> The conversation's Web Channel URL, http(s) or ws(s)
|
|
5
|
+
|
|
6
|
+
Commands, when the agent supports them:
|
|
7
|
+
/new Start a new conversation and follow it
|
|
8
|
+
/fork Fork this conversation and follow the fork
|
|
9
|
+
/reset [note] Start this conversation over, with an optional handoff note
|
|
10
|
+
/conversations List the agent's conversations; ● marks the one followed
|
|
11
|
+
/switch <id> Follow another conversation (a unique id prefix is enough)
|
|
12
|
+
|
|
13
|
+
Options:
|
|
14
|
+
--as Sets the "as" query parameter (demo agents read it as the participant)
|
|
15
|
+
--header Adds a header to the WebSocket upgrade; repeatable
|
|
16
|
+
|
|
17
|
+
Cloudflare Access:
|
|
18
|
+
A URL behind Access gets a token from cloudflared, which logs in through
|
|
19
|
+
the browser the first time. Or set CF_ACCESS_CLIENT_ID and
|
|
20
|
+
CF_ACCESS_CLIENT_SECRET to send a service token instead.`;var T=class extends Error{};function E(e,t={}){let n,r,i={};for(let t=0;t<e.length;t++){let a=e[t],[o,s]=D(a),c=()=>{if(s!==void 0)return s;let n=e[++t];if(n===void 0)throw new T(`${o} needs a value`);return n};if(o===`--as`)r=c();else if(o===`--header`||o===`-H`){let[e,t]=ee(c());i[e]=t}else if(a.startsWith(`-`))throw new T(`Unknown flag ${a}`);else if(n===void 0)n=a;else throw new T(`Unexpected argument ${a}`)}if(n===void 0)throw new T(`Missing <url>`);let a=te(n);return r!==void 0&&a.searchParams.set(`as`,r),{url:a.toString(),headers:{...O(t),...i}}}function D(e){if(!e.startsWith(`--`))return[e,void 0];let t=e.indexOf(`=`);return t===-1?[e,void 0]:[e.slice(0,t),e.slice(t+1)]}function ee(e){let t=[e.indexOf(`=`),e.indexOf(`:`)].filter(e=>e>0).sort((e,t)=>e-t)[0];if(t===void 0)throw new T(`Header "${e}" is not name=value`);return[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}function te(e){let t;try{t=new URL(e)}catch{throw new T(`"${e}" is not a URL`)}let n={"http:":`ws:`,"https:":`wss:`,"ws:":`ws:`,"wss:":`wss:`}[t.protocol];if(!n)throw new T(`Unsupported protocol ${t.protocol}`);return t.protocol=n,t.hash=``,t}function O(e){let t=e.CF_ACCESS_CLIENT_ID,n=e.CF_ACCESS_CLIENT_SECRET;if(!t&&!n)return{};if(!t||!n)throw new T(`Set both CF_ACCESS_CLIENT_ID and CF_ACCESS_CLIENT_SECRET`);return{"cf-access-client-id":t,"cf-access-client-secret":n}}function ne(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var k=ne();function re(e){k=e}var A={exec:()=>null};function j(e){let t=[];return n=>{let r=Math.max(0,Math.min(3,n-1)),i=t[r];return i||(i=e(r),t[r]=i),i}}function M(e,t=``){let n=typeof e==`string`?e:e.source,r={replace:(e,t)=>{let i=typeof t==`string`?t:t.source;return i=i.replace(N.caret,`$1`),n=n.replace(e,i),r},getRegex:()=>new RegExp(n,t)};return r}var ie=((e=``)=>{try{return!!RegExp(`(?<=1)(?<!1)`+e)}catch{return!1}})(),N={codeRemoveIndent:/^(?: {1,4}| {0,3}\t)/gm,outputLinkReplace:/\\([\[\]])/g,indentCodeCompensation:/^(\s+)(?:```)/,beginningSpace:/^\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\n/g,tabCharGlobal:/\t/g,multipleSpaceGlobal:/\s+/g,blankLine:/^[ \t]*$/,doubleBlankLine:/\n[ \t]*\n[ \t]*$/,blockquoteStart:/^ {0,3}>/,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:/^ *:-+ *$/,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,escapeTest:/[&<>"']/,escapeReplace:/[&<>"']/g,escapeTestNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/,escapeReplaceNoEncode:/[<>"']|&(?!(#\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\w+);)/g,caret:/(^|[^\[])\^/g,percentDecode:/%25/g,findPipe:/\|/g,splitPipe:/ \|/,slashPipe:/\\\|/g,carriageReturn:/\r\n|\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\S*/,endingNewline:/\n$/,listItemRegex:e=>RegExp(`^( {0,3}${e})((?:[ ][^\\n]*)?(?:\\n|$))`),nextBulletRegex:j(e=>RegExp(`^ {0,${e}}(?:[*+-]|\\d{1,9}[.)])((?:[ ][^\\n]*)?(?:\\n|$))`)),hrRegex:j(e=>RegExp(`^ {0,${e}}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})(?:\\n+|$)`)),fencesBeginRegex:j(e=>RegExp(`^ {0,${e}}(?:\`\`\`|~~~)`)),headingBeginRegex:j(e=>RegExp(`^ {0,${e}}#`)),htmlBeginRegex:j(e=>RegExp(`^ {0,${e}}<(?:[a-z].*>|!--)`,`i`)),blockquoteBeginRegex:j(e=>RegExp(`^ {0,${e}}>`))},ae=/^(?:[ \t]*(?:\n|$))+/,oe=/^((?: {4}| {0,3}\t)[^\n]+(?:\n(?:[ \t]*(?:\n|$))*)?)+/,se=/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/,ce=/^ {0,3}((?:-[\t ]*){3,}|(?:_[ \t]*){3,}|(?:\*[ \t]*){3,})(?:\n+|$)/,le=/^ {0,3}(#{1,6})(?=\s|$)(.*)(?:\n+|$)/,ue=/ {0,3}(?:[*+-]|\d{1,9}[.)])/,de=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\n(?!\s*?\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\n {0,3}(=+|-+) *(?:\n+|$)/,fe=M(de).replace(/bull/g,ue).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(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/\|table/g,``).getRegex(),pe=M(de).replace(/bull/g,ue).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(/html/g,/ {0,3}<[^\n>]+>\n/).replace(/table/g,/ {0,3}\|?(?:[:\- ]*\|)+[\:\- ]*\n/).getRegex(),me=/^([^\n]+(?:\n(?!hr|heading|lheading|blockquote|fences|list|html|table|[ \t]+\n)[^\n]+)*)/,he=/^[^\n]+/,ge=/(?!\s*\])(?:\\[\s\S]|[^\[\]\\])+/,_e=M(/^ {0,3}\[(label)\]: *(?:\n[ \t]*)?([^<\s][^\s]*|<.*?>)(?:(?: +(?:\n[ \t]*)?| *\n[ \t]*)(title))? *(?:\n+|$)/).replace(`label`,ge).replace(`title`,/(?:"(?:\\"?|[^"\\])*"|'[^'\n]*(?:\n[^'\n]+)*\n?'|\([^()]*\))/).getRegex(),ve=M(/^(bull)([ \t][^\n]*?)?(?:\n|$)/).replace(/bull/g,ue).getRegex(),ye=`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|table|tbody|td|tfoot|th|thead|title|tr|track|ul`,be=/<!--(?:-?>|[\s\S]*?(?:-->|$))/,xe=M(`^ {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)(?: +|\\n|/?>)[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|<(?!script|pre|style|textarea)([a-z][\\w-]*)(?:attribute)*? */?>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$)|</(?!script|pre|style|textarea)[a-z][\\w-]*\\s*>(?=[ \\t]*(?:\\n|$))[\\s\\S]*?(?:(?:\\n[ ]*)+\\n|$))`,`i`).replace(`comment`,be).replace(`tag`,ye).replace(`attribute`,/ +[a-zA-Z:_][\w.:-]*(?: *= *"[^"\n]*"| *= *'[^'\n]*'| *= *[^\s"'=<>`]+)?/).getRegex(),Se=e=>M(me).replace(`hr`,ce).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`,e).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ye).getRegex(),Ce=Se(/ {0,3}(?:[*+-]|1[.)])[ \t]+[^ \t\n]/),we=Se(/ {0,3}(?:[*+-]|\d{1,9}[.)])(?:[ \t]|\n|$)/),Te={blockquote:M(/^( {0,3}> ?(paragraph|[^\n]*)(?:\n|$))+/).replace(`paragraph`,we).getRegex(),code:oe,def:_e,fences:se,heading:le,hr:ce,html:xe,lheading:fe,list:ve,newline:ae,paragraph:Ce,table:A,text:he},Ee=M(`^ *([^\\n ].*)\\n {0,3}((?:\\| *)?:?-+:? *(?:\\| *:?-+:? *)*(?:\\| *)?)(?:\\n((?:(?! *\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\n|$))*)\\n*|$)`).replace(`hr`,ce).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`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ye).getRegex(),De={...Te,lheading:pe,table:Ee,paragraph:M(me).replace(`hr`,ce).replace(`heading`,` {0,3}#{1,6}(?:\\s|$)`).replace(`|lheading`,``).replace(`table`,Ee).replace(`blockquote`,` {0,3}>`).replace(`fences`," {0,3}(?:`{3,}(?=[^`\\n]*(?:\\n|$))|~~~)[^\\n]*(?:\\n|$)").replace(`list`,` {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]`).replace(`html`,`</?(?:tag)(?: +|\\n|/?>)|<(?:script|pre|style|textarea|!--)`).replace(`tag`,ye).getRegex()},Oe={...Te,html:M(`^ *(?:comment *(?:\\n|\\s*$)|<(tag)[\\s\\S]+?</\\1> *(?:\\n{2,}|\\s*$)|<tag(?:"[^"]*"|'[^']*'|\\s[^'"/>\\s]*)*?/?> *(?:\\n{2,}|\\s*$))`).replace(`comment`,be).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:A,lheading:/^(.+?)\n {0,3}(=+|-+) *(?:\n+|$)/,paragraph:M(me).replace(`hr`,ce).replace(`heading`,` *#{1,6} *[^
|
|
21
|
+
]`).replace(`lheading`,fe).replace(`|table`,``).replace(`blockquote`,` {0,3}>`).replace(`|fences`,``).replace(`|list`,``).replace(`|html`,``).replace(`|tag`,``).getRegex()},ke=/^\\([!"#$%&'()*+,\-./:;<=>?@\[\]\\^_`{|}~])/,Ae=/^(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/,je=/^( {2,}|\\)\n(?!\s*$)/,Me=/^(`+|[^`])(?:(?= {2,}\n)|[\s\S]*?(?:(?=[\\<!\[`*_]|\b_|$)|[^ ](?= {2,}\n)))/,P=/[\p{P}\p{S}]/u,Ne=/[\s\p{P}\p{S}]/u,F=/[^\s\p{P}\p{S}]/u,Pe=M(/^((?![*_])punctSpace)/,`u`).replace(/punctSpace/g,Ne).getRegex(),Fe=/[\p{Pi}\p{Ps}"']/u,Ie=/(?!~)[\p{P}\p{S}]/u,Le=/(?!~)[\s\p{P}\p{S}]/u,Re=/(?:[^\s\p{P}\p{S}]|~)/u,ze=M(/link|precode-code|html/,`g`).replace(`link`,/\[(?:[^\[\]`]|(?<a>`+)[^`]+\k<a>(?!`))*?\]\((?:\\[\s\S]|[^\\\(\)]|\((?:\\[\s\S]|[^\\\(\)])*\))*\)/).replace(`precode-`,ie?"(?<!`)()":"(^^|[^`])").replace(`code`,/(?<b>`+)[^`]+\k<b>(?!`)/).replace(`html`,/<(?! )[^<>]*?>/).getRegex(),Be=/^(?:\*+(?:((?!\*)punct)|([^\s*]))?)|^_+(?:((?!_)punct)|([^\s_]))?/,Ve=M(Be,`u`).replace(/punct/g,P).getRegex(),He=M(Be,`u`).replace(/punct/g,Ie).getRegex(),Ue=M(/^(?:\*+(?:((?!\*)(?!openQuote)punct)|([^\s*]))?)|^_+(?:((?!_)(?!openQuote)punct)|([^\s_]))?/,`u`).replace(/openQuote/g,Fe).replace(/punct/g,P).getRegex(),We=`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)punctSpace(\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|notPunctSpace(\\*+)(?=notPunctSpace)`,Ge=M(We,`gu`).replace(/notPunctSpace/g,F).replace(/punctSpace/g,Ne).replace(/punct/g,P).getRegex(),Ke=M(We,`gu`).replace(/notPunctSpace/g,Re).replace(/punctSpace/g,Le).replace(/punct/g,Ie).getRegex(),qe=M(`^[^_*]*?__[^_*]*?\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\*)punct(\\*+)(?=[\\s]|$)|notPunctSpace(\\*+)(?!\\*)(?=punctSpace|$)|(?!\\*)[\\s](\\*+)(?=notPunctSpace)|[\\s](\\*+)(?!\\*)(?=punct)|(?!\\*)punct(\\*+)(?!\\*)(?=punct)|(?:(?!\\*)punct|notPunctSpace)(\\*+)(?!\\*)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,F).replace(/punctSpace/g,Ne).replace(/punct/g,P).getRegex(),Je=M(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)`,`gu`).replace(/notPunctSpace/g,F).replace(/punctSpace/g,Ne).replace(/punct/g,P).getRegex(),Ye=M(`^[^_*]*?\\*\\*[^_*]*?_[^_*]*?(?=\\*\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)[\\s](_+)(?=notPunctSpace)|[\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)|(?:(?!_)punct|notPunctSpace)(_+)(?!_)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,F).replace(/punctSpace/g,Ne).replace(/punct/g,P).getRegex(),Xe=M(/^~~?(?:((?!~)punct)|[^\s~])/,`u`).replace(/punct/g,P).getRegex(),Ze=M(`^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)`,`gu`).replace(/notPunctSpace/g,F).replace(/punctSpace/g,Ne).replace(/punct/g,P).getRegex(),Qe=M(/\\(punct)/,`gu`).replace(/punct/g,P).getRegex(),$e=M(/^<(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(),et=M(be).replace(`(?:-->|$)`,`-->`).getRegex(),tt=M(`^comment|^</[a-zA-Z][\\w:-]*\\s*>|^<[a-zA-Z][\\w-]*(?:attribute)*?\\s*/?>|^<\\?[\\s\\S]*?\\?>|^<![a-zA-Z]+\\s[\\s\\S]*?>|^<!\\[CDATA\\[[\\s\\S]*?\\]\\]>`).replace(`comment`,et).replace(`attribute`,/\s+[a-zA-Z:_][\w.:-]*(?:\s*=\s*"[^"]*"|\s*=\s*'[^']*'|\s*=\s*[^\s"'=<>`]+)?/).getRegex(),nt=/(?:\[(?:\\[\s\S]|[^\[\]\\])*\]|\\[\s\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\])|[^\[\]\\`])*?/,rt=M(/^!?\[(label)\]\(\s*(href)(?:(?:[ \t]+(?:\n[ \t]*)?|\n[ \t]*)(title))?\s*\)/).replace(`label`,nt).replace(`href`,/<(?:\\.|[^\n<>\\])+>|[^ \t\n\x00-\x1f]+|(?=\))/).replace(`title`,/"(?:\\"?|[^"\\])*"|'(?:\\'?|[^'\\])*'|\((?:\\\)?|[^)\\])*\)/).getRegex(),it=M(/^!?\[(label)\]\[(ref)\]/).replace(`label`,nt).replace(`ref`,ge).getRegex(),at=M(/^!?\[(ref)\](?:\[\])?/).replace(`ref`,ge).getRegex(),ot=M(`reflink|nolink(?!\\()`,`g`).replace(`reflink`,it).replace(`nolink`,at).getRegex(),st=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,ct={_backpedal:A,anyPunctuation:Qe,autolink:$e,blockSkip:ze,br:je,code:Ae,del:A,delLDelim:A,delRDelim:A,emStrongLDelim:Ve,emStrongRDelimAst:Ge,emStrongRDelimUnd:Je,escape:ke,link:rt,nolink:at,punctuation:Pe,reflink:it,reflinkSearch:ot,tag:tt,text:Me,url:A},lt={...ct,emStrongLDelim:Ue,emStrongRDelimAst:qe,emStrongRDelimUnd:Ye,link:M(/^!?\[(label)\]\((.*?)\)/).replace(`label`,nt).getRegex(),reflink:M(/^!?\[(label)\]\s*\[([^\]]*)\]/).replace(`label`,nt).getRegex()},ut={...ct,emStrongRDelimAst:Ke,emStrongLDelim:He,delLDelim:Xe,delRDelim:Ze,url:M(/^((?:protocol):\/\/|www\.)(?:[a-zA-Z0-9\-]+\.?)+[^\s<]*|^email/).replace(`protocol`,st).replace(`email`,/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\([^)]*\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\s~])((?:\\[\s\S]|[^\\])*?(?:\\[\s\S]|[^\s~\\]))\1(?=[^~]|$)/,text:M(/^(`+|~+|[^`~])(?:(?=[`~])|(?= {2,}\n)|(?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)|[\s\S]*?(?:(?=[\\<!\[`*~_]|\b_|protocol:\/\/|www\.|$)|[^ ](?= {2,}\n)|[^a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-](?=[a-zA-Z0-9.!#$%&'*+\/=?_`{\|}~-]+@)))/).replace(`protocol`,st).getRegex()},dt={...ut,br:M(je).replace(`{2,}`,`*`).getRegex(),text:M(ut.text).replace(`\\b_`,`\\b_| {2,}\\n`).replace(/\{2,\}/g,`*`).getRegex()},ft={normal:Te,gfm:De,pedantic:Oe},pt={normal:ct,gfm:ut,breaks:dt,pedantic:lt},mt={"&":`&`,"<":`<`,">":`>`,'"':`"`,"'":`'`},ht=e=>mt[e];function gt(e,t){if(t){if(N.escapeTest.test(e))return e.replace(N.escapeReplace,ht)}else if(N.escapeTestNoEncode.test(e))return e.replace(N.escapeReplaceNoEncode,ht);return e}function _t(e){try{e=encodeURI(e).replace(N.percentDecode,`%`)}catch{return null}return e}function vt(e,t){let n=e.replace(N.findPipe,(e,t,n)=>{let r=!1,i=t;for(;--i>=0&&n[i]===`\\`;)r=!r;return r?`|`:` |`}).split(N.splitPipe),r=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),t)if(n.length>t)n.splice(t);else for(;n.length<t;)n.push(``);for(;r<n.length;r++)n[r]=n[r].trim().replace(N.slashPipe,`|`);return n}function yt(e,t,n){let r=e.length;if(r===0)return``;let i=0;for(;i<r;){let a=e.charAt(r-i-1);if(a===t&&!n)i++;else if(a!==t&&n)i++;else break}return e.slice(0,r-i)}function bt(e){let t=e.split(`
|
|
22
|
+
`),n=t.length-1;for(;n>=0&&N.blankLine.test(t[n]);)n--;return t.length-n<=2?e:t.slice(0,n+1).join(`
|
|
23
|
+
`)}function xt(e,t){if(e.indexOf(t[1])===-1)return-1;let n=0;for(let r=0;r<e.length;r++)if(e[r]===`\\`)r++;else if(e[r]===t[0])n++;else if(e[r]===t[1]&&(n--,n<0))return r;return n>0?-2:-1}function St(e,t=0){let n=t,r=``;for(let t of e)if(t===` `){let e=4-n%4;r+=` `.repeat(e),n+=e}else r+=t,n++;return r}function Ct(e,t,n,r,i){let a=t.href,o=t.title||null,s=e[1].replace(i.other.outputLinkReplace,`$1`),c=e[0].charAt(0)===`!`;r.state.inLink=!0;let l=r.state.linkEmitted,u=r.state.inRawBlock;r.state.linkEmitted=!1;let d=r.inlineTokens(s),f=r.state.linkEmitted;if(r.state.linkEmitted=l,r.state.inLink=!1,!c){if(f){r.state.inRawBlock=u;return}r.state.linkEmitted=!0}return{type:c?`image`:`link`,raw:n,href:a,title:o,text:s,tokens:d}}function wt(e,t,n){let r=e.match(n.other.indentCodeCompensation);if(r===null)return t;let i=r[1];return t.split(`
|
|
24
|
+
`).map(e=>{let t=e.match(n.other.beginningSpace);if(t===null)return e;let[r]=t;return r.length>=i.length?e.slice(i.length):e}).join(`
|
|
25
|
+
`)}var Tt=class{options;rules;lexer;constructor(e){this.options=e||k}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:`space`,raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let e=this.options.pedantic?t[0]:bt(t[0]);return{type:`code`,raw:e,codeBlockStyle:`indented`,text:e.replace(this.rules.other.codeRemoveIndent,``)}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let e=t[0],n=wt(e,t[3]||``,this.rules);return{type:`code`,raw:e,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,`$1`):t[2],text:n}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let e=t[2].trim();if(this.rules.other.endingHash.test(e)){let t=yt(e,`#`);(this.options.pedantic||!t||this.rules.other.endingSpaceChar.test(t))&&(e=t.trim())}return{type:`heading`,raw:yt(t[0],`
|
|
26
|
+
`),depth:t[1].length,text:e,tokens:this.lexer.inline(e)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:`hr`,raw:yt(t[0],`
|
|
27
|
+
`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let e=yt(t[0],`
|
|
28
|
+
`).split(`
|
|
29
|
+
`),n=``,r=``,i=[];for(;e.length>0;){let t=!1,a=[],o;for(o=0;o<e.length;o++)if(this.rules.other.blockquoteStart.test(e[o]))a.push(e[o]),t=!0;else if(!t)a.push(e[o]);else break;e=e.slice(o);let s=a.join(`
|
|
30
|
+
`),c=s.replace(this.rules.other.blockquoteSetextReplace,`
|
|
31
|
+
$1`).replace(this.rules.other.blockquoteSetextReplace2,``);n=n?`${n}
|
|
32
|
+
${s}`:s,r=r?`${r}
|
|
33
|
+
${c}`:c;let l=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(c,i,!0),this.lexer.state.top=l,e.length===0)break;let u=i.at(-1);if(u?.type===`code`)break;if(u?.type===`blockquote`){let t=u,a=e.join(`
|
|
34
|
+
`),o=t.raw+`
|
|
35
|
+
`+a.replace(this.rules.other.blockquoteSetextReplace2,``),s=this.blockquote(o);i[i.length-1]=s,n=`${n}
|
|
36
|
+
${a}`,r=r.substring(0,r.length-t.text.length)+s.text;break}else if(u?.type===`list`){let t=u,a=t.raw+`
|
|
37
|
+
`+e.join(`
|
|
38
|
+
`),o=this.list(a);i[i.length-1]=o,n=n.substring(0,n.length-u.raw.length)+o.raw,r=r.substring(0,r.length-t.raw.length)+o.raw,e=a.substring(i.at(-1).raw.length).split(`
|
|
39
|
+
`);continue}}return{type:`blockquote`,raw:n,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),r=n.length>1,i={type:`list`,raw:``,ordered:r,start:r?+n.slice(0,-1):``,loose:!1,items:[]};n=r?`\\d{1,9}\\${n.slice(-1)}`:`\\${n}`,this.options.pedantic&&(n=r?n:`[*+-]`);let a=this.rules.other.listItemRegex(n),o=!1;for(;e;){let n=!1,r=``,s=``;if(!(t=a.exec(e))||this.rules.block.hr.test(e))break;r=t[0],e=e.substring(r.length);let c=St(t[2].split(`
|
|
40
|
+
`,1)[0],t[1].length),l=e.split(`
|
|
41
|
+
`,1)[0],u=!c.trim(),d=0;if(this.options.pedantic?(d=2,s=c.trimStart()):u?d=t[1].length+1:(d=c.search(this.rules.other.nonSpaceChar),d=d>4?1:d,s=c.slice(d),d+=t[1].length),u&&this.rules.other.blankLine.test(l)&&(r+=l+`
|
|
42
|
+
`,e=e.substring(l.length+1),n=!0),!n){let t=this.rules.other.nextBulletRegex(d),n=this.rules.other.hrRegex(d),i=this.rules.other.fencesBeginRegex(d),a=this.rules.other.headingBeginRegex(d),o=this.rules.other.htmlBeginRegex(d),f=this.rules.other.blockquoteBeginRegex(d);for(;e;){let p=e.split(`
|
|
43
|
+
`,1)[0],m;if(l=p,this.options.pedantic?(l=l.replace(this.rules.other.listReplaceNesting,` `),m=l):m=l.replace(this.rules.other.tabCharGlobal,` `),i.test(l)||a.test(l)||o.test(l)||f.test(l)||t.test(l)||n.test(l))break;if(m.search(this.rules.other.nonSpaceChar)>=d||!l.trim())s+=`
|
|
44
|
+
`+m.slice(d);else{if(u||c.replace(this.rules.other.tabCharGlobal,` `).search(this.rules.other.nonSpaceChar)>=4||i.test(c)||a.test(c)||n.test(c))break;s+=`
|
|
45
|
+
`+l}u=!l.trim(),r+=p+`
|
|
46
|
+
`,e=e.substring(p.length+1),c=m.slice(d)}}i.loose||(o?i.loose=!0:this.rules.other.doubleBlankLine.test(r)&&(o=!0)),i.items.push({type:`list_item`,raw:r,task:!!this.options.gfm&&this.rules.other.listIsTask.test(s),loose:!1,text:s,tokens:[]}),i.raw+=r}let s=i.items.at(-1);if(s)s.raw=s.raw.trimEnd(),s.text=s.text.trimEnd();else return;i.raw=i.raw.trimEnd();for(let e of i.items)if(this.lexer.state.top=!1,e.tokens=this.lexer.blockTokens(e.text,[]),!i.loose){let t=e.tokens.filter(e=>e.type===`space`);i.loose=t.length>0&&t.some(e=>this.rules.other.anyLine.test(e.raw))}for(let e of i.items){let t=e.tokens[0];if(e.task&&(t?.type===`text`||t?.type===`paragraph`)){e.text=e.text.replace(this.rules.other.listReplaceTask,``),t.raw=t.raw.replace(this.rules.other.listReplaceTask,``),t.text=t.text.replace(this.rules.other.listReplaceTask,``);for(let e=this.lexer.inlineQueue.length-1;e>=0;e--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[e].src)){this.lexer.inlineQueue[e].src=this.lexer.inlineQueue[e].src.replace(this.rules.other.listReplaceTask,``);break}let n=this.rules.other.listTaskCheckbox.exec(e.raw);if(n){let t={type:`checkbox`,raw:n[0]+` `,checked:n[0]!==`[ ]`};e.checked=t.checked,i.loose?e.tokens[0]&&[`paragraph`,`text`].includes(e.tokens[0].type)&&`tokens`in e.tokens[0]&&e.tokens[0].tokens?(e.tokens[0].raw=t.raw+e.tokens[0].raw,e.tokens[0].text=t.raw+e.tokens[0].text,e.tokens[0].tokens.unshift(t)):e.tokens.unshift({type:`paragraph`,raw:t.raw,text:t.raw,tokens:[t]}):e.tokens.unshift(t)}}else e.task&&=!1}if(i.loose)for(let e of i.items){e.loose=!0;for(let t of e.tokens)t.type===`text`&&(t.type=`paragraph`)}return i}}html(e){let t=this.rules.block.html.exec(e);if(t){let e=bt(t[0]);return{type:`html`,block:!0,raw:e,pre:t[1]===`pre`||t[1]===`script`||t[1]===`style`,text:e}}}def(e){let t=this.rules.block.def.exec(e);if(t){let e=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,` `),n=t[2]?t[2].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:e,raw:yt(t[0],`
|
|
47
|
+
`),href:n,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=vt(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,``).split(`|`),i=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,``).split(`
|
|
48
|
+
`):[],a={type:`table`,raw:yt(t[0],`
|
|
49
|
+
`),header:[],align:[],rows:[]};if(n.length===r.length){for(let e of r)this.rules.other.tableAlignRight.test(e)?a.align.push(`right`):this.rules.other.tableAlignCenter.test(e)?a.align.push(`center`):this.rules.other.tableAlignLeft.test(e)?a.align.push(`left`):a.align.push(null);for(let e=0;e<n.length;e++)a.header.push({text:n[e],tokens:this.lexer.inline(n[e]),header:!0,align:a.align[e]});for(let e of i)a.rows.push(vt(e,a.header.length).map((e,t)=>({text:e,tokens:this.lexer.inline(e),header:!1,align:a.align[t]})));return a}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let e=t[1].trim();return{type:`heading`,raw:yt(t[0],`
|
|
50
|
+
`),depth:t[2].charAt(0)===`=`?1:2,text:e,tokens:this.lexer.inline(e)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let e=t[1].charAt(t[1].length-1)===`
|
|
51
|
+
`?t[1].slice(0,-1):t[1];return{type:`paragraph`,raw:t[0],text:e,tokens:this.lexer.inline(e)}}}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.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){let t=this.rules.inline.link.exec(e);if(t){let e=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(e)){if(!this.rules.other.endAngleBracket.test(e))return;let t=yt(e.slice(0,-1),`\\`);if((e.length-t.length)%2==0)return}else{let e=xt(t[2],`()`);if(e===-2)return;if(e>-1){let n=(t[0].indexOf(`!`)===0?5:4)+t[1].length+e;t[2]=t[2].substring(0,e),t[0]=t[0].substring(0,n).trim(),t[3]=``}}let n=t[2],r=``;if(this.options.pedantic){let e=this.rules.other.pedanticHrefTitle.exec(n);e&&(n=e[1],r=e[3])}else r=t[3]?t[3].slice(1,-1):``;return n=n.trim(),this.rules.other.startAngleBracket.test(n)&&(n=this.options.pedantic&&!this.rules.other.endAngleBracket.test(e)?n.slice(1):n.slice(1,-1)),Ct(t,{href:n&&n.replace(this.rules.inline.anyPunctuation,`$1`),title:r&&r.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))||(n=this.rules.inline.nolink.exec(e))){let e=t[(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,` `).toLowerCase()];if(!e){let e=n[0].charAt(0);return{type:`text`,raw:e,text:e}}return Ct(n,e,n[0],this.lexer,this.rules)}}emStrong(e,t,n=``){let r=this.rules.inline.emStrongLDelim.exec(e);if(!(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&n.match(this.rules.other.unicodeAlphaNumeric))&&(!(r[1]||r[3])||!n||this.rules.inline.punctuation.exec(n))){let i=[...r[0]].length-1,a,o,s=i,c=0,l=r[0][0],u=n===l,d=l===`*`?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(d.lastIndex=0,t=t.slice(-1*e.length+i);(r=d.exec(t))!==null;){if(a=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!a)continue;if(o=[...a].length,r[3]||r[4]){s+=o;continue}else if(r[5]||r[6]){if(i%3&&!((i+o)%3)){c+=o;continue}if(u)break}if(s-=o,s>0)continue;o=Math.min(o,o+s+c);let t=[...r[0]][0].length,n=e.slice(0,i+r.index+t+o);if(Math.min(i,o)%2){let e=n.slice(1,-1);return{type:`em`,raw:n,text:e,tokens:this.lexer.inlineTokens(e)}}let l=n.slice(2,-2);return{type:`strong`,raw:n,text:l,tokens:this.lexer.inlineTokens(l)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let e=t[2].replace(this.rules.other.newLineCharGlobal,` `),n=this.rules.other.nonSpaceChar.test(e),r=this.rules.other.startingSpaceChar.test(e)&&this.rules.other.endingSpaceChar.test(e);return n&&r&&(e=e.substring(1,e.length-1)),{type:`codespan`,raw:t[0],text:e}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:`br`,raw:t[0]}}del(e,t,n=``){let r=this.rules.inline.delLDelim.exec(e);if(r&&(!r[1]||!n||this.rules.inline.punctuation.exec(n))){let n=[...r[0]].length-1,i,a,o=n,s=this.rules.inline.delRDelim;for(s.lastIndex=0,t=t.slice(-1*e.length+n);(r=s.exec(t))!==null;){if(i=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!i||(a=[...i].length,a!==n))continue;if(r[3]||r[4]){o+=a;continue}if(o-=a,o>0)continue;a=Math.min(a,a+o);let t=[...r[0]][0].length,s=e.slice(0,n+r.index+t+a),c=s.slice(n,-n);return{type:`del`,raw:s,text:c,tokens:this.lexer.inlineTokens(c)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let e,n;return t[2]===`@`?(e=t[1],n=`mailto:`+e):(e=t[1],n=e),{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let e,n;if(t[2]===`@`)e=t[0],n=`mailto:`+e;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??``;while(r!==t[0]);e=t[0],n=t[1]===`www.`?`http://`+t[0]:t[0]}return{type:`link`,raw:t[0],text:e,href:n,tokens:[{type:`text`,raw:e,text:e}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let e=this.lexer.state.inRawBlock;return{type:`text`,raw:t[0],text:t[0],escaped:e}}}},Et=class e{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||k,this.options.tokenizer=this.options.tokenizer||new Tt,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,linkEmitted:!1,top:!0};let t={other:N,block:ft.normal,inline:pt.normal};this.options.pedantic?(t.block=ft.pedantic,t.inline=pt.pedantic):this.options.gfm&&(t.block=ft.gfm,this.options.breaks?t.inline=pt.breaks:t.inline=pt.gfm),this.tokenizer.rules=t}static get rules(){return{block:ft,inline:pt}}static lex(t,n){return new e(n).lex(t)}static lexInline(t,n){return new e(n).inlineTokens(t)}lex(e){e=e.replace(N.carriageReturn,`
|
|
52
|
+
`),this.blockTokens(e,this.tokens);for(let e=0;e<this.inlineQueue.length;e++){let t=this.inlineQueue[e];this.inlineTokens(t.src,t.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(N.tabCharGlobal,` `).replace(N.spaceLine,``));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let i;if(this.options.extensions?.block?.some(n=>(i=n.call({lexer:this},e,t))?(e=e.substring(i.raw.length),t.push(i),!0):!1))continue;if(i=this.tokenizer.space(e)){e=e.substring(i.raw.length);let n=t.at(-1);i.raw.length===1&&n!==void 0?n.raw+=`
|
|
53
|
+
`:t.push(i);continue}if(i=this.tokenizer.code(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
54
|
+
`)?``:`
|
|
55
|
+
`)+i.raw,n.text+=`
|
|
56
|
+
`+i.text,this.inlineQueue.at(-1).src=n.text):t.push(i);continue}if(i=this.tokenizer.fences(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.heading(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.hr(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.blockquote(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.list(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.html(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.def(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`paragraph`||n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
57
|
+
`)?``:`
|
|
58
|
+
`)+i.raw,n.text+=`
|
|
59
|
+
`+i.raw,this.inlineQueue.at(-1).src=n.text):this.tokens.links[i.tag]||(this.tokens.links[i.tag]={href:i.href,title:i.title},t.push(i));continue}if(i=this.tokenizer.table(e)){e=e.substring(i.raw.length),t.push(i);continue}if(i=this.tokenizer.lheading(e)){e=e.substring(i.raw.length),t.push(i);continue}let a=e;if(this.options.extensions?.startBlock){let t=1/0,n=e.slice(1),r;this.options.extensions.startBlock.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(a=e.substring(0,t+1))}if(this.state.top&&(i=this.tokenizer.paragraph(a))){let r=t.at(-1);n&&r?.type===`paragraph`?(r.raw+=(r.raw.endsWith(`
|
|
60
|
+
`)?``:`
|
|
61
|
+
`)+i.raw,r.text+=`
|
|
62
|
+
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=r.text):t.push(i),n=a.length!==e.length,e=e.substring(i.raw.length);continue}if(i=this.tokenizer.text(e)){e=e.substring(i.raw.length);let n=t.at(-1);n?.type===`text`?(n.raw+=(n.raw.endsWith(`
|
|
63
|
+
`)?``:`
|
|
64
|
+
`)+i.raw,n.text+=`
|
|
65
|
+
`+i.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=n.text):t.push(i);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 t of e.matchAll(this.tokenizer.rules.inline.reflinkSearch)){let e=t[0],n=e.lastIndexOf(`[`);if(!(e.charAt(0)===`!`||!Object.hasOwn(this.tokens.links,e.slice(n+1,-1)))&&!(n>1&&this.linkInText(e.slice(1,n-1))))return!0}return!1}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e;if(this.tokens.links&&e.includes(`[`)){let e=this.tokenizer.rules.inline.reflinkSearch,t=n=>{let r=n.lastIndexOf(`[`);if(!Object.hasOwn(this.tokens.links,n.slice(r+1,-1)))return n;if(r>1&&n.charAt(0)!==`!`){let i=n.slice(1,r-1);if(this.linkInText(i))return`[`+i.replace(e,t)+`][`+`a`.repeat(n.length-r-2)+`]`}return`[`+`a`.repeat(n.length-2)+`]`};n=n.replace(e,t)}n=n.replace(this.tokenizer.rules.inline.anyPunctuation,e=>`+`.repeat(e.length)),n=n.replace(this.tokenizer.rules.inline.blockSkip,(e,t,n)=>{let r=n?n.length:0;return e.slice(0,r)+`[`+`a`.repeat(e.length-r-2)+`]`}),n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let r=!1,i=``,a=1/0;for(;e;){if(e.length<a)a=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}r||(i=``),r=!1;let o;if(this.options.extensions?.inline?.some(n=>(o=n.call({lexer:this},e,t))?(e=e.substring(o.raw.length),t.push(o),!0):!1))continue;if(o=this.tokenizer.escape(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.tag(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.link(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(o.raw.length);let n=t.at(-1);o.type===`text`&&n?.type===`text`?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if(o=this.tokenizer.emStrong(e,n,i)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.codespan(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.br(e)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.del(e,n,i)){e=e.substring(o.raw.length),t.push(o);continue}if(o=this.tokenizer.autolink(e)){e=e.substring(o.raw.length),t.push(o);continue}if(!this.state.inLink&&(o=this.tokenizer.url(e))){e=e.substring(o.raw.length),t.push(o);continue}let s=e;if(this.options.extensions?.startInline){let t=1/0,n=e.slice(1),r;this.options.extensions.startInline.forEach(e=>{r=e.call({lexer:this},n),typeof r==`number`&&r>=0&&(t=Math.min(t,r))}),t<1/0&&t>=0&&(s=e.substring(0,t+1))}if(o=this.tokenizer.inlineText(s)){e=e.substring(o.raw.length),o.raw.slice(-1)!==`_`&&(i=o.raw.slice(-1)),r=!0;let n=t.at(-1);n?.type===`text`?(n.raw+=o.raw,n.text+=o.text):t.push(o);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=`Infinite loop on byte: `+e;if(this.options.silent)console.error(t);else throw Error(t)}},Dt=class{options;parser;constructor(e){this.options=e||k}space(e){return``}code({text:e,lang:t,escaped:n}){let r=(t||``).match(N.notSpaceStart)?.[0],i=e.replace(N.endingNewline,``)+`
|
|
66
|
+
`;return r?`<pre><code class="language-`+gt(r)+`">`+(n?i:gt(i,!0))+`</code></pre>
|
|
67
|
+
`:`<pre><code>`+(n?i:gt(i,!0))+`</code></pre>
|
|
68
|
+
`}blockquote({tokens:e}){return`<blockquote>
|
|
69
|
+
${this.parser.parse(e)}</blockquote>
|
|
70
|
+
`}html({text:e}){return e}def(e){return``}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>
|
|
71
|
+
`}hr(e){return`<hr>
|
|
72
|
+
`}list(e){let t=e.ordered,n=e.start,r=``;for(let t=0;t<e.items.length;t++){let n=e.items[t];r+=this.listitem(n)}let i=t?`ol`:`ul`,a=t&&n!==1?` start="`+n+`"`:``;return`<`+i+a+`>
|
|
73
|
+
`+r+`</`+i+`>
|
|
74
|
+
`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>
|
|
75
|
+
`}checkbox({checked:e}){return`<input `+(e?`checked="" `:``)+`disabled="" type="checkbox"> `}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>
|
|
76
|
+
`}table(e){let t=``,n=``;for(let t=0;t<e.header.length;t++)n+=this.tablecell(e.header[t]);t+=this.tablerow({text:n});let r=``;for(let t=0;t<e.rows.length;t++){let i=e.rows[t];n=``;for(let e=0;e<i.length;e++)n+=this.tablecell(i[e]);r+=this.tablerow({text:n})}return r&&=`<tbody>${r}</tbody>`,`<table>
|
|
77
|
+
<thead>
|
|
78
|
+
`+t+`</thead>
|
|
79
|
+
`+r+`</table>
|
|
80
|
+
`}tablerow({text:e}){return`<tr>
|
|
81
|
+
${e}</tr>
|
|
82
|
+
`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?`th`:`td`;return(e.align?`<${n} align="${e.align}">`:`<${n}>`)+t+`</${n}>
|
|
83
|
+
`}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>${gt(e,!0)}</code>`}br(e){return`<br>`}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let r=this.parser.parseInline(n),i=_t(e);if(i===null)return r;e=i;let a=`<a href="`+e+`"`;return t&&(a+=` title="`+gt(t)+`"`),a+=`>`+r+`</a>`,a}image({href:e,title:t,text:n,tokens:r}){r&&(n=this.parser.parseInline(r,this.parser.textRenderer));let i=_t(e);if(i===null)return gt(n);e=i;let a=`<img src="${e}" alt="${gt(n)}"`;return t&&(a+=` title="${gt(t)}"`),a+=`>`,a}text(e){return`tokens`in e&&e.tokens?this.parser.parseInline(e.tokens):`escaped`in e&&e.escaped?e.text:gt(e.text)}},Ot=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return``+e}image({text:e}){return``+e}br(){return``}checkbox({raw:e}){return e}},kt=class e{options;renderer;textRenderer;constructor(e){this.options=e||k,this.options.renderer=this.options.renderer||new Dt,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Ot}static parse(t,n){return new e(n).parse(t)}static parseInline(t,n){return new e(n).parseInline(t)}parse(e){this.renderer.parser=this;let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(this.options.extensions?.renderers?.[r.type]){let e=r,n=this.options.extensions.renderers[e.type].call({parser:this},e);if(n!==!1||![`space`,`hr`,`heading`,`code`,`table`,`blockquote`,`list`,`checkbox`,`html`,`def`,`paragraph`,`text`].includes(e.type)){t+=n||``;continue}}let i=r;switch(i.type){case`space`:t+=this.renderer.space(i);break;case`hr`:t+=this.renderer.hr(i);break;case`heading`:t+=this.renderer.heading(i);break;case`code`:t+=this.renderer.code(i);break;case`table`:t+=this.renderer.table(i);break;case`blockquote`:t+=this.renderer.blockquote(i);break;case`list`:t+=this.renderer.list(i);break;case`checkbox`:t+=this.renderer.checkbox(i);break;case`html`:t+=this.renderer.html(i);break;case`def`:t+=this.renderer.def(i);break;case`paragraph`:t+=this.renderer.paragraph(i);break;case`text`:t+=this.renderer.text(i);break;default:{let e=`Token with "`+i.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(this.options.extensions?.renderers?.[i.type]){let e=this.options.extensions.renderers[i.type].call({parser:this},i);if(e!==!1||![`escape`,`html`,`link`,`image`,`checkbox`,`strong`,`em`,`codespan`,`br`,`del`,`text`].includes(i.type)){n+=e||``;continue}}let a=i;switch(a.type){case`escape`:n+=t.text(a);break;case`html`:n+=t.html(a);break;case`link`:n+=t.link(a);break;case`image`:n+=t.image(a);break;case`checkbox`:n+=t.checkbox(a);break;case`strong`:n+=t.strong(a);break;case`em`:n+=t.em(a);break;case`codespan`:n+=t.codespan(a);break;case`br`:n+=t.br(a);break;case`del`:n+=t.del(a);break;case`text`:n+=t.text(a);break;default:{let e=`Token with "`+a.type+`" type was not found.`;if(this.options.silent)return console.error(e),``;throw Error(e)}}}return n}},At=class{options;block;constructor(e){this.options=e||k}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?Et.lex:Et.lexInline}provideParser(e=this.block){return e?kt.parse:kt.parseInline}},jt=class{defaults=ne();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=kt;Renderer=Dt;TextRenderer=Ot;Lexer=Et;Tokenizer=Tt;Hooks=At;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let r of e)switch(n=n.concat(t.call(this,r)),r.type){case`table`:{let e=r;for(let r of e.header)n=n.concat(this.walkTokens(r.tokens,t));for(let r of e.rows)for(let e of r)n=n.concat(this.walkTokens(e.tokens,t));break}case`list`:{let e=r;n=n.concat(this.walkTokens(e.items,t));break}default:{let e=r;this.defaults.extensions?.childTokens?.[e.type]?this.defaults.extensions.childTokens[e.type].forEach(r=>{let i=e[r].flat(1/0);n=n.concat(this.walkTokens(i,t))}):e.tokens&&(n=n.concat(this.walkTokens(e.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(e=>{let n={...e};if(n.async=this.defaults.async||n.async||!1,e.extensions&&(e.extensions.forEach(e=>{if(!e.name)throw Error(`extension name required`);if(`renderer`in e){let n=t.renderers[e.name];n?t.renderers[e.name]=function(...t){let r=e.renderer.apply(this,t);return r===!1&&(r=n.apply(this,t)),r}:t.renderers[e.name]=e.renderer}if(`tokenizer`in e){if(!e.level||e.level!==`block`&&e.level!==`inline`)throw Error(`extension level must be 'block' or 'inline'`);let n=t[e.level];n?n.unshift(e.tokenizer):t[e.level]=[e.tokenizer],e.start&&(e.level===`block`?t.startBlock?t.startBlock.push(e.start):t.startBlock=[e.start]:e.level===`inline`&&(t.startInline?t.startInline.push(e.start):t.startInline=[e.start]))}`childTokens`in e&&e.childTokens&&(t.childTokens[e.name]=e.childTokens)}),n.extensions=t),e.renderer){let t=this.defaults.renderer||new Dt(this.defaults);for(let n in e.renderer){if(!(n in t))throw Error(`renderer '${n}' does not exist`);if([`options`,`parser`].includes(n))continue;let r=n,i=e.renderer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n||``}}n.renderer=t}if(e.tokenizer){let t=this.defaults.tokenizer||new Tt(this.defaults);for(let n in e.tokenizer){if(!(n in t))throw Error(`tokenizer '${n}' does not exist`);if([`options`,`rules`,`lexer`].includes(n))continue;let r=n,i=e.tokenizer[r],a=t[r];t[r]=(...e)=>{let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.tokenizer=t}if(e.hooks){let t=this.defaults.hooks||new At;for(let n in e.hooks){if(!(n in t))throw Error(`hook '${n}' does not exist`);if([`options`,`block`].includes(n))continue;let r=n,i=e.hooks[r],a=t[r];At.passThroughHooks.has(n)?t[r]=e=>{if(this.defaults.async&&At.passThroughHooksRespectAsync.has(n))return(async()=>{let n=await i.call(t,e);return a.call(t,n)})();let r=i.call(t,e);return a.call(t,r)}:t[r]=(...e)=>{if(this.defaults.async)return(async()=>{let n=await i.apply(t,e);return n===!1&&(n=await a.apply(t,e)),n})();let n=i.apply(t,e);return n===!1&&(n=a.apply(t,e)),n}}n.hooks=t}if(e.walkTokens){let t=this.defaults.walkTokens,r=e.walkTokens;n.walkTokens=function(e){let n=[];return n.push(r.call(this,e)),t&&(n=n.concat(t.call(this,e))),n}}this.defaults={...this.defaults,...n}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return Et.lex(e,t??this.defaults)}parser(e,t){return kt.parse(e,t??this.defaults)}parseMarkdown(e){return(t,n)=>{let r={...n},i={...this.defaults,...r},a=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return a(Error(`marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.`));if(typeof t>`u`||t===null)return a(Error(`marked(): input parameter is undefined or null`));if(typeof t!=`string`)return a(Error(`marked(): input parameter is of type `+Object.prototype.toString.call(t)+`, string expected`));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let n=i.hooks?await i.hooks.preprocess(t):t,r=await(i.hooks?await i.hooks.provideLexer(e):e?Et.lex:Et.lexInline)(n,i),a=i.hooks?await i.hooks.processAllTokens(r):r;i.walkTokens&&await Promise.all(this.walkTokens(a,i.walkTokens));let o=await(i.hooks?await i.hooks.provideParser(e):e?kt.parse:kt.parseInline)(a,i);return i.hooks?await i.hooks.postprocess(o):o})().catch(a);try{i.hooks&&(t=i.hooks.preprocess(t));let n=(i.hooks?i.hooks.provideLexer(e):e?Et.lex:Et.lexInline)(t,i);i.hooks&&(n=i.hooks.processAllTokens(n)),i.walkTokens&&this.walkTokens(n,i.walkTokens);let r=(i.hooks?i.hooks.provideParser(e):e?kt.parse:kt.parseInline)(n,i);return i.hooks&&(r=i.hooks.postprocess(r)),r}catch(e){return a(e)}}}onError(e,t){return n=>{if(n.message+=`
|
|
84
|
+
Please report this to https://github.com/markedjs/marked.`,e){let e=`<p>An error occurred:</p><pre>`+gt(n.message+``,!0)+`</pre>`;return t?Promise.resolve(e):e}if(t)return Promise.reject(n);throw n}}},Mt=new jt;function I(e,t){return Mt.parse(e,t)}I.options=I.setOptions=function(e){return Mt.setOptions(e),I.defaults=Mt.defaults,re(I.defaults),I},I.getDefaults=ne,I.defaults=k;function Nt(...e){return Mt.use(...e),I.defaults=Mt.defaults,re(I.defaults),I}I.use=Nt,I.walkTokens=function(e,t){return Mt.walkTokens(e,t)},I.parseInline=Mt.parseInline,I.Parser=kt,I.parser=kt.parse,I.Renderer=Dt,I.TextRenderer=Ot,I.Lexer=Et,I.lexer=Et.lex,I.Tokenizer=Tt,I.Hooks=At,I.parse=I,I.options,I.setOptions,I.walkTokens,I.parseInline,kt.parse,Et.lex;const Pt=[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,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,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,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],Ft=[12288,12288,65281,65376,65504,65510],It=[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,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,101589,101631,101662,101760,101874,110576,110579,110581,110587,110589,110590,110592,110882,110898,110898,110928,110930,110933,110933,110948,110951,110960,111355,119552,119638,119648,119670,126980,126980,127183,127183,127374,127374,127377,127386,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,128728,128732,128735,128747,128748,128756,128764,128992,129003,129008,129008,129292,129338,129340,129349,129351,129535,129648,129660,129664,129674,129678,129734,129736,129736,129741,129756,129759,129770,129775,129784,131072,196605,196608,262141],Lt=(e,t)=>{let n=0,r=Math.floor(e.length/2)-1;for(;n<=r;){let i=Math.floor((n+r)/2),a=i*2;if(t<e[a])r=i-1;else if(t>e[a+1])n=i+1;else return!0}return!1},Rt=19968,[zt,Bt]=Vt(It);function Vt(e){let t=e[0],n=e[1];for(let r=0;r<e.length;r+=2){let i=e[r],a=e[r+1];if(Rt>=i&&Rt<=a)return[i,a];a-i>n-t&&(t=i,n=a)}return[t,n]}const Ht=e=>e<161||e>1114109?!1:Lt(Pt,e),Ut=e=>e<12288||e>65510?!1:Lt(Ft,e),Wt=e=>e>=zt&&e<=Bt?!0:e<4352||e>262141?!1:Lt(It,e);function Gt(e){if(!Number.isSafeInteger(e))throw TypeError(`Expected a code point, got \`${typeof e}\`.`)}function Kt(e,{ambiguousAsWide:t=!1}={}){return Gt(e),Ut(e)||Wt(e)||t&&Ht(e)?2:1}const qt=new Intl.Segmenter(void 0,{granularity:`grapheme`}),Jt=new Intl.Segmenter(void 0,{granularity:`word`});function Yt(){return qt}function Xt(){return Jt}function Zt(e){let t=e.codePointAt(0);return t>=126976&&t<=130047||t>=8960&&t<=9215||t>=9728&&t<=10175||t>=11088&&t<=11093||e.includes(`️`)||e.length>2}const Qt=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Mark}|\p{Surrogate})+$/v,$t=/^[\p{Default_Ignorable_Code_Point}\p{Control}\p{Format}\p{Mark}\p{Surrogate}]+/v,en=/^(?:\p{Default_Ignorable_Code_Point}|\p{Control}|\p{Format}|\p{Mark}|\p{Surrogate})$/v,tn=/^\p{Mark}$/v,nn=/^(?:[\p{Spacing_Mark}--[\u1734\u302E\u302F]]|[\u065F\u0F7F\u102B\u102C\u1031\u1033-\u1035\u1038\u103A-\u103E])+$/v,rn=/^\p{RGI_Emoji}$/v,an=new Map,on=/[\p{Script_Extensions=Han}\p{Script_Extensions=Hiragana}\p{Script_Extensions=Katakana}\p{Script_Extensions=Hangul}\p{Script_Extensions=Bopomofo}]/u,sn=RegExp(`(?:(?=\\p{Punctuation})${on.source}|[,.:;!?()[]{}“”‘’…—])`,`u`),cn=RegExp(`(?:\\s|${sn.source})`,`u`),ln=RegExp(`(?:^|${cn.source})`,`u`);function un(e){for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n<32||n>126)return!1}return!0}function dn(e,t){if(t<=0||e.length===0)return{text:``,width:0};if(un(e)){let n=e.slice(0,t);return{text:n,width:n.length}}let n=e.includes(`\x1B`),r=e.includes(` `);if(!n&&!r){let n=``,r=0;for(let{segment:i}of qt.segment(e)){let e=pn(i);if(r+e>t)break;n+=i,r+=e}return{text:n,width:r}}let i=``,a=0,o=0,s=``;for(;o<e.length;){let n=R(e,o);if(n){s+=n.code,o+=n.length;continue}if(e[o]===` `){if(a+3>t)break;s&&=(i+=s,``),i+=` `,a+=3,o++;continue}let r=o;for(;r<e.length&&e[r]!==` `&&!R(e,r);)r++;for(let{segment:n}of qt.segment(e.slice(o,r))){let e=pn(n);if(a+e>t)return{text:i,width:a};s&&=(i+=s,``),i+=n,a+=e}o=r}return{text:i,width:a}}function fn(e,t,n,r,i,a){let o=`\x1B[0m`,s=Sn(e),c=t+r,l;return l=n.length>0?`${e}${s}${o}${n}${o}`:`${e}${s}${o}`,a?l+` `.repeat(Math.max(0,i-c)):l}function pn(e){if(e.length===1){let t=e.charCodeAt(0);if(t>=32&&t<=126)return 1;if(t===9)return 3}if(nn.test(e))return[...e].length;if(Qt.test(e))return 0;if(Zt(e)&&rn.test(e))return 2;let t=e.replace($t,``),n=t.codePointAt(0);if(n===void 0)return 0;if(n>=127462&&n<=127487)return 2;let r=Kt(n),i=!1,a=[...t];for(let e of a.slice(1))if(nn.test(e))r+=1,i=!1;else if(tn.test(e))i=!0;else if(!en.test(e)){let t=e.codePointAt(0);i||t>=65280&&t<=65519?r+=Kt(t):(t===3635||t===3763)&&(r+=1),i=!1}return r}function L(e){if(e.length===0)return 0;let t=_n(e);if(t!==-1)return t;let n=an.get(e);if(n!==void 0)return n;let r=e;e.includes(` `)&&(r=r.replace(/\t/g,` `));let i=r.indexOf(`\x1B`);if(i!==-1){let e=``,t=0;for(;i!==-1;){let n=vn(r,i);n>0?(e+=r.slice(t,i),i+=n,t=i):i++,i=r.indexOf(`\x1B`,i)}r=e+r.slice(t)}let a=0;for(let{segment:e}of qt.segment(r))a+=pn(e);if(an.size>=512){let e=an.keys().next().value;e!==void 0&&an.delete(e)}return an.set(e,a),a}const mn=/[\u0e33\u0eb3]/,hn=/[\u0e33\u0eb3]/g;function gn(e){let t=e;if(mn.test(t)&&(t=t.replace(hn,e=>e===`ำ`?`ํา`:`ໍາ`)),!t.includes(` `))return t;let n=``,r=0;for(;r<t.length;){let e=R(t,r);if(e){n+=e.code,r+=e.length;continue}n+=t[r]===` `?` `:t[r],r++}return n}function R(e,t){let n=vn(e,t);return n>0?{code:e.substring(t,t+n),length:n}:null}function _n(e){let t=0,n=0;for(;n<e.length;){let r=e.charCodeAt(n);if(r>=32&&r<=126)t++,n++;else if(r===9)t+=3,n++;else if(r===27){let t=vn(e,n);if(t===0)return-1;n+=t}else return-1}return t}function vn(e,t){if(t>=e.length||e.charCodeAt(t)!==27)return 0;let n=e[t+1];if(n===`[`){for(let n=t+2;n<e.length;n++){let r=e.charCodeAt(n);if(r===109||r===71||r===75||r===72||r===74)return n+1-t}return 0}if(n===`]`||n===`_`){for(let n=t+2;n<e.length;n++){let r=e.charCodeAt(n);if(r===7)return n+1-t;if(r===27&&e[n+1]===`\\`)return n+2-t}return 0}return 0}function yn(e){if(!e.startsWith(`\x1B]8;`))return;let t=e.endsWith(`\x07`)?`\x07`:`\x1B\\`,n=e.slice(4,t===`\x07`?-1:-2),r=n.indexOf(`;`);if(r===-1)return;let i=n.slice(0,r),a=n.slice(r+1);return a?{params:i,url:a,terminator:t}:null}function bn(e){return`\x1b]8;${e.params};${e.url}${e.terminator}`}function xn(e){return`\x1b]8;;${e}`}function Sn(e){if(!e.includes(`\x1B]8;`))return``;let t=null,n=0;for(;n<e.length;){let r=R(e,n);if(r){let e=yn(r.code);e!==void 0&&(t=e),n+=r.length}else n++}return t?xn(t.terminator):``}var Cn=class{bold=!1;dim=!1;italic=!1;underline=!1;blink=!1;inverse=!1;hidden=!1;strikethrough=!1;fgColor=null;bgColor=null;activeHyperlink=null;process(e){let t=yn(e);if(t!==void 0){this.activeHyperlink=t;return}if(!e.endsWith(`m`))return;let n=e.match(/\x1b\[([\d;]*)m/);if(!n)return;let r=n[1];if(r===``||r===`0`){this.reset();return}let i=r.split(`;`),a=0;for(;a<i.length;){let e=Number.parseInt(i[a],10);if(e===38||e===48){if(i[a+1]===`5`&&i[a+2]!==void 0){let t=`${i[a]};${i[a+1]};${i[a+2]}`;e===38?this.fgColor=t:this.bgColor=t,a+=3;continue}else if(i[a+1]===`2`&&i[a+4]!==void 0){let t=`${i[a]};${i[a+1]};${i[a+2]};${i[a+3]};${i[a+4]}`;e===38?this.fgColor=t:this.bgColor=t,a+=5;continue}}switch(e){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.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:e>=30&&e<=37||e>=90&&e<=97?this.fgColor=String(e):(e>=40&&e<=47||e>=100&&e<=107)&&(this.bgColor=String(e));break}a++}}reset(){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 e=[];this.bold&&e.push(`1`),this.dim&&e.push(`2`),this.italic&&e.push(`3`),this.underline&&e.push(`4`),this.blink&&e.push(`5`),this.inverse&&e.push(`7`),this.hidden&&e.push(`8`),this.strikethrough&&e.push(`9`),this.fgColor&&e.push(this.fgColor),this.bgColor&&e.push(this.bgColor);let t=e.length>0?`\x1b[${e.join(`;`)}m`:``;return this.activeHyperlink&&(t+=bn(this.activeHyperlink)),t}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 e=``;return this.underline&&(e+=`\x1B[24m`),this.activeHyperlink&&(e+=xn(this.activeHyperlink.terminator)),e}};function wn(e,t){let n=e.indexOf(`\x1B`);for(;n!==-1;){let r=vn(e,n);r>0?(t.process(e.substring(n,n+r)),n+=r):n++,n=e.indexOf(`\x1B`,n)}}function*Tn(e){for(let{segment:t}of qt.segment(e))yield t}function En(e){let t=[],n=``,r=``,i=null,a=0,o=()=>{n&&(t.push(n),n=``,i=null)};for(;a<e.length;){let s=R(e,a);if(s){r+=s.code,a+=s.length;continue}let c=e.indexOf(`\x1B`,a+1);for(;c!==-1&&vn(e,c)===0;)c=e.indexOf(`\x1B`,c+1);c===-1&&(c=e.length);let l=e.slice(a,c),u=un(l);for(let e of u?l:Tn(l)){let a=e===` `;if(!u&&!a&&on.test(e)){o();let n=r+e;r=``,t.push(n);continue}let s=a?`space`:`word`;n&&i!==s&&o(),r&&=(n+=r,``),i=s,n+=e}a=c}return r&&(n?n+=r:t.length>0?t[t.length-1]+=r:n=r),n&&t.push(n),t}function Dn(e){for(let t of e)Number(t)}function On(e,t){if(!e)return[``];let n=e.split(/\r\n|\r|\n/),r=[],i=new Cn;for(let e of n){let n=kn((r.length>0?i.getActiveCodes():``)+e,t);for(let e of n)r.push(e);wn(e,i)}return r.length>0?r:[``]}function kn(e,t){if(!e)return[``];if(L(e)<=t)return[e];let n=[],r=new Cn,i=En(e),a=``,o=0;for(let e of i){let i=L(e),s=e.trim()===``;if(i>t&&!s){if(a){let e=r.getLineEndReset();e&&(a+=e),n.push(a),a=``,o=0}let i=Mn(e,t,r);for(let e=0;e<i.length-1;e++)n.push(i[e]);a=i[i.length-1],o=L(a);continue}if(o+i>t&&o>0){let t=a.trimEnd(),c=r.getLineEndReset();c&&(t+=c),n.push(t),s?(a=r.getActiveCodes(),o=0):(a=r.getActiveCodes()+e,o=i)}else a+=e,o+=i;wn(e,r)}return a&&n.push(a),n.length>0?n.map(e=>e.trimEnd()):[``]}const An=/[(){}[\]<>.,;:'"!?+\-=*/\\|&%^$#@~`]/;function jn(e){return/\s/.test(e)}function Mn(e,t,n){let r=[],i=n.getActiveCodes(),a=0,o=0,s=[];for(;o<e.length;){let t=R(e,o);if(t)s.push({type:`ansi`,value:t.code}),o+=t.length;else{let t=o;for(;t<e.length&&!R(e,t);)t++;let n=e.slice(o,t);for(let e of qt.segment(n))s.push({type:`grapheme`,value:e.segment});o=t}}for(let e of s){if(e.type===`ansi`){i+=e.value,n.process(e.value);continue}let o=e.value;if(!o)continue;let s=L(o);if(a+s>t){let e=n.getLineEndReset();e&&(i+=e),r.push(i),i=n.getActiveCodes(),a=0}i+=o,a+=s}return i&&r.push(i),r.length>0?r:[``]}function Nn(e,t,n){let r=L(e),i=Math.max(0,t-r);return n(e+` `.repeat(i))}function z(e,t,n=`...`,r=!1){if(t<=0)return``;if(e.length===0)return r?` `.repeat(t):``;let i=L(n);if(i>=t){let i=L(e);if(i<=t)return r?e+` `.repeat(t-i):e;let a=dn(n,t);return a.width===0?r?` `.repeat(t):``:fn(``,0,a.text,a.width,t,r)}if(un(e)){if(e.length<=t)return r?e+` `.repeat(t-e.length):e;let a=t-i;return fn(e.slice(0,a),a,n,i,t,r)}let a=t-i,o=``,s=``,c=0,l=0,u=!0,d=!1,f=!1,p=e.includes(`\x1B`),m=e.includes(` `);if(!p&&!m){for(let{segment:n}of qt.segment(e)){let e=pn(n);if(u&&l+e<=a?(o+=n,l+=e):u=!1,c+=e,c>t){d=!0;break}}f=!d}else{let n=0;for(;n<e.length;){let r=R(e,n);if(r){s+=r.code,n+=r.length;continue}if(e[n]===` `){if(u&&l+3<=a?(s&&=(o+=s,``),o+=` `,l+=3):(u=!1,s=``),c+=3,c>t){d=!0;break}n++;continue}let i=n;for(;i<e.length&&e[i]!==` `&&!R(e,i);)i++;for(let{segment:r}of qt.segment(e.slice(n,i))){let e=pn(r);if(u&&l+e<=a?(s&&=(o+=s,``),o+=r,l+=e):(u=!1,s=``),c+=e,c>t){d=!0;break}}if(d)break;n=i}f=n>=e.length}return!d&&f?r?e+` `.repeat(Math.max(0,t-c)):e:fn(o,l,n,i,t,r)}function Pn(e,t,n,r=!1){return Fn(e,t,n,r).text}function Fn(e,t,n,r=!1){if(n<=0)return{text:``,width:0};let i=t+n,a=``,o=0,s=0,c=0,l=``;for(;c<e.length;){let n=R(e,c);if(n){s>=t&&s<i?(a+=l+n.code,l=``):s<t&&(l+=n.code),c+=n.length;continue}let u=c;for(;u<e.length&&!R(e,u);)u++;for(let{segment:n}of qt.segment(e.slice(c,u))){let e=pn(n),c=s>=t&&s<i,u=!r||s+e<=i;if(c&&u&&(l&&=(a+=l,``),a+=n,o+=e),s+=e,s>=i)break}if(c=u,s>=i)break}return{text:a,width:o}}const In=new Cn;function Ln(e,t,n,r,i=!1){let a=``,o=0,s=``,c=0,l=0,u=0,d=``,f=!1,p=n+r;for(In.clear();u<e.length;){let m=R(e,u);if(m){In.process(m.code),l<t?d+=m.code:l>=n&&l<p&&f&&(s+=m.code),u+=m.length;continue}let h=u;for(;h<e.length&&!R(e,h);)h++;for(let{segment:m}of qt.segment(e.slice(u,h))){let e=pn(m);if(l<t&&l+e<=t?(d&&=(a+=d,``),a+=m,o+=e):l>=n&&l<p&&(!i||l+e<=p)&&(f||=(s+=In.getActiveCodes(),!0),s+=m,c+=e),l+=e,r<=0?l>=t:l>=p)break}if(u=h,r<=0?l>=t:l>=p)break}return{before:a,beforeWidth:o,after:s,afterWidth:c}}RegExp(`${ln.source}$`,`u`);const Rn=String.raw`[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?`;RegExp(`^oklch\\(\\s*(${Rn})(%)?\\s+(${Rn})\\s+(${Rn})(?:deg)?\\s*\\)$`,`i`),RegExp(`^okhsl\\(\\s*(${Rn})(?:deg)?\\s+(${Rn})(%)?\\s+(${Rn})(%)?\\s*\\)$`,`i`),Array.from({length:24},(e,t)=>8+t*10);let zn=!1;function Bn(e){zn=e}const Vn=new Set("`-=[]\\;',./!@#$%^&*()_+|~{}:<>?".split(``)),B={shift:1,alt:2,ctrl:4,super:8},V={escape:27,tab:9,enter:13,space:32,backspace:127,kpEnter:57414},H={up:-1,down:-2,right:-3,left:-4},U={delete:-10,insert:-11,pageUp:-12,pageDown:-13,home:-14,end:-15},Hn=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,H.left],[57418,H.right],[57419,H.up],[57420,H.down],[57421,U.pageUp],[57422,U.pageDown],[57423,U.home],[57424,U.end],[57425,U.insert],[57426,U.delete]]);function Un(e){return Hn.get(e)??e}function Wn(e,t){return t&-193&B.shift&&e>=65&&e<=90?e+32:e}const W={up:[`\x1B[A`,`\x1BOA`],down:[`\x1B[B`,`\x1BOB`],right:[`\x1B[C`,`\x1BOC`],left:[`\x1B[D`,`\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~`]},Gn={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$`]},Kn={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^`]},G=(e,t)=>t.includes(e),K=(e,t,n)=>n===B.shift?G(e,Gn[t]):n===B.ctrl?G(e,Kn[t]):!1;function qn(e){return e.includes(`\x1B[200~`)?!1:!!(e.includes(`:3u`)||e.includes(`:3~`)||e.includes(`:3A`)||e.includes(`:3B`)||e.includes(`:3C`)||e.includes(`:3D`)||e.includes(`:3H`)||e.includes(`:3F`))}function Jn(e){return e.includes(`\x1B[200~`)?!1:!!(e.includes(`:2u`)||e.includes(`:2~`)||e.includes(`:2A`)||e.includes(`:2B`)||e.includes(`:2C`)||e.includes(`:2D`)||e.includes(`:2H`)||e.includes(`:2F`))}function Yn(e){if(!e)return`press`;let t=parseInt(e,10);return t===2?`repeat`:t===3?`release`:`press`}function Xn(e){let t=e.match(/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/);if(t){let e=parseInt(t[1],10),n=t[2]&&t[2].length>0?parseInt(t[2],10):void 0,r=t[3]?parseInt(t[3],10):void 0,i=t[4]?parseInt(t[4],10):1,a=Yn(t[5]);return{codepoint:e,shiftedKey:n,baseLayoutKey:r,modifier:i-1,eventType:a}}let n=e.match(/^\x1b\[1;(\d+)(?::(\d+))?([ABCD])$/);if(n){let e=parseInt(n[1],10),t=Yn(n[2]);return{codepoint:{A:-1,B:-2,C:-3,D:-4}[n[3]],modifier:e-1,eventType:t}}let r=e.match(/^\x1b\[(\d+)(?:;(\d+))?(?::(\d+))?~$/);if(r){let e=parseInt(r[1],10),t=r[2]?parseInt(r[2],10):1,n=Yn(r[3]),i={2:U.insert,3:U.delete,5:U.pageUp,6:U.pageDown,7:U.home,8:U.end}[e];if(i!==void 0)return{codepoint:i,modifier:t-1,eventType:n}}let i=e.match(/^\x1b\[1;(\d+)(?::(\d+))?([HF])$/);if(i){let e=parseInt(i[1],10),t=Yn(i[2]);return{codepoint:i[3]===`H`?U.home:U.end,modifier:e-1,eventType:t}}return null}function q(e,t,n){let r=Xn(e);if(!r||(r.modifier&-193)!=(n&-193))return!1;let i=Wn(Un(r.codepoint),r.modifier);if(i===Wn(Un(t),n))return!0;if(r.baseLayoutKey!==void 0&&r.baseLayoutKey===t){let e=i,t=e>=97&&e<=122,n=Vn.has(String.fromCharCode(e));if(!t&&!n)return!0}return!1}function Zn(e){let t=e.match(/^\x1b\[27;(\d+);(\d+)~$/);if(!t)return null;let n=parseInt(t[1],10);return{codepoint:parseInt(t[2],10),modifier:n-1}}function J(e,t,n){let r=Zn(e);return r?r.codepoint===t&&r.modifier===n:!1}function Qn(){return!!process.env.WT_SESSION&&!process.env.SSH_CONNECTION&&!process.env.SSH_CLIENT&&!process.env.SSH_TTY}function $n(e,t){return e===``?t===0:e===`\b`?Qn()?t===B.ctrl:t===0:!1}function er(e){let t=e.toLowerCase(),n=t.charCodeAt(0);return n>=97&&n<=122||t===`[`||t===`\\`||t===`]`||t===`_`?String.fromCharCode(n&31):t===`-`?``:null}function tr(e){return e>=`0`&&e<=`9`}function nr(e,t,n){if(n===0)return!1;let r=Zn(e);return!r||r.modifier!==n?!1:Wn(r.codepoint,r.modifier)===Wn(t,n)}function rr(e){let t=e.toLowerCase().split(`+`),n=t[t.length-1];return n?{key:n,ctrl:t.includes(`ctrl`),shift:t.includes(`shift`),alt:t.includes(`alt`),super:t.includes(`super`)}:null}function Y(e,t){let n=rr(t);if(!n)return!1;let{key:r,ctrl:i,shift:a,alt:o,super:s}=n,c=0;switch(a&&(c|=B.shift),o&&(c|=B.alt),i&&(c|=B.ctrl),s&&(c|=B.super),r){case`escape`:case`esc`:return c===0?e===`\x1B`||q(e,V.escape,0)||J(e,V.escape,0):!1;case`space`:return!zn&&(c===B.ctrl&&e===`\0`||c===B.alt&&e===`\x1B `)?!0:c===0?e===` `||q(e,V.space,0)||J(e,V.space,0):q(e,V.space,c)||J(e,V.space,c);case`tab`:return c===B.shift?e===`\x1B[Z`||q(e,V.tab,B.shift)||J(e,V.tab,B.shift):c===0?e===` `||q(e,V.tab,0):q(e,V.tab,c)||J(e,V.tab,c);case`enter`:case`return`:return c===B.shift?q(e,V.enter,B.shift)||q(e,V.kpEnter,B.shift)||J(e,V.enter,B.shift)?!0:zn?e===`\x1B\r`||e===`
|
|
85
|
+
`:!1:c===B.alt?q(e,V.enter,B.alt)||q(e,V.kpEnter,B.alt)||J(e,V.enter,B.alt)?!0:zn?!1:e===`\x1B\r`:c===0?e===`\r`||!zn&&e===`
|
|
86
|
+
`||e===`\x1BOM`||q(e,V.enter,0)||q(e,V.kpEnter,0):q(e,V.enter,c)||q(e,V.kpEnter,c)||J(e,V.enter,c);case`backspace`:return c===B.alt?e===`\x1B`||e===`\x1B\b`?!0:q(e,V.backspace,B.alt)||J(e,V.backspace,B.alt):c===B.ctrl?$n(e,B.ctrl)?!0:q(e,V.backspace,B.ctrl)||J(e,V.backspace,B.ctrl):c===0?$n(e,0)||q(e,V.backspace,0)||J(e,V.backspace,0):q(e,V.backspace,c)||J(e,V.backspace,c);case`insert`:return c===0?G(e,W.insert)||q(e,U.insert,0):K(e,`insert`,c)?!0:q(e,U.insert,c);case`delete`:return c===0?G(e,W.delete)||q(e,U.delete,0):K(e,`delete`,c)?!0:q(e,U.delete,c);case`clear`:return c===0?G(e,W.clear):K(e,`clear`,c);case`home`:return c===0?G(e,W.home)||q(e,U.home,0):K(e,`home`,c)?!0:q(e,U.home,c);case`end`:return c===0?G(e,W.end)||q(e,U.end,0):K(e,`end`,c)?!0:q(e,U.end,c);case`pageup`:return c===0?G(e,W.pageUp)||q(e,U.pageUp,0):K(e,`pageUp`,c)?!0:q(e,U.pageUp,c);case`pagedown`:return c===0?G(e,W.pageDown)||q(e,U.pageDown,0):K(e,`pageDown`,c)?!0:q(e,U.pageDown,c);case`up`:return c===B.alt?e===`\x1Bp`||q(e,H.up,B.alt):c===0?G(e,W.up)||q(e,H.up,0):K(e,`up`,c)?!0:q(e,H.up,c);case`down`:return c===B.alt?e===`\x1Bn`||q(e,H.down,B.alt):c===0?G(e,W.down)||q(e,H.down,0):K(e,`down`,c)?!0:q(e,H.down,c);case`left`:return c===B.alt?e===`\x1B[1;3D`||!zn&&e===`\x1BB`||e===`\x1Bb`||q(e,H.left,B.alt):c===B.ctrl?e===`\x1B[1;5D`||K(e,`left`,B.ctrl)||q(e,H.left,B.ctrl):c===0?G(e,W.left)||q(e,H.left,0):K(e,`left`,c)?!0:q(e,H.left,c);case`right`:return c===B.alt?e===`\x1B[1;3C`||!zn&&e===`\x1BF`||e===`\x1Bf`||q(e,H.right,B.alt):c===B.ctrl?e===`\x1B[1;5C`||K(e,`right`,B.ctrl)||q(e,H.right,B.ctrl):c===0?G(e,W.right)||q(e,H.right,0):K(e,`right`,c)?!0:q(e,H.right,c);case`f1`:case`f2`:case`f3`:case`f4`:case`f5`:case`f6`:case`f7`:case`f8`:case`f9`:case`f10`:case`f11`:case`f12`:return c===0?G(e,W[r]):!1}if(r.length===1&&(r>=`a`&&r<=`z`||tr(r)||Vn.has(r))){let t=r.charCodeAt(0),n=er(r),i=r>=`a`&&r<=`z`,a=tr(r);return c===B.ctrl+B.alt&&!zn&&n&&e===`\x1b${n}`||c===B.alt&&!zn&&(i||a||Vn.has(r))&&e===`\x1b${r}`?!0:c===B.ctrl?n&&e===n?!0:q(e,t,B.ctrl)||nr(e,t,B.ctrl):c===B.shift+B.ctrl?q(e,t,B.shift+B.ctrl)||nr(e,t,B.shift+B.ctrl):c===B.shift?i&&e===r.toUpperCase()?!0:q(e,t,B.shift)||nr(e,t,B.shift):c===0?e===r||q(e,t,0):q(e,t,c)||nr(e,t,c)}return!1}const ir=/^\x1b\[(\d+)(?::(\d*))?(?::(\d+))?(?:;(\d+))?(?::(\d+))?u$/,ar=B.shift|192;function or(e){let t=e.match(ir);if(!t)return;let n=Number.parseInt(t[1]??``,10);if(!Number.isFinite(n))return;let r=t[2]&&t[2].length>0?Number.parseInt(t[2],10):void 0,i=t[4]?Number.parseInt(t[4],10):1,a=Number.isFinite(i)?i-1:0;if((a&~ar)!==0||a&(B.alt|B.ctrl))return;let o=n;if(a&B.shift&&typeof r==`number`&&(o=r),o=Un(o),!(!Number.isFinite(o)||o<32))try{return String.fromCodePoint(o)}catch{return}}function sr(e){let t=Zn(e);if(t&&!(t.modifier&-193&~B.shift)&&!(!Number.isFinite(t.codepoint)||t.codepoint<32))try{return String.fromCodePoint(t.codepoint)}catch{return}}function cr(e){return or(e)??sr(e)}function lr(e){let t=e.startsWith(`#`)?e.slice(1):e;return{r:parseInt(t.slice(0,2),16),g:parseInt(t.slice(2,4),16),b:parseInt(t.slice(4,6),16)}}function ur(e){if(!/^[0-9a-f]+$/i.test(e))return;let t=16**e.length-1;if(!(t<=0))return Math.round(parseInt(e,16)/t*255)}const dr=/^\x1b\](?:(1[01])|4;(\d{1,3}));([^\x07\x1b]*)(?:\x07|\x1b\\)$/i,fr=/^(?:\x1b\[\?997;(1|2)n)+$/;function pr(e){let t=e.match(dr);if(t)return{target:t[1]===`10`?`foreground`:t[1]===`11`?`background`:Number.parseInt(t[2],10),rgb:mr(t[3])}}function mr(e){let t=e.trim();if(t.startsWith(`#`)){let e=t.slice(1);if(/^[0-9a-f]{6}$/i.test(e))return lr(t);if(/^[0-9a-f]{12}$/i.test(e)){let t=ur(e.slice(0,4)),n=ur(e.slice(4,8)),r=ur(e.slice(8,12));return t!==void 0&&n!==void 0&&r!==void 0?{r:t,g:n,b:r}:void 0}return}let[n,r,i]=t.replace(/^rgba?:/i,``).split(`/`);if(n===void 0||r===void 0||i===void 0)return;let a=ur(n),o=ur(r),s=ur(i);return a!==void 0&&o!==void 0&&s!==void 0?{r:a,g:o,b:s}:void 0}function hr(e){let t=e.match(fr);if(t)return t[1]===`2`?`light`:`dark`}let gr=null,_r={};function vr(){try{return t(`tmux display-message -p '#{client_termfeatures}'`,{encoding:`utf8`,timeout:250,stdio:[`ignore`,`pipe`,`ignore`]}).split(`,`).map(e=>e.trim()).includes(`hyperlinks`)}catch{return!1}}function yr(e){let t=process.env.TERM_PROGRAM?.toLowerCase()||``,n=process.env.TERMINAL_EMULATOR?.toLowerCase()||``,r=process.env.TERM?.toLowerCase()||``,i=process.env.COLORTERM?.toLowerCase()||``,a=i===`truecolor`||i===`24bit`||r.endsWith(`-direct`),o=process.platform===`win32`;return process.env.TMUX||r.startsWith(`tmux`)?{images:null,trueColor:a,hyperlinks:e()}:r.startsWith(`screen`)?{images:null,trueColor:a,hyperlinks:!1}:process.env.KITTY_WINDOW_ID||t===`kitty`||t===`ghostty`||r.includes(`ghostty`)||process.env.GHOSTTY_RESOURCES_DIR||process.env.WEZTERM_PANE||t===`wezterm`||t===`warpterminal`||process.env.WARP_SESSION_ID||process.env.WARP_TERMINAL_SESSION_UUID?{images:`kitty`,trueColor:!0,hyperlinks:!0}:process.env.ITERM_SESSION_ID||t===`iterm.app`?{images:`iterm2`,trueColor:!0,hyperlinks:!0}:process.env.WT_SESSION||t===`alacritty`||t===`vscode`||t===`zed`?{images:null,trueColor:!0,hyperlinks:!0}:n===`jetbrains-jediterm`||o?{images:null,trueColor:!0,hyperlinks:!1}:{images:null,trueColor:a,hyperlinks:!1}}function br(e){return e===`1`?!0:e===`0`?!1:void 0}function xr(e=vr){let t=br(process.env.PI_HYPERLINKS),n=yr(t===void 0?e:()=>t),r=process.env.PI_IMAGE_PROTOCOL?.toLowerCase(),i=r===`kitty`||r===`iterm2`?r:r===`none`||r===`0`?null:void 0,a=br(process.env.PI_TRUE_COLOR);return{...n,...i===void 0?{}:{images:i},...a===void 0?{}:{trueColor:a},...t===void 0?{}:{hyperlinks:t}}}function Sr(){if(!gr){let e=_r.hyperlinks;gr={...xr(e===void 0?void 0:()=>e),..._r}}return gr}const Cr=`\x1B]1337;File=`;function wr(e){return e.startsWith(`\x1B_G`)||e.startsWith(Cr)?!0:e.includes(`\x1B_G`)||e.includes(Cr)}function Tr(e){return`\x1b_Ga=d,d=I,i=${e},q=2\x1b\\`}function Er(e,t){return`\x1b]8;;${t}\x1b\\${e}\x1b]8;;\x1b\\`}function Dr(e,t){let n=e.handleMouse?.(t);if(n){if(`target`in n){let t=n;return t.focus&&e.handleInput?{...t,focusTarget:e}:t}if(!(!n.handled&&!n.capture&&!n.focus))return{...n,handled:!0,...n.focus?{focusTarget:e}:{},target:{component:e,originX:t.screenX-t.x,originY:t.screenY-t.y,width:t.width,height:t.height}}}}const Or=`\x1b]10;?\x07\x1b]11;?\x07${Array.from({length:16},(e,t)=>`\x1b]4;${t};?\x07`).join(``)}\x1b[c`,kr=/^\x1b\[\?[\d;]*c$/;function Ar(e){return e!==null&&`focused`in e}const jr=`\x1B_pi:c\x07`;function Mr(e,t){if(e===void 0)return;if(typeof e==`number`)return e;let n=e.match(/^(\d+(?:\.\d+)?)%$/);if(n)return Math.floor(t*parseFloat(n[1])/100)}var Nr=class{children=[];mouseLayout;addChild(e){this.children.push(e)}removeChild(e){let t=this.children.indexOf(e);t!==-1&&this.children.splice(t,1)}clear(){this.children=[]}invalidate(){for(let e of this.children)e.invalidate?.()}handleMouse(e){if(e.y<0||e.y>=e.height)return;let t=this.mouseLayout?.width===e.width?this.mouseLayout.children:this.children.map(t=>({component:t,height:t.render(e.width).length})),n=0;for(let{component:r,height:i}of t){if(e.y>=n&&e.y<n+i){let t=Dr(r,{...e,y:e.y-n,height:i});return t?.focus&&this.handleInput?{...t,focusTarget:this}:t}n+=i}}render(e){let t=[],n=[];for(let r of this.children){let i=r.render(e);n.push({component:r,height:i.length});for(let e of i)t.push(e)}return this.mouseLayout={width:e,children:n},t}};const Pr=`\x1B[0m\x1B]8;;\x07`;function Fr(e,t,n,r,i){if(wr(e))return e;let a=n+r,o=Ln(e,n,a,i-a,!0),s=Fn(t,0,r,!0),c=Math.max(0,n-o.beforeWidth),l=Math.max(0,r-s.width),u=Math.max(n,o.beforeWidth),d=Math.max(r,s.width),f=Math.max(0,i-u-d),p=Math.max(0,f-o.afterWidth),m=o.before+` `.repeat(c)+Pr+s.text+` `.repeat(l)+Pr+o.after+` `.repeat(p);return L(m)<=i?m:Pn(m,0,i,!0)}var Ir=class e extends Nr{terminal;focusedComponent=null;inputListeners=new Set;onDebug;renderRequested=!1;immediateRenderScheduled=!1;renderTimer;lastRenderAt=0;static MIN_RENDER_INTERVAL_MS=16;showHardwareCursor=!1;clearOnShrink=!1;fullRedrawCount=0;stopped=!1;pendingTerminalColorQueries=[];terminalColorSchemeListeners=new Set;terminalColorSchemeNotificationsEnabled=!1;logDirectory;focusOrderCounter=0;overlayStack=[];renderedOverlayLayouts=[];get hasOverlayEntries(){return this.overlayStack.length>0}overlayFocusRestore={status:`inactive`};constructor(e,t,n){super(),this.terminal=e,this.logDirectory=n,t!==void 0&&(this.showHardwareCursor=t)}resetRenderState(){}beforeTerminalStart(){}afterTerminalStart(){}beforeTerminalStop(e){}afterTerminalStop(e){}get fullRedraws(){return this.fullRedrawCount}getShowHardwareCursor(){return this.showHardwareCursor}setShowHardwareCursor(e){this.showHardwareCursor!==e&&(this.showHardwareCursor=e,e||this.hideTerminalCursor(),this.requestRender())}getClearOnShrink(){return this.clearOnShrink}setClearOnShrink(e){this.clearOnShrink=e}getFocusedComponent(){return this.focusedComponent}setFocus(e){this.setFocusInternal({component:e,overlayFocusRestore:`clear`})}setFocusInternal({component:e,overlayFocusRestore:t}){let n=this.focusedComponent,r=e,i=n?this.overlayStack.find(e=>e.component===n&&this.isOverlayVisible(e)):void 0,a=r?this.overlayStack.some(e=>e.component===r):!1,o=this.getVisibleOverlayFocusRestore();r&&!a?o.status===`blocked`&&o.blockedBy===n?o.resume.status===`focus-target`||!this.isComponentMounted(o.blockedBy)?r=this.resolveBlockedOverlayFocusResume(o):this.overlayFocusRestore={status:`blocked`,overlay:o.overlay,blockedBy:r,resume:o.resume}:i&&o.status!==`inactive`&&o.overlay===i&&!this.isOverlayFocusAncestor(i,r)&&(this.overlayFocusRestore={status:`blocked`,overlay:i,blockedBy:r,resume:{status:`restore-overlay`}}):r===null&&(o.status===`blocked`&&o.blockedBy===n?r=this.resolveBlockedOverlayFocusResume(o):t===`clear`&&this.clearOverlayFocusRestore()),Ar(this.focusedComponent)&&(this.focusedComponent.focused=!1),this.focusedComponent=r,Ar(r)&&(r.focused=!0);let s=r?this.overlayStack.find(e=>e.component===r&&this.isOverlayVisible(e)):void 0;s&&(this.overlayFocusRestore={status:`eligible`,overlay:s})}clearOverlayFocusRestore(){this.overlayFocusRestore={status:`inactive`}}clearOverlayFocusRestoreFor(e){this.overlayFocusRestore.status!==`inactive`&&this.overlayFocusRestore.overlay===e&&this.clearOverlayFocusRestore()}resolveBlockedOverlayFocusResume(e){return e.resume.status===`restore-overlay`?e.overlay.component:(this.clearOverlayFocusRestore(),e.resume.target)}getVisibleOverlayFocusRestore(){let e=this.overlayFocusRestore;return e.status===`inactive`?e:!this.overlayStack.includes(e.overlay)||!this.isOverlayVisible(e.overlay)?{status:`inactive`}:e}isOverlayFocusAncestor(e,t){let n=new Set,r=e.preFocus;for(;r&&!n.has(r);){if(n.add(r),r===t)return!0;r=this.overlayStack.find(e=>e.component===r)?.preFocus??null}return!1}retargetOverlayPreFocus(e){for(let t of this.overlayStack)t!==e&&t.preFocus===e.component&&(t.preFocus=e.preFocus)}getMountedRoots(){return this.children}isComponentMounted(e){return this.getMountedRoots().some(t=>this.containsComponent(t,e))}containsComponent(e,t){return e===t?!0:e instanceof Nr?e.children.some(e=>this.containsComponent(e,t)):!1}showOverlay(e,t){let n={component:e,...t===void 0?{}:{options:t},preFocus:this.focusedComponent,hidden:!1,focusOrder:++this.focusOrderCounter};return this.overlayStack.push(n),!t?.nonCapturing&&this.isOverlayVisible(n)&&this.setFocus(e),this.hideTerminalCursor(),this.requestRender(),{hide:()=>{let t=this.overlayStack.indexOf(n);if(t!==-1){if(this.clearOverlayFocusRestoreFor(n),this.retargetOverlayPreFocus(n),this.overlayStack.splice(t,1),this.focusedComponent===e){let e=this.getTopmostVisibleOverlay();this.setFocus(e?.component??n.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}},setHidden:r=>{if(n.hidden!==r){if(n.hidden=r,r){if(this.clearOverlayFocusRestoreFor(n),this.focusedComponent===e){let e=this.getTopmostVisibleOverlay();this.setFocus(e?.component??n.preFocus)}}else!t?.nonCapturing&&this.isOverlayVisible(n)&&(n.focusOrder=++this.focusOrderCounter,this.setFocus(e));this.requestRender()}},isHidden:()=>n.hidden,focus:()=>{!this.overlayStack.includes(n)||!this.isOverlayVisible(n)||(n.focusOrder=++this.focusOrderCounter,this.setFocus(e),this.requestRender())},unfocus:t=>{let r=this.focusedComponent===e,i=this.overlayFocusRestore,a=i.status!==`inactive`&&i.overlay===n;if(!(!r&&!a)){if(i.status===`blocked`&&i.overlay===n&&this.focusedComponent===i.blockedBy){t?this.overlayFocusRestore={status:`blocked`,overlay:n,blockedBy:i.blockedBy,resume:{status:`focus-target`,target:t.target}}:this.clearOverlayFocusRestore(),this.requestRender();return}if(this.clearOverlayFocusRestoreFor(n),r||t){let e=this.getTopmostVisibleOverlay(),r=e&&e!==n?e.component:n.preFocus;this.setFocus(t?t.target:r)}this.requestRender()}},isFocused:()=>this.focusedComponent===e,getBounds:()=>{if(!(!this.overlayStack.includes(n)||!this.isOverlayVisible(n)||!n.bounds))return{...n.bounds}}}}hideOverlay(){let e=this.overlayStack[this.overlayStack.length-1];if(e){if(this.clearOverlayFocusRestoreFor(e),this.retargetOverlayPreFocus(e),this.overlayStack.pop(),this.focusedComponent===e.component){let t=this.getTopmostVisibleOverlay();this.setFocus(t?.component??e.preFocus)}this.overlayStack.length===0&&this.hideTerminalCursor(),this.requestRender()}}hideTerminalCursor(){this.stopped||this.terminal.hideCursor()}hasOverlay(){return this.overlayStack.some(e=>this.isOverlayVisible(e))}isOverlayFocused(){return this.overlayStack.some(e=>e.component===this.focusedComponent&&this.isOverlayVisible(e))}resolveMouseFocusTarget(e){for(let t=this.overlayStack.length-1;t>=0;t--){let n=this.overlayStack[t];if(this.isOverlayVisible(n)&&this.containsComponent(n.component,e))return n.component}return e}dispatchMouseToOverlay(e){for(let t=this.renderedOverlayLayouts.length-1;t>=0;t--){let n=this.renderedOverlayLayouts[t];if(e.screenX<n.col||e.screenX>=n.col+n.width||e.screenY<n.row||e.screenY>=n.row+n.height)continue;let r=Dr(n.entry.component,{...e,x:e.screenX-n.col,y:e.screenY-n.row,width:n.width,height:n.height});return r?{hit:!0,result:r.focus?{...r,focusTarget:n.entry.component}:r}:{hit:!0}}return{hit:!1}}isOverlayVisible(e){return e.hidden?!1:e.options?.visible?e.options.visible(this.terminal.columns,this.terminal.rows):!0}getTopmostVisibleOverlay(){let e;for(let t of this.overlayStack)t.options?.nonCapturing||!this.isOverlayVisible(t)||(!e||t.focusOrder>e.focusOrder)&&(e=t);return e}invalidate(){for(let e of this.getMountedRoots())e.invalidate();for(let e of this.overlayStack)e.component.invalidate()}start(){this.stopped=!1,this.beforeTerminalStart(),this.terminal.start(e=>this.handleTerminalInput(e),()=>this.requestRender()),this.afterTerminalStart(),this.terminal.hideCursor(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write(`\x1B[?2031h`),this.queryCellSize(),this.requestRender()}addInputListener(e){return this.inputListeners.add(e),()=>{this.inputListeners.delete(e)}}removeInputListener(e){this.inputListeners.delete(e)}onTerminalColorSchemeChange(e){return this.terminalColorSchemeListeners.add(e),()=>{this.terminalColorSchemeListeners.delete(e)}}setTerminalColorSchemeNotifications(e){this.terminalColorSchemeNotificationsEnabled!==e&&(this.terminalColorSchemeNotificationsEnabled=e,this.stopped||this.terminal.write(e?`\x1B[?2031h`:`\x1B[?2031l`))}queryCellSize(){Sr().images&&this.terminal.write(`\x1B[16t`)}stop(e={}){this.stopped=!0,this.cancelRenderTimer(),this.terminalColorSchemeNotificationsEnabled&&this.terminal.write(`\x1B[?2031l`),this.beforeTerminalStop(e),this.terminal.showCursor(),this.terminal.stop(),this.afterTerminalStop(e)}renderNow(e=!1){e&&this.resetRenderState(),this.renderRequested=!1,this.cancelRenderTimer(),this.lastRenderAt=r.now(),this.doRender()}requestRender(e=!1){if(e){this.resetRenderState(),this.requestImmediateRender();return}this.renderRequested||(this.renderRequested=!0,process.nextTick(()=>this.scheduleRender()))}requestImmediateRender(){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=r.now(),this.doRender())}))}cancelRenderTimer(){this.renderTimer&&=(clearTimeout(this.renderTimer),void 0)}scheduleRender(){if(this.stopped||this.renderTimer||!this.renderRequested)return;let t=r.now()-this.lastRenderAt,n=Math.max(0,e.MIN_RENDER_INTERVAL_MS-t);this.renderTimer=setTimeout(()=>{this.renderTimer=void 0,!(this.stopped||!this.renderRequested)&&(this.renderRequested=!1,this.lastRenderAt=r.now(),this.doRender(),this.renderRequested&&this.scheduleRender())},n)}handleTerminalInput(e){if(this.consumeTerminalColorResponse(e)||this.consumeTerminalColorSchemeReport(e))return;if(this.inputListeners.size>0){let t=e;for(let e of this.inputListeners){let n=e(t);if(n?.consume)return;n?.data!==void 0&&(t=n.data)}if(t.length===0)return;e=t}if(this.consumeCellSizeResponse(e))return;if(Y(e,`shift+ctrl+d`)&&this.onDebug){this.onDebug();return}let t=this.overlayStack.find(e=>e.component===this.focusedComponent);if(t&&!this.isOverlayVisible(t)){let e=this.getTopmostVisibleOverlay();e?this.setFocus(e.component):this.setFocusInternal({component:t.preFocus,overlayFocusRestore:`preserve`})}if(!this.overlayStack.some(e=>e.component===this.focusedComponent)){let e=this.getVisibleOverlayFocusRestore();e.status===`eligible`?this.setFocus(e.overlay.component):e.status===`blocked`&&e.blockedBy!==this.focusedComponent&&(e.resume.status===`restore-overlay`?this.setFocus(e.overlay.component):(this.clearOverlayFocusRestore(),this.setFocus(e.resume.target)))}if(this.focusedComponent?.handleInput){if(qn(e)&&!this.focusedComponent.wantsKeyRelease)return;this.focusedComponent.handleInput(e),this.requestImmediateRender()}}consumeTerminalColorResponse(e){let t=this.pendingTerminalColorQueries[0];if(!t)return!1;if(kr.test(e))return this.pendingTerminalColorQueries.shift(),this.completeTerminalColorQuery(t),!0;let n=pr(e);if(!n)return!1;let{target:r,rgb:i}=n,a=String(r);return!t.deliver||t.replied.has(a)?!0:(t.replied.add(a),r===`foreground`?t.foreground=i:r===`background`?t.background=i:r<16&&(t.palette[r]=i),t.replied.size===18&&this.completeTerminalColorQuery(t),!0)}terminalColorQueryResult(e){let t=e.palette.every(e=>e!==void 0)?e.palette:void 0;return{foreground:e.foreground,background:e.background,palette:t}}completeTerminalColorQuery(e){let t=e.deliver;e.deliver=void 0,clearTimeout(e.timer),t?.(this.terminalColorQueryResult(e))}consumeTerminalColorSchemeReport(e){let t=hr(e);if(!t)return!1;for(let e of this.terminalColorSchemeListeners)e(t);return!0}consumeCellSizeResponse(e){let t=e.match(/^\x1b\[6;(\d+);(\d+)t$/);if(!t)return!1;let n=parseInt(t[1],10),r=parseInt(t[2],10);return n<=0||r<=0?!0:(this.invalidate(),this.requestRender(),!0)}resolveOverlayLayout(e,t,n,r){let i=e??{},a=typeof i.margin==`number`?{top:i.margin,right:i.margin,bottom:i.margin,left:i.margin}:i.margin??{},o=Math.max(0,a.top??0),s=Math.max(0,a.right??0),c=Math.max(0,a.bottom??0),l=Math.max(0,a.left??0),u=Math.max(1,n-l-s),d=Math.max(1,r-o-c),f=Mr(i.width,n)??Math.min(80,u);i.minWidth!==void 0&&(f=Math.max(f,i.minWidth)),f=Math.max(1,Math.min(f,u));let p=Mr(i.maxHeight,r);p!==void 0&&(p=Math.max(1,Math.min(p,d)));let m=p===void 0?t:Math.min(t,p),h,g;if(i.row!==void 0)if(typeof i.row==`string`){let e=i.row.match(/^(\d+(?:\.\d+)?)%$/);if(e){let t=Math.max(0,d-m),n=parseFloat(e[1])/100;h=o+Math.floor(t*n)}else h=this.resolveAnchorRow(`center`,m,d,o)}else h=i.row;else{let e=i.anchor??`center`;h=this.resolveAnchorRow(e,m,d,o)}if(i.col!==void 0)if(typeof i.col==`string`){let e=i.col.match(/^(\d+(?:\.\d+)?)%$/);if(e){let t=Math.max(0,u-f),n=parseFloat(e[1])/100;g=l+Math.floor(t*n)}else g=this.resolveAnchorCol(`center`,f,u,l)}else g=i.col;else{let e=i.anchor??`center`;g=this.resolveAnchorCol(e,f,u,l)}return i.offsetY!==void 0&&(h+=i.offsetY),i.offsetX!==void 0&&(g+=i.offsetX),h=Math.max(o,Math.min(h,r-c-m)),g=Math.max(l,Math.min(g,n-s-f)),{width:f,row:h,col:g,maxHeight:p}}resolveAnchorRow(e,t,n,r){switch(e){case`top-left`:case`top-center`:case`top-right`:return r;case`bottom-left`:case`bottom-center`:case`bottom-right`:return r+n-t;case`left-center`:case`center`:case`right-center`:return r+Math.floor((n-t)/2)}}resolveAnchorCol(e,t,n,r){switch(e){case`top-left`:case`left-center`:case`bottom-left`:return r;case`top-right`:case`right-center`:case`bottom-right`:return r+n-t;case`top-center`:case`center`:case`bottom-center`:return r+Math.floor((n-t)/2)}}compositeOverlays(e,t,n){if(this.overlayStack.length===0)return this.renderedOverlayLayouts=[],e;let r=[...e];for(let e of this.overlayStack)e.bounds=void 0;let i=[],a=r.length,o=this.overlayStack.filter(e=>this.isOverlayVisible(e));o.sort((e,t)=>e.focusOrder-t.focusOrder);for(let e of o){let{component:r,options:o}=e,{width:s,maxHeight:c}=this.resolveOverlayLayout(o,0,t,n),l=r.render(s);c!==void 0&&l.length>c&&(l=l.slice(0,c));let{row:u,col:d}=this.resolveOverlayLayout(o,l.length,t,n);e.bounds={row:u,col:d,width:s,height:l.length},i.push({entry:e,overlayLines:l,row:u,col:d,w:s}),a=Math.max(a,u+l.length)}this.renderedOverlayLayouts=i.map(({entry:e,row:t,col:n,w:r,overlayLines:i})=>({entry:e,row:t,col:n,width:r,height:i.length}));let s=Math.max(r.length,n,a);for(;r.length<s;)r.push(``);let c=Math.max(0,s-n);for(let{overlayLines:e,row:n,col:a,w:o}of i)for(let i=0;i<e.length;i++){let s=c+n+i;if(s>=0&&s<r.length){let n=L(e[i])>o?Pn(e[i],0,o,!0):e[i];r[s]=this.compositeLineAt(r[s],n,a,o,t)}}return r}applyLineResets(e){for(let t=0;t<e.length;t++){let n=e[t];wr(n)||(e[t]=gn(n)+`\x1B[0m\x1B]8;;\x07`)}return e}compositeLineAt(e,t,n,r,i){return Fr(e,t,n,r,i)}extractCursorPosition(e,t){let n=Math.max(0,e.length-t);for(let t=e.length-1;t>=n;t--){let n=e[t],r=n.indexOf(jr);if(r!==-1){let i=L(n.slice(0,r));return e[t]=n.slice(0,r)+n.slice(r+7),{row:t,col:i}}}return null}queryTerminalColors({timeoutMs:e,onLateReply:t}){return new Promise(n=>{let r={palette:Array.from({length:16},()=>void 0),replied:new Set,deliver:n,timer:void 0};r.timer=setTimeout(()=>{r.deliver=t,n(this.terminalColorQueryResult(r))},e),this.pendingTerminalColorQueries.push(r),this.terminal.write(Or)})}};const Lr={"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:`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+home`,`ctrl+a`],description:`Move to line start`},"tui.editor.cursorLineEnd":{defaultKeys:[`end`,`ctrl+end`,`ctrl+e`],description:`Move to line end`},"tui.editor.jumpForward":{defaultKeys:`ctrl+]`,description:`Jump forward 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.deleteWordBackward":{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.editor.undo":{defaultKeys:`ctrl+-`,description:`Undo`},"tui.input.newLine":{defaultKeys:[`shift+enter`,`ctrl+j`],description:`Insert newline`},"tui.input.submit":{defaultKeys:`enter`,description:`Submit input`},"tui.input.tab":{defaultKeys:`tab`,description:`Tab / autocomplete`},"tui.input.copy":{defaultKeys:`ctrl+c`,description:`Copy selection`},"tui.select.up":{defaultKeys:`up`,description:`Move selection up`},"tui.select.down":{defaultKeys:`down`,description:`Move selection down`},"tui.select.pageUp":{defaultKeys:`pageUp`,description:`Selection page up`},"tui.select.pageDown":{defaultKeys:`pageDown`,description:`Selection page down`},"tui.select.confirm":{defaultKeys:`enter`,description:`Confirm selection`},"tui.select.cancel":{defaultKeys:[`escape`,`ctrl+c`],description:`Cancel selection`},"tui.altScreen.pageUp":{defaultKeys:`pageUp`,description:`Scroll viewport up one page`},"tui.altScreen.pageDown":{defaultKeys:`pageDown`,description:`Scroll viewport down one page`},"tui.altScreen.halfPageUp":{defaultKeys:[],description:`Scroll viewport up half a page`},"tui.altScreen.halfPageDown":{defaultKeys:[],description:`Scroll viewport down half a page`},"tui.altScreen.lineUp":{defaultKeys:[],description:`Scroll viewport up one line`},"tui.altScreen.lineDown":{defaultKeys:[],description:`Scroll viewport down one line`},"tui.altScreen.previousPrompt":{defaultKeys:[`ctrl+shift+up`,`ctrl+up`],description:`Jump to previous semantic prompt`},"tui.altScreen.nextPrompt":{defaultKeys:[`ctrl+shift+down`,`ctrl+down`],description:`Jump to next semantic prompt`},"tui.altScreen.search":{defaultKeys:`ctrl+shift+f`,description:`Search the primary scroll view`},"tui.altScreen.searchNext":{defaultKeys:[`enter`,`ctrl+g`],description:`Select the next search match`},"tui.altScreen.searchPrevious":{defaultKeys:[`shift+enter`,`ctrl+shift+g`],description:`Select the previous search match`},"tui.altScreen.searchClose":{defaultKeys:`escape`,description:`Close transcript search`},"tui.altScreen.top":{defaultKeys:`home`,description:`Scroll viewport to top`},"tui.altScreen.bottom":{defaultKeys:`end`,description:`Scroll viewport to bottom`}};function Rr(e){if(e===void 0)return[];let t=Array.isArray(e)?e:[e],n=new Set,r=[];for(let e of t)n.has(e)||(n.add(e),r.push(e));return r}var zr=class{definitions;userBindings;keysById=new Map;conflicts=[];constructor(e,t={}){this.definitions=e,this.userBindings=t,this.rebuild()}rebuild(){this.keysById.clear(),this.conflicts=[];let e=new Map;for(let[t,n]of Object.entries(this.userBindings))if(t in this.definitions)for(let r of Rr(n)){let n=e.get(r)??new Set;n.add(t),e.set(r,n)}for(let[t,n]of e)n.size>1&&this.conflicts.push({key:t,keybindings:[...n]});for(let[e,t]of Object.entries(this.definitions)){let n=this.userBindings[e],r=Rr(n===void 0?t.defaultKeys:n);this.keysById.set(e,r)}}matches(e,t){let n=this.keysById.get(t)??[];for(let t of n)if(Y(e,t))return!0;return!1}getKeys(e){return[...this.keysById.get(e)??[]]}getDefinition(e){return this.definitions[e]}getConflicts(){return this.conflicts.map(e=>({...e,keybindings:[...e.keybindings]}))}setUserBindings(e){this.userBindings=e,this.rebuild()}getUserBindings(){return{...this.userBindings}}getResolvedBindings(){let e={};for(let t of Object.keys(this.definitions)){let n=this.keysById.get(t)??[];e[t]=n.length===1?n[0]:[...n]}return e}};let Br=null;function Vr(){return Br||=new zr(Lr),Br}var Hr=class{ring=[];push(e,t){if(e)if(t.accumulate&&this.ring.length>0){let n=this.ring.pop();this.ring.push(t.prepend?e+n:n+e)}else this.ring.push(e)}peek(){return this.ring.length>0?this.ring[this.ring.length-1]:void 0}rotate(){if(this.ring.length>1){let e=this.ring.pop();this.ring.unshift(e)}}get length(){return this.ring.length}},Ur=class{stack=[];push(e){this.stack.push(structuredClone(e))}pop(){return this.stack.pop()}clear(){this.stack.length=0}get length(){return this.stack.length}};const Wr=Xt();function Gr(e,t,n){if(t<=0)return 0;let r=e.slice(0,t),i=n?.segment,a=n?.isAtomicSegment,o=i?[...i(r)]:[...Wr.segment(r)],s=t;for(;o.length>0&&!a?.(o[o.length-1]?.segment||``)&&jn(o[o.length-1]?.segment||``);)s-=o.pop()?.segment.length||0;if(o.length===0)return s;let c=o[o.length-1];if(a?.(c.segment))s-=c.segment.length;else if(c.isWordLike){let e=c.segment,t=[...e.matchAll(new RegExp(An,`g`))];if(t.length<=0)s-=e.length;else{let n=t[t.length-1];s-=e.length-(n.index+n[0].length)}}else for(;o.length>0&&!a?.(o[o.length-1]?.segment||``)&&!o[o.length-1]?.isWordLike&&!jn(o[o.length-1]?.segment||``);)s-=o.pop()?.segment.length||0;return s}function Kr(e,t,n){if(t>=e.length)return e.length;let r=e.slice(t),i=n?.segment,a=n?.isAtomicSegment,o=(i?i(r):Wr.segment(r))[Symbol.iterator](),s=o.next(),c=t;for(;!s.done&&!a?.(s.value.segment)&&jn(s.value.segment);)c+=s.value.segment.length,s=o.next();if(s.done)return c;if(a?.(s.value.segment))c+=s.value.segment.length;else if(s.value.isWordLike)c+=An.exec(s.value.segment)?.index??s.value.segment.length;else for(;!s.done&&!a?.(s.value.segment)&&!s.value.isWordLike&&!jn(s.value.segment);)c+=s.value.segment.length,s=o.next();return c}const qr=e=>e.replace(/[\r\n]+/g,` `).trim(),Jr=(e,t,n)=>Math.max(t,Math.min(e,n));var Yr=class{items=[];filteredItems=[];selectedIndex=0;mousePressedIndex;maxVisible=5;theme;layout;onSelect;onCancel;onSelectionChange;constructor(e,t,n,r={}){this.items=e,this.filteredItems=e,this.maxVisible=t,this.theme=n,this.layout=r}setFilter(e){this.filteredItems=this.items.filter(t=>t.value.toLowerCase().startsWith(e.toLowerCase())),this.selectedIndex=0}setSelectedIndex(e){this.selectedIndex=Math.max(0,Math.min(e,this.filteredItems.length-1))}invalidate(){}render(e){let t=[];if(this.filteredItems.length===0)return t.push(this.theme.noMatch(` No matching commands`)),t;let n=this.getPrimaryColumnWidth(),{startIndex:r,endIndex:i}=this.getVisibleRange();for(let a=r;a<i;a++){let r=this.filteredItems[a];if(!r)continue;let i=a===this.selectedIndex,o=r.description?qr(r.description):void 0;t.push(this.renderItem(r,i,e,o,n))}if(r>0||i<this.filteredItems.length){let n=` (${this.selectedIndex+1}/${this.filteredItems.length})`;t.push(this.theme.scrollInfo(z(n,e-2,``)))}return t}handleMouse(e){if(this.filteredItems.length===0)return;if(e.type===`wheel`&&e.wheelDelta){let t=e.wheelDelta<0?-1:1,n=this.selectedIndex;return this.selectedIndex=Math.max(0,Math.min(this.filteredItems.length-1,this.selectedIndex+t)),this.selectedIndex!==n&&this.notifySelectionChange(),{handled:!0,render:this.selectedIndex!==n}}if(e.button!==`left`||e.type!==`press`&&e.type!==`click`)return;let{startIndex:t,endIndex:n}=this.getVisibleRange(),r=t+e.y;if(!(r<t||r>=n)){if(e.type===`press`)return this.mousePressedIndex=r,this.selectedIndex!==r&&(this.selectedIndex=r,this.notifySelectionChange()),{handled:!0,focus:!0};if(e.type===`click`){let e=this.mousePressedIndex??r;this.mousePressedIndex=void 0;let t=this.selectedIndex!==e;this.selectedIndex=e,t&&this.notifySelectionChange();let n=this.filteredItems[this.selectedIndex];return n&&this.onSelect?.(n),{handled:!0}}}}handleInput(e){let t=Vr();if(t.matches(e,`tui.select.up`))this.selectedIndex=this.selectedIndex===0?this.filteredItems.length-1:this.selectedIndex-1,this.notifySelectionChange();else if(t.matches(e,`tui.select.down`))this.selectedIndex=this.selectedIndex===this.filteredItems.length-1?0:this.selectedIndex+1,this.notifySelectionChange();else if(t.matches(e,`tui.select.confirm`)){let e=this.filteredItems[this.selectedIndex];e&&this.onSelect&&this.onSelect(e)}else t.matches(e,`tui.select.cancel`)&&this.onCancel&&this.onCancel()}getVisibleRange(){let e=Math.max(0,Math.min(this.selectedIndex-Math.floor(this.maxVisible/2),this.filteredItems.length-this.maxVisible));return{startIndex:e,endIndex:Math.min(e+this.maxVisible,this.filteredItems.length)}}renderItem(e,t,n,r,i){let a=t?`→ `:` `,o=L(a);if(r&&n>40){let s=Math.max(1,Math.min(i,n-o-4)),c=Math.max(1,s-2),l=this.truncatePrimary(e,t,c,s),u=L(l),d=` `.repeat(Math.max(1,s-u)),f=n-(o+u+d.length)-2;if(f>10){let e=z(r,f,``);if(t)return this.theme.selectedText(`${a}${l}${d}${e}`);let n=this.theme.description(d+e);return a+l+n}}let s=n-o-2,c=this.truncatePrimary(e,t,s,s);return t?this.theme.selectedText(`${a}${c}`):a+c}getPrimaryColumnWidth(){let{min:e,max:t}=this.getPrimaryColumnBounds();return Jr(this.filteredItems.reduce((e,t)=>Math.max(e,L(this.getDisplayValue(t))+2),0),e,t)}getPrimaryColumnBounds(){let e=this.layout.minPrimaryColumnWidth??this.layout.maxPrimaryColumnWidth??32,t=this.layout.maxPrimaryColumnWidth??this.layout.minPrimaryColumnWidth??32;return{min:Math.max(1,Math.min(e,t)),max:Math.max(1,Math.max(e,t))}}truncatePrimary(e,t,n,r){let i=this.getDisplayValue(e);return z(this.layout.truncatePrimary?this.layout.truncatePrimary({text:i,maxWidth:n,columnWidth:r,item:e,isSelected:t}):z(i,n,``),n,``)}getDisplayValue(e){return e.label||e.value}notifySelectionChange(){let e=this.filteredItems[this.selectedIndex];e&&this.onSelectionChange&&this.onSelectionChange(e)}getSelectedItem(){return this.filteredItems[this.selectedIndex]||null}};const Xr=Yt(),Zr=Xt(),Qr=/\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]/g,$r=/^\[paste #(\d+)( (\+\d+ lines|\d+ chars))?\]$/;function ei(e){return e.length>=10&&$r.test(e)}function ti(e,t,n){if(n.size===0||!e.includes(`[paste #`))return t.segment(e);let r=[];for(let t of e.matchAll(Qr)){let e=Number.parseInt(t[1],10);n.has(e)&&r.push({start:t.index,end:t.index+t[0].length})}if(r.length===0)return t.segment(e);let i=t.segment(e),a=[],o=0;for(let t of i){for(;o<r.length&&r[o].end<=t.index;)o++;let n=o<r.length?r[o]:null;if(n&&t.index>=n.start&&t.index<n.end){if(t.index===n.start){let t=e.slice(n.start,n.end);a.push({segment:t,index:n.start,input:e})}}else a.push(t)}return a}function ni(e,t,n){if(!e||t<=0)return[{text:``,startIndex:0,endIndex:0}];if(L(e)<=t)return[{text:e,startIndex:0,endIndex:e.length}];let r=[],i=n??[...Xr.segment(e)],a=0,o=0,s=-1,c=0;for(let n=0;n<i.length;n++){let l=i[n],u=l.segment,d=L(u),f=l.index,p=!ei(u)&&jn(u);if(a+d>t&&(s>=0&&a-c+d<=t?(r.push({text:e.slice(o,s),startIndex:o,endIndex:s}),o=s,a-=c):o<f&&(r.push({text:e.slice(o,f),startIndex:o,endIndex:f}),o=f,a=0),s=-1),d>t){let e=ni(u,t);for(let t=0;t<e.length-1;t++){let n=e[t];r.push({text:n.text,startIndex:f+n.startIndex,endIndex:f+n.endIndex})}let n=e[e.length-1];o=f+n.startIndex,a=L(n.text),s=-1;continue}a+=d;let m=i[n+1];if(p&&m&&(ei(m.segment)||!jn(m.segment)))s=m.index,c=a;else if(!p&&m&&!jn(m.segment)){let e=!ei(u)&&on.test(u),t=!ei(m.segment)&&on.test(m.segment);(e||t)&&(s=m.index,c=a)}}return r.push({text:e.slice(o),startIndex:o,endIndex:e.length}),r}const ri={minPrimaryColumnWidth:12,maxPrimaryColumnWidth:32},ii=[`@`,`#`],ai=RegExp(`(?:(?!${cn.source}).)*`,`u`),oi=`${ln.source}[([{<\`]*`;function si(e){return e.replace(/[\\^$.*+?()[\]{}|-]/g,`\\$&`)}function ci(e){return RegExp(`${oi}(?:@"[^"]*|[${e.map(si).join(``)}]${ai.source})$`,`u`)}function li(e){let t=e.filter(e=>e!==`@`).map(si);return RegExp(`${oi}(?:@(?:"[^"]*|${ai.source})|[${t.join(``)}]${ai.source})$`,`u`)}function ui(e,t,n){let r=Math.max(0,n),i=` ${e} ${t} more `,a=L(i);if(a+2<=r){let e=Math.floor((r-a)/2);return`─`.repeat(e)+i+`─`.repeat(r-e-a)}let o=`─── ${e} ${t} more `,s=r-L(o);if(s>=0)return o+`─`.repeat(s);let c=`...`.slice(0,r);return Pn(o,0,r-L(c),!0)+c}var di=class{state={lines:[``],cursorLine:0,cursorCol:0};focused=!1;tui;theme;paddingX=0;lastWidth=80;renderedVisibleLineCount=1;renderedAutocompleteHeight=0;scrollOffset=0;borderColor;autocompleteProvider;autocompleteTriggerCharacters=[...ii];autocompleteTriggerPattern=ci(this.autocompleteTriggerCharacters);autocompleteDebouncePattern=li(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 Hr;lastAction=null;jumpMode=null;preferredVisualCol=null;snappedFromCursorCol=null;undoStack=new Ur;onSubmit;onChange;disableSubmit=!1;constructor(e,t,n={}){this.tui=e,this.theme=t,this.borderColor=t.borderColor;let r=n.paddingX??0;this.paddingX=Number.isFinite(r)?Math.max(0,Math.floor(r)):0;let i=n.autocompleteMaxVisible??5;this.autocompleteMaxVisible=Number.isFinite(i)?Math.max(3,Math.min(20,Math.floor(i))):5}validPasteIds(){return new Set(this.pastes.keys())}segment(e,t){return ti(e,t===`word`?Zr:Xr,this.validPasteIds())}getPaddingX(){return this.paddingX}setPaddingX(e){let t=Number.isFinite(e)?Math.max(0,Math.floor(e)):0;this.paddingX!==t&&(this.paddingX=t,this.tui.requestRender())}getAutocompleteMaxVisible(){return this.autocompleteMaxVisible}setAutocompleteMaxVisible(e){let t=Number.isFinite(e)?Math.max(3,Math.min(20,Math.floor(e))):5;this.autocompleteMaxVisible!==t&&(this.autocompleteMaxVisible=t,this.tui.requestRender())}setAutocompleteProvider(e){this.cancelAutocomplete(),this.autocompleteProvider=e,this.setAutocompleteTriggerCharacters(e.triggerCharacters??[])}addToHistory(e){let t=e.trim();t&&(this.history.length>0&&this.history[0]===t||(this.history.unshift(t),this.history.length>100&&this.history.pop()))}isEditorEmpty(){return this.state.lines.length===1&&this.state.lines[0]===``}isOnFirstVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===0}isOnLastVisualLine(){let e=this.buildVisualLineMap(this.lastWidth);return this.findCurrentVisualLine(e)===e.length-1}navigateHistory(e){if(this.lastAction=null,this.history.length===0)return;let t=this.historyIndex-e;if(!(t<-1||t>=this.history.length))if(this.historyIndex===-1&&t>=0&&(this.pushUndoSnapshot(),this.historyDraft=structuredClone(this.state)),this.historyIndex=t,this.historyIndex===-1){let e=this.historyDraft;this.historyDraft=null,e?(this.state=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null,this.scrollOffset=0,this.onChange&&this.onChange(this.getText())):this.setTextInternal(``)}else this.setTextInternal(this.history[this.historyIndex]||``,e===-1?`start`:`end`)}exitHistoryBrowsing(){this.historyIndex=-1,this.historyDraft=null}setTextInternal(e,t=`end`){let n=e.split(`
|
|
87
|
+
`);this.state.lines=n.length===0?[``]:n,this.state.cursorLine=t===`start`?0:this.state.lines.length-1,this.setCursorCol(t===`start`?0:this.state.lines[this.state.cursorLine]?.length||0),this.scrollOffset=0,this.onChange&&this.onChange(this.getText())}invalidate(){}renderTopBorder(e,t){let n=t>0?ui(`↑`,t,e):`─`.repeat(e);return this.borderColor(n)}renderBottomBorder(e,t){let n=t>0?ui(`↓`,t,e):`─`.repeat(e);return this.borderColor(n)}render(e){let t=Math.max(0,Math.floor((e-1)/2)),n=Math.min(this.paddingX,t),r=Math.max(1,e-n*2),i=Math.max(1,r-+!n);this.lastWidth=i;let a=this.layoutText(i),o=this.tui.terminal.rows,s=Math.max(5,Math.floor(o*.3)),c=a.findIndex(e=>e.hasCursor);c===-1&&(c=0),c<this.scrollOffset?this.scrollOffset=c:c>=this.scrollOffset+s&&(this.scrollOffset=c-s+1);let l=Math.max(0,a.length-s);this.scrollOffset=Math.max(0,Math.min(this.scrollOffset,l));let u=a.slice(this.scrollOffset,this.scrollOffset+s);this.renderedVisibleLineCount=u.length;let d=[],f=` `.repeat(n),p=f;d.push(this.renderTopBorder(e,this.scrollOffset));let m=this.focused;for(let e of u){let t=e.text,i=L(e.text),a=!1;if(e.hasCursor&&e.cursorPos!==void 0){let o=t.slice(0,e.cursorPos),s=t.slice(e.cursorPos),c=m?jr:``;if(s.length>0){let e=[...this.segment(s,`grapheme`)][0]?.segment||``,n=s.slice(e.length),r=`\x1b[7m${e}\x1b[0m`;t=o+c+r+n}else t=o+c+`\x1B[7m \x1B[0m`,i+=1,i>r&&n>0&&(a=!0)}let o=` `.repeat(Math.max(0,r-i)),s=a?p.slice(1):p;d.push(`${f}${t}${o}${s}`)}let h=a.length-(this.scrollOffset+u.length);if(d.push(this.renderBottomBorder(e,h)),this.renderedAutocompleteHeight=0,this.autocompleteState&&this.autocompleteList){let e=this.autocompleteList.render(r);this.renderedAutocompleteHeight=e.length;for(let t of e){let e=L(t),n=` `.repeat(Math.max(0,r-e));d.push(`${f}${t}${n}${p}`)}}return d}handleMouse(e){let t=this.renderedVisibleLineCount+2;if(this.autocompleteState&&this.autocompleteList&&e.y>=t&&e.y<t+this.renderedAutocompleteHeight){let n=Math.max(0,Math.floor((e.width-1)/2)),r=Math.min(this.paddingX,n),i=Math.max(1,e.width-r*2),a=this.autocompleteList.handleMouse?.({...e,x:e.x-r,y:e.y-t,width:i,height:this.renderedAutocompleteHeight});return a?{...a,focus:!0}:void 0}if(e.type!==`click`||e.button!==`left`)return;if(e.y<=0||e.y>this.renderedVisibleLineCount)return{handled:!0,focus:!0};let n=this.buildVisualLineMap(this.lastWidth),r=this.scrollOffset+e.y-1,i=n[r];if(!i)return{handled:!0,focus:!0};let a=this.state.lines[i.logicalLine]??``,o=i.startCol+i.length,s=a.slice(i.startCol,o),c=Math.max(0,Math.floor((e.width-1)/2)),l=Math.min(this.paddingX,c),u=Math.max(0,e.x-l),d=0,f=s.length,p=0;for(let e of this.segment(s,`grapheme`)){let t=d+L(e.segment);if(p=e.index,u<t){f=e.index;break}d=t}return!(r===n.length-1||n[r+1]?.logicalLine!==i.logicalLine)&&f===s.length&&s.length>0&&(f=p),this.state.cursorLine=i.logicalLine,this.setCursorCol(i.startCol+f),this.lastAction=null,this.exitHistoryBrowsing(),this.autocompleteState&&this.updateAutocomplete(),{handled:!0,focus:!0}}handleInput(e){let t=Vr();if(this.jumpMode!==null){if(t.matches(e,`tui.editor.jumpForward`)||t.matches(e,`tui.editor.jumpBackward`)){this.jumpMode=null;return}let n=cr(e)??(e.charCodeAt(0)>=32?e:void 0);if(n!==void 0){let e=this.jumpMode;this.jumpMode=null,this.jumpToChar(n,e);return}this.jumpMode=null}if(e.includes(`\x1B[200~`)&&(this.isInPaste=!0,this.pasteBuffer=``,e=e.replace(`\x1B[200~`,``)),this.isInPaste){this.pasteBuffer+=e;let t=this.pasteBuffer.indexOf(`\x1B[201~`);if(t!==-1){let e=this.pasteBuffer.substring(0,t);e.length>0&&this.handlePaste(e),this.isInPaste=!1;let n=this.pasteBuffer.substring(t+6);this.pasteBuffer=``,n.length>0&&this.handleInput(n);return}return}if(t.matches(e,`tui.input.copy`))return;if(t.matches(e,`tui.editor.undo`)){this.undo();return}if(this.autocompleteState&&this.autocompleteList){if(t.matches(e,`tui.select.cancel`)){this.cancelAutocomplete();return}if(t.matches(e,`tui.select.up`)||t.matches(e,`tui.select.down`)){this.autocompleteList.handleInput(e);return}if(t.matches(e,`tui.input.tab`)){let e=this.autocompleteList.getSelectedItem();if(e&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,this.autocompletePrefix);this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText())}return}if(t.matches(e,`tui.select.confirm`)){let e=this.autocompleteList.getSelectedItem();if(e&&this.autocompleteProvider){this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,this.autocompletePrefix);if(this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.autocompletePrefix.startsWith(`/`))this.cancelAutocomplete();else{this.cancelAutocomplete(),this.onChange&&this.onChange(this.getText());return}}}}if(t.matches(e,`tui.input.tab`)&&!this.autocompleteState){this.handleTabCompletion();return}if(t.matches(e,`tui.editor.deleteToLineEnd`)){this.deleteToEndOfLine();return}if(t.matches(e,`tui.editor.deleteToLineStart`)){this.deleteToStartOfLine();return}if(t.matches(e,`tui.editor.deleteWordBackward`)){this.deleteWordBackwards();return}if(t.matches(e,`tui.editor.deleteWordForward`)){this.deleteWordForward();return}if(t.matches(e,`tui.editor.deleteCharBackward`)||Y(e,`shift+backspace`)){this.handleBackspace();return}if(t.matches(e,`tui.editor.deleteCharForward`)||Y(e,`shift+delete`)){this.handleForwardDelete();return}if(t.matches(e,`tui.editor.yank`)){this.yank();return}if(t.matches(e,`tui.editor.yankPop`)){this.yankPop();return}if(t.matches(e,`tui.editor.historyPrevious`)){this.cancelAutocomplete(),this.navigateHistory(-1);return}if(t.matches(e,`tui.editor.historyNext`)){this.cancelAutocomplete(),this.navigateHistory(1);return}if(t.matches(e,`tui.editor.cursorLineStart`)){this.moveToLineStart();return}if(t.matches(e,`tui.editor.cursorLineEnd`)){this.moveToLineEnd();return}if(t.matches(e,`tui.editor.cursorWordLeft`)){this.moveWordBackwards();return}if(t.matches(e,`tui.editor.cursorWordRight`)){this.moveWordForwards();return}if(t.matches(e,`tui.input.newLine`)||e.charCodeAt(0)===10&&e.length>1||e===`\x1B\r`||e===`\x1B[13;2~`||e.length>1&&e.includes(`\x1B`)&&e.includes(`\r`)||e===`
|
|
88
|
+
`&&e.length===1){if(this.shouldSubmitOnBackslashEnter(e,t)){this.handleBackspace(),this.submitValue();return}this.addNewLine();return}if(t.matches(e,`tui.input.submit`)){if(this.disableSubmit)return;let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol>0&&e[this.state.cursorCol-1]===`\\`){this.handleBackspace(),this.addNewLine();return}this.submitValue();return}if(t.matches(e,`tui.editor.cursorUp`)){this.isOnFirstVisualLine()&&(this.isEditorEmpty()||this.historyIndex>-1||this.state.cursorCol===0)?this.navigateHistory(-1):this.isOnFirstVisualLine()?this.moveToLineStart():this.moveCursor(-1,0);return}if(t.matches(e,`tui.editor.cursorDown`)){this.historyIndex>-1&&this.isOnLastVisualLine()?this.navigateHistory(1):this.isOnLastVisualLine()?this.moveToLineEnd():this.moveCursor(1,0);return}if(t.matches(e,`tui.editor.cursorRight`)){this.moveCursor(0,1);return}if(t.matches(e,`tui.editor.cursorLeft`)){this.moveCursor(0,-1);return}if(t.matches(e,`tui.editor.pageUp`)){this.pageScroll(-1);return}if(t.matches(e,`tui.editor.pageDown`)){this.pageScroll(1);return}if(t.matches(e,`tui.editor.jumpForward`)){this.jumpMode=`forward`;return}if(t.matches(e,`tui.editor.jumpBackward`)){this.jumpMode=`backward`;return}if(Y(e,`shift+space`)){this.insertCharacter(` `);return}let n=cr(e);if(n!==void 0){this.insertCharacter(n);return}e.charCodeAt(0)>=32&&this.insertCharacter(e)}layoutText(e){let t=[];if(this.state.lines.length===0||this.state.lines.length===1&&this.state.lines[0]===``)return t.push({text:``,hasCursor:!0,cursorPos:0}),t;for(let n=0;n<this.state.lines.length;n++){let r=this.state.lines[n]||``,i=n===this.state.cursorLine;if(L(r)<=e)i?t.push({text:r,hasCursor:!0,cursorPos:this.state.cursorCol}):t.push({text:r,hasCursor:!1});else{let n=ni(r,e,[...this.segment(r,`grapheme`)]);for(let e=0;e<n.length;e++){let r=n[e];if(!r)continue;let a=this.state.cursorCol,o=e===n.length-1,s=!1,c=0;i&&(o?(s=a>=r.startIndex,c=a-r.startIndex):(s=a>=r.startIndex&&a<r.endIndex,s&&(c=a-r.startIndex,c>r.text.length&&(c=r.text.length)))),s?t.push({text:r.text,hasCursor:!0,cursorPos:c}):t.push({text:r.text,hasCursor:!1})}}}return t}getText(){return this.state.lines.join(`
|
|
89
|
+
`)}expandPasteMarkers(e){let t=e;for(let[e,n]of this.pastes){let r=RegExp(`\\[paste #${e}( (\\+\\d+ lines|\\d+ chars))?\\]`,`g`);t=t.replace(r,()=>n)}return t}getExpandedText(){return this.expandPasteMarkers(this.state.lines.join(`
|
|
90
|
+
`))}getLines(){return[...this.state.lines]}getCursor(){return{line:this.state.cursorLine,col:this.state.cursorCol}}setText(e){this.cancelAutocomplete(),this.lastAction=null,this.exitHistoryBrowsing();let t=this.normalizeText(e);this.getText()!==t&&this.pushUndoSnapshot(),this.pastes.clear(),this.pasteCounter=0,this.setTextInternal(t)}insertTextAtCursor(e){e&&(this.cancelAutocomplete(),this.pushUndoSnapshot(),this.lastAction=null,this.exitHistoryBrowsing(),this.insertTextAtCursorInternal(e))}normalizeText(e){return e.replace(/\r\n/g,`
|
|
91
|
+
`).replace(/\r/g,`
|
|
92
|
+
`).replace(/\t/g,` `)}insertTextAtCursorInternal(e){if(!e)return;let t=this.normalizeText(e),n=t.split(`
|
|
93
|
+
`),r=this.state.lines[this.state.cursorLine]||``,i=r.slice(0,this.state.cursorCol),a=r.slice(this.state.cursorCol);n.length===1?(this.state.lines[this.state.cursorLine]=i+t+a,this.setCursorCol(this.state.cursorCol+t.length)):(this.state.lines=[...this.state.lines.slice(0,this.state.cursorLine),i+n[0],...n.slice(1,-1),n[n.length-1]+a,...this.state.lines.slice(this.state.cursorLine+1)],this.state.cursorLine+=n.length-1,this.setCursorCol((n[n.length-1]||``).length)),this.onChange&&this.onChange(this.getText())}insertCharacter(e,t){this.exitHistoryBrowsing(),t||((jn(e)||this.lastAction!==`type-word`)&&this.pushUndoSnapshot(),this.lastAction=`type-word`);let n=this.state.lines[this.state.cursorLine]||``,r=n.slice(0,this.state.cursorCol),i=n.slice(this.state.cursorCol);if(this.state.lines[this.state.cursorLine]=r+e+i,this.setCursorCol(this.state.cursorCol+e.length),this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else if(e===`/`&&this.isAtStartOfMessage())this.tryTriggerAutocomplete();else if(this.autocompleteTriggerCharacters.includes(e)){let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);this.autocompleteTriggerPattern.test(e)&&this.tryTriggerAutocomplete()}else if(/[a-zA-Z0-9.\-_]/.test(e)||on.test(e)){let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);(this.isInSlashCommandContext(e)||this.autocompleteTriggerPattern.test(e))&&this.tryTriggerAutocomplete()}}handlePaste(e){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let t=e.replace(/\x1b\[(\d+);5u/g,(e,t)=>{let n=Number(t);return n>=97&&n<=122?String.fromCharCode(n-96):n>=65&&n<=90?String.fromCharCode(n-64):e}),n=this.normalizeText(t).split(``).filter(e=>e===`
|
|
94
|
+
`||e.charCodeAt(0)>=32).join(``);if(/^[/~.]/.test(n)){let e=this.state.lines[this.state.cursorLine]||``,t=this.state.cursorCol>0?e[this.state.cursorCol-1]:``;t&&/\w/.test(t)&&(n=` ${n}`)}let r=n.split(`
|
|
95
|
+
`),i=n.length;if(r.length>10||i>1e3){this.pasteCounter++;let e=this.pasteCounter;this.pastes.set(e,n);let t=r.length>10?`[paste #${e} +${r.length} lines]`:`[paste #${e} ${i} chars]`;this.insertTextAtCursorInternal(t);return}if(r.length===1){this.insertTextAtCursorInternal(n);return}this.insertTextAtCursorInternal(n)}addNewLine(){this.cancelAutocomplete(),this.exitHistoryBrowsing(),this.lastAction=null,this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||``,t=e.slice(0,this.state.cursorCol),n=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=t,this.state.lines.splice(this.state.cursorLine+1,0,n),this.state.cursorLine++,this.setCursorCol(0),this.onChange&&this.onChange(this.getText())}shouldSubmitOnBackslashEnter(e,t){if(this.disableSubmit||!Y(e,`enter`))return!1;let n=t.getKeys(`tui.input.submit`);if(!(n.includes(`shift+enter`)||n.includes(`shift+return`)))return!1;let r=this.state.lines[this.state.cursorLine]||``;return this.state.cursorCol>0&&r[this.state.cursorCol-1]===`\\`}submitValue(){this.cancelAutocomplete();let e=this.expandPasteMarkers(this.state.lines.join(`
|
|
96
|
+
`)).trim();this.state={lines:[``],cursorLine:0,cursorCol:0},this.pastes.clear(),this.pasteCounter=0,this.exitHistoryBrowsing(),this.scrollOffset=0,this.undoStack.clear(),this.lastAction=null,this.onChange&&this.onChange(``),this.onSubmit&&this.onSubmit(e)}handleBackspace(){if(this.exitHistoryBrowsing(),this.lastAction=null,this.state.cursorCol>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||``,t=e.slice(0,this.state.cursorCol),n=[...this.segment(t,`grapheme`)],r=n[n.length-1],i=r?r.segment.length:1,a=$r.exec(r.segment);if(a){let e=Number(a[1]);this.pastes.delete(e),this.pasteCounter--;let t=[...this.pastes.keys()].filter(t=>t>e).sort((e,t)=>e-t);for(let e of t)this.pastes.set(e-1,this.pastes.get(e)),this.pastes.delete(e);this.state.lines=this.state.lines.map(t=>t.replace(Qr,(t,n,r)=>{let i=Number(n);return i<=e?t:`[paste #${i-1}${r}]`}))}e=this.state.lines[this.state.cursorLine]||``;let o=e.slice(0,this.state.cursorCol-i),s=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=o+s,this.setCursorCol(this.state.cursorCol-i)}else if(this.state.cursorLine>0){this.pushUndoSnapshot();let e=this.state.lines[this.state.cursorLine]||``,t=this.state.lines[this.state.cursorLine-1]||``;this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);(this.isInSlashCommandContext(e)||this.autocompleteTriggerPattern.test(e))&&this.tryTriggerAutocomplete()}}setCursorCol(e){this.state.cursorCol=e,this.preferredVisualCol=null,this.snappedFromCursorCol=null}moveToVisualLine(e,t,n){let r=e[t],i=e[n];if(!(r&&i))return;let a;if(this.snappedFromCursorCol!==null){let t=this.findVisualLineAt(e,r.logicalLine,this.snappedFromCursorCol);a=this.snappedFromCursorCol-e[t].startCol}else a=this.state.cursorCol-r.startCol;let o=t===e.length-1||e[t+1]?.logicalLine!==r.logicalLine?r.length:Math.max(0,r.length-1),s=n===e.length-1||e[n+1]?.logicalLine!==i.logicalLine?i.length:Math.max(0,i.length-1),c=this.computeVerticalMoveColumn(a,o,s);this.state.cursorLine=i.logicalLine;let l=i.startCol+c,u=this.state.lines[i.logicalLine]||``;this.state.cursorCol=Math.min(l,u.length);let d=[...this.segment(u,`grapheme`)];for(let r of d){if(r.index>this.state.cursorCol)break;if(!(r.segment.length<=1)&&this.state.cursorCol<r.index+r.segment.length){if(r.index<i.startCol&&n>t){let a=r.index+r.segment.length,o=n+1;for(;o<e.length&&e[o].logicalLine===i.logicalLine&&e[o].startCol<a;)o++;if(o<e.length){this.moveToVisualLine(e,t,o);return}}this.snappedFromCursorCol=this.state.cursorCol,this.state.cursorCol=r.index;return}}this.snappedFromCursorCol=null}computeVerticalMoveColumn(e,t,n){let r=this.preferredVisualCol!==null,i=e<t,a=n<e;if(!r||i)return a?(this.preferredVisualCol=e,n):(this.preferredVisualCol=null,e);let o=n<this.preferredVisualCol;if(a||o)return n;let s=this.preferredVisualCol;return this.preferredVisualCol=null,s}moveToLineStart(){this.lastAction=null,this.setCursorCol(0)}moveToLineEnd(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||``;this.setCursorCol(e.length)}deleteToStartOfLine(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol>0){this.pushUndoSnapshot();let t=e.slice(0,this.state.cursorCol);this.killRing.push(t,{prepend:!0,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`,this.state.lines[this.state.cursorLine]=e.slice(this.state.cursorCol),this.setCursorCol(0)}else if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
|
|
97
|
+
`,{prepend:!0,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`;let t=this.state.lines[this.state.cursorLine-1]||``;this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}this.onChange&&this.onChange(this.getText())}deleteToEndOfLine(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol);this.killRing.push(t,{prepend:!1,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`,this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
|
|
98
|
+
`,{prepend:!1,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`;let t=this.state.lines[this.state.cursorLine+1]||``;this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}this.onChange&&this.onChange(this.getText())}deleteWordBackwards(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.pushUndoSnapshot(),this.killRing.push(`
|
|
99
|
+
`,{prepend:!0,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`;let t=this.state.lines[this.state.cursorLine-1]||``;this.state.lines[this.state.cursorLine-1]=t+e,this.state.lines.splice(this.state.cursorLine,1),this.state.cursorLine--,this.setCursorCol(t.length)}}else{this.pushUndoSnapshot();let t=this.lastAction===`kill`,n=this.state.cursorCol;this.moveWordBackwards();let r=this.state.cursorCol;this.setCursorCol(n);let i=e.slice(r,this.state.cursorCol);this.killRing.push(i,{prepend:!0,accumulate:t}),this.lastAction=`kill`,this.state.lines[this.state.cursorLine]=e.slice(0,r)+e.slice(this.state.cursorCol),this.setCursorCol(r)}this.onChange&&this.onChange(this.getText())}deleteWordForward(){this.exitHistoryBrowsing();let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol>=e.length){if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot(),this.killRing.push(`
|
|
100
|
+
`,{prepend:!1,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`;let t=this.state.lines[this.state.cursorLine+1]||``;this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}}else{this.pushUndoSnapshot();let t=this.lastAction===`kill`,n=this.state.cursorCol;this.moveWordForwards();let r=this.state.cursorCol;this.setCursorCol(n);let i=e.slice(this.state.cursorCol,r);this.killRing.push(i,{prepend:!1,accumulate:t}),this.lastAction=`kill`,this.state.lines[this.state.cursorLine]=e.slice(0,this.state.cursorCol)+e.slice(r)}this.onChange&&this.onChange(this.getText())}handleForwardDelete(){this.exitHistoryBrowsing(),this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol<e.length){this.pushUndoSnapshot();let t=e.slice(this.state.cursorCol),n=[...this.segment(t,`grapheme`)][0],r=n?n.segment.length:1,i=e.slice(0,this.state.cursorCol),a=e.slice(this.state.cursorCol+r);this.state.lines[this.state.cursorLine]=i+a}else if(this.state.cursorLine<this.state.lines.length-1){this.pushUndoSnapshot();let t=this.state.lines[this.state.cursorLine+1]||``;this.state.lines[this.state.cursorLine]=e+t,this.state.lines.splice(this.state.cursorLine+1,1)}if(this.onChange&&this.onChange(this.getText()),this.autocompleteState)this.updateAutocomplete();else{let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);(this.isInSlashCommandContext(e)||this.autocompleteTriggerPattern.test(e))&&this.tryTriggerAutocomplete()}}buildVisualLineMap(e){let t=[];for(let n=0;n<this.state.lines.length;n++){let r=this.state.lines[n]||``,i=L(r);if(r.length===0)t.push({logicalLine:n,startCol:0,length:0});else if(i<=e)t.push({logicalLine:n,startCol:0,length:r.length});else{let i=ni(r,e,[...this.segment(r,`grapheme`)]);for(let e of i)t.push({logicalLine:n,startCol:e.startIndex,length:e.endIndex-e.startIndex})}}return t}findVisualLineAt(e,t,n){for(let r=0;r<e.length;r++){let i=e[r];if(!i||i.logicalLine!==t)continue;let a=n-i.startCol,o=r===e.length-1||e[r+1]?.logicalLine!==i.logicalLine;if(a>=0&&(a<i.length||o&&a===i.length))return r}return e.length-1}findCurrentVisualLine(e){return this.findVisualLineAt(e,this.state.cursorLine,this.state.cursorCol)}moveCursor(e,t){this.lastAction=null;let n=this.buildVisualLineMap(this.lastWidth),r=this.findCurrentVisualLine(n);if(e!==0){let t=r+e;t>=0&&t<n.length&&this.moveToVisualLine(n,r,t)}if(t!==0){let e=this.state.lines[this.state.cursorLine]||``;if(t>0)if(this.state.cursorCol<e.length){let t=e.slice(this.state.cursorCol),n=[...this.segment(t,`grapheme`)][0];this.setCursorCol(this.state.cursorCol+(n?n.segment.length:1))}else if(this.state.cursorLine<this.state.lines.length-1)this.state.cursorLine++,this.setCursorCol(0);else{let e=n[r];e&&(this.preferredVisualCol=this.state.cursorCol-e.startCol)}else if(this.state.cursorCol>0){let t=e.slice(0,this.state.cursorCol),n=[...this.segment(t,`grapheme`)],r=n[n.length-1];this.setCursorCol(this.state.cursorCol-(r?r.segment.length:1))}else if(this.state.cursorLine>0){this.state.cursorLine--;let e=this.state.lines[this.state.cursorLine]||``;this.setCursorCol(e.length)}}this.autocompleteState&&this.updateAutocomplete()}pageScroll(e){this.lastAction=null;let t=this.tui.terminal.rows,n=Math.max(5,Math.floor(t*.3)),r=this.buildVisualLineMap(this.lastWidth),i=this.findCurrentVisualLine(r),a=Math.max(0,Math.min(r.length-1,i+e*n));this.moveToVisualLine(r,i,a)}moveWordBackwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol===0){if(this.state.cursorLine>0){this.state.cursorLine--;let e=this.state.lines[this.state.cursorLine]||``;this.setCursorCol(e.length)}return}this.setCursorCol(Gr(e,this.state.cursorCol,{segment:e=>this.segment(e,`word`),isAtomicSegment:ei}))}yank(){if(this.killRing.length===0)return;this.pushUndoSnapshot();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction=`yank`}yankPop(){if(this.lastAction!==`yank`||this.killRing.length<=1)return;this.pushUndoSnapshot(),this.deleteYankedText(),this.killRing.rotate();let e=this.killRing.peek();this.insertYankedText(e),this.lastAction=`yank`}insertYankedText(e){this.exitHistoryBrowsing();let t=e.split(`
|
|
101
|
+
`);if(t.length===1){let t=this.state.lines[this.state.cursorLine]||``,n=t.slice(0,this.state.cursorCol),r=t.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+e+r,this.setCursorCol(this.state.cursorCol+e.length)}else{let e=this.state.lines[this.state.cursorLine]||``,n=e.slice(0,this.state.cursorCol),r=e.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=n+(t[0]||``);for(let e=1;e<t.length-1;e++)this.state.lines.splice(this.state.cursorLine+e,0,t[e]||``);let i=this.state.cursorLine+t.length-1;this.state.lines.splice(i,0,(t[t.length-1]||``)+r),this.state.cursorLine=i,this.setCursorCol((t[t.length-1]||``).length)}this.onChange&&this.onChange(this.getText())}deleteYankedText(){let e=this.killRing.peek();if(!e)return;let t=e.split(`
|
|
102
|
+
`);if(t.length===1){let t=this.state.lines[this.state.cursorLine]||``,n=e.length,r=t.slice(0,this.state.cursorCol-n),i=t.slice(this.state.cursorCol);this.state.lines[this.state.cursorLine]=r+i,this.setCursorCol(this.state.cursorCol-n)}else{let e=this.state.cursorLine-(t.length-1),n=(this.state.lines[e]||``).length-(t[0]||``).length,r=(this.state.lines[this.state.cursorLine]||``).slice(this.state.cursorCol),i=(this.state.lines[e]||``).slice(0,n);this.state.lines.splice(e,t.length,i+r),this.state.cursorLine=e,this.setCursorCol(n)}this.onChange&&this.onChange(this.getText())}pushUndoSnapshot(){this.undoStack.push({state:this.state,pastes:this.pastes,pasteCounter:this.pasteCounter})}undo(){this.exitHistoryBrowsing();let e=this.undoStack.pop();e&&(Object.assign(this.state,e.state),this.pastes=e.pastes,this.pasteCounter=e.pasteCounter,this.lastAction=null,this.preferredVisualCol=null,this.onChange&&this.onChange(this.getText()))}jumpToChar(e,t){this.lastAction=null;let n=t===`forward`,r=this.state.lines,i=n?r.length:-1,a=n?1:-1;for(let t=this.state.cursorLine;t!==i;t+=a){let i=r[t]||``,a=t===this.state.cursorLine?n?this.state.cursorCol+1:this.state.cursorCol-1:void 0,o=n?i.indexOf(e,a):i.lastIndexOf(e,a);if(o!==-1){this.state.cursorLine=t,this.setCursorCol(o);return}}}moveWordForwards(){this.lastAction=null;let e=this.state.lines[this.state.cursorLine]||``;if(this.state.cursorCol>=e.length){this.state.cursorLine<this.state.lines.length-1&&(this.state.cursorLine++,this.setCursorCol(0));return}this.setCursorCol(Kr(e,this.state.cursorCol,{segment:e=>this.segment(e,`word`),isAtomicSegment:ei}))}isSlashMenuAllowed(){return this.state.cursorLine===0}isAtStartOfMessage(){if(!this.isSlashMenuAllowed())return!1;let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);return e.trim()===``||e.trim()===`/`}isInSlashCommandContext(e){return this.isSlashMenuAllowed()&&e.trimStart().startsWith(`/`)}getBestAutocompleteMatchIndex(e,t){if(!t)return-1;let n=-1;for(let r=0;r<e.length;r++){let i=e[r].value;if(i===t)return r;n===-1&&i.startsWith(t)&&(n=r)}return n}createAutocompleteList(e,t){let n=e.startsWith(`/`)?ri:void 0,r=new Yr(t,this.autocompleteMaxVisible,this.theme.selectList,n);return r.onSelect=e=>{if(!this.autocompleteProvider)return;this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,this.autocompletePrefix);this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.cancelAutocomplete(),this.onChange?.(this.getText())},r}tryTriggerAutocomplete(e=!1){this.requestAutocomplete({force:!1,explicitTab:e})}handleTabCompletion(){if(!this.autocompleteProvider)return;let e=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);this.isInSlashCommandContext(e)&&!e.trimStart().includes(` `)?this.handleSlashCommandCompletion():this.forceFileAutocomplete(!0)}handleSlashCommandCompletion(){this.requestAutocomplete({force:!1,explicitTab:!0})}forceFileAutocomplete(e=!1){this.requestAutocomplete({force:!0,explicitTab:e})}requestAutocomplete(e){if(!this.autocompleteProvider||e.force&&!(!this.autocompleteProvider.shouldTriggerFileCompletion||this.autocompleteProvider.shouldTriggerFileCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol)))return;this.cancelAutocompleteRequest();let t=++this.autocompleteStartToken,n=this.getAutocompleteDebounceMs(e);if(n>0){this.autocompleteDebounceTimer=setTimeout(()=>{this.autocompleteDebounceTimer=void 0,this.startAutocompleteRequest(t,e)},n);return}this.startAutocompleteRequest(t,e)}async startAutocompleteRequest(e,t){let n=this.autocompleteRequestTask;this.autocompleteRequestTask=(async()=>{if(await n,e!==this.autocompleteStartToken||!this.autocompleteProvider)return;let r=new AbortController;this.autocompleteAbort=r;let i=++this.autocompleteRequestId,a=this.getText(),o=this.state.cursorLine,s=this.state.cursorCol;await this.runAutocompleteRequest(i,r,a,o,s,t)})(),await this.autocompleteRequestTask}setAutocompleteTriggerCharacters(e){let t=[...ii];for(let n of e)n.length!==1||n===`/`||jn(n)||t.includes(n)||t.push(n);this.autocompleteTriggerCharacters=t,this.autocompleteTriggerPattern=ci(t),this.autocompleteDebouncePattern=li(t)}getAutocompleteDebounceMs(e){if(e.explicitTab||e.force)return 0;let t=(this.state.lines[this.state.cursorLine]||``).slice(0,this.state.cursorCol);return this.autocompleteDebouncePattern.test(t)?20:0}async runAutocompleteRequest(e,t,n,r,i,a){if(!this.autocompleteProvider)return;let o=await this.autocompleteProvider.getSuggestions(this.state.lines,this.state.cursorLine,this.state.cursorCol,{signal:t.signal,force:a.force});if(this.isAutocompleteRequestCurrent(e,t,n,r,i)){if(this.autocompleteAbort=void 0,!o||!Array.isArray(o.items)||o.items.length===0){this.cancelAutocomplete(),this.tui.requestRender();return}if(a.force&&a.explicitTab&&o.items.length===1){let e=o.items[0];this.pushUndoSnapshot(),this.lastAction=null;let t=this.autocompleteProvider.applyCompletion(this.state.lines,this.state.cursorLine,this.state.cursorCol,e,o.prefix);this.state.lines=t.lines,this.state.cursorLine=t.cursorLine,this.setCursorCol(t.cursorCol),this.onChange&&this.onChange(this.getText()),this.tui.requestRender();return}this.applyAutocompleteSuggestions(o,a.force?`force`:`regular`),this.tui.requestRender()}}isAutocompleteRequestCurrent(e,t,n,r,i){return!t.signal.aborted&&e===this.autocompleteRequestId&&this.getText()===n&&this.state.cursorLine===r&&this.state.cursorCol===i}applyAutocompleteSuggestions(e,t){this.autocompletePrefix=e.prefix,this.autocompleteList=this.createAutocompleteList(e.prefix,e.items);let n=this.getBestAutocompleteMatchIndex(e.items,e.prefix);n>=0&&this.autocompleteList.setSelectedIndex(n),this.autocompleteState=t}cancelAutocompleteRequest(){this.autocompleteStartToken+=1,this.autocompleteDebounceTimer&&=(clearTimeout(this.autocompleteDebounceTimer),void 0),this.autocompleteAbort?.abort(),this.autocompleteAbort=void 0}clearAutocompleteUi(){this.autocompleteState=null,this.autocompleteList=void 0,this.autocompletePrefix=``}cancelAutocomplete(){this.cancelAutocompleteRequest(),this.clearAutocompleteUi()}isShowingAutocomplete(){return this.autocompleteState!==null}updateAutocomplete(){!this.autocompleteState||!this.autocompleteProvider||this.requestAutocomplete({force:this.autocompleteState===`force`,explicitTab:!1})}};const fi=Yt();var pi=class{value=``;cursor=0;prompt;placeholder;placeholderStyle;renderedStartColumn=0;onSubmit;onEscape;focused=!1;pasteBuffer=``;isInPaste=!1;killRing=new Hr;lastAction=null;undoStack=new Ur;constructor(e={}){this.prompt=e.prompt??`> `,this.placeholder=e.placeholder??``,this.placeholderStyle=e.placeholderStyle??(e=>e)}getValue(){return this.value}setValue(e){this.value=e,this.cursor=Math.min(this.cursor,e.length)}handleInput(e){if(e.includes(`\x1B[200~`)&&(this.isInPaste=!0,this.pasteBuffer=``,e=e.replace(`\x1B[200~`,``)),this.isInPaste){this.pasteBuffer+=e;let t=this.pasteBuffer.indexOf(`\x1B[201~`);if(t!==-1){let e=this.pasteBuffer.substring(0,t);this.handlePaste(e),this.isInPaste=!1;let n=this.pasteBuffer.substring(t+6);this.pasteBuffer=``,n&&this.handleInput(n)}return}let t=Vr();if(t.matches(e,`tui.select.cancel`)){this.onEscape&&this.onEscape();return}if(t.matches(e,`tui.editor.undo`)){this.undo();return}if(t.matches(e,`tui.input.submit`)||e===`
|
|
103
|
+
`){this.onSubmit&&this.onSubmit(this.value);return}if(t.matches(e,`tui.editor.deleteCharBackward`)){this.handleBackspace();return}if(t.matches(e,`tui.editor.deleteCharForward`)){this.handleForwardDelete();return}if(t.matches(e,`tui.editor.deleteWordBackward`)){this.deleteWordBackwards();return}if(t.matches(e,`tui.editor.deleteWordForward`)){this.deleteWordForward();return}if(t.matches(e,`tui.editor.deleteToLineStart`)){this.deleteToLineStart();return}if(t.matches(e,`tui.editor.deleteToLineEnd`)){this.deleteToLineEnd();return}if(t.matches(e,`tui.editor.yank`)){this.yank();return}if(t.matches(e,`tui.editor.yankPop`)){this.yankPop();return}if(t.matches(e,`tui.editor.cursorLeft`)){if(this.lastAction=null,this.cursor>0){let e=this.value.slice(0,this.cursor),t=[...fi.segment(e)],n=t[t.length-1];this.cursor-=n?n.segment.length:1}return}if(t.matches(e,`tui.editor.cursorRight`)){if(this.lastAction=null,this.cursor<this.value.length){let e=this.value.slice(this.cursor),t=[...fi.segment(e)][0];this.cursor+=t?t.segment.length:1}return}if(t.matches(e,`tui.editor.cursorLineStart`)){this.lastAction=null,this.cursor=0;return}if(t.matches(e,`tui.editor.cursorLineEnd`)){this.lastAction=null,this.cursor=this.value.length;return}if(t.matches(e,`tui.editor.cursorWordLeft`)){this.moveWordBackwards();return}if(t.matches(e,`tui.editor.cursorWordRight`)){this.moveWordForwards();return}let n=or(e);if(n!==void 0){this.insertCharacter(n);return}[...e].some(e=>{let t=e.charCodeAt(0);return t<32||t===127||t>=128&&t<=159})||this.insertCharacter(e)}handleMouse(e){if(e.type!==`press`||e.button!==`left`||e.y!==0)return;let t=Math.max(0,e.x-2),n=this.renderedStartColumn+t,r=0;this.cursor=this.value.length;for(let e of fi.segment(this.value)){let t=r+L(e.segment);if(n<t){this.cursor=e.index;break}r=t}return this.lastAction=null,{handled:!0,focus:!0}}insertCharacter(e){(jn(e)||this.lastAction!==`type-word`)&&this.pushUndo(),this.lastAction=`type-word`,this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length}handleBackspace(){if(this.lastAction=null,this.cursor>0){this.pushUndo();let e=this.value.slice(0,this.cursor),t=[...fi.segment(e)],n=t[t.length-1],r=n?n.segment.length:1;this.value=this.value.slice(0,this.cursor-r)+this.value.slice(this.cursor),this.cursor-=r}}handleForwardDelete(){if(this.lastAction=null,this.cursor<this.value.length){this.pushUndo();let e=this.value.slice(this.cursor),t=[...fi.segment(e)][0],n=t?t.segment.length:1;this.value=this.value.slice(0,this.cursor)+this.value.slice(this.cursor+n)}}deleteToLineStart(){if(this.cursor===0)return;this.pushUndo();let e=this.value.slice(0,this.cursor);this.killRing.push(e,{prepend:!0,accumulate:this.lastAction===`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 e=this.value.slice(this.cursor);this.killRing.push(e,{prepend:!1,accumulate:this.lastAction===`kill`}),this.lastAction=`kill`,this.value=this.value.slice(0,this.cursor)}deleteWordBackwards(){if(this.cursor===0)return;let e=this.lastAction===`kill`;this.pushUndo();let t=this.cursor;this.moveWordBackwards();let n=this.cursor;this.cursor=t;let r=this.value.slice(n,this.cursor);this.killRing.push(r,{prepend:!0,accumulate:e}),this.lastAction=`kill`,this.value=this.value.slice(0,n)+this.value.slice(this.cursor),this.cursor=n}deleteWordForward(){if(this.cursor>=this.value.length)return;let e=this.lastAction===`kill`;this.pushUndo();let t=this.cursor;this.moveWordForwards();let n=this.cursor;this.cursor=t;let r=this.value.slice(this.cursor,n);this.killRing.push(r,{prepend:!1,accumulate:e}),this.lastAction=`kill`,this.value=this.value.slice(0,this.cursor)+this.value.slice(n)}yank(){let e=this.killRing.peek();e&&(this.pushUndo(),this.value=this.value.slice(0,this.cursor)+e+this.value.slice(this.cursor),this.cursor+=e.length,this.lastAction=`yank`)}yankPop(){if(this.lastAction!==`yank`||this.killRing.length<=1)return;this.pushUndo();let e=this.killRing.peek()||``;this.value=this.value.slice(0,this.cursor-e.length)+this.value.slice(this.cursor),this.cursor-=e.length,this.killRing.rotate();let t=this.killRing.peek()||``;this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length,this.lastAction=`yank`}pushUndo(){this.undoStack.push({value:this.value,cursor:this.cursor})}undo(){let e=this.undoStack.pop();e&&(this.value=e.value,this.cursor=e.cursor,this.lastAction=null)}moveWordBackwards(){this.cursor!==0&&(this.lastAction=null,this.cursor=Gr(this.value,this.cursor))}moveWordForwards(){this.cursor>=this.value.length||(this.lastAction=null,this.cursor=Kr(this.value,this.cursor))}handlePaste(e){this.lastAction=null,this.pushUndo();let t=e.replace(/\r\n/g,``).replace(/\r/g,``).replace(/\n/g,``).replace(/\t/g,` `);this.value=this.value.slice(0,this.cursor)+t+this.value.slice(this.cursor),this.cursor+=t.length}invalidate(){}render(e){let t=e-L(this.prompt);if(t<=0)return[z(this.prompt,e,``)];if(this.value.length===0&&this.placeholder){let e=z(this.placeholder,t,``),n=[...fi.segment(e)][0]?.segment??` `,r=e.slice(n.length),i=(this.focused?jr:``)+`\x1b[7m${this.placeholderStyle(n)}\x1b[27m`+this.placeholderStyle(r),a=` `.repeat(Math.max(0,t-L(i)));return[this.prompt+i+a]}let n=``,r=this.cursor;this.renderedStartColumn=0;let i=L(this.value);if(i<t)n=this.value;else{let e=this.cursor===this.value.length?t-1:t,a=L(this.value.slice(0,this.cursor));if(e>0){let t=Math.floor(e/2),o=0;o=a<t?0:a>i-t?Math.max(0,i-e):Math.max(0,a-t),this.renderedStartColumn=o,n=Pn(this.value,o,e,!0),r=Pn(this.value,o,Math.max(0,a-o),!0).length}else n=``,r=0}let a=[...fi.segment(n.slice(r))][0],o=n.slice(0,r),s=a?.segment??` `,c=n.slice(r+s.length),l=this.focused?jr:``,u=`\x1b[7m${s}\x1b[27m`,d=o+l+u+c,f=L(d),p=` `.repeat(Math.max(0,t-f));return[this.prompt+d+p]}};const mi={alpha:`α`,beta:`β`,gamma:`γ`,delta:`δ`,epsilon:`ϵ`,varepsilon:`ε`,zeta:`ζ`,eta:`η`,theta:`θ`,vartheta:`ϑ`,iota:`ι`,kappa:`κ`,varkappa:`ϰ`,lambda:`λ`,mu:`μ`,nu:`ν`,xi:`ξ`,pi:`π`,varpi:`ϖ`,rho:`ρ`,varrho:`ϱ`,sigma:`σ`,varsigma:`ς`,tau:`τ`,upsilon:`υ`,phi:`ϕ`,varphi:`φ`,chi:`χ`,psi:`ψ`,omega:`ω`,Gamma:`Γ`,Delta:`Δ`,Theta:`Θ`,Lambda:`Λ`,Xi:`Ξ`,Pi:`Π`,Sigma:`Σ`,Upsilon:`Υ`,Phi:`Φ`,Psi:`Ψ`,Omega:`Ω`,pm:`±`,mp:`∓`,times:`×`,div:`÷`,cdot:`·`,ast:`∗`,star:`⋆`,circ:`∘`,bullet:`•`,oplus:`⊕`,ominus:`⊖`,otimes:`⊗`,oslash:`⊘`,odot:`⊙`,bigcirc:`○`,dagger:`†`,ddagger:`‡`,amalg:`⨿`,uplus:`⊎`,sqcap:`⊓`,sqcup:`⊔`,bowtie:`⋈`,Join:`⋈`,ltimes:`⋉`,rtimes:`⋊`,leftouterjoin:`⟕`,rightouterjoin:`⟖`,fullouterjoin:`⟗`,triangleleft:`◁`,triangleright:`▷`,wr:`≀`,cap:`∩`,cup:`∪`,bigcap:`⋂`,bigcup:`⋃`,bigwedge:`⋀`,bigvee:`⋁`,bigsqcup:`⨆`,biguplus:`⨄`,bigoplus:`⨁`,bigotimes:`⨂`,bigodot:`⨀`,setminus:`∖`,in:`∈`,notin:`∉`,ni:`∋`,subset:`⊂`,supset:`⊃`,subseteq:`⊆`,supseteq:`⊇`,sqsubset:`⊏`,sqsupset:`⊐`,sqsubseteq:`⊑`,sqsupseteq:`⊒`,prec:`≺`,preceq:`≼`,succ:`≻`,succeq:`≽`,ll:`≪`,gg:`≫`,le:`≤`,leq:`≤`,leqslant:`≤`,ge:`≥`,geq:`≥`,geqslant:`≥`,ne:`≠`,neq:`≠`,equiv:`≡`,approx:`≈`,sim:`∼`,simeq:`≃`,cong:`≅`,asymp:`≍`,doteq:`≐`,propto:`∝`,parallel:`∥`,perp:`⊥`,mid:`∣`,vdash:`⊢`,dashv:`⊣`,models:`⊨`,Vdash:`⊩`,Vvdash:`⊪`,nvdash:`⊬`,nvDash:`⊭`,forall:`∀`,exists:`∃`,nexists:`∄`,neg:`¬`,land:`∧`,wedge:`∧`,lor:`∨`,vee:`∨`,to:`→`,rightarrow:`→`,longrightarrow:`→`,leftarrow:`←`,longleftarrow:`←`,gets:`←`,leftrightarrow:`↔`,longleftrightarrow:`↔`,hookleftarrow:`↩`,hookrightarrow:`↪`,twoheadleftarrow:`↞`,twoheadrightarrow:`↠`,leftharpoonup:`↼`,leftharpoondown:`↽`,rightharpoonup:`⇀`,rightharpoondown:`⇁`,rightleftharpoons:`⇌`,leftrightharpoons:`⇋`,nearrow:`↗`,searrow:`↘`,swarrow:`↙`,nwarrow:`↖`,rightsquigarrow:`⇝`,leadsto:`⇝`,Rightarrow:`⇒`,Longrightarrow:`⇒`,Leftarrow:`⇐`,Longleftarrow:`⇐`,Leftrightarrow:`⇔`,Longleftrightarrow:`⇔`,implies:`⇒`,iff:`⇔`,mapsto:`↦`,longmapsto:`↦`,uparrow:`↑`,downarrow:`↓`,partial:`∂`,nabla:`∇`,int:`∫`,iint:`∬`,iiint:`∭`,oint:`∮`,sum:`∑`,prod:`∏`,coprod:`∐`,infty:`∞`,emptyset:`∅`,varnothing:`∅`,angle:`∠`,therefore:`∴`,because:`∵`,aleph:`ℵ`,beth:`ℶ`,gimel:`ℷ`,daleth:`ℸ`,top:`⊤`,bot:`⊥`,triangle:`△`,square:`□`,lozenge:`◊`,checkmark:`✓`,complement:`∁`,wp:`℘`,prime:`′`,ldots:`…`,dots:`…`,cdots:`⋯`,vdots:`⋮`,ddots:`⋱`,ell:`ℓ`,hbar:`ℏ`,Im:`ℑ`,Re:`ℜ`,langle:`⟨`,rangle:`⟩`,vert:`|`,lvert:`|`,rvert:`|`,Vert:`‖`,lVert:`‖`,rVert:`‖`,lbrace:`{`,rbrace:`}`,backslash:`\\`,lfloor:`⌊`,rfloor:`⌋`,lceil:`⌈`,rceil:`⌉`,colon:`:`},hi=new Set(`arccos.arcsin.arctan.arg.cos.cosh.cot.coth.csc.deg.det.dim.exp.gcd.hom.inf.ker.lg.lim.liminf.limsup.ln.log.max.min.Pr.sec.sin.sinh.sup.tan.tanh`.split(`.`)),gi=new Set([`argmax`,`argmin`,`inf`,`injlim`,`lim`,`liminf`,`limsup`,`max`,`min`,`projlim`,`sup`]),_i=new Set([`bigcap`,`bigcup`,`bigodot`,`bigoplus`,`bigotimes`,`bigsqcup`,`biguplus`,`bigvee`,`bigwedge`,`coprod`,`int`,`iint`,`iiint`,`oint`,`prod`,`sum`]),vi=new Set(`Leftarrow.Leftrightarrow.Longleftarrow.Longleftrightarrow.Longrightarrow.Rightarrow.Join.Vdash.Vvdash.approx.asymp.bowtie.cong.dashv.fullouterjoin.doteq.downarrow.equiv.ge.geq.geqslant.gets.gg.hookleftarrow.hookrightarrow.iff.implies.in.leadsto.le.leftarrow.leftharpoondown.leftharpoonup.leftrightarrow.leftrightharpoons.leftouterjoin.leq.leqslant.ll.longleftarrow.longleftrightarrow.longmapsto.longrightarrow.ltimes.mapsto.mid.models.ne.nearrow.neq.ni.notin.nvdash.nvDash.nwarrow.parallel.perp.prec.preceq.propto.rightharpoondown.rightharpoonup.rightleftharpoons.rightouterjoin.rightarrow.rightsquigarrow.rtimes.searrow.sim.simeq.sqsubset.sqsubseteq.sqsupset.sqsupseteq.subset.subseteq.succ.succeq.supset.supseteq.swarrow.to.triangleleft.triangleright.twoheadleftarrow.twoheadrightarrow.uparrow.vdash`.split(`.`)),yi={"<":`≮`,">":`≯`,"=":`≠`,"∈":`∉`,"∋":`∌`,"∣":`∤`,"∥":`∦`,"∼":`≁`,"≃":`≄`,"≅":`≇`,"≈":`≉`,"≡":`≢`,"≤":`≰`,"≥":`≱`,"≺":`⊀`,"≻":`⊁`,"⊂":`⊄`,"⊃":`⊅`,"⊆":`⊈`,"⊇":`⊉`,"⊢":`⊬`,"⊨":`⊭`,"↔":`↮`,"←":`↚`,"→":`↛`,"⇒":`⇏`,"⇐":`⇍`,"⇔":`⇎`,"≼":`⋠`,"≽":`⋡`},bi={C:`ℂ`,H:`ℍ`,N:`ℕ`,P:`ℙ`,Q:`ℚ`,R:`ℝ`,Z:`ℤ`},xi={0:`⁰`,1:`¹`,2:`²`,3:`³`,4:`⁴`,5:`⁵`,6:`⁶`,7:`⁷`,8:`⁸`,9:`⁹`,"+":`⁺`,"-":`⁻`,"=":`⁼`,"(":`⁽`,")":`⁾`,a:`ᵃ`,b:`ᵇ`,c:`ᶜ`,d:`ᵈ`,e:`ᵉ`,f:`ᶠ`,g:`ᵍ`,h:`ʰ`,i:`ⁱ`,j:`ʲ`,k:`ᵏ`,l:`ˡ`,m:`ᵐ`,n:`ⁿ`,o:`ᵒ`,p:`ᵖ`,r:`ʳ`,s:`ˢ`,t:`ᵗ`,u:`ᵘ`,v:`ᵛ`,w:`ʷ`,x:`ˣ`,y:`ʸ`,z:`ᶻ`},Si={0:`₀`,1:`₁`,2:`₂`,3:`₃`,4:`₄`,5:`₅`,6:`₆`,7:`₇`,8:`₈`,9:`₉`,"+":`₊`,"-":`₋`,"=":`₌`,"(":`₍`,")":`₎`,a:`ₐ`,e:`ₑ`,h:`ₕ`,i:`ᵢ`,j:`ⱼ`,k:`ₖ`,l:`ₗ`,m:`ₘ`,n:`ₙ`,o:`ₒ`,p:`ₚ`,r:`ᵣ`,s:`ₛ`,t:`ₜ`,u:`ᵤ`,v:`ᵥ`,x:`ₓ`},Ci=new Set([`,`,`:`,`;`,` `,`>`,`enspace`,`enskip`,`medspace`,`quad`,`qquad`,`thickspace`,`thinspace`]),wi=new Set([`!`,`negmedspace`,`negthickspace`,`negthinspace`]),Ti=new Set([`bf`,`cal`,`it`,`rm`,`sf`,`sl`,`tt`]),Ei=new Set([`displaystyle`,`limits`,`nolimits`,`scriptstyle`,`scriptscriptstyle`,`textstyle`]),Di=new Set([`big`,`Big`,`bigg`,`Bigg`,`bigl`,`Bigl`,`biggl`,`Biggl`,`bigr`,`Bigr`,`biggr`,`Biggr`]),Oi=new Set(`emph.mathcal.mathbf.mathfrak.mathit.mathrm.mathnormal.mathscr.mathsf.mathtt.mathup.mbox.overbrace.pmb.smash.substack.text.textbf.textit.textmd.textnormal.textrm.textsc.textsf.textsl.texttt.textup.underbrace.bm.boldsymbol`.split(`.`)),ki={acute:`́`,bar:`̅`,breve:`̆`,check:`̌`,ddot:`̈`,dot:`̇`,grave:`̀`,hat:`̂`,mathring:`̊`,overleftarrow:`⃖`,overleftrightarrow:`⃡`,overline:`̅`,overrightarrow:`⃗`,tilde:`̃`,underline:`̲`,vec:`⃗`,widehat:`̂`,widetilde:`̃`};function Ai(e,t){let n=``;for(let r of e){let e=t[r];if(e===void 0)return;n+=e}return n}function ji(e){return e.trim().replace(/\s*([=+-])\s*/g,`$1`)}function Mi(e,t){return Ai(ji(e),t===`sub`?Si:xi)}function Ni(e,t){e=ji(e);let n=Mi(e,t);if(n!==void 0)return n;let r=t===`sub`?`_`:`^`;return Array.from(e).length===1||t===`sub`&&/^[A-Za-z]+$/.test(e)?`${r}${e}`:`${r}(${e})`}function Pi(e,t){e=e.trim(),t=t.trim();let n=/^[\p{L}\p{N}.]+$/u.test(e),r=/^[\p{N}.]+$/u.test(t)||Array.from(t).length===1;return`${n?e:`(${e})`}/${r?t:`(${t})`}`}function Fi(e,t=`√`){return e=e.trim(),/^[\p{L}\p{N}.]+$/u.test(e)?`${t}${e}`:`${t}(${e})`}const Ii=``,Li=``,Ri=/(?<=[\p{L}\p{N})\]}\u{f0001}])\u{f0004}/gu,zi=/\u{f0005}(?=[\p{L}\p{N}√\u{f0000}])/gu;function Bi(e){return e.replace(Ri,` `).replaceAll(Ii,``).replace(zi,` `).replaceAll(Li,``).split(`
|
|
104
|
+
`).map(e=>e.replace(/[ \t]+/g,` `).trim()).filter((e,t,n)=>e.length>0||t>0&&t<n.length-1).join(`
|
|
105
|
+
`).trim()}const Vi=``,Hi=``,Ui=/\u{f0000}(\d+)\u{f0001}/gu,Wi=/\u{f0000}(\d+)\u{f0001}$/u,Gi=``;function Ki(e,t,n=!1){let r=Math.max(0,t-L(e)),i=n?Math.floor(r/2):0;return`${` `.repeat(i)}${e}${` `.repeat(r-i)}`}function qi(e){if(e.length===0)return{lines:[``],width:0,baseline:0};let t=Math.max(...e.map(e=>e.baseline)),n=Math.max(...e.map(e=>e.lines.length-e.baseline-1)),r=[];for(let i=0;i<=t+n;i++){let n=``;for(let r of e){let e=i-t+r.baseline;n+=e>=0&&e<r.lines.length?Ki(r.lines[e]??``,r.width):` `.repeat(r.width)}r.push(n.trimEnd())}return{lines:r,width:e.reduce((e,t)=>e+t.width,0),baseline:t}}function Ji(e,t){let n=[],r=0;for(let i of e.split(`
|
|
106
|
+
`)){let e=[],a=0,o;for(let n of i.matchAll(Ui)){let r=n.index,s=t[Number(n[1])];if(s){if(r>a){let t=i.slice(a,r),n=(o?t.trimStart():t).trimEnd(),c=o?.type===`matrix`&&/^\s/.test(t),l=s.type===`matrix`&&/\s$/.test(t),u=n?`${c?` `:``}${n}${l?` `:``}`:c||l?` `:``;e.push({lines:[u],width:L(u),baseline:0})}if(s.type===`fraction`){let n=Ji(s.numerator,t),r=Ji(s.denominator,t),i=Math.max(n.width,r.width,1),a=i+2;e.push({lines:[...n.lines.map(e=>Ki(e,a,!0)),` ${`─`.repeat(i)} `,...r.lines.map(e=>Ki(e,a,!0))],width:a,baseline:n.lines.length})}else if(s.type===`operator`){let t=Math.max(L(s.operator),s.lower===void 0?0:L(s.lower),s.upper===void 0?0:L(s.upper)),n=[];s.upper!==void 0&&n.push(`${Ki(s.upper,t,!0)} `),n.push(`${Ki(s.operator,t,!0)} `),s.lower!==void 0&&n.push(`${Ki(s.lower,t,!0)} `),e.push({lines:n,width:t+1,baseline:s.upper===void 0?0:1})}else if(s.type===`script`){let n=s.upper===void 0?void 0:Ji(s.upper,t),r=s.lower===void 0?void 0:Ji(s.lower,t),i=Math.max(n?.width??0,r?.width??0);e.push({lines:[...n?.lines.map(e=>Ki(e,i))??[],` `.repeat(i),...r?.lines.map(e=>Ki(e,i))??[]],width:i,baseline:n?.lines.length??0})}else{let t=Math.max(0,...s.lines.map(e=>L(e)));e.push({lines:s.lines.map(e=>Ki(e,t)),width:t,baseline:s.baseline})}a=r+n[0].length,o=s}}if(a<i.length){let t=i.slice(a),n=o?t.trimStart():t,r=o?.type===`matrix`&&/^\s/.test(t)?` ${n}`:n;e.push({lines:[r],width:L(r),baseline:0})}let s=qi(e);n.length===0&&(r=s.baseline),n.push(...s.lines)}return{lines:n,width:Math.max(0,...n.map(e=>L(e))),baseline:r}}var Yi=class e{source;layoutNodes;display;position=0;supported=!0;stackFractions=!0;scriptDepth=0;constructor(e,t,n){this.source=e,this.layoutNodes=t,this.display=n}render(){let e=this.parseSequence();if(!(!this.supported||this.position!==this.source.length))return Bi(e)}parseSequence(e){let t=``;for(;this.position<this.source.length;){let n=this.source[this.position];if(e&&n===e)return this.position++,t;if(n===`}`)return this.supported=!1,t;if(n===`{`){this.position++,t+=this.parseSequence(`}`);continue}if(n===`\\`){let e=this.parseCommand();e===`\0`?(t=t.trimEnd(),t.endsWith(Li)&&(t=t.slice(0,-2))):t+=e;continue}if(n===`^`||n===`_`){this.position++,t=t.trimEnd();let e=this.parseScripts(n);t.endsWith(Li)?t=`${t.slice(0,-2)}${e}${Li}`:t+=e;continue}if(/\s/.test(n)){t+=this.parseWhitespace();continue}if(n===`=`||n===`<`||n===`>`){t=`${t.trimEnd()} ${n} `,this.position++;continue}if(n===`&`){this.position++;continue}if(n===`~`){this.position++,t+=` `;continue}if(n===`.`){let e=Wi.exec(t),r=e?this.layoutNodes[Number(e[1])]:void 0;if(r?.type===`matrix`){let e=r.lines.length-1;r.lines[e]=`${r.lines[e]??``}${n}`,this.position++;continue}}t+=n,this.position++}return e&&(this.supported=!1),t}parseScripts(e){let t={},n=[],r=e=>{let r=e===`_`?`sub`:`sup`;this.scriptDepth++;try{t[r]=this.parseRequiredArgument(!1)}finally{this.scriptDepth--}n.push(r)};r(e);let i=this.position;for(;i<this.source.length&&/\s/.test(this.source[i]??``);)i++;let a=this.source[i];(a===`^`||a===`_`)&&a!==e&&(this.position=i+1,r(a));let o=t.sub===void 0?void 0:Mi(t.sub,`sub`),s=t.sup===void 0?void 0:Mi(t.sup,`sup`),c=![t.sub,t.sup].some(e=>e!==void 0&&(e.includes(`/`)||!e.includes(Vi)&&Array.from(e).length>1&&!/[A-Z*∗]/.test(e)));return this.display&&c&&(this.scriptDepth>0||t.sub!==void 0&&o===void 0||t.sup!==void 0&&s===void 0)?`${Vi}${this.layoutNodes.push({type:`script`,lower:t.sub===void 0?void 0:Bi(t.sub),upper:t.sup===void 0?void 0:Bi(t.sup)})-1}${Hi}`:n.map(e=>e===`sub`?o??Ni(t.sub??``,e):s??Ni(t.sup??``,e)).join(``)}parseWhitespace(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??``);)this.position++;return` `}parseCommand(){if(this.position++,this.position>=this.source.length)return this.supported=!1,``;let e=``,t=this.source[this.position]??``;if(t===`
|
|
107
|
+
`||t===`\r`)return this.position++,t===`\r`&&this.source[this.position]===`
|
|
108
|
+
`&&this.position++,` `;if(/[A-Za-z]/.test(t)){let t=this.position;for(;this.position<this.source.length&&/[A-Za-z]/.test(this.source[this.position]??``);)this.position++;e=this.source.slice(t,this.position)}else e=t,this.position++;if(e===`\\`)return`
|
|
109
|
+
`;if(Ci.has(e))return` `;if(wi.has(e))return`\0`;if(Ti.has(e)){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??``);)this.position++;return``}if(Ei.has(e))return``;if(e===`{`||e===`}`||e===`$`||e===`%`||e===`#`||e===`_`||e===`&`)return e;if(e===`|`)return`‖`;if(e===`not`){let e=this.parseRequiredArgument(!1).trim(),t=yi[e];if(t!==void 0)return` ${t} `;let n=Array.from(e);return n.length===0?(this.supported=!1,``):` ${n[0]}\u0338${n.slice(1).join(``)} `}if(gi.has(e))return this.parseOperator(e,`bracket`,!0,!0);let n=mi[e];if(n!==void 0)return _i.has(e)?this.parseOperator(n,`script`,!0):e===`cdot`||e===`times`||vi.has(e)?` ${n} `:n;if(hi.has(e))return`${Ii}${e}${Li}`;if(Di.has(e))return``;if(e===`left`||e===`middle`||e===`right`)return this.source[this.position]===`.`&&this.position++,``;if(e===`frac`||e===`dfrac`||e===`tfrac`){let t=this.display&&this.stackFractions&&e!==`tfrac`,n=this.parseRequiredArgument(!t),r=this.parseRequiredArgument(!t);return t?`${Vi}${this.layoutNodes.push({type:`fraction`,numerator:Bi(n),denominator:Bi(r)})-1}${Hi}`:Pi(n,r)}if(e===`sqrt`){let e=this.parseOptionalArgument()?.trim(),t=this.parseRequiredArgument();return e===void 0||e===`2`?Fi(t):e===`3`?Fi(t,`∛`):e===`4`?Fi(t,`∜`):`${Ni(e,`sup`)}${Fi(t)}`}if(e===`boxed`||e===`fbox`)return`[${this.parseRequiredArgument().trim()}]`;if(e===`binom`||e===`dbinom`||e===`tbinom`)return`(${this.parseRequiredArgument()} choose ${this.parseRequiredArgument()})`;let r=ki[e];if(r!==void 0){let t=this.parseRequiredArgument();return Array.from(t).length===1?`${t}${r}`:`${e}(${t})`}if(e===`mathbb`){let e=this.parseRequiredArgument();return Array.from(e,e=>bi[e]??e).join(``)}if(e===`operatorname`){let e=this.source[this.position]===`*`;e&&this.position++;let t=Bi(this.parseRequiredArgument()).trim();return this.parseOperator(t,`bracket`,e,!0)}if(e===`mod`||e===`bmod`)return` mod `;if(e===`pmod`||e===`pod`){let t=this.parseRequiredArgument().trim();return e===`pmod`?` (mod ${t})`:` (${t})`}if(e===`overset`||e===`stackrel`){let e=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${Ni(e,`sup`)}`}if(e===`underset`){let e=this.parseRequiredArgument();return`${this.parseRequiredArgument().trim()}${Ni(e,`sub`)}`}if(Oi.has(e)){let t=this.parseRequiredArgument();return e.startsWith(`text`)||e===`mbox`?t:t.trim()}return e===`begin`?this.parseEnvironment():e===`end`?(this.supported=!1,``):(this.supported=!1,`\\${e}`)}parseOperator(e,t,n,r=!1){let i=n,a=this.position;for(;a<this.source.length&&/[ \t]/.test(this.source[a]??``);)a++;let o=/^\\(limits|nolimits)(?![A-Za-z])/.exec(this.source.slice(a));o&&(i=o[1]===`limits`,this.position=a+o[0].length);let s,c;for(;;){let e=this.position;for(;e<this.source.length&&/[ \t]/.test(this.source[e]??``);)e++;let t=this.source[e];if(t!==`_`&&t!==`^`)break;this.position=e+1;let n=Bi(this.parseRequiredArgument(!1)).replaceAll(` `,``);t===`_`?(s!==void 0&&(this.supported=!1),s=n):(c!==void 0&&(this.supported=!1),c=n)}if(this.display&&i&&(s!==void 0||c!==void 0))return`${Vi}${this.layoutNodes.push({type:`operator`,operator:e,lower:s,upper:c})-1}${Hi}`;let l=e;return s!==void 0&&(l+=t===`bracket`?`[${s}]`:Ni(s,`sub`)),c!==void 0&&(l+=Ni(c,`sup`)),r?` ${l} `:l}parseRequiredArgument(e=!0){let t=this.stackFractions;this.stackFractions=t&&e;let n=this.parseRequiredArgumentValue();return this.stackFractions=t,n}parseRequiredArgumentValue(){for(;this.position<this.source.length&&/\s/.test(this.source[this.position]??``);)this.position++;if(this.position>=this.source.length)return this.supported=!1,``;if(this.source[this.position]===`{`)return this.position++,this.parseSequence(`}`);if(this.source[this.position]===`\\`)return this.parseCommand();let e=this.source[this.position]??``;return this.position++,e}parseOptionalArgument(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??``);)this.position++;if(this.source[this.position]!==`[`)return;let e=this.source.indexOf(`]`,this.position+1);if(e<0){this.supported=!1;return}let t=this.source.slice(this.position+1,e);return this.position=e+1,this.renderNested(t)}readRawGroup(){for(;this.position<this.source.length&&/[ \t]/.test(this.source[this.position]??``);)this.position++;if(this.source[this.position]!==`{`){this.supported=!1;return}let e=++this.position,t=1;for(;this.position<this.source.length;){let n=this.source[this.position];if(n===`\\`){this.position+=2;continue}if(n===`{`&&t++,n===`}`&&t--,t===0){let t=this.source.slice(e,this.position);return this.position++,t}this.position++}this.supported=!1}splitEnvironmentRows(e){return e.split(/\\\\(?:\[[^\]\n]*\])?/)}parseEnvironment(){let e=this.readRawGroup();if(!e)return``;let t=`\\end{${e}}`,n=this.source.indexOf(t,this.position);if(n<0)return this.supported=!1,``;let r=this.source.slice(this.position,n);if(this.position=n+t.length,e===`equation`||e===`equation*`||e===`displaymath`)return this.renderNested(r).trim();if(e===`aligned`||e===`align`||e===`align*`||e===`alignedat`||e===`alignat`||e===`alignat*`||e===`gather`||e===`gathered`||e===`multline`||e===`multline*`||e===`split`){let t=[`alignedat`,`alignat`,`alignat*`].includes(e),n=t?r.replace(/^\s*\{[^}]*\}/,``):r;return this.splitEnvironmentRows(n).map(e=>{let n=e.split(`&`),r=t?Array.from({length:Math.ceil(n.length/2)},(e,t)=>n.slice(t*2,t*2+2).join(``)).join(` `):n.join(``);return this.renderNested(r).trim()}).filter(Boolean).join(`
|
|
110
|
+
`)}if(e===`cases`||e===`cases*`)return this.renderCases(r);if([`array`,`matrix`,`smallmatrix`,`pmatrix`,`bmatrix`,`Bmatrix`,`vmatrix`,`Vmatrix`].includes(e)){let t=e===`array`?r.replace(/^\s*\{[^}]*\}/,``):r;return this.renderMatrix(e,t)}return this.supported=!1,r}renderCases(e){let t=this.splitEnvironmentRows(e).map(e=>e.split(`&`).map(e=>this.renderNested(e,!1).trim())).filter(e=>e.some(Boolean)),n=Math.max(0,...t.map(e=>L((e[0]??``).replace(/,\s*$/,``)))),r=t.map(e=>{let t=(e[0]??``).replace(/,\s*$/,``),r=e[1]??``;if(!r)return t;let i=/^(?:if|when|for|otherwise)\b/i.test(r)?` `:` if `;return`${t}${Gi.repeat(n-L(t))}${i}${r}`});if(r.length<=1)return r.length===0?``:`⎧ ${r[0]}`;let i=Math.floor(r.length/2),a=[...r];r.length%2==0&&a.splice(i,0,void 0);let o=a.map((e,t)=>{let n=t===0?`⎧`:t===a.length-1?`⎩`:`⎨`;return e===void 0?n:`${n} ${e}`});return`${Vi}${this.layoutNodes.push({type:`matrix`,lines:o,baseline:i})-1}${Hi}`}renderMatrix(e,t){let n=this.splitEnvironmentRows(t).map(e=>e.split(`&`).map(e=>this.renderNested(e,!1).trim())).filter(e=>e.some(Boolean)),r=Math.max(0,...n.map(e=>e.length)),i=Array.from({length:r},(e,t)=>Math.max(0,...n.map(e=>L(e[t]??``)))),a=n.map(e=>Array.from({length:r},(t,n)=>{let r=e[n]??``;return`${r}${Gi.repeat(Math.max(0,(i[n]??0)-L(r)))}`}).join(` │ `)),o;if(e===`array`||e===`matrix`||e===`smallmatrix`)o=a;else{let t={pmatrix:[`⎛`,`⎞`,`⎜`,`⎟`,`⎝`,`⎠`],bmatrix:[`⎡`,`⎤`,`⎢`,`⎥`,`⎣`,`⎦`],Bmatrix:[`⎧`,`⎫`,`⎨`,`⎬`,`⎩`,`⎭`],vmatrix:[`│`,`│`,`│`,`│`,`│`,`│`],Vmatrix:[`║`,`║`,`║`,`║`,`║`,`║`]}[e];if(!t)return this.supported=!1,a.join(`
|
|
111
|
+
`);o=a.map((e,n)=>`${n===0?t[0]:n===a.length-1?t[4]:t[2]} ${e} ${n===0?t[1]:n===a.length-1?t[5]:t[3]}`)}return o.length<=1?o[0]??``:`${Vi}${this.layoutNodes.push({type:`matrix`,lines:o,baseline:0})-1}${Hi}`}renderNested(t,n=!0){let r=new e(t,this.layoutNodes,this.display&&n).render();return r===void 0?(this.supported=!1,t):r}};function Xi(e,t={}){let n=[],r=new Yi(e,n,t.display===!0).render();if(r===void 0)return;if(n.length===0)return r.replaceAll(Gi,` `);let i=Ji(r,n).lines,a=Math.min(...i.filter(e=>e.trim()).map(e=>e.length-e.trimStart().length));return i.map(e=>e.slice(a).trimEnd()).join(`
|
|
112
|
+
`).trimEnd().replaceAll(Gi,` `)}const Zi=/^(~~)(?=[^\s~])((?:\\.|[^\\])*?(?:\\.|[^\s~\\]))\1(?=[^~]|$)/;var Qi=class extends Tt{del(e){let t=Zi.exec(e);if(!t)return;let n=t[2];return{type:`del`,raw:t[0],text:n,tokens:this.lexer.inlineTokens(n)}}};function $i(e,t){let n=0;for(let r=t-1;r>=0&&e[r]===`\\`;r--)n++;return n%2==1}function ea(e,t,n){let r=e.indexOf(t,n);for(;r>=0&&$i(e,r);)r=e.indexOf(t,r+t.length);return r}function ta(e){return/\\[A-Za-z]+|[_^=+*/<>()[\]|±≤≥≠≈∈→⇒∞∫∑√-]/.test(e)}function na(e){let t=``,n=``;if(e.startsWith(`$$`))t=`$$`,n=`$$`;else if(e.startsWith(`\\(`))t=`\\(`,n=`\\)`;else if(e.startsWith(`\\[`))t=`\\[`,n=`\\]`;else if(e.startsWith(`$`)&&!/^\$\s/.test(e))t=`$`,n=`$`;else return;let r=ea(e,n,t.length);if(r>=0&&t===`$`&&(/\s$/.test(e.slice(t.length,r))||/^\d/.test(e.slice(r+1))||/^[A-Z_][A-Z0-9_]*(?:[^A-Za-z0-9_\s])?$/.test(e.slice(t.length,r))&&/^[A-Za-z_][A-Za-z0-9_]*/.test(e.slice(r+1))||e.slice(t.length,r).includes("`")))return;if(r<0){let n=e.slice(t.length);return t.startsWith(`\\`)||ta(n)?{type:`latex`,raw:e,text:n,pending:!0}:void 0}let i=e.slice(t.length,r);if(!(!i||i.includes(`
|
|
113
|
+
`)))return{type:`latex`,raw:e.slice(0,r+n.length),text:i}}function ra(e){let t=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*?)\$\$[ \t]*(?:\n|$)/.exec(e);if(t?.[1])return{type:`latexBlock`,raw:t[0],text:t[1].trim()};let n=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*?)\\\][ \t]*(?:\n|$)/.exec(e);if(n?.[1])return{type:`latexBlock`,raw:n[0],text:n[1].trim()};let r=/^ {0,3}\\\[[ \t]*(?:\n)?([\s\S]*)$/.exec(e);if(r)return{type:`latexBlock`,raw:r[0],text:r[1],pending:!0};let i=/^ {0,3}\$\$[ \t]*(?:\n)?([\s\S]*)$/.exec(e);if(i?.[1]&&ta(i[1]))return{type:`latexBlock`,raw:i[0],text:i[1],pending:!0}}const ia=[{name:`latexBlock`,level:`block`,start(e){let t=/(?:^|\n) {0,3}(?:\$\$|\\\[)/.exec(e);return t?t.index+ +!!t[0].startsWith(`
|
|
114
|
+
`):void 0},tokenizer:ra},{name:`latex`,level:`inline`,start(e){let t=[e.indexOf(`$`),e.indexOf(`\\(`),e.indexOf(`\\[`)].filter(e=>e>=0);return t.length>0?Math.min(...t):void 0},tokenizer:na}];function aa(e){let t=e[e.length-1];if(t?.type===`list`){aa(t.items[t.items.length-1]?.tokens??[]);return}if(t?.type===`blockquote`){aa(t.tokens??[]);return}if(t?.type!==`code`)return;let n=/^(`{3,}|~{3,})/.exec(t.raw)?.[1],r=t.raw.split(`
|
|
115
|
+
`).pop();!n||!r||r.length>=n.length||r!==n[0]?.repeat(r.length)||(t.text=t.text.slice(0,-r.length).replace(/\n$/,``))}const oa=new jt;oa.setOptions({tokenizer:new Qi}),oa.use({extensions:[...ia]});var sa=class{text;paddingX;paddingY;defaultTextStyle;theme;options;defaultStylePrefix;cachedText;cachedWidth;cachedLines;cachedTokens;constructor(e,t,n,r,i,a){this.text=e,this.paddingX=t,this.paddingY=n,this.theme=r,this.defaultTextStyle=i,this.options=a?{...a}:{}}setText(e){this.text=e,this.invalidate()}invalidate(){this.cachedText=void 0,this.cachedWidth=void 0,this.cachedLines=void 0}render(e){if(this.cachedLines&&this.cachedText===this.text&&this.cachedWidth===e)return this.cachedLines;let t=Math.max(1,e-this.paddingX*2),n=this.options.transform?.(this.text,t)??this.text;if(!n||n.trim()===``){let t=[];return this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=t,t}let r=n.replace(/\t/g,` `),i=this.cachedTokens?.deref(),a=i?.source===r?i.tokens:void 0;a||(a=oa.lexer(r),aa(a),this.cachedTokens=new WeakRef({source:r,tokens:a}));let o=[];for(let e=0;e<a.length;e++){let n=a[e],r=a[e+1],i=this.renderToken(n,t,r?.type);for(let e of i)o.push(e)}let s=[];for(let e of o)if(wr(e))s.push(e);else for(let n of On(e,t))s.push(n);let c=` `.repeat(this.paddingX),l=` `.repeat(this.paddingX),u=this.defaultTextStyle?.bgColor,d=[];for(let t of s){if(wr(t)){d.push(t);continue}let n=c+t+l;if(u)d.push(Nn(n,e,u));else{let t=L(n),r=Math.max(0,e-t);d.push(n+` `.repeat(r))}}let f=` `.repeat(e),p=[];for(let t=0;t<this.paddingY;t++){let t=u?Nn(f,e,u):f;p.push(t)}let m=p.concat(d,p);return Dn(m),this.cachedText=this.text,this.cachedWidth=e,this.cachedLines=m,m.length>0?m:[``]}applyDefaultStyle(e){if(!this.defaultTextStyle)return e;let t=e;return this.defaultTextStyle.color&&(t=this.defaultTextStyle.color(t)),this.defaultTextStyle.bold&&(t=this.theme.bold(t)),this.defaultTextStyle.italic&&(t=this.theme.italic(t)),this.defaultTextStyle.strikethrough&&(t=this.theme.strikethrough(t)),this.defaultTextStyle.underline&&(t=this.theme.underline(t)),t}getDefaultStylePrefix(){if(!this.defaultTextStyle)return``;if(this.defaultStylePrefix!==void 0)return this.defaultStylePrefix;let e=`\0`;this.defaultTextStyle.color&&(e=this.defaultTextStyle.color(e)),this.defaultTextStyle.bold&&(e=this.theme.bold(e)),this.defaultTextStyle.italic&&(e=this.theme.italic(e)),this.defaultTextStyle.strikethrough&&(e=this.theme.strikethrough(e)),this.defaultTextStyle.underline&&(e=this.theme.underline(e));let t=e.indexOf(`\0`);return this.defaultStylePrefix=t>=0?e.slice(0,t):``,this.defaultStylePrefix}getStylePrefix(e){let t=e(`\0`),n=t.indexOf(`\0`);return n>=0?t.slice(0,n):``}getDefaultInlineStyleContext(){return{applyText:e=>this.applyDefaultStyle(e),stylePrefix:this.getDefaultStylePrefix()}}renderToken(e,t,n,r){let i=[];switch(e.type){case`heading`:{let t=e.depth,r=`${`#`.repeat(t)} `,a;a=t===1?e=>this.theme.heading(this.theme.bold(this.theme.underline(e))):e=>this.theme.heading(this.theme.bold(e));let o={applyText:a,stylePrefix:this.getStylePrefix(a)},s=this.renderInlineTokens(e.tokens||[],o),c=t>=3?a(r)+s:s;i.push(c),n&&n!==`space`&&i.push(``);break}case`paragraph`:{let t=this.renderInlineTokens(e.tokens||[],r);i.push(t),n&&n!==`list`&&n!==`space`&&i.push(``);break}case`text`:i.push(this.renderInlineTokens([e],r));break;case`latexBlock`:{let t=e,r=!t.pending&&this.options.renderLatex!==!1?Xi(t.text,{display:!0})??t.raw.trim():t.raw.trim();for(let e of r.split(`
|
|
116
|
+
`))i.push(this.applyDefaultStyle(e));n&&n!==`space`&&i.push(``);break}case`code`:{let t=this.theme.codeBlockIndent??` `;if(i.push(this.theme.codeBlockBorder(`\`\`\`${e.lang||``}`)),this.theme.highlightCode){let n=this.theme.highlightCode(e.text,e.lang);for(let e of n)i.push(`${t}${e}`)}else{let n=e.text.split(`
|
|
117
|
+
`);for(let e of n)i.push(`${t}${this.theme.codeBlock(e)}`)}i.push(this.theme.codeBlockBorder("```")),n&&n!==`space`&&i.push(``);break}case`list`:{let n=this.renderList(e,0,t,r);i.push(...n);break}case`table`:{let a=this.renderTable(e,t,n,r);i.push(...a);break}case`blockquote`:{let r=e=>this.theme.quote(this.theme.italic(e)),a=this.getStylePrefix(r),o=e=>r(a?e.replace(/\x1b\[0m/g,`\x1b[0m${a}`):e),s=Math.max(1,t-2),c={applyText:e=>e,stylePrefix:a},l=e.tokens||[],u=[];for(let e=0;e<l.length;e++){let t=l[e],n=l[e+1];u.push(...this.renderToken(t,s,n?.type,c))}for(;u.length>0&&u[u.length-1]===``;)u.pop();for(let e of u){let t=On(o(e),s);for(let e of t)i.push(this.theme.quoteBorder(`│ `)+e)}n&&n!==`space`&&i.push(``);break}case`hr`:i.push(this.theme.hr(`─`.repeat(Math.min(t,80)))),n&&n!==`space`&&i.push(``);break;case`html`:`raw`in e&&typeof e.raw==`string`&&i.push(this.applyDefaultStyle(e.raw.trim()));break;case`space`:i.push(``);break;default:`text`in e&&typeof e.text==`string`&&i.push(e.text)}return i}renderInlineTokens(e,t){let n=``,r=t??this.getDefaultInlineStyleContext(),{applyText:i,stylePrefix:a}=r,o=e=>e.split(`
|
|
118
|
+
`).map(e=>i(e)).join(`
|
|
119
|
+
`);for(let t of e)switch(t.type){case`latex`:{let e=t,r=!e.pending&&this.options.renderLatex!==!1?Xi(e.text)??e.raw:e.raw;n+=o(r);break}case`escape`:n+=o(this.options.preserveBackslashEscapes?t.raw:t.text);break;case`text`:t.tokens&&t.tokens.length>0?n+=this.renderInlineTokens(t.tokens,r):n+=o(t.text);break;case`paragraph`:n+=this.renderInlineTokens(t.tokens||[],r);break;case`strong`:{let e=this.renderInlineTokens(t.tokens||[],r);n+=this.theme.bold(e)+a;break}case`em`:{let e=this.renderInlineTokens(t.tokens||[],r);n+=this.theme.italic(e)+a;break}case`codespan`:n+=this.theme.code(t.text)+a;break;case`link`:{let e=this.renderInlineTokens(t.tokens||[],r),i=this.theme.link(this.theme.underline(e));if(Sr().hyperlinks)n+=Er(i,t.href)+a;else{let e=t.href.startsWith(`mailto:`)?t.href.slice(7):t.href;t.text===t.href||t.text===e?n+=i+a:n+=i+this.theme.linkUrl(` (${t.href})`)+a}break}case`br`:n+=`
|
|
120
|
+
`;break;case`del`:{let e=this.renderInlineTokens(t.tokens||[],r);n+=this.theme.strikethrough(e)+a;break}case`html`:`raw`in t&&typeof t.raw==`string`&&(n+=o(t.raw));break;default:`text`in t&&typeof t.text==`string`&&(n+=o(t.text))}for(;a&&n.endsWith(a);)n=n.slice(0,-a.length);return n}getOrderedListMarker(e){let t=/^(?: {0,3})(\d{1,9}[.)])[ \t]+/.exec(e.raw);return t?`${t[1]} `:void 0}getUnorderedListMarker(e){let t=/^(?: {0,3})([-+*])(?:[ \t]+|(?=\r?\n|$))/.exec(e.raw);return t?`${t[1]} `:void 0}renderList(e,t,n,r){let i=[],a=` `.repeat(t),o=typeof e.start==`number`?e.start:1;for(let s=0;s<e.items.length;s++){let c=e.items[s],l=s===e.items.length-1,u=(e.ordered?this.options.preserveOrderedListMarkers?this.getOrderedListMarker(c)??`${o+s}. `:`${o+s}. `:this.options.preserveOrderedListMarkers?this.getUnorderedListMarker(c)??`- `:`- `)+(c.task?`[${c.checked?`x`:` `}] `:``),d=a+this.theme.listBullet(u),f=a+` `.repeat(L(u)),p=Math.max(1,n-L(d)),m=!1;for(let e of c.tokens){if(e.type===`list`){i.push(...this.renderList(e,t+1,n,r)),m=!0;continue}let a=this.renderToken(e,p,void 0,r);for(let e of a)for(let t of On(e,p)){let e=m?f:d;i.push(e+t),m=!0}}m||i.push(d),e.loose&&!l&&i.push(``)}return i}getLongestWordWidth(e,t){let n=e.split(/\s+/).filter(e=>e.length>0),r=0;for(let e of n)r=Math.max(r,L(e));return t===void 0?r:Math.min(r,t)}wrapCellText(e,t,n=``){let r=On(e,Math.max(1,t));return r.map((e,t)=>`${e}${t<r.length-1?`\x1B[22;23;24;25;27;28;29;39m`:``}${n}`)}renderTable(e,t,n,r){let i=[],a=e.header.length;if(a===0)return i;let o=3*a+1,s=t-o;if(s<a){let r=e.raw?On(e.raw,t):[];return n&&n!==`space`&&r.push(``),r}let c=[],l=[];for(let t=0;t<a;t++){let n=this.renderInlineTokens(e.header[t].tokens||[],r);c[t]=L(n),l[t]=Math.max(1,this.getLongestWordWidth(n,30))}for(let t of e.rows)for(let e=0;e<t.length;e++){let n=this.renderInlineTokens(t[e].tokens||[],r);c[e]=Math.max(c[e]||0,L(n)),l[e]=Math.max(l[e]||1,this.getLongestWordWidth(n,30))}let u=l,d=u.reduce((e,t)=>e+t,0);if(d>s){u=Array(a).fill(1);let e=s-a;if(e>0){let t=l.reduce((e,t)=>e+Math.max(0,t-1),0),n=l.map(n=>{let r=Math.max(0,n-1);return t>0?Math.floor(r/t*e):0});for(let e=0;e<a;e++)u[e]+=n[e]??0;let r=e-n.reduce((e,t)=>e+t,0);for(let e=0;r>0&&e<a;e++)u[e]++,r--}d=u.reduce((e,t)=>e+t,0)}let f=c.reduce((e,t)=>e+t,0)+o,p;if(f<=t)p=c.map((e,t)=>Math.max(e,u[t]));else{let e=c.reduce((e,t,n)=>e+Math.max(0,t-u[n]),0),t=Math.max(0,s-d);p=u.map((n,r)=>{let i=c[r],a=Math.max(0,i-n),o=0;return e>0&&(o=Math.floor(a/e*t)),n+o});let n=s-p.reduce((e,t)=>e+t,0);for(;n>0;){let e=!1;for(let t=0;t<a&&n>0;t++)p[t]<c[t]&&(p[t]++,n--,e=!0);if(!e)break}}let m=p.map(e=>`─`.repeat(e));i.push(`┌─${m.join(`─┬─`)}─┐`);let h=e.header.map((e,t)=>{let n=this.renderInlineTokens(e.tokens||[],r);return this.wrapCellText(n,p[t],r?.stylePrefix)}),g=Math.max(...h.map(e=>e.length));for(let e=0;e<g;e++){let t=h.map((t,n)=>{let r=t[e]||``,i=r+` `.repeat(Math.max(0,p[n]-L(r)));return this.theme.bold(i)});i.push(`│ ${t.join(` │ `)} │`)}let _=`├─${p.map(e=>`─`.repeat(e)).join(`─┼─`)}─┤`;i.push(_);for(let t=0;t<e.rows.length;t++){let n=e.rows[t].map((e,t)=>{let n=this.renderInlineTokens(e.tokens||[],r);return this.wrapCellText(n,p[t],r?.stylePrefix)}),a=Math.max(...n.map(e=>e.length));for(let e=0;e<a;e++){let t=n.map((t,n)=>{let r=t[e]||``;return r+` `.repeat(Math.max(0,p[n]-L(r)))});i.push(`│ ${t.join(` │ `)} │`)}t<e.rows.length-1&&i.push(_)}let v=p.map(e=>`─`.repeat(e));return i.push(`└─${v.join(`─┴─`)}─┘`),n&&n!==`space`&&i.push(``),i}};const ca=e(import.meta.url);function la(e,t={}){let n=o(c(t.moduleUrl??import.meta.url)),r=[];try{let n=(t.resolvePackage??ca.resolve)(`@earendil-works/pi-tui`);r.push(s(o(n),`..`,e))}catch{}return r.push(s(n,`..`,e),s(n,e),s(o(t.execPath??process.execPath),e)),Array.from(new Set(r))}const ua=e(import.meta.url),da=new Map;function fa(e,t=``){let n=process.arch;if(n!==`x64`&&n!==`arm64`)return;let r=a.join(`native`,e,`prebuilds`,`${e}-${n}`,`${e}-platform${t}.node`);if(da.has(r))return da.get(r);for(let e of la(r))try{let t=ua(e);if(typeof t?.getText==`function`&&typeof t.getImage==`function`)return da.set(r,t),t}catch{}da.set(r,void 0)}function pa(){if(!(process.platform!==`darwin`&&process.platform!==`win32`))return fa(process.platform)}const ma=`\x1B[201~`;function ha(e){if(!e.startsWith(`\x1B`))return`not-escape`;if(e.length===1)return`incomplete`;let t=e.slice(1);return t.startsWith(`[`)?t.startsWith(`[M`)?e.length>=6?`complete`:`incomplete`:ga(e):t.startsWith(`]`)?_a(e):t.startsWith(`P`)?va(e):t.startsWith(`_`)?ya(e):t.startsWith(`O`)?t.length>=2?`complete`:`incomplete`:(t.length,`complete`)}function ga(e){if(!e.startsWith(`\x1B[`))return`complete`;if(e.length<3)return`incomplete`;let t=e.slice(2),n=t[t.length-1],r=n.charCodeAt(0);if(r>=64&&r<=126){if(t.startsWith(`<`)){if(/^<\d+;\d+;\d+[Mm]$/.test(t))return`complete`;if(n===`M`||n===`m`){let e=t.slice(1,-1).split(`;`);if(e.length===3&&e.every(e=>/^\d+$/.test(e)))return`complete`}return`incomplete`}return`complete`}return`incomplete`}function _a(e){return!e.startsWith(`\x1B]`)||e.endsWith(`\x1B\\`)||e.endsWith(`\x07`)?`complete`:`incomplete`}function va(e){return!e.startsWith(`\x1BP`)||e.endsWith(`\x1B\\`)?`complete`:`incomplete`}function ya(e){return!e.startsWith(`\x1B_`)||e.endsWith(`\x1B\\`)?`complete`:`incomplete`}function ba(e){let t=e.match(/^\x1b\[(\d+)(?::\d*)?(?::\d+)?u$/);if(!t)return;let n=parseInt(t[1],10);return n>=32?n:void 0}function xa(e){let t=[],n=0;for(;n<e.length;){let r=e.slice(n);if(r.startsWith(`\x1B`)){let e=1;for(;e<=r.length;){let i=r.slice(0,e),a=ha(i);if(a===`complete`){if(i===`\x1B\x1B`){let i=r[e];if(i===`[`||i===`]`||i===`O`||i===`P`||i===`_`){t.push(`\x1B`),n+=1;break}}t.push(i),n+=e;break}else if(a===`incomplete`)e++;else{t.push(i),n+=e;break}}if(e>r.length)return{sequences:t,remainder:r}}else t.push(r[0]),n++}return{sequences:t,remainder:``}}var Sa=class extends l{buffer=``;timeout=null;timeoutMs;escapeTimeoutMs;pasteMode=!1;pasteBuffer=``;pendingKittyPrintableCodepoint;constructor(e={}){super(),this.timeoutMs=e.timeout??50,this.escapeTimeoutMs=e.escapeTimeout??10}process(e){this.timeout&&=(clearTimeout(this.timeout),null);let t;if(Buffer.isBuffer(e))if(e.length===1&&e[0]>127){let n=e[0]-128;t=`\x1b${String.fromCharCode(n)}`}else t=e.toString();else t=e;if(t.length===0&&this.buffer.length===0){this.emitDataSequence(``);return}if(this.buffer+=t,this.pasteMode){this.pasteBuffer+=this.buffer,this.buffer=``;let e=this.pasteBuffer.indexOf(ma);if(e!==-1){let t=this.pasteBuffer.slice(0,e),n=this.pasteBuffer.slice(e+6);this.pasteMode=!1,this.pasteBuffer=``,this.pendingKittyPrintableCodepoint=void 0,this.emit(`paste`,t),n.length>0&&this.process(n)}return}let n=this.buffer.indexOf(`\x1B[200~`);if(n!==-1){if(n>0){let e=xa(this.buffer.slice(0,n));for(let t of e.sequences)this.emitDataSequence(t)}this.pendingKittyPrintableCodepoint=void 0,this.buffer=this.buffer.slice(n+6),this.pasteMode=!0,this.pasteBuffer=this.buffer,this.buffer=``;let e=this.pasteBuffer.indexOf(ma);if(e!==-1){let t=this.pasteBuffer.slice(0,e),n=this.pasteBuffer.slice(e+6);this.pasteMode=!1,this.pasteBuffer=``,this.pendingKittyPrintableCodepoint=void 0,this.emit(`paste`,t),n.length>0&&this.process(n)}return}let r=xa(this.buffer);this.buffer=r.remainder;for(let e of r.sequences)this.emitDataSequence(e);if(this.buffer.length>0){let e=this.buffer===`\x1B`?this.escapeTimeoutMs:this.timeoutMs;this.timeout=setTimeout(()=>{let e=this.flush();for(let t of e)this.emitDataSequence(t)},e)}}emitDataSequence(e){let t=e.length===1?e.codePointAt(0):void 0;if(t!==void 0&&t===this.pendingKittyPrintableCodepoint){this.pendingKittyPrintableCodepoint=void 0;return}this.pendingKittyPrintableCodepoint=ba(e),this.emit(`data`,e)}flush(){if(this.timeout&&=(clearTimeout(this.timeout),null),this.buffer.length===0)return[];let e=[this.buffer];return this.buffer=``,this.pendingKittyPrintableCodepoint=void 0,e}clear(){this.timeout&&=(clearTimeout(this.timeout),null),this.buffer=``,this.pasteMode=!1,this.pasteBuffer=``,this.pendingKittyPrintableCodepoint=void 0}getBuffer(){return this.buffer}destroy(){this.clear()}};function Ca(e){let t=pa();if(!t?.isModifierPressed)return!1;try{return t.isModifierPressed(e)===!0}catch{return!1}}const wa=`\x1B]9;4;3\x07`,Ta=`\x1B]9;4;0\x07`;function Ea(e){let t=e.match(/^\x1b\[\?(\d+)u$/);if(t)return{type:`kitty-flags`,flags:Number.parseInt(t[1],10)};if(/^\x1b\[\?[\d;]*c$/.test(e))return{type:`device-attributes`}}function Da(e){return e===`\x1B[`||/^\x1b\[\?[\d;]*$/.test(e)}function Oa(){return process.platform===`darwin`&&process.env.TERM_PROGRAM===`Apple_Terminal`}function ka(){if(!(process.platform===`win32`||process.pid<=0))try{process.kill(process.pid,`SIGWINCH`)}catch{}}function Aa(e,t,n){return t&&e===`\r`&&n?`\x1B[13;2u`:e}function ja(e=process.env){let t=Number(e.PI_TUI_ESC_TIMEOUT);return Number.isFinite(t)&&t>0?t:e.SSH_CONNECTION||e.SSH_TTY?100:10}var Ma=class{wasRaw=!1;inputHandler;resizeHandler;_kittyProtocolActive=!1;_modifyOtherKeysActive=!1;keyboardProtocolPushed=!1;pendingKeyboardProtocolDeviceAttributes=0;keyboardProtocolNegotiationBuffer=``;keyboardProtocolBufferFlushTimer;stdinBuffer;stdinDataHandler;progressInterval;writeLogPath=(()=>{let e=process.env.PI_TUI_WRITE_LOG||``;if(!e)return``;try{if(u.statSync(e).isDirectory()){let t=new Date,n=`${t.getFullYear()}-${String(t.getMonth()+1).padStart(2,`0`)}-${String(t.getDate()).padStart(2,`0`)}_${String(t.getHours()).padStart(2,`0`)}-${String(t.getMinutes()).padStart(2,`0`)}-${String(t.getSeconds()).padStart(2,`0`)}`;return a.join(e,`tui-${n}-${process.pid}.log`)}}catch{}return e})();get kittyProtocolActive(){return this._kittyProtocolActive}get modifyOtherKeysActive(){return this._modifyOtherKeysActive}start(e,t){this.inputHandler=e,this.resizeHandler=t,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),ka(),this.enableWindowsVTInput(),this.queryAndEnableKittyProtocol()}setupStdinBuffer(){this.stdinBuffer=new Sa({escapeTimeout:ja()}),this.stdinBuffer.on(`data`,e=>{let t=this.readKeyboardProtocolNegotiationSequence(e);if(t===`pending`){this.scheduleKeyboardProtocolNegotiationBufferFlush();return}t&&this.handleKeyboardProtocolNegotiationSequence(t.parsed)||this.forwardInputSequence(t?.sequence??e)}),this.stdinBuffer.on(`paste`,e=>{this.inputHandler&&this.inputHandler(`\x1b[200~${e}\x1b[201~`)}),this.stdinDataHandler=e=>{this.stdinBuffer.process(e)}}queryAndEnableKittyProtocol(){this.setupStdinBuffer(),process.stdin.on(`data`,this.stdinDataHandler),this.keyboardProtocolPushed=!0,this.pendingKeyboardProtocolDeviceAttributes+=1,this.clearKeyboardProtocolNegotiationBuffer(),process.stdout.write(`\x1B[>7u\x1B[?u\x1B[c`)}handleKeyboardProtocolNegotiationSequence(e){if(this.clearKeyboardProtocolNegotiationBuffer(),e.type===`device-attributes`){if(this.pendingKeyboardProtocolDeviceAttributes===0)return!1;--this.pendingKeyboardProtocolDeviceAttributes}return e.type===`kitty-flags`?(e.flags===0?this.enableModifyOtherKeys():(this.disableModifyOtherKeys(),this._kittyProtocolActive||(this._kittyProtocolActive=!0,Bn(!0))),!0):(this._kittyProtocolActive||this.enableModifyOtherKeys(),!0)}readKeyboardProtocolNegotiationSequence(e){if(this.keyboardProtocolNegotiationBuffer){let t=this.keyboardProtocolNegotiationBuffer+e,n=Ea(t);if(n)return this.clearKeyboardProtocolNegotiationBuffer(),{parsed:n,sequence:t};if(Da(t))return this.setKeyboardProtocolNegotiationBuffer(t),`pending`;this.flushKeyboardProtocolNegotiationBufferAsInput()}let t=Ea(e);if(t)return{parsed:t,sequence:e};if(Da(e))return this.setKeyboardProtocolNegotiationBuffer(e),`pending`}setKeyboardProtocolNegotiationBuffer(e){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=e}clearKeyboardProtocolNegotiationBuffer(){this.clearKeyboardProtocolNegotiationBufferFlushTimer(),this.keyboardProtocolNegotiationBuffer=``}flushKeyboardProtocolNegotiationBufferAsInput(){if(!this.keyboardProtocolNegotiationBuffer)return;let e=this.keyboardProtocolNegotiationBuffer;this.clearKeyboardProtocolNegotiationBuffer(),this.forwardInputSequence(e)}scheduleKeyboardProtocolNegotiationBufferFlush(){!this.keyboardProtocolNegotiationBuffer||this.keyboardProtocolBufferFlushTimer||(this.keyboardProtocolBufferFlushTimer=setTimeout(()=>{this.keyboardProtocolBufferFlushTimer=void 0,this.flushKeyboardProtocolNegotiationBufferAsInput()},150))}clearKeyboardProtocolNegotiationBufferFlushTimer(){this.keyboardProtocolBufferFlushTimer&&=(clearTimeout(this.keyboardProtocolBufferFlushTimer),void 0)}forwardInputSequence(e){if(!this.inputHandler)return;let t=e===`\r`&&(Oa()||process.platform===`win32`),n=Aa(e,t,t&&Ca(`shift`));this.inputHandler(n)}enableModifyOtherKeys(){this._kittyProtocolActive||this._modifyOtherKeysActive||(process.stdout.write(`\x1B[>4;2m`),this._modifyOtherKeysActive=!0)}disableModifyOtherKeys(){this._modifyOtherKeysActive&&=(process.stdout.write(`\x1B[>4;0m`),!1)}enableWindowsVTInput(){if(process.platform===`win32`)try{pa()?.enableVirtualTerminalInput?.()}catch{}}async drainInput(e=1e3,t=50){let n=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),n&&(process.stdout.write(`\x1B[<u`),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,Bn(!1)),this.disableModifyOtherKeys();let r=this.inputHandler;this.inputHandler=void 0;let i=Date.now(),a=()=>{i=Date.now()};process.stdin.on(`data`,a);let o=Date.now()+e;try{for(;;){let e=Date.now(),n=o-e;if(n<=0||e-i>=t)break;await new Promise(e=>setTimeout(e,Math.min(t,n)))}}finally{process.stdin.removeListener(`data`,a),this.inputHandler=r}}stop(){this.clearProgressInterval()&&process.stdout.write(Ta),process.stdout.write(`\x1B[?2004l`);let e=this.keyboardProtocolPushed||this._kittyProtocolActive;this.clearKeyboardProtocolNegotiationBuffer(),e&&(process.stdout.write(`\x1B[<u`),this.keyboardProtocolPushed=!1,this._kittyProtocolActive=!1,Bn(!1)),this.disableModifyOtherKeys(),this.stdinBuffer&&=(this.stdinBuffer.destroy(),void 0),this.stdinDataHandler&&=(process.stdin.removeListener(`data`,this.stdinDataHandler),void 0),this.inputHandler=void 0,this.resizeHandler&&=(process.stdout.removeListener(`resize`,this.resizeHandler),void 0),process.stdin.pause(),process.stdin.setRawMode&&process.stdin.setRawMode(this.wasRaw)}write(e){if(process.stdout.write(e),this.writeLogPath)try{u.appendFileSync(this.writeLogPath,e,{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(e){e>0?process.stdout.write(`\x1b[${e}B`):e<0&&process.stdout.write(`\x1b[${-e}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(e){process.stdout.write(`\x1b]0;${e}\x07`)}setProgress(e){e?(process.stdout.write(wa),this.progressInterval||=setInterval(()=>{process.stdout.write(wa)},1e3)):(this.clearProgressInterval(),process.stdout.write(Ta))}clearProgressInterval(){return this.progressInterval?(clearInterval(this.progressInterval),this.progressInterval=void 0,!0):!1}};const Na=1024*1024;var Pa=class{buffer=``;writtenChars=0;write;constructor(e){this.write=e}append(e){let t=0;for(;t<e.length;){let n=Na-this.buffer.length;if(n===0){this.flush();continue}let r=Math.min(e.length,t+n);if(r<e.length&&e.charCodeAt(r-1)>=55296&&e.charCodeAt(r-1)<=56319&&e.charCodeAt(r)>=56320&&e.charCodeAt(r)<=57343&&r--,r===t){this.flush();continue}this.buffer+=e.slice(t,r),t=r,this.buffer.length===Na&&this.flush()}}flush(){this.buffer&&=(this.write(this.buffer),this.writtenChars+=this.buffer.length,``)}get length(){return this.writtenChars+this.buffer.length}};function Fa(e){let t=e.indexOf(`\x1B_G`);if(t===-1)return;let n=t+3,r=e.indexOf(`;`,n);if(r===-1)return;let i=[],a=1;for(let t of e.slice(n,r).split(`,`)){let[e,n]=t.split(`=`,2);if(n===void 0)continue;let r=Number(n);!Number.isInteger(r)||r<=0||r>4294967295||(e===`i`?i.push(r):e===`r`&&(a=r))}return{ids:i,rows:a}}function Ia(e){return Fa(e)?.ids??[]}function La(e){return Fa(e)?.rows??1}function Ra(){return!!process.env.TERMUX_VERSION}var za=class extends Ir{mode=`regular`;previousLines=[];previousKittyImageIds=new Set;previousWidth=0;previousHeight=0;cursorRow=0;hardwareCursorRow=0;maxLinesRendered=0;previousViewportTop=0;captureRenderState(){return{previousLines:[...this.previousLines],previousWidth:this.previousWidth,previousHeight:this.previousHeight,cursorRow:this.cursorRow,hardwareCursorRow:this.hardwareCursorRow,maxLinesRendered:this.maxLinesRendered,previousViewportTop:this.previousViewportTop}}restoreRenderState(e){this.previousLines=e.previousLines.map(e=>wr(e)?``:e),this.previousKittyImageIds=new Set,this.previousWidth=e.previousWidth,this.previousHeight=e.previousHeight,this.cursorRow=e.cursorRow,this.hardwareCursorRow=e.hardwareCursorRow,this.maxLinesRendered=e.maxLinesRendered,this.previousViewportTop=e.previousViewportTop}resetRenderState(){this.previousLines=[],this.previousWidth=-1,this.previousHeight=-1,this.cursorRow=0,this.hardwareCursorRow=0,this.maxLinesRendered=0,this.previousViewportTop=0}beforeTerminalStop(e){if(e.preserveScreen||this.previousLines.length===0)return;this.terminal.write(` `);let t=this.previousLines.length-this.hardwareCursorRow;t>0?this.terminal.write(`\x1b[${t}B`):t<0&&this.terminal.write(`\x1b[${-t}A`),this.terminal.write(`\r
|
|
121
|
+
`)}collectKittyImageIds(e){let t=new Set;for(let n of e)for(let e of Ia(n))t.add(e);return t}deleteKittyImages(e){let t=``;for(let n of e)t+=Tr(n);return t}getKittyImageReservedRows(e,t,n=e.length-1){let r=La(e[t]??``);if(r<=1)return 1;let i=Math.min(r,n-t+1,e.length-t),a=1;for(;a<i;){let n=e[t+a]??``;if(wr(n)||L(n)>0)break;a++}return a}expandChangedRangeForKittyImages(e,t,n){let r=e,i=t,a=n=>{for(let a=0;a<n.length;a++){if(Ia(n[a]).length===0)continue;let o=a+this.getKittyImageReservedRows(n,a)-1;(a>=e||a<=t&&o>=e)&&(r=Math.min(r,a),i=Math.max(i,o))}};return a(this.previousLines),a(n),{firstChanged:r,lastChanged:i}}deleteChangedKittyImages(e,t){if(e<0||t<e)return``;let n=new Set,r=Math.min(t,this.previousLines.length-1);for(let t=e;t<=r;t++)for(let e of Ia(this.previousLines[t]??``))n.add(e);return this.deleteKittyImages(n)}doRender(){if(this.stopped)return;let e=this.terminal.columns,t=this.terminal.rows,n=this.previousWidth!==0&&this.previousWidth!==e,r=this.previousHeight!==0&&this.previousHeight!==t,o=this.previousHeight>0?this.previousViewportTop+this.previousHeight:t,s=r?Math.max(0,o-t):this.previousViewportTop,c=s,l=this.hardwareCursorRow,d=e=>{let t=l-s;return e-c-t},f=this.render(e);this.hasOverlayEntries&&(f=this.compositeOverlays(f,e,t));let p=this.extractCursorPosition(f,t);f=this.applyLineResets(f);let m=n=>{this.fullRedrawCount+=1;let r=new Pa(e=>this.terminal.write(e));r.append(`\x1B[?2026h`),n&&(r.append(this.deleteKittyImages(this.previousKittyImageIds)),r.append(`\x1B[2J\x1B[H\x1B[3J`));for(let e=0;e<f.length;e++){e>0&&r.append(`\r
|
|
122
|
+
`);let n=f[e],i=wr(n)?this.getKittyImageReservedRows(f,e):1;if(i>1&&i<=t){for(let e=1;e<i;e++)r.append(`\r
|
|
123
|
+
`);r.append(`\x1b[${i-1}A`),r.append(n),r.append(`\x1b[${i-1}B`),e+=i-1;continue}r.append(n)}r.append(`\x1B[?2026l`),r.flush(),this.cursorRow=Math.max(0,f.length-1),this.hardwareCursorRow=this.cursorRow,n?this.maxLinesRendered=f.length:this.maxLinesRendered=Math.max(this.maxLinesRendered,f.length);let i=Math.max(t,f.length);this.previousViewportTop=Math.max(0,i-t),this.positionHardwareCursor(p,f.length),this.previousLines=f,this.previousKittyImageIds=this.collectKittyImageIds(f),this.previousWidth=e,this.previousHeight=t},h=process.env.PI_TUI_DEBUG_REDRAW===`1`?this.logDirectory:void 0,g=e=>{if(h===void 0)return;let n=a.join(h,`pi-tui-debug.log`),r=`[${new Date().toISOString()}] fullRender: ${e} (prev=${this.previousLines.length}, new=${f.length}, height=${t})\n`;u.mkdirSync(a.dirname(n),{recursive:!0}),u.appendFileSync(n,r)};if(this.previousLines.length===0&&!n&&!r){g(`first render`),m(!1);return}if(n){g(`terminal width changed (${this.previousWidth} -> ${e})`),m(!0);return}if(r&&!Ra()){g(`terminal height changed (${this.previousHeight} -> ${t})`),m(!0);return}if(this.getClearOnShrink()&&f.length<this.maxLinesRendered&&!this.hasOverlayEntries){g(`clearOnShrink (maxLinesRendered=${this.maxLinesRendered})`),m(!0);return}let _=-1,v=-1,y=Math.max(f.length,this.previousLines.length);for(let e=0;e<y;e++)(e<this.previousLines.length?this.previousLines[e]:``)!==(e<f.length?f[e]:``)&&(_===-1&&(_=e),v=e);let b=f.length>this.previousLines.length;if(b&&(_===-1&&(_=this.previousLines.length),v=f.length-1),_!==-1){let e=this.expandChangedRangeForKittyImages(_,v,f);_=e.firstChanged,v=e.lastChanged}let x=b&&_===this.previousLines.length&&_>0;if(_===-1){this.positionHardwareCursor(p,f.length),this.previousViewportTop=s,this.previousHeight=t;return}if(_>=f.length){if(this.previousLines.length>f.length){let e=new Pa(e=>this.terminal.write(e));e.append(`\x1B[?2026h`),e.append(this.deleteChangedKittyImages(_,v));let n=Math.max(0,f.length-1);if(n<s){g(`deleted lines moved viewport up (${n} < ${s})`),m(!0);return}let r=d(n);r>0?e.append(`\x1b[${r}B`):r<0&&e.append(`\x1b[${-r}A`),e.append(`\r`);let i=this.previousLines.length-f.length;if(i>t){g(`extraLines > height (${i} > ${t})`),m(!0);return}let a=f.length===0?0:1;i>0&&a>0&&e.append(`\x1b[${a}B`);for(let t=0;t<i;t++)e.append(`\r\x1B[2K`),t<i-1&&e.append(`\x1B[1B`);let o=Math.max(0,i-1+a);o>0&&e.append(`\x1b[${o}A`),e.append(`\x1B[?2026l`),e.flush(),this.cursorRow=n,this.hardwareCursorRow=n}this.positionHardwareCursor(p,f.length),this.previousLines=f,this.previousKittyImageIds=this.collectKittyImageIds(f),this.previousWidth=e,this.previousHeight=t,this.previousViewportTop=s;return}if(_<s){g(`firstChanged < viewportTop (${_} < ${s})`),m(!0);return}let S=new Pa(e=>this.terminal.write(e));S.append(`\x1B[?2026h`),S.append(this.deleteChangedKittyImages(_,v));let C=s+t-1,w=x?_-1:_;if(w>C){let e=Math.max(0,Math.min(t-1,l-s)),n=t-1-e;n>0&&S.append(`\x1b[${n}B`);let r=w-C;S.append(`\r
|
|
124
|
+
`.repeat(r)),s+=r,c+=r,l=w}let T=d(w);T>0?S.append(`\x1b[${T}B`):T<0&&S.append(`\x1b[${-T}A`),S.append(x?`\r
|
|
125
|
+
`:`\r`);let E=Math.min(v,f.length-1);for(let n=_;n<=E;n++){n>_&&S.append(`\r
|
|
126
|
+
`);let r=f[n],o=wr(r),s=o?this.getKittyImageReservedRows(f,n,E):1;if(s>1){let e=n-c;if(e<0||e+s>t){g(`kitty image pre-clear would scroll (${e} + ${s} > ${t})`),m(!0);return}S.append(`\x1B[2K`);for(let e=1;e<s;e++)S.append(`\r
|
|
127
|
+
\x1B[2K`);S.append(`\x1b[${s-1}A`),S.append(r),S.append(`\x1b[${s-1}B`),n+=s-1;continue}if(S.append(`\x1B[2K`),!o&&L(r)>e){let t=a.join(this.logDirectory??i.tmpdir(),`pi-tui-crash.log`),o=[`Crash at ${new Date().toISOString()}`,`Terminal width: ${e}`,`Line ${n} visible width: ${L(r)}`,``,`=== All rendered lines ===`,...f.map((e,t)=>`[${t}] (w=${L(e)}) ${e}`),``].join(`
|
|
128
|
+
`);u.mkdirSync(a.dirname(t),{recursive:!0}),u.writeFileSync(t,o),this.stop();let s=[`Rendered line ${n} exceeds terminal width (${L(r)} > ${e}).`,``,`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: ${t}`].join(`
|
|
129
|
+
`);throw Error(s)}S.append(r)}let D=E;if(this.previousLines.length>f.length){if(E<f.length-1){let e=f.length-1-E;S.append(`\x1b[${e}B`),D=f.length-1}let e=this.previousLines.length-f.length;for(let e=f.length;e<this.previousLines.length;e++)S.append(`\r
|
|
130
|
+
\x1B[2K`);S.append(`\x1b[${e}A`)}if(S.append(`\x1B[?2026l`),process.env.PI_TUI_DEBUG===`1`){let e=`/tmp/tui`;u.mkdirSync(e,{recursive:!0});let n=a.join(e,`render-${Date.now()}-${Math.random().toString(36).slice(2)}.log`),r=[`firstChanged: ${_}`,`viewportTop: ${c}`,`cursorRow: ${this.cursorRow}`,`height: ${t}`,`lineDiff: ${T}`,`hardwareCursorRow: ${l}`,`renderEnd: ${E}`,`finalCursorRow: ${D}`,`cursorPos: ${JSON.stringify(p)}`,`newLines.length: ${f.length}`,`previousLines.length: ${this.previousLines.length}`,``,`=== newLines ===`,JSON.stringify(f,null,2),``,`=== previousLines ===`,JSON.stringify(this.previousLines,null,2),``,`=== buffer ===`,`[${S.length} chars written in bounded chunks]`].join(`
|
|
131
|
+
`);u.writeFileSync(n,r)}S.flush(),this.cursorRow=Math.max(0,f.length-1),this.hardwareCursorRow=D,this.maxLinesRendered=Math.max(this.maxLinesRendered,f.length),this.previousViewportTop=Math.max(s,D-t+1),this.positionHardwareCursor(p,f.length),this.previousLines=f,this.previousKittyImageIds=this.collectKittyImageIds(f),this.previousWidth=e,this.previousHeight=t}positionHardwareCursor(e,t){if(!e||t<=0){this.terminal.hideCursor();return}let n=Math.max(0,Math.min(e.row,t-1)),r=Math.max(0,e.col),i=n-this.hardwareCursorRow,a=``;i>0?a+=`\x1b[${i}B`:i<0&&(a+=`\x1b[${-i}A`),a+=`\x1b[${r+1}G`,a&&this.terminal.write(a),this.hardwareCursorRow=n,this.getShowHardwareCursor()?this.terminal.showCursor():this.terminal.hideCursor()}};function Ba(e,t){let n=e.parts.map(e=>({...e})),r=e.metadata,i=new Map,a=e=>n.find(t=>t.type===`tool`&&t.toolCallId===e);for(let e of t)switch(e.type){case`text-start`:case`reasoning-start`:{let t=e.type===`text-start`?`text`:`reasoning`,r={type:t,text:``,...e.providerMetadata!==void 0&&{providerMetadata:e.providerMetadata}};i.set(`${t}:${e.id}`,r),n.push(r);break}case`text-delta`:case`reasoning-delta`:{let t=e.type===`text-delta`?`text`:`reasoning`,n=i.get(`${t}:${e.id}`);n&&(n.text+=e.delta);break}case`text-end`:case`reasoning-end`:{let t=`${e.type.split(`-`)[0]}:${e.id}`,n=i.get(t);n&&e.providerMetadata!==void 0&&(n.providerMetadata={...n.providerMetadata,...e.providerMetadata}),i.delete(t);break}case`tool-input-start`:case`tool-input-available`:case`tool-input-error`:{let{type:t,...r}=e,i=a(e.toolCallId),o={...i,...r,type:`tool`,state:t===`tool-input-start`?`input-streaming`:t===`tool-input-available`?`input-available`:`output-error`};i?n[n.indexOf(i)]=o:n.push(o);break}case`tool-input-delta`:break;case`tool-approval-request`:case`tool-output-available`:case`tool-output-error`:case`tool-output-denied`:{let t=a(e.toolCallId);if(!t)break;e.type===`tool-approval-request`?(t.state=`approval-requested`,t.approval={id:e.approvalId}):e.type===`tool-output-available`?(t.state=`output-available`,t.output=e.output,t.preliminary=e.preliminary):e.type===`tool-output-error`?(t.state=`output-error`,t.errorText=e.errorText):t.state=`output-denied`;break}case`data`:{if(e.transient)break;let{transient:t,...r}=e,i=n.findIndex(t=>t.type===`data`&&t.name===e.name&&t.id!==void 0&&t.id===e.id);i===-1?n.push(r):n[i]=r;break}case`metadata`:r={...r,...e.metadata};break;default:n.push(e)}return{...e,parts:n,...r&&{metadata:r}}}var Va=class{#e;#t;#n;#r=[];#i;#a=!1;#o=!1;#s;#c;#l=[];#u=new Map;#d=new Map;#f=new Map;#p;#m=new Map;#h=new Set;#g=new Set;#_={connected:!1,operations:[],messages:[],turns:[]};constructor(e,t={}){this.#e=String(e),this.#t=t.followUrl??Ha,this.#b()}get state(){return this.#_}subscribe(e){return this.#h.add(e),()=>this.#h.delete(e)}onActivity(e){return this.#g.add(e),()=>this.#g.delete(e)}chunksOf(e){return this.#d.get(e)?.chunks}send(e){if(this.#a)return Promise.reject(Error(`Closed`));let t=e.eventId??crypto.randomUUID(),n={...e,eventId:t};return new Promise((e,r)=>{this.#f.set(t,{event:n,resolve:()=>{n.type===`message`&&this.#C([n.message]),e()},reject:r}),this.#o&&this.#x({type:`channels:event`,event:n})})}listConversations(){if(this.#a)return Promise.reject(Error(`Closed`));if(!this.#o)return Promise.reject(Error(`Not connected`));let e=crypto.randomUUID();return new Promise((t,n)=>{this.#m.set(e,{resolve:t,reject:n}),this.#x({type:`channels:list-conversations`,requestId:e})})}follow(e){if(this.#a||e===this.#n)return;this.#y(Error(`Switched conversation`)),this.#e=String(this.#t(new URL(this.#e),e));let t=this.#i;this.#o=!1,this.#v(),this.#b(),t?.close(),this.#D()}close(){this.#a=!0,this.#v(),this.#i?.close(),this.#y(Error(`Closed`))}#v(){clearTimeout(this.#s),this.#s=void 0}#y(e){for(let t of this.#f.values())t.reject(e);this.#f.clear();for(let t of this.#m.values())t.reject(e);this.#m.clear()}#b(){let e=new WebSocket(this.#e);this.#i=e,e.addEventListener(`message`,t=>{if(e!==this.#i||typeof t.data!=`string`)return;let n=JSON.parse(t.data);typeof n.type==`string`&&n.type.startsWith(`channels:`)&&this.#S(n)}),e.addEventListener(`close`,()=>{if(e===this.#i){this.#o=!1;for(let e of this.#m.values())e.reject(Error(`Disconnected`));this.#m.clear(),this.#D(),!(this.#a||e!==this.#i)&&(this.#s=setTimeout(()=>{this.#s=void 0,this.#b()},1e3))}})}#x(e){this.#i?.readyState===WebSocket.OPEN&&this.#i.send(JSON.stringify(e))}#S(e){if(!(e.type!==`channels:snapshot`&&e.type!==`channels:ack`&&e.type!==`channels:conversations`&&e.conversationId!==this.#n)){switch(e.type){case`channels:snapshot`:e.conversationId!==this.#n&&(this.#n!==void 0&&(this.#d.clear(),this.#e=String(this.#t(new URL(this.#e),e.conversationId))),this.#n=e.conversationId),this.#r=e.operations,this.#o=!0,this.#c=e.you,this.#l=e.messages,this.#u.clear(),this.#T(e.turns);for(let t of e.turns)this.#E(t);for(let{event:e}of this.#f.values())this.#x({type:`channels:event`,event:e});break;case`channels:turn`:this.#E(e.turn),this.#D(),this.#w({type:`turn`,turn:e.turn});return;case`channels:messages`:this.#C(e.messages);return;case`channels:chunks`:{let t=this.#d.get(e.responseId),n=(t?.chunks.length??0)-e.from;if(!t||n<0)return;let r=e.chunks.slice(n);if(r.length===0||(t.chunks.push(...r),this.#w({type:`chunks`,responseId:e.responseId,turnId:t.turnId,chunks:r}),!t.shown))return;break}case`channels:ack`:{let t=this.#f.get(e.eventId);this.#f.delete(e.eventId),e.error?t?.reject(Error(e.error)):t?.resolve();return}case`channels:end`:{let t=this.#d.get(e.responseId);if(!t)return;if(t.ended=!0,(!t.shown||e.state===`not-found`)&&this.#d.delete(e.responseId),this.#w({type:`end`,responseId:e.responseId,turnId:t.turnId,state:e.state}),e.state===`not-found`)break;return}case`channels:caught-up`:return;case`channels:conversations`:{let t=e.requestId===void 0?void 0:this.#m.get(e.requestId);if(t&&this.#m.delete(e.requestId??``),e.error){t?.reject(Error(e.error));return}e.conversations&&(this.#p=e.conversations,t?.resolve(e.conversations));break}}this.#D()}}#C(e){for(let t of e){let e=this.#l.findIndex(e=>e.id===t.id);e===-1?this.#l.push(t):this.#l[e]=t}this.#D()}#w(e){for(let t of this.#g)t(e)}#T(e){let t=new Set(e.flatMap(e=>e.status===`running`?[e.responseId]:[]));for(let[e,n]of this.#d){if(!t.has(e)){this.#d.delete(e);continue}this.#x({type:`channels:subscribe`,responseId:e,from:n.chunks.length})}}#E(e){let t=e.status===`running`?e.responseId:void 0;for(let[n,r]of this.#d)r.turnId===e.turnId&&n!==t&&(r.shown=!1,r.ended&&this.#d.delete(n));e.status!==`settled`||e.outcome===`awaiting-input`?this.#u.set(e.turnId,e):this.#u.delete(e.turnId),e.status===`running`&&!this.#d.has(e.responseId)&&(this.#d.set(e.responseId,{turnId:e.turnId,...e.extends!==void 0&&{extends:e.extends},chunks:[],shown:!0,ended:!1}),this.#x({type:`channels:subscribe`,responseId:e.responseId}))}#D(){let e=[...this.#l];for(let[t,n]of this.#d){if(!n.shown)continue;let r=e.findIndex(e=>e.id===n.extends),i=Ba(r===-1?{id:t,role:`assistant`,parts:[]}:e[r],n.chunks);r===-1?e.push(i):e[r]=i}this.#_={connected:this.#o,...this.#n!==void 0&&{conversationId:this.#n},operations:this.#r,...this.#c&&{you:this.#c},messages:e,turns:[...this.#u.values()],...this.#p&&{conversations:this.#p}};for(let e of this.#h)e(this.#_)}};function Ha(e,t){let n=new URL(e),r=/^\/channels\/([^/]+)(?:\/[^/]+)?$/.exec(e.pathname);return r&&(n.pathname=`/channels/${r[1]}/${encodeURIComponent(t)}`),n}var Ua=y(_(((e,t)=>{function n(e){return e instanceof Map?e.clear=e.delete=e.set=function(){throw Error(`map is read-only`)}:e instanceof Set&&(e.add=e.clear=e.delete=function(){throw Error(`set is read-only`)}),Object.freeze(e),Object.getOwnPropertyNames(e).forEach(t=>{let r=e[t],i=typeof r;(i===`object`||i===`function`)&&!Object.isFrozen(r)&&n(r)}),e}var r=class{constructor(e){e.data===void 0&&(e.data={}),this.data=e.data,this.isMatchIgnored=!1}ignoreMatch(){this.isMatchIgnored=!0}};function i(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`).replace(/'/g,`'`)}function a(e,...t){let n=Object.create(null);for(let t in e)n[t]=e[t];return t.forEach(function(e){for(let t in e)n[t]=e[t]}),n}let o=e=>!!e.scope,s=(e,{prefix:t})=>{if(e.startsWith(`language:`))return e.replace(`language:`,`language-`);if(e.includes(`.`)){let n=e.split(`.`);return[`${t}${n.shift()}`,...n.map((e,t)=>`${e}${`_`.repeat(t+1)}`)].join(` `)}return`${t}${e}`};var c=class{constructor(e,t){this.buffer=``,this.classPrefix=t.classPrefix,e.walk(this)}addText(e){this.buffer+=i(e)}openNode(e){if(!o(e))return;let t=s(e.scope,{prefix:this.classPrefix});this.span(t)}closeNode(e){o(e)&&(this.buffer+=`</span>`)}value(){return this.buffer}span(e){this.buffer+=`<span class="${e}">`}};let l=(e={})=>{let t={children:[]};return Object.assign(t,e),t};var u=class e{constructor(){this.rootNode=l(),this.stack=[this.rootNode]}get top(){return this.stack[this.stack.length-1]}get root(){return this.rootNode}add(e){this.top.children.push(e)}openNode(e){let t=l({scope:e});this.add(t),this.stack.push(t)}closeNode(){if(this.stack.length>1)return this.stack.pop()}closeAllNodes(){for(;this.closeNode(););}toJSON(){return JSON.stringify(this.rootNode,null,4)}walk(e){return this.constructor._walk(e,this.rootNode)}static _walk(e,t){return typeof t==`string`?e.addText(t):t.children&&(e.openNode(t),t.children.forEach(t=>this._walk(e,t)),e.closeNode(t)),e}static _collapse(t){typeof t!=`string`&&t.children&&(t.children.every(e=>typeof e==`string`)?t.children=[t.children.join(``)]:t.children.forEach(t=>{e._collapse(t)}))}},d=class extends u{constructor(e){super(),this.options=e}addText(e){e!==``&&this.add(e)}startScope(e){this.openNode(e)}endScope(){this.closeNode()}__addSublanguage(e,t){let n=e.root;t&&(n.scope=`language:${t}`),this.add(n)}toHTML(){return new c(this,this.options).value()}finalize(){return this.closeAllNodes(),!0}};function f(e){return e?typeof e==`string`?e:e.source:null}function p(e){return g(`(?=`,e,`)`)}function m(e){return g(`(?:`,e,`)*`)}function h(e){return g(`(?:`,e,`)?`)}function g(...e){return e.map(e=>f(e)).join(``)}function _(e){let t=e[e.length-1];return typeof t==`object`&&t.constructor===Object?(e.splice(e.length-1,1),t):{}}function v(...e){return`(`+(_(e).capture?``:`?:`)+e.map(e=>f(e)).join(`|`)+`)`}function y(e){return RegExp(e.toString()+`|`).exec(``).length-1}function b(e,t){let n=e&&e.exec(t);return n&&n.index===0}let x=new RegExp(v(/\[(?:[^\\\]]|\\.)*\]/,/\(\?<(?![=!])[^>]+>/,/\(\?'[^']+'/,/\(\??/,/\\([1-9][0-9]*)/,/\\./));function S(e,{joinWith:t}){let n=0;return e.map(e=>{n+=1;let t=n,r=f(e),i=``;for(;r.length>0;){let e=x.exec(r);if(!e){i+=r;break}i+=r.substring(0,e.index),r=r.substring(e.index+e[0].length),e[0][0]===`\\`&&e[1]?i+=`\\`+String(Number(e[1])+t):(i+=e[0],(e[0]===`(`||/^\(\?[<']/.test(e[0]))&&n++)}return i}).map(e=>`(${e})`).join(t)}let C=/\b\B/,w=`[a-zA-Z]\\w*`,T=`[a-zA-Z_]\\w*`,E=`\\b\\d+(\\.\\d+)?`,D=`(-?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)`,ee=`\\b(0b[01]+)`,te=(e={})=>{let t=/^#![ ]*\//;return e.binary&&(e.begin=g(t,/.*\b/,e.binary,/\b.*/)),a({scope:`meta`,begin:t,end:/$/,relevance:0,"on:begin":(e,t)=>{e.index!==0&&t.ignoreMatch()}},e)},O={begin:`\\\\[\\s\\S]`,relevance:0},ne={scope:`string`,begin:`'`,end:`'`,illegal:`\\n`,contains:[O]},k={scope:`string`,begin:`"`,end:`"`,illegal:`\\n`,contains:[O]},re={begin:/\b(a|an|the|are|I'm|isn't|don't|doesn't|won't|but|just|should|pretty|simply|enough|gonna|going|wtf|so|such|will|you|your|they|like|more)\b/},A=function(e,t,n={}){let r=a({scope:`comment`,begin:e,end:t,contains:[]},n);r.contains.push({scope:`doctag`,begin:`[ ]*(?=(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):)`,end:/(TODO|FIXME|NOTE|BUG|OPTIMIZE|HACK|XXX):/,excludeBegin:!0,relevance:0});let i=v(`I`,`a`,`is`,`so`,`us`,`to`,`at`,`if`,`in`,`it`,`on`,/[A-Za-z]+['](d|ve|re|ll|t|s|n)/,/[A-Za-z]+[-][a-z]+/,/[A-Za-z][a-z]{2,}/);return r.contains.push({begin:g(/[ ]+/,`(`,i,/[.]?[:]?([.][ ]|[ ])/,`){3}`)}),r},j=A(`//`,`$`),M=A(`/\\*`,`\\*/`),ie=A(`#`,`$`);var N=Object.freeze({__proto__:null,APOS_STRING_MODE:ne,BACKSLASH_ESCAPE:O,BINARY_NUMBER_MODE:{scope:`number`,begin:ee,relevance:0},BINARY_NUMBER_RE:ee,COMMENT:A,C_BLOCK_COMMENT_MODE:M,C_LINE_COMMENT_MODE:j,C_NUMBER_MODE:{scope:`number`,begin:D,relevance:0},C_NUMBER_RE:D,END_SAME_AS_BEGIN:function(e){return Object.assign(e,{"on:begin":(e,t)=>{t.data._beginMatch=e[1]},"on:end":(e,t)=>{t.data._beginMatch!==e[1]&&t.ignoreMatch()}})},HASH_COMMENT_MODE:ie,IDENT_RE:w,MATCH_NOTHING_RE:C,METHOD_GUARD:{begin:`\\.\\s*[a-zA-Z_]\\w*`,relevance:0},NUMBER_MODE:{scope:`number`,begin:E,relevance:0},NUMBER_RE:E,PHRASAL_WORDS_MODE:re,QUOTE_STRING_MODE:k,REGEXP_MODE:{scope:`regexp`,begin:/\/(?=[^/\n]*\/)/,end:/\/[gimuy]*/,contains:[O,{begin:/\[/,end:/\]/,relevance:0,contains:[O]}]},RE_STARTERS_RE:`!|!=|!==|%|%=|&|&&|&=|\\*|\\*=|\\+|\\+=|,|-|-=|/=|/|:|;|<<|<<=|<=|<|===|==|=|>>>=|>>=|>=|>>>|>>|>|\\?|\\[|\\{|\\(|\\^|\\^=|\\||\\|=|\\|\\||~`,SHEBANG:te,TITLE_MODE:{scope:`title`,begin:w,relevance:0},UNDERSCORE_IDENT_RE:T,UNDERSCORE_TITLE_MODE:{scope:`title`,begin:T,relevance:0}});function ae(e,t){e.input[e.index-1]===`.`&&t.ignoreMatch()}function oe(e,t){e.className!==void 0&&(e.scope=e.className,delete e.className)}function se(e,t){t&&e.beginKeywords&&(e.begin=`\\b(`+e.beginKeywords.split(` `).join(`|`)+`)(?!\\.)(?=\\b|\\s)`,e.__beforeBegin=ae,e.keywords=e.keywords||e.beginKeywords,delete e.beginKeywords,e.relevance===void 0&&(e.relevance=0))}function ce(e,t){Array.isArray(e.illegal)&&(e.illegal=v(...e.illegal))}function le(e,t){if(e.match){if(e.begin||e.end)throw Error(`begin & end are not supported with match`);e.begin=e.match,delete e.match}}function ue(e,t){e.relevance===void 0&&(e.relevance=1)}let de=(e,t)=>{if(!e.beforeMatch)return;if(e.starts)throw Error(`beforeMatch cannot be used with starts`);let n=Object.assign({},e);Object.keys(e).forEach(t=>{delete e[t]}),e.keywords=n.keywords,e.begin=g(n.beforeMatch,p(n.begin)),e.starts={relevance:0,contains:[Object.assign(n,{endsParent:!0})]},e.relevance=0,delete n.beforeMatch},fe=[`of`,`and`,`for`,`in`,`not`,`or`,`if`,`then`,`parent`,`list`,`value`];function pe(e,t,n=`keyword`){let r=Object.create(null);return typeof e==`string`?i(n,e.split(` `)):Array.isArray(e)?i(n,e):Object.keys(e).forEach(function(n){Object.assign(r,pe(e[n],t,n))}),r;function i(e,n){t&&(n=n.map(e=>e.toLowerCase())),n.forEach(function(t){let n=t.split(`|`);r[n[0]]=[e,me(n[0],n[1])]})}}function me(e,t){return t?Number(t):+!he(e)}function he(e){return fe.includes(e.toLowerCase())}let ge={},_e=e=>{console.error(e)},ve=(e,...t)=>{console.log(`WARN: ${e}`,...t)},ye=(e,t)=>{ge[`${e}/${t}`]||(console.log(`Deprecated as of ${e}. ${t}`),ge[`${e}/${t}`]=!0)},be=Error();function xe(e,t,{key:n}){let r=0,i=e[n],a={},o={};for(let e=1;e<=t.length;e++)o[e+r]=i[e],a[e+r]=!0,r+=y(t[e-1]);e[n]=o,e[n]._emit=a,e[n]._multi=!0}function Se(e){if(Array.isArray(e.begin)){if(e.skip||e.excludeBegin||e.returnBegin)throw _e(`skip, excludeBegin, returnBegin not compatible with beginScope: {}`),be;if(typeof e.beginScope!=`object`||e.beginScope===null)throw _e(`beginScope must be object`),be;xe(e,e.begin,{key:`beginScope`}),e.begin=S(e.begin,{joinWith:``})}}function Ce(e){if(Array.isArray(e.end)){if(e.skip||e.excludeEnd||e.returnEnd)throw _e(`skip, excludeEnd, returnEnd not compatible with endScope: {}`),be;if(typeof e.endScope!=`object`||e.endScope===null)throw _e(`endScope must be object`),be;xe(e,e.end,{key:`endScope`}),e.end=S(e.end,{joinWith:``})}}function we(e){e.scope&&typeof e.scope==`object`&&e.scope!==null&&(e.beginScope=e.scope,delete e.scope)}function Te(e){we(e),typeof e.beginScope==`string`&&(e.beginScope={_wrap:e.beginScope}),typeof e.endScope==`string`&&(e.endScope={_wrap:e.endScope}),Se(e),Ce(e)}function Ee(e){function t(t,n){return new RegExp(f(t),`m`+(e.case_insensitive?`i`:``)+(e.unicodeRegex?`u`:``)+(n?`g`:``))}class n{constructor(){this.matchIndexes={},this.regexes=[],this.matchAt=1,this.position=0}addRule(e,t){t.position=this.position++,this.matchIndexes[this.matchAt]=t,this.regexes.push([t,e]),this.matchAt+=y(e)+1}compile(){this.regexes.length===0&&(this.exec=()=>null);let e=this.regexes.map(e=>e[1]);this.matcherRe=t(S(e,{joinWith:`|`}),!0),this.lastIndex=0}exec(e){this.matcherRe.lastIndex=this.lastIndex;let t=this.matcherRe.exec(e);if(!t)return null;let n=t.findIndex((e,t)=>t>0&&e!==void 0),r=this.matchIndexes[n];return t.splice(0,n),Object.assign(t,r)}}class r{constructor(){this.rules=[],this.multiRegexes=[],this.count=0,this.lastIndex=0,this.regexIndex=0}getMatcher(e){if(this.multiRegexes[e])return this.multiRegexes[e];let t=new n;return this.rules.slice(e).forEach(([e,n])=>t.addRule(e,n)),t.compile(),this.multiRegexes[e]=t,t}resumingScanAtSamePosition(){return this.regexIndex!==0}considerAll(){this.regexIndex=0}addRule(e,t){this.rules.push([e,t]),t.type===`begin`&&this.count++}exec(e){let t=this.getMatcher(this.regexIndex);t.lastIndex=this.lastIndex;let n=t.exec(e);if(this.resumingScanAtSamePosition()&&!(n&&n.index===this.lastIndex)){let t=this.getMatcher(0);t.lastIndex=this.lastIndex+1,n=t.exec(e)}return n&&(this.regexIndex+=n.position+1,this.regexIndex===this.count&&this.considerAll()),n}}function i(e){let t=new r;return e.contains.forEach(e=>t.addRule(e.begin,{rule:e,type:`begin`})),e.terminatorEnd&&t.addRule(e.terminatorEnd,{type:`end`}),e.illegal&&t.addRule(e.illegal,{type:`illegal`}),t}function o(n,r){let a=n;if(n.isCompiled)return a;[oe,le,Te,de].forEach(e=>e(n,r)),e.compilerExtensions.forEach(e=>e(n,r)),n.__beforeBegin=null,[se,ce,ue].forEach(e=>e(n,r)),n.isCompiled=!0;let s=null;return typeof n.keywords==`object`&&n.keywords.$pattern&&(n.keywords=Object.assign({},n.keywords),s=n.keywords.$pattern,delete n.keywords.$pattern),s||=/\w+/,n.keywords&&=pe(n.keywords,e.case_insensitive),a.keywordPatternRe=t(s,!0),r&&(n.begin||=/\B|\b/,a.beginRe=t(a.begin),!n.end&&!n.endsWithParent&&(n.end=/\B|\b/),n.end&&(a.endRe=t(a.end)),a.terminatorEnd=f(a.end)||``,n.endsWithParent&&r.terminatorEnd&&(a.terminatorEnd+=(n.end?`|`:``)+r.terminatorEnd)),n.illegal&&(a.illegalRe=t(n.illegal)),n.contains||=[],n.contains=[].concat(...n.contains.map(function(e){return Oe(e===`self`?n:e)})),n.contains.forEach(function(e){o(e,a)}),n.starts&&o(n.starts,r),a.matcher=i(a),a}if(e.compilerExtensions||=[],e.contains&&e.contains.includes(`self`))throw Error("ERR: contains `self` is not supported at the top-level of a language. See documentation.");return e.classNameAliases=a(e.classNameAliases||{}),o(e)}function De(e){return e?e.endsWithParent||De(e.starts):!1}function Oe(e){return e.variants&&!e.cachedVariants&&(e.cachedVariants=e.variants.map(function(t){return a(e,{variants:null},t)})),e.cachedVariants?e.cachedVariants:De(e)?a(e,{starts:e.starts?a(e.starts):null}):Object.isFrozen(e)?a(e):e}var ke=`11.12.0`,Ae=class extends Error{constructor(e,t){super(e),this.name=`HTMLInjectionError`,this.html=t}};let je=i,Me=a,P=Symbol(`nomatch`),Ne=function(e){let t=Object.create(null),i=Object.create(null),a=[],o=!0,s=`Could not find the language '{}', did you forget to load/include a language module?`,c={disableAutodetect:!0,name:`Plain text`,contains:[]},l={ignoreUnescapedHTML:!1,throwUnescapedHTML:!1,noHighlightRe:/^(no-?highlight)$/i,languageDetectRe:/\blang(?:uage)?-([\w-]+)\b/i,classPrefix:`hljs-`,cssSelector:`pre code`,languages:null,__emitter:d};function u(e){return l.noHighlightRe.test(e)}function f(e){let t=e.className+` `;t+=e.parentNode?e.parentNode.className:``;let n=l.languageDetectRe.exec(t);if(n){let t=re(n[1]);return t||(ve(s.replace(`{}`,n[1])),ve(`Falling back to no-highlight mode for this block.`,e)),t?n[1]:`no-highlight`}return t.split(/\s+/).find(e=>u(e)||re(e))}function _(e,t,n){let r=``,i=``;typeof t==`object`?(r=e,n=t.ignoreIllegals,i=t.language):(ye(`10.7.0`,`highlight(lang, code, ...args) has been deprecated.`),ye(`10.7.0`,`Please use highlight(code, options) instead.
|
|
132
|
+
https://github.com/highlightjs/highlight.js/issues/2277`),i=e,r=t),n===void 0&&(n=!0);let a={code:r,language:i};oe(`before:highlight`,a);let o=a.result?a.result:y(a.language,a.code,n);return o.code=a.code,oe(`after:highlight`,o),o}function y(e,n,i,a){let c=Object.create(null);function u(e,t){return e.keywords[t]}function d(){if(!O.keywords){k.addText(A);return}let e=0;O.keywordPatternRe.lastIndex=0;let t=O.keywordPatternRe.exec(A),n=``;for(;t;){n+=A.substring(e,t.index);let r=D.case_insensitive?t[0].toLowerCase():t[0],i=u(O,r);if(i){let[e,a]=i;if(k.addText(n),n=``,c[r]=(c[r]||0)+1,c[r]<=7&&(j+=a),e.startsWith(`_`))n+=t[0];else{let n=D.classNameAliases[e]||e;m(t[0],n)}}else n+=t[0];e=O.keywordPatternRe.lastIndex,t=O.keywordPatternRe.exec(A)}n+=A.substring(e),k.addText(n)}function f(){if(A===``)return;let e=null;if(typeof O.subLanguage==`string`){if(!t[O.subLanguage]){k.addText(A);return}e=y(O.subLanguage,A,!0,ne[O.subLanguage]),ne[O.subLanguage]=e._top}else e=S(A,O.subLanguage.length?O.subLanguage:null);O.relevance>0&&(j+=e.relevance),k.__addSublanguage(e._emitter,e.language)}function p(){O.subLanguage==null?d():f(),A=``}function m(e,t){e!==``&&(k.startScope(t),k.addText(e),k.endScope())}function h(e,t){let n=1,r=t.length-1;for(;n<=r;){if(!e._emit[n]){n++;continue}let r=D.classNameAliases[e[n]]||e[n],i=t[n];r?m(i,r):(A=i,d(),A=``),n++}}function g(e,t){return e.scope&&typeof e.scope==`string`&&k.openNode(D.classNameAliases[e.scope]||e.scope),e.beginScope&&(e.beginScope._wrap?(m(A,D.classNameAliases[e.beginScope._wrap]||e.beginScope._wrap),A=``):e.beginScope._multi&&(h(e.beginScope,t),A=``)),O=Object.create(e,{parent:{value:O}}),O}function _(e,t,n){let i=b(e.endRe,n);if(i){if(e[`on:end`]){let n=new r(e);e[`on:end`](t,n),n.isMatchIgnored&&(i=!1)}if(i){for(;e.endsParent&&e.parent;)e=e.parent;return e}}if(e.endsWithParent)return _(e.parent,t,n)}function v(e){return O.matcher.regexIndex===0?(A+=e[0],1):(N=!0,0)}function x(e){let t=e[0],n=e.rule,i=new r(n),a=[n.__beforeBegin,n[`on:begin`]];for(let n of a)if(n&&(n(e,i),i.isMatchIgnored))return v(t);return n.skip?A+=t:(n.excludeBegin&&(A+=t),p(),!n.returnBegin&&!n.excludeBegin&&(A=t)),g(n,e),n.returnBegin?0:t.length}function C(e){let t=e[0],r=n.substring(e.index),i=_(O,e,r);if(!i)return P;let a=O;O.endScope&&O.endScope._wrap?(p(),m(t,O.endScope._wrap)):O.endScope&&O.endScope._multi?(p(),h(O.endScope,e)):a.skip?A+=t:(a.returnEnd||a.excludeEnd||(A+=t),p(),a.excludeEnd&&(A=t));do O.scope&&k.closeNode(),!O.skip&&!O.subLanguage&&(j+=O.relevance),O=O.parent;while(O!==i.parent);return i.starts&&g(i.starts,e),a.returnEnd?0:t.length}function w(){let e=[];for(let t=O;t!==D;t=t.parent)t.scope&&e.unshift(t.scope);e.forEach(e=>k.openNode(e))}let T={};function E(t,r){let a=r&&r[0];if(A+=t,a==null)return p(),0;if(T.type===`begin`&&r.type===`end`&&T.index===r.index&&a===``){if(A+=n.slice(r.index,r.index+1),!o){let t=Error(`0 width match regex (${e})`);throw t.languageName=e,t.badRule=T.rule,t}return 1}if(T=r,r.type===`begin`)return x(r);if(r.type===`illegal`&&!i){let e=Error(`Illegal lexeme "`+a+`" for mode "`+(O.scope||`<unnamed>`)+`"`);throw e.mode=O,e}else if(r.type===`end`){let e=C(r);if(e!==P)return e}if(r.type===`illegal`&&a===``)return r.index===n.length||(A+=`
|
|
133
|
+
`),1;if(ie>1e5&&ie>r.index*3)throw Error(`potential infinite loop, way more iterations than matches`);return A+=a,a.length}let D=re(e);if(!D)throw _e(s.replace(`{}`,e)),Error(`Unknown language: "`+e+`"`);let ee=Ee(D),te=``,O=a||ee,ne={},k=new l.__emitter(l);w();let A=``,j=0,M=0,ie=0,N=!1;try{if(D.__emitTokens)D.__emitTokens(n,k);else{for(O.matcher.considerAll();;){ie++,N?N=!1:O.matcher.considerAll(),O.matcher.lastIndex=M;let e=O.matcher.exec(n);if(!e)break;let t=E(n.substring(M,e.index),e);M=e.index+t}E(n.substring(M))}return k.finalize(),te=k.toHTML(),{language:e,value:te,relevance:j,illegal:!1,_emitter:k,_top:O}}catch(t){if(t.message&&t.message.includes(`Illegal`))return{language:e,value:je(n),illegal:!0,relevance:0,_illegalBy:{message:t.message,index:M,context:n.slice(M-100,M+100),mode:t.mode,resultSoFar:te},_emitter:k};if(o)return{language:e,value:je(n),illegal:!1,relevance:0,errorRaised:t,_emitter:k,_top:O};throw t}}function x(e){let t={value:je(e),illegal:!1,relevance:0,_top:c,_emitter:new l.__emitter(l)};return t._emitter.addText(e),t}function S(e,n){n=n||l.languages||Object.keys(t);let r=x(e),i=n.filter(re).filter(j).map(t=>y(t,e,!1));i.unshift(r);let[a,o]=i.sort((e,t)=>{if(e.relevance!==t.relevance)return t.relevance-e.relevance;if(e.language&&t.language){if(re(e.language).supersetOf===t.language)return 1;if(re(t.language).supersetOf===e.language)return-1}return 0}),s=a;return s.secondBest=o,s}function C(e,t,n){let r=t&&i[t]||n;e.classList.add(`hljs`),e.classList.add(`language-${r}`)}function w(e){let t=null,n=f(e);if(u(n))return;if(oe(`before:highlightElement`,{el:e,language:n}),e.dataset.highlighted){console.log("Element previously highlighted. To highlight again, first unset `dataset.highlighted`.",e);return}if(e.children.length>0&&(l.ignoreUnescapedHTML||(console.warn(`One of your code blocks includes unescaped HTML. This is a potentially serious security risk.`),console.warn(`https://github.com/highlightjs/highlight.js/wiki/security`),console.warn(`The element with unescaped HTML:`),console.warn(e)),l.throwUnescapedHTML))throw new Ae(`One of your code blocks includes unescaped HTML.`,e.innerHTML);t=e;let r=t.textContent,i=n?_(r,{language:n,ignoreIllegals:!0}):S(r);e.innerHTML=i.value,e.dataset.highlighted=`yes`,C(e,n,i.language),e.result={language:i.language,re:i.relevance,relevance:i.relevance},i.secondBest&&(e.secondBest={language:i.secondBest.language,relevance:i.secondBest.relevance}),oe(`after:highlightElement`,{el:e,result:i,text:r})}function T(e){l=Me(l,e)}let E=()=>{te(),ye(`10.6.0`,`initHighlighting() deprecated. Use highlightAll() now.`)};function D(){te(),ye(`10.6.0`,`initHighlightingOnLoad() deprecated. Use highlightAll() now.`)}let ee=!1;function te(){function e(){te()}if(document.readyState===`loading`){ee||window.addEventListener(`DOMContentLoaded`,e,!1),ee=!0;return}document.querySelectorAll(l.cssSelector).forEach(w)}function O(n,r){let i=null;try{i=r(e)}catch(e){if(_e(`Language definition for '{}' could not be registered.`.replace(`{}`,n)),o)_e(e);else throw e;i=c}i.name||=n,t[n]=i,i.rawDefinition=r.bind(null,e),i.aliases&&A(i.aliases,{languageName:n})}function ne(e){delete t[e];for(let t of Object.keys(i))i[t]===e&&delete i[t]}function k(){return Object.keys(t)}function re(e){return e=(e||``).toLowerCase(),t[e]||t[i[e]]}function A(e,{languageName:t}){typeof e==`string`&&(e=[e]),e.forEach(e=>{i[e.toLowerCase()]=t})}function j(e){let t=re(e);return t&&!t.disableAutodetect}function M(e){e[`before:highlightBlock`]&&!e[`before:highlightElement`]&&(e[`before:highlightElement`]=t=>{e[`before:highlightBlock`](Object.assign({block:t.el},t))}),e[`after:highlightBlock`]&&!e[`after:highlightElement`]&&(e[`after:highlightElement`]=t=>{e[`after:highlightBlock`](Object.assign({block:t.el},t))})}function ie(e){M(e),a.push(e)}function ae(e){let t=a.indexOf(e);t!==-1&&a.splice(t,1)}function oe(e,t){let n=e;a.forEach(function(e){e[n]&&e[n](t)})}function se(e){return ye(`10.7.0`,`highlightBlock will be removed entirely in v12.0`),ye(`10.7.0`,`Please use highlightElement now.`),w(e)}Object.assign(e,{highlight:_,highlightAuto:S,highlightAll:te,highlightElement:w,highlightBlock:se,configure:T,initHighlighting:E,initHighlightingOnLoad:D,registerLanguage:O,unregisterLanguage:ne,listLanguages:k,getLanguage:re,registerAliases:A,autoDetection:j,inherit:Me,addPlugin:ie,removePlugin:ae}),e.debugMode=function(){o=!1},e.safeMode=function(){o=!0},e.versionString=ke,e.regex={concat:g,lookahead:p,either:v,optional:h,anyNumberOfTimes:m};for(let e in N)typeof N[e]==`object`&&n(N[e]);return Object.assign(e,N),e},F=Ne({});F.newInstance=()=>Ne({}),t.exports=F,F.HighlightJS=F,F.default=F}))()).default;function Wa(e){let t=e.regex,n={},r={begin:/\$\{/,end:/\}/,contains:[`self`,{begin:/:-/,contains:[n]}]};Object.assign(n,{className:`variable`,variants:[{begin:t.concat(/\$[\w\d#@][\w\d_]*/,`(?![\\w\\d])(?![$])`)},r]});let i={className:`subst`,begin:/\$\(/,end:/\)/,contains:[e.BACKSLASH_ESCAPE]},a=e.inherit(e.COMMENT(),{match:[/(^|\s)/,/#.*$/],scope:{2:`comment`}}),o={begin:/<<-?\s*(?=\w+)/,starts:{contains:[e.END_SAME_AS_BEGIN({begin:/(\w+)/,end:/(\w+)/,className:`string`})]}},s={className:`string`,begin:/"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,n,i]};i.contains.push(s);let c={match:/\\"/},l={className:`string`,begin:/'/,end:/'/},u={match:/\\'/},d={begin:/\$?\(\(/,end:/\)\)/,contains:[{begin:/\d+#[0-9a-f]+/,className:`number`},e.NUMBER_MODE,n]},f=e.SHEBANG({binary:`(${[`fish`,`bash`,`zsh`,`sh`,`csh`,`ksh`,`tcsh`,`dash`,`scsh`].join(`|`)})`,relevance:10}),p={className:`function`,begin:/\w[\w\d_]*\s*\(\s*\)\s*\{/,returnBegin:!0,contains:[e.inherit(e.TITLE_MODE,{begin:/\w[\w\d_]*/})],relevance:0},m=[`if`,`then`,`else`,`elif`,`fi`,`time`,`for`,`while`,`until`,`in`,`do`,`done`,`case`,`esac`,`coproc`,`function`,`select`],h=[`true`,`false`],g={match:/(\/[a-z._-]+)+/},_=[`break`,`cd`,`continue`,`eval`,`exec`,`exit`,`export`,`getopts`,`hash`,`pwd`,`readonly`,`return`,`shift`,`test`,`times`,`trap`,`umask`,`unset`],v=[`alias`,`bind`,`builtin`,`caller`,`command`,`declare`,`echo`,`enable`,`help`,`let`,`local`,`logout`,`mapfile`,`printf`,`read`,`readarray`,`source`,`sudo`,`type`,`typeset`,`ulimit`,`unalias`],y=`autoload.bg.bindkey.bye.cap.chdir.clone.comparguments.compcall.compctl.compdescribe.compfiles.compgroups.compquote.comptags.comptry.compvalues.dirs.disable.disown.echotc.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`.split(`.`),b=`chcon.chgrp.chown.chmod.cp.dd.df.dir.dircolors.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.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`.split(`.`);return{name:`Bash`,aliases:[`sh`,`zsh`],keywords:{$pattern:/\b[a-z][a-z0-9._-]+\b/,keyword:m,literal:h,built_in:[..._,...v,`set`,`shopt`,...y,...b]},contains:[f,e.SHEBANG(),p,d,a,o,g,s,c,l,u,n]}}const Ga=e=>({IMPORTANT:{scope:`meta`,begin:`!important`},BLOCK_COMMENT:e.C_BLOCK_COMMENT_MODE,HEXCOLOR:{scope:`number`,begin:/#(([0-9a-fA-F]{3,4})|(([0-9a-fA-F]{2}){3,4}))\b/},UNICODE_RANGE:{scope:`number`,begin:/\b[Uu]\+[0-9A-Fa-f][0-9A-Fa-f?]{0,5}(-[0-9A-Fa-f][0-9A-Fa-f]{0,5})?/},FUNCTION_DISPATCH:{className:`built_in`,begin:/[\w-]+(?=\()/},ATTRIBUTE_SELECTOR_MODE:{scope:`selector-attr`,begin:/\[/,end:/\]/,illegal:`$`,contains:[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},CSS_NUMBER_MODE:{scope:`number`,begin:e.NUMBER_RE+`(%|em|ex|ch|rem|vw|vh|vmin|vmax|cm|mm|in|pt|pc|px|deg|grad|rad|turn|s|ms|Hz|kHz|dpi|dpcm|dppx)?`,relevance:0},CSS_VARIABLE:{className:`attr`,begin:/--[A-Za-z_][A-Za-z0-9_-]*/}}),Ka=`a.abbr.address.article.aside.audio.b.blockquote.body.button.canvas.caption.cite.code.dd.del.details.dfn.div.dl.dt.em.fieldset.figcaption.figure.footer.form.h1.h2.h3.h4.h5.h6.header.hgroup.html.i.iframe.img.input.ins.kbd.label.legend.li.main.mark.menu.nav.object.ol.optgroup.option.p.picture.q.quote.samp.section.select.source.span.strong.summary.sup.table.tbody.td.textarea.tfoot.th.thead.time.tr.ul.var.video`.split(`.`),qa=`defs.g.marker.mask.pattern.svg.switch.symbol.feBlend.feColorMatrix.feComponentTransfer.feComposite.feConvolveMatrix.feDiffuseLighting.feDisplacementMap.feFlood.feGaussianBlur.feImage.feMerge.feMorphology.feOffset.feSpecularLighting.feTile.feTurbulence.linearGradient.radialGradient.stop.circle.ellipse.image.line.path.polygon.polyline.rect.text.use.textPath.tspan.foreignObject.clipPath`.split(`.`),Ja=[...Ka,...qa],Ya=`any-hover.any-pointer.aspect-ratio.color.color-gamut.color-index.device-aspect-ratio.device-height.device-width.display-mode.forced-colors.grid.height.hover.inverted-colors.monochrome.orientation.overflow-block.overflow-inline.pointer.prefers-color-scheme.prefers-contrast.prefers-reduced-motion.prefers-reduced-transparency.resolution.scan.scripting.update.width.min-width.max-width.min-height.max-height`.split(`.`).sort().reverse(),Xa=`active.any-link.blank.checked.current.default.defined.dir.disabled.drop.empty.enabled.first.first-child.first-of-type.fullscreen.future.focus.focus-visible.focus-within.has.host.host-context.hover.indeterminate.in-range.invalid.is.lang.last-child.last-of-type.left.link.local-link.not.nth-child.nth-col.nth-last-child.nth-last-col.nth-last-of-type.nth-of-type.only-child.only-of-type.optional.out-of-range.past.placeholder-shown.read-only.read-write.required.right.root.scope.target.target-within.user-invalid.valid.visited.where`.split(`.`).sort().reverse(),Za=[`after`,`backdrop`,`before`,`cue`,`cue-region`,`first-letter`,`first-line`,`grammar-error`,`marker`,`part`,`placeholder`,`selection`,`slotted`,`spelling-error`].sort().reverse(),Qa=`accent-color.align-content.align-items.align-self.alignment-baseline.all.anchor-name.animation.animation-composition.animation-delay.animation-direction.animation-duration.animation-fill-mode.animation-iteration-count.animation-name.animation-play-state.animation-range.animation-range-end.animation-range-start.animation-timeline.animation-timing-function.appearance.aspect-ratio.backdrop-filter.backface-visibility.background.background-attachment.background-blend-mode.background-clip.background-color.background-image.background-origin.background-position.background-position-x.background-position-y.background-repeat.background-size.baseline-shift.block-size.border.border-block.border-block-color.border-block-end.border-block-end-color.border-block-end-style.border-block-end-width.border-block-start.border-block-start-color.border-block-start-style.border-block-start-width.border-block-style.border-block-width.border-bottom.border-bottom-color.border-bottom-left-radius.border-bottom-right-radius.border-bottom-style.border-bottom-width.border-collapse.border-color.border-end-end-radius.border-end-start-radius.border-image.border-image-outset.border-image-repeat.border-image-slice.border-image-source.border-image-width.border-inline.border-inline-color.border-inline-end.border-inline-end-color.border-inline-end-style.border-inline-end-width.border-inline-start.border-inline-start-color.border-inline-start-style.border-inline-start-width.border-inline-style.border-inline-width.border-left.border-left-color.border-left-style.border-left-width.border-radius.border-right.border-right-color.border-right-style.border-right-width.border-spacing.border-start-end-radius.border-start-start-radius.border-style.border-top.border-top-color.border-top-left-radius.border-top-right-radius.border-top-style.border-top-width.border-width.bottom.box-align.box-decoration-break.box-direction.box-flex.box-flex-group.box-lines.box-ordinal-group.box-orient.box-pack.box-shadow.box-sizing.break-after.break-before.break-inside.caption-side.caret-color.clear.clip.clip-path.clip-rule.color.color-interpolation.color-interpolation-filters.color-profile.color-rendering.color-scheme.column-count.column-fill.column-gap.column-rule.column-rule-color.column-rule-style.column-rule-width.column-span.column-width.columns.contain.contain-intrinsic-block-size.contain-intrinsic-height.contain-intrinsic-inline-size.contain-intrinsic-size.contain-intrinsic-width.container.container-name.container-type.content.content-visibility.corner-bottom-left-shape.corner-bottom-right-shape.corner-shape.corner-top-left-shape.corner-top-right-shape.counter-increment.counter-reset.counter-set.cue.cue-after.cue-before.cursor.cx.cy.direction.display.dominant-baseline.empty-cells.enable-background.field-sizing.fill.fill-opacity.fill-rule.filter.flex.flex-basis.flex-direction.flex-flow.flex-grow.flex-shrink.flex-wrap.float.flood-color.flood-opacity.flow.font.font-display.font-family.font-feature-settings.font-kerning.font-language-override.font-optical-sizing.font-palette.font-size.font-size-adjust.font-smooth.font-smoothing.font-stretch.font-style.font-synthesis.font-synthesis-position.font-synthesis-small-caps.font-synthesis-style.font-synthesis-weight.font-variant.font-variant-alternates.font-variant-caps.font-variant-east-asian.font-variant-emoji.font-variant-ligatures.font-variant-numeric.font-variant-position.font-variation-settings.font-weight.forced-color-adjust.gap.glyph-orientation-horizontal.glyph-orientation-vertical.grid.grid-area.grid-auto-columns.grid-auto-flow.grid-auto-rows.grid-column.grid-column-end.grid-column-start.grid-gap.grid-row.grid-row-end.grid-row-start.grid-template.grid-template-areas.grid-template-columns.grid-template-rows.hanging-punctuation.height.hyphenate-character.hyphenate-limit-chars.hyphens.icon.image-orientation.image-rendering.image-resolution.ime-mode.initial-letter.initial-letter-align.inline-size.inset.inset-area.inset-block.inset-block-end.inset-block-start.inset-inline.inset-inline-end.inset-inline-start.isolation.justify-content.justify-items.justify-self.kerning.left.letter-spacing.lighting-color.line-break.line-height.line-height-step.list-style.list-style-image.list-style-position.list-style-type.margin.margin-block.margin-block-end.margin-block-start.margin-bottom.margin-inline.margin-inline-end.margin-inline-start.margin-left.margin-right.margin-top.margin-trim.marker.marker-end.marker-mid.marker-start.marks.mask.mask-border.mask-border-mode.mask-border-outset.mask-border-repeat.mask-border-slice.mask-border-source.mask-border-width.mask-clip.mask-composite.mask-image.mask-mode.mask-origin.mask-position.mask-repeat.mask-size.mask-type.masonry-auto-flow.math-depth.math-shift.math-style.max-block-size.max-height.max-inline-size.max-width.min-block-size.min-height.min-inline-size.min-width.mix-blend-mode.nav-down.nav-index.nav-left.nav-right.nav-up.none.normal.object-fit.object-position.offset.offset-anchor.offset-distance.offset-path.offset-position.offset-rotate.opacity.order.orphans.outline.outline-color.outline-offset.outline-style.outline-width.overflow.overflow-anchor.overflow-block.overflow-clip-margin.overflow-inline.overflow-wrap.overflow-x.overflow-y.overlay.overscroll-behavior.overscroll-behavior-block.overscroll-behavior-inline.overscroll-behavior-x.overscroll-behavior-y.padding.padding-block.padding-block-end.padding-block-start.padding-bottom.padding-inline.padding-inline-end.padding-inline-start.padding-left.padding-right.padding-top.page.page-break-after.page-break-before.page-break-inside.paint-order.pause.pause-after.pause-before.perspective.perspective-origin.place-content.place-items.place-self.pointer-events.position.position-anchor.position-visibility.print-color-adjust.quotes.r.resize.rest.rest-after.rest-before.right.rotate.row-gap.ruby-align.ruby-position.scale.scroll-behavior.scroll-margin.scroll-margin-block.scroll-margin-block-end.scroll-margin-block-start.scroll-margin-bottom.scroll-margin-inline.scroll-margin-inline-end.scroll-margin-inline-start.scroll-margin-left.scroll-margin-right.scroll-margin-top.scroll-padding.scroll-padding-block.scroll-padding-block-end.scroll-padding-block-start.scroll-padding-bottom.scroll-padding-inline.scroll-padding-inline-end.scroll-padding-inline-start.scroll-padding-left.scroll-padding-right.scroll-padding-top.scroll-snap-align.scroll-snap-stop.scroll-snap-type.scroll-timeline.scroll-timeline-axis.scroll-timeline-name.scrollbar-color.scrollbar-gutter.scrollbar-width.shape-image-threshold.shape-margin.shape-outside.shape-rendering.speak.speak-as.src.stop-color.stop-opacity.stroke.stroke-dasharray.stroke-dashoffset.stroke-linecap.stroke-linejoin.stroke-miterlimit.stroke-opacity.stroke-width.tab-size.table-layout.text-align.text-align-all.text-align-last.text-anchor.text-combine-upright.text-decoration.text-decoration-color.text-decoration-line.text-decoration-skip.text-decoration-skip-ink.text-decoration-style.text-decoration-thickness.text-emphasis.text-emphasis-color.text-emphasis-position.text-emphasis-style.text-indent.text-justify.text-orientation.text-overflow.text-rendering.text-shadow.text-size-adjust.text-transform.text-underline-offset.text-underline-position.text-wrap.text-wrap-mode.text-wrap-style.timeline-scope.top.touch-action.transform.transform-box.transform-origin.transform-style.transition.transition-behavior.transition-delay.transition-duration.transition-property.transition-timing-function.translate.unicode-bidi.unicode-range.user-modify.user-select.vector-effect.vertical-align.view-timeline.view-timeline-axis.view-timeline-inset.view-timeline-name.view-transition-name.visibility.voice-balance.voice-duration.voice-family.voice-pitch.voice-range.voice-rate.voice-stress.voice-volume.white-space.white-space-collapse.widows.width.will-change.word-break.word-spacing.word-wrap.writing-mode.x.y.z-index.zoom`.split(`.`).sort().reverse();function $a(e){let t=e.regex,n=Ga(e),r={begin:/-(webkit|moz|ms|o)-(?=[a-z])/},i=/@-?\w[\w]*(-\w+)*/,a=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE];return{name:`CSS`,case_insensitive:!0,illegal:/[=|'\$]/,keywords:{keyframePosition:`from to`},classNameAliases:{keyframePosition:`selector-tag`},contains:[n.BLOCK_COMMENT,r,n.CSS_NUMBER_MODE,{className:`selector-id`,begin:/#[A-Za-z0-9_-]+/,relevance:0},{className:`selector-class`,begin:`\\.[a-zA-Z-][a-zA-Z0-9_-]*`,relevance:0},n.ATTRIBUTE_SELECTOR_MODE,{className:`selector-pseudo`,variants:[{begin:`:(`+Xa.join(`|`)+`)`},{begin:`:(:)?(`+Za.join(`|`)+`)`}]},n.CSS_VARIABLE,{className:`attribute`,begin:`\\b(`+Qa.join(`|`)+`)\\b`},{begin:/:/,end:/[;}{]/,contains:[n.BLOCK_COMMENT,n.HEXCOLOR,n.IMPORTANT,n.CSS_NUMBER_MODE,n.UNICODE_RANGE,...a,{begin:/(url|data-uri)\(/,end:/\)/,relevance:0,keywords:{built_in:`url data-uri`},contains:[...a,{className:`string`,begin:/[^)]/,endsWithParent:!0,excludeEnd:!0}]},n.FUNCTION_DISPATCH]},{begin:t.lookahead(/@/),end:`[{;]`,relevance:0,illegal:/:/,contains:[{className:`keyword`,begin:i},{begin:/\s/,endsWithParent:!0,excludeEnd:!0,relevance:0,keywords:{$pattern:/[a-z-]+/,keyword:`and or not only`,attribute:Ya.join(` `)},contains:[{begin:/[a-z-]+(?=:)/,className:`attribute`},...a,n.CSS_NUMBER_MODE]}]},{className:`selector-tag`,begin:`\\b(`+Ja.join(`|`)+`)\\b`}]}}function eo(e){let t=e.regex;return{name:`Diff`,aliases:[`patch`],contains:[{className:`meta`,relevance:10,match:t.either(/^@@ +-\d+,\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+ +\+\d+,\d+ +@@/,/^@@ +-\d+,\d+ +\+\d+ +@@/,/^@@ +-\d+ +\+\d+ +@@/,/^\*\*\* +\d+,\d+ +\*\*\*\*$/,/^--- +\d+,\d+ +----$/)},{className:`comment`,variants:[{begin:t.either(/Index: /,/^index/,/={3,}/,/^-{3}/,/^\*{3} /,/^\+{3}/,/^diff --git/),end:/$/},{match:/^\*{15}$/}]},{className:`addition`,begin:/^\+/,end:/$/},{className:`deletion`,begin:/^-/,end:/$/},{className:`addition`,begin:/^!/,end:/$/}]}}const to=`[A-Za-z$_][0-9A-Za-z$_]*`,no=`as.in.of.if.for.while.finally.var.new.function.do.return.void.else.break.catch.instanceof.with.throw.case.default.try.switch.continue.typeof.delete.let.yield.const.class.debugger.async.await.static.import.from.export.extends.using`.split(`.`),ro=[`true`,`false`,`null`,`undefined`,`NaN`,`Infinity`],io=`Object.Function.Boolean.Symbol.Math.Date.Number.BigInt.String.RegExp.Array.Float32Array.Float64Array.Int8Array.Uint8Array.Uint8ClampedArray.Int16Array.Int32Array.Uint16Array.Uint32Array.BigInt64Array.BigUint64Array.Set.Map.WeakSet.WeakMap.ArrayBuffer.SharedArrayBuffer.Atomics.DataView.JSON.Promise.Generator.GeneratorFunction.AsyncFunction.Reflect.Proxy.Intl.WebAssembly`.split(`.`),ao=[`Error`,`EvalError`,`InternalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],oo=[`setInterval`,`setTimeout`,`clearInterval`,`clearTimeout`,`require`,`exports`,`eval`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`escape`,`unescape`],so=[`arguments`,`this`,`super`,`console`,`window`,`document`,`localStorage`,`sessionStorage`,`module`,`self`,`global`],co=[].concat(oo,io,ao);function lo(e){let t=e.regex,n=(e,{after:t})=>{let n=`</`+e[0].slice(1);return e.input.indexOf(n,t)!==-1},r=to,i={begin:`<>`,end:`</>`},a=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{let r=e[0].length+e.index,i=e.input[r];if(i===`<`||i===`,`){t.ignoreMatch();return}i===`>`&&(n(e,{after:r})||t.ignoreMatch());let a,o=e.input.substring(r);if(a=o.match(/^\s*=/)){t.ignoreMatch();return}if((a=o.match(/^\s+extends\s+/))&&a.index===0){t.ignoreMatch();return}}},s={$pattern:to,keyword:no,literal:ro,built_in:co,"variable.language":so},c=`[0-9](_?[0-9])*`,l=`\\.(${c})`,u=`0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`,d={className:`number`,variants:[{begin:`(\\b(${u})((${l})|\\.)?|(${l}))[eE][+-]?(${c})\\b`},{begin:`\\b(${u})\\b((${l})\\b|\\.)?|(${l})\\b`},{begin:`\\b(0|[1-9](_?[0-9])*)n\\b`},{begin:`\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b`},{begin:`\\b0[bB][0-1](_?[0-1])*n?\\b`},{begin:`\\b0[oO][0-7](_?[0-7])*n?\\b`},{begin:`\\b0[0-7]+n?\\b`}],relevance:0},f={className:`subst`,begin:`\\$\\{`,end:`\\}`,keywords:s,contains:[]},p={begin:".?html`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`xml`}},m={begin:".?css`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`css`}},h={begin:".?gql`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`graphql`}},g={className:`string`,begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,f]},_={className:`comment`,variants:[e.COMMENT(/\/\*\*(?!\/)/,`\\*/`,{relevance:0,contains:[{begin:`(?=@[A-Za-z]+)`,relevance:0,contains:[{className:`doctag`,begin:`@[A-Za-z]+`},{className:`type`,begin:`\\{`,end:`\\}`,excludeEnd:!0,excludeBegin:!0,relevance:0},{className:`variable`,begin:`[A-Za-z$_][0-9A-Za-z$_]*(?=\\s*(-)|$)`,endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},v=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,{match:/\$\d+/},d];f.contains=v.concat({begin:/\{/,end:/\}/,keywords:s,contains:[`self`].concat(v)});let y=[].concat(_,f.contains),b=y.concat([{begin:/(\s*)\(/,end:/\)/,keywords:s,contains:[`self`].concat(y)}]),x={className:`params`,begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b},S={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,`(`,t.concat(/\./,r),`)*`)],scope:{1:`keyword`,3:`title.class`,5:`keyword`,7:`title.class.inherited`}},{match:[/class/,/\s+/,r],scope:{1:`keyword`,3:`title.class`}}]},C={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:`title.class`,keywords:{_:[...io,...ao]}},w={label:`use_strict`,className:`meta`,relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},T={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:`keyword`,3:`title.function`},label:`func.def`,contains:[x],illegal:/%/},E={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:`variable.constant`};function D(e){return t.concat(`(?!`,e.join(`|`),`)`)}let ee={match:t.concat(/\b/,D([...oo,`super`,`import`,`await`].map(e=>`${e}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:`title.function`,relevance:0},te={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:`prototype`,className:`property`,relevance:0},O={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:`keyword`,3:`title.function`},contains:[{begin:/\(\)/},x]},ne=`(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|`+e.UNDERSCORE_IDENT_RE+`)\\s*=>`,k={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(ne)],keywords:`async`,className:{1:`keyword`,3:`title.function`},contains:[x]};return{name:`JavaScript`,aliases:[`js`,`jsx`,`mjs`,`cjs`],keywords:s,exports:{PARAMS_CONTAINS:b,CLASS_REFERENCE:C},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:`shebang`,binary:`node`,relevance:5}),w,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,_,{match:/\$\d+/},d,C,{scope:`attr`,match:r+t.lookahead(`:`),relevance:0},k,{begin:`(`+e.RE_STARTERS_RE+`|\\b(case|return|throw)\\b)\\s*`,keywords:`return throw case`,relevance:0,contains:[_,e.REGEXP_MODE,{className:`function`,begin:ne,returnBegin:!0,end:`\\s*=>`,contains:[{className:`params`,variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:a},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:`xml`,contains:[{begin:o.begin,end:o.end,skip:!0,contains:[`self`]}]}]},T,{beginKeywords:`while if switch catch for`},{begin:`\\b(?!function)`+e.UNDERSCORE_IDENT_RE+`\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{`,returnBegin:!0,label:`func.def`,contains:[x,e.inherit(e.TITLE_MODE,{begin:r,className:`title.function`})]},{match:/\.\.\./,relevance:0},te,{match:`\\$[A-Za-z$_][0-9A-Za-z$_]*`,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:`title.function`},contains:[x]},ee,E,S,O,{match:/\$[(.]/}]}}const uo={scope:`number`,match:`([-+]?)(\\b0[xX][a-fA-F0-9]+|(\\b\\d+(\\.\\d*)?|\\.\\d+)([eE][-+]?\\d+)?)|NaN|[-+]?Infinity`,relevance:0};function fo(e){let t={className:`attr`,begin:/(("(\\.|[^\\"\r\n])*")|('(\\.|[^\\'\r\n])*'))(?=\s*:)/,relevance:1.01},n={match:/[{}[\],:]/,className:`punctuation`,relevance:0},r=[`true`,`false`,`null`],i={scope:`literal`,beginKeywords:r.join(` `)};return{name:`JSON`,aliases:[`jsonc`,`json5`],keywords:{literal:r},contains:[t,n,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,i,uo,e.C_LINE_COMMENT_MODE,e.C_BLOCK_COMMENT_MODE],illegal:`\\S`}}function po(e){let t=e.regex,n=/[\p{XID_Start}_]\p{XID_Continue}*/u,r=`and.as.assert.async.await.break.case.class.continue.def.del.elif.else.except.finally.for.from.global.if.import.in.is.lambda.lazy.match.nonlocal|10.not.or.pass.raise.return.try.while.with.yield`.split(`.`),i={$pattern:/[A-Za-z]\w+|__\w+__/,keyword:r,built_in:`__import__.abs.aiter.all.anext.any.ascii.bin.bool.breakpoint.bytearray.bytes.callable.chr.classmethod.compile.complex.delattr.dict.dir.divmod.enumerate.eval.exec.filter.float.format.frozendict.frozenset.getattr.globals.hasattr.hash.help.hex.id.input.int.isinstance.issubclass.iter.len.list.locals.map.max.memoryview.min.next.object.oct.open.ord.pow.print.property.range.repr.reversed.round.sentinel.set.setattr.slice.sorted.staticmethod.str.sum.super.tuple.type.vars.zip`.split(`.`),literal:[`__debug__`,`Ellipsis`,`False`,`None`,`NotImplemented`,`True`],type:[`Any`,`Callable`,`Coroutine`,`Dict`,`List`,`Literal`,`Generic`,`Optional`,`Sequence`,`Set`,`Tuple`,`Type`,`Union`]},a={className:`meta`,begin:/^(>>>|\.\.\.) /},o={className:`subst`,begin:/\{/,end:/\}/,keywords:i,illegal:/#/},s={begin:/\{\{/,relevance:0},c={className:`string`,contains:[e.BACKSLASH_ESCAPE],variants:[{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,a],relevance:10},{begin:/([uU]|[bB]|[rR]|[bB][rR]|[rR][bB])?"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,a],relevance:10},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'''/,end:/'''/,contains:[e.BACKSLASH_ESCAPE,a,s,o]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"""/,end:/"""/,contains:[e.BACKSLASH_ESCAPE,a,s,o]},{begin:/([uU]|[rR])'/,end:/'/,relevance:10},{begin:/([uU]|[rR])"/,end:/"/,relevance:10},{begin:/([bB]|[bB][rR]|[rR][bB])'/,end:/'/},{begin:/([bB]|[bB][rR]|[rR][bB])"/,end:/"/},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])'/,end:/'/,contains:[e.BACKSLASH_ESCAPE,s,o]},{begin:/([fFtT][rR]|[rR][fFtT]|[fFtT])"/,end:/"/,contains:[e.BACKSLASH_ESCAPE,s,o]},e.APOS_STRING_MODE,e.QUOTE_STRING_MODE]},l=`[0-9](_?[0-9])*`,u=`(\\b(${l}))?\\.(${l})|\\b(${l})\\.`,d=`\\b|${r.join(`|`)}`,f={className:`number`,relevance:0,variants:[{begin:`(\\b(${l})|(${u}))[eE][+-]?(${l})[jJ]?(?=${d})`},{begin:`(${u})[jJ]?`},{begin:`\\b([1-9](_?[0-9])*|0+(_?0)*)[lLjJ]?(?=${d})`},{begin:`\\b0[bB](_?[01])+[lL]?(?=${d})`},{begin:`\\b0[oO](_?[0-7])+[lL]?(?=${d})`},{begin:`\\b0[xX](_?[0-9a-fA-F])+[lL]?(?=${d})`},{begin:`\\b(${l})[jJ](?=${d})`}]},p={className:`comment`,begin:t.lookahead(/# type:/),end:/$/,keywords:i,contains:[{begin:/# type:/},{begin:/#/,end:/\b\B/,endsWithParent:!0}]},m={className:`params`,variants:[{className:``,begin:/\(\s*\)/,skip:!0},{begin:/\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:i,contains:[`self`,a,f,c,e.HASH_COMMENT_MODE]}]};return o.contains=[c,f,a],{name:`Python`,aliases:[`py`,`gyp`,`ipython`],unicodeRegex:!0,keywords:i,illegal:/(<\/|\?)|=>/,contains:[a,f,{scope:`variable.language`,match:/\bself\b/},{beginKeywords:`if`,relevance:0},{match:/\bor\b/,scope:`keyword`},c,p,e.HASH_COMMENT_MODE,{match:[/\bdef/,/\s+/,n],scope:{1:`keyword`,3:`title.function`},contains:[m]},{variants:[{match:[/\bclass/,/\s+/,n,/\s*/,/\(\s*/,n,/\s*\)/]},{match:[/\bclass/,/\s+/,n]}],scope:{1:`keyword`,3:`title.class`,6:`title.class.inherited`}},{className:`meta`,begin:/^[\t ]*@/,end:/(?=#)|$/,contains:[f,m,c]}]}}function mo(e){let t=e.regex,n=e.COMMENT(`--`,`$`),r={scope:`string`,variants:[{begin:/'/,end:/'/,contains:[{match:/''/}]}]},i={begin:/"/,end:/"/,contains:[{match:/""/}]},a=[`true`,`false`,`unknown`],o=[`double precision`,`large object`,`with timezone`,`without timezone`],s=`bigint.binary.blob.boolean.char.character.clob.date.dec.decfloat.decimal.float.int.integer.interval.nchar.nclob.national.numeric.real.row.smallint.time.timestamp.varchar.varying.varbinary`.split(`.`),c=[`add`,`asc`,`collation`,`desc`,`final`,`first`,`last`,`view`],l=`abs.acos.all.allocate.alter.and.any.are.array.array_agg.array_max_cardinality.as.asensitive.asin.asymmetric.at.atan.atomic.authorization.avg.begin.begin_frame.begin_partition.between.bigint.binary.blob.boolean.both.by.call.called.cardinality.cascaded.case.cast.ceil.ceiling.char.char_length.character.character_length.check.classifier.clob.close.coalesce.collate.collect.column.commit.condition.connect.constraint.contains.convert.copy.corr.corresponding.cos.cosh.count.covar_pop.covar_samp.create.cross.cube.cume_dist.current.current_catalog.current_date.current_default_transform_group.current_path.current_role.current_row.current_schema.current_time.current_timestamp.current_path.current_role.current_transform_group_for_type.current_user.cursor.cycle.date.day.deallocate.dec.decimal.decfloat.declare.default.define.delete.dense_rank.deref.describe.deterministic.disconnect.distinct.double.drop.dynamic.each.element.else.empty.end.end_frame.end_partition.end-exec.equals.escape.every.except.exec.execute.exists.exp.external.extract.false.fetch.filter.first_value.float.floor.for.foreign.frame_row.free.from.full.function.fusion.get.global.grant.group.grouping.groups.having.hold.hour.identity.in.indicator.initial.inner.inout.insensitive.insert.int.integer.intersect.intersection.interval.into.is.join.json_array.json_arrayagg.json_exists.json_object.json_objectagg.json_query.json_table.json_table_primitive.json_value.lag.language.large.last_value.lateral.lead.leading.left.like.like_regex.listagg.ln.local.localtime.localtimestamp.log.log10.lower.match.match_number.match_recognize.matches.max.member.merge.method.min.minute.mod.modifies.module.month.multiset.national.natural.nchar.nclob.new.no.none.normalize.not.nth_value.ntile.null.nullif.numeric.octet_length.occurrences_regex.of.offset.old.omit.on.one.only.open.or.order.out.outer.over.overlaps.overlay.parameter.partition.pattern.per.percent.percent_rank.percentile_cont.percentile_disc.period.portion.position.position_regex.power.precedes.precision.prepare.primary.procedure.ptf.range.rank.reads.real.recursive.ref.references.referencing.regr_avgx.regr_avgy.regr_count.regr_intercept.regr_r2.regr_slope.regr_sxx.regr_sxy.regr_syy.release.result.return.returns.revoke.right.rollback.rollup.row.row_number.rows.running.savepoint.scope.scroll.search.second.seek.select.sensitive.session_user.set.show.similar.sin.sinh.skip.smallint.some.specific.specifictype.sql.sqlexception.sqlstate.sqlwarning.sqrt.start.static.stddev_pop.stddev_samp.submultiset.subset.substring.substring_regex.succeeds.sum.symmetric.system.system_time.system_user.table.tablesample.tan.tanh.then.time.timestamp.timezone_hour.timezone_minute.to.trailing.translate.translate_regex.translation.treat.trigger.trim.trim_array.true.truncate.uescape.union.unique.unknown.unnest.update.upper.user.using.value.values.value_of.var_pop.var_samp.varbinary.varchar.varying.versioning.when.whenever.where.width_bucket.window.with.within.without.year`.split(`.`),u=`abs.acos.array_agg.asin.atan.avg.cast.ceil.ceiling.coalesce.corr.cos.cosh.count.covar_pop.covar_samp.cume_dist.dense_rank.deref.element.exp.extract.first_value.floor.json_array.json_arrayagg.json_exists.json_object.json_objectagg.json_query.json_table.json_table_primitive.json_value.lag.last_value.lead.listagg.ln.log.log10.lower.max.min.mod.nth_value.ntile.nullif.percent_rank.percentile_cont.percentile_disc.position.position_regex.power.rank.regr_avgx.regr_avgy.regr_count.regr_intercept.regr_r2.regr_slope.regr_sxx.regr_sxy.regr_syy.row_number.sin.sinh.sqrt.stddev_pop.stddev_samp.substring.substring_regex.sum.tan.tanh.translate.translate_regex.treat.trim.trim_array.unnest.upper.value_of.var_pop.var_samp.width_bucket`.split(`.`),d=[`current_catalog`,`current_date`,`current_default_transform_group`,`current_path`,`current_role`,`current_schema`,`current_transform_group_for_type`,`current_user`,`session_user`,`system_time`,`system_user`,`current_time`,`localtime`,`current_timestamp`,`localtimestamp`],f=[`create table`,`insert into`,`primary key`,`foreign key`,`not null`,`alter table`,`add constraint`,`grouping sets`,`on overflow`,`character set`,`respect nulls`,`ignore nulls`,`nulls first`,`nulls last`,`depth first`,`breadth first`],p=u,m=[...l,...c].filter(e=>!u.includes(e)),h={scope:`variable`,match:/@[a-z0-9][a-z0-9_]*/},g={scope:`operator`,match:/[-+*/=%^~]|&&?|\|\|?|!=?|<(?:=>?|<|>)?|>[>=]?/,relevance:0},_={match:t.concat(/\b/,t.either(...p),/\s*\(/),relevance:0,keywords:{built_in:p}};function v(e){return t.concat(/\b/,t.either(...e.map(e=>e.replace(/\s+/,`\\s+`))),/\b/)}let y={scope:`keyword`,match:v(f),relevance:0};function b(e,{exceptions:t,when:n}={}){let r=n;return t||=[],e.map(e=>e.match(/\|\d+$/)||t.includes(e)?e:r(e)?`${e}|0`:e)}return{name:`SQL`,case_insensitive:!0,illegal:/[{}]|<\//,keywords:{$pattern:/\b[\w\.]+/,keyword:b(m,{when:e=>e.length<3}),literal:a,type:s,built_in:d},contains:[{scope:`type`,match:v(o)},y,_,h,r,i,e.C_NUMBER_MODE,e.C_BLOCK_COMMENT_MODE,n,g]}}const ho=`[A-Za-z$_][0-9A-Za-z$_]*`,go=`as.in.of.if.for.while.finally.var.new.function.do.return.void.else.break.catch.instanceof.with.throw.case.default.try.switch.continue.typeof.delete.let.yield.const.class.debugger.async.await.static.import.from.export.extends.using`.split(`.`),_o=[`true`,`false`,`null`,`undefined`,`NaN`,`Infinity`],vo=`Object.Function.Boolean.Symbol.Math.Date.Number.BigInt.String.RegExp.Array.Float32Array.Float64Array.Int8Array.Uint8Array.Uint8ClampedArray.Int16Array.Int32Array.Uint16Array.Uint32Array.BigInt64Array.BigUint64Array.Set.Map.WeakSet.WeakMap.ArrayBuffer.SharedArrayBuffer.Atomics.DataView.JSON.Promise.Generator.GeneratorFunction.AsyncFunction.Reflect.Proxy.Intl.WebAssembly`.split(`.`),yo=[`Error`,`EvalError`,`InternalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],bo=[`setInterval`,`setTimeout`,`clearInterval`,`clearTimeout`,`require`,`exports`,`eval`,`isFinite`,`isNaN`,`parseFloat`,`parseInt`,`decodeURI`,`decodeURIComponent`,`encodeURI`,`encodeURIComponent`,`escape`,`unescape`],xo=[`arguments`,`this`,`super`,`console`,`window`,`document`,`localStorage`,`sessionStorage`,`module`,`self`,`global`],So=[].concat(bo,vo,yo);function Co(e){let t=e.regex,n=(e,{after:t})=>{let n=`</`+e[0].slice(1);return e.input.indexOf(n,t)!==-1},r=ho,i={begin:`<>`,end:`</>`},a=/<[A-Za-z0-9\\._:-]+\s*\/>/,o={begin:/<[A-Za-z0-9\\._:-]+/,end:/\/[A-Za-z0-9\\._:-]+>|\/>/,isTrulyOpeningTag:(e,t)=>{let r=e[0].length+e.index,i=e.input[r];if(i===`<`||i===`,`){t.ignoreMatch();return}i===`>`&&(n(e,{after:r})||t.ignoreMatch());let a,o=e.input.substring(r);if(a=o.match(/^\s*=/)){t.ignoreMatch();return}if((a=o.match(/^\s+extends\s+/))&&a.index===0){t.ignoreMatch();return}}},s={$pattern:ho,keyword:go,literal:_o,built_in:So,"variable.language":xo},c=`[0-9](_?[0-9])*`,l=`\\.(${c})`,u=`0|[1-9](_?[0-9])*|0[0-7]*[89][0-9]*`,d={className:`number`,variants:[{begin:`(\\b(${u})((${l})|\\.)?|(${l}))[eE][+-]?(${c})\\b`},{begin:`\\b(${u})\\b((${l})\\b|\\.)?|(${l})\\b`},{begin:`\\b(0|[1-9](_?[0-9])*)n\\b`},{begin:`\\b0[xX][0-9a-fA-F](_?[0-9a-fA-F])*n?\\b`},{begin:`\\b0[bB][0-1](_?[0-1])*n?\\b`},{begin:`\\b0[oO][0-7](_?[0-7])*n?\\b`},{begin:`\\b0[0-7]+n?\\b`}],relevance:0},f={className:`subst`,begin:`\\$\\{`,end:`\\}`,keywords:s,contains:[]},p={begin:".?html`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`xml`}},m={begin:".?css`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`css`}},h={begin:".?gql`",end:``,starts:{end:"`",returnEnd:!1,contains:[e.BACKSLASH_ESCAPE,f],subLanguage:`graphql`}},g={className:`string`,begin:"`",end:"`",contains:[e.BACKSLASH_ESCAPE,f]},_={className:`comment`,variants:[e.COMMENT(/\/\*\*(?!\/)/,`\\*/`,{relevance:0,contains:[{begin:`(?=@[A-Za-z]+)`,relevance:0,contains:[{className:`doctag`,begin:`@[A-Za-z]+`},{className:`type`,begin:`\\{`,end:`\\}`,excludeEnd:!0,excludeBegin:!0,relevance:0},{className:`variable`,begin:`[A-Za-z$_][0-9A-Za-z$_]*(?=\\s*(-)|$)`,endsParent:!0,relevance:0},{begin:/(?=[^\n])\s/,relevance:0}]}]}),e.C_BLOCK_COMMENT_MODE,e.C_LINE_COMMENT_MODE]},v=[e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,{match:/\$\d+/},d];f.contains=v.concat({begin:/\{/,end:/\}/,keywords:s,contains:[`self`].concat(v)});let y=[].concat(_,f.contains),b=y.concat([{begin:/(\s*)\(/,end:/\)/,keywords:s,contains:[`self`].concat(y)}]),x={className:`params`,begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b},S={variants:[{match:[/class/,/\s+/,r,/\s+/,/extends/,/\s+/,t.concat(r,`(`,t.concat(/\./,r),`)*`)],scope:{1:`keyword`,3:`title.class`,5:`keyword`,7:`title.class.inherited`}},{match:[/class/,/\s+/,r],scope:{1:`keyword`,3:`title.class`}}]},C={relevance:0,match:t.either(/\bJSON/,/\b[A-Z][a-z]+([A-Z][a-z]*|\d)*/,/\b[A-Z]{2,}([A-Z][a-z]+|\d)+([A-Z][a-z]*)*/,/\b[A-Z]{2,}[a-z]+([A-Z][a-z]+|\d)*([A-Z][a-z]*)*/),className:`title.class`,keywords:{_:[...vo,...yo]}},w={label:`use_strict`,className:`meta`,relevance:10,begin:/^\s*['"]use (strict|asm)['"]/},T={variants:[{match:[/function/,/\s+/,r,/(?=\s*\()/]},{match:[/function/,/\s*(?=\()/]}],className:{1:`keyword`,3:`title.function`},label:`func.def`,contains:[x],illegal:/%/},E={relevance:0,match:/\b[A-Z][A-Z_0-9]+\b/,className:`variable.constant`};function D(e){return t.concat(`(?!`,e.join(`|`),`)`)}let ee={match:t.concat(/\b/,D([...bo,`super`,`import`,`await`].map(e=>`${e}\\s*\\(`)),r,t.lookahead(/\s*\(/)),className:`title.function`,relevance:0},te={begin:t.concat(/\./,t.lookahead(t.concat(r,/(?![0-9A-Za-z$_(])/))),end:r,excludeBegin:!0,keywords:`prototype`,className:`property`,relevance:0},O={match:[/get|set/,/\s+/,r,/(?=\()/],className:{1:`keyword`,3:`title.function`},contains:[{begin:/\(\)/},x]},ne=`(\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)|`+e.UNDERSCORE_IDENT_RE+`)\\s*=>`,k={match:[/const|var|let/,/\s+/,r,/\s*/,/=\s*/,/(async\s*)?/,t.lookahead(ne)],keywords:`async`,className:{1:`keyword`,3:`title.function`},contains:[x]};return{name:`JavaScript`,aliases:[`js`,`jsx`,`mjs`,`cjs`],keywords:s,exports:{PARAMS_CONTAINS:b,CLASS_REFERENCE:C},illegal:/#(?![$_A-Za-z])/,contains:[e.SHEBANG({label:`shebang`,binary:`node`,relevance:5}),w,e.APOS_STRING_MODE,e.QUOTE_STRING_MODE,p,m,h,g,_,{match:/\$\d+/},d,C,{scope:`attr`,match:r+t.lookahead(`:`),relevance:0},k,{begin:`(`+e.RE_STARTERS_RE+`|\\b(case|return|throw)\\b)\\s*`,keywords:`return throw case`,relevance:0,contains:[_,e.REGEXP_MODE,{className:`function`,begin:ne,returnBegin:!0,end:`\\s*=>`,contains:[{className:`params`,variants:[{begin:e.UNDERSCORE_IDENT_RE,relevance:0},{className:null,begin:/\(\s*\)/,skip:!0},{begin:/(\s*)\(/,end:/\)/,excludeBegin:!0,excludeEnd:!0,keywords:s,contains:b}]}]},{begin:/,/,relevance:0},{match:/\s+/,relevance:0},{variants:[{begin:i.begin,end:i.end},{match:a},{begin:o.begin,"on:begin":o.isTrulyOpeningTag,end:o.end}],subLanguage:`xml`,contains:[{begin:o.begin,end:o.end,skip:!0,contains:[`self`]}]}]},T,{beginKeywords:`while if switch catch for`},{begin:`\\b(?!function)`+e.UNDERSCORE_IDENT_RE+`\\([^()]*(\\([^()]*(\\([^()]*\\)[^()]*)*\\)[^()]*)*\\)\\s*\\{`,returnBegin:!0,label:`func.def`,contains:[x,e.inherit(e.TITLE_MODE,{begin:r,className:`title.function`})]},{match:/\.\.\./,relevance:0},te,{match:`\\$[A-Za-z$_][0-9A-Za-z$_]*`,relevance:0},{match:[/\bconstructor(?=\s*\()/],className:{1:`title.function`},contains:[x]},ee,E,S,O,{match:/\$[(.]/}]}}function wo(e){let t=e.regex,n=Co(e),r=[`any`,`void`,`number`,`boolean`,`string`,`object`,`never`,`symbol`,`bigint`,`unknown`],i={begin:[/namespace/,/\s+/,e.IDENT_RE],beginScope:{1:`keyword`,3:`title.class`}},a={beginKeywords:`interface`,end:/\{/,excludeEnd:!0,keywords:{keyword:`interface extends`,built_in:r},contains:[n.exports.CLASS_REFERENCE]},o={className:`meta`,relevance:10,begin:/^\s*['"]use strict['"]/},s={$pattern:ho,keyword:go.concat([`type`,`interface`,`public`,`private`,`protected`,`implements`,`declare`,`abstract`,`readonly`,`enum`,`override`,`satisfies`]),literal:_o,built_in:So.concat(r),"variable.language":xo},c={className:`meta`,begin:`@[A-Za-z$_][0-9A-Za-z$_]*`},l=(e,t,n)=>{let r=e.contains.findIndex(e=>e.label===t);if(r===-1)throw Error(`can not find mode to replace`);e.contains.splice(r,1,n)};Object.assign(n.keywords,s),n.exports.PARAMS_CONTAINS.push(c);let u=n.contains.find(e=>e.scope===`attr`),d=Object.assign({},u,{match:t.concat(`[A-Za-z$_][0-9A-Za-z$_]*`,t.lookahead(/\s*\?:/))});n.exports.PARAMS_CONTAINS.push([n.exports.CLASS_REFERENCE,u,d]),n.contains=n.contains.concat([c,i,a,d]),l(n,`shebang`,e.SHEBANG()),l(n,`use_strict`,o);let f=n.contains.find(e=>e.label===`func.def`);return f.relevance=0,Object.assign(n,{name:`TypeScript`,aliases:[`ts`,`tsx`,`mts`,`cts`]}),n}function To(e){let t=e.regex,n=t.concat(/[\p{L}_]/u,t.optional(/[\p{L}0-9_.-]*:/u),/[\p{L}0-9_.-]*/u),r=/[\p{L}0-9._:-]+/u,i={className:`symbol`,begin:/&[a-z]+;|&#[0-9]+;|&#x[a-f0-9]+;/},a={begin:/\s/,contains:[{className:`keyword`,begin:/#?[a-z_][a-z1-9_-]+/,illegal:/\n/}]},o=e.inherit(a,{begin:/\(/,end:/\)/}),s=e.inherit(e.APOS_STRING_MODE,{className:`string`}),c=e.inherit(e.QUOTE_STRING_MODE,{className:`string`}),l={endsWithParent:!0,illegal:/</,relevance:0,contains:[{className:`attr`,begin:r,relevance:0},{begin:/=\s*/,relevance:0,contains:[{className:`string`,endsParent:!0,variants:[{begin:/"/,end:/"/,contains:[i]},{begin:/'/,end:/'/,contains:[i]},{begin:/[^\s"'=<>`]+/}]}]}]};return{name:`HTML, XML`,aliases:[`html`,`xhtml`,`rss`,`atom`,`xjb`,`xsd`,`xsl`,`plist`,`wsf`,`svg`],case_insensitive:!0,unicodeRegex:!0,contains:[{className:`meta`,begin:/<![a-z]/,end:/>/,relevance:10,contains:[a,c,s,o,{begin:/\[/,end:/\]/,contains:[{className:`meta`,begin:/<![a-z]/,end:/>/,contains:[a,o,c,s]}]}]},e.COMMENT(/<!--/,/-->/,{relevance:10}),{begin:/<!\[CDATA\[/,end:/\]\]>/,relevance:10},i,{className:`meta`,end:/\?>/,variants:[{begin:/<\?xml/,relevance:10,contains:[c]},{begin:/<\?[a-z][a-z0-9]+/}]},{className:`tag`,begin:/<style(?=\s|>)/,end:/>/,keywords:{name:`style`},contains:[l],starts:{end:/<\/style>/,returnEnd:!0,subLanguage:`css`}},{className:`tag`,begin:/<script(?=\s|>)/,end:/>/,keywords:{name:`script`},contains:[l],starts:{end:/<\/script>/,returnEnd:!0,subLanguage:`javascript`}},{className:`tag`,begin:/<>|<\/>/},{className:`tag`,begin:t.concat(/</,t.lookahead(t.concat(n,t.either(/\/>/,/>/,/\s/)))),end:/\/?>/,contains:[{className:`name`,begin:n,relevance:0,starts:l}]},{className:`tag`,begin:t.concat(/<\//,t.lookahead(t.concat(n,/>/))),contains:[{className:`name`,begin:n,relevance:0},{begin:/>/,relevance:0,endsParent:!0}]}]}}function Eo(e){let t=`true false yes no null`,n={className:`attr`,variants:[{begin:/[\w*@][\w*@ :()\./-]*:(?=[ \t]|$)/},{begin:/"[\w*@][\w*@ :()\./-]*":(?=[ \t]|$)/},{begin:/'[\w*@][\w*@ :()\./-]*':(?=[ \t]|$)/}]},r={className:`template-variable`,variants:[{begin:/\{\{/,end:/\}\}/},{begin:/%\{/,end:/\}/}]},i={className:`string`,relevance:0,begin:/'/,end:/'/,contains:[{match:/''/,scope:`char.escape`,relevance:0}]},a={className:`string`,relevance:0,variants:[{begin:/"/,end:/"/},{begin:/\S+/}],contains:[e.BACKSLASH_ESCAPE,r]},o=e.inherit(a,{variants:[{begin:/'/,end:/'/,contains:[{begin:/''/,relevance:0}]},{begin:/"/,end:/"/},{begin:/[^\s,{}[\]]+/}]}),s={className:`number`,begin:`\\b[0-9]{4}(-[0-9][0-9]){0,2}([Tt \\t][0-9][0-9]?(:[0-9][0-9]){2})?(\\.[0-9]*)?([ \\t])*(Z|[-+][0-9][0-9]?(:[0-9][0-9])?)?\\b`},c={end:`,`,endsWithParent:!0,excludeEnd:!0,keywords:t,relevance:0},l={begin:/\{/,end:/\}/,contains:[c],illegal:`\\n`,relevance:0},u={begin:`\\[`,end:`\\]`,contains:[c],illegal:`\\n`,relevance:0},d=[n,{className:`meta`,begin:`^---\\s*$`,relevance:10},{className:`string`,begin:`[\\|>]([1-9]?[+-])?[ ]*\\n( +)[^ ][^\\n]*\\n(\\2[^\\n]+\\n?)*`},{begin:`<%[%=-]?`,end:`[%-]?%>`,subLanguage:`ruby`,excludeBegin:!0,excludeEnd:!0,relevance:0},{className:`type`,begin:`!\\w+![\\w#;/?:@&=+$,.~*'()[\\]]+`},{className:`type`,begin:`!<[\\w#;/?:@&=+$,.~*'()[\\]]+>`},{className:`type`,begin:`![\\w#;/?:@&=+$,.~*'()[\\]]+`},{className:`type`,begin:`!![\\w#;/?:@&=+$,.~*'()[\\]]+`},{className:`meta`,begin:`&`+e.UNDERSCORE_IDENT_RE+`$`},{className:`meta`,begin:`\\*`+e.UNDERSCORE_IDENT_RE+`$`},{className:`bullet`,begin:`-(?=[ ]|$)`,relevance:0},e.HASH_COMMENT_MODE,{beginKeywords:t,keywords:{literal:t}},s,{className:`number`,begin:e.C_NUMBER_RE+`\\b`,relevance:0},l,u,i,a],f=[...d];return f.pop(),f.push(o),c.contains=f,{name:`YAML`,case_insensitive:!0,aliases:[`yml`],contains:d}}const X=(e,t)=>n=>`\x1b[${e}m${n}\x1b[${t}m`,Z={bold:X(`1`,`22`),dim:X(`2`,`22`),italic:X(`3`,`23`),underline:X(`4`,`24`),strike:X(`9`,`29`),inverse:X(`7`,`27`),red:X(`31`,`39`),green:X(`32`,`39`),yellow:X(`33`,`39`),blue:X(`34`,`39`),magenta:X(`35`,`39`),cyan:X(`36`,`39`),gray:X(`90`,`39`)},Q={you:e=>Z.bold(Z.cyan(e)),other:e=>Z.bold(Z.magenta(e)),border:Z.gray,muted:Z.gray,accent:Z.cyan,ok:Z.green,warn:Z.yellow,error:Z.red},Do={heading:e=>Z.bold(Z.cyan(e)),link:Z.blue,linkUrl:Z.gray,code:Z.yellow,codeBlock:e=>e,codeBlockBorder:Z.gray,quote:Z.italic,quoteBorder:Z.gray,hr:Z.gray,listBullet:Z.cyan,bold:Z.bold,italic:Z.italic,strikethrough:Z.strike,underline:Z.underline},Oo={borderColor:Z.gray,selectList:{selectedPrefix:Z.cyan,selectedText:Z.cyan,description:Z.gray,scrollInfo:Z.gray,noMatch:Z.gray}};function $(e){return e.replace(/\r\n?/g,`
|
|
134
|
+
`).replaceAll(` `,` `).replace(/\x1b\[[0-?]*[ -/]*[@-~]/g,``).replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)?/g,``).replace(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g,``)}function ko(e){return{...e,toolName:$(e.toolName),...e.title!==void 0&&{title:$(e.title)},...e.errorText!==void 0&&{errorText:$(e.errorText)},...e.approval&&{approval:{...e.approval,...e.approval.reason!==void 0&&{reason:$(e.approval.reason)}}}}}function Ao(e,t){let n=new Set([...t.sent.values()].map(e=>e.messageId)),r=new Map;for(let e of t.notices)e.after!==void 0&&r.set(e.after,[...r.get(e.after)??[],e]);let i=[];for(let a of e.messages){i.push(...Mo(a,e.turns,n,t));for(let e of r.get(a.id)??[])i.push(jo(e))}let a=new Map(i.map((e,t)=>[e.key,t])),o=i.filter((e,t)=>a.get(e.key)===t),s=new Set(e.messages.map(e=>e.id));for(let e of t.notices)(e.after===void 0||!s.has(e.after))&&o.push(jo(e));return o}function jo(e){return{kind:`notice`,...e,text:$(e.text)}}function Mo(e,t,n,r){let i=t=>`${e.id}:${t}`;if(e.role!==`assistant`){let t=$(e.parts.flatMap(e=>e.type===`text`?[e.text]:[]).join(`
|
|
135
|
+
`));return[e.role===`system`?{kind:`system`,key:e.id,text:t}:{kind:`user`,key:e.id,text:t,from:n.has(e.id)?{you:!0}:{you:!1,...Io(e.metadata)}},...No(e)]}let a=Fo(e.id,t),o=a?.status===`running`,s=e.parts.length-1;return e.parts.flatMap((e,t)=>{switch(e.type){case`text`:case`reasoning`:return[{kind:e.type,key:i(t),text:$(e.text),streaming:o&&t===s}];case`tool`:return[{kind:`tool`,key:`tool:${e.toolCallId}`,part:ko(e),...a&&{turnId:a.turnId,turn:a.status===`running`?`running`:`awaiting`,yours:r.sent.has(a.startedBy)},...r.outbox.some(t=>t.target===e.toolCallId)&&{sending:!0}}];default:{let n=Po(e);return n?[{kind:`attachment`,key:i(t),label:$(n)}]:[]}}})}function No(e){return e.parts.flatMap((t,n)=>{let r=Po(t);return r?[{kind:`attachment`,key:`${e.id}:${n}`,label:$(r)}]:[]})}function Po(e){switch(e.type){case`file`:return`file ${e.filename??e.mediaType}`;case`source-url`:return`source ${e.title??e.url}`;case`source-document`:return`source ${e.title}`;case`data`:return`data ${e.name}`;default:return}}function Fo(e,t){return t.find(t=>t.status===`running`?t.responseId===e||t.extends===e:t.status===`settled`&&t.messageIds.includes(e))}function Io(e){for(let t of[`sender`,`participant`,`author`,`user`]){let n=e?.[t];if(typeof n==`string`&&n)return{name:$(n)};if(n&&typeof n==`object`&&!Array.isArray(n)){let{name:e,id:t}=n;if(typeof e==`string`&&e)return{name:$(e)};if(typeof t==`string`&&t)return{name:$(t)}}}return{}}function Lo(e,t,n,r){let i=e=>t.sent.has(e.startedBy),a=e.turns.find(e=>e.status===`running`),o=a&&t.runningSince.get(a.turnId);return{connected:e.connected,seen:r,...e.you&&{you:$(e.you.name??e.you.id)},...a&&{running:{turnId:a.turnId,yours:i(a),...t.outbox.some(e=>e.target===a.turnId)&&{cancelling:!0},...o!==void 0&&{seconds:Math.max(0,Math.floor((n-o)/1e3))}}},queued:e.turns.filter(e=>e.status===`queued`).map(e=>({turnId:e.turnId,label:$(t.sent.get(e.startedBy)?.text??``),yours:i(e)})),awaiting:e.turns.filter(e=>e.status===`settled`).length,sending:t.outbox.map(e=>({...e,label:$(e.label)}))}}function Ro(e){let t=Math.floor(e/60),n=e%60;return`${t}:${String(n).padStart(2,`0`)}`}const zo={toolsExpanded:!0,reasoningExpanded:!1,toggled:new Set};function Bo(e){return e.kind===`tool`||e.kind===`reasoning`}function Vo(e,t){let n=e.kind===`tool`?t.toolsExpanded:t.reasoningExpanded;return t.toggled.has(e.key)?!n:n}function Ho(e,t){let n=new Set(e.toggled);return n.delete(t)||n.add(t),{...e,toggled:n}}function Uo(e,t,n){let r=new Set(n.filter(e=>e.kind===t).map(e=>e.key));return{...e,...t===`tool`?{toolsExpanded:!e.toolsExpanded}:{reasoningExpanded:!e.reasoningExpanded},toggled:new Set([...e.toggled].filter(e=>!r.has(e)))}}function Wo(e,t,n){let r=e.filter(Bo).map(e=>e.key),i=t===void 0?-1:r.indexOf(t);return i===-1?n===`up`?r.at(-1):void 0:n===`up`?r[Math.max(0,i-1)]:r[i+1]}function Go(e,t){switch(e.state){case`input-streaming`:return t===`running`?`preparing`:`stopped`;case`input-available`:return e.owner!==void 0&&!e.providerExecuted?t===`awaiting`?`client`:t?`preparing`:`stopped`:t?`running`:`stopped`;case`approval-requested`:return t===`awaiting`?`approval`:t?`preparing`:`stopped`;case`approval-responded`:return e.approval?.approved===!1?`denied`:t?`running`:`stopped`;case`output-available`:return e.preliminary&&t?`running`:`done`;case`output-error`:return`error`;case`output-denied`:return`denied`}}function Ko(e,t){return e.filter(e=>e.kind===`tool`&&!e.sending&&qo(e,t))}function qo(e,t){let n=Go(e.part,e.turn);return n===`approval`||n===`client`&&t!==void 0&&e.part.owner===t}function Jo(e){try{return JSON.parse(e)}catch{return e}}for(let[e,t]of Object.entries({bash:Wa,css:$a,diff:eo,javascript:lo,json:fo,python:po,sql:mo,typescript:wo,xml:To,yaml:Eo}))Ua.registerLanguage(e,t);Ua.registerAliases([`sh`,`shell`,`zsh`,`console`],{languageName:`bash`}),Ua.registerAliases([`html`,`svg`],{languageName:`xml`}),Ua.registerAliases([`jsonc`,`json5`],{languageName:`json`});const Yo={keyword:Z.magenta,built_in:Z.cyan,type:Z.cyan,literal:Z.yellow,number:Z.yellow,string:Z.green,regexp:Z.red,symbol:Z.yellow,comment:e=>Z.italic(Z.gray(e)),doctag:Z.gray,meta:Z.gray,title:Z.blue,"title.function":Z.blue,"title.class":Z.cyan,attr:Z.cyan,attribute:Z.cyan,property:Z.cyan,variable:Z.red,"template-variable":Z.red,params:e=>e,section:e=>Z.bold(Z.blue(e)),name:Z.magenta,tag:Z.gray,bullet:Z.cyan,addition:Z.green,deletion:Z.red,emphasis:Z.italic,strong:Z.bold};function Xo(e,t){let n=t&&Ua.getLanguage(t)?t:void 0;if(!n)return e.split(`
|
|
136
|
+
`);let r=Ua.highlight(e,{language:n,ignoreIllegals:!0}).value;return es(r).split(`
|
|
137
|
+
`)}const Zo=new WeakMap;function Qo(e){if(typeof e!=`object`||!e)return $o(e);let t=Zo.get(e);return t||Zo.set(e,t=$o(e)),t}function $o(e){return Xo($(JSON.stringify(e,null,2)??`undefined`),`json`)}function es(e){let t=[],n=``,r=e=>{n+=e.split(`
|
|
138
|
+
`).map(e=>e&&t.reduceRight((e,t)=>t(e),e)).join(`
|
|
139
|
+
`)},i=e.split(/(<span class="[^"]*">|<\/span>)/);for(let e of i)if(e.startsWith(`<span`)){let n=/class="hljs-([^" ]+)/.exec(e)?.[1]??``,r=Yo[n]??Yo[n.split(`.`)[0]]??(e=>e);t.push(r)}else e===`</span>`?t.pop():e&&r(ts(e));return n}function ts(e){return e.replaceAll(`<`,`<`).replaceAll(`>`,`>`).replaceAll(`"`,`"`).replaceAll(`'`,`'`).replaceAll(`'`,`'`).replaceAll(`&`,`&`)}const ns=[`⠋`,`⠙`,`⠹`,`⠸`,`⠼`,`⠴`,`⠦`,`⠧`,`⠇`,`⠏`];var rs=class extends Nr{#e=new Map;constructor(e){super(),this.context=e}update(e){let t=new Map;for(let n of e){let e=this.#e.get(n.key);e||=is(n,this.context),e.update(n),t.set(n.key,e)}this.#e.clear();for(let[e,n]of t)this.#e.set(e,n);this.children=[...t.values()]}render(e){let t=[];for(let n of this.children){let r=n.render(e);r.length!==0&&t.push(``,...r.map(t=>z(t,e)))}return t}};function is(e,t){switch(e.kind){case`text`:return new as;case`reasoning`:return new os(t);case`tool`:return new cs(t);default:return new ps}}var as=class{#e=new sa(``,0,0,{...Do,highlightCode:Xo});#t=``;update(e){e.kind!==`text`||e.text===this.#t||(this.#t=e.text,this.#e.setText(e.text))}render(e){return this.#t?this.#e.render(e):[]}invalidate(){this.#e.invalidate()}},os=class{#e;constructor(e){this.context=e}update(e){e.kind===`reasoning`&&(this.#e=e)}render(e){let t=this.#e;if(!t)return[];let{ui:n,frame:r}=this.context,i=Vo(t,n),a=`${t.streaming?Q.accent(ns[r%ns.length]):i?`▾`:`▸`} ${t.streaming?`Thinking…`:`Thought`} ${hs(t.text.length)}`;a=n.selected===t.key?Z.inverse(a):Z.dim(a);let o=[z(a,e)];if(i)for(let n of ms(t.text.trim(),e-2))o.push(` ${Z.dim(Z.italic(n))}`);return o}invalidate(){}};const ss={preparing:[`preparing`,Q.muted],running:[`running`,Q.accent],approval:[`? awaiting approval`,Q.warn],client:[`awaiting a client result`,Q.warn],done:[`✓ done`,Q.ok],error:[`✗ error`,Q.error],denied:[`⊘ denied`,Q.error],stopped:[`stopped`,Q.muted]};var cs=class{#e;constructor(e){this.context=e}update(e){e.kind===`tool`&&(this.#e=e)}render(e){let t=this.#e;if(!t)return[];let{part:n}=t,{ui:r,frame:i}=this.context,a=Go(n,t.turn),[o,s]=ls(t,a,this.context.you),c=s(a===`preparing`||a===`running`||t.sending?`${ns[i%ns.length]} ${o}`:o);a===`approval`&&t.yours===!1&&(c=`${Z.dim(`their turn ·`)} ${c}`);let l=r.selected===t.key,u=Z.bold(n.title??n.toolName),d=t.sending?void 0:us(t,a,this.context.you);if(!Vo(t,r)){let t=n.output??n.errorText??n.input,r=t===void 0?``:` ${Z.dim(fs(t))}`,i=`▸ ◆ ${u} ${c}${r}`,a=[z(l?Z.inverse(i):i,e)];return d&&l&&a.push(z(` ${Q.accent(d)}`,e)),a}let f=l?Q.accent:a===`approval`||a===`client`?Q.warn:a===`error`?Q.error:Q.border,p=Math.max(1,e-4),m=[],h=(e,t)=>{m.push(Z.dim(e));for(let e of t)m.push(...On(e,p))};return h(`input`,n.input===void 0?[Z.dim(`…`)]:Qo(n.input)),n.output!==void 0&&h(n.preliminary?`output (partial)`:`output`,Qo(n.output)),n.errorText&&h(`error`,ms(n.errorText,p).map(Q.error)),n.approval?.reason&&h(`reason`,[n.approval.reason]),d&&m.push(l?Q.accent(d):Z.dim(`${d} (select with ↑)`)),ds(`◆ ${u}`,c,m,e,f)}invalidate(){}};function ls(e,t,n){if(e.sending)return[`sending answer`,Q.muted];if(t===`client`){let t=e.part.owner;return t===n?[`awaiting your result`,Q.warn]:[`waiting for ${t}'s client`,Q.muted]}return ss[t]}function us(e,t,n){if(t===`approval`)return`y approve · n deny · r deny with a reason`;if(t===`client`&&e.part.owner===n)return`Enter to answer`}function ds(e,t,n,r,i){let a=Math.max(1,r-4),o=Math.max(1,r-L(e)-L(t)-6),s=t?`${t}${i(` ╮`)}`:i(`─╮`),c=[z(`${i(`╭ `)}${e}${i(` ${`─`.repeat(o)} `)}${s}`,r)];for(let e of n){let t=z(e,a),n=` `.repeat(Math.max(0,a-L(t)));c.push(`${i(`│`)} ${t}${n} ${i(`│`)}`)}return c.push(i(`╰${`─`.repeat(Math.max(0,r-2))}╯`)),c.map(e=>z(e,r))}function fs(e){return typeof e==`string`?e.replace(/\s+/g,` `):JSON.stringify(e)}var ps=class{#e=()=>[];update(e){switch(e.kind){case`user`:{let t=e.from.you?Q.you(`▌`):Q.other(`▌`),n=e.from.you?Q.you(`you`):Q.other(e.from.name??`another participant`);this.#e=r=>[`${t} ${n}`,...ms(e.text,r-2).map(e=>`${t} ${e}`)];return}case`system`:this.#e=t=>ms(`system: ${e.text}`,t).map(e=>Z.dim(e));return;case`attachment`:this.#e=t=>[z(Z.dim(`+ ${e.label}`),t)];return;case`notice`:{let t=e.tone===`error`?Q.error:Q.muted;this.#e=n=>ms(e.text,n).map(e=>t(e));return}}}render(e){return this.#e(e)}invalidate(){}};function ms(e,t){return e.split(`
|
|
140
|
+
`).flatMap(e=>On(e,Math.max(1,t)))}function hs(e){return e<1e3?`${e} chars`:`${(e/1e3).toFixed(1)}k chars`}const gs=e=>e.split(`
|
|
141
|
+
`)[0]??``;var _s=class{constructor(){this.prompts=[]}render(e){let t=this.status;if(!t)return[];let n=[];t.seen&&!t.connected&&n.push(Q.warn(`⚠ Reconnecting… sends wait and go out on reconnect`));for(let e of this.prompts)n.push(Q.warn(`◆ ${e} needs you ${Z.dim(`(↑ to select it)`)}`));for(let e of t.queued){let t=e.yours?`"${gs(e.label)}"`:Z.italic(`from another participant`);n.push(`${Q.muted(`⧗ queued `)} ${t}`)}for(let e of t.sending)n.push(`${Q.muted(`↑ sending`)} "${gs(e.label)}" ${Z.dim(`(not acknowledged)`)}`);return n.length===0?[]:[``,...n.map(t=>z(t,e))]}invalidate(){}},vs=class{constructor(e,t){this.conversation=e,this.context=t}render(e){if(this.hint)return[z(Z.dim(this.hint),e)];let t=this.status;if(!t)return[];let n=[t.connected?Q.ok(`● connected`):t.seen?Q.warn(`◌ reconnecting`):Q.muted(`◌ connecting`)];if(t.running){let{seconds:e,yours:r,cancelling:i}=t.running,a=e===void 0?``:` ${Ro(e)}`,o=ns[this.context.frame%ns.length];n.push(`${Q.accent(o)} running${a} ${Z.dim(r?`(yours)`:`(another participant's)`)}`),n.push(i?Q.warn(`cancelling…`):Z.dim(`Esc cancels`))}return t.awaiting>0&&n.push(Q.warn(`${t.awaiting} awaiting input`)),t.you&&n.push(`you: ${Q.accent(t.you)}`),n.push(Z.dim(this.conversation)),[z(n.join(Z.dim(` · `)),e)]}invalidate(){}},ys=class{constructor(e){this.conversation=e}render(e){return[z(`${Q.accent(`◆ Channels`)} ${Z.dim(this.conversation)}`,e),...On(Z.dim(`Enter send · Shift+Enter new line · ↑ select a block · Ctrl+O tools · Ctrl+T thinking · Esc cancel · Ctrl+C quit`),Math.max(1,e)).map(t=>z(t,e))]}invalidate(){}},bs=class{#e;#t=!1;constructor(e,t,n,r){this.part=t,this.answer=n,this.ignore=r,this.#e=new di(e,Oo),this.#e.onSubmit=e=>{e&&n({ok:!0,output:Jo(e)})}}get focused(){return this.#t}set focused(e){this.#t=e,this.#e.focused=e}handleInput(e){Y(e,`escape`)?this.ignore():Y(e,`ctrl+x`)?this.answer({ok:!1,errorText:this.#e.getText().trim()}):this.#e.handleInput(e)}render(e){let t=Math.max(1,e-4),n=[Z.dim(`input`),...this.part.input===void 0?[]:Qo(this.part.input),``,Z.dim(`output: JSON, or text sent as a string`),...this.#e.render(t),Z.dim(`Enter send · Shift+Enter new line · Ctrl+X send as an error · Esc ignore`)];return ds(`◆ ${Z.bold(this.part.title??this.part.toolName)}`,Q.warn(`your client's result`),n,e,Q.warn)}invalidate(){this.#e.invalidate()}},xs=class{#e=new pi({prompt:`› `});#t=!1;constructor(e,t,n){this.part=e,this.close=n,this.#e.onSubmit=e=>t(e.trim()),this.#e.onEscape=n}get focused(){return this.#t}set focused(e){this.#t=e,this.#e.focused=e}handleInput(e){this.#e.handleInput(e)}render(e){let t=Math.max(1,e-4);return ds(`Deny ${Z.bold(this.part.title??this.part.toolName)}`,``,[Z.dim(`reason`),...this.#e.render(t),Z.dim(`Enter deny · Esc back`)],e,Q.error)}invalidate(){this.#e.invalidate()}};function Ss(e){if(Object.keys(e).length===0)return;let t=globalThis.WebSocket;class n extends t{constructor(t,n){super(t,{headers:e,...n!==void 0&&{protocols:n}})}}globalThis.WebSocket=n}const Cs={anchor:`bottom-center`,width:`100%`,maxHeight:`80%`};function ws(e){Ss(e.headers);let t=new Va(e.url),n=new za(new Ma),r={frame:0,ui:zo},i={sent:new Map,outbox:[],runningSince:new Map,notices:[]},a=!1,o=!1,s=[],c,l=new Set,u=new rs(r),d=new _s,f=new di(n,Oo,{paddingX:1}),p=Es(e.url),m=new vs(p,r),h=new ys(p),g;n.addChild(h),n.addChild(u),n.addChild(d),n.addChild(f),n.addChild(m),n.setFocus(f);let _=(e,n,r)=>{let a=r??t.state.messages.at(-1)?.id;i.notices.push({key:`notice:${i.notices.length}`,text:e,tone:n,...a!==void 0&&{after:a}})},v=(e,n,r)=>{let a=e.eventId??crypto.randomUUID();i.outbox.push({eventId:a,label:n,...r&&{target:r}});let s=()=>{i.outbox=i.outbox.filter(e=>e.eventId!==a),w()};t.send({...e,eventId:a}).then(s,e=>{o||(_(`✗ ${n} refused: ${Ds(e)}`,`error`),s())}),w()},y=()=>{c?.handle.hide(),c=void 0},b=()=>{y(),w()},x=e=>{let{part:t,turnId:r}=e;if(r===void 0)return;let i=new bs(n,t,e=>{y(),v({type:`tool-result`,turnId:r,toolCallId:t.toolCallId,result:e},`${e.ok?`result`:`error`} for ${t.toolName}`,t.toolCallId)},b);c={handle:n.showOverlay(i,Cs),key:e.key,name:t.toolName}},S=(e,t,n)=>{let{part:i,turnId:a}=e;a===void 0||!i.approval||(r.ui={...r.ui,selected:void 0},v({type:`approval-response`,turnId:a,approvalId:i.approval.id,approved:t,...n&&{reason:n}},`${t?`approve`:`deny`} ${i.toolName}`,i.toolCallId))},C=e=>{let t=new xs(e.part,t=>{y(),S(e,!1,t)},b);c={handle:n.showOverlay(t,Cs),key:e.key,name:e.part.toolName}},w=()=>{let e=t.state,o=i,p=e.you?.id;r.you=p,s=Ao(e,o);let{ui:h}=r;if(h.selected&&!s.some(e=>e.key===h.selected)&&(r.ui={...h,selected:void 0}),c){let e=s.find(e=>e.key===c?.key);(e?.kind!==`tool`||!e.sending&&!qo(e,p))&&(_(`${c.name} was answered elsewhere`,`info`),y())}let g=Ko(s,p),v=g.filter(e=>!l.has(e.key));for(let e of v)l.add(e.key);let b=v.at(-1);b&&!c&&!r.ui.selected&&f.getText()===``&&(Go(b.part,b.turn)===`client`?x(b):r.ui={...r.ui,selected:b.key}),u.update(s);let S=Lo(e,o,Date.now(),a);d.status=S,d.prompts=g.filter(e=>e.key!==r.ui.selected).map(e=>e.part.toolName),m.status=S,m.hint=Ts(s,r),n.requestRender()},T=e=>{let{ui:n}=r,i=s.find(e=>e.key===n.selected);if(Y(e,`ctrl+o`)||Y(e,`ctrl+t`))r.ui=Uo(n,Y(e,`ctrl+o`)?`tool`:`reasoning`,s);else if(i){let t=i.kind===`tool`&&!i.sending?Go(i.part,i.turn):void 0;if(i.kind===`tool`&&t===`approval`){let t=Y(e,`y`)?()=>S(i,!0):Y(e,`n`)?()=>S(i,!1):Y(e,`r`)?()=>C(i):void 0;if(t)return t(),!0}if(i.kind===`tool`&&t===`client`&&qo(i,r.you)&&Y(e,`enter`))x(i);else if(Y(e,`up`)||Y(e,`down`)){let t=Y(e,`up`)?`up`:`down`;r.ui={...n,selected:Wo(s,n.selected,t)}}else if(Y(e,`enter`)||Y(e,`space`))r.ui=Ho(n,i.key);else if(Y(e,`escape`))r.ui={...n,selected:void 0};else return r.ui={...n,selected:void 0},w(),!1}else if(Y(e,`up`)&&f.getText()===``){let e=Wo(s,void 0,`up`);if(e===void 0)return!1;r.ui={...n,selected:e}}else if(Y(e,`escape`)){let e=t.state.turns.find(e=>e.status===`running`);if(!e)return!1;v({type:`cancel`,turnId:e.turnId},`cancel`,e.turnId)}else return!1;return w(),!0};t.subscribe(e=>{if(e.connected&&(a=!0),e.conversationId!==g){g!==void 0&&(i.sent.clear(),i.runningSince.clear(),i.notices=[],l.clear(),r.ui={...r.ui,selected:void 0}),g=e.conversationId;let t=g?`${p} · ${g}`:p;h.conversation=t,m.conversation=t}for(let t of e.turns)t.status===`running`&&!i.runningSince.has(t.turnId)&&i.runningSince.set(t.turnId,Date.now());w()}),t.onActivity(e=>{if(e.type===`turn`){let{turn:t}=e;t.status!==`running`&&i.runningSince.delete(t.turnId),t.status===`settled`&&t.outcome===`failed`?(_(`✗ Turn failed${t.error?`: ${t.error}`:``}`,`error`,t.messageIds.at(-1)),w()):t.status===`settled`&&t.outcome===`aborted`&&(_(`⊘ Turn cancelled`,`info`,t.messageIds.at(-1)),w())}else e.type===`end`&&e.state===`interrupted`&&(_(`Response interrupted; waiting for the agent`,`info`),w())});let E=async()=>{try{let e=await t.listConversations(),n=t.state.conversationId;e.length===0&&_(`No conversations yet`,`info`);for(let{id:t,parent:r,busy:i}of e)_(`${t===n?`● `:` `}${t}${r===void 0?``:` ↳ forked from ${r}`}${i?` (busy)`:``}`,`info`)}catch(e){_(`✗ /conversations failed: ${Ds(e)}`,`error`)}w()},D=async e=>{if(!e){_(`Usage: /switch <conversation id>`,`error`),w();return}let n;try{n=(await t.listConversations()).map(({id:e})=>e)}catch(e){_(`✗ /switch failed: ${Ds(e)}`,`error`),w();return}let r=n.includes(e)?[e]:n.filter(t=>t.startsWith(e));if(r.length!==1){_(r.length===0?`No conversation matches ${e}`:`${e} matches ${r.length} conversations`,`error`),w();return}t.follow(r[0])},ee=e=>{let[n,...r]=e.trim().split(/\s+/);if(n===`/conversations`)return E(),!0;if(n===`/switch`)return D(r[0]),!0;let i=n===`/new`?{type:`conversation-create`}:n===`/fork`?{type:`conversation-fork`}:n===`/reset`?{type:`conversation-reset`,...r.length&&{handoff:r.join(` `)}}:void 0;return i?t.state.operations.includes(i.type)?(v(i,n),!0):(_(`${n} is not supported by this agent`,`error`),w(),!0):!1};return f.onSubmit=e=>{if(!e||ee(e))return;let t=crypto.randomUUID(),n=crypto.randomUUID();i.sent.set(t,{messageId:n,text:e}),v({type:`message`,eventId:t,message:{id:n,role:`user`,parts:[{type:`text`,text:e}]}},e)},new Promise(e=>{let a=()=>{o=!0,clearInterval(s),n.stop(),t.close(),e()};n.addInputListener(e=>{if(!qn(e)&&!(Jn(e)&&!Y(e,`up`)&&!Y(e,`down`))){if(Y(e,`ctrl+c`)||Y(e,`ctrl+d`)&&!c&&f.getText()===``)return a(),{consume:!0};if(!c)return T(e)?{consume:!0}:void 0}});let s=setInterval(()=>{r.frame++,(t.state.turns.some(e=>e.status===`running`)||i.outbox.length>0)&&w()},100);n.start(),w()})}function Ts(e,t){let n=e.find(e=>e.key===t.ui.selected);if(!n||!Bo(n))return;let r=`↑↓ move · Space toggle · Esc back to composer`;if(n.kind===`reasoning`)return`reasoning · Enter toggle · ${r}`;let i=n.part.toolName;if(n.sending)return`${i} · ${r}`;let a=Go(n.part,n.turn);return a===`approval`?`${i} · y approve · n deny · r deny with a reason · ${r}`:a===`client`&&qo(n,t.you)?`${i} · Enter answer · ${r}`:`${i} · Enter toggle · ${r}`}function Es(e){let{host:t,pathname:n}=new URL(e);return`${t}${/^(\/channels\/[^/]+)\/[^/]+$/.exec(n)?.[1]??n}`}function Ds(e){return e instanceof Error?e.message:String(e)}async function Os(e){if(e.includes(`--help`)||e.includes(`-h`))return console.log(w),0;let t;try{t=E(e,process.env)}catch(e){if(!(e instanceof T))throw e;return console.error(`${e.message}\n\n${w}`),2}try{let e=await x(t.url,t.headers);t={...t,headers:{...t.headers,...e}}}catch(e){return console.error(e instanceof Error?e.message:String(e)),1}return await ws(t),0}const ks=`Usage: agents <command>
|
|
142
|
+
|
|
143
|
+
Commands:
|
|
144
|
+
tui <url> Chat with an agent's Web Channel from the terminal`,[As,...js]=process.argv.slice(2);As===`tui`&&process.exit(await Os(js)),(As===void 0||As===`--help`||As===`-h`)&&(console.log(ks),process.exit(0)),console.error(`Unknown command "${As}"\n\n${ks}`),process.exit(2);export{};
|