diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 976c562..c4a739c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,9 +11,11 @@ permissions: jobs: test: runs-on: ubuntu-latest + timeout-minutes: 15 strategy: + fail-fast: false matrix: - node-version: [22, 24] + node-version: [22, 24, 26] steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 @@ -22,12 +24,29 @@ jobs: # Installed in a scratch dir, not the repo root: this package.json's own # peerDependencies (client-only @deepseek-ai/* packages included) make # npm's arborist either crash or silently drop the packages we actually - # asked for when they're installed alongside it. + # asked for when they're installed alongside it. Supply the host peers + # explicitly and skip npm's cyclic peer traversal (notably npm on Node 22). - run: | - mkdir /tmp/peer-install && cd /tmp/peer-install - npm init -y >/dev/null - npm install --no-save @deepseek-ai/dsh-llm @deepseek-ai/dsh-subprocess @deepseek-ai/schemastery - cp -r node_modules "$GITHUB_WORKSPACE/node_modules" - - run: node test/unit.mjs - - run: node test/smoke.mjs - - run: node test/smoke-terminal.mjs + mkdir /tmp/peer-install + node --input-type=module <<'NODE' + import { readFileSync, writeFileSync } from 'node:fs'; + const pkg = JSON.parse(readFileSync('package.json', 'utf8')); + writeFileSync('/tmp/peer-install/package.json', JSON.stringify({ private: true, dependencies: { + ...pkg.dependencies, ...pkg.devDependencies, + '@deepseek-ai/cordis': '4.0.2', + '@deepseek-ai/dsh-llm': '0.1.1-rc.2', + '@deepseek-ai/dsh-subprocess': '0.1.1-rc.2', + '@deepseek-ai/dsh-brand': '0.1.1-rc.2', + '@deepseek-ai/dsh-attachment': '0.1.1-rc.2', + '@deepseek-ai/dsh-invariants': '0.1.1-rc.2', + '@deepseek-ai/dsh-timeout': '0.1.1-rc.2', + } })); + NODE + npm install --prefix /tmp/peer-install --legacy-peer-deps --no-audit --no-fund + cp -r /tmp/peer-install/node_modules "$GITHUB_WORKSPACE/node_modules" + - run: npm run build + - run: npm test + - if: matrix.node-version == 24 + run: node node_modules/playwright/cli.js install --with-deps chromium + - if: matrix.node-version == 24 + run: npm run test:browser diff --git a/.gitignore b/.gitignore index 3a7a71b..330efc5 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ node_modules/ *.meta.json .DS_Store .dsh-shell-transcripts/ +.claude/settings.local.json +release-artifacts/ diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..94fb10a --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,35 @@ +# Changelog + +## 0.2.0 — 2026-10-19 (release candidate) + +This release candidate includes the unpublished 0.1.1 installation fixes. +GitHub Release remains a draft until the separate publishing step. + +### Terminal and correctness + +- Fix command timeout/cancellation escalation (including surviving child processes), UTF-8 tail retention, literal prompt placeholders, and ANSI OSC preview stripping. +- Restore the documented `/!` model-context admission check and paired command audit events. Keep `/!` available without the Web service; start terminal mode when that service becomes available. +- Persist natural terminal exits without a browser, drain final output on close, reuse saved records, and retain failed saves for retry. Reject stale history selections and isolate prefix-related session IDs during reads/pruning. +- Ignore outdated history/preview responses and handle WebSocket transport errors without an unhandled host exception. Add host and real-browser regressions for the reviewed cases. + +- Fix invisible panel labels/actions in the DSH light theme by using paired host foreground/background aliases. Restore the on-screen Ctrl+C/D/Z buttons and add light/dark/fallback contrast and legacy history interaction regressions. + +- Replace the line-oriented terminal with xterm.js and FitAddon: direct keystrokes, shell completion/history, IME/paste, full-screen applications, progress overwrite and PTY resize. +- Add structured WebSocket output/input/activity/exit frames while retaining legacy raw clients. Automatic protocol replies do not create empty-session history. +- Handle natural exit, stream generations, disconnect and scope disposal; preserve history references and explicit-only model analysis. +- Build the browser entry with tsdown, embed CSS, reuse host React/DSH services, and include third-party notices. +- Add protocol regressions and browser tests using real bash/PTY, optional vim/htop, and the shipped loader bundle. + +### Installation and compatibility + +- Add `npm run setup:local` to initialize source checkouts used by DSH's `link:` installs. Reuse host peers, refuse conflicting links, and verify runtime imports; support `--skip-install` for dependencies already restored offline. +- Mark browser-provided client peers optional and explicitly include the tested DSH `0.1.1-rc.2` peer range alongside `0.1.0-rc.6`. +- Document local dependency recovery in English and Chinese; include the setup tool and Chinese README in the npm package. +- Run the existing tests before npm publication and test local setup's failure handling and repeatability. + +### Requirements and verification + +- Published runtime requires Node >=22. Source builds require Node 22.18+, 24.11+, or 26+. +- Includes xterm.js 6.0.0 and FitAddon 0.11.0 with their MIT notices; React and DSH browser services remain host-provided. +- Local verification covers macOS, real bash/PTY, Chrome, vim, loader integration and package entrypoints. htop is optional and was unavailable; Windows runtime has not been tested. +- Ubuntu CI validates Node 22, 24 and 26, with the real-browser suite on Node 24. CI results are recorded with the release artifacts. diff --git a/CLAUDE.md b/CLAUDE.md index a3bdb6f..0ad4035 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,17 +11,19 @@ A [DeepSeek Harness (DSH)](https://github.com/deepseek-ai/deepseek-harness) plug **Note**: DSH's input trigger system only supports `/` and `@` as trigger characters (hardcoded in `dsh-client-ui-input-trigger/lib/types/types.d.ts`). We cannot use a bare `!` prefix like Claude Code does, so we use `/!` instead. -Not a git repository (no `.git`) — this is a working checkout, not something to run `git log`/`git diff` against for history. +This is a git repository (origin: `git@github.com:CHplus0/dsh-shell-command.git`, branch `main`, tag `v0.1.0`) — `git log`/`git diff` work as usual. The internal `开发进度.md` progress file was removed before the v0.1.0 release (commit `0e84ce1`) and only survives in git history; its forward-looking notes are preserved in "Known limitations & follow-ups" below. ## Commands ```sh node test/unit.mjs # pure parse/format tests, no dependencies node test/smoke.mjs # full apply() + handler against a mock context -node test/smoke-terminal.mjs # terminal registry + hasInput tracking + history-reference RPC (mock) +node test/smoke-terminal.mjs # terminal registry + history-reference RPC (mock) +node test/terminal-protocol.mjs # structured/legacy WS, resize, lifecycle and empty-session regressions +npm run test:browser # actual xterm bundle + bash PTY + optional vim/htop ``` -There is no build step (`lib/client.js` is hand-authored, no bundler) and no lint script configured in `package.json`. +Run `npm run build` after browser edits. `src/client.js`, `src/terminal-controller.js`, and `src/terminal-view.js` are source; `lib/client.js` is generated by tsdown and committed for link/registry installs. Never edit that generated file by hand. No lint script is configured. `npm run test:browser` tests the generated bundle with Chromium and a real PTY; install Chromium with `npx playwright install chromium` or set `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH`. The smoke tests import the real `@deepseek-ai/*` peer packages. Outside of a DSH profile install, link them once: @@ -58,7 +60,7 @@ Two input trigger sources registered via `inputTriggers.registerSource`: `runCommand` has two backends behind one normalized outcome shape: - `ctx.subprocess` (harness-managed seam, preferred when present): scrubbed environment, tree-scoped `SIGTERM → grace → SIGKILL`, bounded tail-retaining stream collection. -- `node:child_process` fallback (used when the seam is absent): scrubbed env via `scrubbedParentEnv()` from `@deepseek-ai/dsh-subprocess`, in-memory bounded buffers, process-level (not tree-level) kill. +- `node:child_process` fallback (used when the seam is absent): scrubbed env via `scrubbedParentEnv()` from `@deepseek-ai/dsh-subprocess`, in-memory bounded buffers, POSIX process-group `SIGTERM → grace → SIGKILL` (Windows uses `taskkill /T /F`). Pre-cancelled requests never spawn. Timeout vs. cancellation is always classified from the caller-owned `AbortSignal`s (`timeoutSignal.aborted` / `signal.aborted`), never inferred from exit code/signal — keep that ordering if you touch the outcome-normalization tail of `runCommand`. @@ -75,11 +77,12 @@ This design aligns with dsh-btw: the trigger only works in sessions that have al One persistent PTY per session (`sessionId` → `TerminalHandle`), owner-scoped, with a bounded in-memory transcript that backs both the live WebSocket replay and later on-demand history reference: -- `connection.rpc` control channel (`/shell-term-rpc`): `open` / `transcript` / `close` / `historyList` / `historyRead` / `historyInject`. -- `ctx.webServer.registerUpgrade` WebSocket (`/shell-term/ws`) for the live byte stream; connecting replays the current transcript first. -- `close` never sends anything to the model — it is a pure persistence step. A session is only persisted if it actually received input: `TerminalHandle.hasInput` is set in both `attachWs`'s WebSocket message handler and the exported `write()` fallback (the real production input path is the WS handler; `write()` is the test/non-WS route). A PTY prints its shell banner/prompt unprompted, so `transcript` being non-empty does *not* mean the user did anything — `hasInput` is the real signal. A session that never received input leaves zero trace: no persisted file, no `.meta.json` sidecar, no entry in `manager.list()`. +- `connection.rpc` control channel (`/shell-term-rpc`): `open` / `resize` / `transcript` / `close` / `historyList` / `historyRead` / `historyInject`. Resize requires integer dimensions in 2..1000. Optional `streamId` rejects stale requests. Each PTY generation has a distinct stream ID. +- `ctx.webServer.registerUpgrade` WebSocket (`/shell-term/ws`) for the live byte stream; connecting replays the current transcript first. `protocol=2` opts into JSON `{type:"output",data}` and `{type:"exit",exitCode}` server frames, with `{type:"input",data}`, `{type:"binary",data:[bytes]}`, and `{type:"activity"}` client frames. Input frames alone do not mark user activity in v2. Legacy sockets keep raw streams and input tracking. Optional `streamId` rejects stale attachments. +- `close` never sends anything to the model — it is a pure persistence step. A session is only persisted if it actually received input: `TerminalHandle.hasInput` is set by structured WebSocket activity markers, legacy raw user input, or the exported `write()` fallback. Automatic xterm protocol responses are kept separate from user activity. A PTY prints its shell banner/prompt unprompted, so `transcript` being non-empty does *not* mean the user did anything — `hasInput` is the real signal. A session that never received input leaves zero trace: no persisted file, no `.meta.json` sidecar, no entry in `manager.list()`. - When a session did receive input, its transcript persists to `//` (pruned to `terminalTranscriptKeep` files per session), alongside a `.meta.json` sidecar (`{ timestamp, exitCode, truncated }`) that backs the history tab's list view. The filename carries a zero-padded per-manager counter (`--`) so two closes landing in the same millisecond don't collide and silently overwrite each other's transcript+sidecar; `list()`/`prune()` both sort on this filename, so the padding also keeps sort order agreeing with persist order past the 10th same-millisecond collision. `list()` tolerates pre-existing `.log` files with no sidecar (from before history mode shipped) by falling back to file stat + `exitCode: null`. - On the client, `TerminalController.exit()` ends the PTY and, based on `close`'s result, either returns to `closed` (empty session, panel disappears) or enters `ended` (panel stays open, jumps to the `history` tab, and pre-selects the just-persisted entry via `pendingSelectPath` — see `lib/client.js`). Whether to feed that transcript to the model is left entirely to the user, via the history tab's existing "引用并分析" action. +- Natural exit saves on the host before notifying sockets, including while disconnected. `manager.finish()` drains final PTY output, escalates to SIGKILL if necessary, reuses an existing persisted path, and retains the handle on persistence failure so the user can retry. The low-level `manager.close()` remains synchronous and does not persist by itself. Terminal mode binds to a child Cordis lifecycle so late/reloaded `webServer` availability never disables `/!`. - History reference (`lib/client.js`'s 历史 tab, "引用并分析"): `historyInject` takes an array of transcript paths (validated against `manager.list()` for that session — a client can only reference its own session's transcripts, not arbitrary paths) plus free-form notes, and wakes the model synchronously: notes via `agent.inject`, pointer via `agent.followup`. The pointer (`buildHistoryPointerMessage`) stays content-free (paths/timestamps/exit codes, no transcript text) since a rerun between persist time and read time may have produced different output; the model has to actually read the referenced files. This is the *only* path in the plugin that ever sends a terminal transcript into the model's context — closing a `/terminal` session never does, regardless of whether it received input. - **Why `agent.inject` before `agent.followup` produces one wake, not two, and why the pair still lands as two ordinary bubbles**: `agent.followup` opens a brand-new turn and wakes the model — calling it twice would mean two separate model replies, so the user's notes can never themselves go through `followup`. `agent.inject` queues its message for the *next step* without waking anything. `dsh-agent`'s `Inbox.claim()` pulls the next-step queue first, then the next-turn item, and folds them into one `user/message` batch for that turn's first step — so an `inject` call placed immediately before a `followup` call rides in as a distinct message in the same wake, not a second wake. `buildHistoryNotesMessage` (the message constructor that carries the user's own words) uses `source: { kind: "user" }` instead of the plugin-notice shape (see below), so it renders as an ordinary chat bubble — it falls back to a default account (`请帮我对比分析这些历史终端记录。`) when the user left the field empty. @@ -91,18 +94,42 @@ Two message shapes, chosen by what a message *is*, not by which API sent it: Preserve the `source` shape on any new message constructor — it's what the client UI (`dsh-client-ui-conversation`) keys off to choose `UserStyleBubble` vs. `ContextInjectionRow` rendering. -### Client bundle (`lib/client.js`) +### Browser sources and generated bundle -Hand-authored, no build step, loaded via `window.__ModuleLoader__.load`. Registers both input trigger sources described above. The terminal popup is `ReactDOM.createPortal`-rendered to `document.body` (not inline in the `conversation.input.dock` slot — that slot only mounts the component once per session so its lifecycle stays scoped to the session) as a freely movable/resizable floating panel: `position: fixed`, a draggable header, and a corner resize grip, with geometry clamped to the viewport and a minimum size, held in `TerminalController`'s snapshot state. It does its own minimal ANSI/SGR-to-`` color rendering (`renderAnsi`) rather than pulling in a terminal-emulation library — this also strips OSC sequences (e.g. bash's window-title `\x1b]0;...\x07`) before the CSI/SGR tokenizer runs, mirroring `stripAnsi` in `inject.js`, so a shell's title-set escape doesn't render as garbled text ahead of the real prompt. It's currently line-oriented (scrollback + input line), not full VT100/xterm — `vim`/`htop`/progress bars/`resize` are known-unsupported, with an xterm.js migration noted as the follow-up in `开发进度.md`. +`src/client.js` registers both triggers and renders the floating portal panel/history tab. +`src/terminal-controller.js` owns the WebSocket, generation checks, lifecycle and history RPC. +`src/terminal-view.js` owns one xterm/FitAddon instance per PTY epoch. Live/history tab +switches hide the same emulator; do not remount/replay it on each tab switch. -The panel has two tabs: **会话** (live PTY scrollback + input line while a session is open; a read-only final scrollback with no input row once `ended`) and **历史** (past `/terminal` sessions for this session id, read via `historyList`/`historyRead`, multi-select checkboxes + a notes textarea + "引用并分析", calling `historyInject`). Clicking the header's "退出" button ends the PTY (no consent prompt) — a non-empty close lands in `ended` with the history tab pre-selecting the just-closed entry (`pendingSelectPath`, consumed by `HistoryTab`'s `selected` state initializer on mount) and auto-expanding its preview (via a mount-time `useEffect` calling `controller.togglePreview`); the same header slot then reads "关闭面板" to dismiss the panel outright. The history tab's footer also offers a "直接退出,本次不分析" button next to "引用并分析", calling `controller.dismiss()` directly — it's gated to `state.status === "ended" || "error"` (same condition as the header's "关闭面板" label) since `dismiss()` only tears down client-side UI state and never calls the close RPC; surfacing it while a PTY is still `open` would let a user believe they'd skipped a session that's actually still running server-side. The notes textarea includes a small-text hint below it showing the default message used when notes are left blank: "请帮我分别分析这些历史终端记录。" (changed from "对比分析" to "分别分析" per user feedback). History entries never carry embedded transcript content into the model context by default — `historyInject` builds a pointer-only message (paths + timestamps + exit codes + your notes) via `agent.inject` (non-waking), explicitly labeled as historical so the model doesn't mistake it for a just-happened event; a rerun of the same command may produce different output by the time it's read. +`scripts/build-client.mjs` bundles xterm/FitAddon and inlines the upstream CSS into +`lib/client.js`, inside DSH's lazy CommonJS factory. React, ReactDOM and DSH runtime +remain external. Styles are installed/disposed by a plugin effect. Source checkout +setup builds the client; registry installs use the committed artifact. -The input line supports ArrowUp/ArrowDown recall of previously-submitted lines for that terminal window (`TerminalController.submittedLines`, capped at 500 entries, populated by `send()`), entirely client-side — it never touches the PTY. This is deliberate, not a shortcut: input is sent as whole lines on Enter rather than keystroke-by-keystroke, so there's no server-side readline buffer this client is in sync with; forwarding raw arrow-key bytes to the PTY the way Ctrl+C/D/Z bytes are forwarded would recall history into the *PTY's* echo (rendered in scrollback) while the local draft box stayed unchanged, producing a visible desync between what's shown and what Enter would submit. `submittedLines` persists across open/close (unlike `this.transcript`, which is server PTY content and does reset) since it represents the user's own typed history for this terminal window. Tab-completion is not supported for the same reason (it depends on server-side filesystem state a pure client-side recall can't have) and left as a known limitation alongside the VT100/xterm gaps below. +Input is sent verbatim through xterm's onData/onBinary events. Shell readline owns +history/completion. DOM input activity is marked separately from terminal protocol +replies: automatic device replies must never mark an empty session as used. Mouse +focus/scroll alone does not count unless mouse reporting is active. ResizeObserver +fits visible containers and sends validated resize RPC; hidden tabs never resize +the PTY down to zero. On natural exit, close/persist runs without model injection. +Disconnect disables input; dismiss closes the server PTY even in the error state. +Disposal releases sockets, observers, emulator listeners and the server handle. ### Config All config flows through the single `schemastery` `Config` object in `lib/index.js`, applied via the profile's `cordis.patch.yml` (`cordis.patch.yml` in this repo root is the *shipped default* patch documenting every key; profile-level overrides replace a row's entire `config`, so restating the complete config on override is required, not optional). +## Known limitations & follow-ups + +Formerly tracked in the (now-removed) `开发进度.md`; retained here so the forward-looking notes aren't lost: + +- Full xterm interaction, Tab completion, CR progress and resize are implemented. +- Persisted history is a bounded raw transcript, not an emulator snapshot. Full-screen + screen state may not be fully reconstructed after reconnect/refresh if the tail + was truncated. Historical preview remains a log rather than a terminal replay. +- **Config in the Web settings page**: config currently flows only through the profile `cordis.patch.yml`; it hasn't moved into the Web settings UI (limited by the third-party settings whitelist). +- **Peer dependency upgrades**: pins `@deepseek-ai/dsh 0.1.0-rc.x` peer deps; any upgrade needs a regression pass. + ## Non-obvious constraints - Everything runs with the host's own OS privileges — there is no sandbox/approval step by design (same trust model as a user typing directly into their own terminal). Command text is still recorded to the trajectory (`command/run`) for auditability. diff --git a/README.md b/README.md index d86f532..cb6bdaf 100644 --- a/README.md +++ b/README.md @@ -25,6 +25,30 @@ dsh plugin --profile web add "link:/path/to/dsh-shell-command" Restart the web surface once (`dsh web`) so the host-side command loads. It appears in the input `/` menu automatically. +### Local link dependencies + +A `link:` install links the source checkout without installing its dependencies. +Initialize a DSH web profile first, then run this in the checkout: + +```sh +npm run setup:local +npm test +dsh web +``` + +The setup command installs dependencies, builds the browser entry, and links host peers from +`$DSH_HOME/profiles/node_modules` (default: `~/.dsh/profiles/node_modules`). It +checks existing peer paths and refuses to overwrite a different package or broken +link. Use `npm run setup:local -- --skip-install` when dependencies are already +available, including after an offline recovery. + +Browser peers are optional npm peers because DSH supplies the client services; +DSH 0.1.1-rc.2 bundles `ui-slots` in its browser frontend. The client still +requires those services. Setup verifies the plugin, `ws`, and native `node-pty` +imports; also open `/terminal` and execute a command to check the real PTY. +Installing `schemastery` globally or setting `NODE_PATH` does not fix ESM imports +from a checkout with missing dependencies. + ## Quick Start ### Your first `/!` command @@ -106,10 +130,12 @@ You decide later whether to reference it for analysis (see History Tab workflow #### Session Tab Features -- **Line-oriented terminal**: monospace scrollback + input line -- **Control keys**: Ctrl+C/D/Z send raw control bytes to the shell -- **Command history**: ArrowUp/ArrowDown recall previously-submitted lines (client-side, max 500 entries) -- **Limitations**: Tab-completion not supported; full VT100/xterm (vim, htop) planned for future release +- **Full interaction**: xterm.js streams keystrokes to the PTY; supports vim, htop, and ncurses applications +- **Control keys**: Ctrl+C interrupts, Ctrl+D sends EOF, Ctrl+Z suspends through the shell +- **Completion and history**: Tab, arrow history, and line editing use the shell itself +- **Input and display**: IME composition, Unicode paste, ANSI colors, cursor movement, and progress overwrite +- **Resize**: the PTY follows the floating panel dimensions; switching tabs preserves the emulator +- **Exit and disconnect**: natural shell exit persists history; disconnect disables input until the session is closed and reopened #### History Tab Workflow @@ -200,7 +226,7 @@ Model: Comparing the three build runs: Run 2 was 3x faster due to npm cache... - **Choose the right tool**: Use `/!` for single commands where you want immediate feedback; use `/terminal` for exploratory workflows - **Empty sessions don't persist**: If you open `/terminal` but don't type anything, it won't create a history entry (by design) -- **Arrow keys are your friend**: In the terminal input line, ↑/↓ recalls your last 500 commands (client-side, session-scoped) +- **Completion and history**: Use Tab and ↑/↓ directly in the terminal; the shell controls history persistence - **Notes add context**: A good note ("Compare error messages" or "Focus on performance metrics") helps the model analyze more effectively - **Selective analysis**: You don't have to analyze every terminal session — only reference what's relevant to your current question - **History is per-session**: Each DSH conversation has its own terminal history; they don't mix @@ -248,6 +274,26 @@ mkdir -p node_modules/@deepseek-ai ln -s "$HOME/.dsh/profiles/node_modules/@deepseek-ai/"* node_modules/@deepseek-ai/ ``` +### Browser build and interaction tests + +Edit browser sources under `src/`; `lib/client.js` is the committed, shipped build artifact. +Source builds require Node 22.18+, 24.11+, or 26+ for tsdown; the shipped runtime keeps Node >=22 support. +After client edits: + +```sh +npm run build +npm test +npx playwright install chromium +npm run test:browser +``` + +The tsdown build embeds xterm, FitAddon, and CSS in one DSH loader entry; React and +DSH services remain host-provided. Browser tests exercise the generated bundle +against a real bash PTY in a temporary workspace and need Chromium plus local +server permissions. They also exercise vim/htop when installed. +Set `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` to use an existing Chromium installation. +Local setup builds source checkouts; registry installs use the shipped artifact. + ## FAQ **Q: When should I use `/!` vs `/terminal`?** @@ -262,14 +308,14 @@ A: In `/.dsh-shell-transcripts/`, one `.log` file per session plus a **Q: Can I delete history entries manually?** A: Yes, just delete the `.log` and `.meta.json` files from `.dsh-shell-transcripts/`. The History tab reads from disk on each open. -**Q: Why doesn't vim/htop/ncurses work in `/terminal`?** -A: The current terminal is line-oriented (scrollback + input line), not a full VT100/xterm emulator. Full terminal emulation (using xterm.js) is planned for a future release — it requires introducing a build pipeline. +**Q: Can I run vim/htop/ncurses in `/terminal`?** +A: The Session tab now uses xterm.js and supports these applications when installed on the host. **Q: Do the arrow-key command recalls persist across sessions?** -A: The ↑/↓ history is client-side and resets when you close the browser tab or the panel. It's scoped to the current terminal window, not saved to disk. +A: ↑/↓ uses shell history. History files and persistence across sessions follow your shell configuration. **Q: What's the difference between "引用并分析" and just asking about the commands in chat?** -A: "引用并分析" sends the actual command transcripts (output, timestamps, exit codes) to the model as structured data. Asking in chat relies on your description, which may miss details. Use reference-and-analyze when you want the model to see the raw output. +A: "引用并分析" sends your notes plus file references, timestamps and exit codes. The model is instructed to read the selected transcript files for the original output. Asking in chat relies on your description, which may miss details. **Q: Can I reference transcripts from a previous DSH conversation?** A: No. Terminal history is session-scoped. Each DSH conversation has its own `.dsh-shell-transcripts/` namespace, and the History tab only shows entries from the current session ID. @@ -283,18 +329,14 @@ A: `/!` requires an active model conversation. Send at least one message to the ## Limitations - The `/!` output is delivered as a plugin-sourced message (visible in the conversation) -- Terminal mode: line-oriented display only (vim/htop require full xterm emulation, planned for a future release) +- History files retain bounded raw terminal bytes, including cursor and full-screen control sequences; history previews are logs, not screen recordings. +- Page refresh replays the bounded transcript. After truncation, previous cursor/full-screen state may not be completely reconstructable. - API surface targets `@deepseek-ai/dsh` `0.1.0-rc.x`; pin peers and re-verify on DSH upgrades ## Future Roadmap We're planning several enhancements for future releases: -### Full terminal emulation (xterm.js migration) -- **Current**: Line-oriented terminal (scrollback + input line) -- **Goal**: Full VT100/xterm emulation supporting vim, htop, ncurses apps, oh-my-posh, and other rich terminal UIs -- **Requires**: Introducing a build pipeline (webpack/vite) to bundle xterm.js and its addons - ### Internationalization (i18n) - Multi-language UI support (English, Chinese, etc.) - Language detection from user preferences diff --git a/README.zh.md b/README.zh.md index 41e25ed..a4dca2a 100644 --- a/README.zh.md +++ b/README.zh.md @@ -19,12 +19,36 @@ # 从 npm / 仓库安装 dsh plugin --profile web add dsh-shell-command -# 本地源码(开发用 live link,改源码重启即生效) +# 本地源码(开发用 live link,客户端改动需构建后重启) dsh plugin --profile web add "link:/path/to/dsh-shell-command" ``` 安装后重启一次 Web 界面(`dsh web`)让 host 端命令加载;它会自动出现在输入框 `/` 菜单中。 +### 本地 link 安装的依赖恢复 + +`link:` 只链接源码,不会安装源码目录的依赖。若启动时出现 +`Cannot find package '@deepseek-ai/schemastery'`,先初始化 DSH web profile, +然后在本插件目录执行: + +```sh +cd /path/to/dsh-shell-command +npm run setup:local +npm test +dsh web +``` + +初始化命令安装插件自身依赖、构建浏览器入口,再从 `${DSH_HOME:-~/.dsh}/profiles/node_modules` +链接宿主 peer 包。它检查已有链接,不会覆盖不同的 peer 包或断开的链接。 +DSH 0.1.1-rc.2 的 `ui-slots` 已内置在浏览器 bundle 中,无需单独安装; +浏览器 peer 在清单中标记为 optional,仍需宿主提供对应客户端服务。 + +依赖已经安装时(例如离线恢复后),使用 `npm run setup:local -- --skip-install`; +该命令仍会检查插件入口、`ws` 和原生 `node-pty` 能否导入。 +`node-pty` 导入成功后还需要在 Web 界面打开 `/terminal` 并执行命令验证。 +macOS 上的编译失败应先检查安装日志和 Command Line Tools;ESM 导入不通过 +`NODE_PATH` 查找依赖,全局安装 `schemastery` 不能替代本地初始化。 + ## 快速上手 ### 第一次使用 `/!` 命令 @@ -106,10 +130,12 @@ dsh plugin --profile web add "link:/path/to/dsh-shell-command" #### 会话Tab特性 -- **行式终端**:等宽回显 + 输入行 -- **控制键**:Ctrl+C/D/Z 发送原始控制字节到 shell -- **命令历史**:方向键上下浏览已提交过的命令(纯客户端,最多 500 条) -- **限制**:不支持 Tab 补全;完整 VT100/xterm(vim、htop)计划后续版本支持 +- **完整交互**:xterm.js 逐键接入 PTY,支持 vim、htop 和 ncurses 应用 +- **控制键**:Ctrl+C 中断、Ctrl+D 发送 EOF、Ctrl+Z 挂起,由 shell 处理 +- **补全与历史**:Tab 补全、↑/↓ 历史和命令行编辑使用 shell 自身功能 +- **输入与显示**:支持中文输入法、粘贴、ANSI 颜色、光标移动和进度条覆盖 +- **尺寸同步**:调整浮窗大小会同步终端行列数;切换到历史Tab保留现场 +- **退出与断线**:shell 自然退出自动保存历史;断线后停止输入,可关闭会话再重新打开 #### 历史Tab工作流程 @@ -200,7 +226,7 @@ dsh plugin --profile web add "link:/path/to/dsh-shell-command" - **选择合适的工具**:单命令且需要立即反馈用 `/!`;探索性工作流程且稍后决定是否分析用 `/terminal` - **空会话不持久化**:打开 `/terminal` 但没输入任何命令,不会创建历史记录(这是设计如此,避免混乱) -- **方向键是你的朋友**:终端输入行中,↑/↓ 可回顾最近 500 条命令(客户端、会话级别) +- **补全与历史**:在终端中使用 Tab 和 ↑/↓;历史保存策略由当前 shell 配置决定 - **说明增加上下文**:好的说明(「对比错误信息」或「关注性能指标」)帮助模型更有效地分析 - **选择性分析**:不必分析每个终端会话——只引用与当前问题相关的内容 - **历史是每个会话独立的**:每个 DSH 对话有自己的终端历史;它们不会混在一起 @@ -248,6 +274,25 @@ mkdir -p node_modules/@deepseek-ai ln -s "$HOME/.dsh/profiles/node_modules/@deepseek-ai/"* node_modules/@deepseek-ai/ ``` +### 客户端构建与交互验收 + +客户端源码位于 `src/`,`lib/client.js` 是提交并随包分发的生成文件。 +源码构建使用 tsdown,需要 Node 22.18+、24.11+ 或 26+;已发布包的运行环境仍支持 Node >=22。 +修改客户端后执行: + +```sh +npm run build +npm test +npx playwright install chromium +npm run test:browser +``` + +构建使用 tsdown,xterm、FitAddon 与 CSS 都打入同一个 DSH 加载器入口,React 和 +DSH 服务由宿主提供。浏览器测试在临时目录中启动真实 bash PTY,并测试实际生成的 +客户端;需要 Chromium 和本机监听权限。可用时同时验证 vim/htop。 +可用 `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` 指定已安装的 Chromium。 +本地初始化也会构建源码;仅安装已发布包时直接使用随包产物。 + ## 常见问题 FAQ **问:何时该用 `/!` 而非 `/terminal`?** @@ -262,14 +307,14 @@ ln -s "$HOME/.dsh/profiles/node_modules/@deepseek-ai/"* node_modules/@deepseek-a **问:可以手动删除历史记录吗?** 答:可以,直接从 `.dsh-shell-transcripts/` 删除对应的 `.log` 和 `.meta.json` 文件。历史Tab每次打开时从磁盘读取。 -**问:为什么 vim/htop/ncurses 在 `/terminal` 里不能用?** -答:当前终端是行式的(回显 + 输入行),不是完整的 VT100/xterm 模拟器。完整终端模拟(使用 xterm.js)计划后续版本支持——需要引入构建流水线。 +**问:可以运行 vim/htop/ncurses 吗?** +答:可以。会话Tab使用 xterm.js,按键直接发送给 PTY;程序需要安装在宿主机器上。 **问:方向键命令回顾会跨会话持久化吗?** -答:↑/↓ 历史是客户端的,关闭浏览器Tab或面板后会重置。它的作用域是当前终端窗口,不保存到磁盘。 +答:↑/↓ 使用 shell 自身历史。是否写入历史文件、是否跨会话保留,由 shell 的配置决定。 **问:「引用并分析」和直接在对话中问命令有什么区别?** -答:「引用并分析」会把实际的命令转录(输出、时间戳、退出码)作为结构化数据发给模型。在对话中问依赖你的描述,可能会遗漏细节。当你希望模型看到原始输出时,用引用分析。 +答:「引用并分析」会发送你的说明,以及选中转录的文件路径、时间戳和退出码,并要求模型读取这些文件中的原始输出。在对话中问依赖你的描述,可能会遗漏细节。 **问:可以引用之前 DSH 对话的转录吗?** 答:不可以。终端历史是会话级别的。每个 DSH 对话有自己的 `.dsh-shell-transcripts/` 命名空间,历史Tab只显示当前 session ID 的记录。 @@ -283,18 +328,14 @@ ln -s "$HOME/.dsh/profiles/node_modules/@deepseek-ai/"* node_modules/@deepseek-a ## 已知限制 - `/!` 的输出作为 plugin 来源的消息交付(在对话中可见) -- 终端模式:仅行式显示(vim/htop 需要完整 xterm 模拟,后续版本计划支持) +- 历史文件保存有界的原始终端字节,包含光标和全屏控制序列;历史预览用于查看日志,不是屏幕录像。 +- 刷新页面后从有界转录回放;发生截断时,无法保证还原全部先前的光标或全屏状态。 - API 面锁定 `@deepseek-ai/dsh` `0.1.0-rc.x`;升级 DSH 时需锁定 peer 并回归 ## 未来优化方向 我们计划在后续版本中进行以下改进: -### 完整终端模拟(迁移到 xterm.js) -- **当前**:行式终端(回显 + 输入行) -- **目标**:完整 VT100/xterm 模拟,支持 vim、htop、ncurses 应用、oh-my-posh 等丰富终端 UI -- **需要**:引入构建流水线(webpack/vite)以打包 xterm.js 及其插件 - ### 国际化支持(i18n) - 多语言 UI 支持(英文、中文等) - 从用户偏好自动检测语言 diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md new file mode 100644 index 0000000..0ef2be5 --- /dev/null +++ b/THIRD_PARTY_NOTICES.md @@ -0,0 +1,50 @@ +# Bundled third-party software + +The browser bundle includes the following MIT-licensed packages. + +## @xterm/xterm + +Copyright (c) 2017-2019, The xterm.js authors (https://github.com/xtermjs/xterm.js) +Copyright (c) 2014-2016, SourceLair Private Company (https://www.sourcelair.com) +Copyright (c) 2012-2013, Christopher Jeffrey (https://github.com/chjj/) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + + +## @xterm/addon-fit + +Copyright (c) 2019, The xterm.js authors (https://github.com/xtermjs/xterm.js) + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/docs/bugfix-validation.md b/docs/bugfix-validation.md new file mode 100644 index 0000000..1604fbf --- /dev/null +++ b/docs/bugfix-validation.md @@ -0,0 +1,67 @@ +# 功能审查与修复验收 + +日期:2026-10-19(Asia/Taipei)。依据:README.md、README.zh.md、 +CLAUDE.md、docs/xterm-migration-plan.md。范围是当前工作区,包含此前尚未提交的 +xterm 迁移和安装兼容性改动;既有改动继续保留。 + +## 修复内容 + +- 单命令执行:备用执行路径在超时/取消后终止 POSIX 进程组并升级 SIGKILL; + Windows 路径使用 taskkill /T /F。提前取消不启动进程。恢复首次模型请求检查和 + command/run、command/done 审计;自定义提示词的变量按字面量一次替换。 +- 终端关闭:自然退出在服务端保存,断线不影响保存;显式关闭等待最终输出和退出码, + 必要时强制结束。已保存的记录不会重复写入;保存失败返回错误并保留 handle 供重试。 +- 加载与交互:Web 服务缺失不阻塞 /!,服务晚到时启用终端;过期的历史和预览响应 + 不覆盖当前状态;流标识跨宿主重载保持唯一;WebSocket 协议/连接错误不会形成宿主未处理异常。 +- 历史与文本:UTF-8 尾部截断不破坏中文或 emoji,不超过配置字节数;OSC 标题控制符 + 不吞掉中间正文;按完整文件名后缀区分会话,读取和清理不会混淆前缀相同的会话 ID; + 历史引用拒绝部分失效的选择,并去重重复路径。 + +## 需求与证据 + +| 文档需求 | 对应验证 | +|---|---| +| /! 在会话目录执行,输出交模型分析 | smoke.mjs;browser.mjs 通过实际触发器、RPC 和生成客户端验证消息 | +| 首次请求前拒绝 /!,执行后记录生命周期 | smoke.mjs;browser.mjs 验证 command/run、command/done 配对与拒绝路径 | +| 超时、取消、非零退出、spawn 失败与输出上限 | smoke.mjs;regressions.mjs 的真实进程、忽略 TERM 的后代进程、提前取消、UTF-8、失败与 managed seam 合约检查 | +| 子进程环境清洗 | regressions.mjs 验证 DSH_* 不进入实际子进程;两条路径复用宿主清洗/执行能力 | +| 单命令功能不依赖终端服务成功加载 | regressions.mjs 使用真实 Cordis 验证缺失与晚到的 Web 服务、注册和卸载 | +| 一个会话复用一个 PTY,流输入不补换行 | terminal-protocol.mjs;browser.mjs 逐键输入和持久工作目录验证 | +| Tab 补全、方向键历史、中文输入与粘贴 | browser.mjs 使用真实 bash/PTY 与 xterm 的交互验证 | +| Ctrl+C/D/Z、进度覆盖、全屏程序、尺寸同步 | browser.mjs 验证真实信号、CR、独立全屏缓冲区、vim 编辑保存、stty size | +| 切换历史标签保留模拟器现场 | browser.mjs 验证模拟器对象不重建、不重复回放 | +| 空会话与自动协议响应不生成记录 | smoke-terminal.mjs、terminal-protocol.mjs、browser.mjs | +| 关闭和自然退出不触发模型分析 | host 模拟 agent 在关闭时禁止 inject/followup;浏览器验证调用次数不增加 | +| 断线后禁用输入,结束后能干净重开 | browser.mjs:断线、提前关闭、自然退出、重新打开、scope dispose、未返回的 open RPC | +| 断线期间自然退出不丢记录,结束只保存一次 | regressions.mjs;browser.mjs 的真实离线 exit 9 验证记录内容和最终退出码 | +| 最后输出排空,保存失败可重试 | regressions.mjs:延迟 PTY 输出、忽略首次结束信号、被文件阻挡的保存目录及恢复后重试 | +| 历史列表、预览、多选、说明、默认消息、显式引用 | smoke-terminal.mjs 和 browser.mjs;真实生成客户端验证旧版无 sidecar 日志、展开/收起与分析按钮 | +| 历史预览响应乱序时仍服从当前用户操作 | browser.mjs:A/B 响应倒序、收起、切换标签、过期错误、历史列表倒序响应 | +| 会话隔离、限制保留数量、同毫秒文件排序 | regressions.mjs:前缀关联的两个会话、固定时钟下 12 次保存和保留最新 10 条、旧文件名兼容 | +| 畸形输入/连接不能拖垮宿主 | terminal-protocol.mjs 的畸形 JSON/尺寸/数据;browser.mjs 的真实未掩码 WebSocket 帧 | +| 样式、主题和生成加载器可用 | browser.mjs 使用实际 lib/client.js 的两阶段加载器,验证明/暗/缺省主题、控件、CSS 安装与卸载 | +| 本地初始化、分发产物和入口完整 | setup-local.mjs 回归;setup:local --skip-install;npm pack 后解包导入服务端,核对浏览器产物与必需文件,排除转录及 node_modules | + +## 验证边界 + +本次最终执行结果: + +| 检查 | 结果 | +|---|---| +| npm run build | 通过,重新生成 lib/client.js | +| npm run setup:local -- --skip-install | 通过,运行时依赖导入及源码构建成功 | +| npm test | setup、unit、smoke、terminal smoke、protocol、requirements regressions 全部通过 | +| npm run test:browser | 使用本机 Chrome,所有必需交互与新增回归通过 | +| npm pack + 解包入口检查 | 通过;18 个分发文件,服务端可导入,客户端与已验证构建产物一致,无本地转录或 node_modules | +| git diff --check | 通过 | + +实际环境为 macOS、Node v26.8.1、Chrome/Chromium 155.0.8059.82;使用临时目录中的 +真实 bash、PTY、WebSocket 和 vim。DSH 服务接口使用 fixture;模型消息由测试 agent +接收,未向真实模型发请求。htop 未安装,按既有验收规则跳过可选测试。 + +Windows 实际运行、远端 CI 和其他 Node 版本尚未在本次本机运行中执行;Windows +终止分支已实现,但不声称完成该平台实测。既有 CI 保留 Ubuntu / Node 22、24、26。 +历史仍是有界原始日志;截断后不能完整重建旧全屏画面,这是文档中保留的既有限制。 +未来规划中的国际化、导出导入和历史搜索不属于当前已承诺的功能。 + +本次修改保留在工作区。实际 DSH Web 实例需重启并刷新页面才能加载更新后的宿主和客户端。 diff --git a/docs/releasing.md b/docs/releasing.md new file mode 100644 index 0000000..097f8b8 --- /dev/null +++ b/docs/releasing.md @@ -0,0 +1,58 @@ +# Release procedure + +## Candidate preparation + +Keep releases in draft until the separate publishing step is explicitly requested. +For v0.2.0, the candidate includes the xterm migration, installation compatibility +changes and correctness fixes since v0.1.0. The 0.1.1 changes were not separately +published. Local artifacts live in ignored `release-artifacts/v0.2.0/`. + +1. Update package.json and CHANGELOG.md; build the committed browser bundle. +2. Run `npm run build`, `npm test` and `npm run test:browser`. Use + `PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH` if the installed Playwright browser is unavailable. +3. Commit only release sources, tests, docs and generated browser output. Exclude + local Claude settings, dependencies, transcripts and release artifacts. +4. Push the candidate branch and open a draft PR against main. Wait for all + required Node 22/24/26 CI jobs to pass on the exact candidate commit. +5. Run `npm pack --json --pack-destination release-artifacts/v0.2.0/`. + Unpack the archive into a temporary directory, verify its manifest version, + server imports, generated client and third-party notices, and ensure no local + settings, node_modules, transcripts or release artifacts entered the package. +6. Generate release notes, a publishing checklist, provenance (source commit, + package integrity, verification and CI links), and SHA256SUMS. Create or update + only the matching draft GitHub Release, targeting the full candidate SHA. + Upload the archive and those materials, then download and verify their hashes. + +## Separate official publishing step + +The following steps are prepared for a later, explicitly authorized publication; +creating the draft does not run them. + +1. Merge the verified PR. Check out the final main commit with a clean working + tree and ensure package.json still declares the intended release version. +2. Rebuild, rerun the tests, pack the final main commit and regenerate provenance + and checksums. Verify the unpacked package, replace the draft assets and set + its target to that exact final commit before creating/pushing the version tag. +3. Check account access using `npm whoami --registry=https://registry.npmjs.org` + and inspect existing versions with + `npm view dsh-shell-command versions --json --registry=https://registry.npmjs.org`. + Sign in or complete OTP interactively if required; do not store credentials + or OTP values in scripts, release notes, PRs or provenance. +4. From the final artifact directory, verify `shasum -a 256 -c SHA256SUMS`, then + publish the verified archive: + + ```sh + npm publish ./dsh-shell-command-0.2.0.tgz --access public --tag latest --registry=https://registry.npmjs.org + ``` + +5. Verify npm's version, integrity and latest tag against the final archive. + Publish the matching GitHub draft with + `gh release edit v0.2.0 --repo CHplus0/dsh-shell-command --draft=false --latest`. +6. Confirm the public release, assets and a clean installation. If npm publishing + succeeded but the GitHub step failed, retry only the GitHub step; never try to + republish the same npm version. If a version is already occupied by a different + artifact, stop and choose a new version through a separate release decision. + +All npm publication commands explicitly select the official registry. They do +not change the user's global npm mirror configuration. Preserve optional htop +and untested Windows disclosures in the final release notes. diff --git a/docs/xterm-migration-plan.md b/docs/xterm-migration-plan.md new file mode 100644 index 0000000..daa7625 --- /dev/null +++ b/docs/xterm-migration-plan.md @@ -0,0 +1,31 @@ +# xterm terminal migration + +Branch: `feat/xterm-terminal`; starting commit: `741bba4`. +Preserve the existing uncommitted setup, compatibility, and documentation changes. + +## Implementation + +1. Split browser source from the generated `lib/client.js`. Build with tsdown, + bundle xterm/FitAddon and CSS, and retain DSH's lazy CommonJS factory wrapper. +2. Replace the line input with a persistent xterm instance. Stream input/output + without adding newlines, preserve the instance across tab switches, and fit + the PTY to the visible container. +3. Add validated resize RPC and opt-in structured WebSocket messages for output, + user activity, and process exit, keeping legacy raw clients working. +4. Keep empty closes silent, preserve bounded raw transcripts/history references, + and handle natural exit, disconnect, reopen, and disposal. +5. Update installation/build scripts, CI, and English/Chinese documentation. + +## Acceptance + +- Existing setup/unit/smoke tests and new host lifecycle/protocol tests pass. +- Real browser + PTY tests cover keystrokes, shell history/completion, CJK paste + and composition, Ctrl+C/D/Z, progress overwrite, alternate screen/vim, + resize, tab preservation, disconnect, clean reopen, and transcript history. +- Build artifact materializes through the actual DSH loader contract with + host React/DSH externals. Package includes the browser bundle and CSS. +- Automatic terminal replies alone do not create history. Closing does not + wake the model; explicit history references remain the sole terminal wake. + +Defaults: preserve shell selection/startup, one PTY per session, existing +transcript limits and format. No registry publication is part of this task. diff --git a/docs/xterm-validation.md b/docs/xterm-validation.md new file mode 100644 index 0000000..ce159f1 --- /dev/null +++ b/docs/xterm-validation.md @@ -0,0 +1,68 @@ +# /terminal xterm 迁移验收 + +日期:2026-10-18(Asia/Taipei) + +分支:`feat/xterm-terminal` + +起点:`741bba4`;保留开始任务前已有的安装、兼容性和文档改动。 + +## 实现结果 + +- xterm.js 6.0.0 / FitAddon 0.11.0,使用 tsdown 0.23.1 生成 DSH 加载器入口。 +- React、ReactDOM 和 DSH 客户端服务由宿主提供;xterm 与 CSS 内嵌分发。 +- 按键直接进入 PTY,shell 负责编辑、历史和补全;浮窗尺寸同步到 PTY。 +- 历史页签切换保留模拟器;自然退出保存转录,模型分析仍由显式引用触发。 +- 新增 resize RPC 与 opt-in WebSocket v2,保留原始字节流客户端兼容。 +- 自动协议回复不计入用户输入;旧流请求不能操作新流。 + +## 实际执行的检查 + +| 检查 | 结果 | +|---|---| +| `npm run setup:local` | 通过;正式安装项目依赖、恢复宿主 peers 并构建客户端 | +| `npm run setup:local -- --skip-install` | 通过;已有依赖的离线初始化路径可用 | +| `npm run build` | 通过;浏览器产物约 515 kB,gzip 约 130 kB | +| `npm test` | setup、unit、单命令 smoke、terminal smoke、terminal protocol 全部通过 | +| `npm run test:browser` | Chromium 151.0.7922.34 + Node v26.8.1,macOS 原生 PTY,通过 | +| npm package dry-run | 包含客户端、服务端、安装脚本与第三方许可证;排除本地会话和开发环境文件 | +| `git diff --check` | 通过 | + +浏览器测试加载实际生成的 `lib/client.js`,通过注册/实例化两阶段加载器契约运行; +宿主服务使用测试 fixture,终端、WebSocket、RPC、文件保存、bash 和 vim 使用真实实现。 +测试在临时工作目录运行,没有调用真实模型,也没有重启用户正在运行的 DSH 服务。 + +## 交互覆盖 + +- 逐键输入、工作目录和环境状态延续、Tab 文件名补全、shell 方向键历史。 +- 中文/emoji 粘贴,浏览器 DOM composition 事件与输入转发。 +- 等待真实 sleep 子进程启动后验证 Ctrl+C 中断和 Ctrl+Z 挂起;Ctrl+D 自然退出。 +- CR 进度覆盖、全屏缓冲区、历史页签来回切换不重复输出。 +- 调整容器后以真实 `stty size` 验证行列数。 +- vim 实际编辑、保存并退出,读取保存文件核对内容。 +- 空会话及自动设备查询回复不产生历史;使用后保存、多选引用接口保持可用。 +- 断线禁用输入、错误状态关闭后释放 PTY、服务端提前关闭后可正常关闭面板。 +- 干净重开、重复打开、会话销毁、打开 RPC 尚未返回时销毁的竞态清理。 +- 畸形消息、二进制鼠标报告、旧版字节流、尺寸校验、失效流请求与 spawn 失败恢复。 + +## 验证边界与使用 + +- 本机没有安装 htop,该可选测试跳过;vim 和独立全屏测试已通过。 +- 本次实际验证环境为 macOS;CI 已增加 Ubuntu / Node 22、24、26 构建和回归, + Node 24 运行浏览器测试。远端 CI 尚未由本任务触发,Windows 未实测。 +- 历史保持有界原始转录格式。截断后重新连接/刷新不能保证还原完整的先前屏幕状态。 +- 源码构建要求 Node 22.18+、24.11+ 或 26+;已分发产物的运行要求仍为 Node >=22。 +- 本机 web profile 已链接该仓库;重启 `dsh web` 并刷新页面后加载新客户端和服务端。 + +## 浅色主题与上一版小窗交互回归修复 + +用户反馈小窗顶部标签/按钮消失后,在运行中的 DSH 浅色页面确认:宿主使用 +`--dsw-alias-label-primary` / `--dsw-alias-bg-layer-1`,而旧面板读取未定义的 +`--color-text` / `--color-surface`,最终将接近黑色的继承文字显示在深色背景上。 + +- 面板改用宿主的成对前景/背景主题变量,缺省颜色也成对设置;历史预览背景同步适配。 +- 恢复原有 `^C` / `^D` / `^Z` 控制按钮,使用按钮也正确计入用户输入。 +- 浏览器 fixture 改为复现宿主的浅色主题,并检查浅色、深色及无主题变量三种情况下 + 标签和操作按钮的文字对比度至少为 4.5:1。 +- 实测旧版无 `.meta.json` 的日志、展开/收起预览、多选两条记录、附加用户说明并引用。 +- 实测退出后预选/展开刚结束记录、显式分析、直接退出不分析,以及活动终端不能静默丢弃。 +- 新浏览器回归全部通过;既有真实 PTY、vim、连接及生命周期测试继续通过。 diff --git a/lib/client.js b/lib/client.js index 0cb077e..70babed 100644 --- a/lib/client.js +++ b/lib/client.js @@ -1,917 +1,305 @@ -/* dsh-shell-command client bundle — multi-command terminal popup. +window.__ModuleLoader__.load({id:`dsh-shell-command`,factory:e=>{var t={exports:{}},n=t.exports;Object.defineProperty(n,Symbol.toStringTag,{value:`Module`});var r=Object.create,i=Object.defineProperty,a=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.getPrototypeOf,c=Object.prototype.hasOwnProperty,l=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),u=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var s=o(t),l=0,u=s.length,d;lt[e]).bind(null,d),enumerable:!(r=a(t,d))||r.enumerable});return e},d=(e,t,n)=>(n=e==null?{}:r(s(e)),u(t||!e||!e.__esModule||!c.call(e,`default`)?i(n,`default`,{value:e,enumerable:!0}):n,e));let f=e("react");f=d(f,1);let p=e("react-dom");p=d(p,1);let m=e("@deepseek-ai/dsh-client-runtime/client");var h=/* @__PURE__ */ l(((e,t)=>{(function(n,r){if(typeof e==`object`&&typeof t==`object`)t.exports=r();else if(typeof define==`function`&&define.amd)define([],r);else{var i=r();for(var a in i)(typeof e==`object`?e:n)[a]=i[a]}})(globalThis,(()=>(()=>{"use strict";var e={2840:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.AccessibilityManager=void 0;let a=n(7721),o=n(4292),s=n(7150),c=n(7098),l=n(6501),u=n(7093),d=class extends s.Disposable{constructor(e,t,n,r){super(),this._terminal=e,this._coreBrowserService=n,this._renderService=r,this._rowColumns=/* @__PURE__ */ new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce=``;let i=this._coreBrowserService.mainDocument;this._accessibilityContainer=i.createElement(`div`),this._accessibilityContainer.classList.add(`xterm-accessibility`),this._rowContainer=i.createElement(`div`),this._rowContainer.setAttribute(`role`,`list`),this._rowContainer.classList.add(`xterm-accessibility-tree`),this._rowElements=[];for(let e=0;ethis._handleBoundaryFocus(e,0),this._bottomBoundaryFocusListener=e=>this._handleBoundaryFocus(e,1),this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=i.createElement(`div`),this._liveRegion.classList.add(`live-region`),this._liveRegion.setAttribute(`aria-live`,`assertive`),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this._register(new o.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw Error(`Cannot enable accessibility before Terminal.open`);this._terminal.element.insertAdjacentElement(`afterbegin`,this._accessibilityContainer),this._register(this._terminal.onResize((e=>this._handleResize(e.rows)))),this._register(this._terminal.onRender((e=>this._refreshRows(e.start,e.end)))),this._register(this._terminal.onScroll((()=>this._refreshRows()))),this._register(this._terminal.onA11yChar((e=>this._handleChar(e)))),this._register(this._terminal.onLineFeed((()=>this._handleChar(` +`)))),this._register(this._terminal.onA11yTab((e=>this._handleTab(e)))),this._register(this._terminal.onKey((e=>this._handleKey(e.key)))),this._register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this._register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this._register((0,u.addDisposableListener)(i,`selectionchange`,(()=>this._handleSelectionChange()))),this._register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRowsDimensions(),this._refreshRows(),this._register((0,s.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(e){for(let t=0;t0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===` +`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=a.tooMuchOutput.get())))}_clearLiveRegion(){this._liveRegion.textContent=``,this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),/\p{Control}/u.test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let n=this._terminal.buffer,r=n.lines.length.toString();for(let i=e;i<=t;i++){let e=n.lines.get(n.ydisp+i),t=[],a=e?.translateToString(!0,void 0,void 0,t)||``,o=(n.ydisp+i+1).toString(),s=this._rowElements[i];s&&(a.length===0?(s.textContent=`\xA0`,this._rowColumns.set(s,[0,1])):(s.textContent=a,this._rowColumns.set(s,t)),s.setAttribute(`aria-posinset`,o),s.setAttribute(`aria-setsize`,r),this._alignRowWidth(s))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce=``)}_handleBoundaryFocus(e,t){let n=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2];if(n.getAttribute(`aria-posinset`)===(t===0?`1`:`${this._terminal.buffer.lines.length}`)||e.relatedTarget!==r)return;let i,a;if(t===0?(i=n,a=this._rowElements.pop(),this._rowContainer.removeChild(a)):(i=this._rowElements.shift(),a=n,this._rowContainer.removeChild(i)),i.removeEventListener(`focus`,this._topBoundaryFocusListener),a.removeEventListener(`focus`,this._bottomBoundaryFocusListener),t===0){let e=this._createAccessibilityTreeNode();this._rowElements.unshift(e),this._rowContainer.insertAdjacentElement(`afterbegin`,e)}else{let e=this._createAccessibilityTreeNode();this._rowElements.push(e),this._rowContainer.appendChild(e)}this._rowElements[0].addEventListener(`focus`,this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._terminal.scrollLines(t===0?-1:1),this._rowElements[t===0?1:this._rowElements.length-2].focus(),e.preventDefault(),e.stopImmediatePropagation()}_handleSelectionChange(){if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed)return void(this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection());if(!e.anchorNode||!e.focusNode)return void console.error(`anchorNode and/or focusNode are null`);let t={node:e.anchorNode,offset:e.anchorOffset},n={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(n.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===n.node&&t.offset>n.offset)&&([t,n]=[n,t]),t.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(t={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(t.node))return;let r=this._rowElements.slice(-1)[0];if(n.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(n={node:r,offset:r.textContent?.length??0}),!this._rowContainer.contains(n.node))return;let i=({node:e,offset:t})=>{let n=e instanceof Text?e.parentNode:e,r=parseInt(n?.getAttribute(`aria-posinset`),10)-1;if(isNaN(r))return console.warn(`row is invalid. Race condition?`),null;let i=this._rowColumns.get(n);if(!i)return console.warn(`columns is null. Race condition?`),null;let a=t=this._terminal.cols&&(++r,a=0),{row:r,column:a}},a=i(t),o=i(n);if(a&&o){if(a.row>o.row||a.row===o.row&&a.column>=o.column)throw Error(`invalid range`);this._terminal.select(a.column,a.row,(o.row-a.row)*this._terminal.cols-a.column+o.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener(`focus`,this._bottomBoundaryFocusListener);for(let e=this._rowContainer.children.length;ee;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener(`focus`,this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){let e=this._coreBrowserService.mainDocument.createElement(`div`);return e.setAttribute(`role`,`listitem`),e.tabIndex=-1,this._refreshRowDimensions(e),e}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){Object.assign(this._accessibilityContainer.style,{width:`${this._renderService.dimensions.css.canvas.width}px`,fontSize:`${this._terminal.options.fontSize}px`}),this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let e=0;e{function n(e){return e.replace(/\r?\n/g,`\r`)}function r(e,t){return t?`\x1B[200~`+e+`\x1B[201~`:e}function i(e,t,i,a){e=r(e=n(e),i.decPrivateModes.bracketedPasteMode&&!0!==a.rawOptions.ignoreBracketedPasteMode),i.triggerDataEvent(e,!0),t.value=``}function a(e,t,n){let r=n.getBoundingClientRect(),i=e.clientX-r.left-10,a=e.clientY-r.top-10;t.style.width=`20px`,t.style.height=`20px`,t.style.left=`${i}px`,t.style.top=`${a}px`,t.style.zIndex=`1000`,t.focus()}Object.defineProperty(t,"__esModule",{value:!0}),t.prepareTextForTerminal=n,t.bracketTextForPaste=r,t.copyHandler=function(e,t){e.clipboardData&&e.clipboardData.setData(`text/plain`,t.selectionText),e.preventDefault()},t.handlePasteEvent=function(e,t,n,r){e.stopPropagation(),e.clipboardData&&i(e.clipboardData.getData(`text/plain`),t,n,r)},t.paste=i,t.moveTextAreaUnderMouseCursor=a,t.rightClickHandler=function(e,t,n,r,i){a(e,t,n),i&&r.rightClickSelect(e),t.value=r.selectionText,t.select()}},7174:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorContrastCache=void 0;let r=n(7710);t.ColorContrastCache=class{constructor(){this._color=new r.TwoKeyMap,this._css=new r.TwoKeyMap}setCss(e,t,n){this._css.set(e,t,n)}getCss(e,t){return this._css.get(e,t)}setColor(e,t,n){this._color.set(e,t,n)}getColor(e,t){return this._color.get(e,t)}clear(){this._color.clear(),this._css.clear()}}},1718:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreBrowserTerminal=void 0;let r=n(7861),i=n(7721),a=n(3285),o=n(4017),s=n(4196),c=n(9925),l=n(3618),u=n(3955),d=n(4792),f=n(945),p=n(9574),m=n(9820),h=n(9784),g=n(5783),_=n(2079),v=n(7098),y=n(9078),b=n(4103),x=n(5777),S=n(701),C=n(6107),w=n(3534),T=n(706),E=n(8693),D=n(4720),O=n(6501),k=n(2486),A=n(2840),j=n(8906),M=n(802),N=n(7093),P=n(7150);class F extends x.CoreTerminal{get linkifier(){return this._linkifier.value}get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(e={}){super(e),this._linkifier=this._register(new P.MutableDisposable),this.browser=S,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this._register(new P.MutableDisposable),this._onCursorMove=this._register(new M.Emitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this._register(new M.Emitter),this.onKey=this._onKey.event,this._onRender=this._register(new M.Emitter),this.onRender=this._onRender.event,this._onSelectionChange=this._register(new M.Emitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this._register(new M.Emitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this._register(new M.Emitter),this.onBell=this._onBell.event,this._onFocus=this._register(new M.Emitter),this._onBlur=this._register(new M.Emitter),this._onA11yCharEmitter=this._register(new M.Emitter),this._onA11yTabEmitter=this._register(new M.Emitter),this._onWillOpen=this._register(new M.Emitter),this._setup(),this._decorationService=this._instantiationService.createInstance(D.DecorationService),this._instantiationService.setService(O.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(m.LinkProviderService),this._instantiationService.setService(v.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(a.OscLinkProvider)),this._register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this._register(this._inputHandler.onRequestRefreshRows((e=>this.refresh(e?.start??0,e?.end??this.rows-1)))),this._register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this._register(this._inputHandler.onRequestReset((()=>this.reset()))),this._register(this._inputHandler.onRequestWindowsOptionsReport((e=>this._reportWindowsOptions(e)))),this._register(this._inputHandler.onColor((e=>this._handleColorEvent(e)))),this._register(M.Event.forward(this._inputHandler.onCursorMove,this._onCursorMove)),this._register(M.Event.forward(this._inputHandler.onTitleChange,this._onTitleChange)),this._register(M.Event.forward(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this._register(M.Event.forward(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this._register(this._bufferService.onResize((e=>this._afterResize(e.cols,e.rows)))),this._register((0,P.toDisposable)((()=>{this._customKeyEventHandler=void 0,this.element?.parentNode?.removeChild(this.element)})))}_handleColorEvent(e){if(this._themeService)for(let t of e){let e,n=``;switch(t.index){case 256:e=`foreground`,n=`10`;break;case 257:e=`background`,n=`11`;break;case 258:e=`cursor`,n=`12`;break;default:e=`ansi`,n=`4;`+t.index}switch(t.type){case 0:let r=b.color.toColorRGB(e===`ansi`?this._themeService.colors.ansi[t.index]:this._themeService.colors[e]);this.coreService.triggerDataEvent(`${w.C0.ESC}]${n};${(0,E.toRgbString)(r)}${w.C1_ESCAPED.ST}`);break;case 1:if(e===`ansi`)this._themeService.modifyColors((e=>e.ansi[t.index]=b.channels.toColor(...t.color)));else{let n=e;this._themeService.modifyColors((e=>e[n]=b.channels.toColor(...t.color)))}break;case 2:this._themeService.restoreColor(t.index)}}}_setup(){super._setup(),this._customKeyEventHandler=void 0}get buffer(){return this.buffers.active}focus(){this.textarea&&this.textarea.focus({preventScroll:!0})}_handleScreenReaderModeOptionChange(e){e?!this._accessibilityManager.value&&this._renderService&&(this._accessibilityManager.value=this._instantiationService.createInstance(A.AccessibilityManager,this)):this._accessibilityManager.clear()}_handleTextAreaFocus(e){this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(w.C0.ESC+`[I`),this.element.classList.add(`focus`),this._showCursor(),this._onFocus.fire()}blur(){return this.textarea?.blur()}_handleTextAreaBlur(){this.textarea.value=``,this.refresh(this.buffer.y,this.buffer.y),this.coreService.decPrivateModes.sendFocus&&this.coreService.triggerDataEvent(w.C0.ESC+`[O`),this.element.classList.remove(`focus`),this._onBlur.fire()}_syncTextArea(){if(!this.textarea||!this.buffer.isCursorInViewport||this._compositionHelper.isComposing||!this._renderService)return;let e=this.buffer.ybase+this.buffer.y,t=this.buffer.lines.get(e);if(!t)return;let n=Math.min(this.buffer.x,this.cols-1),r=this._renderService.dimensions.css.cell.height,i=t.getWidth(n),a=this._renderService.dimensions.css.cell.width*i,o=this.buffer.y*this._renderService.dimensions.css.cell.height,s=n*this._renderService.dimensions.css.cell.width;this.textarea.style.left=s+`px`,this.textarea.style.top=o+`px`,this.textarea.style.width=a+`px`,this.textarea.style.height=r+`px`,this.textarea.style.lineHeight=r+`px`,this.textarea.style.zIndex=`-5`}_initGlobal(){this._bindKeys(),this._register((0,N.addDisposableListener)(this.element,`copy`,(e=>{this.hasSelection()&&(0,r.copyHandler)(e,this._selectionService)})));let e=e=>(0,r.handlePasteEvent)(e,this.textarea,this.coreService,this.optionsService);this._register((0,N.addDisposableListener)(this.textarea,`paste`,e)),this._register((0,N.addDisposableListener)(this.element,`paste`,e)),S.isFirefox?this._register((0,N.addDisposableListener)(this.element,`mousedown`,(e=>{e.button===2&&(0,r.rightClickHandler)(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))):this._register((0,N.addDisposableListener)(this.element,`contextmenu`,(e=>{(0,r.rightClickHandler)(e,this.textarea,this.screenElement,this._selectionService,this.options.rightClickSelectsWord)}))),S.isLinux&&this._register((0,N.addDisposableListener)(this.element,`auxclick`,(e=>{e.button===1&&(0,r.moveTextAreaUnderMouseCursor)(e,this.textarea,this.screenElement)})))}_bindKeys(){this._register((0,N.addDisposableListener)(this.textarea,`keyup`,(e=>this._keyUp(e)),!0)),this._register((0,N.addDisposableListener)(this.textarea,`keydown`,(e=>this._keyDown(e)),!0)),this._register((0,N.addDisposableListener)(this.textarea,`keypress`,(e=>this._keyPress(e)),!0)),this._register((0,N.addDisposableListener)(this.textarea,`compositionstart`,(()=>this._compositionHelper.compositionstart()))),this._register((0,N.addDisposableListener)(this.textarea,`compositionupdate`,(e=>this._compositionHelper.compositionupdate(e)))),this._register((0,N.addDisposableListener)(this.textarea,`compositionend`,(()=>this._compositionHelper.compositionend()))),this._register((0,N.addDisposableListener)(this.textarea,`input`,(e=>this._inputEvent(e)),!0)),this._register(this.onRender((()=>this._compositionHelper.updateCompositionElements())))}open(e){if(!e)throw Error(`Terminal requires a parent element.`);if(e.isConnected||this._logService.debug(`Terminal.open was called on an element that was not attached to the DOM`),this.element?.ownerDocument.defaultView&&this._coreBrowserService)return void(this.element.ownerDocument.defaultView!==this._coreBrowserService.window&&(this._coreBrowserService.window=this.element.ownerDocument.defaultView));this._document=e.ownerDocument,this.options.documentOverride&&this.options.documentOverride instanceof Document&&(this._document=this.optionsService.rawOptions.documentOverride),this.element=this._document.createElement(`div`),this.element.dir=`ltr`,this.element.classList.add(`terminal`),this.element.classList.add(`xterm`),e.appendChild(this.element);let t=this._document.createDocumentFragment();this._viewportElement=this._document.createElement(`div`),this._viewportElement.classList.add(`xterm-viewport`),t.appendChild(this._viewportElement),this.screenElement=this._document.createElement(`div`),this.screenElement.classList.add(`xterm-screen`),this._register((0,N.addDisposableListener)(this.screenElement,`mousemove`,(e=>this.updateCursorStyle(e)))),this._helperContainer=this._document.createElement(`div`),this._helperContainer.classList.add(`xterm-helpers`),this.screenElement.appendChild(this._helperContainer),t.appendChild(this.screenElement);let n=this.textarea=this._document.createElement(`textarea`);this.textarea.classList.add(`xterm-helper-textarea`),this.textarea.setAttribute(`aria-label`,i.promptLabel.get()),S.isChromeOS||this.textarea.setAttribute(`aria-multiline`,`false`),this.textarea.setAttribute(`autocorrect`,`off`),this.textarea.setAttribute(`autocapitalize`,`off`),this.textarea.setAttribute(`spellcheck`,`false`),this.textarea.tabIndex=0,this._register(this.optionsService.onSpecificOptionChange(`disableStdin`,(()=>n.readOnly=this.optionsService.rawOptions.disableStdin))),this.textarea.readOnly=this.optionsService.rawOptions.disableStdin,this._coreBrowserService=this._register(this._instantiationService.createInstance(p.CoreBrowserService,this.textarea,e.ownerDocument.defaultView??window,this._document??typeof window<`u`?window.document:null)),this._instantiationService.setService(v.ICoreBrowserService,this._coreBrowserService),this._register((0,N.addDisposableListener)(this.textarea,`focus`,(e=>this._handleTextAreaFocus(e)))),this._register((0,N.addDisposableListener)(this.textarea,`blur`,(()=>this._handleTextAreaBlur()))),this._helperContainer.appendChild(this.textarea),this._charSizeService=this._instantiationService.createInstance(d.CharSizeService,this._document,this._helperContainer),this._instantiationService.setService(v.ICharSizeService,this._charSizeService),this._themeService=this._instantiationService.createInstance(y.ThemeService),this._instantiationService.setService(v.IThemeService,this._themeService),this._characterJoinerService=this._instantiationService.createInstance(f.CharacterJoinerService),this._instantiationService.setService(v.ICharacterJoinerService,this._characterJoinerService),this._renderService=this._register(this._instantiationService.createInstance(g.RenderService,this.rows,this.screenElement)),this._instantiationService.setService(v.IRenderService,this._renderService),this._register(this._renderService.onRenderedViewportChange((e=>this._onRender.fire(e)))),this.onResize((e=>this._renderService.resize(e.cols,e.rows))),this._compositionView=this._document.createElement(`div`),this._compositionView.classList.add(`composition-view`),this._compositionHelper=this._instantiationService.createInstance(l.CompositionHelper,this.textarea,this._compositionView),this._helperContainer.appendChild(this._compositionView),this._mouseService=this._instantiationService.createInstance(h.MouseService),this._instantiationService.setService(v.IMouseService,this._mouseService);let r=this._linkifier.value=this._register(this._instantiationService.createInstance(j.Linkifier,this.screenElement));this.element.appendChild(t);try{this._onWillOpen.fire(this.element)}catch{}this._renderService.hasRenderer()||this._renderService.setRenderer(this._createRenderer()),this._register(this.onCursorMove((()=>{this._renderService.handleCursorMove(),this._syncTextArea()}))),this._register(this.onResize((()=>this._renderService.handleResize(this.cols,this.rows)))),this._register(this.onBlur((()=>this._renderService.handleBlur()))),this._register(this.onFocus((()=>this._renderService.handleFocus()))),this._viewport=this._register(this._instantiationService.createInstance(o.Viewport,this.element,this.screenElement)),this._register(this._viewport.onRequestScrollLines((e=>{super.scrollLines(e,!1),this.refresh(0,this.rows-1)}))),this._selectionService=this._register(this._instantiationService.createInstance(_.SelectionService,this.element,this.screenElement,r)),this._instantiationService.setService(v.ISelectionService,this._selectionService),this._register(this._selectionService.onRequestScrollLines((e=>this.scrollLines(e.amount,e.suppressScrollEvent)))),this._register(this._selectionService.onSelectionChange((()=>this._onSelectionChange.fire()))),this._register(this._selectionService.onRequestRedraw((e=>this._renderService.handleSelectionChanged(e.start,e.end,e.columnSelectMode)))),this._register(this._selectionService.onLinuxMouseSelection((e=>{this.textarea.value=e,this.textarea.focus(),this.textarea.select()}))),this._register(M.Event.any(this._onScroll.event,this._inputHandler.onScroll)((()=>{this._selectionService.refresh(),this._viewport?.queueSync()}))),this._register(this._instantiationService.createInstance(s.BufferDecorationRenderer,this.screenElement)),this._register((0,N.addDisposableListener)(this.element,`mousedown`,(e=>this._selectionService.handleMouseDown(e)))),this.coreMouseService.areMouseEventsActive?(this._selectionService.disable(),this.element.classList.add(`enable-mouse-events`)):this._selectionService.enable(),this.options.screenReaderMode&&(this._accessibilityManager.value=this._instantiationService.createInstance(A.AccessibilityManager,this)),this._register(this.optionsService.onSpecificOptionChange(`screenReaderMode`,(e=>this._handleScreenReaderModeOptionChange(e)))),this.options.overviewRuler.width&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(c.OverviewRulerRenderer,this._viewportElement,this.screenElement))),this.optionsService.onSpecificOptionChange(`overviewRuler`,(e=>{!this._overviewRulerRenderer&&e&&this._viewportElement&&this.screenElement&&(this._overviewRulerRenderer=this._register(this._instantiationService.createInstance(c.OverviewRulerRenderer,this._viewportElement,this.screenElement)))})),this._charSizeService.measure(),this.refresh(0,this.rows-1),this._initGlobal(),this.bindMouse()}_createRenderer(){return this._instantiationService.createInstance(u.DomRenderer,this,this._document,this.element,this.screenElement,this._viewportElement,this._helperContainer,this.linkifier)}bindMouse(){let e=this,t=this.element;function n(t){let n=e._mouseService.getMouseReportCoords(t,e.screenElement);if(!n)return!1;let r,i;switch(t.overrideType||t.type){case`mousemove`:i=32,t.buttons===void 0?(r=3,t.button!==void 0&&(r=t.button<3?t.button:3)):r=1&t.buttons?0:4&t.buttons?1:2&t.buttons?2:3;break;case`mouseup`:i=0,r=t.button<3?t.button:3;break;case`mousedown`:i=1,r=t.button<3?t.button:3;break;case`wheel`:if(e._customWheelEventHandler&&!1===e._customWheelEventHandler(t))return!1;let n=t.deltaY;if(n===0||e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return!1;i=n<0?0:1,r=4;break;default:return!1}return!(i===void 0||r===void 0||r>4)&&e.coreMouseService.triggerMouseEvent({col:n.col,row:n.row,x:n.x,y:n.y,button:r,action:i,ctrl:t.ctrlKey,alt:t.altKey,shift:t.shiftKey})}let r={mouseup:null,wheel:null,mousedrag:null,mousemove:null},i={mouseup:e=>(n(e),e.buttons||(this._document.removeEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.removeEventListener(`mousemove`,r.mousedrag)),this.cancel(e)),wheel:e=>(n(e),this.cancel(e,!0)),mousedrag:e=>{e.buttons&&n(e)},mousemove:e=>{e.buttons||n(e)}};this._register(this.coreMouseService.onProtocolChange((e=>{e?(this.optionsService.rawOptions.logLevel===`debug`&&this._logService.debug(`Binding to mouse events:`,this.coreMouseService.explainEvents(e)),this.element.classList.add(`enable-mouse-events`),this._selectionService.disable()):(this._logService.debug(`Unbinding from mouse events.`),this.element.classList.remove(`enable-mouse-events`),this._selectionService.enable()),8&e?r.mousemove||=(t.addEventListener(`mousemove`,i.mousemove),i.mousemove):(t.removeEventListener(`mousemove`,r.mousemove),r.mousemove=null),16&e?r.wheel||=(t.addEventListener(`wheel`,i.wheel,{passive:!1}),i.wheel):(t.removeEventListener(`wheel`,r.wheel),r.wheel=null),2&e?r.mouseup||=i.mouseup:(this._document.removeEventListener(`mouseup`,r.mouseup),r.mouseup=null),4&e?r.mousedrag||=i.mousedrag:(this._document.removeEventListener(`mousemove`,r.mousedrag),r.mousedrag=null)}))),this.coreMouseService.activeProtocol=this.coreMouseService.activeProtocol,this._register((0,N.addDisposableListener)(t,`mousedown`,(e=>{if(e.preventDefault(),this.focus(),this.coreMouseService.areMouseEventsActive&&!this._selectionService.shouldForceSelection(e))return n(e),r.mouseup&&this._document.addEventListener(`mouseup`,r.mouseup),r.mousedrag&&this._document.addEventListener(`mousemove`,r.mousedrag),this.cancel(e)}))),this._register((0,N.addDisposableListener)(t,`wheel`,(t=>{if(!r.wheel){if(this._customWheelEventHandler&&!1===this._customWheelEventHandler(t))return!1;if(!this.buffer.hasScrollback){if(t.deltaY===0)return!1;if(e.coreMouseService.consumeWheelEvent(t,e._renderService?.dimensions?.device?.cell?.height,e._coreBrowserService?.dpr)===0)return this.cancel(t,!0);let n=w.C0.ESC+(this.coreService.decPrivateModes.applicationCursorKeys?`O`:`[`)+(t.deltaY<0?`A`:`B`);return this.coreService.triggerDataEvent(n,!0),this.cancel(t,!0)}}}),{passive:!1}))}refresh(e,t){this._renderService?.refreshRows(e,t)}updateCursorStyle(e){this._selectionService?.shouldColumnSelect(e)?this.element.classList.add(`column-select`):this.element.classList.remove(`column-select`)}_showCursor(){this.coreService.isCursorInitialized||(this.coreService.isCursorInitialized=!0,this.refresh(this.buffer.y,this.buffer.y))}scrollLines(e,t){this._viewport?this._viewport.scrollLines(e):super.scrollLines(e,t),this.refresh(0,this.rows-1)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){e&&this._viewport?this._viewport.scrollToLine(this.buffer.ybase,!0):this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}paste(e){(0,r.paste)(e,this.textarea,this.coreService,this.optionsService)}attachCustomKeyEventHandler(e){this._customKeyEventHandler=e}attachCustomWheelEventHandler(e){this._customWheelEventHandler=e}registerLinkProvider(e){return this._linkProviderService.registerLinkProvider(e)}registerCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);let t=this._characterJoinerService.register(e);return this.refresh(0,this.rows-1),t}deregisterCharacterJoiner(e){if(!this._characterJoinerService)throw Error(`Terminal must be opened first`);this._characterJoinerService.deregister(e)&&this.refresh(0,this.rows-1)}get markers(){return this.buffer.markers}registerMarker(e){return this.buffer.addMarker(this.buffer.ybase+this.buffer.y+e)}registerDecoration(e){return this._decorationService.registerDecoration(e)}hasSelection(){return!!this._selectionService&&this._selectionService.hasSelection}select(e,t,n){this._selectionService.setSelection(e,t,n)}getSelection(){return this._selectionService?this._selectionService.selectionText:``}getSelectionPosition(){if(this._selectionService&&this._selectionService.hasSelection)return{start:{x:this._selectionService.selectionStart[0],y:this._selectionService.selectionStart[1]},end:{x:this._selectionService.selectionEnd[0],y:this._selectionService.selectionEnd[1]}}}clearSelection(){this._selectionService?.clearSelection()}selectAll(){this._selectionService?.selectAll()}selectLines(e,t){this._selectionService?.selectLines(e,t)}_keyDown(e){if(this._keyDownHandled=!1,this._keyDownSeen=!0,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;let t=this.browser.isMac&&this.options.macOptionIsMeta&&e.altKey;if(!t&&!this._compositionHelper.keydown(e))return this.options.scrollOnUserInput&&this.buffer.ybase!==this.buffer.ydisp&&this.scrollToBottom(!0),!1;t||e.key!==`Dead`&&e.key!==`AltGraph`||(this._unprocessedDeadKey=!0);let n=(0,T.evaluateKeyboardEvent)(e,this.coreService.decPrivateModes.applicationCursorKeys,this.browser.isMac,this.options.macOptionIsMeta);if(this.updateCursorStyle(e),n.type===3||n.type===2){let t=this.rows-1;return this.scrollLines(n.type===2?-t:t),this.cancel(e,!0)}return n.type===1&&this.selectAll(),!!this._isThirdLevelShift(this.browser,e)||(n.cancel&&this.cancel(e,!0),!n.key||!!(e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.key.length===1&&e.key.charCodeAt(0)>=65&&e.key.charCodeAt(0)<=90)||(this._unprocessedDeadKey?(this._unprocessedDeadKey=!1,!0):(n.key!==w.C0.ETX&&n.key!==w.C0.CR||(this.textarea.value=``),this._onKey.fire({key:n.key,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(n.key,!0),!this.optionsService.rawOptions.screenReaderMode||e.altKey||e.ctrlKey?this.cancel(e,!0):void(this._keyDownHandled=!0))))}_isThirdLevelShift(e,t){let n=e.isMac&&!this.options.macOptionIsMeta&&t.altKey&&!t.ctrlKey&&!t.metaKey||e.isWindows&&t.altKey&&t.ctrlKey&&!t.metaKey||e.isWindows&&t.getModifierState(`AltGraph`);return t.type===`keypress`?n:n&&(!t.keyCode||t.keyCode>47)}_keyUp(e){this._keyDownSeen=!1,this._customKeyEventHandler&&!1===this._customKeyEventHandler(e)||(function(e){return e.keyCode===16||e.keyCode===17||e.keyCode===18}(e)||this.focus(),this.updateCursorStyle(e),this._keyPressHandled=!1)}_keyPress(e){let t;if(this._keyPressHandled=!1,this._keyDownHandled||this._customKeyEventHandler&&!1===this._customKeyEventHandler(e))return!1;if(this.cancel(e),e.charCode)t=e.charCode;else if(e.which===null||e.which===void 0)t=e.keyCode;else{if(e.which===0||e.charCode===0)return!1;t=e.which}return!(!t||(e.altKey||e.ctrlKey||e.metaKey)&&!this._isThirdLevelShift(this.browser,e)||(t=String.fromCharCode(t),this._onKey.fire({key:t,domEvent:e}),this._showCursor(),this.coreService.triggerDataEvent(t,!0),this._keyPressHandled=!0,this._unprocessedDeadKey=!1,0))}_inputEvent(e){if(e.data&&e.inputType===`insertText`&&(!e.composed||!this._keyDownSeen)&&!this.optionsService.rawOptions.screenReaderMode){if(this._keyPressHandled)return!1;this._unprocessedDeadKey=!1;let t=e.data;return this.coreService.triggerDataEvent(t,!0),this.cancel(e),!0}return!1}resize(e,t){e!==this.cols||t!==this.rows?super.resize(e,t):this._charSizeService&&!this._charSizeService.hasValidSize&&this._charSizeService.measure()}_afterResize(e,t){this._charSizeService?.measure()}clear(){if(this.buffer.ybase!==0||this.buffer.y!==0){this.buffer.clearAllMarkers(),this.buffer.lines.set(0,this.buffer.lines.get(this.buffer.ybase+this.buffer.y)),this.buffer.lines.length=1,this.buffer.ydisp=0,this.buffer.ybase=0,this.buffer.y=0;for(let e=1;e=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Linkifier=void 0;let a=n(7150),o=n(6501),s=n(7098),c=n(802),l=n(7093),u=class extends a.Disposable{get currentLink(){return this._currentLink}constructor(e,t,n,r,i){super(),this._element=e,this._mouseService=t,this._renderService=n,this._bufferService=r,this._linkProviderService=i,this._linkCacheDisposables=[],this._isMouseOut=!0,this._wasResized=!1,this._activeLine=-1,this._onShowLinkUnderline=this._register(new c.Emitter),this.onShowLinkUnderline=this._onShowLinkUnderline.event,this._onHideLinkUnderline=this._register(new c.Emitter),this.onHideLinkUnderline=this._onHideLinkUnderline.event,this._register((0,a.toDisposable)((()=>{(0,a.dispose)(this._linkCacheDisposables),this._linkCacheDisposables.length=0,this._lastMouseEvent=void 0,this._activeProviderReplies?.clear()}))),this._register(this._bufferService.onResize((()=>{this._clearCurrentLink(),this._wasResized=!0}))),this._register((0,l.addDisposableListener)(this._element,`mouseleave`,(()=>{this._isMouseOut=!0,this._clearCurrentLink()}))),this._register((0,l.addDisposableListener)(this._element,`mousemove`,this._handleMouseMove.bind(this))),this._register((0,l.addDisposableListener)(this._element,`mousedown`,this._handleMouseDown.bind(this))),this._register((0,l.addDisposableListener)(this._element,`mouseup`,this._handleMouseUp.bind(this)))}_handleMouseMove(e){this._lastMouseEvent=e;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);if(!t)return;this._isMouseOut=!1;let n=e.composedPath();for(let e=0;e{e?.forEach((e=>{e.link.dispose&&e.link.dispose()}))})),this._activeProviderReplies=/* @__PURE__ */ new Map,this._activeLine=e.y);let n=!1;for(let[r,i]of this._linkProviderService.linkProviders.entries())t?this._activeProviderReplies?.get(r)&&(n=this._checkLinkProviderResult(r,e,n)):i.provideLinks(e.y,(t=>{if(this._isMouseOut)return;let i=t?.map((e=>({link:e})));this._activeProviderReplies?.set(r,i),n=this._checkLinkProviderResult(r,e,n),this._activeProviderReplies?.size===this._linkProviderService.linkProviders.length&&this._removeIntersectingLinks(e.y,this._activeProviderReplies)}))}_removeIntersectingLinks(e,t){let n=/* @__PURE__ */ new Set;for(let r=0;re?this._bufferService.cols:r.link.range.end.x;for(let e=a;e<=o;e++){if(n.has(e)){i.splice(t--,1);break}n.add(e)}}}}_checkLinkProviderResult(e,t,n){if(!this._activeProviderReplies)return n;let r=this._activeProviderReplies.get(e),i=!1;for(let t=0;tthis._linkAtPosition(e.link,t)));e&&(n=!0,this._handleNewLink(e))}if(this._activeProviderReplies.size===this._linkProviderService.linkProviders.length&&!n)for(let e=0;ethis._linkAtPosition(e.link,t)));if(r){n=!0,this._handleNewLink(r);break}}return n}_handleMouseDown(){this._mouseDownLink=this._currentLink}_handleMouseUp(e){if(!this._currentLink)return;let t=this._positionFromMouseEvent(e,this._element,this._mouseService);var n,r;t&&this._mouseDownLink&&(n=this._mouseDownLink.link,r=this._currentLink.link,n.text===r.text&&n.range.start.x===r.range.start.x&&n.range.start.y===r.range.start.y&&n.range.end.x===r.range.end.x&&n.range.end.y===r.range.end.y)&&this._linkAtPosition(this._currentLink.link,t)&&this._currentLink.link.activate(e,this._currentLink.link.text)}_clearCurrentLink(e,t){this._currentLink&&this._lastMouseEvent&&(!e||!t||this._currentLink.link.range.start.y>=e&&this._currentLink.link.range.end.y<=t)&&(this._linkLeave(this._element,this._currentLink.link,this._lastMouseEvent),this._currentLink=void 0,(0,a.dispose)(this._linkCacheDisposables),this._linkCacheDisposables.length=0)}_handleNewLink(e){if(!this._lastMouseEvent)return;let t=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);t&&this._linkAtPosition(e.link,t)&&(this._currentLink=e,this._currentLink.state={decorations:{underline:e.link.decorations===void 0||e.link.decorations.underline,pointerCursor:e.link.decorations===void 0||e.link.decorations.pointerCursor},isHovered:!0},this._linkHover(this._element,e.link,this._lastMouseEvent),e.link.decorations={},Object.defineProperties(e.link.decorations,{pointerCursor:{get:()=>this._currentLink?.state?.decorations.pointerCursor,set:e=>{this._currentLink?.state&&this._currentLink.state.decorations.pointerCursor!==e&&(this._currentLink.state.decorations.pointerCursor=e,this._currentLink.state.isHovered&&this._element.classList.toggle(`xterm-cursor-pointer`,e))}},underline:{get:()=>this._currentLink?.state?.decorations.underline,set:t=>{this._currentLink?.state&&this._currentLink?.state?.decorations.underline!==t&&(this._currentLink.state.decorations.underline=t,this._currentLink.state.isHovered&&this._fireUnderlineEvent(e.link,t))}}}),this._linkCacheDisposables.push(this._renderService.onRenderedViewportChange((e=>{if(!this._currentLink)return;let t=e.start===0?0:e.start+1+this._bufferService.buffer.ydisp,n=this._bufferService.buffer.ydisp+1+e.end;if(this._currentLink.link.range.start.y>=t&&this._currentLink.link.range.end.y<=n&&(this._clearCurrentLink(t,n),this._lastMouseEvent)){let e=this._positionFromMouseEvent(this._lastMouseEvent,this._element,this._mouseService);e&&this._askForLink(e,!1)}}))))}_linkHover(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!0,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!0),this._currentLink.state.decorations.pointerCursor&&e.classList.add(`xterm-cursor-pointer`)),t.hover&&t.hover(n,t.text)}_fireUnderlineEvent(e,t){let n=e.range,r=this._bufferService.buffer.ydisp,i=this._createLinkUnderlineEvent(n.start.x-1,n.start.y-r-1,n.end.x,n.end.y-r-1,void 0);(t?this._onShowLinkUnderline:this._onHideLinkUnderline).fire(i)}_linkLeave(e,t,n){this._currentLink?.state&&(this._currentLink.state.isHovered=!1,this._currentLink.state.decorations.underline&&this._fireUnderlineEvent(t,!1),this._currentLink.state.decorations.pointerCursor&&e.classList.remove(`xterm-cursor-pointer`)),t.leave&&t.leave(n,t.text)}_linkAtPosition(e,t){let n=e.range.start.y*this._bufferService.cols+e.range.start.x,r=e.range.end.y*this._bufferService.cols+e.range.end.x,i=t.y*this._bufferService.cols+t.x;return n<=i&&i<=r}_positionFromMouseEvent(e,t,n){let r=n.getCoords(e,t,this._bufferService.cols,this._bufferService.rows);if(r)return{x:r[0],y:r[1]+this._bufferService.buffer.ydisp}}_createLinkUnderlineEvent(e,t,n,r,i){return{x1:e,y1:t,x2:n,y2:r,cols:this._bufferService.cols,fg:i}}};t.Linkifier=u,t.Linkifier=u=r([i(1,s.IMouseService),i(2,s.IRenderService),i(3,o.IBufferService),i(4,s.ILinkProviderService)],u)},7721:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.tooMuchOutput=t.promptLabel=void 0;let n=`Terminal input`;t.promptLabel={get:()=>n,set:e=>n=e};let r=`Too much output to announce, navigate to rows manually to read`;t.tooMuchOutput={get:()=>r,set:e=>r=e}},3285:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkProvider=void 0;let a=n(3055),o=n(6501),s=class{constructor(e,t,n){this._bufferService=e,this._optionsService=t,this._oscLinkService=n}provideLinks(e,t){let n=this._bufferService.buffer.lines.get(e-1);if(!n)return void t(void 0);let r=[],i=this._optionsService.rawOptions.linkHandler,o=new a.CellData,s=n.getTrimmedLength(),l=-1,u=-1,d=!1;for(let t=0;ti?i.activate(e,t,a):c(0,t),hover:(e,t)=>i?.hover?.(e,t,a),leave:(e,t)=>i?.leave?.(e,t,a)})}d=!1,o.hasExtendedAttrs()&&o.extended.urlId?(u=t,l=o.extended.urlId):(u=-1,l=-1)}}t(r)}};function c(e,t){if(confirm(`Do you want to navigate to ${t}?\n\nWARNING: This link could potentially be dangerous`)){let e=window.open();if(e){try{e.opener=null}catch{}e.location.href=t}else console.warn(`Opening link blocked as opener could not be cleared`)}}t.OscLinkProvider=s,t.OscLinkProvider=s=r([i(0,o.IBufferService),i(1,o.IOptionsService),i(2,o.IOscLinkService)],s)},4852:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RenderDebouncer=void 0,t.RenderDebouncer=class{constructor(e,t){this._renderCallback=e,this._coreBrowserService=t,this._refreshCallbacks=[]}dispose(){this._animationFrame&&=(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),void 0)}addRefreshCallback(e){return this._refreshCallbacks.push(e),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())),this._animationFrame}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t),this._animationFrame||=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh()))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(let e of this._refreshCallbacks)e(0);this._refreshCallbacks=[]}}},4292:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TimeBasedDebouncer=void 0,t.TimeBasedDebouncer=class{constructor(e,t=1e3){this._renderCallback=e,this._debounceThresholdMS=t,this._lastRefreshMs=0,this._additionalRefreshRequested=!1}dispose(){this._refreshTimeoutID&&clearTimeout(this._refreshTimeoutID)}refresh(e,t,n){this._rowCount=n,e=e===void 0?0:e,t=t===void 0?this._rowCount-1:t,this._rowStart=this._rowStart===void 0?e:Math.min(this._rowStart,e),this._rowEnd=this._rowEnd===void 0?t:Math.max(this._rowEnd,t);let r=performance.now();if(r-this._lastRefreshMs>=this._debounceThresholdMS)this._lastRefreshMs=r,this._innerRefresh();else if(!this._additionalRefreshRequested){let e=r-this._lastRefreshMs,t=this._debounceThresholdMS-e;this._additionalRefreshRequested=!0,this._refreshTimeoutID=window.setTimeout((()=>{this._lastRefreshMs=performance.now(),this._innerRefresh(),this._additionalRefreshRequested=!1,this._refreshTimeoutID=void 0}),t)}}_innerRefresh(){if(this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return;let e=Math.max(this._rowStart,0),t=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(e,t)}}},9302:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_ANSI_COLORS=void 0;let r=n(4103);t.DEFAULT_ANSI_COLORS=Object.freeze((()=>{let e=[r.css.toColor(`#2e3436`),r.css.toColor(`#cc0000`),r.css.toColor(`#4e9a06`),r.css.toColor(`#c4a000`),r.css.toColor(`#3465a4`),r.css.toColor(`#75507b`),r.css.toColor(`#06989a`),r.css.toColor(`#d3d7cf`),r.css.toColor(`#555753`),r.css.toColor(`#ef2929`),r.css.toColor(`#8ae234`),r.css.toColor(`#fce94f`),r.css.toColor(`#729fcf`),r.css.toColor(`#ad7fa8`),r.css.toColor(`#34e2e2`),r.css.toColor(`#eeeeec`)],t=[0,95,135,175,215,255];for(let n=0;n<216;n++){let i=t[n/36%6|0],a=t[n/6%6|0],o=t[n%6];e.push({css:r.channels.toCss(i,a,o),rgba:r.channels.toRgba(i,a,o)})}for(let t=0;t<24;t++){let n=8+10*t;e.push({css:r.channels.toCss(n,n,n),rgba:r.channels.toRgba(n,n,n)})}return e})())},4017:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.Viewport=void 0;let a=n(7098),o=n(7150),s=n(6501),c=n(7093),l=n(8234),u=n(802),d=n(9881),f=class extends o.Disposable{constructor(e,t,n,r,i,a,s,f){super(),this._bufferService=n,this._optionsService=s,this._renderService=f,this._onRequestScrollLines=this._register(new u.Emitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._isSyncing=!1,this._isHandlingScroll=!1,this._suppressOnScrollHandler=!1;let p=this._register(new d.Scrollable({forceIntegerValues:!1,smoothScrollDuration:this._optionsService.rawOptions.smoothScrollDuration,scheduleAtNextAnimationFrame:e=>(0,c.scheduleAtNextAnimationFrame)(r.window,e)}));this._register(this._optionsService.onSpecificOptionChange(`smoothScrollDuration`,(()=>{p.setSmoothScrollDuration(this._optionsService.rawOptions.smoothScrollDuration)}))),this._scrollableElement=this._register(new l.SmoothScrollableElement(t,{vertical:1,horizontal:2,useShadows:!1,mouseWheelSmoothScroll:!0,...this._getChangeOptions()},p)),this._register(this._optionsService.onMultipleOptionChange([`scrollSensitivity`,`fastScrollSensitivity`,`overviewRuler`],(()=>this._scrollableElement.updateOptions(this._getChangeOptions())))),this._register(i.onProtocolChange((e=>{this._scrollableElement.updateOptions({handleMouseWheel:!(16&e)})}))),this._scrollableElement.setScrollDimensions({height:0,scrollHeight:0}),this._register(u.Event.runAndSubscribe(a.onChangeColors,(()=>{this._scrollableElement.getDomNode().style.backgroundColor=a.colors.background.css}))),e.appendChild(this._scrollableElement.getDomNode()),this._register((0,o.toDisposable)((()=>this._scrollableElement.getDomNode().remove()))),this._styleElement=r.mainDocument.createElement(`style`),t.appendChild(this._styleElement),this._register((0,o.toDisposable)((()=>this._styleElement.remove()))),this._register(u.Event.runAndSubscribe(a.onChangeColors,(()=>{this._styleElement.textContent=[`.xterm .xterm-scrollable-element > .scrollbar > .slider {`,` background: ${a.colors.scrollbarSliderBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider:hover {`,` background: ${a.colors.scrollbarSliderHoverBackground.css};`,`}`,`.xterm .xterm-scrollable-element > .scrollbar > .slider.active {`,` background: ${a.colors.scrollbarSliderActiveBackground.css};`,`}`].join(` +`)}))),this._register(this._bufferService.onResize((()=>this.queueSync()))),this._register(this._bufferService.buffers.onBufferActivate((()=>{this._latestYDisp=void 0,this.queueSync()}))),this._register(this._bufferService.onScroll((()=>this._sync()))),this._register(this._scrollableElement.onScroll((e=>this._handleScroll(e))))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:!0,scrollTop:t.scrollTop+e*this._renderService.dimensions.css.cell.height})}scrollToLine(e,t){t&&(this._latestYDisp=e),this._scrollableElement.setScrollPosition({reuseAnimation:!t,scrollTop:e*this._renderService.dimensions.css.cell.height})}_getChangeOptions(){return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:this._optionsService.rawOptions.overviewRuler?.width||14}}queueSync(e){e!==void 0&&(this._latestYDisp=e),this._queuedAnimationFrame===void 0&&(this._queuedAnimationFrame=this._renderService.addRefreshCallback((()=>{this._queuedAnimationFrame=void 0,this._sync(this._latestYDisp)})))}_sync(e=this._bufferService.buffer.ydisp){this._renderService&&!this._isSyncing&&(this._isSyncing=!0,this._suppressOnScrollHandler=!0,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=!1,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=!1)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=!0;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),n=t-this._bufferService.buffer.ydisp;n!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(n)),this._isHandlingScroll=!1}};t.Viewport=f,t.Viewport=f=r([i(2,s.IBufferService),i(3,a.ICoreBrowserService),i(4,s.ICoreMouseService),i(5,a.IThemeService),i(6,s.IOptionsService),i(7,a.IRenderService)],f)},4196:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferDecorationRenderer=void 0;let a=n(7098),o=n(7150),s=n(6501),c=class extends o.Disposable{constructor(e,t,n,r,i){super(),this._screenElement=e,this._bufferService=t,this._coreBrowserService=n,this._decorationService=r,this._renderService=i,this._decorationElements=/* @__PURE__ */ new Map,this._altBufferIsActive=!1,this._dimensionsChanged=!1,this._container=document.createElement(`div`),this._container.classList.add(`xterm-decoration-container`),this._screenElement.appendChild(this._container),this._register(this._renderService.onRenderedViewportChange((()=>this._doRefreshDecorations()))),this._register(this._renderService.onDimensionsChange((()=>{this._dimensionsChanged=!0,this._queueRefresh()}))),this._register(this._coreBrowserService.onDprChange((()=>this._queueRefresh()))),this._register(this._bufferService.buffers.onBufferActivate((()=>{this._altBufferIsActive=this._bufferService.buffer===this._bufferService.buffers.alt}))),this._register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh()))),this._register(this._decorationService.onDecorationRemoved((e=>this._removeDecoration(e)))),this._register((0,o.toDisposable)((()=>{this._container.remove(),this._decorationElements.clear()})))}_queueRefresh(){this._animationFrame===void 0&&(this._animationFrame=this._renderService.addRefreshCallback((()=>{this._doRefreshDecorations(),this._animationFrame=void 0})))}_doRefreshDecorations(){for(let e of this._decorationService.decorations)this._renderDecoration(e);this._dimensionsChanged=!1}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){let t=this._coreBrowserService.mainDocument.createElement(`div`);t.classList.add(`xterm-decoration`),t.classList.toggle(`xterm-decoration-top-layer`,e?.options?.layer===`top`),t.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,t.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+`px`,t.style.top=(e.marker.line-this._bufferService.buffers.active.ydisp)*this._renderService.dimensions.css.cell.height+`px`,t.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`;let n=e.options.x??0;return n&&n>this._bufferService.cols&&(t.style.display=`none`),this._refreshXPosition(e,t),t}_refreshStyle(e){let t=e.marker.line-this._bufferService.buffers.active.ydisp;if(t<0||t>=this._bufferService.rows)e.element&&(e.element.style.display=`none`,e.onRenderEmitter.fire(e.element));else{let n=this._decorationElements.get(e);n||(n=this._createElement(e),e.element=n,this._decorationElements.set(e,n),this._container.appendChild(n),e.onDispose((()=>{this._decorationElements.delete(e),n.remove()}))),n.style.display=this._altBufferIsActive?`none`:`block`,this._altBufferIsActive||(n.style.width=`${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px`,n.style.height=(e.options.height||1)*this._renderService.dimensions.css.cell.height+`px`,n.style.top=t*this._renderService.dimensions.css.cell.height+`px`,n.style.lineHeight=`${this._renderService.dimensions.css.cell.height}px`),e.onRenderEmitter.fire(n)}}_refreshXPosition(e,t=e.element){if(!t)return;let n=e.options.x??0;(e.options.anchor||`left`)===`right`?t.style.right=n?n*this._renderService.dimensions.css.cell.width+`px`:``:t.style.left=n?n*this._renderService.dimensions.css.cell.width+`px`:``}_removeDecoration(e){this._decorationElements.get(e)?.remove(),this._decorationElements.delete(e),e.dispose()}};t.BufferDecorationRenderer=c,t.BufferDecorationRenderer=c=r([i(1,s.IBufferService),i(2,a.ICoreBrowserService),i(3,s.IDecorationService),i(4,a.IRenderService)],c)},957:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ColorZoneStore=void 0,t.ColorZoneStore=class{constructor(){this._zones=[],this._zonePool=[],this._zonePoolIndex=0,this._linePadding={full:0,left:0,center:0,right:0}}get zones(){return this._zonePool.length=Math.min(this._zonePool.length,this._zones.length),this._zones}clear(){this._zones.length=0,this._zonePoolIndex=0}addDecoration(e){if(e.options.overviewRulerOptions){for(let t of this._zones)if(t.color===e.options.overviewRulerOptions.color&&t.position===e.options.overviewRulerOptions.position){if(this._lineIntersectsZone(t,e.marker.line))return;if(this._lineAdjacentToZone(t,e.marker.line,e.options.overviewRulerOptions.position))return void this._addLineToZone(t,e.marker.line)}if(this._zonePoolIndex=e.startBufferLine&&t<=e.endBufferLine}_lineAdjacentToZone(e,t,n){return t>=e.startBufferLine-this._linePadding[n||`full`]&&t<=e.endBufferLine+this._linePadding[n||`full`]}_addLineToZone(e,t){e.startBufferLine=Math.min(e.startBufferLine,t),e.endBufferLine=Math.max(e.endBufferLine,t)}}},9925:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OverviewRulerRenderer=void 0;let a=n(957),o=n(7098),s=n(7150),c=n(6501),l={full:0,left:0,center:0,right:0},u={full:0,left:0,center:0,right:0},d={full:0,left:0,center:0,right:0},f=class extends s.Disposable{get _width(){return this._optionsService.options.overviewRuler?.width||0}constructor(e,t,n,r,i,o,c,l){super(),this._viewportElement=e,this._screenElement=t,this._bufferService=n,this._decorationService=r,this._renderService=i,this._optionsService=o,this._themeService=c,this._coreBrowserService=l,this._colorZoneStore=new a.ColorZoneStore,this._shouldUpdateDimensions=!0,this._shouldUpdateAnchor=!0,this._lastKnownBufferLength=0,this._canvas=this._coreBrowserService.mainDocument.createElement(`canvas`),this._canvas.classList.add(`xterm-decoration-overview-ruler`),this._refreshCanvasDimensions(),this._viewportElement.parentElement?.insertBefore(this._canvas,this._viewportElement),this._register((0,s.toDisposable)((()=>this._canvas?.remove())));let u=this._canvas.getContext(`2d`);if(!u)throw Error(`Ctx cannot be null`);this._ctx=u,this._register(this._decorationService.onDecorationRegistered((()=>this._queueRefresh(void 0,!0)))),this._register(this._decorationService.onDecorationRemoved((()=>this._queueRefresh(void 0,!0)))),this._register(this._renderService.onRenderedViewportChange((()=>this._queueRefresh()))),this._register(this._bufferService.buffers.onBufferActivate((()=>{this._canvas.style.display=this._bufferService.buffer===this._bufferService.buffers.alt?`none`:`block`}))),this._register(this._bufferService.onScroll((()=>{this._lastKnownBufferLength!==this._bufferService.buffers.normal.lines.length&&(this._refreshDrawHeightConstants(),this._refreshColorZonePadding())}))),this._register(this._renderService.onRender((()=>{this._containerHeight&&this._containerHeight===this._screenElement.clientHeight||(this._queueRefresh(!0),this._containerHeight=this._screenElement.clientHeight)}))),this._register(this._coreBrowserService.onDprChange((()=>this._queueRefresh(!0)))),this._register(this._optionsService.onSpecificOptionChange(`overviewRuler`,(()=>this._queueRefresh(!0)))),this._register(this._themeService.onChangeColors((()=>this._queueRefresh()))),this._queueRefresh(!0)}_refreshDrawConstants(){let e=Math.floor((this._canvas.width-1)/3),t=Math.ceil((this._canvas.width-1)/3);u.full=this._canvas.width,u.left=e,u.center=t,u.right=e,this._refreshDrawHeightConstants(),d.full=1,d.left=1,d.center=1+u.left,d.right=1+u.left+u.center}_refreshDrawHeightConstants(){l.full=Math.round(2*this._coreBrowserService.dpr);let e=this._canvas.height/this._bufferService.buffer.lines.length,t=Math.round(Math.max(Math.min(e,12),6)*this._coreBrowserService.dpr);l.left=t,l.center=t,l.right=t}_refreshColorZonePadding(){this._colorZoneStore.setPadding({full:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*l.full),left:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*l.left),center:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*l.center),right:Math.floor(this._bufferService.buffers.active.lines.length/(this._canvas.height-1)*l.right)}),this._lastKnownBufferLength=this._bufferService.buffers.normal.lines.length}_refreshCanvasDimensions(){this._canvas.style.width=`${this._width}px`,this._canvas.width=Math.round(this._width*this._coreBrowserService.dpr),this._canvas.style.height=`${this._screenElement.clientHeight}px`,this._canvas.height=Math.round(this._screenElement.clientHeight*this._coreBrowserService.dpr),this._refreshDrawConstants(),this._refreshColorZonePadding()}_refreshDecorations(){this._shouldUpdateDimensions&&this._refreshCanvasDimensions(),this._ctx.clearRect(0,0,this._canvas.width,this._canvas.height),this._colorZoneStore.clear();for(let e of this._decorationService.decorations)this._colorZoneStore.addDecoration(e);this._ctx.lineWidth=1,this._renderRulerOutline();let e=this._colorZoneStore.zones;for(let t of e)t.position!==`full`&&this._renderColorZone(t);for(let t of e)t.position===`full`&&this._renderColorZone(t);this._shouldUpdateDimensions=!1,this._shouldUpdateAnchor=!1}_renderRulerOutline(){this._ctx.fillStyle=this._themeService.colors.overviewRulerBorder.css,this._ctx.fillRect(0,0,1,this._canvas.height),this._optionsService.rawOptions.overviewRuler.showTopBorder&&this._ctx.fillRect(1,0,this._canvas.width-1,1),this._optionsService.rawOptions.overviewRuler.showBottomBorder&&this._ctx.fillRect(1,this._canvas.height-1,this._canvas.width-1,this._canvas.height)}_renderColorZone(e){this._ctx.fillStyle=e.color,this._ctx.fillRect(d[e.position||`full`],Math.round((this._canvas.height-1)*(e.startBufferLine/this._bufferService.buffers.active.lines.length)-l[e.position||`full`]/2),u[e.position||`full`],Math.round((this._canvas.height-1)*((e.endBufferLine-e.startBufferLine)/this._bufferService.buffers.active.lines.length)+l[e.position||`full`]))}_queueRefresh(e,t){this._shouldUpdateDimensions=e||this._shouldUpdateDimensions,this._shouldUpdateAnchor=t||this._shouldUpdateAnchor,this._animationFrame===void 0&&(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>{this._refreshDecorations(),this._animationFrame=void 0})))}};t.OverviewRulerRenderer=f,t.OverviewRulerRenderer=f=r([i(2,c.IBufferService),i(3,c.IDecorationService),i(4,o.IRenderService),i(5,c.IOptionsService),i(6,o.IThemeService),i(7,o.ICoreBrowserService)],f)},3618:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CompositionHelper=void 0;let a=n(7098),o=n(6501),s=n(3534),c=class{get isComposing(){return this._isComposing}constructor(e,t,n,r,i,a){this._textarea=e,this._compositionView=t,this._bufferService=n,this._optionsService=r,this._coreService=i,this._renderService=a,this._isComposing=!1,this._isSendingComposition=!1,this._compositionPosition={start:0,end:0},this._dataAlreadySent=``}compositionstart(){this._isComposing=!0,this._compositionPosition.start=this._textarea.value.length,this._compositionView.textContent=``,this._dataAlreadySent=``,this._compositionView.classList.add(`active`)}compositionupdate(e){this._compositionView.textContent=e.data,this.updateCompositionElements(),setTimeout((()=>{this._compositionPosition.end=this._textarea.value.length}),0)}compositionend(){this._finalizeComposition(!0)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return!1;this._finalizeComposition(!1)}return e.keyCode!==229||(this._handleAnyTextareaChanges(),!1)}_finalizeComposition(e){if(this._compositionView.classList.remove(`active`),this._isComposing=!1,e){let e={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=!0,setTimeout((()=>{if(this._isSendingComposition){let t;this._isSendingComposition=!1,e.start+=this._dataAlreadySent.length,t=this._isComposing?this._textarea.value.substring(e.start,this._compositionPosition.start):this._textarea.value.substring(e.start),t.length>0&&this._coreService.triggerDataEvent(t,!0)}}),0)}else{this._isSendingComposition=!1;let e=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(e,!0)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout((()=>{if(!this._isComposing){let t=this._textarea.value,n=t.replace(e,``);this._dataAlreadySent=n,t.length>e.length?this._coreService.triggerDataEvent(n,!0):t.lengththis.updateCompositionElements(!0)),0)}}};t.CompositionHelper=c,t.CompositionHelper=c=r([i(2,o.IBufferService),i(3,o.IOptionsService),i(4,o.ICoreService),i(5,a.IRenderService)],c)},5251:(e,t)=>{function n(e,t,n){let r=n.getBoundingClientRect(),i=e.getComputedStyle(n),a=parseInt(i.getPropertyValue(`padding-left`)),o=parseInt(i.getPropertyValue(`padding-top`));return[t.clientX-r.left-a,t.clientY-r.top-o]}Object.defineProperty(t,"__esModule",{value:!0}),t.getCoordsRelativeToElement=n,t.getCoords=function(e,t,r,i,a,o,s,c,l){if(!o)return;let u=n(e,t,r);return u?(u[0]=Math.ceil((u[0]+(l?s/2:0))/s),u[1]=Math.ceil(u[1]/c),u[0]=Math.min(Math.max(u[0],1),i+ +!!l),u[1]=Math.min(Math.max(u[1],1),a),u):void 0}},9686:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.moveToCellSequence=function(e,t,n,r){let o=n.buffer.x,u=n.buffer.y;if(!n.buffer.hasScrollback)return function(e,t,n,r,o,u){return i(t,r,o,u).length===0?``:l(s(e,t,e,t-a(t,o),!1,o).length,c(`D`,u))}(o,u,0,t,n,r)+i(u,t,n,r)+function(e,t,n,r,o,u){let d;d=i(t,r,o,u).length>0?r-a(r,o):t;let f=r,p=function(e,t,n,r,o,s){let c;return c=i(n,r,o,s).length>0?r-a(r,o):t,e=n&&ce?`D`:`C`,l(Math.abs(o-e),c(d,r));d=u>t?`D`:`C`;let f=Math.abs(u-t);return l(function(e,t){return t.cols-e}(u>t?e:o,n)+(f-1)*n.cols+1+((u>t?o:e)-1),c(d,r))};let r=n(3534);function i(e,t,n,r){let i=e-a(e,n),s=t-a(t,n);return l(Math.abs(i-s)-function(e,t,n){let r=0,i=e-a(e,n),s=t-a(t,n);for(let a=0;a=0&&et?`A`:`B`}function s(e,t,n,r,i,a){let o=e,s=t,c=``;for(;(o!==n||s!==r)&&s>=0&&sa.cols-1?(c+=a.buffer.translateBufferLineToString(s,!1,e,o),o=0,e=0,s++):!i&&o<0&&(c+=a.buffer.translateBufferLineToString(s,!1,0,e+1),o=a.cols-1,e=o,s--);return c+a.buffer.translateBufferLineToString(s,!1,e,o)}function c(e,t){let n=t?`O`:`[`;return r.C0.ESC+n+e}function l(e,t){e=Math.floor(e);let n=``;for(let r=0;r=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRenderer=void 0;let a=n(1433),o=n(2744),s=n(9176),c=n(6181),l=n(2274),u=n(7098),d=n(4103),f=n(7150),p=n(6501),m=n(802),h=`xterm-dom-renderer-owner-`,g=`xterm-rows`,_=`xterm-fg-`,v=`xterm-bg-`,y=`xterm-focus`,b=`xterm-selection`,x=1,S=class extends f.Disposable{constructor(e,t,n,r,i,s,u,d,p,_,v,y,S,C){super(),this._terminal=e,this._document=t,this._element=n,this._screenElement=r,this._viewportElement=i,this._helperContainer=s,this._linkifier2=u,this._charSizeService=p,this._optionsService=_,this._bufferService=v,this._coreService=y,this._coreBrowserService=S,this._themeService=C,this._terminalClass=x++,this._rowElements=[],this._selectionRenderModel=(0,l.createSelectionRenderModel)(),this.onRequestRedraw=this._register(new m.Emitter).event,this._rowContainer=this._document.createElement(`div`),this._rowContainer.classList.add(g),this._rowContainer.style.lineHeight=`normal`,this._rowContainer.setAttribute(`aria-hidden`,`true`),this._refreshRowElements(this._bufferService.cols,this._bufferService.rows),this._selectionContainer=this._document.createElement(`div`),this._selectionContainer.classList.add(b),this._selectionContainer.setAttribute(`aria-hidden`,`true`),this.dimensions=(0,c.createRenderDimensions)(),this._updateDimensions(),this._register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this._register(this._themeService.onChangeColors((e=>this._injectCss(e)))),this._injectCss(this._themeService.colors),this._rowFactory=d.createInstance(a.DomRendererRowFactory,document),this._element.classList.add(h+this._terminalClass),this._screenElement.appendChild(this._rowContainer),this._screenElement.appendChild(this._selectionContainer),this._register(this._linkifier2.onShowLinkUnderline((e=>this._handleLinkHover(e)))),this._register(this._linkifier2.onHideLinkUnderline((e=>this._handleLinkLeave(e)))),this._register((0,f.toDisposable)((()=>{this._element.classList.remove(h+this._terminalClass),this._rowContainer.remove(),this._selectionContainer.remove(),this._widthCache.dispose(),this._themeStyleElement.remove(),this._dimensionsStyleElement.remove()}))),this._widthCache=new o.WidthCache(this._document,this._helperContainer),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}_updateDimensions(){let e=this._coreBrowserService.dpr;this.dimensions.device.char.width=this._charSizeService.width*e,this.dimensions.device.char.height=Math.ceil(this._charSizeService.height*e),this.dimensions.device.cell.width=this.dimensions.device.char.width+Math.round(this._optionsService.rawOptions.letterSpacing),this.dimensions.device.cell.height=Math.floor(this.dimensions.device.char.height*this._optionsService.rawOptions.lineHeight),this.dimensions.device.char.left=0,this.dimensions.device.char.top=0,this.dimensions.device.canvas.width=this.dimensions.device.cell.width*this._bufferService.cols,this.dimensions.device.canvas.height=this.dimensions.device.cell.height*this._bufferService.rows,this.dimensions.css.canvas.width=Math.round(this.dimensions.device.canvas.width/e),this.dimensions.css.canvas.height=Math.round(this.dimensions.device.canvas.height/e),this.dimensions.css.cell.width=this.dimensions.css.canvas.width/this._bufferService.cols,this.dimensions.css.cell.height=this.dimensions.css.canvas.height/this._bufferService.rows;for(let e of this._rowElements)e.style.width=`${this.dimensions.css.canvas.width}px`,e.style.height=`${this.dimensions.css.cell.height}px`,e.style.lineHeight=`${this.dimensions.css.cell.height}px`,e.style.overflow=`hidden`;this._dimensionsStyleElement||(this._dimensionsStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._dimensionsStyleElement));let t=`${this._terminalSelector} .${g} span { display: inline-block; height: 100%; vertical-align: top;}`;this._dimensionsStyleElement.textContent=t,this._selectionContainer.style.height=this._viewportElement.style.height,this._screenElement.style.width=`${this.dimensions.css.canvas.width}px`,this._screenElement.style.height=`${this.dimensions.css.canvas.height}px`}_injectCss(e){this._themeStyleElement||(this._themeStyleElement=this._document.createElement(`style`),this._screenElement.appendChild(this._themeStyleElement));let t=`${this._terminalSelector} .${g} { pointer-events: none; color: ${e.foreground.css}; font-family: ${this._optionsService.rawOptions.fontFamily}; font-size: ${this._optionsService.rawOptions.fontSize}px; font-kerning: none; white-space: pre}`;t+=`${this._terminalSelector} .${g} .xterm-dim { color: ${d.color.multiplyOpacity(e.foreground,.5).css};}`,t+=`${this._terminalSelector} span:not(.xterm-bold) { font-weight: ${this._optionsService.rawOptions.fontWeight};}${this._terminalSelector} span.xterm-bold { font-weight: ${this._optionsService.rawOptions.fontWeightBold};}${this._terminalSelector} span.xterm-italic { font-style: italic;}`;let n=`blink_underline_${this._terminalClass}`,r=`blink_bar_${this._terminalClass}`,i=`blink_block_${this._terminalClass}`;t+=`@keyframes ${n} { 50% { border-bottom-style: hidden; }}`,t+=`@keyframes ${r} { 50% { box-shadow: none; }}`,t+=`@keyframes ${i} { 0% { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css}; } 50% { background-color: inherit; color: ${e.cursor.css}; }}`,t+=`${this._terminalSelector} .${g}.${y} .xterm-cursor.xterm-cursor-blink.xterm-cursor-underline { animation: ${n} 1s step-end infinite;}${this._terminalSelector} .${g}.${y} .xterm-cursor.xterm-cursor-blink.xterm-cursor-bar { animation: ${r} 1s step-end infinite;}${this._terminalSelector} .${g}.${y} .xterm-cursor.xterm-cursor-blink.xterm-cursor-block { animation: ${i} 1s step-end infinite;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-block { background-color: ${e.cursor.css}; color: ${e.cursorAccent.css};}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-block:not(.xterm-cursor-blink) { background-color: ${e.cursor.css} !important; color: ${e.cursorAccent.css} !important;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-outline { outline: 1px solid ${e.cursor.css}; outline-offset: -1px;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-bar { box-shadow: ${this._optionsService.rawOptions.cursorWidth}px 0 0 ${e.cursor.css} inset;}${this._terminalSelector} .${g} .xterm-cursor.xterm-cursor-underline { border-bottom: 1px ${e.cursor.css}; border-bottom-style: solid; height: calc(100% - 1px);}`,t+=`${this._terminalSelector} .${b} { position: absolute; top: 0; left: 0; z-index: 1; pointer-events: none;}${this._terminalSelector}.focus .${b} div { position: absolute; background-color: ${e.selectionBackgroundOpaque.css};}${this._terminalSelector} .${b} div { position: absolute; background-color: ${e.selectionInactiveBackgroundOpaque.css};}`;for(let[n,r]of e.ansi.entries())t+=`${this._terminalSelector} .${_}${n} { color: ${r.css}; }${this._terminalSelector} .${_}${n}.xterm-dim { color: ${d.color.multiplyOpacity(r,.5).css}; }${this._terminalSelector} .${v}${n} { background-color: ${r.css}; }`;t+=`${this._terminalSelector} .${_}${s.INVERTED_DEFAULT_COLOR} { color: ${d.color.opaque(e.background).css}; }${this._terminalSelector} .${_}${s.INVERTED_DEFAULT_COLOR}.xterm-dim { color: ${d.color.multiplyOpacity(d.color.opaque(e.background),.5).css}; }${this._terminalSelector} .${v}${s.INVERTED_DEFAULT_COLOR} { background-color: ${e.foreground.css}; }`,this._themeStyleElement.textContent=t}_setDefaultSpacing(){let e=this.dimensions.css.cell.width-this._widthCache.get(`W`,!1,!1);this._rowContainer.style.letterSpacing=`${e}px`,this._rowFactory.defaultSpacing=e}handleDevicePixelRatioChange(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}_refreshRowElements(e,t){for(let e=this._rowElements.length;e<=t;e++){let e=this._document.createElement(`div`);this._rowContainer.appendChild(e),this._rowElements.push(e)}for(;this._rowElements.length>t;)this._rowContainer.removeChild(this._rowElements.pop())}handleResize(e,t){this._refreshRowElements(e,t),this._updateDimensions(),this.handleSelectionChanged(this._selectionRenderModel.selectionStart,this._selectionRenderModel.selectionEnd,this._selectionRenderModel.columnSelectMode)}handleCharSizeChanged(){this._updateDimensions(),this._widthCache.clear(),this._setDefaultSpacing()}handleBlur(){this._rowContainer.classList.remove(y),this.renderRows(0,this._bufferService.rows-1)}handleFocus(){this._rowContainer.classList.add(y),this.renderRows(this._bufferService.buffer.y,this._bufferService.buffer.y)}handleSelectionChanged(e,t,n){if(this._selectionContainer.replaceChildren(),this._rowFactory.handleSelectionChanged(e,t,n),this.renderRows(0,this._bufferService.rows-1),!e||!t||(this._selectionRenderModel.update(this._terminal,e,t,n),!this._selectionRenderModel.hasSelection))return;let r=this._selectionRenderModel.viewportStartRow,i=this._selectionRenderModel.viewportEndRow,a=this._selectionRenderModel.viewportCappedStartRow,o=this._selectionRenderModel.viewportCappedEndRow,s=this._document.createDocumentFragment();if(n){let n=e[0]>t[0];s.appendChild(this._createSelectionElement(a,n?t[0]:e[0],n?e[0]:t[0],o-a+1))}else{let n=r===a?e[0]:0,c=a===i?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(a,n,c));let l=o-a-1;if(s.appendChild(this._createSelectionElement(a+1,0,this._bufferService.cols,l)),a!==o){let e=i===o?t[0]:this._bufferService.cols;s.appendChild(this._createSelectionElement(o,0,e))}}this._selectionContainer.appendChild(s)}_createSelectionElement(e,t,n,r=1){let i=this._document.createElement(`div`),a=t*this.dimensions.css.cell.width,o=this.dimensions.css.cell.width*(n-t);return a+o>this.dimensions.css.canvas.width&&(o=this.dimensions.css.canvas.width-a),i.style.height=r*this.dimensions.css.cell.height+`px`,i.style.top=e*this.dimensions.css.cell.height+`px`,i.style.left=`${a}px`,i.style.width=`${o}px`,i}handleCursorMove(){}_handleOptionsChanged(){this._updateDimensions(),this._injectCss(this._themeService.colors),this._widthCache.setFont(this._optionsService.rawOptions.fontFamily,this._optionsService.rawOptions.fontSize,this._optionsService.rawOptions.fontWeight,this._optionsService.rawOptions.fontWeightBold),this._setDefaultSpacing()}clear(){for(let e of this._rowElements)e.replaceChildren()}renderRows(e,t){let n=this._bufferService.buffer,r=n.ybase+n.y,i=Math.min(n.x,this._bufferService.cols-1),a=this._coreService.decPrivateModes.cursorBlink??this._optionsService.rawOptions.cursorBlink,o=this._coreService.decPrivateModes.cursorStyle??this._optionsService.rawOptions.cursorStyle,s=this._optionsService.rawOptions.cursorInactiveStyle;for(let c=e;c<=t;c++){let e=c+n.ydisp,t=this._rowElements[c],l=n.lines.get(e);if(!t||!l)break;t.replaceChildren(...this._rowFactory.createRow(l,e,e===r,o,s,i,a,this.dimensions.css.cell.width,this._widthCache,-1,-1))}}get _terminalSelector(){return`.${h}${this._terminalClass}`}_handleLinkHover(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!0)}_handleLinkLeave(e){this._setCellUnderline(e.x1,e.x2,e.y1,e.y2,e.cols,!1)}_setCellUnderline(e,t,n,r,i,a){n<0&&(e=0),r<0&&(t=0);let o=this._bufferService.rows-1;n=Math.max(Math.min(n,o),0),r=Math.max(Math.min(r,o),0),i=Math.min(i,this._bufferService.cols);let s=this._bufferService.buffer,c=s.ybase+s.y,l=Math.min(s.x,i-1),u=this._optionsService.rawOptions.cursorBlink,d=this._optionsService.rawOptions.cursorStyle,f=this._optionsService.rawOptions.cursorInactiveStyle;for(let o=n;o<=r;++o){let p=o+s.ydisp,m=this._rowElements[o],h=s.lines.get(p);if(!m||!h)break;m.replaceChildren(...this._rowFactory.createRow(h,p,p===c,d,f,l,u,this.dimensions.css.cell.width,this._widthCache,a?o===n?e:0:-1,a?(o===r?t:i)-1:-1))}}};t.DomRenderer=S,t.DomRenderer=S=r([i(7,p.IInstantiationService),i(8,u.ICharSizeService),i(9,p.IOptionsService),i(10,p.IBufferService),i(11,p.ICoreService),i(12,u.ICoreBrowserService),i(13,u.IThemeService)],S)},1433:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.DomRendererRowFactory=void 0;let a=n(9176),o=n(8938),s=n(3055),c=n(6501),l=n(4103),u=n(7098),d=n(945),f=n(6181),p=n(5451),m=class{constructor(e,t,n,r,i,a,o){this._document=e,this._characterJoinerService=t,this._optionsService=n,this._coreBrowserService=r,this._coreService=i,this._decorationService=a,this._themeService=o,this._workCell=new s.CellData,this._columnSelectMode=!1,this.defaultSpacing=0}handleSelectionChanged(e,t,n){this._selectionStart=e,this._selectionEnd=t,this._columnSelectMode=n}createRow(e,t,n,r,i,s,c,u,f,m,g){let _=[],v=this._characterJoinerService.getJoinedCharacters(t),y=this._themeService.colors,b,x=e.getNoBgTrimmedLength();n&&x=M,R=F,z=this._workCell;if(v.length>0&&F===v[0][0]&&L){let r=v.shift(),i=this._isCellInSelection(r[0],t);for(w=r[0]+1;w=r[1],L?(I=!0,z=new d.JoinedCellData(this._workCell,e.translateToString(!0,r[0],r[1]),r[1]-r[0]),R=r[1]-1,x=z.getWidth()):M=r[1]}let B=this._isCellInSelection(F,t),V=n&&F===s,H=P&&F>=m&&F<=g,U=!1;this._decorationService.forEachDecorationAtCell(F,t,void 0,(e=>{U=!0}));let W=z.getChars()||o.WHITESPACE_CELL_CHAR;if(W===` `&&(z.isUnderline()||z.isOverline())&&(W=`\xA0`),j=x*u-f.get(W,z.isBold(),z.isItalic()),b){if(S&&(B&&A||!B&&!A&&z.bg===T)&&(B&&A&&y.selectionForeground||z.fg===E)&&z.extended.ext===D&&H===O&&j===k&&!V&&!I&&!U&&L){z.isInvisible()?C+=o.WHITESPACE_CELL_CHAR:C+=W,S++;continue}S&&(b.textContent=C),b=this._document.createElement(`span`),S=0,C=``}else b=this._document.createElement(`span`);if(T=z.bg,E=z.fg,D=z.extended.ext,O=H,k=j,A=B,I&&s>=F&&s<=R&&(s=F),!this._coreService.isCursorHidden&&V&&this._coreService.isCursorInitialized){if(N.push(`xterm-cursor`),this._coreBrowserService.isFocused)c&&N.push(`xterm-cursor-blink`),N.push(r===`bar`?`xterm-cursor-bar`:r===`underline`?`xterm-cursor-underline`:`xterm-cursor-block`);else if(i)switch(i){case`outline`:N.push(`xterm-cursor-outline`);break;case`block`:N.push(`xterm-cursor-block`);break;case`bar`:N.push(`xterm-cursor-bar`);break;case`underline`:N.push(`xterm-cursor-underline`)}}if(z.isBold()&&N.push(`xterm-bold`),z.isItalic()&&N.push(`xterm-italic`),z.isDim()&&N.push(`xterm-dim`),C=z.isInvisible()?o.WHITESPACE_CELL_CHAR:z.getChars()||o.WHITESPACE_CELL_CHAR,z.isUnderline()&&(N.push(`xterm-underline-${z.extended.underlineStyle}`),C===` `&&(C=`\xA0`),!z.isUnderlineColorDefault())){if(z.isUnderlineColorRGB())b.style.textDecorationColor=`rgb(${p.AttributeData.toColorRGB(z.getUnderlineColor()).join(`,`)})`;else{let e=z.getUnderlineColor();this._optionsService.rawOptions.drawBoldTextInBrightColors&&z.isBold()&&e<8&&(e+=8),b.style.textDecorationColor=y.ansi[e].css}}z.isOverline()&&(N.push(`xterm-overline`),C===` `&&(C=`\xA0`)),z.isStrikethrough()&&N.push(`xterm-strikethrough`),H&&(b.style.textDecoration=`underline`);let G=z.getFgColor(),K=z.getFgColorMode(),q=z.getBgColor(),J=z.getBgColorMode(),Y=!!z.isInverse();if(Y){let e=G;G=q,q=e;let t=K;K=J,J=t}let X,Z,Q,$=!1;switch(this._decorationService.forEachDecorationAtCell(F,t,void 0,(e=>{e.options.layer!==`top`&&$||(e.backgroundColorRGB&&(J=50331648,q=e.backgroundColorRGB.rgba>>8&16777215,X=e.backgroundColorRGB),e.foregroundColorRGB&&(K=50331648,G=e.foregroundColorRGB.rgba>>8&16777215,Z=e.foregroundColorRGB),$=e.options.layer===`top`)})),!$&&B&&(X=this._coreBrowserService.isFocused?y.selectionBackgroundOpaque:y.selectionInactiveBackgroundOpaque,q=X.rgba>>8&16777215,J=50331648,$=!0,y.selectionForeground&&(K=50331648,G=y.selectionForeground.rgba>>8&16777215,Z=y.selectionForeground)),$&&N.push(`xterm-decoration-top`),J){case 16777216:case 33554432:Q=y.ansi[q],N.push(`xterm-bg-${q}`);break;case 50331648:Q=l.channels.toColor(q>>16,q>>8&255,255&q),this._addStyle(b,`background-color:#${h((q>>>0).toString(16),`0`,6)}`);break;default:Y?(Q=y.foreground,N.push(`xterm-bg-${a.INVERTED_DEFAULT_COLOR}`)):Q=y.background}switch(X||z.isDim()&&(X=l.color.multiplyOpacity(Q,.5)),K){case 16777216:case 33554432:z.isBold()&&G<8&&this._optionsService.rawOptions.drawBoldTextInBrightColors&&(G+=8),this._applyMinimumContrast(b,Q,y.ansi[G],z,X,void 0)||N.push(`xterm-fg-${G}`);break;case 50331648:let e=l.channels.toColor(G>>16&255,G>>8&255,255&G);this._applyMinimumContrast(b,Q,e,z,X,Z)||this._addStyle(b,`color:#${h(G.toString(16),`0`,6)}`);break;default:this._applyMinimumContrast(b,Q,y.foreground,z,X,Z)||Y&&N.push(`xterm-fg-${a.INVERTED_DEFAULT_COLOR}`)}N.length&&=(b.className=N.join(` `),0),V||I||U||!L?b.textContent=C:S++,j!==this.defaultSpacing&&(b.style.letterSpacing=`${j}px`),_.push(b),F=R}return b&&S&&(b.textContent=C),_}_applyMinimumContrast(e,t,n,r,i,a){if(this._optionsService.rawOptions.minimumContrastRatio===1||(0,f.treatGlyphAsBackgroundColor)(r.getCode()))return!1;let o=this._getContrastCache(r),s;if(i||a||(s=o.getColor(t.rgba,n.rgba)),s===void 0){let e=this._optionsService.rawOptions.minimumContrastRatio/(r.isDim()?2:1);s=l.color.ensureContrastRatio(i||t,a||n,e),o.setColor((i||t).rgba,(a||n).rgba,s??null)}return!!s&&(this._addStyle(e,`color:${s.css}`),!0)}_getContrastCache(e){return e.isDim()?this._themeService.colors.halfContrastCache:this._themeService.colors.contrastCache}_addStyle(e,t){e.setAttribute(`style`,`${e.getAttribute(`style`)||``}${t};`)}_isCellInSelection(e,t){let n=this._selectionStart,r=this._selectionEnd;return!(!n||!r)&&(this._columnSelectMode?n[0]<=r[0]?e>=n[0]&&t>=n[1]&&e=n[1]&&e>=r[0]&&t<=r[1]:t>n[1]&&t=n[0]&&e=n[0])}};function h(e,t,n){for(;e.length{Object.defineProperty(t,"__esModule",{value:!0}),t.WidthCache=void 0,t.WidthCache=class{constructor(e,t){this._flat=/* @__PURE__ */ new Float32Array(256),this._font=``,this._fontSize=0,this._weight=`normal`,this._weightBold=`bold`,this._measureElements=[],this._container=e.createElement(`div`),this._container.classList.add(`xterm-width-cache-measure-container`),this._container.setAttribute(`aria-hidden`,`true`),this._container.style.whiteSpace=`pre`,this._container.style.fontKerning=`none`;let n=e.createElement(`span`);n.classList.add(`xterm-char-measure-element`);let r=e.createElement(`span`);r.classList.add(`xterm-char-measure-element`),r.style.fontWeight=`bold`;let i=e.createElement(`span`);i.classList.add(`xterm-char-measure-element`),i.style.fontStyle=`italic`;let a=e.createElement(`span`);a.classList.add(`xterm-char-measure-element`),a.style.fontWeight=`bold`,a.style.fontStyle=`italic`,this._measureElements=[n,r,i,a],this._container.appendChild(n),this._container.appendChild(r),this._container.appendChild(i),this._container.appendChild(a),t.appendChild(this._container),this.clear()}dispose(){this._container.remove(),this._measureElements.length=0,this._holey=void 0}clear(){this._flat.fill(-9999),this._holey=/* @__PURE__ */ new Map}setFont(e,t,n,r){e===this._font&&t===this._fontSize&&n===this._weight&&r===this._weightBold||(this._font=e,this._fontSize=t,this._weight=n,this._weightBold=r,this._container.style.fontFamily=this._font,this._container.style.fontSize=`${this._fontSize}px`,this._measureElements[0].style.fontWeight=`${n}`,this._measureElements[1].style.fontWeight=`${r}`,this._measureElements[2].style.fontWeight=`${n}`,this._measureElements[3].style.fontWeight=`${r}`,this.clear())}get(e,t,n){let r=0;if(!t&&!n&&e.length===1&&(r=e.charCodeAt(0))<256){if(this._flat[r]!==-9999)return this._flat[r];let t=this._measure(e,0);return t>0&&(this._flat[r]=t),t}let i=e;t&&(i+=`B`),n&&(i+=`I`);let a=this._holey.get(i);if(a===void 0){let r=0;t&&(r|=1),n&&(r|=2),a=this._measure(e,r),a>0&&this._holey.set(i,a)}return a}_measure(e,t){let n=this._measureElements[t];return n.textContent=e.repeat(32),n.offsetWidth/32}}},9176:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.INVERTED_DEFAULT_COLOR=void 0,t.INVERTED_DEFAULT_COLOR=257},6181:(e,t)=>{function n(e){return 57508<=e&&e<=57558}function r(e){return e>=128512&&e<=128591||e>=127744&&e<=128511||e>=128640&&e<=128767||e>=9728&&e<=9983||e>=9984&&e<=10175||e>=65024&&e<=65039||e>=129280&&e<=129535||e>=127462&&e<=127487}Object.defineProperty(t,"__esModule",{value:!0}),t.throwIfFalsy=function(e){if(!e)throw Error(`value must not be falsy`);return e},t.isPowerlineGlyph=n,t.isRestrictedPowerlineGlyph=function(e){return 57520<=e&&e<=57527},t.isEmoji=r,t.allowRescaling=function(e,t,i,a){return t===1&&i>Math.ceil(1.5*a)&&e!==void 0&&e>255&&!r(e)&&!n(e)&&!function(e){return 57344<=e&&e<=63743}(e)},t.treatGlyphAsBackgroundColor=function(e){return n(e)||function(e){return 9472<=e&&e<=9631}(e)},t.createRenderDimensions=function(){return{css:{canvas:{width:0,height:0},cell:{width:0,height:0}},device:{canvas:{width:0,height:0},cell:{width:0,height:0},char:{width:0,height:0,left:0,top:0}}}},t.computeNextVariantOffset=function(e,t,n=0){return(e-(2*Math.round(t)-n))%(2*Math.round(t))}},2274:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createSelectionRenderModel=function(){return new n};class n{constructor(){this.clear()}clear(){this.hasSelection=!1,this.columnSelectMode=!1,this.viewportStartRow=0,this.viewportEndRow=0,this.viewportCappedStartRow=0,this.viewportCappedEndRow=0,this.startCol=0,this.endCol=0,this.selectionStart=void 0,this.selectionEnd=void 0}update(e,t,n,r=!1){if(this.selectionStart=t,this.selectionEnd=n,!t||!n||t[0]===n[0]&&t[1]===n[1])return void this.clear();let i=e.buffers.active.ydisp,a=t[1]-i,o=n[1]-i,s=Math.max(a,0),c=Math.min(o,e.rows-1);s>=e.rows||c<0?this.clear():(this.hasSelection=!0,this.columnSelectMode=r,this.viewportStartRow=a,this.viewportEndRow=o,this.viewportCappedStartRow=s,this.viewportCappedEndRow=c,this.startCol=t[0],this.endCol=n[0])}isCellSelected(e,t,n){return!!this.hasSelection&&(n-=e.buffer.active.viewportY,this.columnSelectMode?this.startCol<=this.endCol?t>=this.startCol&&n>=this.viewportCappedStartRow&&t=this.viewportCappedStartRow&&t>=this.endCol&&n<=this.viewportCappedEndRow:n>this.viewportStartRow&&n=this.startCol&&t=this.startCol)}}},5959:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionModel=void 0,t.SelectionModel=class{constructor(e){this._bufferService=e,this.isSelectAllActive=!1,this.selectionStartLength=0}clearSelection(){this.selectionStart=void 0,this.selectionEnd=void 0,this.isSelectAllActive=!1,this.selectionStartLength=0}get finalSelectionStart(){return this.isSelectAllActive?[0,0]:this.selectionEnd&&this.selectionStart&&this.areSelectionValuesReversed()?this.selectionEnd:this.selectionStart}get finalSelectionEnd(){if(this.isSelectAllActive)return[this._bufferService.cols,this._bufferService.buffer.ybase+this._bufferService.rows-1];if(this.selectionStart){if(!this.selectionEnd||this.areSelectionValuesReversed()){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?e%this._bufferService.cols==0?[this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)-1]:[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[e,this.selectionStart[1]]}if(this.selectionStartLength&&this.selectionEnd[1]===this.selectionStart[1]){let e=this.selectionStart[0]+this.selectionStartLength;return e>this._bufferService.cols?[e%this._bufferService.cols,this.selectionStart[1]+Math.floor(e/this._bufferService.cols)]:[Math.max(e,this.selectionEnd[0]),this.selectionEnd[1]]}return this.selectionEnd}}areSelectionValuesReversed(){let e=this.selectionStart,t=this.selectionEnd;return!(!e||!t)&&(e[1]>t[1]||e[1]===t[1]&&e[0]>t[0])}handleTrim(e){return this.selectionStart&&(this.selectionStart[1]-=e),this.selectionEnd&&(this.selectionEnd[1]-=e),this.selectionEnd&&this.selectionEnd[1]<0?(this.clearSelection(),!0):(this.selectionStart&&this.selectionStart[1]<0&&(this.selectionStart[1]=0),!1)}}},4792:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharSizeService=void 0;let a=n(6501),o=n(7150),s=n(802),c=class extends o.Disposable{get hasValidSize(){return this.width>0&&this.height>0}constructor(e,t,n){super(),this._optionsService=n,this.width=0,this.height=0,this._onCharSizeChange=this._register(new s.Emitter),this.onCharSizeChange=this._onCharSizeChange.event;try{this._measureStrategy=this._register(new d(this._optionsService))}catch{this._measureStrategy=this._register(new u(e,t,this._optionsService))}this._register(this._optionsService.onMultipleOptionChange([`fontFamily`,`fontSize`],(()=>this.measure())))}measure(){let e=this._measureStrategy.measure();e.width===this.width&&e.height===this.height||(this.width=e.width,this.height=e.height,this._onCharSizeChange.fire())}};t.CharSizeService=c,t.CharSizeService=c=r([i(2,a.IOptionsService)],c);class l extends o.Disposable{constructor(){super(...arguments),this._result={width:0,height:0}}_validateAndSet(e,t){e!==void 0&&e>0&&t!==void 0&&t>0&&(this._result.width=e,this._result.height=t)}}class u extends l{constructor(e,t,n){super(),this._document=e,this._parentElement=t,this._optionsService=n,this._measureElement=this._document.createElement(`span`),this._measureElement.classList.add(`xterm-char-measure-element`),this._measureElement.textContent=`W`.repeat(32),this._measureElement.setAttribute(`aria-hidden`,`true`),this._measureElement.style.whiteSpace=`pre`,this._measureElement.style.fontKerning=`none`,this._parentElement.appendChild(this._measureElement)}measure(){return this._measureElement.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._measureElement.style.fontSize=`${this._optionsService.rawOptions.fontSize}px`,this._validateAndSet(Number(this._measureElement.offsetWidth)/32,Number(this._measureElement.offsetHeight)),this._result}}class d extends l{constructor(e){super(),this._optionsService=e,this._canvas=new OffscreenCanvas(100,100),this._ctx=this._canvas.getContext(`2d`);let t=this._ctx.measureText(`W`);if(!(`width`in t&&`fontBoundingBoxAscent`in t&&`fontBoundingBoxDescent`in t))throw Error(`Required font metrics not supported`)}measure(){this._ctx.font=`${this._optionsService.rawOptions.fontSize}px ${this._optionsService.rawOptions.fontFamily}`;let e=this._ctx.measureText(`W`);return this._validateAndSet(e.width,e.fontBoundingBoxAscent+e.fontBoundingBoxDescent),this._result}}},945:function(e,t,n){var r,i=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},a=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CharacterJoinerService=t.JoinedCellData=void 0;let o=n(5451),s=n(8938),c=n(3055),l=n(6501);class u extends o.AttributeData{constructor(e,t,n){super(),this.content=0,this.combinedData=``,this.fg=e.fg,this.bg=e.bg,this.combinedData=t,this._width=n}isCombined(){return 2097152}getWidth(){return this._width}getChars(){return this.combinedData}getCode(){return 2097151}setFromCharData(e){throw Error(`not implemented`)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.JoinedCellData=u;let d=r=class{constructor(e){this._bufferService=e,this._characterJoiners=[],this._nextCharacterJoinerId=0,this._workCell=new c.CellData}register(e){let t={id:this._nextCharacterJoinerId++,handler:e};return this._characterJoiners.push(t),t.id}deregister(e){for(let t=0;t1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t1){let e=this._getJoinedRanges(r,o,a,t,i);for(let t=0;t{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreBrowserService=void 0;let r=n(802),i=n(7093),a=n(7150);class o extends a.Disposable{constructor(e,t,n){super(),this._textarea=e,this._window=t,this.mainDocument=n,this._isFocused=!1,this._cachedIsFocused=void 0,this._screenDprMonitor=this._register(new s(this._window)),this._onDprChange=this._register(new r.Emitter),this.onDprChange=this._onDprChange.event,this._onWindowChange=this._register(new r.Emitter),this.onWindowChange=this._onWindowChange.event,this._register(this.onWindowChange((e=>this._screenDprMonitor.setWindow(e)))),this._register(r.Event.forward(this._screenDprMonitor.onDprChange,this._onDprChange)),this._register((0,i.addDisposableListener)(this._textarea,`focus`,(()=>this._isFocused=!0))),this._register((0,i.addDisposableListener)(this._textarea,`blur`,(()=>this._isFocused=!1)))}get window(){return this._window}set window(e){this._window!==e&&(this._window=e,this._onWindowChange.fire(this._window))}get dpr(){return this.window.devicePixelRatio}get isFocused(){return this._cachedIsFocused===void 0&&(this._cachedIsFocused=this._isFocused&&this._textarea.ownerDocument.hasFocus(),queueMicrotask((()=>this._cachedIsFocused=void 0))),this._cachedIsFocused}}t.CoreBrowserService=o;class s extends a.Disposable{constructor(e){super(),this._parentWindow=e,this._windowResizeListener=this._register(new a.MutableDisposable),this._onDprChange=this._register(new r.Emitter),this.onDprChange=this._onDprChange.event,this._outerListener=()=>this._setDprAndFireIfDiffers(),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._updateDpr(),this._setWindowResizeListener(),this._register((0,a.toDisposable)((()=>this.clearListener())))}setWindow(e){this._parentWindow=e,this._setWindowResizeListener(),this._setDprAndFireIfDiffers()}_setWindowResizeListener(){this._windowResizeListener.value=(0,i.addDisposableListener)(this._parentWindow,`resize`,(()=>this._setDprAndFireIfDiffers()))}_setDprAndFireIfDiffers(){this._parentWindow.devicePixelRatio!==this._currentDevicePixelRatio&&this._onDprChange.fire(this._parentWindow.devicePixelRatio),this._updateDpr()}_updateDpr(){this._outerListener&&(this._resolutionMediaMatchList?.removeListener(this._outerListener),this._currentDevicePixelRatio=this._parentWindow.devicePixelRatio,this._resolutionMediaMatchList=this._parentWindow.matchMedia(`screen and (resolution: ${this._parentWindow.devicePixelRatio}dppx)`),this._resolutionMediaMatchList.addListener(this._outerListener))}clearListener(){this._resolutionMediaMatchList&&this._outerListener&&(this._resolutionMediaMatchList.removeListener(this._outerListener),this._resolutionMediaMatchList=void 0,this._outerListener=void 0)}}},9820:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LinkProviderService=void 0;let r=n(7150);class i extends r.Disposable{constructor(){super(),this.linkProviders=[],this._register((0,r.toDisposable)((()=>this.linkProviders.length=0)))}registerLinkProvider(e){return this.linkProviders.push(e),{dispose:()=>{let t=this.linkProviders.indexOf(e);t!==-1&&this.linkProviders.splice(t,1)}}}}t.LinkProviderService=i},9784:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.MouseService=void 0;let a=n(7098),o=n(5251),s=class{constructor(e,t){this._renderService=e,this._charSizeService=t}getCoords(e,t,n,r,i){return(0,o.getCoords)(window,e,t,n,r,this._charSizeService.hasValidSize,this._renderService.dimensions.css.cell.width,this._renderService.dimensions.css.cell.height,i)}getMouseReportCoords(e,t){let n=(0,o.getCoordsRelativeToElement)(window,e,t);if(this._charSizeService.hasValidSize)return n[0]=Math.min(Math.max(n[0],0),this._renderService.dimensions.css.canvas.width-1),n[1]=Math.min(Math.max(n[1],0),this._renderService.dimensions.css.canvas.height-1),{col:Math.floor(n[0]/this._renderService.dimensions.css.cell.width),row:Math.floor(n[1]/this._renderService.dimensions.css.cell.height),x:Math.floor(n[0]),y:Math.floor(n[1])}}};t.MouseService=s,t.MouseService=s=r([i(0,a.IRenderService),i(1,a.ICharSizeService)],s)},5783:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.RenderService=void 0;let a=n(4852),o=n(7098),s=n(7150),c=n(6168),l=n(6501),u=n(802),d=class extends s.Disposable{get dimensions(){return this._renderer.value.dimensions}constructor(e,t,n,r,i,o,l,d,p){super(),this._rowCount=e,this._optionsService=n,this._charSizeService=r,this._coreService=i,this._coreBrowserService=d,this._renderer=this._register(new s.MutableDisposable),this._pausedResizeTask=new c.DebouncedIdleTask,this._observerDisposable=this._register(new s.MutableDisposable),this._isPaused=!1,this._needsFullRefresh=!1,this._isNextRenderRedrawOnly=!0,this._needsSelectionRefresh=!1,this._canvasWidth=0,this._canvasHeight=0,this._selectionState={start:void 0,end:void 0,columnSelectMode:!1},this._onDimensionsChange=this._register(new u.Emitter),this.onDimensionsChange=this._onDimensionsChange.event,this._onRenderedViewportChange=this._register(new u.Emitter),this.onRenderedViewportChange=this._onRenderedViewportChange.event,this._onRender=this._register(new u.Emitter),this.onRender=this._onRender.event,this._onRefreshRequest=this._register(new u.Emitter),this.onRefreshRequest=this._onRefreshRequest.event,this._renderDebouncer=new a.RenderDebouncer(((e,t)=>this._renderRows(e,t)),this._coreBrowserService),this._register(this._renderDebouncer),this._syncOutputHandler=new f(this._coreBrowserService,this._coreService,(()=>this._fullRefresh())),this._register((0,s.toDisposable)((()=>this._syncOutputHandler.dispose()))),this._register(this._coreBrowserService.onDprChange((()=>this.handleDevicePixelRatioChange()))),this._register(l.onResize((()=>this._fullRefresh()))),this._register(l.buffers.onBufferActivate((()=>this._renderer.value?.clear()))),this._register(this._optionsService.onOptionChange((()=>this._handleOptionsChanged()))),this._register(this._charSizeService.onCharSizeChange((()=>this.handleCharSizeChanged()))),this._register(o.onDecorationRegistered((()=>this._fullRefresh()))),this._register(o.onDecorationRemoved((()=>this._fullRefresh()))),this._register(this._optionsService.onMultipleOptionChange([`customGlyphs`,`drawBoldTextInBrightColors`,`letterSpacing`,`lineHeight`,`fontFamily`,`fontSize`,`fontWeight`,`fontWeightBold`,`minimumContrastRatio`,`rescaleOverlappingGlyphs`],(()=>{this.clear(),this.handleResize(l.cols,l.rows),this._fullRefresh()}))),this._register(this._optionsService.onMultipleOptionChange([`cursorBlink`,`cursorStyle`],(()=>this.refreshRows(l.buffer.y,l.buffer.y,!0)))),this._register(p.onChangeColors((()=>this._fullRefresh()))),this._registerIntersectionObserver(this._coreBrowserService.window,t),this._register(this._coreBrowserService.onWindowChange((e=>this._registerIntersectionObserver(e,t))))}_registerIntersectionObserver(e,t){if(`IntersectionObserver`in e){let n=new e.IntersectionObserver((e=>this._handleIntersectionChange(e[e.length-1])),{threshold:0});n.observe(t),this._observerDisposable.value=(0,s.toDisposable)((()=>n.disconnect()))}}_handleIntersectionChange(e){this._isPaused=e.isIntersecting===void 0?e.intersectionRatio===0:!e.isIntersecting,this._isPaused||this._charSizeService.hasValidSize||this._charSizeService.measure(),!this._isPaused&&this._needsFullRefresh&&(this._pausedResizeTask.flush(),this.refreshRows(0,this._rowCount-1),this._needsFullRefresh=!1)}refreshRows(e,t,n=!1){if(this._isPaused)return void(this._needsFullRefresh=!0);if(this._coreService.decPrivateModes.synchronizedOutput)return void this._syncOutputHandler.bufferRows(e,t);let r=this._syncOutputHandler.flush();r&&(e=Math.min(e,r.start),t=Math.max(t,r.end)),n||(this._isNextRenderRedrawOnly=!1),this._renderDebouncer.refresh(e,t,this._rowCount)}_renderRows(e,t){this._renderer.value&&(this._coreService.decPrivateModes.synchronizedOutput?this._syncOutputHandler.bufferRows(e,t):(e=Math.min(e,this._rowCount-1),t=Math.min(t,this._rowCount-1),this._renderer.value.renderRows(e,t),this._needsSelectionRefresh&&=(this._renderer.value.handleSelectionChanged(this._selectionState.start,this._selectionState.end,this._selectionState.columnSelectMode),!1),this._isNextRenderRedrawOnly||this._onRenderedViewportChange.fire({start:e,end:t}),this._onRender.fire({start:e,end:t}),this._isNextRenderRedrawOnly=!0))}resize(e,t){this._rowCount=t,this._fireOnCanvasResize()}_handleOptionsChanged(){this._renderer.value&&(this.refreshRows(0,this._rowCount-1),this._fireOnCanvasResize())}_fireOnCanvasResize(){this._renderer.value&&(this._renderer.value.dimensions.css.canvas.width===this._canvasWidth&&this._renderer.value.dimensions.css.canvas.height===this._canvasHeight||this._onDimensionsChange.fire(this._renderer.value.dimensions))}hasRenderer(){return!!this._renderer.value}setRenderer(e){this._renderer.value=e,this._renderer.value&&(this._renderer.value.onRequestRedraw((e=>this.refreshRows(e.start,e.end,!0))),this._needsSelectionRefresh=!0,this._fullRefresh())}addRefreshCallback(e){return this._renderDebouncer.addRefreshCallback(e)}_fullRefresh(){this._isPaused?this._needsFullRefresh=!0:this.refreshRows(0,this._rowCount-1)}clearTextureAtlas(){this._renderer.value&&(this._renderer.value.clearTextureAtlas?.(),this._fullRefresh())}handleDevicePixelRatioChange(){this._charSizeService.measure(),this._renderer.value&&(this._renderer.value.handleDevicePixelRatioChange(),this.refreshRows(0,this._rowCount-1))}handleResize(e,t){this._renderer.value&&(this._isPaused?this._pausedResizeTask.set((()=>this._renderer.value?.handleResize(e,t))):this._renderer.value.handleResize(e,t),this._fullRefresh())}handleCharSizeChanged(){this._renderer.value?.handleCharSizeChanged()}handleBlur(){this._renderer.value?.handleBlur()}handleFocus(){this._renderer.value?.handleFocus()}handleSelectionChanged(e,t,n){this._selectionState.start=e,this._selectionState.end=t,this._selectionState.columnSelectMode=n,this._renderer.value?.handleSelectionChanged(e,t,n)}handleCursorMove(){this._renderer.value?.handleCursorMove()}clear(){this._renderer.value?.clear()}};t.RenderService=d,t.RenderService=d=r([i(2,l.IOptionsService),i(3,o.ICharSizeService),i(4,l.ICoreService),i(5,l.IDecorationService),i(6,l.IBufferService),i(7,o.ICoreBrowserService),i(8,o.IThemeService)],d);class f{constructor(e,t,n){this._coreBrowserService=e,this._coreService=t,this._onTimeout=n,this._start=0,this._end=0,this._isBuffering=!1}bufferRows(e,t){this._isBuffering?(this._start=Math.min(this._start,e),this._end=Math.max(this._end,t)):(this._start=e,this._end=t,this._isBuffering=!0),this._timeout===void 0&&(this._timeout=this._coreBrowserService.window.setTimeout((()=>{this._timeout=void 0,this._coreService.decPrivateModes.synchronizedOutput=!1,this._onTimeout()}),1e3))}flush(){if(this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0),!this._isBuffering)return;let e={start:this._start,end:this._end};return this._isBuffering=!1,e}dispose(){this._timeout!==void 0&&(this._coreBrowserService.window.clearTimeout(this._timeout),this._timeout=void 0)}}},2079:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.SelectionService=void 0;let a=n(5251),o=n(9686),s=n(5959),c=n(7098),l=n(7150),u=n(701),d=n(9384),f=n(3055),p=n(6501),m=n(802),h=/* @__PURE__ */ RegExp(`\xA0`,`g`),g=class extends l.Disposable{constructor(e,t,n,r,i,a,o,c,u){super(),this._element=e,this._screenElement=t,this._linkifier=n,this._bufferService=r,this._coreService=i,this._mouseService=a,this._optionsService=o,this._renderService=c,this._coreBrowserService=u,this._dragScrollAmount=0,this._enabled=!0,this._workCell=new f.CellData,this._mouseDownTimeStamp=0,this._oldHasSelection=!1,this._oldSelectionStart=void 0,this._oldSelectionEnd=void 0,this._onLinuxMouseSelection=this._register(new m.Emitter),this.onLinuxMouseSelection=this._onLinuxMouseSelection.event,this._onRedrawRequest=this._register(new m.Emitter),this.onRequestRedraw=this._onRedrawRequest.event,this._onSelectionChange=this._register(new m.Emitter),this.onSelectionChange=this._onSelectionChange.event,this._onRequestScrollLines=this._register(new m.Emitter),this.onRequestScrollLines=this._onRequestScrollLines.event,this._mouseMoveListener=e=>this._handleMouseMove(e),this._mouseUpListener=e=>this._handleMouseUp(e),this._coreService.onUserInput((()=>{this.hasSelection&&this.clearSelection()})),this._trimListener=this._bufferService.buffer.lines.onTrim((e=>this._handleTrim(e))),this._register(this._bufferService.buffers.onBufferActivate((e=>this._handleBufferActivate(e)))),this.enable(),this._model=new s.SelectionModel(this._bufferService),this._activeSelectionMode=0,this._register((0,l.toDisposable)((()=>{this._removeMouseDownListeners()}))),this._register(this._bufferService.onResize((e=>{e.rowsChanged&&this.clearSelection()})))}reset(){this.clearSelection()}disable(){this.clearSelection(),this._enabled=!1}enable(){this._enabled=!0}get selectionStart(){return this._model.finalSelectionStart}get selectionEnd(){return this._model.finalSelectionEnd}get hasSelection(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;return!(!e||!t||e[0]===t[0]&&e[1]===t[1])}get selectionText(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd;if(!e||!t)return``;let n=this._bufferService.buffer,r=[];if(this._activeSelectionMode===3){if(e[0]===t[0])return``;let i=e[0]e.replace(h,` `))).join(u.isWindows?`\r +`:` +`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh())),u.isLinux&&e&&this.selectionText.length&&this._onLinuxMouseSelection.fire(this.selectionText)}_refresh(){this._refreshAnimationFrame=void 0,this._onRedrawRequest.fire({start:this._model.finalSelectionStart,end:this._model.finalSelectionEnd,columnSelectMode:this._activeSelectionMode===3})}_isClickInSelection(e){let t=this._getMouseBufferCoords(e),n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!!(n&&r&&t)&&this._areCoordsInSelection(t,n,r)}isCellInSelection(e,t){let n=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!(!n||!r)&&this._areCoordsInSelection([e,t],n,r)}_areCoordsInSelection(e,t,n){return e[1]>t[1]&&e[1]=t[0]&&e[0]=t[0]}_selectWordAtCursor(e,t){let n=this._linkifier.currentLink?.link?.range;if(n)return this._model.selectionStart=[n.start.x-1,n.start.y-1],this._model.selectionStartLength=(0,d.getRangeLength)(n,this._bufferService.cols),this._model.selectionEnd=void 0,!0;let r=this._getMouseBufferCoords(e);return!!r&&(this._selectWordAt(r,t),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(e,t){this._model.clearSelection(),e=Math.max(e,0),t=Math.min(t,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,e],this._model.selectionEnd=[this._bufferService.cols,t],this.refresh(),this._onSelectionChange.fire()}_handleTrim(e){this._model.handleTrim(e)&&this.refresh()}_getMouseBufferCoords(e){let t=this._mouseService.getCoords(e,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=(0,a.getCoordsRelativeToElement)(this._coreBrowserService.window,e,this._screenElement)[1],n=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=n?0:(t>n&&(t-=n),t=Math.min(Math.max(t,-50),50),t/=50,t/Math.abs(t)+Math.round(14*t))}shouldForceSelection(e){return u.isMac?e.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:e.shiftKey}handleMouseDown(e){if(this._mouseDownTimeStamp=e.timeStamp,(e.button!==2||!this.hasSelection)&&e.button===0){if(!this._enabled){if(!this.shouldForceSelection(e))return;e.stopPropagation()}e.preventDefault(),this._dragScrollAmount=0,this._enabled&&e.shiftKey?this._handleIncrementalClick(e):e.detail===1?this._handleSingleClick(e):e.detail===2?this._handleDoubleClick(e):e.detail===3&&this._handleTripleClick(e),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener(`mouseup`,this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval((()=>this._dragScroll()),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener(`mousemove`,this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener(`mouseup`,this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(e){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(e))}_handleSingleClick(e){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(e)?3:0,this._model.selectionStart=this._getMouseBufferCoords(e),!this._model.selectionStart)return;this._model.selectionEnd=void 0;let t=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);t&&t.length!==this._model.selectionStart[0]&&t.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(e){this._selectWordAtCursor(e,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(u.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(e){if(e.stopImmediatePropagation(),!this._model.selectionStart)return;let t=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(e),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]0?this._model.selectionEnd[0]=this._bufferService.cols:this._dragScrollAmount<0&&(this._model.selectionEnd[0]=0));let n=this._bufferService.buffer;if(this._model.selectionEnd[1]0?(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=this._bufferService.cols),this._model.selectionEnd[1]=Math.min(e.ydisp+this._bufferService.rows,e.lines.length-1)):(this._activeSelectionMode!==3&&(this._model.selectionEnd[0]=0),this._model.selectionEnd[1]=e.ydisp),this.refresh()}}_handleMouseUp(e){let t=e.timeStamp-this._mouseDownTimeStamp;if(this._removeMouseDownListeners(),this.selectionText.length<=1&&t<500&&e.altKey&&this._optionsService.rawOptions.altClickMovesCursor){if(this._bufferService.buffer.ybase===this._bufferService.buffer.ydisp){let t=this._mouseService.getCoords(e,this._element,this._bufferService.cols,this._bufferService.rows,!1);if(t&&t[0]!==void 0&&t[1]!==void 0){let e=(0,o.moveToCellSequence)(t[0]-1,t[1]-1,this._bufferService,this._coreService.decPrivateModes.applicationCursorKeys);this._coreService.triggerDataEvent(e,!0)}}}else this._fireEventIfSelectionChanged()}_fireEventIfSelectionChanged(){let e=this._model.finalSelectionStart,t=this._model.finalSelectionEnd,n=!(!e||!t||e[0]===t[0]&&e[1]===t[1]);n?e&&t&&(this._oldSelectionStart&&this._oldSelectionEnd&&e[0]===this._oldSelectionStart[0]&&e[1]===this._oldSelectionStart[1]&&t[0]===this._oldSelectionEnd[0]&&t[1]===this._oldSelectionEnd[1]||this._fireOnSelectionChange(e,t,n)):this._oldHasSelection&&this._fireOnSelectionChange(e,t,n)}_fireOnSelectionChange(e,t,n){this._oldSelectionStart=e,this._oldSelectionEnd=t,this._oldHasSelection=n,this._onSelectionChange.fire()}_handleBufferActivate(e){this.clearSelection(),this._trimListener.dispose(),this._trimListener=e.activeBuffer.lines.onTrim((e=>this._handleTrim(e)))}_convertViewportColToCharacterIndex(e,t){let n=t;for(let r=0;t>=r;r++){let i=e.loadCell(r,this._workCell).getChars().length;this._workCell.getWidth()===0?n--:i>1&&t!==r&&(n+=i-1)}return n}setSelection(e,t,n){this._model.clearSelection(),this._removeMouseDownListeners(),this._model.selectionStart=[e,t],this._model.selectionStartLength=n,this.refresh(),this._fireEventIfSelectionChanged()}rightClickSelect(e){this._isClickInSelection(e)||(this._selectWordAtCursor(e,!1)&&this.refresh(!0),this._fireEventIfSelectionChanged())}_getWordAt(e,t,n=!0,r=!0){if(e[0]>=this._bufferService.cols)return;let i=this._bufferService.buffer,a=i.lines.get(e[1]);if(!a)return;let o=i.translateBufferLineToString(e[1],!1),s=this._convertViewportColToCharacterIndex(a,e[0]),c=s,l=e[0]-s,u=0,d=0,f=0,p=0;if(o.charAt(s)===` `){for(;s>0&&o.charAt(s-1)===` `;)s--;for(;c1&&(p+=r-1,c+=r-1);t>0&&s>0&&!this._isCharWordSeparator(a.loadCell(t-1,this._workCell));){a.loadCell(t-1,this._workCell);let e=this._workCell.getChars().length;this._workCell.getWidth()===0?(u++,t--):e>1&&(f+=e-1,s-=e-1),s--,t--}for(;n1&&(p+=e-1,c+=e-1),c++,n++}}c++;let m=s+l-u+f,h=Math.min(this._bufferService.cols,c-s+u+d-f-p);if(t||o.slice(s,c).trim()!==``){if(n&&m===0&&a.getCodePoint(0)!==32){let t=i.lines.get(e[1]-1);if(t&&a.isWrapped&&t.getCodePoint(this._bufferService.cols-1)!==32){let t=this._getWordAt([this._bufferService.cols-1,e[1]-1],!1,!0,!1);if(t){let e=this._bufferService.cols-t.start;m-=e,h+=e}}}if(r&&m+h===this._bufferService.cols&&a.getCodePoint(this._bufferService.cols-1)!==32){let t=i.lines.get(e[1]+1);if(t?.isWrapped&&t.getCodePoint(0)!==32){let t=this._getWordAt([0,e[1]+1],!1,!1,!0);t&&(h+=t.length)}}return{start:m,length:h}}}_selectWordAt(e,t){let n=this._getWordAt(e,t);if(n){for(;n.start<0;)n.start+=this._bufferService.cols,e[1]--;this._model.selectionStart=[n.start,e[1]],this._model.selectionStartLength=n.length}}_selectToWordAt(e){let t=this._getWordAt(e,!0);if(t){let n=e[1];for(;t.start<0;)t.start+=this._bufferService.cols,n--;if(!this._model.areSelectionValuesReversed())for(;t.start+t.length>this._bufferService.cols;)t.length-=this._bufferService.cols,n++;this._model.selectionEnd=[this._model.areSelectionValuesReversed()?t.start:t.start+t.length,n]}}_isCharWordSeparator(e){return e.getWidth()!==0&&this._optionsService.rawOptions.wordSeparator.indexOf(e.getChars())>=0}_selectLineAt(e){let t=this._bufferService.buffer.getWrappedRangeForLine(e),n={start:{x:0,y:t.first},end:{x:this._bufferService.cols-1,y:t.last}};this._model.selectionStart=[0,t.first],this._model.selectionEnd=void 0,this._model.selectionStartLength=(0,d.getRangeLength)(n,this._bufferService.cols)}};t.SelectionService=g,t.SelectionService=g=r([i(3,p.IBufferService),i(4,p.ICoreService),i(5,c.IMouseService),i(6,p.IOptionsService),i(7,c.IRenderService),i(8,c.ICoreBrowserService)],g)},7098:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ILinkProviderService=t.IThemeService=t.ICharacterJoinerService=t.ISelectionService=t.IRenderService=t.IMouseService=t.ICoreBrowserService=t.ICharSizeService=void 0;let r=n(6201);t.ICharSizeService=(0,r.createDecorator)(`CharSizeService`),t.ICoreBrowserService=(0,r.createDecorator)(`CoreBrowserService`),t.IMouseService=(0,r.createDecorator)(`MouseService`),t.IRenderService=(0,r.createDecorator)(`RenderService`),t.ISelectionService=(0,r.createDecorator)(`SelectionService`),t.ICharacterJoinerService=(0,r.createDecorator)(`CharacterJoinerService`),t.IThemeService=(0,r.createDecorator)(`ThemeService`),t.ILinkProviderService=(0,r.createDecorator)(`LinkProviderService`)},9078:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.ThemeService=void 0;let a=n(7174),o=n(9302),s=n(4103),c=n(7150),l=n(6501),u=n(802),d=s.css.toColor(`#ffffff`),f=s.css.toColor(`#000000`),p=s.css.toColor(`#ffffff`),m=f,h={css:`rgba(255, 255, 255, 0.3)`,rgba:4294967117},g=d,_=class extends c.Disposable{get colors(){return this._colors}constructor(e){super(),this._optionsService=e,this._contrastCache=new a.ColorContrastCache,this._halfContrastCache=new a.ColorContrastCache,this._onChangeColors=this._register(new u.Emitter),this.onChangeColors=this._onChangeColors.event,this._colors={foreground:d,background:f,cursor:p,cursorAccent:m,selectionForeground:void 0,selectionBackgroundTransparent:h,selectionBackgroundOpaque:s.color.blend(f,h),selectionInactiveBackgroundTransparent:h,selectionInactiveBackgroundOpaque:s.color.blend(f,h),scrollbarSliderBackground:s.color.opacity(d,.2),scrollbarSliderHoverBackground:s.color.opacity(d,.4),scrollbarSliderActiveBackground:s.color.opacity(d,.5),overviewRulerBorder:d,ansi:o.DEFAULT_ANSI_COLORS.slice(),contrastCache:this._contrastCache,halfContrastCache:this._halfContrastCache},this._updateRestoreColors(),this._setTheme(this._optionsService.rawOptions.theme),this._register(this._optionsService.onSpecificOptionChange(`minimumContrastRatio`,(()=>this._contrastCache.clear()))),this._register(this._optionsService.onSpecificOptionChange(`theme`,(()=>this._setTheme(this._optionsService.rawOptions.theme))))}_setTheme(e={}){let t=this._colors;if(t.foreground=v(e.foreground,d),t.background=v(e.background,f),t.cursor=s.color.blend(t.background,v(e.cursor,p)),t.cursorAccent=s.color.blend(t.background,v(e.cursorAccent,m)),t.selectionBackgroundTransparent=v(e.selectionBackground,h),t.selectionBackgroundOpaque=s.color.blend(t.background,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundTransparent=v(e.selectionInactiveBackground,t.selectionBackgroundTransparent),t.selectionInactiveBackgroundOpaque=s.color.blend(t.background,t.selectionInactiveBackgroundTransparent),t.selectionForeground=e.selectionForeground?v(e.selectionForeground,s.NULL_COLOR):void 0,t.selectionForeground===s.NULL_COLOR&&(t.selectionForeground=void 0),s.color.isOpaque(t.selectionBackgroundTransparent)&&(t.selectionBackgroundTransparent=s.color.opacity(t.selectionBackgroundTransparent,.3)),s.color.isOpaque(t.selectionInactiveBackgroundTransparent)&&(t.selectionInactiveBackgroundTransparent=s.color.opacity(t.selectionInactiveBackgroundTransparent,.3)),t.scrollbarSliderBackground=v(e.scrollbarSliderBackground,s.color.opacity(t.foreground,.2)),t.scrollbarSliderHoverBackground=v(e.scrollbarSliderHoverBackground,s.color.opacity(t.foreground,.4)),t.scrollbarSliderActiveBackground=v(e.scrollbarSliderActiveBackground,s.color.opacity(t.foreground,.5)),t.overviewRulerBorder=v(e.overviewRulerBorder,g),t.ansi=o.DEFAULT_ANSI_COLORS.slice(),t.ansi[0]=v(e.black,o.DEFAULT_ANSI_COLORS[0]),t.ansi[1]=v(e.red,o.DEFAULT_ANSI_COLORS[1]),t.ansi[2]=v(e.green,o.DEFAULT_ANSI_COLORS[2]),t.ansi[3]=v(e.yellow,o.DEFAULT_ANSI_COLORS[3]),t.ansi[4]=v(e.blue,o.DEFAULT_ANSI_COLORS[4]),t.ansi[5]=v(e.magenta,o.DEFAULT_ANSI_COLORS[5]),t.ansi[6]=v(e.cyan,o.DEFAULT_ANSI_COLORS[6]),t.ansi[7]=v(e.white,o.DEFAULT_ANSI_COLORS[7]),t.ansi[8]=v(e.brightBlack,o.DEFAULT_ANSI_COLORS[8]),t.ansi[9]=v(e.brightRed,o.DEFAULT_ANSI_COLORS[9]),t.ansi[10]=v(e.brightGreen,o.DEFAULT_ANSI_COLORS[10]),t.ansi[11]=v(e.brightYellow,o.DEFAULT_ANSI_COLORS[11]),t.ansi[12]=v(e.brightBlue,o.DEFAULT_ANSI_COLORS[12]),t.ansi[13]=v(e.brightMagenta,o.DEFAULT_ANSI_COLORS[13]),t.ansi[14]=v(e.brightCyan,o.DEFAULT_ANSI_COLORS[14]),t.ansi[15]=v(e.brightWhite,o.DEFAULT_ANSI_COLORS[15]),e.extendedAnsi){let n=Math.min(t.ansi.length-16,e.extendedAnsi.length);for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.CircularList=void 0;let r=n(7150),i=n(802);class a extends r.Disposable{constructor(e){super(),this._maxLength=e,this.onDeleteEmitter=this._register(new i.Emitter),this.onDelete=this.onDeleteEmitter.event,this.onInsertEmitter=this._register(new i.Emitter),this.onInsert=this.onInsertEmitter.event,this.onTrimEmitter=this._register(new i.Emitter),this.onTrim=this.onTrimEmitter.event,this._array=Array(this._maxLength),this._startIndex=0,this._length=0}get maxLength(){return this._maxLength}set maxLength(e){if(this._maxLength===e)return;let t=Array(e);for(let n=0;nthis._length)for(let t=this._length;t=e;t--)this._array[this._getCyclicIndex(t+n.length)]=this._array[this._getCyclicIndex(t)];for(let t=0;tthis._maxLength){let e=this._length+n.length-this._maxLength;this._startIndex+=e,this._length=this._maxLength,this.onTrimEmitter.fire(e)}else this._length+=n.length}trimStart(e){e>this._length&&(e=this._length),this._startIndex+=e,this._length-=e,this.onTrimEmitter.fire(e)}shiftElements(e,t,n){if(!(t<=0)){if(e<0||e>=this._length)throw Error(`start argument out of range`);if(e+n<0)throw Error(`Cannot shift elements in list beyond index 0`);if(n>0){for(let r=t-1;r>=0;r--)this.set(e+r+n,this.get(e+r));let r=e+t+n-this._length;if(r>0)for(this._length+=r;this._length>this._maxLength;)this._length--,this._startIndex++,this.onTrimEmitter.fire(1)}else for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.clone=function e(t,n=5){if(typeof t!=`object`)return t;let r=Array.isArray(t)?[]:{};for(let i in t)r[i]=n<=1?t[i]:t[i]&&e(t[i],n-1);return r}},4103:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.rgba=t.rgb=t.css=t.color=t.channels=t.NULL_COLOR=void 0,t.toPaddedHex=d,t.contrastRatio=f;let n=0,r=0,i=0,a=0;var o,s,c,l,u;function d(e){let t=e.toString(16);return t.length<2?`0`+t:t}function f(e,t){return e>>0},e.toColor=function(t,n,r,i){return{css:e.toCss(t,n,r,i),rgba:e.toRgba(t,n,r,i)}}}(o||(t.channels=o={})),function(e){function t(e,t){return a=Math.round(255*t),[n,r,i]=u.toChannels(e.rgba),{css:o.toCss(n,r,i,a),rgba:o.toRgba(n,r,i,a)}}e.blend=function(e,t){if(a=(255&t.rgba)/255,a===1)return{css:t.css,rgba:t.rgba};let s=t.rgba>>24&255,c=t.rgba>>16&255,l=t.rgba>>8&255,u=e.rgba>>24&255,d=e.rgba>>16&255,f=e.rgba>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),{css:o.toCss(n,r,i),rgba:o.toRgba(n,r,i)}},e.isOpaque=function(e){return!(255&~e.rgba)},e.ensureContrastRatio=function(e,t,n){let r=u.ensureContrastRatio(e.rgba,t.rgba,n);if(r)return o.toColor(r>>24&255,r>>16&255,r>>8&255)},e.opaque=function(e){let t=(255|e.rgba)>>>0;return[n,r,i]=u.toChannels(t),{css:o.toCss(n,r,i),rgba:t}},e.opacity=t,e.multiplyOpacity=function(e,n){return a=255&e.rgba,t(e,a*n/255)},e.toColorRGB=function(e){return[e.rgba>>24&255,e.rgba>>16&255,e.rgba>>8&255]}}(s||(t.color=s={})),function(e){let t,s;try{let e=document.createElement(`canvas`);e.width=1,e.height=1;let n=e.getContext(`2d`,{willReadFrequently:!0});n&&(t=n,t.globalCompositeOperation=`copy`,s=t.createLinearGradient(0,0,1,1))}catch{}e.toColor=function(e){if(e.match(/#[\da-f]{3,8}/i))switch(e.length){case 4:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),o.toColor(n,r,i);case 5:return n=parseInt(e.slice(1,2).repeat(2),16),r=parseInt(e.slice(2,3).repeat(2),16),i=parseInt(e.slice(3,4).repeat(2),16),a=parseInt(e.slice(4,5).repeat(2),16),o.toColor(n,r,i,a);case 7:return{css:e,rgba:(parseInt(e.slice(1),16)<<8|255)>>>0};case 9:return{css:e,rgba:parseInt(e.slice(1),16)>>>0}}let c=e.match(/rgba?\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*(,\s*(0|1|\d?\.(\d+))\s*)?\)/);if(c)return n=parseInt(c[1]),r=parseInt(c[2]),i=parseInt(c[3]),a=Math.round(255*(c[5]===void 0?1:parseFloat(c[5]))),o.toColor(n,r,i,a);if(!t||!s||(t.fillStyle=s,t.fillStyle=e,typeof t.fillStyle!=`string`)||(t.fillRect(0,0,1,1),[n,r,i,a]=t.getImageData(0,0,1,1).data,a!==255))throw Error(`css.toColor: Unsupported css format`);return{rgba:o.toRgba(n,r,i,a),css:e}}}(c||(t.css=c={})),function(e){function t(e,t,n){let r=e/255,i=t/255,a=n/255;return .2126*(r<=.03928?r/12.92:((r+.055)/1.055)**2.4)+.7152*(i<=.03928?i/12.92:((i+.055)/1.055)**2.4)+.0722*(a<=.03928?a/12.92:((a+.055)/1.055)**2.4)}e.relativeLuminance=function(e){return t(e>>16&255,e>>8&255,255&e)},e.relativeLuminance2=t}(l||(t.rgb=l={})),function(e){function t(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u0||s>0||c>0);)o-=Math.max(0,Math.ceil(.1*o)),s-=Math.max(0,Math.ceil(.1*s)),c-=Math.max(0,Math.ceil(.1*c)),u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));return(o<<24|s<<16|c<<8|255)>>>0}function s(e,t,n){let r=e>>24&255,i=e>>16&255,a=e>>8&255,o=t>>24&255,s=t>>16&255,c=t>>8&255,u=f(l.relativeLuminance2(o,s,c),l.relativeLuminance2(r,i,a));for(;u>>0}e.blend=function(e,t){if(a=(255&t)/255,a===1)return t;let s=t>>24&255,c=t>>16&255,l=t>>8&255,u=e>>24&255,d=e>>16&255,f=e>>8&255;return n=u+Math.round((s-u)*a),r=d+Math.round((c-d)*a),i=f+Math.round((l-f)*a),o.toRgba(n,r,i)},e.ensureContrastRatio=function(e,n,r){let i=l.relativeLuminance(e>>8),a=l.relativeLuminance(n>>8);if(f(i,a)>8));if(of(i,l.relativeLuminance(t>>8))?a:t}return a}let o=s(e,n,r),c=f(i,l.relativeLuminance(o>>8));if(cf(i,l.relativeLuminance(a>>8))?o:a}return o}},e.reduceLuminance=t,e.increaseLuminance=s,e.toChannels=function(e){return[e>>24&255,e>>16&255,e>>8&255,255&e]}}(u||(t.rgba=u={}))},5777:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CoreTerminal=void 0;let r=n(6501),i=n(6025),a=n(7276),o=n(9640),s=n(56),c=n(4071),l=n(7792),u=n(6415),d=n(5746),f=n(5882),p=n(2486),m=n(3562),h=n(8811),g=n(802),_=n(7150),v=!1;class y extends _.Disposable{get onScroll(){return this._onScrollApi||(this._onScrollApi=this._register(new g.Emitter),this._onScroll.event((e=>{this._onScrollApi?.fire(e.position)}))),this._onScrollApi.event}get cols(){return this._bufferService.cols}get rows(){return this._bufferService.rows}get buffers(){return this._bufferService.buffers}get options(){return this.optionsService.options}set options(e){for(let t in e)this.optionsService.options[t]=e[t]}constructor(e){super(),this._windowsWrappingHeuristics=this._register(new _.MutableDisposable),this._onBinary=this._register(new g.Emitter),this.onBinary=this._onBinary.event,this._onData=this._register(new g.Emitter),this.onData=this._onData.event,this._onLineFeed=this._register(new g.Emitter),this.onLineFeed=this._onLineFeed.event,this._onResize=this._register(new g.Emitter),this.onResize=this._onResize.event,this._onWriteParsed=this._register(new g.Emitter),this.onWriteParsed=this._onWriteParsed.event,this._onScroll=this._register(new g.Emitter),this._instantiationService=new i.InstantiationService,this.optionsService=this._register(new s.OptionsService(e)),this._instantiationService.setService(r.IOptionsService,this.optionsService),this._bufferService=this._register(this._instantiationService.createInstance(o.BufferService)),this._instantiationService.setService(r.IBufferService,this._bufferService),this._logService=this._register(this._instantiationService.createInstance(a.LogService)),this._instantiationService.setService(r.ILogService,this._logService),this.coreService=this._register(this._instantiationService.createInstance(c.CoreService)),this._instantiationService.setService(r.ICoreService,this.coreService),this.coreMouseService=this._register(this._instantiationService.createInstance(l.CoreMouseService)),this._instantiationService.setService(r.ICoreMouseService,this.coreMouseService),this.unicodeService=this._register(this._instantiationService.createInstance(u.UnicodeService)),this._instantiationService.setService(r.IUnicodeService,this.unicodeService),this._charsetService=this._instantiationService.createInstance(d.CharsetService),this._instantiationService.setService(r.ICharsetService,this._charsetService),this._oscLinkService=this._instantiationService.createInstance(h.OscLinkService),this._instantiationService.setService(r.IOscLinkService,this._oscLinkService),this._inputHandler=this._register(new p.InputHandler(this._bufferService,this._charsetService,this.coreService,this._logService,this.optionsService,this._oscLinkService,this.coreMouseService,this.unicodeService)),this._register(g.Event.forward(this._inputHandler.onLineFeed,this._onLineFeed)),this._register(this._inputHandler),this._register(g.Event.forward(this._bufferService.onResize,this._onResize)),this._register(g.Event.forward(this.coreService.onData,this._onData)),this._register(g.Event.forward(this.coreService.onBinary,this._onBinary)),this._register(this.coreService.onRequestScrollToBottom((()=>this.scrollToBottom(!0)))),this._register(this.coreService.onUserInput((()=>this._writeBuffer.handleUserInput()))),this._register(this.optionsService.onMultipleOptionChange([`windowsMode`,`windowsPty`],(()=>this._handleWindowsPtyOptionChange()))),this._register(this._bufferService.onScroll((()=>{this._onScroll.fire({position:this._bufferService.buffer.ydisp}),this._inputHandler.markRangeDirty(this._bufferService.buffer.scrollTop,this._bufferService.buffer.scrollBottom)}))),this._writeBuffer=this._register(new m.WriteBuffer(((e,t)=>this._inputHandler.parse(e,t)))),this._register(g.Event.forward(this._writeBuffer.onWriteParsed,this._onWriteParsed))}write(e,t){this._writeBuffer.write(e,t)}writeSync(e,t){this._logService.logLevel<=r.LogLevelEnum.WARN&&!v&&(this._logService.warn(`writeSync is unreliable and will be removed soon.`),v=!0),this._writeBuffer.writeSync(e,t)}input(e,t=!0){this.coreService.triggerDataEvent(e,t)}resize(e,t){isNaN(e)||isNaN(t)||(e=Math.max(e,o.MINIMUM_COLS),t=Math.max(t,o.MINIMUM_ROWS),this._bufferService.resize(e,t))}scroll(e,t=!1){this._bufferService.scroll(e,t)}scrollLines(e,t){this._bufferService.scrollLines(e,t)}scrollPages(e){this.scrollLines(e*(this.rows-1))}scrollToTop(){this.scrollLines(-this._bufferService.buffer.ydisp)}scrollToBottom(e){this.scrollLines(this._bufferService.buffer.ybase-this._bufferService.buffer.ydisp)}scrollToLine(e){let t=e-this._bufferService.buffer.ydisp;t!==0&&this.scrollLines(t)}registerEscHandler(e,t){return this._inputHandler.registerEscHandler(e,t)}registerDcsHandler(e,t){return this._inputHandler.registerDcsHandler(e,t)}registerCsiHandler(e,t){return this._inputHandler.registerCsiHandler(e,t)}registerOscHandler(e,t){return this._inputHandler.registerOscHandler(e,t)}_setup(){this._handleWindowsPtyOptionChange()}reset(){this._inputHandler.reset(),this._bufferService.reset(),this._charsetService.reset(),this.coreService.reset(),this.coreMouseService.reset()}_handleWindowsPtyOptionChange(){let e=!1,t=this.optionsService.rawOptions.windowsPty;t&&t.buildNumber!==void 0&&t.buildNumber!==void 0?e=t.backend===`conpty`&&t.buildNumber<21376:this.optionsService.rawOptions.windowsMode&&(e=!0),e?this._enableWindowsWrappingHeuristics():this._windowsWrappingHeuristics.clear()}_enableWindowsWrappingHeuristics(){if(!this._windowsWrappingHeuristics.value){let e=[];e.push(this.onLineFeed(f.updateWindowsModeWrappedState.bind(null,this._bufferService))),e.push(this.registerCsiHandler({final:`H`},(()=>((0,f.updateWindowsModeWrappedState)(this._bufferService),!1)))),this._windowsWrappingHeuristics.value=(0,_.toDisposable)((()=>{for(let t of e)t.dispose()}))}}}t.CoreTerminal=y},2486:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.InputHandler=t.WindowsOptionsReportType=void 0,t.isValidColorIndex=D;let a=n(3534),o=n(6760),s=n(6717),c=n(7150),l=n(726),u=n(6107),d=n(8938),f=n(3055),p=n(5451),m=n(6501),h=n(6415),g=n(1346),_=n(9823),v=n(8693),y=n(802),b={"(":0,")":1,"*":2,"+":3,"-":1,".":2},x=131072;function S(e,t){if(e>24)return t.setWinLines||!1;switch(e){case 1:return!!t.restoreWin;case 2:return!!t.minimizeWin;case 3:return!!t.setWinPosition;case 4:return!!t.setWinSizePixels;case 5:return!!t.raiseWin;case 6:return!!t.lowerWin;case 7:return!!t.refreshWin;case 8:return!!t.setWinSizeChars;case 9:return!!t.maximizeWin;case 10:return!!t.fullscreenWin;case 11:return!!t.getWinState;case 13:return!!t.getWinPosition;case 14:return!!t.getWinSizePixels;case 15:return!!t.getScreenSizePixels;case 16:return!!t.getCellSizePixels;case 18:return!!t.getWinSizeChars;case 19:return!!t.getScreenSizeChars;case 20:return!!t.getIconTitle;case 21:return!!t.getWinTitle;case 22:return!!t.pushTitle;case 23:return!!t.popTitle;case 24:return!!t.setWinLines}return!1}var C;(function(e){e[e.GET_WIN_SIZE_PIXELS=0]=`GET_WIN_SIZE_PIXELS`,e[e.GET_CELL_SIZE_PIXELS=1]=`GET_CELL_SIZE_PIXELS`})(C||(t.WindowsOptionsReportType=C={}));let w=0;class T extends c.Disposable{getAttrData(){return this._curAttrData}constructor(e,t,n,r,i,c,d,f,p=new s.EscapeSequenceParser){super(),this._bufferService=e,this._charsetService=t,this._coreService=n,this._logService=r,this._optionsService=i,this._oscLinkService=c,this._coreMouseService=d,this._unicodeService=f,this._parser=p,this._parseBuffer=/* @__PURE__ */ new Uint32Array(4096),this._stringDecoder=new l.StringToUtf32,this._utf8Decoder=new l.Utf8ToUtf32,this._windowTitle=``,this._iconName=``,this._windowTitleStack=[],this._iconNameStack=[],this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone(),this._onRequestBell=this._register(new y.Emitter),this.onRequestBell=this._onRequestBell.event,this._onRequestRefreshRows=this._register(new y.Emitter),this.onRequestRefreshRows=this._onRequestRefreshRows.event,this._onRequestReset=this._register(new y.Emitter),this.onRequestReset=this._onRequestReset.event,this._onRequestSendFocus=this._register(new y.Emitter),this.onRequestSendFocus=this._onRequestSendFocus.event,this._onRequestSyncScrollBar=this._register(new y.Emitter),this.onRequestSyncScrollBar=this._onRequestSyncScrollBar.event,this._onRequestWindowsOptionsReport=this._register(new y.Emitter),this.onRequestWindowsOptionsReport=this._onRequestWindowsOptionsReport.event,this._onA11yChar=this._register(new y.Emitter),this.onA11yChar=this._onA11yChar.event,this._onA11yTab=this._register(new y.Emitter),this.onA11yTab=this._onA11yTab.event,this._onCursorMove=this._register(new y.Emitter),this.onCursorMove=this._onCursorMove.event,this._onLineFeed=this._register(new y.Emitter),this.onLineFeed=this._onLineFeed.event,this._onScroll=this._register(new y.Emitter),this.onScroll=this._onScroll.event,this._onTitleChange=this._register(new y.Emitter),this.onTitleChange=this._onTitleChange.event,this._onColor=this._register(new y.Emitter),this.onColor=this._onColor.event,this._parseStack={paused:!1,cursorStartX:0,cursorStartY:0,decodedLength:0,position:0},this._specialColors=[256,257,258],this._register(this._parser),this._dirtyRowTracker=new E(this._bufferService),this._activeBuffer=this._bufferService.buffer,this._register(this._bufferService.buffers.onBufferActivate((e=>this._activeBuffer=e.activeBuffer))),this._parser.setCsiHandlerFallback(((e,t)=>{this._logService.debug(`Unknown CSI code: `,{identifier:this._parser.identToString(e),params:t.toArray()})})),this._parser.setEscHandlerFallback((e=>{this._logService.debug(`Unknown ESC code: `,{identifier:this._parser.identToString(e)})})),this._parser.setExecuteHandlerFallback((e=>{this._logService.debug(`Unknown EXECUTE code: `,{code:e})})),this._parser.setOscHandlerFallback(((e,t,n)=>{this._logService.debug(`Unknown OSC code: `,{identifier:e,action:t,data:n})})),this._parser.setDcsHandlerFallback(((e,t,n)=>{t===`HOOK`&&(n=n.toArray()),this._logService.debug(`Unknown DCS code: `,{identifier:this._parser.identToString(e),action:t,payload:n})})),this._parser.setPrintHandler(((e,t,n)=>this.print(e,t,n))),this._parser.registerCsiHandler({final:`@`},(e=>this.insertChars(e))),this._parser.registerCsiHandler({intermediates:` `,final:`@`},(e=>this.scrollLeft(e))),this._parser.registerCsiHandler({final:`A`},(e=>this.cursorUp(e))),this._parser.registerCsiHandler({intermediates:` `,final:`A`},(e=>this.scrollRight(e))),this._parser.registerCsiHandler({final:`B`},(e=>this.cursorDown(e))),this._parser.registerCsiHandler({final:`C`},(e=>this.cursorForward(e))),this._parser.registerCsiHandler({final:`D`},(e=>this.cursorBackward(e))),this._parser.registerCsiHandler({final:`E`},(e=>this.cursorNextLine(e))),this._parser.registerCsiHandler({final:`F`},(e=>this.cursorPrecedingLine(e))),this._parser.registerCsiHandler({final:`G`},(e=>this.cursorCharAbsolute(e))),this._parser.registerCsiHandler({final:`H`},(e=>this.cursorPosition(e))),this._parser.registerCsiHandler({final:`I`},(e=>this.cursorForwardTab(e))),this._parser.registerCsiHandler({final:`J`},(e=>this.eraseInDisplay(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`J`},(e=>this.eraseInDisplay(e,!0))),this._parser.registerCsiHandler({final:`K`},(e=>this.eraseInLine(e,!1))),this._parser.registerCsiHandler({prefix:`?`,final:`K`},(e=>this.eraseInLine(e,!0))),this._parser.registerCsiHandler({final:`L`},(e=>this.insertLines(e))),this._parser.registerCsiHandler({final:`M`},(e=>this.deleteLines(e))),this._parser.registerCsiHandler({final:`P`},(e=>this.deleteChars(e))),this._parser.registerCsiHandler({final:`S`},(e=>this.scrollUp(e))),this._parser.registerCsiHandler({final:`T`},(e=>this.scrollDown(e))),this._parser.registerCsiHandler({final:`X`},(e=>this.eraseChars(e))),this._parser.registerCsiHandler({final:`Z`},(e=>this.cursorBackwardTab(e))),this._parser.registerCsiHandler({final:"`"},(e=>this.charPosAbsolute(e))),this._parser.registerCsiHandler({final:`a`},(e=>this.hPositionRelative(e))),this._parser.registerCsiHandler({final:`b`},(e=>this.repeatPrecedingCharacter(e))),this._parser.registerCsiHandler({final:`c`},(e=>this.sendDeviceAttributesPrimary(e))),this._parser.registerCsiHandler({prefix:`>`,final:`c`},(e=>this.sendDeviceAttributesSecondary(e))),this._parser.registerCsiHandler({final:`d`},(e=>this.linePosAbsolute(e))),this._parser.registerCsiHandler({final:`e`},(e=>this.vPositionRelative(e))),this._parser.registerCsiHandler({final:`f`},(e=>this.hVPosition(e))),this._parser.registerCsiHandler({final:`g`},(e=>this.tabClear(e))),this._parser.registerCsiHandler({final:`h`},(e=>this.setMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`h`},(e=>this.setModePrivate(e))),this._parser.registerCsiHandler({final:`l`},(e=>this.resetMode(e))),this._parser.registerCsiHandler({prefix:`?`,final:`l`},(e=>this.resetModePrivate(e))),this._parser.registerCsiHandler({final:`m`},(e=>this.charAttributes(e))),this._parser.registerCsiHandler({final:`n`},(e=>this.deviceStatus(e))),this._parser.registerCsiHandler({prefix:`?`,final:`n`},(e=>this.deviceStatusPrivate(e))),this._parser.registerCsiHandler({intermediates:`!`,final:`p`},(e=>this.softReset(e))),this._parser.registerCsiHandler({intermediates:` `,final:`q`},(e=>this.setCursorStyle(e))),this._parser.registerCsiHandler({final:`r`},(e=>this.setScrollRegion(e))),this._parser.registerCsiHandler({final:`s`},(e=>this.saveCursor(e))),this._parser.registerCsiHandler({final:`t`},(e=>this.windowOptions(e))),this._parser.registerCsiHandler({final:`u`},(e=>this.restoreCursor(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`}`},(e=>this.insertColumns(e))),this._parser.registerCsiHandler({intermediates:`'`,final:`~`},(e=>this.deleteColumns(e))),this._parser.registerCsiHandler({intermediates:`"`,final:`q`},(e=>this.selectProtected(e))),this._parser.registerCsiHandler({intermediates:`$`,final:`p`},(e=>this.requestMode(e,!0))),this._parser.registerCsiHandler({prefix:`?`,intermediates:`$`,final:`p`},(e=>this.requestMode(e,!1))),this._parser.setExecuteHandler(a.C0.BEL,(()=>this.bell())),this._parser.setExecuteHandler(a.C0.LF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.VT,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.FF,(()=>this.lineFeed())),this._parser.setExecuteHandler(a.C0.CR,(()=>this.carriageReturn())),this._parser.setExecuteHandler(a.C0.BS,(()=>this.backspace())),this._parser.setExecuteHandler(a.C0.HT,(()=>this.tab())),this._parser.setExecuteHandler(a.C0.SO,(()=>this.shiftOut())),this._parser.setExecuteHandler(a.C0.SI,(()=>this.shiftIn())),this._parser.setExecuteHandler(a.C1.IND,(()=>this.index())),this._parser.setExecuteHandler(a.C1.NEL,(()=>this.nextLine())),this._parser.setExecuteHandler(a.C1.HTS,(()=>this.tabSet())),this._parser.registerOscHandler(0,new g.OscHandler((e=>(this.setTitle(e),this.setIconName(e),!0)))),this._parser.registerOscHandler(1,new g.OscHandler((e=>this.setIconName(e)))),this._parser.registerOscHandler(2,new g.OscHandler((e=>this.setTitle(e)))),this._parser.registerOscHandler(4,new g.OscHandler((e=>this.setOrReportIndexedColor(e)))),this._parser.registerOscHandler(8,new g.OscHandler((e=>this.setHyperlink(e)))),this._parser.registerOscHandler(10,new g.OscHandler((e=>this.setOrReportFgColor(e)))),this._parser.registerOscHandler(11,new g.OscHandler((e=>this.setOrReportBgColor(e)))),this._parser.registerOscHandler(12,new g.OscHandler((e=>this.setOrReportCursorColor(e)))),this._parser.registerOscHandler(104,new g.OscHandler((e=>this.restoreIndexedColor(e)))),this._parser.registerOscHandler(110,new g.OscHandler((e=>this.restoreFgColor(e)))),this._parser.registerOscHandler(111,new g.OscHandler((e=>this.restoreBgColor(e)))),this._parser.registerOscHandler(112,new g.OscHandler((e=>this.restoreCursorColor(e)))),this._parser.registerEscHandler({final:`7`},(()=>this.saveCursor())),this._parser.registerEscHandler({final:`8`},(()=>this.restoreCursor())),this._parser.registerEscHandler({final:`D`},(()=>this.index())),this._parser.registerEscHandler({final:`E`},(()=>this.nextLine())),this._parser.registerEscHandler({final:`H`},(()=>this.tabSet())),this._parser.registerEscHandler({final:`M`},(()=>this.reverseIndex())),this._parser.registerEscHandler({final:`=`},(()=>this.keypadApplicationMode())),this._parser.registerEscHandler({final:`>`},(()=>this.keypadNumericMode())),this._parser.registerEscHandler({final:`c`},(()=>this.fullReset())),this._parser.registerEscHandler({final:`n`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`o`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`|`},(()=>this.setgLevel(3))),this._parser.registerEscHandler({final:`}`},(()=>this.setgLevel(2))),this._parser.registerEscHandler({final:`~`},(()=>this.setgLevel(1))),this._parser.registerEscHandler({intermediates:`%`,final:`@`},(()=>this.selectDefaultCharset())),this._parser.registerEscHandler({intermediates:`%`,final:`G`},(()=>this.selectDefaultCharset()));for(let e in o.CHARSETS)this._parser.registerEscHandler({intermediates:`(`,final:e},(()=>this.selectCharset(`(`+e))),this._parser.registerEscHandler({intermediates:`)`,final:e},(()=>this.selectCharset(`)`+e))),this._parser.registerEscHandler({intermediates:`*`,final:e},(()=>this.selectCharset(`*`+e))),this._parser.registerEscHandler({intermediates:`+`,final:e},(()=>this.selectCharset(`+`+e))),this._parser.registerEscHandler({intermediates:`-`,final:e},(()=>this.selectCharset(`-`+e))),this._parser.registerEscHandler({intermediates:`.`,final:e},(()=>this.selectCharset(`.`+e))),this._parser.registerEscHandler({intermediates:`/`,final:e},(()=>this.selectCharset(`/`+e)));this._parser.registerEscHandler({intermediates:`#`,final:`8`},(()=>this.screenAlignmentPattern())),this._parser.setErrorHandler((e=>(this._logService.error(`Parsing error: `,e),e))),this._parser.registerDcsHandler({intermediates:`$`,final:`q`},new _.DcsHandler(((e,t)=>this.requestStatusString(e,t))))}_preserveStack(e,t,n,r){this._parseStack.paused=!0,this._parseStack.cursorStartX=e,this._parseStack.cursorStartY=t,this._parseStack.decodedLength=n,this._parseStack.position=r}_logSlowResolvingAsync(e){this._logService.logLevel<=m.LogLevelEnum.WARN&&Promise.race([e,new Promise(((e,t)=>setTimeout((()=>t(`#SLOW_TIMEOUT`)),5e3)))]).catch((e=>{if(e!==`#SLOW_TIMEOUT`)throw e;console.warn(`async parser handler taking longer than 5000 ms`)}))}_getCurrentLinkId(){return this._curAttrData.extended.urlId}parse(e,t){let n,r=this._activeBuffer.x,i=this._activeBuffer.y,a=0,o=this._parseStack.paused;if(o){if(n=this._parser.parse(this._parseBuffer,this._parseStack.decodedLength,t))return this._logSlowResolvingAsync(n),n;r=this._parseStack.cursorStartX,i=this._parseStack.cursorStartY,this._parseStack.paused=!1,e.length>x&&(a=this._parseStack.position+x)}if(this._logService.logLevel<=m.LogLevelEnum.DEBUG&&this._logService.debug(`parsing data `+(typeof e==`string`?` "${e}"`:` "${Array.prototype.map.call(e,(e=>String.fromCharCode(e))).join(``)}"`)),this._logService.logLevel===m.LogLevelEnum.TRACE&&this._logService.trace(`parsing data (codes)`,typeof e==`string`?e.split(``).map((e=>e.charCodeAt(0))):e),this._parseBuffer.lengthx)for(let t=a;t0&&m.getWidth(this._activeBuffer.x-1)===2&&m.setCellFromCodepoint(this._activeBuffer.x-1,0,1,p);let g=this._parser.precedingJoinState;for(let _=t;_s){if(c){let e=m,t=this._activeBuffer.x-v;for(this._activeBuffer.x=v,this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData(),!0)):(this._activeBuffer.y>=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!0),m=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y),v>0&&m instanceof u.BufferLine&&m.copyCellsFrom(e,t,0,v,!1);t=0;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}else if(f&&(m.insertCells(this._activeBuffer.x,i-v,this._activeBuffer.getNullCell(p)),m.getWidth(s-1)===2&&m.setCellFromCodepoint(s-1,d.NULL_CELL_CODE,d.NULL_CELL_WIDTH,p)),m.setCellFromCodepoint(this._activeBuffer.x++,r,i,p),i>0)for(;--i;)m.setCellFromCodepoint(this._activeBuffer.x++,0,0,p)}this._parser.precedingJoinState=g,this._activeBuffer.x0&&m.getWidth(this._activeBuffer.x)===0&&!m.hasContent(this._activeBuffer.x)&&m.setCellFromCodepoint(this._activeBuffer.x,0,1,p),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}registerCsiHandler(e,t){return e.final!==`t`||e.prefix||e.intermediates?this._parser.registerCsiHandler(e,t):this._parser.registerCsiHandler(e,(e=>!S(e.params[0],this._optionsService.rawOptions.windowOptions)||t(e)))}registerDcsHandler(e,t){return this._parser.registerDcsHandler(e,new _.DcsHandler(t))}registerEscHandler(e,t){return this._parser.registerEscHandler(e,t)}registerOscHandler(e,t){return this._parser.registerOscHandler(e,new g.OscHandler(t))}bell(){return this._onRequestBell.fire(),!0}lineFeed(){return this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._optionsService.rawOptions.convertEol&&(this._activeBuffer.x=0),this._activeBuffer.y++,this._activeBuffer.y===this._activeBuffer.scrollBottom+1?(this._activeBuffer.y--,this._bufferService.scroll(this._eraseAttrData())):this._activeBuffer.y>=this._bufferService.rows?this._activeBuffer.y=this._bufferService.rows-1:this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.x>=this._bufferService.cols&&this._activeBuffer.x--,this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._onLineFeed.fire(),!0}carriageReturn(){return this._activeBuffer.x=0,!0}backspace(){if(!this._coreService.decPrivateModes.reverseWraparound)return this._restrictCursor(),this._activeBuffer.x>0&&this._activeBuffer.x--,!0;if(this._restrictCursor(this._bufferService.cols),this._activeBuffer.x>0)this._activeBuffer.x--;else if(this._activeBuffer.x===0&&this._activeBuffer.y>this._activeBuffer.scrollTop&&this._activeBuffer.y<=this._activeBuffer.scrollBottom&&this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y)?.isWrapped){this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y).isWrapped=!1,this._activeBuffer.y--,this._activeBuffer.x=this._bufferService.cols-1;let e=this._activeBuffer.lines.get(this._activeBuffer.ybase+this._activeBuffer.y);e.hasWidth(this._activeBuffer.x)&&!e.hasContent(this._activeBuffer.x)&&this._activeBuffer.x--}return this._restrictCursor(),!0}tab(){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let e=this._activeBuffer.x;return this._activeBuffer.x=this._activeBuffer.nextStop(),this._optionsService.rawOptions.screenReaderMode&&this._onA11yTab.fire(this._activeBuffer.x-e),!0}shiftOut(){return this._charsetService.setgLevel(1),!0}shiftIn(){return this._charsetService.setgLevel(0),!0}_restrictCursor(e=this._bufferService.cols-1){this._activeBuffer.x=Math.min(e,Math.max(0,this._activeBuffer.x)),this._activeBuffer.y=this._coreService.decPrivateModes.origin?Math.min(this._activeBuffer.scrollBottom,Math.max(this._activeBuffer.scrollTop,this._activeBuffer.y)):Math.min(this._bufferService.rows-1,Math.max(0,this._activeBuffer.y)),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_setCursor(e,t){this._dirtyRowTracker.markDirty(this._activeBuffer.y),this._coreService.decPrivateModes.origin?(this._activeBuffer.x=e,this._activeBuffer.y=this._activeBuffer.scrollTop+t):(this._activeBuffer.x=e,this._activeBuffer.y=t),this._restrictCursor(),this._dirtyRowTracker.markDirty(this._activeBuffer.y)}_moveCursor(e,t){this._restrictCursor(),this._setCursor(this._activeBuffer.x+e,this._activeBuffer.y+t)}cursorUp(e){let t=this._activeBuffer.y-this._activeBuffer.scrollTop;return t>=0?this._moveCursor(0,-Math.min(t,e.params[0]||1)):this._moveCursor(0,-(e.params[0]||1)),!0}cursorDown(e){let t=this._activeBuffer.scrollBottom-this._activeBuffer.y;return t>=0?this._moveCursor(0,Math.min(t,e.params[0]||1)):this._moveCursor(0,e.params[0]||1),!0}cursorForward(e){return this._moveCursor(e.params[0]||1,0),!0}cursorBackward(e){return this._moveCursor(-(e.params[0]||1),0),!0}cursorNextLine(e){return this.cursorDown(e),this._activeBuffer.x=0,!0}cursorPrecedingLine(e){return this.cursorUp(e),this._activeBuffer.x=0,!0}cursorCharAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}cursorPosition(e){return this._setCursor(e.length>=2?(e.params[1]||1)-1:0,(e.params[0]||1)-1),!0}charPosAbsolute(e){return this._setCursor((e.params[0]||1)-1,this._activeBuffer.y),!0}hPositionRelative(e){return this._moveCursor(e.params[0]||1,0),!0}linePosAbsolute(e){return this._setCursor(this._activeBuffer.x,(e.params[0]||1)-1),!0}vPositionRelative(e){return this._moveCursor(0,e.params[0]||1),!0}hVPosition(e){return this.cursorPosition(e),!0}tabClear(e){let t=e.params[0];return t===0?delete this._activeBuffer.tabs[this._activeBuffer.x]:t===3&&(this._activeBuffer.tabs={}),!0}cursorForwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.nextStop();return!0}cursorBackwardTab(e){if(this._activeBuffer.x>=this._bufferService.cols)return!0;let t=e.params[0]||1;for(;t--;)this._activeBuffer.x=this._activeBuffer.prevStop();return!0}selectProtected(e){let t=e.params[0];return t===1&&(this._curAttrData.bg|=536870912),t!==2&&t!==0||(this._curAttrData.bg&=-536870913),!0}_eraseInBufferLine(e,t,n,r=!1,i=!1){let a=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);a.replaceCells(t,n,this._activeBuffer.getNullCell(this._eraseAttrData()),i),r&&(a.isWrapped=!1)}_resetBufferLine(e,t=!1){let n=this._activeBuffer.lines.get(this._activeBuffer.ybase+e);n&&(n.fill(this._activeBuffer.getNullCell(this._eraseAttrData()),t),this._bufferService.buffer.clearMarkers(this._activeBuffer.ybase+e),n.isWrapped=!1)}eraseInDisplay(e,t=!1){let n;switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:for(n=this._activeBuffer.y,this._dirtyRowTracker.markDirty(n),this._eraseInBufferLine(n++,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);n=this._bufferService.cols&&(this._activeBuffer.lines.get(n+1).isWrapped=!1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0);break;case 2:if(this._optionsService.rawOptions.scrollOnEraseInDisplay){for(n=this._bufferService.rows,this._dirtyRowTracker.markRangeDirty(0,n-1);n--&&!this._activeBuffer.lines.get(this._activeBuffer.ybase+n)?.getTrimmedLength(););for(;n>=0;n--)this._bufferService.scroll(this._eraseAttrData())}else{for(n=this._bufferService.rows,this._dirtyRowTracker.markDirty(n-1);n--;)this._resetBufferLine(n,t);this._dirtyRowTracker.markDirty(0)}break;case 3:let e=this._activeBuffer.lines.length-this._bufferService.rows;e>0&&(this._activeBuffer.lines.trimStart(e),this._activeBuffer.ybase=Math.max(this._activeBuffer.ybase-e,0),this._activeBuffer.ydisp=Math.max(this._activeBuffer.ydisp-e,0),this._onScroll.fire(0))}return!0}eraseInLine(e,t=!1){switch(this._restrictCursor(this._bufferService.cols),e.params[0]){case 0:this._eraseInBufferLine(this._activeBuffer.y,this._activeBuffer.x,this._bufferService.cols,this._activeBuffer.x===0,t);break;case 1:this._eraseInBufferLine(this._activeBuffer.y,0,this._activeBuffer.x+1,!1,t);break;case 2:this._eraseInBufferLine(this._activeBuffer.y,0,this._bufferService.cols,!0,t)}return this._dirtyRowTracker.markDirty(this._activeBuffer.y),!0}insertLines(e){this._restrictCursor();let t=e.params[0]||1;if(this._activeBuffer.y>this._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.ythis._activeBuffer.scrollBottom||this._activeBuffer.y65535?2:1}let c=s;for(let e=1;e0||(this._is(`xterm`)||this._is(`rxvt-unicode`)||this._is(`screen`)?this._coreService.triggerDataEvent(a.C0.ESC+`[?1;2c`):this._is(`linux`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[?6c`)),!0}sendDeviceAttributesSecondary(e){return e.params[0]>0||(this._is(`xterm`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>0;276;0c`):this._is(`rxvt-unicode`)?this._coreService.triggerDataEvent(a.C0.ESC+`[>85;95;0c`):this._is(`linux`)?this._coreService.triggerDataEvent(e.params[0]+`c`):this._is(`screen`)&&this._coreService.triggerDataEvent(a.C0.ESC+`[>83;40003;0c`)),!0}_is(e){return(this._optionsService.rawOptions.termName+``).indexOf(e)===0}setMode(e){for(let t=0;te?1:2,p=e.params[0];return m=p,h=t?p===2?4:p===4?f(o.modes.insertMode):p===12?3:p===20?f(d.convertEol):0:p===1?f(n.applicationCursorKeys):p===3?d.windowOptions.setWinLines?c===80?2:+(c===132):0:p===6?f(n.origin):p===7?f(n.wraparound):p===8?3:p===9?f(r===`X10`):p===12?f(d.cursorBlink):p===25?f(!o.isCursorHidden):p===45?f(n.reverseWraparound):p===66?f(n.applicationKeypad):p===67?4:p===1e3?f(r===`VT200`):p===1002?f(r===`DRAG`):p===1003?f(r===`ANY`):p===1004?f(n.sendFocus):p===1005?4:p===1006?f(i===`SGR`):p===1015?4:p===1016?f(i===`SGR_PIXELS`):p===1048?1:p===47||p===1047||p===1049?f(l===u):p===2004?f(n.bracketedPasteMode):p===2026?f(n.synchronizedOutput):0,o.triggerDataEvent(`${a.C0.ESC}[${t?``:`?`}${m};${h}$y`),!0;var m,h}_updateAttrColor(e,t,n,r,i){return t===2?(e|=50331648,e&=-16777216,e|=p.AttributeData.fromColorRGB([n,r,i])):t===5&&(e&=-50331904,e|=33554432|255&n),e}_extractColor(e,t,n){let r=[0,0,-1,0,0,0],i=0,a=0;do{if(r[a+i]=e.params[t+a],e.hasSubParams(t+a)){let n=e.getSubParams(t+a),o=0;do r[1]===5&&(i=1),r[a+o+1+i]=n[o];while(++o=2||r[1]===2&&a+i>=5)break;r[1]&&(i=1)}while(++a+t5)&&(e=1),t.extended.underlineStyle=e,t.fg|=268435456,e===0&&(t.fg&=-268435457),t.updateExtended()}_processSGR0(e){e.fg=u.DEFAULT_ATTR_DATA.fg,e.bg=u.DEFAULT_ATTR_DATA.bg,e.extended=e.extended.clone(),e.extended.underlineStyle=0,e.extended.underlineColor&=-67108864,e.updateExtended()}charAttributes(e){if(e.length===1&&e.params[0]===0)return this._processSGR0(this._curAttrData),!0;let t=e.length,n,r=this._curAttrData;for(let i=0;i=30&&n<=37?(r.fg&=-50331904,r.fg|=16777216|n-30):n>=40&&n<=47?(r.bg&=-50331904,r.bg|=16777216|n-40):n>=90&&n<=97?(r.fg&=-50331904,r.fg|=16777224|n-90):n>=100&&n<=107?(r.bg&=-50331904,r.bg|=16777224|n-100):n===0?this._processSGR0(r):n===1?r.fg|=134217728:n===3?r.bg|=67108864:n===4?(r.fg|=268435456,this._processUnderline(e.hasSubParams(i)?e.getSubParams(i)[0]:1,r)):n===5?r.fg|=536870912:n===7?r.fg|=67108864:n===8?r.fg|=1073741824:n===9?r.fg|=2147483648:n===2?r.bg|=134217728:n===21?this._processUnderline(2,r):n===22?(r.fg&=-134217729,r.bg&=-134217729):n===23?r.bg&=-67108865:n===24?(r.fg&=-268435457,this._processUnderline(0,r)):n===25?r.fg&=-536870913:n===27?r.fg&=-67108865:n===28?r.fg&=-1073741825:n===29?r.fg&=2147483647:n===39?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg):n===49?(r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):n===38||n===48||n===58?i+=this._extractColor(e,i,r):n===53?r.bg|=1073741824:n===55?r.bg&=-1073741825:n===59?(r.extended=r.extended.clone(),r.extended.underlineColor=-1,r.updateExtended()):n===100?(r.fg&=-67108864,r.fg|=16777215&u.DEFAULT_ATTR_DATA.fg,r.bg&=-67108864,r.bg|=16777215&u.DEFAULT_ATTR_DATA.bg):this._logService.debug(`Unknown SGR attribute: %d.`,n);return!0}deviceStatus(e){switch(e.params[0]){case 5:this._coreService.triggerDataEvent(`${a.C0.ESC}[0n`);break;case 6:let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[${e};${t}R`)}return!0}deviceStatusPrivate(e){if(e.params[0]===6){let e=this._activeBuffer.y+1,t=this._activeBuffer.x+1;this._coreService.triggerDataEvent(`${a.C0.ESC}[?${e};${t}R`)}return!0}softReset(e){return this._coreService.isCursorHidden=!1,this._onRequestSyncScrollBar.fire(),this._activeBuffer.scrollTop=0,this._activeBuffer.scrollBottom=this._bufferService.rows-1,this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._coreService.reset(),this._charsetService.reset(),this._activeBuffer.savedX=0,this._activeBuffer.savedY=this._activeBuffer.ybase,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,this._coreService.decPrivateModes.origin=!1,!0}setCursorStyle(e){let t=e.length===0?1:e.params[0];if(t===0)this._coreService.decPrivateModes.cursorStyle=void 0,this._coreService.decPrivateModes.cursorBlink=void 0;else{switch(t){case 1:case 2:this._coreService.decPrivateModes.cursorStyle=`block`;break;case 3:case 4:this._coreService.decPrivateModes.cursorStyle=`underline`;break;case 5:case 6:this._coreService.decPrivateModes.cursorStyle=`bar`}let e=t%2==1;this._coreService.decPrivateModes.cursorBlink=e}return!0}setScrollRegion(e){let t=e.params[0]||1,n;return(e.length<2||(n=e.params[1])>this._bufferService.rows||n===0)&&(n=this._bufferService.rows),n>t&&(this._activeBuffer.scrollTop=t-1,this._activeBuffer.scrollBottom=n-1,this._setCursor(0,0)),!0}windowOptions(e){if(!S(e.params[0],this._optionsService.rawOptions.windowOptions))return!0;let t=e.length>1?e.params[1]:0;switch(e.params[0]){case 14:t!==2&&this._onRequestWindowsOptionsReport.fire(C.GET_WIN_SIZE_PIXELS);break;case 16:this._onRequestWindowsOptionsReport.fire(C.GET_CELL_SIZE_PIXELS);break;case 18:this._bufferService&&this._coreService.triggerDataEvent(`${a.C0.ESC}[8;${this._bufferService.rows};${this._bufferService.cols}t`);break;case 22:t!==0&&t!==2||(this._windowTitleStack.push(this._windowTitle),this._windowTitleStack.length>10&&this._windowTitleStack.shift()),t!==0&&t!==1||(this._iconNameStack.push(this._iconName),this._iconNameStack.length>10&&this._iconNameStack.shift());break;case 23:t!==0&&t!==2||this._windowTitleStack.length&&this.setTitle(this._windowTitleStack.pop()),t!==0&&t!==1||this._iconNameStack.length&&this.setIconName(this._iconNameStack.pop())}return!0}saveCursor(e){return this._activeBuffer.savedX=this._activeBuffer.x,this._activeBuffer.savedY=this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.savedCurAttrData.fg=this._curAttrData.fg,this._activeBuffer.savedCurAttrData.bg=this._curAttrData.bg,this._activeBuffer.savedCharset=this._charsetService.charset,!0}restoreCursor(e){return this._activeBuffer.x=this._activeBuffer.savedX||0,this._activeBuffer.y=Math.max(this._activeBuffer.savedY-this._activeBuffer.ybase,0),this._curAttrData.fg=this._activeBuffer.savedCurAttrData.fg,this._curAttrData.bg=this._activeBuffer.savedCurAttrData.bg,this._charsetService.charset=this._savedCharset,this._activeBuffer.savedCharset&&(this._charsetService.charset=this._activeBuffer.savedCharset),this._restrictCursor(),!0}setTitle(e){return this._windowTitle=e,this._onTitleChange.fire(e),!0}setIconName(e){return this._iconName=e,!0}setOrReportIndexedColor(e){let t=[],n=e.split(`;`);for(;n.length>1;){let e=n.shift(),r=n.shift();if(/^\d+$/.exec(e)){let n=parseInt(e);if(D(n)){if(r===`?`)t.push({type:0,index:n});else{let e=(0,v.parseColor)(r);e&&t.push({type:1,index:n,color:e})}}}}return t.length&&this._onColor.fire(t),!0}setHyperlink(e){let t=e.indexOf(`;`);if(t===-1)return!0;let n=e.slice(0,t).trim(),r=e.slice(t+1);return r?this._createHyperlink(n,r):!n.trim()&&this._finishHyperlink()}_createHyperlink(e,t){this._getCurrentLinkId()&&this._finishHyperlink();let n=e.split(`:`),r,i=n.findIndex((e=>e.startsWith(`id=`)));return i!==-1&&(r=n[i].slice(3)||void 0),this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=this._oscLinkService.registerLink({id:r,uri:t}),this._curAttrData.updateExtended(),!0}_finishHyperlink(){return this._curAttrData.extended=this._curAttrData.extended.clone(),this._curAttrData.extended.urlId=0,this._curAttrData.updateExtended(),!0}_setOrReportSpecialColor(e,t){let n=e.split(`;`);for(let e=0;e=this._specialColors.length);++e,++t)if(n[e]===`?`)this._onColor.fire([{type:0,index:this._specialColors[t]}]);else{let r=(0,v.parseColor)(n[e]);r&&this._onColor.fire([{type:1,index:this._specialColors[t],color:r}])}return!0}setOrReportFgColor(e){return this._setOrReportSpecialColor(e,0)}setOrReportBgColor(e){return this._setOrReportSpecialColor(e,1)}setOrReportCursorColor(e){return this._setOrReportSpecialColor(e,2)}restoreIndexedColor(e){if(!e)return this._onColor.fire([{type:2}]),!0;let t=[],n=e.split(`;`);for(let e=0;e=this._bufferService.rows&&(this._activeBuffer.y=this._bufferService.rows-1),this._restrictCursor(),!0}tabSet(){return this._activeBuffer.tabs[this._activeBuffer.x]=!0,!0}reverseIndex(){if(this._restrictCursor(),this._activeBuffer.y===this._activeBuffer.scrollTop){let e=this._activeBuffer.scrollBottom-this._activeBuffer.scrollTop;this._activeBuffer.lines.shiftElements(this._activeBuffer.ybase+this._activeBuffer.y,e,1),this._activeBuffer.lines.set(this._activeBuffer.ybase+this._activeBuffer.y,this._activeBuffer.getBlankLine(this._eraseAttrData())),this._dirtyRowTracker.markRangeDirty(this._activeBuffer.scrollTop,this._activeBuffer.scrollBottom)}else this._activeBuffer.y--,this._restrictCursor();return!0}fullReset(){return this._parser.reset(),this._onRequestReset.fire(),!0}reset(){this._curAttrData=u.DEFAULT_ATTR_DATA.clone(),this._eraseAttrDataInternal=u.DEFAULT_ATTR_DATA.clone()}_eraseAttrData(){return this._eraseAttrDataInternal.bg&=-67108864,this._eraseAttrDataInternal.bg|=67108863&this._curAttrData.bg,this._eraseAttrDataInternal}setgLevel(e){return this._charsetService.setgLevel(e),!0}screenAlignmentPattern(){let e=new f.CellData;e.content=4194373,e.fg=this._curAttrData.fg,e.bg=this._curAttrData.bg,this._setCursor(0,0);for(let t=0;t(this._coreService.triggerDataEvent(`${a.C0.ESC}${e}${a.C0.ESC}\\`),!0))(e===`"q`?`P1$r${+!!this._curAttrData.isProtected()}"q`:e===`"p`?`P1$r61;1"p`:e===`r`?`P1$r${n.scrollTop+1};${n.scrollBottom+1}r`:e===`m`?`P1$r0m`:e===` q`?`P1$r${{block:2,underline:4,bar:6}[r.cursorStyle]-+!!r.cursorBlink} q`:`P0$r`)}markRangeDirty(e,t){this._dirtyRowTracker.markRangeDirty(e,t)}}t.InputHandler=T;let E=class{constructor(e){this._bufferService=e,this.clearRange()}clearRange(){this.start=this._bufferService.buffer.y,this.end=this._bufferService.buffer.y}markDirty(e){ethis.end&&(this.end=e)}markRangeDirty(e,t){e>t&&(w=e,e=t,t=w),ethis.end&&(this.end=t)}markAllDirty(){this.markRangeDirty(0,this._bufferService.rows-1)}};function D(e){return 0<=e&&e<256}E=r([i(0,m.IBufferService)],E)},7710:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FourKeyMap=t.TwoKeyMap=void 0;class n{constructor(){this._data={}}set(e,t,n){this._data[e]||(this._data[e]={}),this._data[e][t]=n}get(e,t){return this._data[e]?this._data[e][t]:void 0}clear(){this._data={}}}t.TwoKeyMap=n,t.FourKeyMap=class{constructor(){this._data=new n}set(e,t,r,i,a){this._data.get(e,t)||this._data.set(e,t,new n),this._data.get(e,t).set(r,i,a)}get(e,t,n,r){return this._data.get(e,t)?.get(n,r)}clear(){this._data.clear()}}},701:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isChromeOS=t.isLinux=t.isWindows=t.isIphone=t.isIpad=t.isMac=t.isSafari=t.isLegacyEdge=t.isFirefox=t.isNode=void 0,t.getSafariVersion=function(){if(!t.isSafari)return 0;let e=n.match(/Version\/(\d+)/);return e===null||e.length<2?0:parseInt(e[1])},t.isNode=typeof process<`u`&&`title`in process;let n=t.isNode?`node`:navigator.userAgent,r=t.isNode?`node`:navigator.platform;t.isFirefox=n.includes(`Firefox`),t.isLegacyEdge=n.includes(`Edge`),t.isSafari=/^((?!chrome|android).)*safari/i.test(n),t.isMac=[`Macintosh`,`MacIntel`,`MacPPC`,`Mac68K`].includes(r),t.isIpad=r===`iPad`,t.isIphone=r===`iPhone`,t.isWindows=[`Windows`,`Win16`,`Win32`,`WinCE`].includes(r),t.isLinux=r.indexOf(`Linux`)>=0,t.isChromeOS=/\bCrOS\b/.test(n)},3087:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SortedList=void 0;let r=n(6168),i=0;t.SortedList=class{constructor(e){this._getKey=e,this._array=[],this._insertedValues=[],this._flushInsertedTask=new r.IdleTaskQueue,this._isFlushingInserted=!1,this._deletedIndices=[],this._flushDeletedTask=new r.IdleTaskQueue,this._isFlushingDeleted=!1}clear(){this._array.length=0,this._insertedValues.length=0,this._flushInsertedTask.clear(),this._isFlushingInserted=!1,this._deletedIndices.length=0,this._flushDeletedTask.clear(),this._isFlushingDeleted=!1}insert(e){this._flushCleanupDeleted(),this._insertedValues.length===0&&this._flushInsertedTask.enqueue((()=>this._flushInserted())),this._insertedValues.push(e)}_flushInserted(){let e=this._insertedValues.sort(((e,t)=>this._getKey(e)-this._getKey(t))),t=0,n=0,r=Array(this._array.length+this._insertedValues.length);for(let i=0;i=this._array.length||this._getKey(e[t])<=this._getKey(this._array[n])?(r[i]=e[t],t++):r[i]=this._array[n++];this._array=r,this._insertedValues.length=0}_flushCleanupInserted(){!this._isFlushingInserted&&this._insertedValues.length>0&&this._flushInsertedTask.flush()}delete(e){if(this._flushCleanupInserted(),this._array.length===0)return!1;let t=this._getKey(e);if(t===void 0||(i=this._search(t),i===-1)||this._getKey(this._array[i])!==t)return!1;do if(this._array[i]===e)return this._deletedIndices.length===0&&this._flushDeletedTask.enqueue((()=>this._flushDeleted())),this._deletedIndices.push(i),!0;while(++ie-t)),t=0,n=Array(this._array.length-e.length),r=0;for(let i=0;i0&&this._flushDeletedTask.flush()}*getKeyIterator(e){if(this._flushCleanupInserted(),this._flushCleanupDeleted(),this._array.length!==0&&(i=this._search(e),!(i<0||i>=this._array.length)&&this._getKey(this._array[i])===e))do yield this._array[i];while(++i=this._array.length)&&this._getKey(this._array[i])===e))do t(this._array[i]);while(++i=t;){let r=t+n>>1,i=this._getKey(this._array[r]);if(i>e)n=r-1;else{if(!(i0&&this._getKey(this._array[r-1])===e;)r--;return r}t=r+1}}return t}}},6168:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DebouncedIdleTask=t.IdleTaskQueue=t.PriorityTaskQueue=void 0;let r=n(701);class i{constructor(){this._tasks=[],this._i=0}enqueue(e){this._tasks.push(e),this._start()}flush(){for(;this._ii)return r-t<-20&&console.warn(`task queue exceeded allotted deadline by ${Math.abs(Math.round(r-t))}ms`),void this._start();r=i}this.clear()}}class a extends i{_requestCallback(e){return setTimeout((()=>e(this._createDeadline(16))))}_cancelCallback(e){clearTimeout(e)}_createDeadline(e){let t=performance.now()+e;return{timeRemaining:()=>Math.max(0,t-performance.now())}}}t.PriorityTaskQueue=a,t.IdleTaskQueue=!r.isNode&&`requestIdleCallback`in window?class extends i{_requestCallback(e){return requestIdleCallback(e)}_cancelCallback(e){cancelIdleCallback(e)}}:a,t.DebouncedIdleTask=class{constructor(){this._queue=new t.IdleTaskQueue}set(e){this._queue.clear(),this._queue.enqueue(e)}flush(){this._queue.flush()}}},5882:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.updateWindowsModeWrappedState=function(e){let t=e.buffer.lines.get(e.buffer.ybase+e.buffer.y-1)?.get(e.cols-1),n=e.buffer.lines.get(e.buffer.ybase+e.buffer.y);n&&t&&(n.isWrapped=t[r.CHAR_DATA_CODE_INDEX]!==r.NULL_CELL_CODE&&t[r.CHAR_DATA_CODE_INDEX]!==r.WHITESPACE_CELL_CODE)};let r=n(8938)},5451:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ExtendedAttrs=t.AttributeData=void 0;class n{constructor(){this.fg=0,this.bg=0,this.extended=new r}static toColorRGB(e){return[e>>>16&255,e>>>8&255,255&e]}static fromColorRGB(e){return(255&e[0])<<16|(255&e[1])<<8|255&e[2]}clone(){let e=new n;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return 67108864&this.fg}isBold(){return 134217728&this.fg}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:268435456&this.fg}isBlink(){return 536870912&this.fg}isInvisible(){return 1073741824&this.fg}isItalic(){return 67108864&this.bg}isDim(){return 134217728&this.bg}isStrikethrough(){return 2147483648&this.fg}isProtected(){return 536870912&this.bg}isOverline(){return 1073741824&this.bg}getFgColorMode(){return 50331648&this.fg}getBgColorMode(){return 50331648&this.bg}isFgRGB(){return!(50331648&~this.fg)}isBgRGB(){return!(50331648&~this.bg)}isFgPalette(){return(50331648&this.fg)==16777216||(50331648&this.fg)==33554432}isBgPalette(){return(50331648&this.bg)==16777216||(50331648&this.bg)==33554432}isFgDefault(){return!(50331648&this.fg)}isBgDefault(){return!(50331648&this.bg)}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(50331648&this.fg){case 16777216:case 33554432:return 255&this.fg;case 50331648:return 16777215&this.fg;default:return-1}}getBgColor(){switch(50331648&this.bg){case 16777216:case 33554432:return 255&this.bg;case 50331648:return 16777215&this.bg;default:return-1}}hasExtendedAttrs(){return 268435456&this.bg}updateExtended(){this.extended.isEmpty()?this.bg&=-268435457:this.bg|=268435456}getUnderlineColor(){if(268435456&this.bg&&~this.extended.underlineColor)switch(50331648&this.extended.underlineColor){case 16777216:case 33554432:return 255&this.extended.underlineColor;case 50331648:return 16777215&this.extended.underlineColor;default:return this.getFgColor()}return this.getFgColor()}getUnderlineColorMode(){return 268435456&this.bg&&~this.extended.underlineColor?50331648&this.extended.underlineColor:this.getFgColorMode()}isUnderlineColorRGB(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&~this.extended.underlineColor):this.isFgRGB()}isUnderlineColorPalette(){return 268435456&this.bg&&~this.extended.underlineColor?(50331648&this.extended.underlineColor)==16777216||(50331648&this.extended.underlineColor)==33554432:this.isFgPalette()}isUnderlineColorDefault(){return 268435456&this.bg&&~this.extended.underlineColor?!(50331648&this.extended.underlineColor):this.isFgDefault()}getUnderlineStyle(){return 268435456&this.fg?268435456&this.bg?this.extended.underlineStyle:1:0}getUnderlineVariantOffset(){return this.extended.underlineVariantOffset}}t.AttributeData=n;class r{get ext(){return this._urlId?-469762049&this._ext|this.underlineStyle<<26:this._ext}set ext(e){this._ext=e}get underlineStyle(){return this._urlId?5:(469762048&this._ext)>>26}set underlineStyle(e){this._ext&=-469762049,this._ext|=e<<26&469762048}get underlineColor(){return 67108863&this._ext}set underlineColor(e){this._ext&=-67108864,this._ext|=67108863&e}get urlId(){return this._urlId}set urlId(e){this._urlId=e}get underlineVariantOffset(){let e=(3758096384&this._ext)>>29;return e<0?4294967288^e:e}set underlineVariantOffset(e){this._ext&=536870911,this._ext|=e<<29&3758096384}constructor(e=0,t=0){this._ext=0,this._urlId=0,this._ext=e,this._urlId=t}clone(){return new r(this._ext,this._urlId)}isEmpty(){return this.underlineStyle===0&&this._urlId===0}}t.ExtendedAttrs=r},1073:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Buffer=t.MAX_BUFFER_SIZE=void 0;let r=n(5639),i=n(6168),a=n(5451),o=n(6107),s=n(732),c=n(3055),l=n(8938),u=n(8158),d=n(6760);t.MAX_BUFFER_SIZE=4294967295,t.Buffer=class{constructor(e,t,n){this._hasScrollback=e,this._optionsService=t,this._bufferService=n,this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.tabs={},this.savedY=0,this.savedX=0,this.savedCurAttrData=o.DEFAULT_ATTR_DATA.clone(),this.savedCharset=d.DEFAULT_CHARSET,this.markers=[],this._nullCell=c.CellData.fromCharData([0,l.NULL_CELL_CHAR,l.NULL_CELL_WIDTH,l.NULL_CELL_CODE]),this._whitespaceCell=c.CellData.fromCharData([0,l.WHITESPACE_CELL_CHAR,l.WHITESPACE_CELL_WIDTH,l.WHITESPACE_CELL_CODE]),this._isClearing=!1,this._memoryCleanupQueue=new i.IdleTaskQueue,this._memoryCleanupPosition=0,this._cols=this._bufferService.cols,this._rows=this._bufferService.rows,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}getNullCell(e){return e?(this._nullCell.fg=e.fg,this._nullCell.bg=e.bg,this._nullCell.extended=e.extended):(this._nullCell.fg=0,this._nullCell.bg=0,this._nullCell.extended=new a.ExtendedAttrs),this._nullCell}getWhitespaceCell(e){return e?(this._whitespaceCell.fg=e.fg,this._whitespaceCell.bg=e.bg,this._whitespaceCell.extended=e.extended):(this._whitespaceCell.fg=0,this._whitespaceCell.bg=0,this._whitespaceCell.extended=new a.ExtendedAttrs),this._whitespaceCell}getBlankLine(e,t){return new o.BufferLine(this._bufferService.cols,this.getNullCell(e),t)}get hasScrollback(){return this._hasScrollback&&this.lines.maxLength>this._rows}get isCursorInViewport(){let e=this.ybase+this.y-this.ydisp;return e>=0&&et.MAX_BUFFER_SIZE?t.MAX_BUFFER_SIZE:n}fillViewportRows(e){if(this.lines.length===0){e===void 0&&(e=o.DEFAULT_ATTR_DATA);let t=this._rows;for(;t--;)this.lines.push(this.getBlankLine(e))}}clear(){this.ydisp=0,this.ybase=0,this.y=0,this.x=0,this.lines=new r.CircularList(this._getCorrectBufferLength(this._rows)),this.scrollTop=0,this.scrollBottom=this._rows-1,this.setupTabStops()}resize(e,t){let n=this.getNullCell(o.DEFAULT_ATTR_DATA),r=0,i=this._getCorrectBufferLength(t);if(i>this.lines.maxLength&&(this.lines.maxLength=i),this.lines.length>0){if(this._cols0&&this.lines.length<=this.ybase+this.y+a+1?(this.ybase--,a++,this.ydisp>0&&this.ydisp--):this.lines.push(new o.BufferLine(e,n)));else for(let e=this._rows;e>t;e--)this.lines.length>t+this.ybase&&(this.lines.length>this.ybase+this.y+1?this.lines.pop():(this.ybase++,this.ydisp++));if(i0&&(this.lines.trimStart(e),this.ybase=Math.max(this.ybase-e,0),this.ydisp=Math.max(this.ydisp-e,0),this.savedY=Math.max(this.savedY-e,0)),this.lines.maxLength=i}this.x=Math.min(this.x,e-1),this.y=Math.min(this.y,t-1),a&&(this.y+=a),this.savedX=Math.min(this.savedX,e-1),this.scrollTop=0}if(this.scrollBottom=t-1,this._isReflowEnabled&&(this._reflow(e,t),this._cols>e))for(let t=0;t.1*this.lines.length&&(this._memoryCleanupPosition=0,this._memoryCleanupQueue.enqueue((()=>this._batchedMemoryCleanup())))}_batchedMemoryCleanup(){let e=!0;this._memoryCleanupPosition>=this.lines.length&&(this._memoryCleanupPosition=0,e=!1);let t=0;for(;this._memoryCleanupPosition100)return!0;return e}get _isReflowEnabled(){let e=this._optionsService.rawOptions.windowsPty;return e&&e.buildNumber?this._hasScrollback&&e.backend===`conpty`&&e.buildNumber>=21376:this._hasScrollback&&!this._optionsService.rawOptions.windowsMode}_reflow(e,t){this._cols!==e&&(e>this._cols?this._reflowLarger(e,t):this._reflowSmaller(e,t))}_reflowLarger(e,t){let n=this._optionsService.rawOptions.reflowCursorLine,r=(0,s.reflowLargerGetLinesToRemove)(this.lines,this._cols,e,this.ybase+this.y,this.getNullCell(o.DEFAULT_ATTR_DATA),n);if(r.length>0){let n=(0,s.reflowLargerCreateNewLayout)(this.lines,r);(0,s.reflowLargerApplyNewLayout)(this.lines,n.layout),this._reflowLargerAdjustViewport(e,t,n.countRemoved)}}_reflowLargerAdjustViewport(e,t,n){let r=this.getNullCell(o.DEFAULT_ATTR_DATA),i=n;for(;i-->0;)this.ybase===0?(this.y>0&&this.y--,this.lines.length=0;c--){let l=this.lines.get(c);if(!l||!l.isWrapped&&l.getTrimmedLength()<=e)continue;let u=[l];for(;l.isWrapped&&c>0;)l=this.lines.get(--c),u.unshift(l);if(!n){let e=this.ybase+this.y;if(e>=c&&e0&&(i.push({start:c+u.length+a,newLines:h}),a+=h.length),u.push(...h);let g=f.length-1,_=f[g];_===0&&(g--,_=f[g]);let v=u.length-p-1,y=d;for(;v>=0;){let e=Math.min(y,_);if(u[g]===void 0)break;if(u[g].copyCellsFrom(u[v],y-e,_-e,e,!0),_-=e,_===0&&(g--,_=f[g]),y-=e,y===0){v--;let e=Math.max(v,0);y=(0,s.getWrappedLineTrimmedLength)(u,e,this._cols)}}for(let t=0;t0;)this.ybase===0?this.y0){let e=[],t=[];for(let e=0;e=0;l--)if(s&&s.start>r+c){for(let e=s.newLines.length-1;e>=0;e--)this.lines.set(l--,s.newLines[e]);l++,e.push({index:r+1,amount:s.newLines.length}),c+=s.newLines.length,s=i[++o]}else this.lines.set(l,t[r--]);let l=0;for(let t=e.length-1;t>=0;t--)e[t].index+=l,this.lines.onInsertEmitter.fire(e[t]),l+=e[t].amount;let u=Math.max(0,n+a-this.lines.maxLength);u>0&&this.lines.onTrimEmitter.fire(u)}}translateBufferLineToString(e,t,n=0,r){let i=this.lines.get(e);return i?i.translateToString(t,n,r):``}getWrappedRangeForLine(e){let t=e,n=e;for(;t>0&&this.lines.get(t).isWrapped;)t--;for(;n+10;);return e>=this._cols?this._cols-1:e<0?0:e}nextStop(e){for(e??=this.x;!this.tabs[++e]&&e=this._cols?this._cols-1:e<0?0:e}clearMarkers(e){this._isClearing=!0;for(let t=0;t{t.line-=e,t.line<0&&t.dispose()}))),t.register(this.lines.onInsert((e=>{t.line>=e.index&&(t.line+=e.amount)}))),t.register(this.lines.onDelete((e=>{t.line>=e.index&&t.linee.index&&(t.line-=e.amount)}))),t.register(t.onDispose((()=>this._removeMarker(t)))),t}_removeMarker(e){this._isClearing||this.markers.splice(this.markers.indexOf(e),1)}}},6107:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLine=t.DEFAULT_ATTR_DATA=void 0;let r=n(5451),i=n(3055),a=n(8938),o=n(726);t.DEFAULT_ATTR_DATA=Object.freeze(new r.AttributeData);let s=0;class c{constructor(e,t,n=!1){this.isWrapped=n,this._combined={},this._extendedAttrs={},this._data=new Uint32Array(3*e);let r=t||i.CellData.fromCharData([0,a.NULL_CELL_CHAR,a.NULL_CELL_WIDTH,a.NULL_CELL_CODE]);for(let t=0;t>22,2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):n]}set(e,t){this._data[3*e+1]=t[a.CHAR_DATA_ATTR_INDEX],t[a.CHAR_DATA_CHAR_INDEX].length>1?(this._combined[e]=t[1],this._data[3*e+0]=2097152|e|t[a.CHAR_DATA_WIDTH_INDEX]<<22):this._data[3*e+0]=t[a.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|t[a.CHAR_DATA_WIDTH_INDEX]<<22}getWidth(e){return this._data[3*e+0]>>22}hasWidth(e){return 12582912&this._data[3*e+0]}getFg(e){return this._data[3*e+1]}getBg(e){return this._data[3*e+2]}hasContent(e){return 4194303&this._data[3*e+0]}getCodePoint(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e].charCodeAt(this._combined[e].length-1):2097151&t}isCombined(e){return 2097152&this._data[3*e+0]}getString(e){let t=this._data[3*e+0];return 2097152&t?this._combined[e]:2097151&t?(0,o.stringFromCodePoint)(2097151&t):``}isProtected(e){return 536870912&this._data[3*e+2]}loadCell(e,t){return s=3*e,t.content=this._data[s+0],t.fg=this._data[s+1],t.bg=this._data[s+2],2097152&t.content&&(t.combinedData=this._combined[e]),268435456&t.bg&&(t.extended=this._extendedAttrs[e]),t}setCell(e,t){2097152&t.content&&(this._combined[e]=t.combinedData),268435456&t.bg&&(this._extendedAttrs[e]=t.extended),this._data[3*e+0]=t.content,this._data[3*e+1]=t.fg,this._data[3*e+2]=t.bg}setCellFromCodepoint(e,t,n,r){268435456&r.bg&&(this._extendedAttrs[e]=r.extended),this._data[3*e+0]=t|n<<22,this._data[3*e+1]=r.fg,this._data[3*e+2]=r.bg}addCodepointToCell(e,t,n){let r=this._data[3*e+0];2097152&r?this._combined[e]+=(0,o.stringFromCodePoint)(t):2097151&r?(this._combined[e]=(0,o.stringFromCodePoint)(2097151&r)+(0,o.stringFromCodePoint)(t),r&=-2097152,r|=2097152):r=t|1<<22,n&&(r&=-12582913,r|=n<<22),this._data[3*e+0]=r}insertCells(e,t,n){if((e%=this.length)&&this.getWidth(e-1)===2&&this.setCellFromCodepoint(e-1,0,1,n),t=0;--n)this.setCell(e+t+n,this.loadCell(e+n,r));for(let r=0;rthis.length){if(this._data.buffer.byteLength>=4*n)this._data=new Uint32Array(this._data.buffer,0,n);else{let e=new Uint32Array(n);e.set(this._data),this._data=e}for(let n=this.length;n=e&&delete this._combined[r]}let r=Object.keys(this._extendedAttrs);for(let t=0;t=e&&delete this._extendedAttrs[n]}}return this.length=e,4*n*2=0;--e)if(4194303&this._data[3*e+0])return e+(this._data[3*e+0]>>22);return 0}getNoBgTrimmedLength(){for(let e=this.length-1;e>=0;--e)if(4194303&this._data[3*e+0]||50331648&this._data[3*e+2])return e+(this._data[3*e+0]>>22);return 0}copyCellsFrom(e,t,n,r,i){let a=e._data;if(i)for(let i=r-1;i>=0;i--){for(let e=0;e<3;e++)this._data[3*(n+i)+e]=a[3*(t+i)+e];268435456&a[3*(t+i)+2]&&(this._extendedAttrs[n+i]=e._extendedAttrs[t+i])}else for(let i=0;i=t&&(this._combined[i-t+n]=e._combined[i])}}translateToString(e,t,n,r){t??=0,n??=this.length,e&&(n=Math.min(n,this.getTrimmedLength())),r&&(r.length=0);let i=``;for(;t>22||1}return r&&r.push(t),i}}t.BufferLine=c},9384:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.getRangeLength=function(e,t){if(e.start.y>e.end.y)throw Error(`Buffer range end (${e.end.x}, ${e.end.y}) cannot be before start (${e.start.x}, ${e.start.y})`);return t*(e.end.y-e.start.y)+(e.end.x-e.start.x+1)}},732:(e,t)=>{function n(e,t,n){if(t===e.length-1)return e[t].getTrimmedLength();let r=!e[t].hasContent(n-1)&&e[t].getWidth(n-1)===1,i=e[t+1].getWidth(0)===2;return r&&i?n-1:n}Object.defineProperty(t,"__esModule",{value:!0}),t.reflowLargerGetLinesToRemove=function(e,t,r,i,a,o){let s=[];for(let c=0;c=c&&i0&&(e>f||d[e].getTrimmedLength()===0);e--)g++;g>0&&(s.push(c+d.length-g),s.push(g)),c+=d.length-1}return s},t.reflowLargerCreateNewLayout=function(e,t){let n=[],r=0,i=t[r],a=0;for(let o=0;on(e,i,t))).reduce(((e,t)=>e+t)),o=0,s=0,c=0;for(;cl&&(o-=l,s++);let u=e[s].getWidth(o-1)===2;u&&o--;let d=u?r-1:r;i.push(d),c+=d}return i},t.getWrappedLineTrimmedLength=n},4097:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferSet=void 0;let r=n(7150),i=n(1073),a=n(802);class o extends r.Disposable{constructor(e,t){super(),this._optionsService=e,this._bufferService=t,this._onBufferActivate=this._register(new a.Emitter),this.onBufferActivate=this._onBufferActivate.event,this.reset(),this._register(this._optionsService.onSpecificOptionChange(`scrollback`,(()=>this.resize(this._bufferService.cols,this._bufferService.rows)))),this._register(this._optionsService.onSpecificOptionChange(`tabStopWidth`,(()=>this.setupTabStops())))}reset(){this._normal=new i.Buffer(!0,this._optionsService,this._bufferService),this._normal.fillViewportRows(),this._alt=new i.Buffer(!1,this._optionsService,this._bufferService),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}),this.setupTabStops()}get alt(){return this._alt}get active(){return this._activeBuffer}get normal(){return this._normal}activateNormalBuffer(){this._activeBuffer!==this._normal&&(this._normal.x=this._alt.x,this._normal.y=this._alt.y,this._alt.clearAllMarkers(),this._alt.clear(),this._activeBuffer=this._normal,this._onBufferActivate.fire({activeBuffer:this._normal,inactiveBuffer:this._alt}))}activateAltBuffer(e){this._activeBuffer!==this._alt&&(this._alt.fillViewportRows(e),this._alt.x=this._normal.x,this._alt.y=this._normal.y,this._activeBuffer=this._alt,this._onBufferActivate.fire({activeBuffer:this._alt,inactiveBuffer:this._normal}))}resize(e,t){this._normal.resize(e,t),this._alt.resize(e,t),this.setupTabStops(e)}setupTabStops(e){this._normal.setupTabStops(e),this._alt.setupTabStops(e)}}t.BufferSet=o},3055:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CellData=void 0;let r=n(726),i=n(8938),a=n(5451);class o extends a.AttributeData{constructor(){super(...arguments),this.content=0,this.fg=0,this.bg=0,this.extended=new a.ExtendedAttrs,this.combinedData=``}static fromCharData(e){let t=new o;return t.setFromCharData(e),t}isCombined(){return 2097152&this.content}getWidth(){return this.content>>22}getChars(){return 2097152&this.content?this.combinedData:2097151&this.content?(0,r.stringFromCodePoint)(2097151&this.content):``}getCode(){return this.isCombined()?this.combinedData.charCodeAt(this.combinedData.length-1):2097151&this.content}setFromCharData(e){this.fg=e[i.CHAR_DATA_ATTR_INDEX],this.bg=0;let t=!1;if(e[i.CHAR_DATA_CHAR_INDEX].length>2)t=!0;else if(e[i.CHAR_DATA_CHAR_INDEX].length===2){let n=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0);if(55296<=n&&n<=56319){let r=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(1);56320<=r&&r<=57343?this.content=1024*(n-55296)+r-56320+65536|e[i.CHAR_DATA_WIDTH_INDEX]<<22:t=!0}else t=!0}else this.content=e[i.CHAR_DATA_CHAR_INDEX].charCodeAt(0)|e[i.CHAR_DATA_WIDTH_INDEX]<<22;t&&(this.combinedData=e[i.CHAR_DATA_CHAR_INDEX],this.content=2097152|e[i.CHAR_DATA_WIDTH_INDEX]<<22)}getAsCharData(){return[this.fg,this.getChars(),this.getWidth(),this.getCode()]}}t.CellData=o},8938:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WHITESPACE_CELL_CODE=t.WHITESPACE_CELL_WIDTH=t.WHITESPACE_CELL_CHAR=t.NULL_CELL_CODE=t.NULL_CELL_WIDTH=t.NULL_CELL_CHAR=t.CHAR_DATA_CODE_INDEX=t.CHAR_DATA_WIDTH_INDEX=t.CHAR_DATA_CHAR_INDEX=t.CHAR_DATA_ATTR_INDEX=t.DEFAULT_EXT=t.DEFAULT_ATTR=t.DEFAULT_COLOR=void 0,t.DEFAULT_COLOR=0,t.DEFAULT_ATTR=t.DEFAULT_COLOR<<9|256,t.DEFAULT_EXT=0,t.CHAR_DATA_ATTR_INDEX=0,t.CHAR_DATA_CHAR_INDEX=1,t.CHAR_DATA_WIDTH_INDEX=2,t.CHAR_DATA_CODE_INDEX=3,t.NULL_CELL_CHAR=``,t.NULL_CELL_WIDTH=1,t.NULL_CELL_CODE=0,t.WHITESPACE_CELL_CHAR=` `,t.WHITESPACE_CELL_WIDTH=1,t.WHITESPACE_CELL_CODE=32},8158:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Marker=void 0;let r=n(802),i=n(7150);class a{get id(){return this._id}constructor(e){this.line=e,this.isDisposed=!1,this._disposables=[],this._id=a._nextId++,this._onDispose=this.register(new r.Emitter),this.onDispose=this._onDispose.event}dispose(){this.isDisposed||(this.isDisposed=!0,this.line=-1,this._onDispose.fire(),(0,i.dispose)(this._disposables),this._disposables.length=0)}register(e){return this._disposables.push(e),e}}t.Marker=a,a._nextId=1},6760:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_CHARSET=t.CHARSETS=void 0,t.CHARSETS={},t.DEFAULT_CHARSET=t.CHARSETS.B,t.CHARSETS[0]={"`":`◆`,a:`▒`,b:`␉`,c:`␌`,d:`␍`,e:`␊`,f:`°`,g:`±`,h:`␤`,i:`␋`,j:`┘`,k:`┐`,l:`┌`,m:`└`,n:`┼`,o:`⎺`,p:`⎻`,q:`─`,r:`⎼`,s:`⎽`,t:`├`,u:`┤`,v:`┴`,w:`┬`,x:`│`,y:`≤`,z:`≥`,"{":`π`,"|":`≠`,"}":`£`,"~":`·`},t.CHARSETS.A={"#":`£`},t.CHARSETS.B=void 0,t.CHARSETS[4]={"#":`£`,"@":`¾`,"[":`ij`,"\\":`½`,"]":`|`,"{":`¨`,"|":`f`,"}":`¼`,"~":`´`},t.CHARSETS.C=t.CHARSETS[5]={"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS.R={"#":`£`,"@":`à`,"[":`°`,"\\":`ç`,"]":`§`,"{":`é`,"|":`ù`,"}":`è`,"~":`¨`},t.CHARSETS.Q={"@":`à`,"[":`â`,"\\":`ç`,"]":`ê`,"^":`î`,"`":`ô`,"{":`é`,"|":`ù`,"}":`è`,"~":`û`},t.CHARSETS.K={"@":`§`,"[":`Ä`,"\\":`Ö`,"]":`Ü`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`ß`},t.CHARSETS.Y={"#":`£`,"@":`§`,"[":`°`,"\\":`ç`,"]":`é`,"`":`ù`,"{":`à`,"|":`ò`,"}":`è`,"~":`ì`},t.CHARSETS.E=t.CHARSETS[6]={"@":`Ä`,"[":`Æ`,"\\":`Ø`,"]":`Å`,"^":`Ü`,"`":`ä`,"{":`æ`,"|":`ø`,"}":`å`,"~":`ü`},t.CHARSETS.Z={"#":`£`,"@":`§`,"[":`¡`,"\\":`Ñ`,"]":`¿`,"{":`°`,"|":`ñ`,"}":`ç`},t.CHARSETS.H=t.CHARSETS[7]={"@":`É`,"[":`Ä`,"\\":`Ö`,"]":`Å`,"^":`Ü`,"`":`é`,"{":`ä`,"|":`ö`,"}":`å`,"~":`ü`},t.CHARSETS[`=`]={"#":`ù`,"@":`à`,"[":`é`,"\\":`ç`,"]":`ê`,"^":`î`,_:`è`,"`":`ô`,"{":`ä`,"|":`ö`,"}":`ü`,"~":`û`}},3534:(e,t)=>{var n,r,i;Object.defineProperty(t,"__esModule",{value:!0}),t.C1_ESCAPED=t.C1=t.C0=void 0,function(e){e.NUL=`\0`,e.SOH=``,e.STX=``,e.ETX=``,e.EOT=``,e.ENQ=``,e.ACK=``,e.BEL=`\x07`,e.BS=`\b`,e.HT=` `,e.LF=` +`,e.VT=`\v`,e.FF=`\f`,e.CR=`\r`,e.SO=``,e.SI=``,e.DLE=``,e.DC1=``,e.DC2=``,e.DC3=``,e.DC4=``,e.NAK=``,e.SYN=``,e.ETB=``,e.CAN=``,e.EM=``,e.SUB=``,e.ESC=`\x1B`,e.FS=``,e.GS=``,e.RS=``,e.US=``,e.SP=` `,e.DEL=``}(n||(t.C0=n={})),function(e){e.PAD=`€`,e.HOP=``,e.BPH=`‚`,e.NBH=`ƒ`,e.IND=`„`,e.NEL=`…`,e.SSA=`†`,e.ESA=`‡`,e.HTS=`ˆ`,e.HTJ=`‰`,e.VTS=`Š`,e.PLD=`‹`,e.PLU=`Œ`,e.RI=``,e.SS2=`Ž`,e.SS3=``,e.DCS=``,e.PU1=`‘`,e.PU2=`’`,e.STS=`“`,e.CCH=`”`,e.MW=`•`,e.SPA=`–`,e.EPA=`—`,e.SOS=`˜`,e.SGCI=`™`,e.SCI=`š`,e.CSI=`›`,e.ST=`œ`,e.OSC=``,e.PM=`ž`,e.APC=`Ÿ`}(r||(t.C1=r={})),function(e){e.ST=`${n.ESC}\\`}(i||(t.C1_ESCAPED=i={}))},706:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.evaluateKeyboardEvent=function(e,t,n,a){let o={type:0,cancel:!1,key:void 0},s=+!!e.shiftKey|(e.altKey?2:0)|(e.ctrlKey?4:0)|(e.metaKey?8:0);switch(e.keyCode){case 0:e.key===`UIKeyInputUpArrow`?o.key=t?r.C0.ESC+`OA`:r.C0.ESC+`[A`:e.key===`UIKeyInputLeftArrow`?o.key=t?r.C0.ESC+`OD`:r.C0.ESC+`[D`:e.key===`UIKeyInputRightArrow`?o.key=t?r.C0.ESC+`OC`:r.C0.ESC+`[C`:e.key===`UIKeyInputDownArrow`&&(o.key=t?r.C0.ESC+`OB`:r.C0.ESC+`[B`);break;case 8:o.key=e.ctrlKey?`\b`:r.C0.DEL,e.altKey&&(o.key=r.C0.ESC+o.key);break;case 9:if(e.shiftKey){o.key=r.C0.ESC+`[Z`;break}o.key=r.C0.HT,o.cancel=!0;break;case 13:o.key=e.altKey?r.C0.ESC+r.C0.CR:r.C0.CR,o.cancel=!0;break;case 27:o.key=r.C0.ESC,e.altKey&&(o.key=r.C0.ESC+r.C0.ESC),o.cancel=!0;break;case 37:if(e.metaKey)break;o.key=s?r.C0.ESC+`[1;`+(s+1)+`D`:t?r.C0.ESC+`OD`:r.C0.ESC+`[D`;break;case 39:if(e.metaKey)break;o.key=s?r.C0.ESC+`[1;`+(s+1)+`C`:t?r.C0.ESC+`OC`:r.C0.ESC+`[C`;break;case 38:if(e.metaKey)break;o.key=s?r.C0.ESC+`[1;`+(s+1)+`A`:t?r.C0.ESC+`OA`:r.C0.ESC+`[A`;break;case 40:if(e.metaKey)break;o.key=s?r.C0.ESC+`[1;`+(s+1)+`B`:t?r.C0.ESC+`OB`:r.C0.ESC+`[B`;break;case 45:e.shiftKey||e.ctrlKey||(o.key=r.C0.ESC+`[2~`);break;case 46:o.key=s?r.C0.ESC+`[3;`+(s+1)+`~`:r.C0.ESC+`[3~`;break;case 36:o.key=s?r.C0.ESC+`[1;`+(s+1)+`H`:t?r.C0.ESC+`OH`:r.C0.ESC+`[H`;break;case 35:o.key=s?r.C0.ESC+`[1;`+(s+1)+`F`:t?r.C0.ESC+`OF`:r.C0.ESC+`[F`;break;case 33:e.shiftKey?o.type=2:o.key=e.ctrlKey?r.C0.ESC+`[5;`+(s+1)+`~`:r.C0.ESC+`[5~`;break;case 34:e.shiftKey?o.type=3:o.key=e.ctrlKey?r.C0.ESC+`[6;`+(s+1)+`~`:r.C0.ESC+`[6~`;break;case 112:o.key=s?r.C0.ESC+`[1;`+(s+1)+`P`:r.C0.ESC+`OP`;break;case 113:o.key=s?r.C0.ESC+`[1;`+(s+1)+`Q`:r.C0.ESC+`OQ`;break;case 114:o.key=s?r.C0.ESC+`[1;`+(s+1)+`R`:r.C0.ESC+`OR`;break;case 115:o.key=s?r.C0.ESC+`[1;`+(s+1)+`S`:r.C0.ESC+`OS`;break;case 116:o.key=s?r.C0.ESC+`[15;`+(s+1)+`~`:r.C0.ESC+`[15~`;break;case 117:o.key=s?r.C0.ESC+`[17;`+(s+1)+`~`:r.C0.ESC+`[17~`;break;case 118:o.key=s?r.C0.ESC+`[18;`+(s+1)+`~`:r.C0.ESC+`[18~`;break;case 119:o.key=s?r.C0.ESC+`[19;`+(s+1)+`~`:r.C0.ESC+`[19~`;break;case 120:o.key=s?r.C0.ESC+`[20;`+(s+1)+`~`:r.C0.ESC+`[20~`;break;case 121:o.key=s?r.C0.ESC+`[21;`+(s+1)+`~`:r.C0.ESC+`[21~`;break;case 122:o.key=s?r.C0.ESC+`[23;`+(s+1)+`~`:r.C0.ESC+`[23~`;break;case 123:o.key=s?r.C0.ESC+`[24;`+(s+1)+`~`:r.C0.ESC+`[24~`;break;default:if(!e.ctrlKey||e.shiftKey||e.altKey||e.metaKey){if(n&&!a||!e.altKey||e.metaKey)!n||e.altKey||e.ctrlKey||e.shiftKey||!e.metaKey?e.key&&!e.ctrlKey&&!e.altKey&&!e.metaKey&&e.keyCode>=48&&e.key.length===1?o.key=e.key:e.key&&e.ctrlKey&&(e.key===`_`&&(o.key=r.C0.US),e.key===`@`&&(o.key=r.C0.NUL)):e.keyCode===65&&(o.type=1);else{let t=i[e.keyCode]?.[+!!e.shiftKey];if(t)o.key=r.C0.ESC+t;else if(e.keyCode>=65&&e.keyCode<=90){let t=e.ctrlKey?e.keyCode-64:e.keyCode+32,n=String.fromCharCode(t);e.shiftKey&&(n=n.toUpperCase()),o.key=r.C0.ESC+n}else if(e.keyCode===32)o.key=r.C0.ESC+(e.ctrlKey?r.C0.NUL:` `);else if(e.key===`Dead`&&e.code.startsWith(`Key`)){let t=e.code.slice(3,4);e.shiftKey||(t=t.toLowerCase()),o.key=r.C0.ESC+t,o.cancel=!0}}}else e.keyCode>=65&&e.keyCode<=90?o.key=String.fromCharCode(e.keyCode-64):e.keyCode===32?o.key=r.C0.NUL:e.keyCode>=51&&e.keyCode<=55?o.key=String.fromCharCode(e.keyCode-51+27):e.keyCode===56?o.key=r.C0.DEL:e.keyCode===219?o.key=r.C0.ESC:e.keyCode===220?o.key=r.C0.FS:e.keyCode===221&&(o.key=r.C0.GS)}return o};let r=n(3534),i={48:[`0`,`)`],49:[`1`,`!`],50:[`2`,`@`],51:[`3`,`#`],52:[`4`,`$`],53:[`5`,`%`],54:[`6`,`^`],55:[`7`,`&`],56:[`8`,`*`],57:[`9`,`(`],186:[`;`,`:`],187:[`=`,`+`],188:[`,`,`<`],189:[`-`,`_`],190:[`.`,`>`],191:[`/`,`?`],192:["`",`~`],219:[`[`,`{`],220:[`\\`,`|`],221:[`]`,`}`],222:[`'`,`"`]}},726:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Utf8ToUtf32=t.StringToUtf32=void 0,t.stringFromCodePoint=function(e){return e>65535?(e-=65536,String.fromCharCode(55296+(e>>10))+String.fromCharCode(e%1024+56320)):String.fromCharCode(e)},t.utf32ToString=function(e,t=0,n=e.length){let r=``;for(let i=t;i65535?(t-=65536,r+=String.fromCharCode(55296+(t>>10))+String.fromCharCode(t%1024+56320)):r+=String.fromCharCode(t)}return r},t.StringToUtf32=class{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let n=e.length;if(!n)return 0;let r=0,i=0;if(this._interim){let n=e.charCodeAt(i++);56320<=n&&n<=57343?t[r++]=1024*(this._interim-55296)+n-56320+65536:(t[r++]=this._interim,t[r++]=n),this._interim=0}for(let a=i;a=n)return this._interim=i,r;let o=e.charCodeAt(a);56320<=o&&o<=57343?t[r++]=1024*(i-55296)+o-56320+65536:(t[r++]=i,t[r++]=o)}else i!==65279&&(t[r++]=i)}return r}},t.Utf8ToUtf32=class{constructor(){this.interim=/* @__PURE__ */ new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let n=e.length;if(!n)return 0;let r,i,a,o,s=0,c=0,l=0;if(this.interim[0]){let r=!1,i=this.interim[0];i&=(224&i)==192?31:(240&i)==224?15:7;let a,o=0;for(;(a=63&this.interim[++o])&&o<4;)i<<=6,i|=a;let c=(224&this.interim[0])==192?2:(240&this.interim[0])==224?3:4,u=c-o;for(;l=n)return 0;if(a=e[l++],(192&a)!=128){l--,r=!0;break}this.interim[o++]=a,i<<=6,i|=63&a}r||(c===2?i<128?l--:t[s++]=i:c===3?i<2048||i>=55296&&i<=57343||i===65279||(t[s++]=i):i<65536||i>1114111||(t[s++]=i)),this.interim.fill(0)}let u=n-4,d=l;for(;d=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128||(c=(31&r)<<6|63&i,c<128)){d--;continue}t[s++]=c}else if((240&r)==224){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,s;if(a=e[d++],(192&a)!=128){d--;continue}if(c=(15&r)<<12|(63&i)<<6|63&a,c<2048||c>=55296&&c<=57343||c===65279)continue;t[s++]=c}else if((248&r)==240){if(d>=n)return this.interim[0]=r,s;if(i=e[d++],(192&i)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,s;if(a=e[d++],(192&a)!=128){d--;continue}if(d>=n)return this.interim[0]=r,this.interim[1]=i,this.interim[2]=a,s;if(o=e[d++],(192&o)!=128){d--;continue}if(c=(7&r)<<18|(63&i)<<12|(63&a)<<6|63&o,c<65536||c>1114111)continue;t[s++]=c}}return s}}},7428:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeV6=void 0;let r=n(6415),i=[[768,879],[1155,1158],[1160,1161],[1425,1469],[1471,1471],[1473,1474],[1476,1477],[1479,1479],[1536,1539],[1552,1557],[1611,1630],[1648,1648],[1750,1764],[1767,1768],[1770,1773],[1807,1807],[1809,1809],[1840,1866],[1958,1968],[2027,2035],[2305,2306],[2364,2364],[2369,2376],[2381,2381],[2385,2388],[2402,2403],[2433,2433],[2492,2492],[2497,2500],[2509,2509],[2530,2531],[2561,2562],[2620,2620],[2625,2626],[2631,2632],[2635,2637],[2672,2673],[2689,2690],[2748,2748],[2753,2757],[2759,2760],[2765,2765],[2786,2787],[2817,2817],[2876,2876],[2879,2879],[2881,2883],[2893,2893],[2902,2902],[2946,2946],[3008,3008],[3021,3021],[3134,3136],[3142,3144],[3146,3149],[3157,3158],[3260,3260],[3263,3263],[3270,3270],[3276,3277],[3298,3299],[3393,3395],[3405,3405],[3530,3530],[3538,3540],[3542,3542],[3633,3633],[3636,3642],[3655,3662],[3761,3761],[3764,3769],[3771,3772],[3784,3789],[3864,3865],[3893,3893],[3895,3895],[3897,3897],[3953,3966],[3968,3972],[3974,3975],[3984,3991],[3993,4028],[4038,4038],[4141,4144],[4146,4146],[4150,4151],[4153,4153],[4184,4185],[4448,4607],[4959,4959],[5906,5908],[5938,5940],[5970,5971],[6002,6003],[6068,6069],[6071,6077],[6086,6086],[6089,6099],[6109,6109],[6155,6157],[6313,6313],[6432,6434],[6439,6440],[6450,6450],[6457,6459],[6679,6680],[6912,6915],[6964,6964],[6966,6970],[6972,6972],[6978,6978],[7019,7027],[7616,7626],[7678,7679],[8203,8207],[8234,8238],[8288,8291],[8298,8303],[8400,8431],[12330,12335],[12441,12442],[43014,43014],[43019,43019],[43045,43046],[64286,64286],[65024,65039],[65056,65059],[65279,65279],[65529,65531]],a=[[68097,68099],[68101,68102],[68108,68111],[68152,68154],[68159,68159],[119143,119145],[119155,119170],[119173,119179],[119210,119213],[119362,119364],[917505,917505],[917536,917631],[917760,917999]],o;t.UnicodeV6=class{constructor(){if(this.version=`6`,!o){o=/* @__PURE__ */ new Uint8Array(65536),o.fill(1),o[0]=0,o.fill(0,1,32),o.fill(0,127,160),o.fill(2,4352,4448),o[9001]=2,o[9002]=2,o.fill(2,11904,42192),o[12351]=1,o.fill(2,44032,55204),o.fill(2,63744,64256),o.fill(2,65040,65050),o.fill(2,65072,65136),o.fill(2,65280,65377),o.fill(2,65504,65511);for(let e=0;et[i][1])return!1;for(;i>=r;)if(n=r+i>>1,e>t[n][1])r=n+1;else{if(!(e=131072&&e<=196605||e>=196608&&e<=262141?2:1}charProperties(e,t){let n=this.wcwidth(e),i=n===0&&t!==0;if(i){let e=r.UnicodeService.extractWidth(t);e===0?i=!1:e>n&&(n=e)}return r.UnicodeService.createPropertyValue(0,n,i)}}},3562:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.WriteBuffer=void 0;let r=n(7150),i=n(802);class a extends r.Disposable{constructor(e){super(),this._action=e,this._writeBuffer=[],this._callbacks=[],this._pendingData=0,this._bufferOffset=0,this._isSyncWriting=!1,this._syncCalls=0,this._didUserInput=!1,this._onWriteParsed=this._register(new i.Emitter),this.onWriteParsed=this._onWriteParsed.event}handleUserInput(){this._didUserInput=!0}writeSync(e,t){if(t!==void 0&&this._syncCalls>t)return void(this._syncCalls=0);if(this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(void 0),this._syncCalls++,this._isSyncWriting)return;let n;for(this._isSyncWriting=!0;n=this._writeBuffer.shift();){this._action(n);let e=this._callbacks.shift();e&&e()}this._pendingData=0,this._bufferOffset=2147483647,this._isSyncWriting=!1,this._syncCalls=0}write(e,t){if(this._pendingData>5e7)throw Error(`write data discarded, use flow control to avoid losing data`);if(!this._writeBuffer.length){if(this._bufferOffset=0,this._didUserInput)return this._didUserInput=!1,this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t),void this._innerWrite();setTimeout((()=>this._innerWrite()))}this._pendingData+=e.length,this._writeBuffer.push(e),this._callbacks.push(t)}_innerWrite(e=0,t=!0){let n=e||performance.now();for(;this._writeBuffer.length>this._bufferOffset;){let e=this._writeBuffer[this._bufferOffset],r=this._action(e,t);if(r){r.catch((e=>(queueMicrotask((()=>{throw e})),Promise.resolve(!1)))).then(e=>performance.now()-n>=12?setTimeout((()=>this._innerWrite(0,e))):this._innerWrite(n,e));return}let i=this._callbacks[this._bufferOffset];if(i&&i(),this._bufferOffset++,this._pendingData-=e.length,performance.now()-n>=12)break}this._writeBuffer.length>this._bufferOffset?(this._bufferOffset>50&&(this._writeBuffer=this._writeBuffer.slice(this._bufferOffset),this._callbacks=this._callbacks.slice(this._bufferOffset),this._bufferOffset=0),setTimeout((()=>this._innerWrite()))):(this._writeBuffer.length=0,this._callbacks.length=0,this._pendingData=0,this._bufferOffset=0),this._onWriteParsed.fire()}}t.WriteBuffer=a},8693:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseColor=function(e){if(!e)return;let t=e.toLowerCase();if(t.indexOf(`rgb:`)===0){t=t.slice(4);let e=n.exec(t);if(e){let t=e[1]?15:e[4]?255:e[7]?4095:65535;return[Math.round(parseInt(e[1]||e[4]||e[7]||e[10],16)/t*255),Math.round(parseInt(e[2]||e[5]||e[8]||e[11],16)/t*255),Math.round(parseInt(e[3]||e[6]||e[9]||e[12],16)/t*255)]}}else if(t.indexOf(`#`)===0&&(t=t.slice(1),r.exec(t)&&[3,6,9,12].includes(t.length))){let e=t.length/3,n=[0,0,0];for(let r=0;r<3;++r){let i=parseInt(t.slice(e*r,e*r+e),16);n[r]=e===1?i<<4:e===2?i:e===3?i>>4:i>>8}return n}},t.toRgbString=function(e,t=16){let[n,r,a]=e;return`rgb:${i(n,t)}/${i(r,t)}/${i(a,t)}`};let n=/^([\da-f])\/([\da-f])\/([\da-f])$|^([\da-f]{2})\/([\da-f]{2})\/([\da-f]{2})$|^([\da-f]{3})\/([\da-f]{3})\/([\da-f]{3})$|^([\da-f]{4})\/([\da-f]{4})\/([\da-f]{4})$/,r=/^[\da-f]+$/;function i(e,t){let n=e.toString(16),r=n.length<2?`0`+n:n;switch(t){case 4:return n[0];case 8:return r;case 12:return(r+r).slice(0,3);default:return r+r}}},1263:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.PAYLOAD_LIMIT=void 0,t.PAYLOAD_LIMIT=1e7},9823:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DcsHandler=t.DcsParser=void 0;let r=n(726),i=n(7262),a=n(1263),o=[];t.DcsParser=class{constructor(){this._handlers=Object.create(null),this._active=o,this._ident=0,this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=o}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}reset(){if(this._active.length)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].unhook(!1);this._stack.paused=!1,this._active=o,this._ident=0}hook(e,t){if(this.reset(),this._ident=e,this._active=this._handlers[e]||o,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].hook(t);else this._handlerFb(this._ident,`HOOK`,t)}put(e,t,n){if(this._active.length)for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n);else this._handlerFb(this._ident,`PUT`,(0,r.utf32ToString)(e,t,n))}unhook(e,t=!0){if(this._active.length){let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===n){for(;r>=0&&(n=this._active[r].unhook(e),!0!==n);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].unhook(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}else this._handlerFb(this._ident,`UNHOOK`,e);this._active=o,this._ident=0}};let s=new i.Params;s.addParam(0),t.DcsHandler=class{constructor(e){this._handler=e,this._data=``,this._params=s,this._hitLimit=!1}hook(e){this._params=e.length>1||e.params[0]?e.clone():s,this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=(0,r.utf32ToString)(e,t,n),this._data.length>a.PAYLOAD_LIMIT&&(this._data=``,this._hitLimit=!0))}unhook(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data,this._params),t instanceof Promise))return t.then((e=>(this._params=s,this._data=``,this._hitLimit=!1,e)));return this._params=s,this._data=``,this._hitLimit=!1,t}}},6717:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.EscapeSequenceParser=t.VT500_TRANSITION_TABLE=t.TransitionTable=void 0;let r=n(7150),i=n(7262),a=n(1346),o=n(9823);class s{constructor(e){this.table=new Uint8Array(e)}setDefault(e,t){this.table.fill(e<<4|t)}add(e,t,n,r){this.table[t<<8|e]=n<<4|r}addMany(e,t,n,r){for(let i=0;it)),n=(e,n)=>t.slice(e,n),r=n(32,127),i=n(0,24);i.push(25),i.push.apply(i,n(28,32));let a=n(0,14),o;for(o in e.setDefault(1,0),e.addMany(r,0,2,0),a)e.addMany([24,26,153,154],o,3,0),e.addMany(n(128,144),o,3,0),e.addMany(n(144,152),o,3,0),e.add(156,o,0,0),e.add(27,o,11,1),e.add(157,o,4,8),e.addMany([152,158,159],o,0,7),e.add(155,o,11,3),e.add(144,o,11,9);return e.addMany(i,0,3,0),e.addMany(i,1,3,1),e.add(127,1,0,1),e.addMany(i,8,0,8),e.addMany(i,3,3,3),e.add(127,3,0,3),e.addMany(i,4,3,4),e.add(127,4,0,4),e.addMany(i,6,3,6),e.addMany(i,5,3,5),e.add(127,5,0,5),e.addMany(i,2,3,2),e.add(127,2,0,2),e.add(93,1,4,8),e.addMany(r,8,5,8),e.add(127,8,5,8),e.addMany([156,27,24,26,7],8,6,0),e.addMany(n(28,32),8,0,8),e.addMany([88,94,95],1,0,7),e.addMany(r,7,0,7),e.addMany(i,7,0,7),e.add(156,7,0,0),e.add(127,7,0,7),e.add(91,1,11,3),e.addMany(n(64,127),3,7,0),e.addMany(n(48,60),3,8,4),e.addMany([60,61,62,63],3,9,4),e.addMany(n(48,60),4,8,4),e.addMany(n(64,127),4,7,0),e.addMany([60,61,62,63],4,0,6),e.addMany(n(32,64),6,0,6),e.add(127,6,0,6),e.addMany(n(64,127),6,0,0),e.addMany(n(32,48),3,9,5),e.addMany(n(32,48),5,9,5),e.addMany(n(48,64),5,0,6),e.addMany(n(64,127),5,7,0),e.addMany(n(32,48),4,9,5),e.addMany(n(32,48),1,9,2),e.addMany(n(32,48),2,9,2),e.addMany(n(48,127),2,10,0),e.addMany(n(48,80),1,10,0),e.addMany(n(81,88),1,10,0),e.addMany([89,90,92],1,10,0),e.addMany(n(96,127),1,10,0),e.add(80,1,11,9),e.addMany(i,9,0,9),e.add(127,9,0,9),e.addMany(n(28,32),9,0,9),e.addMany(n(32,48),9,9,12),e.addMany(n(48,60),9,8,10),e.addMany([60,61,62,63],9,9,10),e.addMany(i,11,0,11),e.addMany(n(32,128),11,0,11),e.addMany(n(28,32),11,0,11),e.addMany(i,10,0,10),e.add(127,10,0,10),e.addMany(n(28,32),10,0,10),e.addMany(n(48,60),10,8,10),e.addMany([60,61,62,63],10,0,11),e.addMany(n(32,48),10,9,12),e.addMany(i,12,0,12),e.add(127,12,0,12),e.addMany(n(28,32),12,0,12),e.addMany(n(32,48),12,9,12),e.addMany(n(48,64),12,0,11),e.addMany(n(64,127),12,12,13),e.addMany(n(64,127),10,12,13),e.addMany(n(64,127),9,12,13),e.addMany(i,13,13,13),e.addMany(r,13,13,13),e.add(127,13,0,13),e.addMany([27,156,24,26],13,14,0),e.add(160,0,2,0),e.add(160,8,5,8),e.add(160,6,0,6),e.add(160,11,0,11),e.add(160,13,13,13),e}();class c extends r.Disposable{constructor(e=t.VT500_TRANSITION_TABLE){super(),this._transitions=e,this._parseStack={state:0,handlers:[],handlerPos:0,transition:0,chunkPos:0},this.initialState=0,this.currentState=this.initialState,this._params=new i.Params,this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._printHandlerFb=(e,t,n)=>{},this._executeHandlerFb=e=>{},this._csiHandlerFb=(e,t)=>{},this._escHandlerFb=e=>{},this._errorHandlerFb=e=>e,this._printHandler=this._printHandlerFb,this._executeHandlers=Object.create(null),this._csiHandlers=Object.create(null),this._escHandlers=Object.create(null),this._register((0,r.toDisposable)((()=>{this._csiHandlers=Object.create(null),this._executeHandlers=Object.create(null),this._escHandlers=Object.create(null)}))),this._oscParser=this._register(new a.OscParser),this._dcsParser=this._register(new o.DcsParser),this._errorHandler=this._errorHandlerFb,this.registerEscHandler({final:`\\`},(()=>!0))}_identifier(e,t=[64,126]){let n=0;if(e.prefix){if(e.prefix.length>1)throw Error(`only one byte as prefix supported`);if(n=e.prefix.charCodeAt(0),n&&60>n||n>63)throw Error(`prefix must be in range 0x3c .. 0x3f`)}if(e.intermediates){if(e.intermediates.length>2)throw Error(`only two bytes as intermediates are supported`);for(let t=0;tr||r>47)throw Error(`intermediate must be in range 0x20 .. 0x2f`);n<<=8,n|=r}}if(e.final.length!==1)throw Error(`final must be a single byte`);let r=e.final.charCodeAt(0);if(t[0]>r||r>t[1])throw Error(`final must be in range ${t[0]} .. ${t[1]}`);return n<<=8,n|=r,n}identToString(e){let t=[];for(;e;)t.push(String.fromCharCode(255&e)),e>>=8;return t.reverse().join(``)}setPrintHandler(e){this._printHandler=e}clearPrintHandler(){this._printHandler=this._printHandlerFb}registerEscHandler(e,t){let n=this._identifier(e,[48,126]);this._escHandlers[n]===void 0&&(this._escHandlers[n]=[]);let r=this._escHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearEscHandler(e){this._escHandlers[this._identifier(e,[48,126])]&&delete this._escHandlers[this._identifier(e,[48,126])]}setEscHandlerFallback(e){this._escHandlerFb=e}setExecuteHandler(e,t){this._executeHandlers[e.charCodeAt(0)]=t}clearExecuteHandler(e){this._executeHandlers[e.charCodeAt(0)]&&delete this._executeHandlers[e.charCodeAt(0)]}setExecuteHandlerFallback(e){this._executeHandlerFb=e}registerCsiHandler(e,t){let n=this._identifier(e);this._csiHandlers[n]===void 0&&(this._csiHandlers[n]=[]);let r=this._csiHandlers[n];return r.push(t),{dispose:()=>{let e=r.indexOf(t);e!==-1&&r.splice(e,1)}}}clearCsiHandler(e){this._csiHandlers[this._identifier(e)]&&delete this._csiHandlers[this._identifier(e)]}setCsiHandlerFallback(e){this._csiHandlerFb=e}registerDcsHandler(e,t){return this._dcsParser.registerHandler(this._identifier(e),t)}clearDcsHandler(e){this._dcsParser.clearHandler(this._identifier(e))}setDcsHandlerFallback(e){this._dcsParser.setHandlerFallback(e)}registerOscHandler(e,t){return this._oscParser.registerHandler(e,t)}clearOscHandler(e){this._oscParser.clearHandler(e)}setOscHandlerFallback(e){this._oscParser.setHandlerFallback(e)}setErrorHandler(e){this._errorHandler=e}clearErrorHandler(){this._errorHandler=this._errorHandlerFb}reset(){this.currentState=this.initialState,this._oscParser.reset(),this._dcsParser.reset(),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0,this._parseStack.state!==0&&(this._parseStack.state=2,this._parseStack.handlers=[])}_preserveStack(e,t,n,r,i){this._parseStack.state=e,this._parseStack.handlers=t,this._parseStack.handlerPos=n,this._parseStack.transition=r,this._parseStack.chunkPos=i}parse(e,t,n){let r,i=0,a=0,o=0;if(this._parseStack.state){if(this._parseStack.state===2)this._parseStack.state=0,o=this._parseStack.chunkPos+1;else{if(n===void 0||this._parseStack.state===1)throw this._parseStack.state=1,/* @__PURE__ */ Error(`improper continuation due to previous async handler, giving up parsing`);let t=this._parseStack.handlers,a=this._parseStack.handlerPos-1;switch(this._parseStack.state){case 3:if(!1===n&&a>-1){for(;a>=0&&(r=t[a](this._params),!0!==r);a--)if(r instanceof Promise)return this._parseStack.handlerPos=a,r}this._parseStack.handlers=[];break;case 4:if(!1===n&&a>-1){for(;a>=0&&(r=t[a](),!0!==r);a--)if(r instanceof Promise)return this._parseStack.handlerPos=a,r}this._parseStack.handlers=[];break;case 6:if(i=e[this._parseStack.chunkPos],r=this._dcsParser.unhook(i!==24&&i!==26,n),r)return r;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0;break;case 5:if(i=e[this._parseStack.chunkPos],r=this._oscParser.end(i!==24&&i!==26,n),r)return r;i===27&&(this._parseStack.transition|=1),this._params.reset(),this._params.addParam(0),this._collect=0}this._parseStack.state=0,o=this._parseStack.chunkPos+1,this.precedingJoinState=0,this.currentState=15&this._parseStack.transition}}for(let n=o;n>4){case 2:for(let r=n+1;;++r)if(r>=t||(i=e[r])<32||i>126&&i<160||++r>=t||(i=e[r])<32||i>126&&i<160||++r>=t||(i=e[r])<32||i>126&&i<160||++r>=t||(i=e[r])<32||i>126&&i<160){this._printHandler(e,n,r),n=r-1;break}break;case 3:this._executeHandlers[i]?this._executeHandlers[i]():this._executeHandlerFb(i),this.precedingJoinState=0;break;case 0:break;case 1:if(this._errorHandler({position:n,code:i,currentState:this.currentState,collect:this._collect,params:this._params,abort:!1}).abort)return;break;case 7:let o=this._csiHandlers[this._collect<<8|i],s=o?o.length-1:-1;for(;s>=0&&(r=o[s](this._params),!0!==r);s--)if(r instanceof Promise)return this._preserveStack(3,o,s,a,n),r;s<0&&this._csiHandlerFb(this._collect<<8|i,this._params),this.precedingJoinState=0;break;case 8:do switch(i){case 59:this._params.addParam(0);break;case 58:this._params.addSubParam(-1);break;default:this._params.addDigit(i-48)}while(++n47&&i<60);n--;break;case 9:this._collect<<=8,this._collect|=i;break;case 10:let c=this._escHandlers[this._collect<<8|i],l=c?c.length-1:-1;for(;l>=0&&(r=c[l](),!0!==r);l--)if(r instanceof Promise)return this._preserveStack(4,c,l,a,n),r;l<0&&this._escHandlerFb(this._collect<<8|i),this.precedingJoinState=0;break;case 11:this._params.reset(),this._params.addParam(0),this._collect=0;break;case 12:this._dcsParser.hook(this._collect<<8|i,this._params);break;case 13:for(let r=n+1;;++r)if(r>=t||(i=e[r])===24||i===26||i===27||i>127&&i<160){this._dcsParser.put(e,n,r),n=r-1;break}break;case 14:if(r=this._dcsParser.unhook(i!==24&&i!==26),r)return this._preserveStack(6,[],0,a,n),r;i===27&&(a|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0;break;case 4:this._oscParser.start();break;case 5:for(let r=n+1;;r++)if(r>=t||(i=e[r])<32||i>127&&i<160){this._oscParser.put(e,n,r),n=r-1;break}break;case 6:if(r=this._oscParser.end(i!==24&&i!==26),r)return this._preserveStack(5,[],0,a,n),r;i===27&&(a|=1),this._params.reset(),this._params.addParam(0),this._collect=0,this.precedingJoinState=0}this.currentState=15&a}}}t.EscapeSequenceParser=c},1346:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OscHandler=t.OscParser=void 0;let r=n(1263),i=n(726),a=[];t.OscParser=class{constructor(){this._state=0,this._active=a,this._id=-1,this._handlers=Object.create(null),this._handlerFb=()=>{},this._stack={paused:!1,loopPosition:0,fallThrough:!1}}registerHandler(e,t){this._handlers[e]===void 0&&(this._handlers[e]=[]);let n=this._handlers[e];return n.push(t),{dispose:()=>{let e=n.indexOf(t);e!==-1&&n.splice(e,1)}}}clearHandler(e){this._handlers[e]&&delete this._handlers[e]}setHandlerFallback(e){this._handlerFb=e}dispose(){this._handlers=Object.create(null),this._handlerFb=()=>{},this._active=a}reset(){if(this._state===2)for(let e=this._stack.paused?this._stack.loopPosition-1:this._active.length-1;e>=0;--e)this._active[e].end(!1);this._stack.paused=!1,this._active=a,this._id=-1,this._state=0}_start(){if(this._active=this._handlers[this._id]||a,this._active.length)for(let e=this._active.length-1;e>=0;e--)this._active[e].start();else this._handlerFb(this._id,`START`)}_put(e,t,n){if(this._active.length)for(let r=this._active.length-1;r>=0;r--)this._active[r].put(e,t,n);else this._handlerFb(this._id,`PUT`,(0,i.utf32ToString)(e,t,n))}start(){this.reset(),this._state=1}put(e,t,n){if(this._state!==3){if(this._state===1)for(;t0&&this._put(e,t,n)}}end(e,t=!0){if(this._state!==0){if(this._state!==3){if(this._state===1&&this._start(),this._active.length){let n=!1,r=this._active.length-1,i=!1;if(this._stack.paused&&(r=this._stack.loopPosition-1,n=t,i=this._stack.fallThrough,this._stack.paused=!1),!i&&!1===n){for(;r>=0&&(n=this._active[r].end(e),!0!==n);r--)if(n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!1,n;r--}for(;r>=0;r--)if(n=this._active[r].end(!1),n instanceof Promise)return this._stack.paused=!0,this._stack.loopPosition=r,this._stack.fallThrough=!0,n}else this._handlerFb(this._id,`END`,e)}this._active=a,this._id=-1,this._state=0}}},t.OscHandler=class{constructor(e){this._handler=e,this._data=``,this._hitLimit=!1}start(){this._data=``,this._hitLimit=!1}put(e,t,n){this._hitLimit||(this._data+=(0,i.utf32ToString)(e,t,n),this._data.length>r.PAYLOAD_LIMIT&&(this._data=``,this._hitLimit=!0))}end(e){let t=!1;if(this._hitLimit)t=!1;else if(e&&(t=this._handler(this._data),t instanceof Promise))return t.then((e=>(this._data=``,this._hitLimit=!1,e)));return this._data=``,this._hitLimit=!1,t}}},7262:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Params=void 0;let n=2147483647;class r{static fromArray(e){let t=new r;if(!e.length)return t;for(let n=+!!Array.isArray(e[0]);n256)throw Error(`maxSubParamsLength must not be greater than 256`);this.params=new Int32Array(e),this.length=0,this._subParams=new Int32Array(t),this._subParamsLength=0,this._subParamsIdx=new Uint16Array(e),this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}clone(){let e=new r(this.maxLength,this.maxSubParamsLength);return e.params.set(this.params),e.length=this.length,e._subParams.set(this._subParams),e._subParamsLength=this._subParamsLength,e._subParamsIdx.set(this._subParamsIdx),e._rejectDigits=this._rejectDigits,e._rejectSubDigits=this._rejectSubDigits,e._digitIsSub=this._digitIsSub,e}toArray(){let e=[];for(let t=0;t>8,r=255&this._subParamsIdx[t];r-n>0&&e.push(Array.prototype.slice.call(this._subParams,n,r))}return e}reset(){this.length=0,this._subParamsLength=0,this._rejectDigits=!1,this._rejectSubDigits=!1,this._digitIsSub=!1}addParam(e){if(this._digitIsSub=!1,this.length>=this.maxLength)this._rejectDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParamsIdx[this.length]=this._subParamsLength<<8|this._subParamsLength,this.params[this.length++]=e>n?n:e}}addSubParam(e){if(this._digitIsSub=!0,this.length){if(this._rejectDigits||this._subParamsLength>=this.maxSubParamsLength)this._rejectSubDigits=!0;else{if(e<-1)throw Error(`values lesser than -1 are not allowed`);this._subParams[this._subParamsLength++]=e>n?n:e,this._subParamsIdx[this.length-1]++}}}hasSubParams(e){return(255&this._subParamsIdx[e])-(this._subParamsIdx[e]>>8)>0}getSubParams(e){let t=this._subParamsIdx[e]>>8,n=255&this._subParamsIdx[e];return n-t>0?this._subParams.subarray(t,n):null}getSubParamsAll(){let e={};for(let t=0;t>8,r=255&this._subParamsIdx[t];r-n>0&&(e[t]=this._subParams.slice(n,r))}return e}addDigit(e){let t;if(this._rejectDigits||!(t=this._digitIsSub?this._subParamsLength:this.length)||this._digitIsSub&&this._rejectSubDigits)return;let r=this._digitIsSub?this._subParams:this.params,i=r[t-1];r[t-1]=~i?Math.min(10*i+e,n):e}}t.Params=r},3027:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AddonManager=void 0,t.AddonManager=class{constructor(){this._addons=[]}dispose(){for(let e=this._addons.length-1;e>=0;e--)this._addons[e].instance.dispose()}loadAddon(e,t){let n={instance:t,dispose:t.dispose,isDisposed:!1};this._addons.push(n),t.dispose=()=>this._wrappedAddonDispose(n),t.activate(e)}_wrappedAddonDispose(e){if(e.isDisposed)return;let t=-1;for(let n=0;n{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferApiView=void 0;let r=n(793),i=n(3055);t.BufferApiView=class{constructor(e,t){this._buffer=e,this.type=t}init(e){return this._buffer=e,this}get cursorY(){return this._buffer.y}get cursorX(){return this._buffer.x}get viewportY(){return this._buffer.ydisp}get baseY(){return this._buffer.ybase}get length(){return this._buffer.lines.length}getLine(e){let t=this._buffer.lines.get(e);if(t)return new r.BufferLineApiView(t)}getNullCell(){return new i.CellData}}},793:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferLineApiView=void 0;let r=n(3055);t.BufferLineApiView=class{constructor(e){this._line=e}get isWrapped(){return this._line.isWrapped}get length(){return this._line.length}getCell(e,t){if(!(e<0||e>=this._line.length))return t?(this._line.loadCell(e,t),t):this._line.loadCell(e,new r.CellData)}translateToString(e,t,n){return this._line.translateToString(e,t,n)}}},5101:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BufferNamespaceApi=void 0;let r=n(3235),i=n(7150),a=n(802);class o extends i.Disposable{constructor(e){super(),this._core=e,this._onBufferChange=this._register(new a.Emitter),this.onBufferChange=this._onBufferChange.event,this._normal=new r.BufferApiView(this._core.buffers.normal,`normal`),this._alternate=new r.BufferApiView(this._core.buffers.alt,`alternate`),this._core.buffers.onBufferActivate((()=>this._onBufferChange.fire(this.active)))}get active(){if(this._core.buffers.active===this._core.buffers.normal)return this.normal;if(this._core.buffers.active===this._core.buffers.alt)return this.alternate;throw Error(`Active buffer is neither normal nor alternate`)}get normal(){return this._normal.init(this._core.buffers.normal)}get alternate(){return this._alternate.init(this._core.buffers.alt)}}t.BufferNamespaceApi=o},6097:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParserApi=void 0,t.ParserApi=class{constructor(e){this._core=e}registerCsiHandler(e,t){return this._core.registerCsiHandler(e,(e=>t(e.toArray())))}addCsiHandler(e,t){return this.registerCsiHandler(e,t)}registerDcsHandler(e,t){return this._core.registerDcsHandler(e,((e,n)=>t(e,n.toArray())))}addDcsHandler(e,t){return this.registerDcsHandler(e,t)}registerEscHandler(e,t){return this._core.registerEscHandler(e,t)}addEscHandler(e,t){return this.registerEscHandler(e,t)}registerOscHandler(e,t){return this._core.registerOscHandler(e,t)}addOscHandler(e,t){return this.registerOscHandler(e,t)}}},4335:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeApi=void 0,t.UnicodeApi=class{constructor(e){this._core=e}register(e){this._core.unicodeService.register(e)}get versions(){return this._core.unicodeService.versions}get activeVersion(){return this._core.unicodeService.activeVersion}set activeVersion(e){this._core.unicodeService.activeVersion=e}}},9640:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.BufferService=t.MINIMUM_ROWS=t.MINIMUM_COLS=void 0;let a=n(7150),o=n(4097),s=n(6501),c=n(802);t.MINIMUM_COLS=2,t.MINIMUM_ROWS=1;let l=class extends a.Disposable{get buffer(){return this.buffers.active}constructor(e){super(),this.isUserScrolling=!1,this._onResize=this._register(new c.Emitter),this.onResize=this._onResize.event,this._onScroll=this._register(new c.Emitter),this.onScroll=this._onScroll.event,this.cols=Math.max(e.rawOptions.cols||0,t.MINIMUM_COLS),this.rows=Math.max(e.rawOptions.rows||0,t.MINIMUM_ROWS),this.buffers=this._register(new o.BufferSet(e,this)),this._register(this.buffers.onBufferActivate((e=>{this._onScroll.fire(e.activeBuffer.ydisp)})))}resize(e,t){let n=this.cols!==e,r=this.rows!==t;this.cols=e,this.rows=t,this.buffers.resize(e,t),this._onResize.fire({cols:e,rows:t,colsChanged:n,rowsChanged:r})}reset(){this.buffers.reset(),this.isUserScrolling=!1}scroll(e,t=!1){let n=this.buffer,r;r=this._cachedBlankLine,r&&r.length===this.cols&&r.getFg(0)===e.fg&&r.getBg(0)===e.bg||(r=n.getBlankLine(e,t),this._cachedBlankLine=r),r.isWrapped=t;let i=n.ybase+n.scrollTop,a=n.ybase+n.scrollBottom;if(n.scrollTop===0){let e=n.lines.isFull;a===n.lines.length-1?e?n.lines.recycle().copyFrom(r):n.lines.push(r.clone()):n.lines.splice(a+1,0,r.clone()),e?this.isUserScrolling&&(n.ydisp=Math.max(n.ydisp-1,0)):(n.ybase++,this.isUserScrolling||n.ydisp++)}else{let e=a-i+1;n.lines.shiftElements(i+1,e-1,-1),n.lines.set(a,r.clone())}this.isUserScrolling||(n.ydisp=n.ybase),this._onScroll.fire(n.ydisp)}scrollLines(e,t){let n=this.buffer;if(e<0){if(n.ydisp===0)return;this.isUserScrolling=!0}else e+n.ydisp>=n.ybase&&(this.isUserScrolling=!1);let r=n.ydisp;n.ydisp=Math.max(Math.min(n.ydisp+e,n.ybase),0),r!==n.ydisp&&(t||this._onScroll.fire(n.ydisp))}};t.BufferService=l,t.BufferService=l=r([i(0,s.IOptionsService)],l)},5746:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CharsetService=void 0,t.CharsetService=class{constructor(){this.glevel=0,this._charsets=[]}reset(){this.charset=void 0,this._charsets=[],this.glevel=0}setgLevel(e){this.glevel=e,this.charset=this._charsets[e]}setgCharset(e,t){this._charsets[e]=t,this.glevel===e&&(this.charset=t)}}},7792:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreMouseService=void 0;let a=n(6501),o=n(7150),s=n(802),c={NONE:{events:0,restrict:()=>!1},X10:{events:1,restrict:e=>e.button!==4&&e.action===1&&(e.ctrl=!1,e.alt=!1,e.shift=!1,!0)},VT200:{events:19,restrict:e=>e.action!==32},DRAG:{events:23,restrict:e=>e.action!==32||e.button!==3},ANY:{events:31,restrict:e=>!0}};function l(e,t){let n=(e.ctrl?16:0)|(e.shift?4:0)|(e.alt?8:0);return e.button===4?(n|=64,n|=e.action):(n|=3&e.button,4&e.button&&(n|=64),8&e.button&&(n|=128),e.action===32?n|=32:e.action!==0||t||(n|=3)),n}let u=String.fromCharCode,d={DEFAULT:e=>{let t=[l(e,!1)+32,e.col+32,e.row+32];return t[0]>255||t[1]>255||t[2]>255?``:`${u(t[0])}${u(t[1])}${u(t[2])}`},SGR:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`[<${l(e,!0)};${e.col};${e.row}${t}`},SGR_PIXELS:e=>{let t=e.action===0&&e.button!==4?`m`:`M`;return`[<${l(e,!0)};${e.x};${e.y}${t}`}},f=class extends o.Disposable{constructor(e,t,n){super(),this._bufferService=e,this._coreService=t,this._optionsService=n,this._protocols={},this._encodings={},this._activeProtocol=``,this._activeEncoding=``,this._lastEvent=null,this._wheelPartialScroll=0,this._onProtocolChange=this._register(new s.Emitter),this.onProtocolChange=this._onProtocolChange.event;for(let e of Object.keys(c))this.addProtocol(e,c[e]);for(let e of Object.keys(d))this.addEncoding(e,d[e]);this.reset()}addProtocol(e,t){this._protocols[e]=t}addEncoding(e,t){this._encodings[e]=t}get activeProtocol(){return this._activeProtocol}get areMouseEventsActive(){return this._protocols[this._activeProtocol].events!==0}set activeProtocol(e){if(!this._protocols[e])throw Error(`unknown protocol "${e}"`);this._activeProtocol=e,this._onProtocolChange.fire(this._protocols[e].events)}get activeEncoding(){return this._activeEncoding}set activeEncoding(e){if(!this._encodings[e])throw Error(`unknown encoding "${e}"`);this._activeEncoding=e}reset(){this.activeProtocol=`NONE`,this.activeEncoding=`DEFAULT`,this._lastEvent=null,this._wheelPartialScroll=0}consumeWheelEvent(e,t,n){if(e.deltaY===0||e.shiftKey||t===void 0||n===void 0)return 0;let r=t/n,i=this._applyScrollModifier(e.deltaY,e);return e.deltaMode===WheelEvent.DOM_DELTA_PIXEL?(i/=r+0,Math.abs(e.deltaY)<50&&(i*=.3),this._wheelPartialScroll+=i,i=Math.floor(Math.abs(this._wheelPartialScroll))*(this._wheelPartialScroll>0?1:-1),this._wheelPartialScroll%=1):e.deltaMode===WheelEvent.DOM_DELTA_PAGE&&(i*=this._bufferService.rows),i}_applyScrollModifier(e,t){return t.altKey||t.ctrlKey||t.shiftKey?e*this._optionsService.rawOptions.fastScrollSensitivity*this._optionsService.rawOptions.scrollSensitivity:e*this._optionsService.rawOptions.scrollSensitivity}triggerMouseEvent(e){if(e.col<0||e.col>=this._bufferService.cols||e.row<0||e.row>=this._bufferService.rows||e.button===4&&e.action===32||e.button===3&&e.action!==32||e.button!==4&&(e.action===2||e.action===3)||(e.col++,e.row++,e.action===32&&this._lastEvent&&this._equalEvents(this._lastEvent,e,this._activeEncoding===`SGR_PIXELS`))||!this._protocols[this._activeProtocol].restrict(e))return!1;let t=this._encodings[this._activeEncoding](e);return t&&(this._activeEncoding===`DEFAULT`?this._coreService.triggerBinaryEvent(t):this._coreService.triggerDataEvent(t,!0)),this._lastEvent=e,!0}explainEvents(e){return{down:!!(1&e),up:!!(2&e),drag:!!(4&e),move:!!(8&e),wheel:!!(16&e)}}_equalEvents(e,t,n){if(n){if(e.x!==t.x||e.y!==t.y)return!1}else if(e.col!==t.col||e.row!==t.row)return!1;return e.button===t.button&&e.action===t.action&&e.ctrl===t.ctrl&&e.alt===t.alt&&e.shift===t.shift}};t.CoreMouseService=f,t.CoreMouseService=f=r([i(0,a.IBufferService),i(1,a.ICoreService),i(2,a.IOptionsService)],f)},4071:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.CoreService=void 0;let a=n(7453),o=n(7150),s=n(6501),c=n(802),l=Object.freeze({insertMode:!1}),u=Object.freeze({applicationCursorKeys:!1,applicationKeypad:!1,bracketedPasteMode:!1,cursorBlink:void 0,cursorStyle:void 0,origin:!1,reverseWraparound:!1,sendFocus:!1,synchronizedOutput:!1,wraparound:!0}),d=class extends o.Disposable{constructor(e,t,n){super(),this._bufferService=e,this._logService=t,this._optionsService=n,this.isCursorInitialized=!1,this.isCursorHidden=!1,this._onData=this._register(new c.Emitter),this.onData=this._onData.event,this._onUserInput=this._register(new c.Emitter),this.onUserInput=this._onUserInput.event,this._onBinary=this._register(new c.Emitter),this.onBinary=this._onBinary.event,this._onRequestScrollToBottom=this._register(new c.Emitter),this.onRequestScrollToBottom=this._onRequestScrollToBottom.event,this.modes=(0,a.clone)(l),this.decPrivateModes=(0,a.clone)(u)}reset(){this.modes=(0,a.clone)(l),this.decPrivateModes=(0,a.clone)(u)}triggerDataEvent(e,t=!1){if(this._optionsService.rawOptions.disableStdin)return;let n=this._bufferService.buffer;t&&this._optionsService.rawOptions.scrollOnUserInput&&n.ybase!==n.ydisp&&this._onRequestScrollToBottom.fire(),t&&this._onUserInput.fire(),this._logService.debug(`sending data "${e}"`),this._logService.trace(`sending data (codes)`,(()=>e.split(``).map((e=>e.charCodeAt(0))))),this._onData.fire(e)}triggerBinaryEvent(e){this._optionsService.rawOptions.disableStdin||(this._logService.debug(`sending binary "${e}"`),this._logService.trace(`sending binary (codes)`,(()=>e.split(``).map((e=>e.charCodeAt(0))))),this._onBinary.fire(e))}};t.CoreService=d,t.CoreService=d=r([i(0,s.IBufferService),i(1,s.ILogService),i(2,s.IOptionsService)],d)},4720:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DecorationService=void 0;let r=n(4103),i=n(7150),a=n(3087),o=n(802),s=0,c=0;class l extends i.Disposable{get decorations(){return this._decorations.values()}constructor(){super(),this._decorations=new a.SortedList((e=>e?.marker.line)),this._onDecorationRegistered=this._register(new o.Emitter),this.onDecorationRegistered=this._onDecorationRegistered.event,this._onDecorationRemoved=this._register(new o.Emitter),this.onDecorationRemoved=this._onDecorationRemoved.event,this._register((0,i.toDisposable)((()=>this.reset())))}registerDecoration(e){if(e.marker.isDisposed)return;let t=new u(e);if(t){let e=t.marker.onDispose((()=>t.dispose())),n=t.onDispose((()=>{n.dispose(),t&&(this._decorations.delete(t)&&this._onDecorationRemoved.fire(t),e.dispose())}));this._decorations.insert(t),this._onDecorationRegistered.fire(t)}return t}reset(){for(let e of this._decorations.values())e.dispose();this._decorations.clear()}*getDecorationsAtCell(e,t,n){let r=0,i=0;for(let a of this._decorations.getKeyIterator(t))r=a.options.x??0,i=r+(a.options.width??1),e>=r&&e{s=t.options.x??0,c=s+(t.options.width??1),e>=s&&e{Object.defineProperty(t,"__esModule",{value:!0}),t.InstantiationService=t.ServiceCollection=void 0;let r=n(6501),i=n(6201);class a{constructor(...e){this._entries=/* @__PURE__ */ new Map;for(let[t,n]of e)this.set(t,n)}set(e,t){let n=this._entries.get(e);return this._entries.set(e,t),n}forEach(e){for(let[t,n]of this._entries.entries())e(t,n)}has(e){return this._entries.has(e)}get(e){return this._entries.get(e)}}t.ServiceCollection=a,t.InstantiationService=class{constructor(){this._services=new a,this._services.set(r.IInstantiationService,this)}setService(e,t){this._services.set(e,t)}getService(e){return this._services.get(e)}createInstance(e,...t){let n=(0,i.getServiceDependencies)(e).sort(((e,t)=>e.index-t.index)),r=[];for(let t of n){let n=this._services.get(t.id);if(!n)throw Error(`[createInstance] ${e.name} depends on UNKNOWN service ${t.id._id}.`);r.push(n)}let a=n.length>0?n[0].index:t.length;if(t.length!==a)throw Error(`[createInstance] First service dependency of ${e.name} at position ${a+1} conflicts with ${t.length} static arguments`);return new e(...t,...r)}}},7276:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.LogService=void 0,t.setTraceLogger=function(e){c=e},t.traceCall=function(e,t,n){if(typeof n.value!=`function`)throw Error(`not supported`);let r=n.value;n.value=function(...e){if(c.logLevel!==o.LogLevelEnum.TRACE)return r.apply(this,e);c.trace(`GlyphRenderer#${r.name}(${e.map((e=>JSON.stringify(e))).join(`, `)})`);let t=r.apply(this,e);return c.trace(`GlyphRenderer#${r.name} return`,t),t}};let a=n(7150),o=n(6501),s={trace:o.LogLevelEnum.TRACE,debug:o.LogLevelEnum.DEBUG,info:o.LogLevelEnum.INFO,warn:o.LogLevelEnum.WARN,error:o.LogLevelEnum.ERROR,off:o.LogLevelEnum.OFF},c,l=class extends a.Disposable{get logLevel(){return this._logLevel}constructor(e){super(),this._optionsService=e,this._logLevel=o.LogLevelEnum.OFF,this._updateLogLevel(),this._register(this._optionsService.onSpecificOptionChange(`logLevel`,(()=>this._updateLogLevel()))),c=this}_updateLogLevel(){this._logLevel=s[this._optionsService.rawOptions.logLevel]}_evalLazyOptionalParams(e){for(let t=0;t{Object.defineProperty(t,"__esModule",{value:!0}),t.OptionsService=t.DEFAULT_OPTIONS=void 0;let r=n(7150),i=n(701),a=n(802);t.DEFAULT_OPTIONS={cols:80,rows:24,cursorBlink:!1,cursorStyle:`block`,cursorWidth:1,cursorInactiveStyle:`outline`,customGlyphs:!0,drawBoldTextInBrightColors:!0,documentOverride:null,fastScrollModifier:`alt`,fastScrollSensitivity:5,fontFamily:`monospace`,fontSize:15,fontWeight:`normal`,fontWeightBold:`bold`,ignoreBracketedPasteMode:!1,lineHeight:1,letterSpacing:0,linkHandler:null,logLevel:`info`,logger:null,scrollback:1e3,scrollOnEraseInDisplay:!1,scrollOnUserInput:!0,scrollSensitivity:1,screenReaderMode:!1,smoothScrollDuration:0,macOptionIsMeta:!1,macOptionClickForcesSelection:!1,minimumContrastRatio:1,disableStdin:!1,allowProposedApi:!1,allowTransparency:!1,tabStopWidth:8,theme:{},reflowCursorLine:!1,rescaleOverlappingGlyphs:!1,rightClickSelectsWord:i.isMac,windowOptions:{},windowsMode:!1,windowsPty:{},wordSeparator:` ()[]{}',"\``,altClickMovesCursor:!0,convertEol:!1,termName:`xterm`,cancelEvents:!1,overviewRuler:{}};let o=[`normal`,`bold`,`100`,`200`,`300`,`400`,`500`,`600`,`700`,`800`,`900`];class s extends r.Disposable{constructor(e){super(),this._onOptionChange=this._register(new a.Emitter),this.onOptionChange=this._onOptionChange.event;let n={...t.DEFAULT_OPTIONS};for(let t in e)if(t in n)try{let r=e[t];n[t]=this._sanitizeAndValidateOption(t,r)}catch(e){console.error(e)}this.rawOptions=n,this.options={...n},this._setupOptions(),this._register((0,r.toDisposable)((()=>{this.rawOptions.linkHandler=null,this.rawOptions.documentOverride=null})))}onSpecificOptionChange(e,t){return this.onOptionChange((n=>{n===e&&t(this.rawOptions[e])}))}onMultipleOptionChange(e,t){return this.onOptionChange((n=>{e.indexOf(n)!==-1&&t()}))}_setupOptions(){let e=e=>{if(!(e in t.DEFAULT_OPTIONS))throw Error(`No option with key "${e}"`);return this.rawOptions[e]},n=(e,n)=>{if(!(e in t.DEFAULT_OPTIONS))throw Error(`No option with key "${e}"`);n=this._sanitizeAndValidateOption(e,n),this.rawOptions[e]!==n&&(this.rawOptions[e]=n,this._onOptionChange.fire(e))};for(let t in this.rawOptions){let r={get:e.bind(this,t),set:n.bind(this,t)};Object.defineProperty(this.options,t,r)}}_sanitizeAndValidateOption(e,n){switch(e){case`cursorStyle`:if(n||=t.DEFAULT_OPTIONS[e],!function(e){return e===`block`||e===`underline`||e===`bar`}(n))throw Error(`"${n}" is not a valid value for ${e}`);break;case`wordSeparator`:n||=t.DEFAULT_OPTIONS[e];break;case`fontWeight`:case`fontWeightBold`:if(typeof n==`number`&&1<=n&&n<=1e3)break;n=o.includes(n)?n:t.DEFAULT_OPTIONS[e];break;case`cursorWidth`:n=Math.floor(n);case`lineHeight`:case`tabStopWidth`:if(n<1)throw Error(`${e} cannot be less than 1, value: ${n}`);break;case`minimumContrastRatio`:n=Math.max(1,Math.min(21,Math.round(10*n)/10));break;case`scrollback`:if((n=Math.min(n,4294967295))<0)throw Error(`${e} cannot be less than 0, value: ${n}`);break;case`fastScrollSensitivity`:case`scrollSensitivity`:if(n<=0)throw Error(`${e} cannot be less than or equal to 0, value: ${n}`);break;case`rows`:case`cols`:if(!n&&n!==0)throw Error(`${e} must be numeric, value: ${n}`);break;case`windowsPty`:n??={}}return n}}t.OptionsService=s},8811:function(e,t,n){var r=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},i=this&&this.__param||function(e,t){return function(n,r){t(n,r,e)}};Object.defineProperty(t,"__esModule",{value:!0}),t.OscLinkService=void 0;let a=n(6501),o=class{constructor(e){this._bufferService=e,this._nextId=1,this._entriesWithId=/* @__PURE__ */ new Map,this._dataByLinkId=/* @__PURE__ */ new Map}registerLink(e){let t=this._bufferService.buffer;if(e.id===void 0){let n=t.addMarker(t.ybase+t.y),r={data:e,id:this._nextId++,lines:[n]};return n.onDispose((()=>this._removeMarkerFromLink(r,n))),this._dataByLinkId.set(r.id,r),r.id}let n=e,r=this._getEntryIdKey(n),i=this._entriesWithId.get(r);if(i)return this.addLineToLink(i.id,t.ybase+t.y),i.id;let a=t.addMarker(t.ybase+t.y),o={id:this._nextId++,key:this._getEntryIdKey(n),data:n,lines:[a]};return a.onDispose((()=>this._removeMarkerFromLink(o,a))),this._entriesWithId.set(o.key,o),this._dataByLinkId.set(o.id,o),o.id}addLineToLink(e,t){let n=this._dataByLinkId.get(e);if(n&&n.lines.every((e=>e.line!==t))){let e=this._bufferService.buffer.addMarker(t);n.lines.push(e),e.onDispose((()=>this._removeMarkerFromLink(n,e)))}}getLinkData(e){return this._dataByLinkId.get(e)?.data}_getEntryIdKey(e){return`${e.id};;${e.uri}`}_removeMarkerFromLink(e,t){let n=e.lines.indexOf(t);n!==-1&&(e.lines.splice(n,1),e.lines.length===0&&(e.data.id!==void 0&&this._entriesWithId.delete(e.key),this._dataByLinkId.delete(e.id)))}};t.OscLinkService=o,t.OscLinkService=o=r([i(0,a.IBufferService)],o)},6201:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.serviceRegistry=void 0,t.getServiceDependencies=function(e){return e[r]||[]},t.createDecorator=function(e){if(t.serviceRegistry.has(e))return t.serviceRegistry.get(e);let i=function(e,t,a){if(arguments.length!==3)throw Error(`@IServiceName-decorator can only be used to decorate a parameter`);(function(e,t,i){t[n]===t?t[r].push({id:e,index:i}):(t[r]=[{id:e,index:i}],t[n]=t)})(i,e,a)};return i._id=e,t.serviceRegistry.set(e,i),i};let n=`di$target`,r=`di$dependencies`;t.serviceRegistry=/* @__PURE__ */ new Map},6501:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IDecorationService=t.IUnicodeService=t.IOscLinkService=t.IOptionsService=t.ILogService=t.LogLevelEnum=t.IInstantiationService=t.ICharsetService=t.ICoreService=t.ICoreMouseService=t.IBufferService=void 0;let r=n(6201);var i;t.IBufferService=(0,r.createDecorator)(`BufferService`),t.ICoreMouseService=(0,r.createDecorator)(`CoreMouseService`),t.ICoreService=(0,r.createDecorator)(`CoreService`),t.ICharsetService=(0,r.createDecorator)(`CharsetService`),t.IInstantiationService=(0,r.createDecorator)(`InstantiationService`),function(e){e[e.TRACE=0]=`TRACE`,e[e.DEBUG=1]=`DEBUG`,e[e.INFO=2]=`INFO`,e[e.WARN=3]=`WARN`,e[e.ERROR=4]=`ERROR`,e[e.OFF=5]=`OFF`}(i||(t.LogLevelEnum=i={})),t.ILogService=(0,r.createDecorator)(`LogService`),t.IOptionsService=(0,r.createDecorator)(`OptionsService`),t.IOscLinkService=(0,r.createDecorator)(`OscLinkService`),t.IUnicodeService=(0,r.createDecorator)(`UnicodeService`),t.IDecorationService=(0,r.createDecorator)(`DecorationService`)},6415:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.UnicodeService=void 0;let r=n(7428),i=n(802);class a{static extractShouldJoin(e){return!!(1&e)}static extractWidth(e){return e>>1&3}static extractCharKind(e){return e>>3}static createPropertyValue(e,t,n=!1){return(16777215&e)<<3|(3&t)<<1|!!n}constructor(){this._providers=Object.create(null),this._active=``,this._onChange=new i.Emitter,this.onChange=this._onChange.event;let e=new r.UnicodeV6;this.register(e),this._active=e.version,this._activeProvider=e}dispose(){this._onChange.dispose()}get versions(){return Object.keys(this._providers)}get activeVersion(){return this._active}set activeVersion(e){if(!this._providers[e])throw Error(`unknown Unicode version "${e}"`);this._active=e,this._activeProvider=this._providers[e],this._onChange.fire(e)}register(e){this._providers[e.version]=e}wcwidth(e){return this._activeProvider.wcwidth(e)}getStringCellWidth(e){let t=0,n=0,r=e.length;for(let i=0;i=r)return t+this.wcwidth(o);let n=e.charCodeAt(i);56320<=n&&n<=57343?o=1024*(o-55296)+n-56320+65536:t+=this.wcwidth(n)}let s=this.charProperties(o,n),c=a.extractWidth(s);a.extractShouldJoin(s)&&(c-=a.extractWidth(n)),t+=c,n=s}return t}charProperties(e,t){return this._activeProvider.charProperties(e,t)}}t.UnicodeService=a},4333:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.isAndroid=t.isElectron=t.isWebkitWebView=t.isSafari=t.isChrome=t.isWebKit=t.isFirefox=t.onDidChangeFullscreen=t.onDidChangeZoomLevel=void 0,t.addMatchMediaChangeListener=o,t.setZoomLevel=function(e,t){a.INSTANCE.setZoomLevel(e,t)},t.getZoomLevel=function(e){return a.INSTANCE.getZoomLevel(e)},t.getZoomFactor=function(e){return a.INSTANCE.getZoomFactor(e)},t.setZoomFactor=function(e,t){a.INSTANCE.setZoomFactor(e,t)},t.setFullscreen=function(e,t){a.INSTANCE.setFullscreen(e,t)},t.isFullscreen=function(e){return a.INSTANCE.isFullscreen(e)},t.isStandalone=function(){return c},t.isWCOEnabled=function(){return navigator?.windowControlsOverlay?.visible},t.getWCOBoundingRect=function(){return navigator?.windowControlsOverlay?.getTitlebarAreaRect()};let r=n(4693),i=n(802);class a{constructor(){this.mapWindowIdToZoomLevel=/* @__PURE__ */ new Map,this._onDidChangeZoomLevel=new i.Emitter,this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event,this.mapWindowIdToZoomFactor=/* @__PURE__ */ new Map,this._onDidChangeFullscreen=new i.Emitter,this.onDidChangeFullscreen=this._onDidChangeFullscreen.event,this.mapWindowIdToFullScreen=/* @__PURE__ */ new Map}static{this.INSTANCE=new a}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(n,e),this._onDidChangeZoomLevel.fire(n)}getZoomFactor(e){return this.mapWindowIdToZoomFactor.get(this.getWindowId(e))??1}setZoomFactor(e,t){this.mapWindowIdToZoomFactor.set(this.getWindowId(t),e)}setFullscreen(e,t){if(this.isFullscreen(t)===e)return;let n=this.getWindowId(t);this.mapWindowIdToFullScreen.set(n,e),this._onDidChangeFullscreen.fire(n)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}}function o(e,t,n){typeof t==`string`&&(t=e.matchMedia(t)),t.addEventListener(`change`,n)}t.onDidChangeZoomLevel=a.INSTANCE.onDidChangeZoomLevel,t.onDidChangeFullscreen=a.INSTANCE.onDidChangeFullscreen;let s=typeof navigator==`object`?navigator.userAgent:``;t.isFirefox=s.indexOf(`Firefox`)>=0,t.isWebKit=s.indexOf(`AppleWebKit`)>=0,t.isChrome=s.indexOf(`Chrome`)>=0,t.isSafari=!t.isChrome&&s.indexOf(`Safari`)>=0,t.isWebkitWebView=!t.isChrome&&!t.isSafari&&t.isWebKit,t.isElectron=s.indexOf(`Electron/`)>=0,t.isAndroid=s.indexOf(`Android`)>=0;let c=!1;if(typeof r.mainWindow.matchMedia==`function`){let e=r.mainWindow.matchMedia(`(display-mode: standalone) or (display-mode: window-controls-overlay)`),t=r.mainWindow.matchMedia(`(display-mode: fullscreen)`);c=e.matches,o(r.mainWindow,e,(({matches:e})=>{c&&t.matches||(c=e)}))}},7745:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.BrowserFeatures=t.KeyboardSupport=void 0;let o=a(n(4333)),s=n(4693),c=a(n(8163));var l;(function(e){e[e.Always=0]=`Always`,e[e.FullScreen=1]=`FullScreen`,e[e.None=2]=`None`})(l||(t.KeyboardSupport=l={}));let u=typeof navigator==`object`?navigator:{};t.BrowserFeatures={clipboard:{writeText:c.isNative||document.queryCommandSupported&&document.queryCommandSupported(`copy`)||!!(u&&u.clipboard&&u.clipboard.writeText),readText:c.isNative||!!(u&&u.clipboard&&u.clipboard.readText)},keyboard:c.isNative||o.isStandalone()?l.Always:u.keyboard||o.isSafari?l.FullScreen:l.None,touch:`ontouchstart`in s.mainWindow||u.maxTouchPoints>0,pointerEvents:s.mainWindow.PointerEvent&&(`ontouchstart`in s.mainWindow||navigator.maxTouchPoints>0)}},7093:function(e,t,n){var r,i=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),a=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&i(t,e,n);return a(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.SafeTriangle=t.DragAndDropObserver=t.ModifierKeyEmitter=t.DetectedFullscreenMode=t.Namespace=t.EventHelper=t.EventType=t.sharedMutationObserver=t.Dimension=t.WindowIntervalTimer=t.scheduleAtNextAnimationFrame=t.runAtThisOrScheduleAtNextAnimationFrame=t.WindowIdleValue=t.addStandardDisposableGenericMouseUpListener=t.addStandardDisposableGenericMouseDownListener=t.addStandardDisposableListener=t.onDidUnregisterWindow=t.onWillUnregisterWindow=t.onDidRegisterWindow=t.hasWindow=t.getWindowById=t.getWindowId=t.getWindowsCount=t.getWindows=t.getDocument=t.getWindow=t.registerWindow=void 0,t.clearNode=function(e){for(;e.firstChild;)e.firstChild.remove()},t.clearNodeRecursively=function e(t){for(;t.firstChild;){let n=t.firstChild;n.remove(),e(n)}},t.addDisposableListener=x,t.addDisposableGenericMouseDownListener=C,t.addDisposableGenericMouseMoveListener=function(e,n,r){return x(e,g.isIOS&&c.BrowserFeatures.pointerEvents?t.EventType.POINTER_MOVE:t.EventType.MOUSE_MOVE,n,r)},t.addDisposableGenericMouseUpListener=w,t.runWhenWindowIdle=function(e,t,n){return(0,d._runWhenIdle)(e,t,n)},t.disposableWindowInterval=function(e,t,n,r){let i=0,a=e.setInterval((()=>{i++,(typeof r==`number`&&i>=r||!0===t())&&o.dispose()}),n),o=(0,h.toDisposable)((()=>{e.clearInterval(a)}));return o},t.measure=function(e,n){return(0,t.scheduleAtNextAnimationFrame)(e,n,1e4)},t.modify=function(e,n){return(0,t.scheduleAtNextAnimationFrame)(e,n,-1e4)},t.addDisposableThrottledListener=function(e,t,n,r,i){return new k(e,t,n,r,i)},t.getComputedStyle=A,t.getClientArea=function e(n,r){let i=(0,t.getWindow)(n),a=i.document;if(n!==a.body)return new M(n.clientWidth,n.clientHeight);if(g.isIOS&&i?.visualViewport)return new M(i.visualViewport.width,i.visualViewport.height);if(i?.innerWidth&&i.innerHeight)return new M(i.innerWidth,i.innerHeight);if(a.body&&a.body.clientWidth&&a.body.clientHeight)return new M(a.body.clientWidth,a.body.clientHeight);if(a.documentElement&&a.documentElement.clientWidth&&a.documentElement.clientHeight)return new M(a.documentElement.clientWidth,a.documentElement.clientHeight);if(r)return e(r);throw Error(`Unable to figure out browser width and height`)},t.getTopLeftOffset=N,t.size=function(e,t,n){typeof t==`number`&&(e.style.width=`${t}px`),typeof n==`number`&&(e.style.height=`${n}px`)},t.position=function(e,t,n,r,i,a=`absolute`){typeof t==`number`&&(e.style.top=`${t}px`),typeof n==`number`&&(e.style.right=`${n}px`),typeof r==`number`&&(e.style.bottom=`${r}px`),typeof i==`number`&&(e.style.left=`${i}px`),e.style.position=a},t.getDomNodePagePosition=function(e){let n=e.getBoundingClientRect(),r=(0,t.getWindow)(e);return{left:n.left+r.scrollX,top:n.top+r.scrollY,width:n.width,height:n.height}},t.getDomNodeZoomLevel=function(e){let t=e,n=1;do{let e=A(t).zoom;e!=null&&e!==`1`&&(n*=e),t=t.parentElement}while(t!==null&&t!==t.ownerDocument.documentElement);return n},t.getTotalWidth=P,t.getContentWidth=function(e){let t=j.getBorderLeftWidth(e)+j.getBorderRightWidth(e),n=j.getPaddingLeft(e)+j.getPaddingRight(e);return e.offsetWidth-t-n},t.getTotalScrollWidth=F,t.getContentHeight=function(e){let t=j.getBorderTopWidth(e)+j.getBorderBottomWidth(e),n=j.getPaddingTop(e)+j.getPaddingBottom(e);return e.offsetHeight-t-n},t.getTotalHeight=function(e){let t=j.getMarginTop(e)+j.getMarginBottom(e);return e.offsetHeight+t},t.getLargestChildWidth=function(e,t){let n=t.map((t=>Math.max(F(t),P(t))+function(e,t){if(e===null)return 0;let n=N(e),r=N(t);return n.left-r.left}(t,e)||0));return Math.max(...n)},t.isAncestor=I,t.setParentFlowTo=function(e,t){e.dataset[L]=t.id},t.isAncestorUsingFlowTo=function(e,t){let n=e;for(;n;){if(n===t)return!0;if($(n)){let e=R(n);if(e){n=e;continue}}n=n.parentNode}return!1},t.findParentWithClass=z,t.hasParentWithClass=function(e,t,n){return!!z(e,t,n)},t.isShadowRoot=B,t.isInShadowDOM=function(e){return!!V(e)},t.getShadowRoot=V,t.getActiveElement=H,t.isActiveElement=function(e){return H()===e},t.isAncestorOfActiveElement=function(e){return I(H(),e)},t.isActiveDocument=function(e){return e.ownerDocument===U()},t.getActiveDocument=U,t.getActiveWindow=function(){return U().defaultView?.window??v.mainWindow},t.isGlobalStylesheet=function(e){return W.has(e)},t.createStyleSheet2=function(){return new G},t.createStyleSheet=K,t.cloneGlobalStylesheets=function(e){let t=new h.DisposableStore;for(let[n,r]of W)t.add(q(n,r,e));return t},t.createMetaElement=function(e=v.mainWindow.document.head){return J(`meta`,e)},t.createLinkElement=function(e=v.mainWindow.document.head){return J(`link`,e)},t.createCSSRule=function e(t,n,r=X()){if(r&&n){r.sheet?.insertRule(`${t} {${n}}`,0);for(let i of W.get(r)??[])e(t,n,i)}},t.removeCSSRulesContainingSelector=function e(t,n=X()){if(!n)return;let r=Z(n),i=[];for(let e=0;e=0;e--)n.sheet?.deleteRule(i[e]);for(let r of W.get(n)??[])e(t,r)},t.isHTMLElement=$,t.isHTMLAnchorElement=function(e){return e instanceof HTMLAnchorElement||e instanceof(0,t.getWindow)(e).HTMLAnchorElement},t.isHTMLSpanElement=function(e){return e instanceof HTMLSpanElement||e instanceof(0,t.getWindow)(e).HTMLSpanElement},t.isHTMLTextAreaElement=function(e){return e instanceof HTMLTextAreaElement||e instanceof(0,t.getWindow)(e).HTMLTextAreaElement},t.isHTMLInputElement=function(e){return e instanceof HTMLInputElement||e instanceof(0,t.getWindow)(e).HTMLInputElement},t.isHTMLButtonElement=function(e){return e instanceof HTMLButtonElement||e instanceof(0,t.getWindow)(e).HTMLButtonElement},t.isHTMLDivElement=function(e){return e instanceof HTMLDivElement||e instanceof(0,t.getWindow)(e).HTMLDivElement},t.isSVGElement=function(e){return e instanceof SVGElement||e instanceof(0,t.getWindow)(e).SVGElement},t.isMouseEvent=function(e){return e instanceof MouseEvent||e instanceof(0,t.getWindow)(e).MouseEvent},t.isKeyboardEvent=function(e){return e instanceof KeyboardEvent||e instanceof(0,t.getWindow)(e).KeyboardEvent},t.isPointerEvent=function(e){return e instanceof PointerEvent||e instanceof(0,t.getWindow)(e).PointerEvent},t.isDragEvent=function(e){return e instanceof DragEvent||e instanceof(0,t.getWindow)(e).DragEvent},t.isEventLike=function(e){let t=e;return!(!t||typeof t.preventDefault!=`function`||typeof t.stopPropagation!=`function`)},t.saveParentsScrollTop=function(e){let t=[];for(let n=0;e&&e.nodeType===e.ELEMENT_NODE;n++)t[n]=e.scrollTop,e=e.parentNode;return t},t.restoreParentsScrollTop=function(e,t){for(let n=0;e&&e.nodeType===e.ELEMENT_NODE;n++)e.scrollTop!==t[n]&&(e.scrollTop=t[n]),e=e.parentNode},t.trackFocus=function(e){return new ee(e)},t.after=function(e,t){return e.after(t),t},t.append=te,t.prepend=function(e,t){return e.insertBefore(t,e.firstChild),t},t.reset=function(e,...t){e.innerText=``,te(e,...t)},t.$=ae,t.join=function(e,t){let n=[];return e.forEach(((e,r)=>{r>0&&(t instanceof Node?n.push(t.cloneNode()):n.push(document.createTextNode(t))),n.push(e)})),n},t.setVisibility=function(e,...t){e?oe(...t):se(...t)},t.show=oe,t.hide=se,t.removeTabIndexAndUpdateFocus=function(e){e&&e.hasAttribute(`tabIndex`)&&(e.ownerDocument.activeElement===e&&(function(e){for(;e&&e.nodeType===e.ELEMENT_NODE;){if($(e)&&e.hasAttribute(`tabIndex`))return e;e=e.parentNode}return null})(e.parentElement)?.focus(),e.removeAttribute(`tabindex`))},t.finalHandler=function(e){return t=>{t.preventDefault(),t.stopPropagation(),e(t)}},t.domContentLoaded=function(e){return new Promise((t=>{if(e.document.readyState===`complete`||e.document&&e.document.body!==null)t(void 0);else{let n=()=>{e.window.removeEventListener(`DOMContentLoaded`,n,!1),t()};e.window.addEventListener(`DOMContentLoaded`,n,!1)}}))},t.computeScreenAwareSize=function(e,t){let n=e.devicePixelRatio*t;return Math.max(1,Math.floor(n))/e.devicePixelRatio},t.windowOpenNoOpener=function(e){v.mainWindow.open(e,`_blank`,`noopener`)},t.windowOpenPopup=function(e){let t=Math.floor(v.mainWindow.screenLeft+v.mainWindow.innerWidth/2-ce/2),n=Math.floor(v.mainWindow.screenTop+v.mainWindow.innerHeight/2-le/2);v.mainWindow.open(e,`_blank`,`width=${ce},height=${le},top=${n},left=${t}`)},t.windowOpenWithSuccess=function(e,t=!0){let n=v.mainWindow.open();return!!n&&(t&&(n.opener=null),n.location.href=e,!0)},t.animate=function(e,n){let r=()=>{n(),i=(0,t.scheduleAtNextAnimationFrame)(e,r)},i=(0,t.scheduleAtNextAnimationFrame)(e,r);return(0,h.toDisposable)((()=>i.dispose()))},t.asCSSPropertyValue=function(e){return`'${e.replace(/'/g,`%27`)}'`},t.asCssValueWithDefault=function e(t,n){if(t!==void 0){let r=t.match(/^\s*var\((.+)\)$/);if(r){let t=r[1].split(`,`,2);return t.length===2&&(n=e(t[1].trim(),n)),`var(${t[0]}, ${n})`}return t}return n},t.detectFullscreen=function(e){return e.document.fullscreenElement||e.document.webkitFullscreenElement||e.document.webkitIsFullScreen?{mode:ue.DOCUMENT,guess:!1}:e.innerHeight===e.screen.height?{mode:ue.BROWSER,guess:!1}:(g.isMacintosh||g.isLinux)&&e.outerHeight===e.screen.height&&e.outerWidth===e.screen.width?{mode:ue.BROWSER,guess:!0}:null},t.multibyteAwareBtoa=function(e){return btoa(function(e){let t=new Uint16Array(e.length);for(let n=0;n0&&(o.className=s.join(` `));let c={};if(i.groups.name&&(c[i.groups.name]=o),r)for(let e of r)$(e)?o.appendChild(e):typeof e==`string`?o.append(e):`root`in e&&(Object.assign(c,e),o.appendChild(e.root));for(let[e,t]of Object.entries(n))if(e!==`className`){if(e===`style`)for(let[e,n]of Object.entries(t))o.style.setProperty(me(e),typeof n==`number`?n+`px`:``+n);else e===`tabIndex`?o.tabIndex=t:o.setAttribute(me(e),t.toString())}return c.root=o,c},t.svgElem=function(e,...t){let n,r;Array.isArray(t[0])?(n={},r=t[0]):(n=t[0]||{},r=t[1]);let i=pe.exec(e);if(!i||!i.groups)throw Error(`Bad use of h`);let a=i.groups.tag||`div`,o=document.createElementNS(`http://www.w3.org/2000/svg`,a);i.groups.id&&(o.id=i.groups.id);let s=[];if(i.groups.class)for(let e of i.groups.class.split(`.`))e!==``&&s.push(e);if(n.className!==void 0)for(let e of n.className.split(`.`))e!==``&&s.push(e);s.length>0&&(o.className=s.join(` `));let c={};if(i.groups.name&&(c[i.groups.name]=o),r)for(let e of r)$(e)?o.appendChild(e):typeof e==`string`?o.append(e):`root`in e&&(Object.assign(c,e),o.appendChild(e.root));for(let[e,t]of Object.entries(n))if(e!==`className`){if(e===`style`)for(let[e,n]of Object.entries(t))o.style.setProperty(me(e),typeof n==`number`?n+`px`:``+n);else e===`tabIndex`?o.tabIndex=t:o.setAttribute(me(e),t.toString())}return c.root=o,c},t.copyAttributes=he,t.trackAttributes=function(e,n,r){he(e,n,r);let i=new h.DisposableStore;return i.add(t.sharedMutationObserver.observe(e,i,{attributes:!0,attributeFilter:r})((t=>{for(let r of t)r.type===`attributes`&&r.attributeName&&ge(e,n,r.attributeName)}))),i};let s=o(n(4333)),c=n(7745),l=n(5394),u=n(5964),d=n(1758),f=n(9807),p=o(n(802)),m=n(7883),h=n(7150),g=o(n(8163)),_=n(6304),v=n(4693),y=n(7704);r=function(){let e=/* @__PURE__ */ new Map;(0,v.ensureCodeWindow)(v.mainWindow,1);let n={window:v.mainWindow,disposables:new h.DisposableStore};e.set(v.mainWindow.vscodeWindowId,n);let r=new p.Emitter,i=new p.Emitter,a=new p.Emitter;return{onDidRegisterWindow:r.event,onWillUnregisterWindow:a.event,onDidUnregisterWindow:i.event,registerWindow(n){if(e.has(n.vscodeWindowId))return h.Disposable.None;let o=new h.DisposableStore,s={window:n,disposables:o.add(new h.DisposableStore)};return e.set(n.vscodeWindowId,s),o.add((0,h.toDisposable)((()=>{e.delete(n.vscodeWindowId),i.fire(n)}))),o.add(x(n,t.EventType.BEFORE_UNLOAD,(()=>{a.fire(n)}))),r.fire(s),o},getWindows:()=>e.values(),getWindowsCount:()=>e.size,getWindowId:e=>e.vscodeWindowId,hasWindow:t=>e.has(t),getWindowById:function(t,r){return(typeof t==`number`?e.get(t):void 0)??(r?n:void 0)},getWindow(e){let t=e;if(t?.ownerDocument?.defaultView)return t.ownerDocument.defaultView.window;let n=e;return n?.view?n.view.window:v.mainWindow},getDocument(e){let n=e;return(0,t.getWindow)(n).document}}}(),t.registerWindow=r.registerWindow,t.getWindow=r.getWindow,t.getDocument=r.getDocument,t.getWindows=r.getWindows,t.getWindowsCount=r.getWindowsCount,t.getWindowId=r.getWindowId,t.getWindowById=r.getWindowById,t.hasWindow=r.hasWindow,t.onDidRegisterWindow=r.onDidRegisterWindow,t.onWillUnregisterWindow=r.onWillUnregisterWindow,t.onDidUnregisterWindow=r.onDidUnregisterWindow;class b{constructor(e,t,n,r){this._node=e,this._type=t,this._handler=n,this._options=r||!1,this._node.addEventListener(this._type,this._handler,this._options)}dispose(){this._handler&&=(this._node.removeEventListener(this._type,this._handler,this._options),this._node=null,null)}}function x(e,t,n,r){return new b(e,t,n,r)}function S(e,t){return function(n){return t(new u.StandardMouseEvent(e,n))}}function C(e,n,r){return x(e,g.isIOS&&c.BrowserFeatures.pointerEvents?t.EventType.POINTER_DOWN:t.EventType.MOUSE_DOWN,n,r)}function w(e,n,r){return x(e,g.isIOS&&c.BrowserFeatures.pointerEvents?t.EventType.POINTER_UP:t.EventType.MOUSE_UP,n,r)}t.addStandardDisposableListener=function(e,n,r,i){let a=r;return n===`click`||n===`mousedown`||n===`contextmenu`?a=S((0,t.getWindow)(e),r):n!==`keydown`&&n!==`keypress`&&n!==`keyup`||(a=function(e){return function(t){return e(new l.StandardKeyboardEvent(t))}}(r)),x(e,n,a,i)},t.addStandardDisposableGenericMouseDownListener=function(e,n,r){return C(e,S((0,t.getWindow)(e),n),r)},t.addStandardDisposableGenericMouseUpListener=function(e,n,r){return w(e,S((0,t.getWindow)(e),n),r)};class T extends d.AbstractIdleValue{constructor(e,t){super(e,t)}}t.WindowIdleValue=T;class E extends d.IntervalTimer{constructor(e){super(),this.defaultTarget=e&&(0,t.getWindow)(e)}cancelAndSet(e,t,n){return super.cancelAndSet(e,t,n??this.defaultTarget)}}t.WindowIntervalTimer=E;class D{constructor(e,t=0){this._runner=e,this.priority=t,this._canceled=!1}dispose(){this._canceled=!0}execute(){if(!this._canceled)try{this._runner()}catch(e){(0,f.onUnexpectedError)(e)}}static sort(e,t){return t.priority-e.priority}}(function(){let e=/* @__PURE__ */ new Map,n=/* @__PURE__ */ new Map,r=/* @__PURE__ */ new Map,i=/* @__PURE__ */ new Map;t.scheduleAtNextAnimationFrame=(a,o,s=0)=>{let c=(0,t.getWindowId)(a),l=new D(o,s),u=e.get(c);return u||(u=[],e.set(c,u)),u.push(l),r.get(c)||(r.set(c,!0),a.requestAnimationFrame((()=>(t=>{r.set(t,!1);let a=e.get(t)??[];for(n.set(t,a),e.set(t,[]),i.set(t,!0);a.length>0;)a.sort(D.sort),a.shift().execute();i.set(t,!1)})(c)))),l},t.runAtThisOrScheduleAtNextAnimationFrame=(e,r,a)=>{let o=(0,t.getWindowId)(e);if(i.get(o)){let e=new D(r,a),t=n.get(o);return t||(t=[],n.set(o,t)),t.push(e),e}return(0,t.scheduleAtNextAnimationFrame)(e,r,a)}})();let O=function(e,t){return t};class k extends h.Disposable{constructor(e,t,n,r=O,i=8){super();let a=null,o=0,s=this._register(new d.TimeoutTimer),c=()=>{o=(/* @__PURE__ */ new Date()).getTime(),n(a),a=null};this._register(x(e,t,(e=>{a=r(a,e);let t=(/* @__PURE__ */ new Date()).getTime()-o;t>=i?(s.cancel(),c()):s.setIfNotSet(c,i-t)})))}}function A(e){return(0,t.getWindow)(e).getComputedStyle(e,null)}class j{static convertToPixels(e,t){return parseFloat(t)||0}static getDimension(e,t,n){let r=A(e),i=r?r.getPropertyValue(t):`0`;return j.convertToPixels(e,i)}static getBorderLeftWidth(e){return j.getDimension(e,`border-left-width`,`borderLeftWidth`)}static getBorderRightWidth(e){return j.getDimension(e,`border-right-width`,`borderRightWidth`)}static getBorderTopWidth(e){return j.getDimension(e,`border-top-width`,`borderTopWidth`)}static getBorderBottomWidth(e){return j.getDimension(e,`border-bottom-width`,`borderBottomWidth`)}static getPaddingLeft(e){return j.getDimension(e,`padding-left`,`paddingLeft`)}static getPaddingRight(e){return j.getDimension(e,`padding-right`,`paddingRight`)}static getPaddingTop(e){return j.getDimension(e,`padding-top`,`paddingTop`)}static getPaddingBottom(e){return j.getDimension(e,`padding-bottom`,`paddingBottom`)}static getMarginLeft(e){return j.getDimension(e,`margin-left`,`marginLeft`)}static getMarginTop(e){return j.getDimension(e,`margin-top`,`marginTop`)}static getMarginRight(e){return j.getDimension(e,`margin-right`,`marginRight`)}static getMarginBottom(e){return j.getDimension(e,`margin-bottom`,`marginBottom`)}}class M{static{this.None=new M(0,0)}constructor(e,t){this.width=e,this.height=t}with(e=this.width,t=this.height){return e!==this.width||t!==this.height?new M(e,t):this}static is(e){return typeof e==`object`&&typeof e.height==`number`&&typeof e.width==`number`}static lift(e){return e instanceof M?e:new M(e.width,e.height)}static equals(e,t){return e===t||!(!e||!t)&&e.width===t.width&&e.height===t.height}}function N(e){let t=e.offsetParent,n=e.offsetTop,r=e.offsetLeft;for(;(e=e.parentNode)!==null&&e!==e.ownerDocument.body&&e!==e.ownerDocument.documentElement;){n-=e.scrollTop;let i=B(e)?null:A(e);i&&(r-=i.direction===`rtl`?-e.scrollLeft:e.scrollLeft),e===t&&(r+=j.getBorderLeftWidth(e),n+=j.getBorderTopWidth(e),n+=e.offsetTop,r+=e.offsetLeft,t=e.offsetParent)}return{left:r,top:n}}function P(e){let t=j.getMarginLeft(e)+j.getMarginRight(e);return e.offsetWidth+t}function F(e){let t=j.getMarginLeft(e)+j.getMarginRight(e);return e.scrollWidth+t}function I(e,t){return!!t?.contains(e)}t.Dimension=M;let L=`parentFlowToElementId`;function R(e){let t=e.dataset[L];return typeof t==`string`?e.ownerDocument.getElementById(t):null}function z(e,t,n){for(;e&&e.nodeType===e.ELEMENT_NODE;){if(e.classList.contains(t))return e;if(n){if(typeof n==`string`){if(e.classList.contains(n))return null}else if(e===n)return null}e=e.parentNode}return null}function B(e){return e&&!!e.host&&!!e.mode}function V(e){for(;e.parentNode;){if(e===e.ownerDocument?.body)return null;e=e.parentNode}return B(e)?e:null}function H(){let e=U().activeElement;for(;e?.shadowRoot;)e=e.shadowRoot.activeElement;return e}function U(){return(0,t.getWindowsCount)()<=1?v.mainWindow.document:Array.from((0,t.getWindows)()).map((({window:e})=>e.document)).find((e=>e.hasFocus()))??v.mainWindow.document}let W=/* @__PURE__ */ new Map;class G{constructor(){this._currentCssStyle=``,this._styleSheet=void 0}setStyle(e){e!==this._currentCssStyle&&(this._currentCssStyle=e,this._styleSheet?this._styleSheet.innerText=e:this._styleSheet=K(v.mainWindow.document.head,(t=>t.innerText=e)))}dispose(){this._styleSheet&&=(this._styleSheet.remove(),void 0)}}function K(e=v.mainWindow.document.head,n,r){let i=document.createElement(`style`);if(i.type=`text/css`,i.media=`screen`,n?.(i),e.appendChild(i),r&&r.add((0,h.toDisposable)((()=>i.remove()))),e===v.mainWindow.document.head){let e=/* @__PURE__ */ new Set;W.set(i,e);for(let{window:n,disposables:a}of(0,t.getWindows)()){if(n===v.mainWindow)continue;let t=a.add(q(i,e,n));r?.add(t)}}return i}function q(e,n,r){let i=new h.DisposableStore,a=e.cloneNode(!0);r.document.head.appendChild(a),i.add((0,h.toDisposable)((()=>a.remove())));for(let t of Z(e))a.sheet?.insertRule(t.cssText,a.sheet?.cssRules.length);return i.add(t.sharedMutationObserver.observe(e,i,{childList:!0})((()=>{a.textContent=e.textContent}))),n.add(a),i.add((0,h.toDisposable)((()=>n.delete(a)))),i}function J(e,t=v.mainWindow.document.head){let n=document.createElement(e);return t.appendChild(n),n}t.sharedMutationObserver=new class{constructor(){this.mutationObservers=/* @__PURE__ */ new Map}observe(e,t,n){let r=this.mutationObservers.get(e);r||(r=/* @__PURE__ */ new Map,this.mutationObservers.set(e,r));let i=(0,_.hash)(n),a=r.get(i);if(a)a.users+=1;else{let o=new p.Emitter,s=new MutationObserver((e=>o.fire(e)));s.observe(e,n);let c=a={users:1,observer:s,onDidMutate:o.event};t.add((0,h.toDisposable)((()=>{--c.users,c.users===0&&(o.dispose(),s.disconnect(),r?.delete(i),r?.size===0&&this.mutationObservers.delete(e))}))),r.set(i,a)}return a.onDidMutate}};let Y=null;function X(){return Y||=K(),Y}function Z(e){return e?.sheet?.rules?e.sheet.rules:e?.sheet?.cssRules?e.sheet.cssRules:[]}function Q(e){return typeof e.selectorText==`string`}function $(e){return e instanceof HTMLElement||e instanceof(0,t.getWindow)(e).HTMLElement}t.EventType={CLICK:`click`,AUXCLICK:`auxclick`,DBLCLICK:`dblclick`,MOUSE_UP:`mouseup`,MOUSE_DOWN:`mousedown`,MOUSE_OVER:`mouseover`,MOUSE_MOVE:`mousemove`,MOUSE_OUT:`mouseout`,MOUSE_ENTER:`mouseenter`,MOUSE_LEAVE:`mouseleave`,MOUSE_WHEEL:`wheel`,POINTER_UP:`pointerup`,POINTER_DOWN:`pointerdown`,POINTER_MOVE:`pointermove`,POINTER_LEAVE:`pointerleave`,CONTEXT_MENU:`contextmenu`,WHEEL:`wheel`,KEY_DOWN:`keydown`,KEY_PRESS:`keypress`,KEY_UP:`keyup`,LOAD:`load`,BEFORE_UNLOAD:`beforeunload`,UNLOAD:`unload`,PAGE_SHOW:`pageshow`,PAGE_HIDE:`pagehide`,PASTE:`paste`,ABORT:`abort`,ERROR:`error`,RESIZE:`resize`,SCROLL:`scroll`,FULLSCREEN_CHANGE:`fullscreenchange`,WK_FULLSCREEN_CHANGE:`webkitfullscreenchange`,SELECT:`select`,CHANGE:`change`,SUBMIT:`submit`,RESET:`reset`,FOCUS:`focus`,FOCUS_IN:`focusin`,FOCUS_OUT:`focusout`,BLUR:`blur`,INPUT:`input`,STORAGE:`storage`,DRAG_START:`dragstart`,DRAG:`drag`,DRAG_ENTER:`dragenter`,DRAG_LEAVE:`dragleave`,DRAG_OVER:`dragover`,DROP:`drop`,DRAG_END:`dragend`,ANIMATION_START:s.isWebKit?`webkitAnimationStart`:`animationstart`,ANIMATION_END:s.isWebKit?`webkitAnimationEnd`:`animationend`,ANIMATION_ITERATION:s.isWebKit?`webkitAnimationIteration`:`animationiteration`},t.EventHelper={stop:(e,t)=>(e.preventDefault(),t&&e.stopPropagation(),e)};class ee extends h.Disposable{static hasFocusWithin(e){if($(e)){let t=V(e);return I(t?t.activeElement:e.ownerDocument.activeElement,e)}{let t=e;return I(t.document.activeElement,t.document)}}constructor(e){super(),this._onDidFocus=this._register(new p.Emitter),this.onDidFocus=this._onDidFocus.event,this._onDidBlur=this._register(new p.Emitter),this.onDidBlur=this._onDidBlur.event;let n=ee.hasFocusWithin(e),r=!1,i=()=>{r=!1,n||(n=!0,this._onDidFocus.fire())},a=()=>{n&&(r=!0,($(e)?(0,t.getWindow)(e):e).setTimeout((()=>{r&&(r=!1,n=!1,this._onDidBlur.fire())}),0))};this._refreshStateHandler=()=>{ee.hasFocusWithin(e)!==n&&(n?a():i())},this._register(x(e,t.EventType.FOCUS,i,!0)),this._register(x(e,t.EventType.BLUR,a,!0)),$(e)&&(this._register(x(e,t.EventType.FOCUS_IN,(()=>this._refreshStateHandler()))),this._register(x(e,t.EventType.FOCUS_OUT,(()=>this._refreshStateHandler()))))}refreshState(){this._refreshStateHandler()}}function te(e,...t){if(e.append(...t),t.length===1&&typeof t[0]!=`string`)return t[0]}let ne=/([\w\-]+)?(#([\w\-]+))?((\.([\w\-]+))*)/;var re;function ie(e,t,n,...r){let i=ne.exec(t);if(!i)throw Error(`Bad use of emmet`);let a=i[1]||`div`,o;return o=e===re.HTML?document.createElement(a):document.createElementNS(e,a),i[3]&&(o.id=i[3]),i[4]&&(o.className=i[4].replace(/\./g,` `).trim()),n&&Object.entries(n).forEach((([e,t])=>{t!==void 0&&(/^on\w+$/.test(e)?o[e]=t:e===`selected`?t&&o.setAttribute(e,`true`):o.setAttribute(e,t))})),o.append(...r),o}function ae(e,t,...n){return ie(re.HTML,e,t,...n)}function oe(...e){for(let t of e)t.style.display=``,t.removeAttribute(`aria-hidden`)}function se(...e){for(let t of e)t.style.display=`none`,t.setAttribute(`aria-hidden`,`true`)}(function(e){e.HTML=`http://www.w3.org/1999/xhtml`,e.SVG=`http://www.w3.org/2000/svg`})(re||(t.Namespace=re={})),ae.SVG=function(e,t,...n){return ie(re.SVG,e,t,...n)};let ce=780,le=640;var ue;(function(e){e[e.DOCUMENT=1]=`DOCUMENT`,e[e.BROWSER=2]=`BROWSER`})(ue||(t.DetectedFullscreenMode=ue={}));class de extends p.Emitter{constructor(){super(),this._subscriptions=new h.DisposableStore,this._keyStatus={altKey:!1,shiftKey:!1,ctrlKey:!1,metaKey:!1},this._subscriptions.add(p.Event.runAndSubscribe(t.onDidRegisterWindow,(({window:e,disposables:t})=>this.registerListeners(e,t)),{window:v.mainWindow,disposables:this._subscriptions}))}registerListeners(e,t){t.add(x(e,`keydown`,(e=>{if(e.defaultPrevented)return;let t=new l.StandardKeyboardEvent(e);if(t.keyCode!==m.KeyCode.Alt||!e.repeat){if(e.altKey&&!this._keyStatus.altKey)this._keyStatus.lastKeyPressed=`alt`;else if(e.ctrlKey&&!this._keyStatus.ctrlKey)this._keyStatus.lastKeyPressed=`ctrl`;else if(e.metaKey&&!this._keyStatus.metaKey)this._keyStatus.lastKeyPressed=`meta`;else if(e.shiftKey&&!this._keyStatus.shiftKey)this._keyStatus.lastKeyPressed=`shift`;else{if(t.keyCode===m.KeyCode.Alt)return;this._keyStatus.lastKeyPressed=void 0}this._keyStatus.altKey=e.altKey,this._keyStatus.ctrlKey=e.ctrlKey,this._keyStatus.metaKey=e.metaKey,this._keyStatus.shiftKey=e.shiftKey,this._keyStatus.lastKeyPressed&&(this._keyStatus.event=e,this.fire(this._keyStatus))}}),!0)),t.add(x(e,`keyup`,(e=>{e.defaultPrevented||(!e.altKey&&this._keyStatus.altKey?this._keyStatus.lastKeyReleased=`alt`:!e.ctrlKey&&this._keyStatus.ctrlKey?this._keyStatus.lastKeyReleased=`ctrl`:!e.metaKey&&this._keyStatus.metaKey?this._keyStatus.lastKeyReleased=`meta`:!e.shiftKey&&this._keyStatus.shiftKey?this._keyStatus.lastKeyReleased=`shift`:this._keyStatus.lastKeyReleased=void 0,this._keyStatus.lastKeyPressed!==this._keyStatus.lastKeyReleased&&(this._keyStatus.lastKeyPressed=void 0),this._keyStatus.altKey=e.altKey,this._keyStatus.ctrlKey=e.ctrlKey,this._keyStatus.metaKey=e.metaKey,this._keyStatus.shiftKey=e.shiftKey,this._keyStatus.lastKeyReleased&&(this._keyStatus.event=e,this.fire(this._keyStatus)))}),!0)),t.add(x(e.document.body,`mousedown`,(()=>{this._keyStatus.lastKeyPressed=void 0}),!0)),t.add(x(e.document.body,`mouseup`,(()=>{this._keyStatus.lastKeyPressed=void 0}),!0)),t.add(x(e.document.body,`mousemove`,(e=>{e.buttons&&(this._keyStatus.lastKeyPressed=void 0)}),!0)),t.add(x(e,`blur`,(()=>{this.resetKeyStatus()})))}get keyStatus(){return this._keyStatus}get isModifierPressed(){return this._keyStatus.altKey||this._keyStatus.ctrlKey||this._keyStatus.metaKey||this._keyStatus.shiftKey}resetKeyStatus(){this.doResetKeyStatus(),this.fire(this._keyStatus)}doResetKeyStatus(){this._keyStatus={altKey:!1,shiftKey:!1,ctrlKey:!1,metaKey:!1}}static getInstance(){return de.instance||=new de,de.instance}dispose(){super.dispose(),this._subscriptions.dispose()}}t.ModifierKeyEmitter=de;class fe extends h.Disposable{constructor(e,t){super(),this.element=e,this.callbacks=t,this.counter=0,this.dragStartTime=0,this.registerListeners()}registerListeners(){this.callbacks.onDragStart&&this._register(x(this.element,t.EventType.DRAG_START,(e=>{this.callbacks.onDragStart?.(e)}))),this.callbacks.onDrag&&this._register(x(this.element,t.EventType.DRAG,(e=>{this.callbacks.onDrag?.(e)}))),this._register(x(this.element,t.EventType.DRAG_ENTER,(e=>{this.counter++,this.dragStartTime=e.timeStamp,this.callbacks.onDragEnter?.(e)}))),this._register(x(this.element,t.EventType.DRAG_OVER,(e=>{e.preventDefault(),this.callbacks.onDragOver?.(e,e.timeStamp-this.dragStartTime)}))),this._register(x(this.element,t.EventType.DRAG_LEAVE,(e=>{this.counter--,this.counter===0&&(this.dragStartTime=0,this.callbacks.onDragLeave?.(e))}))),this._register(x(this.element,t.EventType.DRAG_END,(e=>{this.counter=0,this.dragStartTime=0,this.callbacks.onDragEnd?.(e)}))),this._register(x(this.element,t.EventType.DROP,(e=>{this.counter=0,this.dragStartTime=0,this.callbacks.onDrop?.(e)})))}}t.DragAndDropObserver=fe;let pe=/(?[\w\-]+)?(?:#(?[\w\-]+))?(?(?:\.(?:[\w\-]+))*)(?:@(?(?:[\w\_])+))?/;function me(e){return e.replace(/([a-z])([A-Z])/g,`$1-$2`).toLowerCase()}function he(e,t,n){for(let{name:r,value:i}of e.attributes)n&&!n.includes(r)||t.setAttribute(r,i)}function ge(e,t,n){let r=e.getAttribute(n);r?t.setAttribute(n,r):t.removeAttribute(n)}t.SafeTriangle=class{constructor(e,t,n){this.originX=e,this.originY=t,this.triangles=[];let{top:r,left:i,right:a,bottom:o}=n.getBoundingClientRect(),s=this.triangles,c=0;s[c++]=i,s[c++]=r,s[c++]=a,s[c++]=r,s[c++]=i,s[c++]=r,s[c++]=i,s[c++]=o,s[c++]=a,s[c++]=r,s[c++]=a,s[c++]=o,s[c++]=i,s[c++]=o,s[c++]=a,s[c++]=o}contains(e,t){let{triangles:n,originX:r,originY:i}=this;for(let a=0;a<4;a++)if((0,y.isPointWithinTriangle)(e,t,r,i,n[2*a],n[2*a+1],n[2*a+2],n[2*a+3]))return!0;return!1}}},9675:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.FastDomNode=void 0,t.createFastDomNode=function(e){return new n(e)};class n{constructor(e){this.domNode=e,this._maxWidth=``,this._width=``,this._height=``,this._top=``,this._left=``,this._bottom=``,this._right=``,this._paddingTop=``,this._paddingLeft=``,this._paddingBottom=``,this._paddingRight=``,this._fontFamily=``,this._fontWeight=``,this._fontSize=``,this._fontStyle=``,this._fontFeatureSettings=``,this._fontVariationSettings=``,this._textDecoration=``,this._lineHeight=``,this._letterSpacing=``,this._className=``,this._display=``,this._position=``,this._visibility=``,this._color=``,this._backgroundColor=``,this._layerHint=!1,this._contain=`none`,this._boxShadow=``}setMaxWidth(e){let t=r(e);this._maxWidth!==t&&(this._maxWidth=t,this.domNode.style.maxWidth=this._maxWidth)}setWidth(e){let t=r(e);this._width!==t&&(this._width=t,this.domNode.style.width=this._width)}setHeight(e){let t=r(e);this._height!==t&&(this._height=t,this.domNode.style.height=this._height)}setTop(e){let t=r(e);this._top!==t&&(this._top=t,this.domNode.style.top=this._top)}setLeft(e){let t=r(e);this._left!==t&&(this._left=t,this.domNode.style.left=this._left)}setBottom(e){let t=r(e);this._bottom!==t&&(this._bottom=t,this.domNode.style.bottom=this._bottom)}setRight(e){let t=r(e);this._right!==t&&(this._right=t,this.domNode.style.right=this._right)}setPaddingTop(e){let t=r(e);this._paddingTop!==t&&(this._paddingTop=t,this.domNode.style.paddingTop=this._paddingTop)}setPaddingLeft(e){let t=r(e);this._paddingLeft!==t&&(this._paddingLeft=t,this.domNode.style.paddingLeft=this._paddingLeft)}setPaddingBottom(e){let t=r(e);this._paddingBottom!==t&&(this._paddingBottom=t,this.domNode.style.paddingBottom=this._paddingBottom)}setPaddingRight(e){let t=r(e);this._paddingRight!==t&&(this._paddingRight=t,this.domNode.style.paddingRight=this._paddingRight)}setFontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.domNode.style.fontFamily=this._fontFamily)}setFontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.domNode.style.fontWeight=this._fontWeight)}setFontSize(e){let t=r(e);this._fontSize!==t&&(this._fontSize=t,this.domNode.style.fontSize=this._fontSize)}setFontStyle(e){this._fontStyle!==e&&(this._fontStyle=e,this.domNode.style.fontStyle=this._fontStyle)}setFontFeatureSettings(e){this._fontFeatureSettings!==e&&(this._fontFeatureSettings=e,this.domNode.style.fontFeatureSettings=this._fontFeatureSettings)}setFontVariationSettings(e){this._fontVariationSettings!==e&&(this._fontVariationSettings=e,this.domNode.style.fontVariationSettings=this._fontVariationSettings)}setTextDecoration(e){this._textDecoration!==e&&(this._textDecoration=e,this.domNode.style.textDecoration=this._textDecoration)}setLineHeight(e){let t=r(e);this._lineHeight!==t&&(this._lineHeight=t,this.domNode.style.lineHeight=this._lineHeight)}setLetterSpacing(e){let t=r(e);this._letterSpacing!==t&&(this._letterSpacing=t,this.domNode.style.letterSpacing=this._letterSpacing)}setClassName(e){this._className!==e&&(this._className=e,this.domNode.className=this._className)}toggleClassName(e,t){this.domNode.classList.toggle(e,t),this._className=this.domNode.className}setDisplay(e){this._display!==e&&(this._display=e,this.domNode.style.display=this._display)}setPosition(e){this._position!==e&&(this._position=e,this.domNode.style.position=this._position)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this.domNode.style.visibility=this._visibility)}setColor(e){this._color!==e&&(this._color=e,this.domNode.style.color=this._color)}setBackgroundColor(e){this._backgroundColor!==e&&(this._backgroundColor=e,this.domNode.style.backgroundColor=this._backgroundColor)}setLayerHinting(e){this._layerHint!==e&&(this._layerHint=e,this.domNode.style.transform=this._layerHint?`translate3d(0px, 0px, 0px)`:``)}setBoxShadow(e){this._boxShadow!==e&&(this._boxShadow=e,this.domNode.style.boxShadow=e)}setContain(e){this._contain!==e&&(this._contain=e,this.domNode.style.contain=this._contain)}setAttribute(e,t){this.domNode.setAttribute(e,t)}removeAttribute(e){this.domNode.removeAttribute(e)}appendChild(e){this.domNode.appendChild(e.domNode)}removeChild(e){this.domNode.removeChild(e.domNode)}}function r(e){return typeof e==`number`?`${e}px`:e}t.FastDomNode=n},8328:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.GlobalPointerMoveMonitor=void 0;let o=a(n(7093)),s=n(7150);t.GlobalPointerMoveMonitor=class{constructor(){this._hooks=new s.DisposableStore,this._pointerMoveCallback=null,this._onStopCallback=null}dispose(){this.stopMonitoring(!1),this._hooks.dispose()}stopMonitoring(e,t){if(!this.isMonitoring())return;this._hooks.clear(),this._pointerMoveCallback=null;let n=this._onStopCallback;this._onStopCallback=null,e&&n&&n(t)}isMonitoring(){return!!this._pointerMoveCallback}startMonitoring(e,t,n,r,i){this.isMonitoring()&&this.stopMonitoring(!1),this._pointerMoveCallback=r,this._onStopCallback=i;let a=e;try{e.setPointerCapture(t),this._hooks.add((0,s.toDisposable)((()=>{try{e.releasePointerCapture(t)}catch{}})))}catch{a=o.getWindow(e)}this._hooks.add(o.addDisposableListener(a,o.EventType.POINTER_MOVE,(e=>{e.buttons===n?(e.preventDefault(),this._pointerMoveCallback(e)):this.stopMonitoring(!0)}))),this._hooks.add(o.addDisposableListener(a,o.EventType.POINTER_UP,(e=>this.stopMonitoring(!0))))}}},6609:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.IframeUtils=void 0,t.parentOriginHash=async function(e,t){if(!crypto.subtle)throw Error(`'crypto.subtle' is not available so webviews will not work. This is likely because the editor is not running in a secure context (https://developer.mozilla.org/en-US/docs/Web/Security/Secure_Contexts).`);let n=JSON.stringify({parentOrigin:e,salt:t}),r=new TextEncoder().encode(n);return function(e){let t=Array.from(new Uint8Array(e)).map((e=>e.toString(16).padStart(2,`0`))).join(``);return BigInt(`0x${t}`).toString(32).padStart(52,`0`)}(await crypto.subtle.digest(`sha-256`,r))};let n=/* @__PURE__ */ new WeakMap;function r(e){if(!e.parent||e.parent===e)return null;try{let t=e.location,n=e.parent.location;if(t.origin!==`null`&&n.origin!==`null`&&t.origin!==n.origin)return null}catch{return null}return e.parent}t.IframeUtils=class{static getSameOriginWindowChain(e){let t=n.get(e);if(!t){t=[],n.set(e,t);let i,a=e;do i=r(a),i?t.push({window:new WeakRef(a),iframeElement:a.frameElement||null}):t.push({window:new WeakRef(a),iframeElement:null}),a=i;while(a)}return t.slice(0)}static getPositionOfChildWindowRelativeToAncestorWindow(e,t){if(!t||e===t)return{top:0,left:0};let n=0,r=0,i=this.getSameOriginWindowChain(e);for(let e of i){let i=e.window.deref();if(n+=i?.scrollY??0,r+=i?.scrollX??0,i===t||!e.iframeElement)break;let a=e.iframeElement.getBoundingClientRect();n+=a.top,r+=a.left}return{top:n,left:r}}}},5394:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.StandardKeyboardEvent=void 0,t.printKeyboardEvent=function(e){let t=[];return e.ctrlKey&&t.push(`ctrl`),e.shiftKey&&t.push(`shift`),e.altKey&&t.push(`alt`),e.metaKey&&t.push(`meta`),`modifiers: [${t.join(`,`)}], code: ${e.code}, keyCode: ${e.keyCode}, key: ${e.key}`},t.printStandardKeyboardEvent=function(e){let t=[];return e.ctrlKey&&t.push(`ctrl`),e.shiftKey&&t.push(`shift`),e.altKey&&t.push(`alt`),e.metaKey&&t.push(`meta`),`modifiers: [${t.join(`,`)}], code: ${e.code}, keyCode: ${e.keyCode} ('${s.KeyCodeUtils.toString(e.keyCode)}')`};let o=a(n(4333)),s=n(7883),c=n(2811),l=a(n(8163)),u=l.isMacintosh?s.KeyMod.WinCtrl:s.KeyMod.CtrlCmd,d=s.KeyMod.Alt,f=s.KeyMod.Shift,p=l.isMacintosh?s.KeyMod.CtrlCmd:s.KeyMod.WinCtrl;t.StandardKeyboardEvent=class{constructor(e){this._standardKeyboardEventBrand=!0;let t=e;this.browserEvent=t,this.target=t.target,this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,this.altGraphKey=t.getModifierState?.(`AltGraph`),this.keyCode=function(e){if(e.charCode){let t=String.fromCharCode(e.charCode).toUpperCase();return s.KeyCodeUtils.fromString(t)}let t=e.keyCode;if(t===3)return s.KeyCode.PauseBreak;if(o.isFirefox)switch(t){case 59:return s.KeyCode.Semicolon;case 60:if(l.isLinux)return s.KeyCode.IntlBackslash;break;case 61:return s.KeyCode.Equal;case 107:return s.KeyCode.NumpadAdd;case 109:return s.KeyCode.NumpadSubtract;case 173:return s.KeyCode.Minus;case 224:if(l.isMacintosh)return s.KeyCode.Meta}else if(o.isWebKit&&(l.isMacintosh&&t===93||!l.isMacintosh&&t===92))return s.KeyCode.Meta;return s.EVENT_KEY_CODE_MAP[t]||s.KeyCode.Unknown}(t),this.code=t.code,this.ctrlKey=this.ctrlKey||this.keyCode===s.KeyCode.Ctrl,this.altKey=this.altKey||this.keyCode===s.KeyCode.Alt,this.shiftKey=this.shiftKey||this.keyCode===s.KeyCode.Shift,this.metaKey=this.metaKey||this.keyCode===s.KeyCode.Meta,this._asKeybinding=this._computeKeybinding(),this._asKeyCodeChord=this._computeKeyCodeChord()}preventDefault(){this.browserEvent&&this.browserEvent.preventDefault&&this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent&&this.browserEvent.stopPropagation&&this.browserEvent.stopPropagation()}toKeyCodeChord(){return this._asKeyCodeChord}equals(e){return this._asKeybinding===e}_computeKeybinding(){let e=s.KeyCode.Unknown;this.keyCode!==s.KeyCode.Ctrl&&this.keyCode!==s.KeyCode.Shift&&this.keyCode!==s.KeyCode.Alt&&this.keyCode!==s.KeyCode.Meta&&(e=this.keyCode);let t=0;return this.ctrlKey&&(t|=u),this.altKey&&(t|=d),this.shiftKey&&(t|=f),this.metaKey&&(t|=p),t|=e,t}_computeKeyCodeChord(){let e=s.KeyCode.Unknown;return this.keyCode!==s.KeyCode.Ctrl&&this.keyCode!==s.KeyCode.Shift&&this.keyCode!==s.KeyCode.Alt&&this.keyCode!==s.KeyCode.Meta&&(e=this.keyCode),new c.KeyCodeChord(this.ctrlKey,this.shiftKey,this.altKey,this.metaKey,e)}}},5964:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.StandardWheelEvent=t.DragMouseEvent=t.StandardMouseEvent=void 0;let o=a(n(4333)),s=n(6609),c=a(n(8163));class l{constructor(e,t){this.timestamp=Date.now(),this.browserEvent=t,this.leftButton=t.button===0,this.middleButton=t.button===1,this.rightButton=t.button===2,this.buttons=t.buttons,this.target=t.target,this.detail=t.detail||1,t.type===`dblclick`&&(this.detail=2),this.ctrlKey=t.ctrlKey,this.shiftKey=t.shiftKey,this.altKey=t.altKey,this.metaKey=t.metaKey,typeof t.pageX==`number`?(this.posx=t.pageX,this.posy=t.pageY):(this.posx=t.clientX+this.target.ownerDocument.body.scrollLeft+this.target.ownerDocument.documentElement.scrollLeft,this.posy=t.clientY+this.target.ownerDocument.body.scrollTop+this.target.ownerDocument.documentElement.scrollTop);let n=s.IframeUtils.getPositionOfChildWindowRelativeToAncestorWindow(e,t.view);this.posx-=n.left,this.posy-=n.top}preventDefault(){this.browserEvent.preventDefault()}stopPropagation(){this.browserEvent.stopPropagation()}}t.StandardMouseEvent=l,t.DragMouseEvent=class extends l{constructor(e,t){super(e,t),this.dataTransfer=t.dataTransfer}},t.StandardWheelEvent=class{constructor(e,t=0,n=0){this.browserEvent=e||null,this.target=e?e.target||e.targetNode||e.srcElement:null,this.deltaY=n,this.deltaX=t;let r=!1;if(o.isChrome){let e=navigator.userAgent.match(/Chrome\/(\d+)/);r=(e?parseInt(e[1]):123)<=122}if(e){let t=e,n=e,i=e.view?.devicePixelRatio||1;if(t.wheelDeltaY!==void 0)this.deltaY=r?t.wheelDeltaY/(120*i):t.wheelDeltaY/120;else if(n.VERTICAL_AXIS!==void 0&&n.axis===n.VERTICAL_AXIS)this.deltaY=-n.detail/3;else if(e.type===`wheel`){let t=e;this.deltaY=t.deltaMode===t.DOM_DELTA_LINE?o.isFirefox&&!c.isMacintosh?-e.deltaY/3:-e.deltaY:-e.deltaY/40}if(t.wheelDeltaX!==void 0)this.deltaX=o.isSafari&&c.isWindows?-t.wheelDeltaX/120:r?t.wheelDeltaX/(120*i):t.wheelDeltaX/120;else if(n.HORIZONTAL_AXIS!==void 0&&n.axis===n.HORIZONTAL_AXIS)this.deltaX=-e.detail/3;else if(e.type===`wheel`){let t=e;this.deltaX=t.deltaMode===t.DOM_DELTA_LINE?o.isFirefox&&!c.isMacintosh?-e.deltaX/3:-e.deltaX:-e.deltaX/40}this.deltaY===0&&this.deltaX===0&&e.wheelDelta&&(this.deltaY=r?e.wheelDelta/(120*i):e.wheelDelta/120)}}preventDefault(){this.browserEvent?.preventDefault()}stopPropagation(){this.browserEvent?.stopPropagation()}}},8594:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__decorate||function(e,t,n,r){var i,a=arguments.length,o=a<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)o=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(i=e[s])&&(o=(a<3?i(o):a>3?i(t,n,o):i(t,n))||o);return a>3&&o&&Object.defineProperty(t,n,o),o},o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Gesture=t.EventType=void 0;let s=o(n(7093)),c=n(4693),l=o(n(3058)),u=n(4838),d=n(802),f=n(7150),p=n(6317);var m;(function(e){e.Tap=`-xterm-gesturetap`,e.Change=`-xterm-gesturechange`,e.Start=`-xterm-gesturestart`,e.End=`-xterm-gesturesend`,e.Contextmenu=`-xterm-gesturecontextmenu`})(m||(t.EventType=m={}));class h extends f.Disposable{static{this.SCROLL_FRICTION=-.005}static{this.HOLD_DELAY=700}static{this.CLEAR_TAP_COUNT_TIME=400}constructor(){super(),this.dispatched=!1,this.targets=new p.LinkedList,this.ignoreTargets=new p.LinkedList,this.activeTouches={},this.handle=null,this._lastSetTapCountTime=0,this._register(d.Event.runAndSubscribe(s.onDidRegisterWindow,(({window:e,disposables:t})=>{t.add(s.addDisposableListener(e.document,`touchstart`,(e=>this.onTouchStart(e)),{passive:!1})),t.add(s.addDisposableListener(e.document,`touchend`,(t=>this.onTouchEnd(e,t)))),t.add(s.addDisposableListener(e.document,`touchmove`,(e=>this.onTouchMove(e)),{passive:!1}))}),{window:c.mainWindow,disposables:this._store}))}static addTarget(e){if(!h.isTouchDevice())return f.Disposable.None;h.INSTANCE||=(0,f.markAsSingleton)(new h);let t=h.INSTANCE.targets.push(e);return(0,f.toDisposable)(t)}static ignoreTarget(e){if(!h.isTouchDevice())return f.Disposable.None;h.INSTANCE||=(0,f.markAsSingleton)(new h);let t=h.INSTANCE.ignoreTargets.push(e);return(0,f.toDisposable)(t)}static isTouchDevice(){return`ontouchstart`in c.mainWindow||navigator.maxTouchPoints>0}dispose(){this.handle&&=(this.handle.dispose(),null),super.dispose()}onTouchStart(e){let t=Date.now();this.handle&&=(this.handle.dispose(),null);for(let n=0,r=e.targetTouches.length;n=h.HOLD_DELAY&&Math.abs(o.initialPageX-l.tail(o.rollingPageX))<30&&Math.abs(o.initialPageY-l.tail(o.rollingPageY))<30){let e=this.newGestureEvent(m.Contextmenu,o.initialTarget);e.pageX=l.tail(o.rollingPageX),e.pageY=l.tail(o.rollingPageY),this.dispatchEvent(e)}else if(r===1){let t=l.tail(o.rollingPageX),r=l.tail(o.rollingPageY),i=l.tail(o.rollingTimestamps)-o.rollingTimestamps[0],a=t-o.rollingPageX[0],s=r-o.rollingPageY[0],c=[...this.targets].filter((e=>o.initialTarget instanceof Node&&e.contains(o.initialTarget)));this.inertia(e,c,n,Math.abs(a)/i,a>0?1:-1,t,Math.abs(s)/i,s>0?1:-1,r)}this.dispatchEvent(this.newGestureEvent(m.End,o.initialTarget)),delete this.activeTouches[a.identifier]}this.dispatched&&=(t.preventDefault(),t.stopPropagation(),!1)}newGestureEvent(e,t){let n=document.createEvent(`CustomEvent`);return n.initEvent(e,!1,!0),n.initialTarget=t,n.tapCount=0,n}dispatchEvent(e){if(e.type===m.Tap){let t=(/* @__PURE__ */ new Date()).getTime(),n=0;n=t-this._lastSetTapCountTime>h.CLEAR_TAP_COUNT_TIME?1:2,this._lastSetTapCountTime=t,e.tapCount=n}else e.type!==m.Change&&e.type!==m.Contextmenu||(this._lastSetTapCountTime=0);if(e.initialTarget instanceof Node){for(let t of this.ignoreTargets)if(t.contains(e.initialTarget))return;let t=[];for(let n of this.targets)if(n.contains(e.initialTarget)){let r=0,i=e.initialTarget;for(;i&&i!==n;)r++,i=i.parentElement;t.push([r,n])}t.sort(((e,t)=>e[0]-t[0]));for(let[n,r]of t)r.dispatchEvent(e),this.dispatched=!0}}inertia(e,t,n,r,i,a,o,c,l){this.handle=s.scheduleAtNextAnimationFrame(e,(()=>{let s=Date.now(),u=s-n,d=0,f=0,p=!0;r+=h.SCROLL_FRICTION*u,o+=h.SCROLL_FRICTION*u,r>0&&(p=!1,d=i*r*u),o>0&&(p=!1,f=c*o*u);let g=this.newGestureEvent(m.Change);g.translationX=d,g.translationY=f,t.forEach((e=>e.dispatchEvent(g))),p||this.inertia(e,t,s,r,i,a+d,o,c,l+f)}))}onTouchMove(e){let t=Date.now();for(let n=0,r=e.changedTouches.length;n3&&(i.rollingPageX.shift(),i.rollingPageY.shift(),i.rollingTimestamps.shift()),i.rollingPageX.push(r.pageX),i.rollingPageY.push(r.pageY),i.rollingTimestamps.push(t)}this.dispatched&&=(e.preventDefault(),e.stopPropagation(),!1)}}t.Gesture=h,a([u.memoize],h,`isTouchDevice`,null)},8801:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.AbstractScrollbar=void 0;let o=a(n(7093)),s=n(9675),c=n(8328),l=n(8974),u=n(79),d=n(8286),f=a(n(8163));class p extends d.Widget{constructor(e){super(),this._lazyRender=e.lazyRender,this._host=e.host,this._scrollable=e.scrollable,this._scrollByPage=e.scrollByPage,this._scrollbarState=e.scrollbarState,this._visibilityController=this._register(new u.ScrollbarVisibilityController(e.visibility,`visible scrollbar `+e.extraScrollbarClassName,`invisible scrollbar `+e.extraScrollbarClassName)),this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._pointerMoveMonitor=this._register(new c.GlobalPointerMoveMonitor),this._shouldRender=!0,this.domNode=(0,s.createFastDomNode)(document.createElement(`div`)),this.domNode.setAttribute(`role`,`presentation`),this.domNode.setAttribute(`aria-hidden`,`true`),this._visibilityController.setDomNode(this.domNode),this.domNode.setPosition(`absolute`),this._register(o.addDisposableListener(this.domNode.domNode,o.EventType.POINTER_DOWN,(e=>this._domNodePointerDown(e))))}_createArrow(e){let t=this._register(new l.ScrollbarArrow(e));this.domNode.domNode.appendChild(t.bgDomNode),this.domNode.domNode.appendChild(t.domNode)}_createSlider(e,t,n,r){this.slider=(0,s.createFastDomNode)(document.createElement(`div`)),this.slider.setClassName(`slider`),this.slider.setPosition(`absolute`),this.slider.setTop(e),this.slider.setLeft(t),typeof n==`number`&&this.slider.setWidth(n),typeof r==`number`&&this.slider.setHeight(r),this.slider.setLayerHinting(!0),this.slider.setContain(`strict`),this.domNode.domNode.appendChild(this.slider.domNode),this._register(o.addDisposableListener(this.slider.domNode,o.EventType.POINTER_DOWN,(e=>{e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}))),this.onclick(this.slider.domNode,(e=>{e.leftButton&&e.stopPropagation()}))}_onElementSize(e){return this._scrollbarState.setVisibleSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollSize(e){return this._scrollbarState.setScrollSize(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}_onElementScrollPosition(e){return this._scrollbarState.setScrollPosition(e)&&(this._visibilityController.setIsNeeded(this._scrollbarState.isNeeded()),this._shouldRender=!0,this._lazyRender||this.render()),this._shouldRender}beginReveal(){this._visibilityController.setShouldBeVisible(!0)}beginHide(){this._visibilityController.setShouldBeVisible(!1)}render(){this._shouldRender&&(this._shouldRender=!1,this._renderDomNode(this._scrollbarState.getRectangleLargeSize(),this._scrollbarState.getRectangleSmallSize()),this._updateSlider(this._scrollbarState.getSliderSize(),this._scrollbarState.getArrowSize()+this._scrollbarState.getSliderPosition()))}_domNodePointerDown(e){e.target===this.domNode.domNode&&this._onPointerDown(e)}delegatePointerDown(e){let t=this.domNode.domNode.getClientRects()[0].top,n=t+this._scrollbarState.getSliderPosition(),r=t+this._scrollbarState.getSliderPosition()+this._scrollbarState.getSliderSize(),i=this._sliderPointerPosition(e);n<=i&&i<=r?e.button===0&&(e.preventDefault(),this._sliderPointerDown(e)):this._onPointerDown(e)}_onPointerDown(e){let t,n;if(e.target===this.domNode.domNode&&typeof e.offsetX==`number`&&typeof e.offsetY==`number`)t=e.offsetX,n=e.offsetY;else{let r=o.getDomNodePagePosition(this.domNode.domNode);t=e.pageX-r.left,n=e.pageY-r.top}let r=this._pointerDownRelativePosition(t,n);this._setDesiredScrollPositionNow(this._scrollByPage?this._scrollbarState.getDesiredScrollPositionFromOffsetPaged(r):this._scrollbarState.getDesiredScrollPositionFromOffset(r)),e.button===0&&(e.preventDefault(),this._sliderPointerDown(e))}_sliderPointerDown(e){if(!(e.target&&e.target instanceof Element))return;let t=this._sliderPointerPosition(e),n=this._sliderOrthogonalPointerPosition(e),r=this._scrollbarState.clone();this.slider.toggleClassName(`active`,!0),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,(e=>{let i=this._sliderOrthogonalPointerPosition(e),a=Math.abs(i-n);if(f.isWindows&&a>140)return void this._setDesiredScrollPositionNow(r.getScrollPosition());let o=this._sliderPointerPosition(e)-t;this._setDesiredScrollPositionNow(r.getDesiredScrollPositionFromDelta(o))}),(()=>{this.slider.toggleClassName(`active`,!1),this._host.onDragEnd()})),this._host.onDragStart()}_setDesiredScrollPositionNow(e){let t={};this.writeScrollPosition(t,e),this._scrollable.setScrollPositionNow(t)}updateScrollbarSize(e){this._updateScrollbarSize(e),this._scrollbarState.setScrollbarSize(e),this._shouldRender=!0,this._lazyRender||this.render()}isNeeded(){return this._scrollbarState.isNeeded()}}t.AbstractScrollbar=p},151:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.HorizontalScrollbar=void 0;let r=n(8801),i=n(8245),a=n(9881);class o extends r.AbstractScrollbar{constructor(e,t,n){let r=e.getScrollDimensions(),o=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new i.ScrollbarState(t.horizontalHasArrows?t.arrowSize:0,t.horizontal===a.ScrollbarVisibility.Hidden?0:t.horizontalScrollbarSize,t.vertical===a.ScrollbarVisibility.Hidden?0:t.verticalScrollbarSize,r.width,r.scrollWidth,o.scrollLeft),visibility:t.horizontal,extraScrollbarClassName:`horizontal`,scrollable:e,scrollByPage:t.scrollByPage}),t.horizontalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(Math.floor((t.horizontalScrollbarSize-t.horizontalSliderSize)/2),0,void 0,t.horizontalSliderSize)}_updateSlider(e,t){this.slider.setWidth(e),this.slider.setLeft(t)}_renderDomNode(e,t){this.domNode.setWidth(e),this.domNode.setHeight(t),this.domNode.setLeft(0),this.domNode.setBottom(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollWidth)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollLeft)||this._shouldRender,this._shouldRender=this._onElementSize(e.width)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return e}_sliderPointerPosition(e){return e.pageX}_sliderOrthogonalPointerPosition(e){return e.pageY}_updateScrollbarSize(e){this.slider.setHeight(e)}writeScrollPosition(e,t){e.scrollLeft=t}updateOptions(e){this.updateScrollbarSize(e.horizontal===a.ScrollbarVisibility.Hidden?0:e.horizontalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(e.vertical===a.ScrollbarVisibility.Hidden?0:e.verticalScrollbarSize),this._visibilityController.setVisibility(e.horizontal),this._scrollByPage=e.scrollByPage}}t.HorizontalScrollbar=o},8234:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.DomScrollableElement=t.SmoothScrollableElement=t.ScrollableElement=t.AbstractScrollableElement=t.MouseWheelClassifier=void 0;let o=n(4333),s=a(n(7093)),c=n(9675),l=n(5964),u=n(151),d=n(5473),f=n(8286),p=n(1758),m=n(802),h=n(7150),g=a(n(8163)),_=n(9881);class v{constructor(e,t,n){this.timestamp=e,this.deltaX=t,this.deltaY=n,this.score=0}}class y{static{this.INSTANCE=new y}constructor(){this._capacity=5,this._memory=[],this._front=-1,this._rear=-1}isPhysicalMouseWheel(){if(this._front===-1&&this._rear===-1)return!1;let e=1,t=0,n=1,r=this._rear;for(;;){let i=r===this._front?e:2**-n;if(e-=i,t+=this._memory[r].score*i,r===this._front)break;r=(this._capacity+r-1)%this._capacity,n++}return t<=.5}acceptStandardWheelEvent(e){if(o.isChrome){let t=s.getWindow(e.browserEvent),n=(0,o.getZoomFactor)(t);this.accept(Date.now(),e.deltaX*n,e.deltaY*n)}else this.accept(Date.now(),e.deltaX,e.deltaY)}accept(e,t,n){let r=null,i=new v(e,t,n);this._front===-1&&this._rear===-1?(this._memory[0]=i,this._front=0,this._rear=0):(r=this._memory[this._rear],this._rear=(this._rear+1)%this._capacity,this._rear===this._front&&(this._front=(this._front+1)%this._capacity),this._memory[this._rear]=i),i.score=this._computeScore(i,r)}_computeScore(e,t){if(Math.abs(e.deltaX)>0&&Math.abs(e.deltaY)>0)return 1;let n=.5;if(this._isAlmostInt(e.deltaX)&&this._isAlmostInt(e.deltaY)||(n+=.25),t){let r=Math.abs(e.deltaX),i=Math.abs(e.deltaY),a=Math.abs(t.deltaX),o=Math.abs(t.deltaY),s=Math.max(Math.min(r,a),1),c=Math.max(Math.min(i,o),1),l=Math.max(r,a),u=Math.max(i,o);l%s==0&&u%c==0&&(n-=.5)}return Math.min(Math.max(n,0),1)}_isAlmostInt(e){return Math.abs(Math.round(e)-e)<.01}}t.MouseWheelClassifier=y;class b extends f.Widget{get options(){return this._options}constructor(e,t,n){super(),this._onScroll=this._register(new m.Emitter),this.onScroll=this._onScroll.event,this._onWillScroll=this._register(new m.Emitter),this.onWillScroll=this._onWillScroll.event,this._options=function(e){let t={lazyRender:e.lazyRender!==void 0&&e.lazyRender,className:e.className===void 0?``:e.className,useShadows:e.useShadows===void 0||e.useShadows,handleMouseWheel:e.handleMouseWheel===void 0||e.handleMouseWheel,flipAxes:e.flipAxes!==void 0&&e.flipAxes,consumeMouseWheelIfScrollbarIsNeeded:e.consumeMouseWheelIfScrollbarIsNeeded!==void 0&&e.consumeMouseWheelIfScrollbarIsNeeded,alwaysConsumeMouseWheel:e.alwaysConsumeMouseWheel!==void 0&&e.alwaysConsumeMouseWheel,scrollYToX:e.scrollYToX!==void 0&&e.scrollYToX,mouseWheelScrollSensitivity:e.mouseWheelScrollSensitivity===void 0?1:e.mouseWheelScrollSensitivity,fastScrollSensitivity:e.fastScrollSensitivity===void 0?5:e.fastScrollSensitivity,scrollPredominantAxis:e.scrollPredominantAxis===void 0||e.scrollPredominantAxis,mouseWheelSmoothScroll:e.mouseWheelSmoothScroll===void 0||e.mouseWheelSmoothScroll,arrowSize:e.arrowSize===void 0?11:e.arrowSize,listenOnDomNode:e.listenOnDomNode===void 0?null:e.listenOnDomNode,horizontal:e.horizontal===void 0?_.ScrollbarVisibility.Auto:e.horizontal,horizontalScrollbarSize:e.horizontalScrollbarSize===void 0?10:e.horizontalScrollbarSize,horizontalSliderSize:e.horizontalSliderSize===void 0?0:e.horizontalSliderSize,horizontalHasArrows:e.horizontalHasArrows!==void 0&&e.horizontalHasArrows,vertical:e.vertical===void 0?_.ScrollbarVisibility.Auto:e.vertical,verticalScrollbarSize:e.verticalScrollbarSize===void 0?10:e.verticalScrollbarSize,verticalHasArrows:e.verticalHasArrows!==void 0&&e.verticalHasArrows,verticalSliderSize:e.verticalSliderSize===void 0?0:e.verticalSliderSize,scrollByPage:e.scrollByPage!==void 0&&e.scrollByPage};return t.horizontalSliderSize=e.horizontalSliderSize===void 0?t.horizontalScrollbarSize:e.horizontalSliderSize,t.verticalSliderSize=e.verticalSliderSize===void 0?t.verticalScrollbarSize:e.verticalSliderSize,g.isMacintosh&&(t.className+=` mac`),t}(t),this._scrollable=n,this._register(this._scrollable.onScroll((e=>{this._onWillScroll.fire(e),this._onDidScroll(e),this._onScroll.fire(e)})));let r={onMouseWheel:e=>this._onMouseWheel(e),onDragStart:()=>this._onDragStart(),onDragEnd:()=>this._onDragEnd()};this._verticalScrollbar=this._register(new d.VerticalScrollbar(this._scrollable,this._options,r)),this._horizontalScrollbar=this._register(new u.HorizontalScrollbar(this._scrollable,this._options,r)),this._domNode=document.createElement(`div`),this._domNode.className=`xterm-scrollable-element `+this._options.className,this._domNode.setAttribute(`role`,`presentation`),this._domNode.style.position=`relative`,this._domNode.appendChild(e),this._domNode.appendChild(this._horizontalScrollbar.domNode.domNode),this._domNode.appendChild(this._verticalScrollbar.domNode.domNode),this._options.useShadows?(this._leftShadowDomNode=(0,c.createFastDomNode)(document.createElement(`div`)),this._leftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._leftShadowDomNode.domNode),this._topShadowDomNode=(0,c.createFastDomNode)(document.createElement(`div`)),this._topShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topShadowDomNode.domNode),this._topLeftShadowDomNode=(0,c.createFastDomNode)(document.createElement(`div`)),this._topLeftShadowDomNode.setClassName(`shadow`),this._domNode.appendChild(this._topLeftShadowDomNode.domNode)):(this._leftShadowDomNode=null,this._topShadowDomNode=null,this._topLeftShadowDomNode=null),this._listenOnDomNode=this._options.listenOnDomNode||this._domNode,this._mouseWheelToDispose=[],this._setListeningToMouseWheel(this._options.handleMouseWheel),this.onmouseover(this._listenOnDomNode,(e=>this._onMouseOver(e))),this.onmouseleave(this._listenOnDomNode,(e=>this._onMouseLeave(e))),this._hideTimeout=this._register(new p.TimeoutTimer),this._isDragging=!1,this._mouseIsOver=!1,this._shouldRender=!0,this._revealOnScroll=!0}dispose(){this._mouseWheelToDispose=(0,h.dispose)(this._mouseWheelToDispose),super.dispose()}getDomNode(){return this._domNode}getOverviewRulerLayoutInfo(){return{parent:this._domNode,insertBefore:this._verticalScrollbar.domNode.domNode}}delegateVerticalScrollbarPointerDown(e){this._verticalScrollbar.delegatePointerDown(e)}getScrollDimensions(){return this._scrollable.getScrollDimensions()}setScrollDimensions(e){this._scrollable.setScrollDimensions(e,!1)}updateClassName(e){this._options.className=e,g.isMacintosh&&(this._options.className+=` mac`),this._domNode.className=`xterm-scrollable-element `+this._options.className}updateOptions(e){e.handleMouseWheel!==void 0&&(this._options.handleMouseWheel=e.handleMouseWheel,this._setListeningToMouseWheel(this._options.handleMouseWheel)),e.mouseWheelScrollSensitivity!==void 0&&(this._options.mouseWheelScrollSensitivity=e.mouseWheelScrollSensitivity),e.fastScrollSensitivity!==void 0&&(this._options.fastScrollSensitivity=e.fastScrollSensitivity),e.scrollPredominantAxis!==void 0&&(this._options.scrollPredominantAxis=e.scrollPredominantAxis),e.horizontal!==void 0&&(this._options.horizontal=e.horizontal),e.vertical!==void 0&&(this._options.vertical=e.vertical),e.horizontalScrollbarSize!==void 0&&(this._options.horizontalScrollbarSize=e.horizontalScrollbarSize),e.verticalScrollbarSize!==void 0&&(this._options.verticalScrollbarSize=e.verticalScrollbarSize),e.scrollByPage!==void 0&&(this._options.scrollByPage=e.scrollByPage),this._horizontalScrollbar.updateOptions(this._options),this._verticalScrollbar.updateOptions(this._options),this._options.lazyRender||this._render()}setRevealOnScroll(e){this._revealOnScroll=e}delegateScrollFromMouseWheelEvent(e){this._onMouseWheel(new l.StandardWheelEvent(e))}_setListeningToMouseWheel(e){this._mouseWheelToDispose.length>0!==e&&(this._mouseWheelToDispose=(0,h.dispose)(this._mouseWheelToDispose),e)&&this._mouseWheelToDispose.push(s.addDisposableListener(this._listenOnDomNode,s.EventType.MOUSE_WHEEL,e=>{this._onMouseWheel(new l.StandardWheelEvent(e))},{passive:!1}))}_onMouseWheel(e){if(e.browserEvent?.defaultPrevented)return;let t=y.INSTANCE;t.acceptStandardWheelEvent(e);let n=!1;if(e.deltaY||e.deltaX){let r=e.deltaY*this._options.mouseWheelScrollSensitivity,i=e.deltaX*this._options.mouseWheelScrollSensitivity;this._options.scrollPredominantAxis&&(this._options.scrollYToX&&i+r===0?i=r=0:Math.abs(r)>=Math.abs(i)?i=0:r=0),this._options.flipAxes&&([r,i]=[i,r]);let a=!g.isMacintosh&&e.browserEvent&&e.browserEvent.shiftKey;!this._options.scrollYToX&&!a||i||(i=r,r=0),e.browserEvent&&e.browserEvent.altKey&&(i*=this._options.fastScrollSensitivity,r*=this._options.fastScrollSensitivity);let o=this._scrollable.getFutureScrollPosition(),s={};if(r){let e=50*r,t=o.scrollTop-(e<0?Math.floor(e):Math.ceil(e));this._verticalScrollbar.writeScrollPosition(s,t)}if(i){let e=50*i,t=o.scrollLeft-(e<0?Math.floor(e):Math.ceil(e));this._horizontalScrollbar.writeScrollPosition(s,t)}s=this._scrollable.validateScrollPosition(s),(o.scrollLeft!==s.scrollLeft||o.scrollTop!==s.scrollTop)&&(this._options.mouseWheelSmoothScroll&&t.isPhysicalMouseWheel()?this._scrollable.setScrollPositionSmooth(s):this._scrollable.setScrollPositionNow(s),n=!0)}let r=n;!r&&this._options.alwaysConsumeMouseWheel&&(r=!0),!r&&this._options.consumeMouseWheelIfScrollbarIsNeeded&&(this._verticalScrollbar.isNeeded()||this._horizontalScrollbar.isNeeded())&&(r=!0),r&&(e.preventDefault(),e.stopPropagation())}_onDidScroll(e){this._shouldRender=this._horizontalScrollbar.onDidScroll(e)||this._shouldRender,this._shouldRender=this._verticalScrollbar.onDidScroll(e)||this._shouldRender,this._options.useShadows&&(this._shouldRender=!0),this._revealOnScroll&&this._reveal(),this._options.lazyRender||this._render()}renderNow(){if(!this._options.lazyRender)throw Error("Please use `lazyRender` together with `renderNow`!");this._render()}_render(){if(this._shouldRender&&(this._shouldRender=!1,this._horizontalScrollbar.render(),this._verticalScrollbar.render(),this._options.useShadows)){let e=this._scrollable.getCurrentScrollPosition(),t=e.scrollTop>0,n=e.scrollLeft>0,r=n?` left`:``,i=t?` top`:``,a=n||t?` top-left-corner`:``;this._leftShadowDomNode.setClassName(`shadow${r}`),this._topShadowDomNode.setClassName(`shadow${i}`),this._topLeftShadowDomNode.setClassName(`shadow${a}${i}${r}`)}}_onDragStart(){this._isDragging=!0,this._reveal()}_onDragEnd(){this._isDragging=!1,this._hide()}_onMouseLeave(e){this._mouseIsOver=!1,this._hide()}_onMouseOver(e){this._mouseIsOver=!0,this._reveal()}_reveal(){this._verticalScrollbar.beginReveal(),this._horizontalScrollbar.beginReveal(),this._scheduleHide()}_hide(){this._mouseIsOver||this._isDragging||(this._verticalScrollbar.beginHide(),this._horizontalScrollbar.beginHide())}_scheduleHide(){this._mouseIsOver||this._isDragging||this._hideTimeout.cancelAndSet((()=>this._hide()),500)}}t.AbstractScrollableElement=b,t.ScrollableElement=class extends b{constructor(e,t){(t||={}).mouseWheelSmoothScroll=!1;let n=new _.Scrollable({forceIntegerValues:!0,smoothScrollDuration:0,scheduleAtNextAnimationFrame:t=>s.scheduleAtNextAnimationFrame(s.getWindow(e),t)});super(e,t,n),this._register(n)}setScrollPosition(e){this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}},t.SmoothScrollableElement=class extends b{constructor(e,t,n){super(e,t,n)}setScrollPosition(e){e.reuseAnimation?this._scrollable.setScrollPositionSmooth(e,e.reuseAnimation):this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}},t.DomScrollableElement=class extends b{constructor(e,t){(t||={}).mouseWheelSmoothScroll=!1;let n=new _.Scrollable({forceIntegerValues:!1,smoothScrollDuration:0,scheduleAtNextAnimationFrame:t=>s.scheduleAtNextAnimationFrame(s.getWindow(e),t)});super(e,t,n),this._register(n),this._element=e,this._register(this.onScroll((e=>{e.scrollTopChanged&&(this._element.scrollTop=e.scrollTop),e.scrollLeftChanged&&(this._element.scrollLeft=e.scrollLeft)}))),this.scanDomNode()}setScrollPosition(e){this._scrollable.setScrollPositionNow(e)}getScrollPosition(){return this._scrollable.getCurrentScrollPosition()}scanDomNode(){this.setScrollDimensions({width:this._element.clientWidth,scrollWidth:this._element.scrollWidth,height:this._element.clientHeight,scrollHeight:this._element.scrollHeight}),this.setScrollPosition({scrollLeft:this._element.scrollLeft,scrollTop:this._element.scrollTop})}}},8974:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollbarArrow=t.ARROW_IMG_SIZE=void 0;let o=n(8328),s=n(8286),c=n(1758),l=a(n(7093));t.ARROW_IMG_SIZE=11;class u extends s.Widget{constructor(e){super(),this._onActivate=e.onActivate,this.bgDomNode=document.createElement(`div`),this.bgDomNode.className=`arrow-background`,this.bgDomNode.style.position=`absolute`,this.bgDomNode.style.width=e.bgWidth+`px`,this.bgDomNode.style.height=e.bgHeight+`px`,e.top!==void 0&&(this.bgDomNode.style.top=`0px`),e.left!==void 0&&(this.bgDomNode.style.left=`0px`),e.bottom!==void 0&&(this.bgDomNode.style.bottom=`0px`),e.right!==void 0&&(this.bgDomNode.style.right=`0px`),this.domNode=document.createElement(`div`),this.domNode.className=e.className,this.domNode.style.position=`absolute`,this.domNode.style.width=t.ARROW_IMG_SIZE+`px`,this.domNode.style.height=t.ARROW_IMG_SIZE+`px`,e.top!==void 0&&(this.domNode.style.top=e.top+`px`),e.left!==void 0&&(this.domNode.style.left=e.left+`px`),e.bottom!==void 0&&(this.domNode.style.bottom=e.bottom+`px`),e.right!==void 0&&(this.domNode.style.right=e.right+`px`),this._pointerMoveMonitor=this._register(new o.GlobalPointerMoveMonitor),this._register(l.addStandardDisposableListener(this.bgDomNode,l.EventType.POINTER_DOWN,(e=>this._arrowPointerDown(e)))),this._register(l.addStandardDisposableListener(this.domNode,l.EventType.POINTER_DOWN,(e=>this._arrowPointerDown(e)))),this._pointerdownRepeatTimer=this._register(new l.WindowIntervalTimer),this._pointerdownScheduleRepeatTimer=this._register(new c.TimeoutTimer)}_arrowPointerDown(e){e.target&&e.target instanceof Element&&(this._onActivate(),this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancelAndSet((()=>{this._pointerdownRepeatTimer.cancelAndSet((()=>this._onActivate()),1e3/24,l.getWindow(e))}),200),this._pointerMoveMonitor.startMonitoring(e.target,e.pointerId,e.buttons,(e=>{}),(()=>{this._pointerdownRepeatTimer.cancel(),this._pointerdownScheduleRepeatTimer.cancel()})),e.preventDefault())}}t.ScrollbarArrow=u},8245:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollbarState=void 0;class n{constructor(e,t,n,r,i,a){this._scrollbarSize=Math.round(t),this._oppositeScrollbarSize=Math.round(n),this._arrowSize=Math.round(e),this._visibleSize=r,this._scrollSize=i,this._scrollPosition=a,this._computedAvailableSize=0,this._computedIsNeeded=!1,this._computedSliderSize=0,this._computedSliderRatio=0,this._computedSliderPosition=0,this._refreshComputedValues()}clone(){return new n(this._arrowSize,this._scrollbarSize,this._oppositeScrollbarSize,this._visibleSize,this._scrollSize,this._scrollPosition)}setVisibleSize(e){let t=Math.round(e);return this._visibleSize!==t&&(this._visibleSize=t,this._refreshComputedValues(),!0)}setScrollSize(e){let t=Math.round(e);return this._scrollSize!==t&&(this._scrollSize=t,this._refreshComputedValues(),!0)}setScrollPosition(e){let t=Math.round(e);return this._scrollPosition!==t&&(this._scrollPosition=t,this._refreshComputedValues(),!0)}setScrollbarSize(e){this._scrollbarSize=Math.round(e)}setOppositeScrollbarSize(e){this._oppositeScrollbarSize=Math.round(e)}static _computeValues(e,t,n,r,i){let a=Math.max(0,n-e),o=Math.max(0,a-2*t),s=r>0&&r>n;if(!s)return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(o),computedSliderRatio:0,computedSliderPosition:0};let c=Math.round(Math.max(20,Math.floor(n*o/r))),l=(o-c)/(r-n),u=i*l;return{computedAvailableSize:Math.round(a),computedIsNeeded:s,computedSliderSize:Math.round(c),computedSliderRatio:l,computedSliderPosition:Math.round(u)}}_refreshComputedValues(){let e=n._computeValues(this._oppositeScrollbarSize,this._arrowSize,this._visibleSize,this._scrollSize,this._scrollPosition);this._computedAvailableSize=e.computedAvailableSize,this._computedIsNeeded=e.computedIsNeeded,this._computedSliderSize=e.computedSliderSize,this._computedSliderRatio=e.computedSliderRatio,this._computedSliderPosition=e.computedSliderPosition}getArrowSize(){return this._arrowSize}getScrollPosition(){return this._scrollPosition}getRectangleLargeSize(){return this._computedAvailableSize}getRectangleSmallSize(){return this._scrollbarSize}isNeeded(){return this._computedIsNeeded}getSliderSize(){return this._computedSliderSize}getSliderPosition(){return this._computedSliderPosition}getDesiredScrollPositionFromOffset(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize-this._computedSliderSize/2;return Math.round(t/this._computedSliderRatio)}getDesiredScrollPositionFromOffsetPaged(e){if(!this._computedIsNeeded)return 0;let t=e-this._arrowSize,n=this._scrollPosition;return t{Object.defineProperty(t,"__esModule",{value:!0}),t.ScrollbarVisibilityController=void 0;let r=n(1758),i=n(7150),a=n(9881);class o extends i.Disposable{constructor(e,t,n){super(),this._visibility=e,this._visibleClassName=t,this._invisibleClassName=n,this._domNode=null,this._isVisible=!1,this._isNeeded=!1,this._rawShouldBeVisible=!1,this._shouldBeVisible=!1,this._revealTimer=this._register(new r.TimeoutTimer)}setVisibility(e){this._visibility!==e&&(this._visibility=e,this._updateShouldBeVisible())}setShouldBeVisible(e){this._rawShouldBeVisible=e,this._updateShouldBeVisible()}_applyVisibilitySetting(){return this._visibility!==a.ScrollbarVisibility.Hidden&&(this._visibility===a.ScrollbarVisibility.Visible||this._rawShouldBeVisible)}_updateShouldBeVisible(){let e=this._applyVisibilitySetting();this._shouldBeVisible!==e&&(this._shouldBeVisible=e,this.ensureVisibility())}setIsNeeded(e){this._isNeeded!==e&&(this._isNeeded=e,this.ensureVisibility())}setDomNode(e){this._domNode=e,this._domNode.setClassName(this._invisibleClassName),this.setShouldBeVisible(!1)}ensureVisibility(){this._isNeeded?this._shouldBeVisible?this._reveal():this._hide(!0):this._hide(!1)}_reveal(){this._isVisible||(this._isVisible=!0,this._revealTimer.setIfNotSet((()=>{this._domNode?.setClassName(this._visibleClassName)}),0))}_hide(e){this._revealTimer.cancel(),this._isVisible&&(this._isVisible=!1,this._domNode?.setClassName(this._invisibleClassName+(e?` fade`:``)))}}t.ScrollbarVisibilityController=o},5473:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.VerticalScrollbar=void 0;let r=n(8801),i=n(8245),a=n(9881);class o extends r.AbstractScrollbar{constructor(e,t,n){let r=e.getScrollDimensions(),o=e.getCurrentScrollPosition();if(super({lazyRender:t.lazyRender,host:n,scrollbarState:new i.ScrollbarState(t.verticalHasArrows?t.arrowSize:0,t.vertical===a.ScrollbarVisibility.Hidden?0:t.verticalScrollbarSize,0,r.height,r.scrollHeight,o.scrollTop),visibility:t.vertical,extraScrollbarClassName:`vertical`,scrollable:e,scrollByPage:t.scrollByPage}),t.verticalHasArrows)throw Error(`horizontalHasArrows is not supported in xterm.js`);this._createSlider(0,Math.floor((t.verticalScrollbarSize-t.verticalSliderSize)/2),t.verticalSliderSize,void 0)}_updateSlider(e,t){this.slider.setHeight(e),this.slider.setTop(t)}_renderDomNode(e,t){this.domNode.setWidth(t),this.domNode.setHeight(e),this.domNode.setRight(0),this.domNode.setTop(0)}onDidScroll(e){return this._shouldRender=this._onElementScrollSize(e.scrollHeight)||this._shouldRender,this._shouldRender=this._onElementScrollPosition(e.scrollTop)||this._shouldRender,this._shouldRender=this._onElementSize(e.height)||this._shouldRender,this._shouldRender}_pointerDownRelativePosition(e,t){return t}_sliderPointerPosition(e){return e.pageY}_sliderOrthogonalPointerPosition(e){return e.pageX}_updateScrollbarSize(e){this.slider.setWidth(e)}writeScrollPosition(e,t){e.scrollTop=t}updateOptions(e){this.updateScrollbarSize(e.vertical===a.ScrollbarVisibility.Hidden?0:e.verticalScrollbarSize),this._scrollbarState.setOppositeScrollbarSize(0),this._visibilityController.setVisibility(e.vertical),this._scrollByPage=e.scrollByPage}}t.VerticalScrollbar=o},8286:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.Widget=void 0;let o=a(n(7093)),s=n(5394),c=n(5964),l=n(8594),u=n(7150);class d extends u.Disposable{onclick(e,t){this._register(o.addDisposableListener(e,o.EventType.CLICK,(n=>t(new c.StandardMouseEvent(o.getWindow(e),n)))))}onmousedown(e,t){this._register(o.addDisposableListener(e,o.EventType.MOUSE_DOWN,(n=>t(new c.StandardMouseEvent(o.getWindow(e),n)))))}onmouseover(e,t){this._register(o.addDisposableListener(e,o.EventType.MOUSE_OVER,(n=>t(new c.StandardMouseEvent(o.getWindow(e),n)))))}onmouseleave(e,t){this._register(o.addDisposableListener(e,o.EventType.MOUSE_LEAVE,(n=>t(new c.StandardMouseEvent(o.getWindow(e),n)))))}onkeydown(e,t){this._register(o.addDisposableListener(e,o.EventType.KEY_DOWN,(e=>t(new s.StandardKeyboardEvent(e)))))}onkeyup(e,t){this._register(o.addDisposableListener(e,o.EventType.KEY_UP,(e=>t(new s.StandardKeyboardEvent(e)))))}oninput(e,t){this._register(o.addDisposableListener(e,o.EventType.INPUT,t))}onblur(e,t){this._register(o.addDisposableListener(e,o.EventType.BLUR,t))}onfocus(e,t){this._register(o.addDisposableListener(e,o.EventType.FOCUS,t))}onchange(e,t){this._register(o.addDisposableListener(e,o.EventType.CHANGE,t))}ignoreGesture(e){return l.Gesture.ignoreTarget(e)}}t.Widget=d},4693:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.mainWindow=void 0,t.ensureCodeWindow=function(e,t){},t.mainWindow=typeof window==`object`?window:globalThis},3058:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Permutation=t.CallbackIterable=t.ArrayQueue=t.booleanComparator=t.numberComparator=t.CompareResult=void 0,t.tail=function(e,t=0){return e[e.length-(1+t)]},t.tail2=function(e){if(e.length===0)throw Error(`Invalid tail call`);return[e.slice(0,e.length-1),e[e.length-1]]},t.equals=function(e,t,n=(e,t)=>e===t){if(e===t)return!0;if(!e||!t||e.length!==t.length)return!1;for(let r=0,i=e.length;rn(e[r],t)))},t.binarySearch2=a,t.quickSelect=function e(t,n,r){if((t|=0)>=n.length)throw TypeError(`invalid index`);let i=n[Math.floor(n.length*Math.random())],a=[],o=[],s=[];for(let e of n){let t=r(e,i);t<0?a.push(e):t>0?o.push(e):s.push(e)}return t{(async()=>{let o=e.length,c=e.slice(0,n).sort(t);for(let l=n,u=Math.min(n+i,o);ln&&await new Promise((e=>setTimeout(e))),a&&a.isCancellationRequested)throw new r.CancellationError;s(e,t,c,l,u)}return c})().then(o,c)}))},t.coalesce=function(e){return e.filter((e=>!!e))},t.coalesceInPlace=function(e){let t=0;for(let n=0;n0},t.distinct=function(e,t=e=>e){let n=/* @__PURE__ */ new Set;return e.filter((e=>{let r=t(e);return!n.has(r)&&(n.add(r),!0)}))},t.uniqueFilter=function(e){let t=/* @__PURE__ */ new Set;return n=>{let r=e(n);return!t.has(r)&&(t.add(r),!0)}},t.firstOrDefault=function(e,t){return e.length>0?e[0]:t},t.lastOrDefault=function(e,t){return e.length>0?e[e.length-1]:t},t.commonPrefixLength=function(e,t,n=(e,t)=>e===t){let r=0;for(let i=0,a=Math.min(e.length,t.length);it;e--)r.push(e);return r},t.index=function(e,t,n){return e.reduce(((e,r)=>(e[t(r)]=n?n(r):r,e)),Object.create(null))},t.insert=function(e,t){return e.push(t),()=>c(e,t)},t.remove=c,t.arrayInsert=function(e,t,n){let r=e.slice(0,t),i=e.slice(t);return r.concat(n,i)},t.shuffle=function(e,t){let n;if(typeof t==`number`){let e=t;n=()=>{let t=179426549*Math.sin(e++);return t-Math.floor(t)}}else n=Math.random;for(let t=e.length-1;t>0;--t){let r=Math.floor(n()*(t+1)),i=e[t];e[t]=e[r],e[r]=i}},t.pushToStart=function(e,t){let n=e.indexOf(t);n>-1&&(e.splice(n,1),e.unshift(t))},t.pushToEnd=function(e,t){let n=e.indexOf(t);n>-1&&(e.splice(n,1),e.push(t))},t.pushMany=function(e,t){for(let n of t)e.push(n)},t.mapArrayOrNot=function(e,t){return Array.isArray(e)?e.map(t):t(e)},t.asArray=function(e){return Array.isArray(e)?e:[e]},t.getRandomElement=function(e){return e[Math.floor(Math.random()*e.length)]},t.insertInto=l,t.splice=function(e,t,n,r){let i=u(e,t),a=e.splice(i,n);return a===void 0&&(a=[]),l(e,i,r),a},t.compareBy=function(e,t){return(n,r)=>t(e(n),e(r))},t.tieBreakComparators=function(...e){return(t,n)=>{for(let r of e){let e=r(t,n);if(!d.isNeitherLessOrGreaterThan(e))return e}return d.neitherLessOrGreaterThan}},t.reverseOrder=function(e){return(t,n)=>-e(t,n)};let r=n(9807),i=n(8297);function a(e,t){let n=0,r=e-1;for(;n<=r;){let e=(n+r)/2|0,i=t(e);if(i<0)n=e+1;else{if(!(i>0))return e;r=e-1}}return-(n+1)}function o(e,t,n){let r=[];function i(e,t,n){if(t===0&&n.length===0)return;let i=r[r.length-1];i&&i.start+i.deleteCount===e?(i.deleteCount+=t,i.toInsert.push(...n)):r.push({start:e,deleteCount:t,toInsert:n})}let a=0,o=0;for(;;){if(a===e.length){i(a,0,t.slice(o));break}if(o===t.length){i(a,e.length-a,[]);break}let r=e[a],s=t[o],c=n(r,s);c===0?(a+=1,o+=1):c<0?(i(a,1,[]),a+=1):c>0&&(i(a,0,[s]),o+=1)}return r}function s(e,t,n,r,a){for(let o=n.length;rt(a,e)<0));n.splice(e,0,a)}}}function c(e,t){let n=e.indexOf(t);if(n>-1)return e.splice(n,1),t}function l(e,t,n){let r=u(e,t),i=e.length,a=n.length;e.length=i+a;for(let t=i-1;t>=r;t--)e[t+a]=e[t];for(let t=0;t0},e.isNeitherLessOrGreaterThan=function(e){return e===0},e.greaterThan=1,e.lessThan=-1,e.neitherLessOrGreaterThan=0})(d||(t.CompareResult=d={})),t.numberComparator=(e,t)=>e-t,t.booleanComparator=(e,n)=>(0,t.numberComparator)(+!!e,+!!n),t.ArrayQueue=class{constructor(e){this.items=e,this.firstIdx=0,this.lastIdx=this.items.length-1}get length(){return this.lastIdx-this.firstIdx+1}takeWhile(e){let t=this.firstIdx;for(;t=0&&e(this.items[t]);)t--;let n=t===this.lastIdx?null:this.items.slice(t+1,this.lastIdx+1);return this.lastIdx=t,n}peek(){if(this.length!==0)return this.items[this.firstIdx]}peekLast(){if(this.length!==0)return this.items[this.lastIdx]}dequeue(){let e=this.items[this.firstIdx];return this.firstIdx++,e}removeLast(){let e=this.items[this.lastIdx];return this.lastIdx--,e}takeCount(e){let t=this.items.slice(this.firstIdx,this.firstIdx+e);return this.firstIdx+=e,t}};class f{static{this.empty=new f((e=>{}))}constructor(e){this.iterate=e}forEach(e){this.iterate((t=>(e(t),!0)))}toArray(){let e=[];return this.iterate((t=>(e.push(t),!0))),e}filter(e){return new f((t=>this.iterate((n=>!e(n)||t(n)))))}map(e){return new f((t=>this.iterate((n=>t(e(n))))))}some(e){let t=!1;return this.iterate((n=>(t=e(n),!t))),t}findFirst(e){let t;return this.iterate((n=>!e(n)||(t=n,!1))),t}findLast(e){let t;return this.iterate((n=>(e(n)&&(t=n),!0))),t}findLastMaxBy(e){let t,n=!0;return this.iterate((r=>((n||d.isGreaterThan(e(r,t)))&&(n=!1,t=r),!0))),t}}t.CallbackIterable=f;class p{constructor(e){this._indexMap=e}static createSortPermutation(e,t){let n=Array.from(e.keys()).sort(((n,r)=>t(e[n],e[r])));return new p(n)}apply(e){return e.map(((t,n)=>e[this._indexMap[n]]))}inverse(){let e=this._indexMap.slice();for(let t=0;t{function n(e,t,n=e.length-1){for(let r=n;r>=0;r--)if(t(e[r]))return r;return-1}function r(e,t,n=0,r=e.length){let i=n,a=r;for(;i=0&&(n=i)}return n},t.findFirstMin=function(e,t){return o(e,((e,n)=>-t(e,n)))},t.findMaxIdx=function(e,t){if(e.length===0)return-1;let n=0;for(let r=1;r0&&(n=r);return n},t.mapFindFirst=function(e,t){for(let n of e){let e=t(n);if(e!==void 0)return e}};class a{static{this.assertInvariants=!1}constructor(e){this._array=e,this._findLastMonotonousLastIdx=0}findLastMonotonous(e){if(a.assertInvariants){if(this._prevFindLastPredicate){for(let t of this._array)if(this._prevFindLastPredicate(t)&&!e(t))throw Error(`MonotonousArray: current predicate must be weaker than (or equal to) the previous predicate.`)}this._prevFindLastPredicate=e}let t=r(this._array,e,this._findLastMonotonousLastIdx);return this._findLastMonotonousLastIdx=t+1,t===-1?void 0:this._array[t]}}function o(e,t){if(e.length===0)return;let n=e[0];for(let r=1;r0&&(n=i)}return n}t.MonotonousArray=a},1758:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.AsyncIterableSource=t.CancelableAsyncIterableObject=t.AsyncIterableObject=t.LazyStatefulPromise=t.StatefulPromise=t.Promises=t.DeferredPromise=t.IntervalCounter=t.TaskSequentializer=t.GlobalIdleValue=t.AbstractIdleValue=t._runWhenIdle=t.runWhenGlobalIdle=t.ThrottledWorker=t.RunOnceWorker=t.ProcessTimeRunOnceScheduler=t.RunOnceScheduler=t.IntervalTimer=t.TimeoutTimer=t.LimitedQueue=t.Queue=t.Limiter=t.AutoOpenBarrier=t.Barrier=t.ThrottledDelayer=t.Delayer=t.SequencerByKey=t.Sequencer=t.Throttler=void 0,t.isThenable=u,t.createCancelablePromise=d,t.raceCancellation=function(e,t,n){return new Promise(((r,i)=>{let a=t.onCancellationRequested((()=>{a.dispose(),r(n)}));e.then(r,i).finally((()=>a.dispose()))}))},t.raceCancellationError=function(e,t){return new Promise(((n,r)=>{let a=t.onCancellationRequested((()=>{a.dispose(),r(new i.CancellationError)}));e.then(n,r).finally((()=>a.dispose()))}))},t.raceCancellablePromises=async function(e){let t=-1,n=e.map(((e,n)=>e.then((e=>(t=n,e)))));try{return await Promise.race(n)}finally{e.forEach(((e,n)=>{n!==t&&e.cancel()}))}},t.raceTimeout=function(e,t,n){let r,i=setTimeout((()=>{r?.(void 0),n?.()}),t);return Promise.race([e.finally((()=>clearTimeout(i))),new Promise((e=>r=e))])},t.asPromise=function(e){return new Promise(((t,n)=>{let r=e();u(r)?r.then(t,n):t(r)}))},t.promiseWithResolvers=f,t.timeout=g,t.disposableTimeout=function(e,t=0,n){let r=setTimeout((()=>{e(),n&&i.dispose()}),t),i=(0,o.toDisposable)((()=>{clearTimeout(r),n?.deleteAndLeak(i)}));return n?.add(i),i},t.sequence=function(e){let t=[],n=0,r=e.length;return Promise.resolve(null).then((function i(a){a!=null&&t.push(a);let o=n!!e,n=null){let r=0,i=e.length,a=()=>{if(r>=i)return Promise.resolve(n);let o=e[r++];return Promise.resolve(o()).then((e=>t(e)?Promise.resolve(e):a()))};return a()},t.firstParallel=function(e,t=e=>!!e,n=null){if(e.length===0)return Promise.resolve(n);let r=e.length,i=()=>{r=-1;for(let t of e)t.cancel?.()};return new Promise(((a,o)=>{for(let s of e)s.then((e=>{--r>=0&&t(e)?(i(),a(e)):r===0&&a(n)})).catch((e=>{--r>=0&&(i(),o(e))}))}))},t.retry=async function(e,t,n){let r;for(let i=0;i{let r=t.token.onCancellationRequested((()=>{r.dispose(),t.dispose(),e.reject(new i.CancellationError)}));try{for await(let r of n){if(t.token.isCancellationRequested)return;e.emitOne(r)}r.dispose(),t.dispose()}catch(n){r.dispose(),t.dispose(),e.reject(n)}}))};let r=n(8447),i=n(9807),a=n(802),o=n(7150),s=n(8163),c=n(5015),l=n(626);function u(e){return!!e&&typeof e.then==`function`}function d(e){let t=new r.CancellationTokenSource,n=e(t.token),a=new Promise(((e,r)=>{let a=t.token.onCancellationRequested((()=>{a.dispose(),r(new i.CancellationError)}));Promise.resolve(n).then((n=>{a.dispose(),t.dispose(),e(n)}),(e=>{a.dispose(),t.dispose(),r(e)}))}));return new class{cancel(){t.cancel(),t.dispose()}then(e,t){return a.then(e,t)}catch(e){return this.then(void 0,e)}finally(e){return a.finally(e)}}}function f(){let e,t;return{promise:new Promise(((n,r)=>{e=n,t=r})),resolve:e,reject:t}}class p{constructor(){this.isDisposed=!1,this.activePromise=null,this.queuedPromise=null,this.queuedPromiseFactory=null}queue(e){if(this.isDisposed)return Promise.reject(/* @__PURE__ */ Error(`Throttler is disposed`));if(this.activePromise){if(this.queuedPromiseFactory=e,!this.queuedPromise){let e=()=>{if(this.queuedPromise=null,this.isDisposed)return;let e=this.queue(this.queuedPromiseFactory);return this.queuedPromiseFactory=null,e};this.queuedPromise=new Promise((t=>{this.activePromise.then(e,e).then(t)}))}return new Promise(((e,t)=>{this.queuedPromise.then(e,t)}))}return this.activePromise=e(),new Promise(((e,t)=>{this.activePromise.then((t=>{this.activePromise=null,e(t)}),(e=>{this.activePromise=null,t(e)}))}))}dispose(){this.isDisposed=!0}}t.Throttler=p,t.Sequencer=class{constructor(){this.current=Promise.resolve(null)}queue(e){return this.current=this.current.then((()=>e()),(()=>e()))}},t.SequencerByKey=class{constructor(){this.promiseMap=/* @__PURE__ */ new Map}queue(e,t){let n=(this.promiseMap.get(e)??Promise.resolve()).catch((()=>{})).then(t).finally((()=>{this.promiseMap.get(e)===n&&this.promiseMap.delete(e)}));return this.promiseMap.set(e,n),n}};class m{constructor(e){this.defaultDelay=e,this.deferred=null,this.completionPromise=null,this.doResolve=null,this.doReject=null,this.task=null}trigger(e,t=this.defaultDelay){this.task=e,this.cancelTimeout(),this.completionPromise||=new Promise(((e,t)=>{this.doResolve=e,this.doReject=t})).then((()=>{if(this.completionPromise=null,this.doResolve=null,this.task){let e=this.task;return this.task=null,e()}}));let n=()=>{this.deferred=null,this.doResolve?.(null)};return this.deferred=t===c.MicrotaskDelay?(e=>{let t=!0;return queueMicrotask((()=>{t&&(t=!1,e())})),{isTriggered:()=>t,dispose:()=>{t=!1}}})(n):((e,t)=>{let n=!0,r=setTimeout((()=>{n=!1,t()}),e);return{isTriggered:()=>n,dispose:()=>{clearTimeout(r),n=!1}}})(t,n),this.completionPromise}isTriggered(){return!!this.deferred?.isTriggered()}cancel(){this.cancelTimeout(),this.completionPromise&&=(this.doReject?.(new i.CancellationError),null)}cancelTimeout(){this.deferred?.dispose(),this.deferred=null}dispose(){this.cancel()}}t.Delayer=m,t.ThrottledDelayer=class{constructor(e){this.delayer=new m(e),this.throttler=new p}trigger(e,t){return this.delayer.trigger((()=>this.throttler.queue(e)),t)}isTriggered(){return this.delayer.isTriggered()}cancel(){this.delayer.cancel()}dispose(){this.delayer.dispose(),this.throttler.dispose()}};class h{constructor(){this._isOpen=!1,this._promise=new Promise(((e,t)=>{this._completePromise=e}))}isOpen(){return this._isOpen}open(){this._isOpen=!0,this._completePromise(!0)}wait(){return this._promise}}function g(e,t){return t?new Promise(((n,r)=>{let a=setTimeout((()=>{o.dispose(),n()}),e),o=t.onCancellationRequested((()=>{clearTimeout(a),o.dispose(),r(new i.CancellationError)}))})):d((t=>g(e,t)))}t.Barrier=h,t.AutoOpenBarrier=class extends h{constructor(e){super(),this._timeout=setTimeout((()=>this.open()),e)}open(){clearTimeout(this._timeout),super.open()}};class _{constructor(e){this._size=0,this._isDisposed=!1,this.maxDegreeOfParalellism=e,this.outstandingPromises=[],this.runningPromises=0,this._onDrained=new a.Emitter}whenIdle(){return this.size>0?a.Event.toPromise(this.onDrained):Promise.resolve()}get onDrained(){return this._onDrained.event}get size(){return this._size}queue(e){if(this._isDisposed)throw Error(`Object has been disposed`);return this._size++,new Promise(((t,n)=>{this.outstandingPromises.push({factory:e,c:t,e:n}),this.consume()}))}consume(){for(;this.outstandingPromises.length&&this.runningPromisesthis.consumed()),(()=>this.consumed()))}}consumed(){this._isDisposed||(this.runningPromises--,--this._size==0&&this._onDrained.fire(),this.outstandingPromises.length>0&&this.consume())}clear(){if(this._isDisposed)throw Error(`Object has been disposed`);this.outstandingPromises.length=0,this._size=this.runningPromises}dispose(){this._isDisposed=!0,this.outstandingPromises.length=0,this._size=0,this._onDrained.dispose()}}t.Limiter=_,t.Queue=class extends _{constructor(){super(1)}},t.LimitedQueue=class{constructor(){this.sequentializer=new x,this.tasks=0}queue(e){return this.sequentializer.isRunning()?this.sequentializer.queue((()=>this.sequentializer.run(this.tasks++,e()))):this.sequentializer.run(this.tasks++,e())}},t.TimeoutTimer=class{constructor(e,t){this._isDisposed=!1,this._token=-1,typeof e==`function`&&typeof t==`number`&&this.setIfNotSet(e,t)}dispose(){this.cancel(),this._isDisposed=!0}cancel(){this._token!==-1&&(clearTimeout(this._token),this._token=-1)}cancelAndSet(e,t){if(this._isDisposed)throw new i.BugIndicatingError(`Calling 'cancelAndSet' on a disposed TimeoutTimer`);this.cancel(),this._token=setTimeout((()=>{this._token=-1,e()}),t)}setIfNotSet(e,t){if(this._isDisposed)throw new i.BugIndicatingError(`Calling 'setIfNotSet' on a disposed TimeoutTimer`);this._token===-1&&(this._token=setTimeout((()=>{this._token=-1,e()}),t))}},t.IntervalTimer=class{constructor(){this.disposable=void 0,this.isDisposed=!1}cancel(){this.disposable?.dispose(),this.disposable=void 0}cancelAndSet(e,t,n=globalThis){if(this.isDisposed)throw new i.BugIndicatingError(`Calling 'cancelAndSet' on a disposed IntervalTimer`);this.cancel();let r=n.setInterval((()=>{e()}),t);this.disposable=(0,o.toDisposable)((()=>{n.clearInterval(r),this.disposable=void 0}))}dispose(){this.cancel(),this.isDisposed=!0}};class v{constructor(e,t){this.timeoutToken=-1,this.runner=e,this.timeout=t,this.timeoutHandler=this.onTimeout.bind(this)}dispose(){this.cancel(),this.runner=null}cancel(){this.isScheduled()&&(clearTimeout(this.timeoutToken),this.timeoutToken=-1)}schedule(e=this.timeout){this.cancel(),this.timeoutToken=setTimeout(this.timeoutHandler,e)}get delay(){return this.timeout}set delay(e){this.timeout=e}isScheduled(){return this.timeoutToken!==-1}flush(){this.isScheduled()&&(this.cancel(),this.doRun())}onTimeout(){this.timeoutToken=-1,this.runner&&this.doRun()}doRun(){this.runner?.()}}t.RunOnceScheduler=v,t.ProcessTimeRunOnceScheduler=class{constructor(e,t){t%1e3!=0&&console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${t}ms is not a multiple of 1000ms.`),this.runner=e,this.timeout=t,this.counter=0,this.intervalToken=-1,this.intervalHandler=this.onInterval.bind(this)}dispose(){this.cancel(),this.runner=null}cancel(){this.isScheduled()&&(clearInterval(this.intervalToken),this.intervalToken=-1)}schedule(e=this.timeout){e%1e3!=0&&console.warn(`ProcessTimeRunOnceScheduler resolution is 1s, ${e}ms is not a multiple of 1000ms.`),this.cancel(),this.counter=Math.ceil(e/1e3),this.intervalToken=setInterval(this.intervalHandler,1e3)}isScheduled(){return this.intervalToken!==-1}onInterval(){this.counter--,this.counter>0||(clearInterval(this.intervalToken),this.intervalToken=-1,this.runner?.())}},t.RunOnceWorker=class extends v{constructor(e,t){super(e,t),this.units=[]}work(e){this.units.push(e),this.isScheduled()||this.schedule()}doRun(){let e=this.units;this.units=[],this.runner?.(e)}dispose(){this.units=[],super.dispose()}};class y extends o.Disposable{constructor(e,t){super(),this.options=e,this.handler=t,this.pendingWork=[],this.throttler=this._register(new o.MutableDisposable),this.disposed=!1}get pending(){return this.pendingWork.length}work(e){if(this.disposed)return!1;if(typeof this.options.maxBufferedWork==`number`){if(this.throttler.value){if(this.pending+e.length>this.options.maxBufferedWork)return!1}else if(this.pending+e.length-this.options.maxWorkChunkSize>this.options.maxBufferedWork)return!1}for(let t of e)this.pendingWork.push(t);return this.throttler.value||this.doWork(),!0}doWork(){this.handler(this.pendingWork.splice(0,this.options.maxWorkChunkSize)),this.pendingWork.length>0&&(this.throttler.value=new v((()=>{this.throttler.clear(),this.doWork()}),this.options.throttleDelay),this.throttler.value.schedule())}dispose(){super.dispose(),this.disposed=!0}}t.ThrottledWorker=y,t._runWhenIdle=typeof globalThis.requestIdleCallback!=`function`||typeof globalThis.cancelIdleCallback!=`function`?(e,t)=>{(0,s.setTimeout0)((()=>{if(n)return;let e=Date.now()+15;t(Object.freeze({didTimeout:!0,timeRemaining:()=>Math.max(0,e-Date.now())}))}));let n=!1;return{dispose(){n||=!0}}}:(e,t,n)=>{let r=e.requestIdleCallback(t,typeof n==`number`?{timeout:n}:void 0),i=!1;return{dispose(){i||(i=!0,e.cancelIdleCallback(r))}}},t.runWhenGlobalIdle=e=>(0,t._runWhenIdle)(globalThis,e);class b{constructor(e,n){this._didRun=!1,this._executor=()=>{try{this._value=n()}catch(e){this._error=e}finally{this._didRun=!0}},this._handle=(0,t._runWhenIdle)(e,(()=>this._executor()))}dispose(){this._handle.dispose()}get value(){if(this._didRun||(this._handle.dispose(),this._executor()),this._error)throw this._error;return this._value}get isInitialized(){return this._didRun}}t.AbstractIdleValue=b,t.GlobalIdleValue=class extends b{constructor(e){super(globalThis,e)}};class x{isRunning(e){return typeof e==`number`?this._running?.taskId===e:!!this._running}get running(){return this._running?.promise}cancelRunning(){this._running?.cancel()}run(e,t,n){return this._running={taskId:e,cancel:()=>n?.(),promise:t},t.then((()=>this.doneRunning(e)),(()=>this.doneRunning(e))),t}doneRunning(e){this._running&&e===this._running.taskId&&(this._running=void 0,this.runQueued())}runQueued(){if(this._queued){let e=this._queued;this._queued=void 0,e.run().then(e.promiseResolve,e.promiseReject)}}queue(e){if(this._queued)this._queued.run=e;else{let{promise:t,resolve:n,reject:r}=f();this._queued={run:e,promise:t,promiseResolve:n,promiseReject:r}}return this._queued.promise}hasQueued(){return!!this._queued}async join(){return this._queued?.promise??this._running?.promise}}var S,C,w;t.TaskSequentializer=x,t.IntervalCounter=class{constructor(e,t=()=>Date.now()){this.interval=e,this.nowFn=t,this.lastIncrementTime=0,this.value=0}increment(){let e=this.nowFn();return e-this.lastIncrementTime>this.interval&&(this.lastIncrementTime=e,this.value=0),this.value++,this.value}},function(e){e[e.Resolved=0]=`Resolved`,e[e.Rejected=1]=`Rejected`}(S||={});class T{get isRejected(){return this.outcome?.outcome===S.Rejected}get isResolved(){return this.outcome?.outcome===S.Resolved}get isSettled(){return!!this.outcome}get value(){return this.outcome?.outcome===S.Resolved?this.outcome?.value:void 0}constructor(){this.p=new Promise(((e,t)=>{this.completeCallback=e,this.errorCallback=t}))}complete(e){return new Promise((t=>{this.completeCallback(e),this.outcome={outcome:S.Resolved,value:e},t()}))}error(e){return new Promise((t=>{this.errorCallback(e),this.outcome={outcome:S.Rejected,value:e},t()}))}cancel(){return this.error(new i.CancellationError)}}t.DeferredPromise=T,function(e){e.settled=async function(e){let t,n=await Promise.all(e.map((e=>e.then((e=>e),(e=>{t||=e})))));if(t!==void 0)throw t;return n},e.withAsyncBody=function(e){return new Promise((async(t,n)=>{try{await e(t,n)}catch(e){n(e)}}))}}(C||(t.Promises=C={}));class E{get value(){return this._value}get error(){return this._error}get isResolved(){return this._isResolved}constructor(e){this._value=void 0,this._error=void 0,this._isResolved=!1,this.promise=e.then((e=>(this._value=e,this._isResolved=!0,e)),(e=>{throw this._error=e,this._isResolved=!0,e}))}requireValue(){if(!this._isResolved)throw new i.BugIndicatingError(`Promise is not resolved yet`);if(this._error)throw this._error;return this._value}}t.StatefulPromise=E,t.LazyStatefulPromise=class{constructor(e){this._compute=e,this._promise=new l.Lazy((()=>new E(this._compute())))}requireValue(){return this._promise.value.requireValue()}getPromise(){return this._promise.value.promise}get currentValue(){return this._promise.rawValue?.value}},function(e){e[e.Initial=0]=`Initial`,e[e.DoneOK=1]=`DoneOK`,e[e.DoneError=2]=`DoneError`}(w||={});class D{static fromArray(e){return new D((t=>{t.emitMany(e)}))}static fromPromise(e){return new D((async t=>{t.emitMany(await e)}))}static fromPromises(e){return new D((async t=>{await Promise.all(e.map((async e=>t.emitOne(await e))))}))}static merge(e){return new D((async t=>{await Promise.all(e.map((async e=>{for await(let n of e)t.emitOne(n)})))}))}static{this.EMPTY=D.fromArray([])}constructor(e,t){this._state=w.Initial,this._results=[],this._error=null,this._onReturn=t,this._onStateChanged=new a.Emitter,queueMicrotask((async()=>{let t={emitOne:e=>this.emitOne(e),emitMany:e=>this.emitMany(e),reject:e=>this.reject(e)};try{await Promise.resolve(e(t)),this.resolve()}catch(e){this.reject(e)}finally{t.emitOne=void 0,t.emitMany=void 0,t.reject=void 0}}))}[Symbol.asyncIterator](){let e=0;return{next:async()=>{for(;;){if(this._state===w.DoneError)throw this._error;if(e(this._onReturn?.(),{done:!0,value:void 0})}}static map(e,t){return new D((async n=>{for await(let r of e)n.emitOne(t(r))}))}map(e){return D.map(this,e)}static filter(e,t){return new D((async n=>{for await(let r of e)t(r)&&n.emitOne(r)}))}filter(e){return D.filter(this,e)}static coalesce(e){return D.filter(e,(e=>!!e))}coalesce(){return D.coalesce(this)}static async toPromise(e){let t=[];for await(let n of e)t.push(n);return t}toPromise(){return D.toPromise(this)}emitOne(e){this._state===w.Initial&&(this._results.push(e),this._onStateChanged.fire())}emitMany(e){this._state===w.Initial&&(this._results=this._results.concat(e),this._onStateChanged.fire())}resolve(){this._state===w.Initial&&(this._state=w.DoneOK,this._onStateChanged.fire())}reject(e){this._state===w.Initial&&(this._state=w.DoneError,this._error=e,this._onStateChanged.fire())}}t.AsyncIterableObject=D;class O extends D{constructor(e,t){super(t),this._source=e}cancel(){this._source.cancel()}}t.CancelableAsyncIterableObject=O,t.AsyncIterableSource=class{constructor(e){let t,n;this._deferred=new T,this._asyncIterable=new D((e=>{if(!t)return n&&e.emitMany(n),this._errorFn=t=>e.reject(t),this._emitFn=t=>e.emitOne(t),this._deferred.p;e.reject(t)}),e),this._emitFn=e=>{n||=[],n.push(e)},this._errorFn=e=>{t||=e}}get asyncIterable(){return this._asyncIterable}resolve(){this._deferred.complete()}reject(e){this._errorFn(e),this._deferred.complete()}emitOne(e){this._emitFn(e)}}},8447:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CancellationTokenSource=t.CancellationToken=void 0,t.cancelOnDispose=function(e){let t=new s;return e.add({dispose(){t.cancel()}}),t.token};let r=n(802),i=Object.freeze((function(e,t){let n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}));var a;(function(e){e.isCancellationToken=function(t){return t===e.None||t===e.Cancelled||t instanceof o||!(!t||typeof t!=`object`)&&typeof t.isCancellationRequested==`boolean`&&typeof t.onCancellationRequested==`function`},e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:r.Event.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:i})})(a||(t.CancellationToken=a={}));class o{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?i:(this._emitter||=new r.Emitter,this._emitter.event)}dispose(){this._emitter&&=(this._emitter.dispose(),null)}}class s{constructor(e){this._token=void 0,this._parentListener=void 0,this._parentListener=e&&e.onCancellationRequested(this.cancel,this)}get token(){return this._token||=new o,this._token}cancel(){this._token?this._token instanceof o&&this._token.cancel():this._token=a.Cancelled}dispose(e=!1){e&&this.cancel(),this._parentListener?.dispose(),this._token?this._token instanceof o&&this._token.dispose():this._token=a.None}}t.CancellationTokenSource=s},4869:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.CharCode=void 0,function(e){e[e.Null=0]=`Null`,e[e.Backspace=8]=`Backspace`,e[e.Tab=9]=`Tab`,e[e.LineFeed=10]=`LineFeed`,e[e.CarriageReturn=13]=`CarriageReturn`,e[e.Space=32]=`Space`,e[e.ExclamationMark=33]=`ExclamationMark`,e[e.DoubleQuote=34]=`DoubleQuote`,e[e.Hash=35]=`Hash`,e[e.DollarSign=36]=`DollarSign`,e[e.PercentSign=37]=`PercentSign`,e[e.Ampersand=38]=`Ampersand`,e[e.SingleQuote=39]=`SingleQuote`,e[e.OpenParen=40]=`OpenParen`,e[e.CloseParen=41]=`CloseParen`,e[e.Asterisk=42]=`Asterisk`,e[e.Plus=43]=`Plus`,e[e.Comma=44]=`Comma`,e[e.Dash=45]=`Dash`,e[e.Period=46]=`Period`,e[e.Slash=47]=`Slash`,e[e.Digit0=48]=`Digit0`,e[e.Digit1=49]=`Digit1`,e[e.Digit2=50]=`Digit2`,e[e.Digit3=51]=`Digit3`,e[e.Digit4=52]=`Digit4`,e[e.Digit5=53]=`Digit5`,e[e.Digit6=54]=`Digit6`,e[e.Digit7=55]=`Digit7`,e[e.Digit8=56]=`Digit8`,e[e.Digit9=57]=`Digit9`,e[e.Colon=58]=`Colon`,e[e.Semicolon=59]=`Semicolon`,e[e.LessThan=60]=`LessThan`,e[e.Equals=61]=`Equals`,e[e.GreaterThan=62]=`GreaterThan`,e[e.QuestionMark=63]=`QuestionMark`,e[e.AtSign=64]=`AtSign`,e[e.A=65]=`A`,e[e.B=66]=`B`,e[e.C=67]=`C`,e[e.D=68]=`D`,e[e.E=69]=`E`,e[e.F=70]=`F`,e[e.G=71]=`G`,e[e.H=72]=`H`,e[e.I=73]=`I`,e[e.J=74]=`J`,e[e.K=75]=`K`,e[e.L=76]=`L`,e[e.M=77]=`M`,e[e.N=78]=`N`,e[e.O=79]=`O`,e[e.P=80]=`P`,e[e.Q=81]=`Q`,e[e.R=82]=`R`,e[e.S=83]=`S`,e[e.T=84]=`T`,e[e.U=85]=`U`,e[e.V=86]=`V`,e[e.W=87]=`W`,e[e.X=88]=`X`,e[e.Y=89]=`Y`,e[e.Z=90]=`Z`,e[e.OpenSquareBracket=91]=`OpenSquareBracket`,e[e.Backslash=92]=`Backslash`,e[e.CloseSquareBracket=93]=`CloseSquareBracket`,e[e.Caret=94]=`Caret`,e[e.Underline=95]=`Underline`,e[e.BackTick=96]=`BackTick`,e[e.a=97]=`a`,e[e.b=98]=`b`,e[e.c=99]=`c`,e[e.d=100]=`d`,e[e.e=101]=`e`,e[e.f=102]=`f`,e[e.g=103]=`g`,e[e.h=104]=`h`,e[e.i=105]=`i`,e[e.j=106]=`j`,e[e.k=107]=`k`,e[e.l=108]=`l`,e[e.m=109]=`m`,e[e.n=110]=`n`,e[e.o=111]=`o`,e[e.p=112]=`p`,e[e.q=113]=`q`,e[e.r=114]=`r`,e[e.s=115]=`s`,e[e.t=116]=`t`,e[e.u=117]=`u`,e[e.v=118]=`v`,e[e.w=119]=`w`,e[e.x=120]=`x`,e[e.y=121]=`y`,e[e.z=122]=`z`,e[e.OpenCurlyBrace=123]=`OpenCurlyBrace`,e[e.Pipe=124]=`Pipe`,e[e.CloseCurlyBrace=125]=`CloseCurlyBrace`,e[e.Tilde=126]=`Tilde`,e[e.NoBreakSpace=160]=`NoBreakSpace`,e[e.U_Combining_Grave_Accent=768]=`U_Combining_Grave_Accent`,e[e.U_Combining_Acute_Accent=769]=`U_Combining_Acute_Accent`,e[e.U_Combining_Circumflex_Accent=770]=`U_Combining_Circumflex_Accent`,e[e.U_Combining_Tilde=771]=`U_Combining_Tilde`,e[e.U_Combining_Macron=772]=`U_Combining_Macron`,e[e.U_Combining_Overline=773]=`U_Combining_Overline`,e[e.U_Combining_Breve=774]=`U_Combining_Breve`,e[e.U_Combining_Dot_Above=775]=`U_Combining_Dot_Above`,e[e.U_Combining_Diaeresis=776]=`U_Combining_Diaeresis`,e[e.U_Combining_Hook_Above=777]=`U_Combining_Hook_Above`,e[e.U_Combining_Ring_Above=778]=`U_Combining_Ring_Above`,e[e.U_Combining_Double_Acute_Accent=779]=`U_Combining_Double_Acute_Accent`,e[e.U_Combining_Caron=780]=`U_Combining_Caron`,e[e.U_Combining_Vertical_Line_Above=781]=`U_Combining_Vertical_Line_Above`,e[e.U_Combining_Double_Vertical_Line_Above=782]=`U_Combining_Double_Vertical_Line_Above`,e[e.U_Combining_Double_Grave_Accent=783]=`U_Combining_Double_Grave_Accent`,e[e.U_Combining_Candrabindu=784]=`U_Combining_Candrabindu`,e[e.U_Combining_Inverted_Breve=785]=`U_Combining_Inverted_Breve`,e[e.U_Combining_Turned_Comma_Above=786]=`U_Combining_Turned_Comma_Above`,e[e.U_Combining_Comma_Above=787]=`U_Combining_Comma_Above`,e[e.U_Combining_Reversed_Comma_Above=788]=`U_Combining_Reversed_Comma_Above`,e[e.U_Combining_Comma_Above_Right=789]=`U_Combining_Comma_Above_Right`,e[e.U_Combining_Grave_Accent_Below=790]=`U_Combining_Grave_Accent_Below`,e[e.U_Combining_Acute_Accent_Below=791]=`U_Combining_Acute_Accent_Below`,e[e.U_Combining_Left_Tack_Below=792]=`U_Combining_Left_Tack_Below`,e[e.U_Combining_Right_Tack_Below=793]=`U_Combining_Right_Tack_Below`,e[e.U_Combining_Left_Angle_Above=794]=`U_Combining_Left_Angle_Above`,e[e.U_Combining_Horn=795]=`U_Combining_Horn`,e[e.U_Combining_Left_Half_Ring_Below=796]=`U_Combining_Left_Half_Ring_Below`,e[e.U_Combining_Up_Tack_Below=797]=`U_Combining_Up_Tack_Below`,e[e.U_Combining_Down_Tack_Below=798]=`U_Combining_Down_Tack_Below`,e[e.U_Combining_Plus_Sign_Below=799]=`U_Combining_Plus_Sign_Below`,e[e.U_Combining_Minus_Sign_Below=800]=`U_Combining_Minus_Sign_Below`,e[e.U_Combining_Palatalized_Hook_Below=801]=`U_Combining_Palatalized_Hook_Below`,e[e.U_Combining_Retroflex_Hook_Below=802]=`U_Combining_Retroflex_Hook_Below`,e[e.U_Combining_Dot_Below=803]=`U_Combining_Dot_Below`,e[e.U_Combining_Diaeresis_Below=804]=`U_Combining_Diaeresis_Below`,e[e.U_Combining_Ring_Below=805]=`U_Combining_Ring_Below`,e[e.U_Combining_Comma_Below=806]=`U_Combining_Comma_Below`,e[e.U_Combining_Cedilla=807]=`U_Combining_Cedilla`,e[e.U_Combining_Ogonek=808]=`U_Combining_Ogonek`,e[e.U_Combining_Vertical_Line_Below=809]=`U_Combining_Vertical_Line_Below`,e[e.U_Combining_Bridge_Below=810]=`U_Combining_Bridge_Below`,e[e.U_Combining_Inverted_Double_Arch_Below=811]=`U_Combining_Inverted_Double_Arch_Below`,e[e.U_Combining_Caron_Below=812]=`U_Combining_Caron_Below`,e[e.U_Combining_Circumflex_Accent_Below=813]=`U_Combining_Circumflex_Accent_Below`,e[e.U_Combining_Breve_Below=814]=`U_Combining_Breve_Below`,e[e.U_Combining_Inverted_Breve_Below=815]=`U_Combining_Inverted_Breve_Below`,e[e.U_Combining_Tilde_Below=816]=`U_Combining_Tilde_Below`,e[e.U_Combining_Macron_Below=817]=`U_Combining_Macron_Below`,e[e.U_Combining_Low_Line=818]=`U_Combining_Low_Line`,e[e.U_Combining_Double_Low_Line=819]=`U_Combining_Double_Low_Line`,e[e.U_Combining_Tilde_Overlay=820]=`U_Combining_Tilde_Overlay`,e[e.U_Combining_Short_Stroke_Overlay=821]=`U_Combining_Short_Stroke_Overlay`,e[e.U_Combining_Long_Stroke_Overlay=822]=`U_Combining_Long_Stroke_Overlay`,e[e.U_Combining_Short_Solidus_Overlay=823]=`U_Combining_Short_Solidus_Overlay`,e[e.U_Combining_Long_Solidus_Overlay=824]=`U_Combining_Long_Solidus_Overlay`,e[e.U_Combining_Right_Half_Ring_Below=825]=`U_Combining_Right_Half_Ring_Below`,e[e.U_Combining_Inverted_Bridge_Below=826]=`U_Combining_Inverted_Bridge_Below`,e[e.U_Combining_Square_Below=827]=`U_Combining_Square_Below`,e[e.U_Combining_Seagull_Below=828]=`U_Combining_Seagull_Below`,e[e.U_Combining_X_Above=829]=`U_Combining_X_Above`,e[e.U_Combining_Vertical_Tilde=830]=`U_Combining_Vertical_Tilde`,e[e.U_Combining_Double_Overline=831]=`U_Combining_Double_Overline`,e[e.U_Combining_Grave_Tone_Mark=832]=`U_Combining_Grave_Tone_Mark`,e[e.U_Combining_Acute_Tone_Mark=833]=`U_Combining_Acute_Tone_Mark`,e[e.U_Combining_Greek_Perispomeni=834]=`U_Combining_Greek_Perispomeni`,e[e.U_Combining_Greek_Koronis=835]=`U_Combining_Greek_Koronis`,e[e.U_Combining_Greek_Dialytika_Tonos=836]=`U_Combining_Greek_Dialytika_Tonos`,e[e.U_Combining_Greek_Ypogegrammeni=837]=`U_Combining_Greek_Ypogegrammeni`,e[e.U_Combining_Bridge_Above=838]=`U_Combining_Bridge_Above`,e[e.U_Combining_Equals_Sign_Below=839]=`U_Combining_Equals_Sign_Below`,e[e.U_Combining_Double_Vertical_Line_Below=840]=`U_Combining_Double_Vertical_Line_Below`,e[e.U_Combining_Left_Angle_Below=841]=`U_Combining_Left_Angle_Below`,e[e.U_Combining_Not_Tilde_Above=842]=`U_Combining_Not_Tilde_Above`,e[e.U_Combining_Homothetic_Above=843]=`U_Combining_Homothetic_Above`,e[e.U_Combining_Almost_Equal_To_Above=844]=`U_Combining_Almost_Equal_To_Above`,e[e.U_Combining_Left_Right_Arrow_Below=845]=`U_Combining_Left_Right_Arrow_Below`,e[e.U_Combining_Upwards_Arrow_Below=846]=`U_Combining_Upwards_Arrow_Below`,e[e.U_Combining_Grapheme_Joiner=847]=`U_Combining_Grapheme_Joiner`,e[e.U_Combining_Right_Arrowhead_Above=848]=`U_Combining_Right_Arrowhead_Above`,e[e.U_Combining_Left_Half_Ring_Above=849]=`U_Combining_Left_Half_Ring_Above`,e[e.U_Combining_Fermata=850]=`U_Combining_Fermata`,e[e.U_Combining_X_Below=851]=`U_Combining_X_Below`,e[e.U_Combining_Left_Arrowhead_Below=852]=`U_Combining_Left_Arrowhead_Below`,e[e.U_Combining_Right_Arrowhead_Below=853]=`U_Combining_Right_Arrowhead_Below`,e[e.U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below=854]=`U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below`,e[e.U_Combining_Right_Half_Ring_Above=855]=`U_Combining_Right_Half_Ring_Above`,e[e.U_Combining_Dot_Above_Right=856]=`U_Combining_Dot_Above_Right`,e[e.U_Combining_Asterisk_Below=857]=`U_Combining_Asterisk_Below`,e[e.U_Combining_Double_Ring_Below=858]=`U_Combining_Double_Ring_Below`,e[e.U_Combining_Zigzag_Above=859]=`U_Combining_Zigzag_Above`,e[e.U_Combining_Double_Breve_Below=860]=`U_Combining_Double_Breve_Below`,e[e.U_Combining_Double_Breve=861]=`U_Combining_Double_Breve`,e[e.U_Combining_Double_Macron=862]=`U_Combining_Double_Macron`,e[e.U_Combining_Double_Macron_Below=863]=`U_Combining_Double_Macron_Below`,e[e.U_Combining_Double_Tilde=864]=`U_Combining_Double_Tilde`,e[e.U_Combining_Double_Inverted_Breve=865]=`U_Combining_Double_Inverted_Breve`,e[e.U_Combining_Double_Rightwards_Arrow_Below=866]=`U_Combining_Double_Rightwards_Arrow_Below`,e[e.U_Combining_Latin_Small_Letter_A=867]=`U_Combining_Latin_Small_Letter_A`,e[e.U_Combining_Latin_Small_Letter_E=868]=`U_Combining_Latin_Small_Letter_E`,e[e.U_Combining_Latin_Small_Letter_I=869]=`U_Combining_Latin_Small_Letter_I`,e[e.U_Combining_Latin_Small_Letter_O=870]=`U_Combining_Latin_Small_Letter_O`,e[e.U_Combining_Latin_Small_Letter_U=871]=`U_Combining_Latin_Small_Letter_U`,e[e.U_Combining_Latin_Small_Letter_C=872]=`U_Combining_Latin_Small_Letter_C`,e[e.U_Combining_Latin_Small_Letter_D=873]=`U_Combining_Latin_Small_Letter_D`,e[e.U_Combining_Latin_Small_Letter_H=874]=`U_Combining_Latin_Small_Letter_H`,e[e.U_Combining_Latin_Small_Letter_M=875]=`U_Combining_Latin_Small_Letter_M`,e[e.U_Combining_Latin_Small_Letter_R=876]=`U_Combining_Latin_Small_Letter_R`,e[e.U_Combining_Latin_Small_Letter_T=877]=`U_Combining_Latin_Small_Letter_T`,e[e.U_Combining_Latin_Small_Letter_V=878]=`U_Combining_Latin_Small_Letter_V`,e[e.U_Combining_Latin_Small_Letter_X=879]=`U_Combining_Latin_Small_Letter_X`,e[e.LINE_SEPARATOR=8232]=`LINE_SEPARATOR`,e[e.PARAGRAPH_SEPARATOR=8233]=`PARAGRAPH_SEPARATOR`,e[e.NEXT_LINE=133]=`NEXT_LINE`,e[e.U_CIRCUMFLEX=94]=`U_CIRCUMFLEX`,e[e.U_GRAVE_ACCENT=96]=`U_GRAVE_ACCENT`,e[e.U_DIAERESIS=168]=`U_DIAERESIS`,e[e.U_MACRON=175]=`U_MACRON`,e[e.U_ACUTE_ACCENT=180]=`U_ACUTE_ACCENT`,e[e.U_CEDILLA=184]=`U_CEDILLA`,e[e.U_MODIFIER_LETTER_LEFT_ARROWHEAD=706]=`U_MODIFIER_LETTER_LEFT_ARROWHEAD`,e[e.U_MODIFIER_LETTER_RIGHT_ARROWHEAD=707]=`U_MODIFIER_LETTER_RIGHT_ARROWHEAD`,e[e.U_MODIFIER_LETTER_UP_ARROWHEAD=708]=`U_MODIFIER_LETTER_UP_ARROWHEAD`,e[e.U_MODIFIER_LETTER_DOWN_ARROWHEAD=709]=`U_MODIFIER_LETTER_DOWN_ARROWHEAD`,e[e.U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING=722]=`U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING`,e[e.U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING=723]=`U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING`,e[e.U_MODIFIER_LETTER_UP_TACK=724]=`U_MODIFIER_LETTER_UP_TACK`,e[e.U_MODIFIER_LETTER_DOWN_TACK=725]=`U_MODIFIER_LETTER_DOWN_TACK`,e[e.U_MODIFIER_LETTER_PLUS_SIGN=726]=`U_MODIFIER_LETTER_PLUS_SIGN`,e[e.U_MODIFIER_LETTER_MINUS_SIGN=727]=`U_MODIFIER_LETTER_MINUS_SIGN`,e[e.U_BREVE=728]=`U_BREVE`,e[e.U_DOT_ABOVE=729]=`U_DOT_ABOVE`,e[e.U_RING_ABOVE=730]=`U_RING_ABOVE`,e[e.U_OGONEK=731]=`U_OGONEK`,e[e.U_SMALL_TILDE=732]=`U_SMALL_TILDE`,e[e.U_DOUBLE_ACUTE_ACCENT=733]=`U_DOUBLE_ACUTE_ACCENT`,e[e.U_MODIFIER_LETTER_RHOTIC_HOOK=734]=`U_MODIFIER_LETTER_RHOTIC_HOOK`,e[e.U_MODIFIER_LETTER_CROSS_ACCENT=735]=`U_MODIFIER_LETTER_CROSS_ACCENT`,e[e.U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR=741]=`U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR`,e[e.U_MODIFIER_LETTER_HIGH_TONE_BAR=742]=`U_MODIFIER_LETTER_HIGH_TONE_BAR`,e[e.U_MODIFIER_LETTER_MID_TONE_BAR=743]=`U_MODIFIER_LETTER_MID_TONE_BAR`,e[e.U_MODIFIER_LETTER_LOW_TONE_BAR=744]=`U_MODIFIER_LETTER_LOW_TONE_BAR`,e[e.U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR=745]=`U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR`,e[e.U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK=746]=`U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK`,e[e.U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK=747]=`U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK`,e[e.U_MODIFIER_LETTER_UNASPIRATED=749]=`U_MODIFIER_LETTER_UNASPIRATED`,e[e.U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD=751]=`U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD`,e[e.U_MODIFIER_LETTER_LOW_UP_ARROWHEAD=752]=`U_MODIFIER_LETTER_LOW_UP_ARROWHEAD`,e[e.U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD=753]=`U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD`,e[e.U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD=754]=`U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD`,e[e.U_MODIFIER_LETTER_LOW_RING=755]=`U_MODIFIER_LETTER_LOW_RING`,e[e.U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT=756]=`U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT`,e[e.U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT=757]=`U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT`,e[e.U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT=758]=`U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT`,e[e.U_MODIFIER_LETTER_LOW_TILDE=759]=`U_MODIFIER_LETTER_LOW_TILDE`,e[e.U_MODIFIER_LETTER_RAISED_COLON=760]=`U_MODIFIER_LETTER_RAISED_COLON`,e[e.U_MODIFIER_LETTER_BEGIN_HIGH_TONE=761]=`U_MODIFIER_LETTER_BEGIN_HIGH_TONE`,e[e.U_MODIFIER_LETTER_END_HIGH_TONE=762]=`U_MODIFIER_LETTER_END_HIGH_TONE`,e[e.U_MODIFIER_LETTER_BEGIN_LOW_TONE=763]=`U_MODIFIER_LETTER_BEGIN_LOW_TONE`,e[e.U_MODIFIER_LETTER_END_LOW_TONE=764]=`U_MODIFIER_LETTER_END_LOW_TONE`,e[e.U_MODIFIER_LETTER_SHELF=765]=`U_MODIFIER_LETTER_SHELF`,e[e.U_MODIFIER_LETTER_OPEN_SHELF=766]=`U_MODIFIER_LETTER_OPEN_SHELF`,e[e.U_MODIFIER_LETTER_LOW_LEFT_ARROW=767]=`U_MODIFIER_LETTER_LOW_LEFT_ARROW`,e[e.U_GREEK_LOWER_NUMERAL_SIGN=885]=`U_GREEK_LOWER_NUMERAL_SIGN`,e[e.U_GREEK_TONOS=900]=`U_GREEK_TONOS`,e[e.U_GREEK_DIALYTIKA_TONOS=901]=`U_GREEK_DIALYTIKA_TONOS`,e[e.U_GREEK_KORONIS=8125]=`U_GREEK_KORONIS`,e[e.U_GREEK_PSILI=8127]=`U_GREEK_PSILI`,e[e.U_GREEK_PERISPOMENI=8128]=`U_GREEK_PERISPOMENI`,e[e.U_GREEK_DIALYTIKA_AND_PERISPOMENI=8129]=`U_GREEK_DIALYTIKA_AND_PERISPOMENI`,e[e.U_GREEK_PSILI_AND_VARIA=8141]=`U_GREEK_PSILI_AND_VARIA`,e[e.U_GREEK_PSILI_AND_OXIA=8142]=`U_GREEK_PSILI_AND_OXIA`,e[e.U_GREEK_PSILI_AND_PERISPOMENI=8143]=`U_GREEK_PSILI_AND_PERISPOMENI`,e[e.U_GREEK_DASIA_AND_VARIA=8157]=`U_GREEK_DASIA_AND_VARIA`,e[e.U_GREEK_DASIA_AND_OXIA=8158]=`U_GREEK_DASIA_AND_OXIA`,e[e.U_GREEK_DASIA_AND_PERISPOMENI=8159]=`U_GREEK_DASIA_AND_PERISPOMENI`,e[e.U_GREEK_DIALYTIKA_AND_VARIA=8173]=`U_GREEK_DIALYTIKA_AND_VARIA`,e[e.U_GREEK_DIALYTIKA_AND_OXIA=8174]=`U_GREEK_DIALYTIKA_AND_OXIA`,e[e.U_GREEK_VARIA=8175]=`U_GREEK_VARIA`,e[e.U_GREEK_OXIA=8189]=`U_GREEK_OXIA`,e[e.U_GREEK_DASIA=8190]=`U_GREEK_DASIA`,e[e.U_IDEOGRAPHIC_FULL_STOP=12290]=`U_IDEOGRAPHIC_FULL_STOP`,e[e.U_LEFT_CORNER_BRACKET=12300]=`U_LEFT_CORNER_BRACKET`,e[e.U_RIGHT_CORNER_BRACKET=12301]=`U_RIGHT_CORNER_BRACKET`,e[e.U_LEFT_BLACK_LENTICULAR_BRACKET=12304]=`U_LEFT_BLACK_LENTICULAR_BRACKET`,e[e.U_RIGHT_BLACK_LENTICULAR_BRACKET=12305]=`U_RIGHT_BLACK_LENTICULAR_BRACKET`,e[e.U_OVERLINE=8254]=`U_OVERLINE`,e[e.UTF8_BOM=65279]=`UTF8_BOM`,e[e.U_FULLWIDTH_SEMICOLON=65307]=`U_FULLWIDTH_SEMICOLON`,e[e.U_FULLWIDTH_COMMA=65292]=`U_FULLWIDTH_COMMA`}(n||(t.CharCode=n={}))},9087:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SetWithKey=void 0,t.groupBy=function(e,t){let n=Object.create(null);for(let r of e){let e=t(r),i=n[e];i||=n[e]=[],i.push(r)}return n},t.diffSets=function(e,t){let n=[],r=[];for(let r of e)t.has(r)||n.push(r);for(let n of t)e.has(n)||r.push(n);return{removed:n,added:r}},t.diffMaps=function(e,t){let n=[],r=[];for(let[r,i]of e)t.has(r)||n.push(i);for(let[n,i]of t)e.has(n)||r.push(i);return{removed:n,added:r}},t.intersection=function(e,t){let n=/* @__PURE__ */ new Set;for(let r of t)e.has(r)&&n.add(r);return n};class r{static{n=Symbol.toStringTag}constructor(e,t){this.toKey=t,this._map=/* @__PURE__ */ new Map,this[n]=`SetWithKey`;for(let t of e)this.add(t)}get size(){return this._map.size}add(e){let t=this.toKey(e);return this._map.set(t,e),this}delete(e){return this._map.delete(this.toKey(e))}has(e){return this._map.has(this.toKey(e))}*entries(){for(let e of this._map.values())yield[e,e]}keys(){return this.values()}*values(){for(let e of this._map.values())yield e}clear(){this._map.clear()}forEach(e,t){this._map.forEach((n=>e.call(t,n,n,this)))}[Symbol.iterator](){return this.values()}}t.SetWithKey=r},4838:(e,t)=>{function n(e){return(t,n,r)=>{let i=null,a=null;if(typeof r.value==`function`?(i=`value`,a=r.value):typeof r.get==`function`&&(i=`get`,a=r.get),!a)throw Error(`not supported`);r[i]=e(a,n)}}Object.defineProperty(t,"__esModule",{value:!0}),t.memoize=function(e,t,n){let r=null,i=null;if(typeof n.value==`function`?(r=`value`,i=n.value,i.length!==0&&console.warn(`Memoize should only be used in functions with zero parameters`)):typeof n.get==`function`&&(r=`get`,i=n.get),!i)throw Error(`not supported`);let a=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(a)||Object.defineProperty(this,a,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[a]}},t.debounce=function(e,t,r){return n(((n,i)=>{let a=`$debounce$${i}`,o=`$debounce$result$${i}`;return function(...i){this[o]||(this[o]=r?r():void 0),clearTimeout(this[a]),t&&(this[o]=t(this[o],...i),i=[this[o]]),this[a]=setTimeout((()=>{n.apply(this,i),this[o]=r?r():void 0}),e)}}))},t.throttle=function(e,t,r){return n(((n,i)=>{let a=`$throttle$timer$${i}`,o=`$throttle$result$${i}`,s=`$throttle$lastRun$${i}`,c=`$throttle$pending$${i}`;return function(...i){if(this[o]||(this[o]=r?r():void 0),this[s]!==null&&this[s]!==void 0||(this[s]=-Number.MAX_VALUE),t&&(this[o]=t(this[o],...i)),this[c])return;let l=this[s]+e;l<=Date.now()?(this[s]=Date.now(),n.apply(this,[this[o]]),this[o]=r?r():void 0):(this[c]=!0,this[a]=setTimeout((()=>{this[c]=!1,this[s]=Date.now(),n.apply(this,[this[o]]),this[o]=r?r():void 0}),l-Date.now()))}}))}},9807:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.BugIndicatingError=t.ErrorNoTelemetry=t.ExpectedError=t.NotSupportedError=t.NotImplementedError=t.ReadonlyError=t.CancellationError=t.errorHandler=t.ErrorHandler=void 0,t.setUnexpectedErrorHandler=function(e){t.errorHandler.setUnexpectedErrorHandler(e)},t.isSigPipeError=function(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.code===`EPIPE`&&t.syscall?.toUpperCase()===`WRITE`},t.onUnexpectedError=function(e){i(e)||t.errorHandler.onUnexpectedError(e)},t.onUnexpectedExternalError=function(e){i(e)||t.errorHandler.onUnexpectedExternalError(e)},t.transformErrorForSerialization=function(e){if(e instanceof Error){let{name:t,message:n}=e;return{$isError:!0,name:t,message:n,stack:e.stacktrace||e.stack,noTelemetry:u.isErrorNoTelemetry(e)}}return e},t.transformErrorFromSerialization=function(e){let t;return e.noTelemetry?t=new u:(t=/* @__PURE__ */ Error(),t.name=e.name),t.message=e.message,t.stack=e.stack,t},t.isCancellationError=i,t.canceled=function(){let e=Error(r);return e.name=e.message,e},t.illegalArgument=function(e){return Error(e?`Illegal argument: ${e}`:`Illegal argument`)},t.illegalState=function(e){return Error(e?`Illegal state: ${e}`:`Illegal state`)},t.getErrorMessage=function(e){return e?e.message?e.message:e.stack?e.stack.split(` +`)[0]:String(e):`Error`};class n{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout((()=>{throw e.stack?u.isErrorNoTelemetry(e)?new u(e.message+` + +`+e.stack):Error(e.message+` + +`+e.stack):e}),0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach((t=>{t(e)}))}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}}t.ErrorHandler=n,t.errorHandler=new n;let r=`Canceled`;function i(e){return e instanceof a||e instanceof Error&&e.name===r&&e.message===r}class a extends Error{constructor(){super(r),this.name=this.message}}t.CancellationError=a;class o extends TypeError{constructor(e){super(e?`${e} is read-only and cannot be changed`:`Cannot change read-only property`)}}t.ReadonlyError=o;class s extends Error{constructor(e){super(`NotImplemented`),e&&(this.message=e)}}t.NotImplementedError=s;class c extends Error{constructor(e){super(`NotSupported`),e&&(this.message=e)}}t.NotSupportedError=c;class l extends Error{constructor(){super(...arguments),this.isExpected=!0}}t.ExpectedError=l;class u extends Error{constructor(e){super(e),this.name=`CodeExpectedError`}static fromError(e){if(e instanceof u)return e;let t=new u;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name===`CodeExpectedError`}}t.ErrorNoTelemetry=u;class d extends Error{constructor(e){super(e||`An unexpected bug occurred.`),Object.setPrototypeOf(this,d.prototype)}}t.BugIndicatingError=d},802:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ValueWithChangeEvent=t.Relay=t.EventBufferer=t.DynamicListEventMultiplexer=t.EventMultiplexer=t.MicrotaskEmitter=t.DebounceEmitter=t.PauseableEmitter=t.AsyncEmitter=t.createEventDeliveryQueue=t.Emitter=t.ListenerRefusalError=t.ListenerLeakError=t.EventProfiling=t.Event=void 0,t.setGlobalLeakWarningThreshold=function(e){let t=u;return u=e,{dispose(){u=t}}};let r=n(9807),i=n(8841),a=n(7150),o=n(6317),s=n(9725);var c;(function(e){function t(e){return(t,n=null,r)=>{let i,a=!1;return i=e((e=>{if(!a)return i?i.dispose():a=!0,t.call(n,e)}),null,r),a&&i.dispose(),i}}function n(e,t,n){return i(((n,r=null,i)=>e((e=>n.call(r,t(e))),null,i)),n)}function r(e,t,n){return i(((n,r=null,i)=>e((e=>t(e)&&n.call(r,e)),null,i)),n)}function i(e,t){let n,r=new _({onWillAddFirstListener(){n=e(r.fire,r)},onDidRemoveLastListener(){n?.dispose()}});return t?.add(r),r.event}function o(e,t,n=100,r=!1,i=!1,a,o){let s,c,l,u,d=0,f=new _({leakWarningThreshold:a,onWillAddFirstListener(){s=e((e=>{d++,c=t(c,e),r&&!l&&(f.fire(c),c=void 0),u=()=>{let e=c;c=void 0,l=void 0,(!r||d>1)&&f.fire(e),d=0},typeof n==`number`?(clearTimeout(l),l=setTimeout(u,n)):l===void 0&&(l=0,queueMicrotask(u))}))},onWillRemoveListener(){i&&d>0&&u?.()},onDidRemoveLastListener(){u=void 0,s.dispose()}});return o?.add(f),f.event}e.None=()=>a.Disposable.None,e.defer=function(e,t){return o(e,(()=>{}),0,void 0,!0,void 0,t)},e.once=t,e.map=n,e.forEach=function(e,t,n){return i(((n,r=null,i)=>e((e=>{t(e),n.call(r,e)}),null,i)),n)},e.filter=r,e.signal=function(e){return e},e.any=function(...e){return(t,n=null,r)=>{return i=(0,a.combinedDisposable)(...e.map((e=>e((e=>t.call(n,e)))))),(o=r)instanceof Array?o.push(i):o&&o.add(i),i;var i,o}},e.reduce=function(e,t,r,i){let a=r;return n(e,(e=>(a=t(a,e),a)),i)},e.debounce=o,e.accumulate=function(t,n=0,r){return e.debounce(t,((e,t)=>e?(e.push(t),e):[t]),n,void 0,!0,void 0,r)},e.latch=function(e,t=(e,t)=>e===t,n){let i,a=!0;return r(e,(e=>{let n=a||!t(e,i);return a=!1,i=e,n}),n)},e.split=function(t,n,r){return[e.filter(t,n,r),e.filter(t,(e=>!n(e)),r)]},e.buffer=function(e,t=!1,n=[],r){let i=n.slice(),a=e((e=>{i?i.push(e):s.fire(e)}));r&&r.add(a);let o=()=>{i?.forEach((e=>s.fire(e))),i=null},s=new _({onWillAddFirstListener(){a||(a=e((e=>s.fire(e))),r&&r.add(a))},onDidAddFirstListener(){i&&(t?setTimeout(o):o())},onDidRemoveLastListener(){a&&a.dispose(),a=null}});return r&&r.add(s),s.event},e.chain=function(e,t){return(n,r,i)=>{let a=t(new c);return e((function(e){let t=a.evaluate(e);t!==s&&n.call(r,t)}),void 0,i)}};let s=Symbol(`HaltChainable`);class c{constructor(){this.steps=[]}map(e){return this.steps.push(e),this}forEach(e){return this.steps.push((t=>(e(t),t))),this}filter(e){return this.steps.push((t=>e(t)?t:s)),this}reduce(e,t){let n=t;return this.steps.push((t=>(n=e(n,t),n))),this}latch(e=(e,t)=>e===t){let t,n=!0;return this.steps.push((r=>{let i=n||!e(r,t);return n=!1,t=r,i?r:s})),this}evaluate(e){for(let t of this.steps)if((e=t(e))===s)break;return e}}e.fromNodeEventEmitter=function(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new _({onWillAddFirstListener:()=>e.on(t,r),onDidRemoveLastListener:()=>e.removeListener(t,r)});return i.event},e.fromDOMEventEmitter=function(e,t,n=e=>e){let r=(...e)=>i.fire(n(...e)),i=new _({onWillAddFirstListener:()=>e.addEventListener(t,r),onDidRemoveLastListener:()=>e.removeEventListener(t,r)});return i.event},e.toPromise=function(e){return new Promise((n=>t(e)(n)))},e.fromPromise=function(e){let t=new _;return e.then((e=>{t.fire(e)}),(()=>{t.fire(void 0)})).finally((()=>{t.dispose()})),t.event},e.forward=function(e,t){return e((e=>t.fire(e)))},e.runAndSubscribe=function(e,t,n){return t(n),e((e=>t(e)))};class l{constructor(e,t){this._observable=e,this._counter=0,this._hasChanged=!1;let n={onWillAddFirstListener:()=>{e.addObserver(this)},onDidRemoveLastListener:()=>{e.removeObserver(this)}};this.emitter=new _(n),t&&t.add(this.emitter)}beginUpdate(e){this._counter++}handlePossibleChange(e){}handleChange(e,t){this._hasChanged=!0}endUpdate(e){this._counter--,this._counter===0&&(this._observable.reportChanges(),this._hasChanged&&(this._hasChanged=!1,this.emitter.fire(this._observable.get())))}}e.fromObservable=function(e,t){return new l(e,t).emitter.event},e.fromObservableLight=function(e){return(t,n,r)=>{let i=0,o=!1,s={beginUpdate(){i++},endUpdate(){i--,i===0&&(e.reportChanges(),o&&(o=!1,t.call(n)))},handlePossibleChange(){},handleChange(){o=!0}};e.addObserver(s),e.reportChanges();let c={dispose(){e.removeObserver(s)}};return r instanceof a.DisposableStore?r.add(c):Array.isArray(r)&&r.push(c),c}}})(c||(t.Event=c={}));class l{static{this.all=/* @__PURE__ */ new Set}static{this._idPool=0}constructor(e){this.listenerCount=0,this.invocationCount=0,this.elapsedOverall=0,this.durations=[],this.name=`${e}_${l._idPool++}`,l.all.add(this)}start(e){this._stopWatch=new s.StopWatch,this.listenerCount=e}stop(){if(this._stopWatch){let e=this._stopWatch.elapsed();this.durations.push(e),this.elapsedOverall+=e,this.invocationCount+=1,this._stopWatch=void 0}}}t.EventProfiling=l;let u=-1;class d{static{this._idPool=1}constructor(e,t,n=(d._idPool++).toString(16).padStart(3,`0`)){this._errorHandler=e,this.threshold=t,this.name=n,this._warnCountdown=0}dispose(){this._stacks?.clear()}check(e,t){let n=this.threshold;if(n<=0||t{let t=this._stacks.get(e.value)||0;this._stacks.set(e.value,t-1)}}getMostFrequentStack(){if(!this._stacks)return;let e,t=0;for(let[n,r]of this._stacks)(!e||t0||this._options?.leakWarningThreshold?new d(e?.onListenerError??r.onUnexpectedError,this._options?.leakWarningThreshold??u):void 0,this._perfMon=this._options?._profName?new l(this._options._profName):void 0,this._deliveryQueue=this._options?.deliveryQueue}dispose(){this._disposed||(this._disposed=!0,this._deliveryQueue?.current===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),this._options?.onDidRemoveLastListener?.(),this._leakageMon?.dispose())}get event(){return this._event??=(e,t,n)=>{if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let e=`[${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (${this._size} vs ${this._leakageMon.threshold})`;console.warn(e);let t=this._leakageMon.getMostFrequentStack()??[`UNKNOWN stack`,-1],n=new m(`${e}. HINT: Stack shows most frequent listener (${t[1]}-times)`,t[0]);return(this._options?.onListenerError||r.onUnexpectedError)(n),a.Disposable.None}if(this._disposed)return a.Disposable.None;t&&(e=e.bind(t));let i=new g(e),o;this._leakageMon&&this._size>=Math.ceil(.2*this._leakageMon.threshold)&&(i.stack=f.create(),o=this._leakageMon.check(i.stack,this._size+1)),this._listeners?this._listeners instanceof g?(this._deliveryQueue??=new v,this._listeners=[this._listeners,i]):this._listeners.push(i):(this._options?.onWillAddFirstListener?.(this),this._listeners=i,this._options?.onDidAddFirstListener?.(this)),this._size++;let s=(0,a.toDisposable)((()=>{o?.(),this._removeListener(i)}));return n instanceof a.DisposableStore?n.add(s):Array.isArray(n)&&n.push(s),s},this._event}_removeListener(e){if(this._options?.onWillRemoveListener?.(this),!this._listeners)return;if(this._size===1)return this._listeners=void 0,this._options?.onDidRemoveLastListener?.(this),void(this._size=0);let t=this._listeners,n=t.indexOf(e);if(n===-1)throw console.log(`disposed?`,this._disposed),console.log(`size?`,this._size),console.log(`arr?`,JSON.stringify(this._listeners)),/* @__PURE__ */ Error(`Attempted to dispose unknown listener`);this._size--,t[n]=void 0;let r=this._deliveryQueue.current===this;if(2*this._size<=t.length){let e=0;for(let n=0;n0}}t.Emitter=_,t.createEventDeliveryQueue=()=>new v;class v{constructor(){this.i=-1,this.end=0}enqueue(e,t,n){this.i=0,this.end=n,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}}t.AsyncEmitter=class extends _{async fireAsync(e,t,n){if(this._listeners)for(this._asyncDeliveryQueue||=new o.LinkedList,((e,t)=>{if(e instanceof g)t(e);else for(let n=0;nthis._asyncDeliveryQueue.push([t.value,e])));this._asyncDeliveryQueue.size>0&&!t.isCancellationRequested;){let[e,i]=this._asyncDeliveryQueue.shift(),a=[],o={...i,token:t,waitUntil:t=>{if(Object.isFrozen(a))throw Error(`waitUntil can NOT be called asynchronous`);n&&(t=n(t,e)),a.push(t)}};try{e(o)}catch(e){(0,r.onUnexpectedError)(e);continue}Object.freeze(a),await Promise.allSettled(a).then((e=>{for(let t of e)t.status===`rejected`&&(0,r.onUnexpectedError)(t.reason)}))}}};class y extends _{get isPaused(){return this._isPaused!==0}constructor(e){super(e),this._isPaused=0,this._eventQueue=new o.LinkedList,this._mergeFn=e?.merge}pause(){this._isPaused++}resume(){if(this._isPaused!==0&&--this._isPaused==0){if(this._mergeFn){if(this._eventQueue.size>0){let e=Array.from(this._eventQueue);this._eventQueue.clear(),super.fire(this._mergeFn(e))}}else for(;!this._isPaused&&this._eventQueue.size!==0;)super.fire(this._eventQueue.shift())}}fire(e){this._size&&(this._isPaused===0?super.fire(e):this._eventQueue.push(e))}}t.PauseableEmitter=y,t.DebounceEmitter=class extends y{constructor(e){super(e),this._delay=e.delay??100}fire(e){this._handle||=(this.pause(),setTimeout((()=>{this._handle=void 0,this.resume()}),this._delay)),super.fire(e)}},t.MicrotaskEmitter=class extends _{constructor(e){super(e),this._queuedEvents=[],this._mergeFn=e?.merge}fire(e){this.hasListeners()&&(this._queuedEvents.push(e),this._queuedEvents.length===1&&queueMicrotask((()=>{this._mergeFn?super.fire(this._mergeFn(this._queuedEvents)):this._queuedEvents.forEach((e=>super.fire(e))),this._queuedEvents=[]})))}};class b{constructor(){this.hasListeners=!1,this.events=[],this.emitter=new _({onWillAddFirstListener:()=>this.onFirstListenerAdd(),onDidRemoveLastListener:()=>this.onLastListenerRemove()})}get event(){return this.emitter.event}add(e){let t={event:e,listener:null};return this.events.push(t),this.hasListeners&&this.hook(t),(0,a.toDisposable)((0,i.createSingleCallFunction)((()=>{this.hasListeners&&this.unhook(t);let e=this.events.indexOf(t);this.events.splice(e,1)})))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach((e=>this.hook(e)))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach((e=>this.unhook(e)))}hook(e){e.listener=e.event((e=>this.emitter.fire(e)))}unhook(e){e.listener?.dispose(),e.listener=null}dispose(){this.emitter.dispose();for(let e of this.events)e.listener?.dispose();this.events=[]}}t.EventMultiplexer=b,t.DynamicListEventMultiplexer=class{constructor(e,t,n,r){this._store=new a.DisposableStore;let i=this._store.add(new b),o=this._store.add(new a.DisposableMap);function s(e){o.set(e,i.add(r(e)))}for(let t of e)s(t);this._store.add(t((e=>{s(e)}))),this._store.add(n((e=>{o.deleteAndDispose(e)}))),this.event=i.event}dispose(){this._store.dispose()}},t.EventBufferer=class{constructor(){this.data=[]}wrapEvent(e,t,n){return(r,i,a)=>e((e=>{let a=this.data[this.data.length-1];if(!t)return void(a?a.buffers.push((()=>r.call(i,e))):r.call(i,e));let o=a;o?(o.items??=[],o.items.push(e),o.buffers.length===0&&a.buffers.push((()=>{o.reducedResult??=n?o.items.reduce(t,n):o.items.reduce(t),r.call(i,o.reducedResult)}))):r.call(i,t(n,e))}),void 0,a)}bufferEvents(e){let t={buffers:[]};this.data.push(t);let n=e();return this.data.pop(),t.buffers.forEach((e=>e())),n}},t.Relay=class{constructor(){this.listening=!1,this.inputEvent=c.None,this.inputEventListener=a.Disposable.None,this.emitter=new _({onDidAddFirstListener:()=>{this.listening=!0,this.inputEventListener=this.inputEvent(this.emitter.fire,this.emitter)},onDidRemoveLastListener:()=>{this.listening=!1,this.inputEventListener.dispose()}}),this.event=this.emitter.event}set input(e){this.inputEvent=e,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=e(this.emitter.fire,this.emitter))}dispose(){this.inputEventListener.dispose(),this.emitter.dispose()}},t.ValueWithChangeEvent=class{static const(e){return new x(e)}constructor(e){this._value=e,this._onDidChange=new _,this.onDidChange=this._onDidChange.event}get value(){return this._value}set value(e){e!==this._value&&(this._value=e,this._onDidChange.fire(void 0))}};class x{constructor(e){this.value=e,this.onDidChange=c.None}}},8841:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.createSingleCallFunction=function(e,t){let n=this,r,i=!1;return function(){if(i)return r;if(i=!0,t)try{r=e.apply(n,arguments)}finally{t()}else r=e.apply(n,arguments);return r}}},6304:function(e,t,n){var r=this&&this.__createBinding||(Object.create?function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);i&&!(`get`in i?!t.__esModule:i.writable||i.configurable)||(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}:function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),i=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),a=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n in e)n!=="default"&&Object.prototype.hasOwnProperty.call(e,n)&&r(t,e,n);return i(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.StringSHA1=t.Hasher=void 0,t.hash=function(e){return s(e,0)},t.doHash=s,t.numberHash=c,t.stringHash=l,t.toHexString=p;let o=a(n(1316));function s(e,t){switch(typeof e){case`object`:return e===null?c(349,t):Array.isArray(e)?(n=e,r=c(104579,r=t),n.reduce(((e,t)=>s(t,e)),r)):function(e,t){return t=c(181387,t),Object.keys(e).sort().reduce(((t,n)=>(t=l(n,t),s(e[n],t))),t)}(e,t);case`string`:return l(e,t);case`boolean`:return function(e,t){return c(e?433:863,t)}(e,t);case`number`:return c(e,t);case`undefined`:return c(937,t);default:return c(617,t)}var n,r}function c(e,t){return(t<<5)-t+e|0}function l(e,t){t=c(149417,t);for(let n=0,r=e.length;n>>r)>>>0}function f(e,t=0,n=e.byteLength,r=0){for(let i=0;ie.toString(16).padStart(2,`0`))).join(``):function(e,t,n=`0`){for(;e.length>>0).toString(16),t/4)}t.Hasher=class{constructor(){this._value=0}get value(){return this._value}hash(e){return this._value=s(e,this._value),this._value}},function(e){e[e.BLOCK_SIZE=64]=`BLOCK_SIZE`,e[e.UNICODE_REPLACEMENT=65533]=`UNICODE_REPLACEMENT`}(u||={});class m{static{this._bigBlock32=/* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(320))}constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(u.BLOCK_SIZE+3),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(e){let t=e.length;if(t===0)return;let n=this._buff,r,i,a=this._buffLen,s=this._leftoverHighSurrogate;for(s===0?(r=e.charCodeAt(0),i=0):(r=s,i=-1,s=0);;){let c=r;if(o.isHighSurrogate(r)){if(!(i+1>>6,e[t++]=128|(63&n)>>>0):n<65536?(e[t++]=224|(61440&n)>>>12,e[t++]=128|(4032&n)>>>6,e[t++]=128|(63&n)>>>0):(e[t++]=240|(1835008&n)>>>18,e[t++]=128|(258048&n)>>>12,e[t++]=128|(4032&n)>>>6,e[t++]=128|(63&n)>>>0),t>=u.BLOCK_SIZE&&(this._step(),t-=u.BLOCK_SIZE,this._totalLen+=u.BLOCK_SIZE,e[0]=e[u.BLOCK_SIZE+0],e[1]=e[u.BLOCK_SIZE+1],e[2]=e[u.BLOCK_SIZE+2]),t}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,u.UNICODE_REPLACEMENT)),this._totalLen+=this._buffLen,this._wrapUp()),p(this._h0)+p(this._h1)+p(this._h2)+p(this._h3)+p(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,f(this._buff,this._buffLen),this._buffLen>56&&(this._step(),f(this._buff));let e=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(e/4294967296),!1),this._buffDV.setUint32(60,e%4294967296,!1),this._step()}_step(){let e=m._bigBlock32,t=this._buffDV;for(let n=0;n<64;n+=4)e.setUint32(n,t.getUint32(n,!1),!1);for(let t=64;t<320;t+=4)e.setUint32(t,d(e.getUint32(t-12,!1)^e.getUint32(t-32,!1)^e.getUint32(t-56,!1)^e.getUint32(t-64,!1),1),!1);let n,r,i,a=this._h0,o=this._h1,s=this._h2,c=this._h3,l=this._h4;for(let t=0;t<80;t++)t<20?(n=o&s|~o&c,r=1518500249):t<40?(n=o^s^c,r=1859775393):t<60?(n=o&s|o&c|s&c,r=2400959708):(n=o^s^c,r=3395469782),i=d(a,5)+n+l+r+e.getUint32(4*t,!1)|0,l=c,c=s,s=d(o,30),o=a,a=i;this._h0=this._h0+a|0,this._h1=this._h1+o|0,this._h2=this._h2+s|0,this._h3=this._h3+c|0,this._h4=this._h4+l|0}}t.StringSHA1=m},4218:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.Iterable=void 0,function(e){function t(e){return e&&typeof e==`object`&&typeof e[Symbol.iterator]==`function`}e.is=t;let n=Object.freeze([]);function*r(e){yield e}e.empty=function(){return n},e.single=r,e.wrap=function(e){return t(e)?e:r(e)},e.from=function(e){return e||n},e.reverse=function*(e){for(let t=e.length-1;t>=0;t--)yield e[t]},e.isEmpty=function(e){return!e||!0===e[Symbol.iterator]().next().done},e.first=function(e){return e[Symbol.iterator]().next().value},e.some=function(e,t){let n=0;for(let r of e)if(t(r,n++))return!0;return!1},e.find=function(e,t){for(let n of e)if(t(n))return n},e.filter=function*(e,t){for(let n of e)t(n)&&(yield n)},e.map=function*(e,t){let n=0;for(let r of e)yield t(r,n++)},e.flatMap=function*(e,t){let n=0;for(let r of e)yield*t(r,n++)},e.concat=function*(...e){for(let t of e)yield*t},e.reduce=function(e,t,n){let r=n;for(let n of e)r=t(r,n);return r},e.slice=function*(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);ti}]},e.asyncToArray=async function(e){let t=[];for await(let n of e)t.push(n);return Promise.resolve(t)}}(n||(t.Iterable=n={}))},7883:(e,t)=>{var n,r;Object.defineProperty(t,"__esModule",{value:!0}),t.KeyMod=t.KeyCodeUtils=t.ScanCodeUtils=t.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE=t.EVENT_KEY_CODE_MAP=t.ScanCode=t.KeyCode=void 0,t.KeyChord=function(e,t){return(e|(65535&t)<<16>>>0)>>>0},function(e){e[e.DependsOnKbLayout=-1]=`DependsOnKbLayout`,e[e.Unknown=0]=`Unknown`,e[e.Backspace=1]=`Backspace`,e[e.Tab=2]=`Tab`,e[e.Enter=3]=`Enter`,e[e.Shift=4]=`Shift`,e[e.Ctrl=5]=`Ctrl`,e[e.Alt=6]=`Alt`,e[e.PauseBreak=7]=`PauseBreak`,e[e.CapsLock=8]=`CapsLock`,e[e.Escape=9]=`Escape`,e[e.Space=10]=`Space`,e[e.PageUp=11]=`PageUp`,e[e.PageDown=12]=`PageDown`,e[e.End=13]=`End`,e[e.Home=14]=`Home`,e[e.LeftArrow=15]=`LeftArrow`,e[e.UpArrow=16]=`UpArrow`,e[e.RightArrow=17]=`RightArrow`,e[e.DownArrow=18]=`DownArrow`,e[e.Insert=19]=`Insert`,e[e.Delete=20]=`Delete`,e[e.Digit0=21]=`Digit0`,e[e.Digit1=22]=`Digit1`,e[e.Digit2=23]=`Digit2`,e[e.Digit3=24]=`Digit3`,e[e.Digit4=25]=`Digit4`,e[e.Digit5=26]=`Digit5`,e[e.Digit6=27]=`Digit6`,e[e.Digit7=28]=`Digit7`,e[e.Digit8=29]=`Digit8`,e[e.Digit9=30]=`Digit9`,e[e.KeyA=31]=`KeyA`,e[e.KeyB=32]=`KeyB`,e[e.KeyC=33]=`KeyC`,e[e.KeyD=34]=`KeyD`,e[e.KeyE=35]=`KeyE`,e[e.KeyF=36]=`KeyF`,e[e.KeyG=37]=`KeyG`,e[e.KeyH=38]=`KeyH`,e[e.KeyI=39]=`KeyI`,e[e.KeyJ=40]=`KeyJ`,e[e.KeyK=41]=`KeyK`,e[e.KeyL=42]=`KeyL`,e[e.KeyM=43]=`KeyM`,e[e.KeyN=44]=`KeyN`,e[e.KeyO=45]=`KeyO`,e[e.KeyP=46]=`KeyP`,e[e.KeyQ=47]=`KeyQ`,e[e.KeyR=48]=`KeyR`,e[e.KeyS=49]=`KeyS`,e[e.KeyT=50]=`KeyT`,e[e.KeyU=51]=`KeyU`,e[e.KeyV=52]=`KeyV`,e[e.KeyW=53]=`KeyW`,e[e.KeyX=54]=`KeyX`,e[e.KeyY=55]=`KeyY`,e[e.KeyZ=56]=`KeyZ`,e[e.Meta=57]=`Meta`,e[e.ContextMenu=58]=`ContextMenu`,e[e.F1=59]=`F1`,e[e.F2=60]=`F2`,e[e.F3=61]=`F3`,e[e.F4=62]=`F4`,e[e.F5=63]=`F5`,e[e.F6=64]=`F6`,e[e.F7=65]=`F7`,e[e.F8=66]=`F8`,e[e.F9=67]=`F9`,e[e.F10=68]=`F10`,e[e.F11=69]=`F11`,e[e.F12=70]=`F12`,e[e.F13=71]=`F13`,e[e.F14=72]=`F14`,e[e.F15=73]=`F15`,e[e.F16=74]=`F16`,e[e.F17=75]=`F17`,e[e.F18=76]=`F18`,e[e.F19=77]=`F19`,e[e.F20=78]=`F20`,e[e.F21=79]=`F21`,e[e.F22=80]=`F22`,e[e.F23=81]=`F23`,e[e.F24=82]=`F24`,e[e.NumLock=83]=`NumLock`,e[e.ScrollLock=84]=`ScrollLock`,e[e.Semicolon=85]=`Semicolon`,e[e.Equal=86]=`Equal`,e[e.Comma=87]=`Comma`,e[e.Minus=88]=`Minus`,e[e.Period=89]=`Period`,e[e.Slash=90]=`Slash`,e[e.Backquote=91]=`Backquote`,e[e.BracketLeft=92]=`BracketLeft`,e[e.Backslash=93]=`Backslash`,e[e.BracketRight=94]=`BracketRight`,e[e.Quote=95]=`Quote`,e[e.OEM_8=96]=`OEM_8`,e[e.IntlBackslash=97]=`IntlBackslash`,e[e.Numpad0=98]=`Numpad0`,e[e.Numpad1=99]=`Numpad1`,e[e.Numpad2=100]=`Numpad2`,e[e.Numpad3=101]=`Numpad3`,e[e.Numpad4=102]=`Numpad4`,e[e.Numpad5=103]=`Numpad5`,e[e.Numpad6=104]=`Numpad6`,e[e.Numpad7=105]=`Numpad7`,e[e.Numpad8=106]=`Numpad8`,e[e.Numpad9=107]=`Numpad9`,e[e.NumpadMultiply=108]=`NumpadMultiply`,e[e.NumpadAdd=109]=`NumpadAdd`,e[e.NUMPAD_SEPARATOR=110]=`NUMPAD_SEPARATOR`,e[e.NumpadSubtract=111]=`NumpadSubtract`,e[e.NumpadDecimal=112]=`NumpadDecimal`,e[e.NumpadDivide=113]=`NumpadDivide`,e[e.KEY_IN_COMPOSITION=114]=`KEY_IN_COMPOSITION`,e[e.ABNT_C1=115]=`ABNT_C1`,e[e.ABNT_C2=116]=`ABNT_C2`,e[e.AudioVolumeMute=117]=`AudioVolumeMute`,e[e.AudioVolumeUp=118]=`AudioVolumeUp`,e[e.AudioVolumeDown=119]=`AudioVolumeDown`,e[e.BrowserSearch=120]=`BrowserSearch`,e[e.BrowserHome=121]=`BrowserHome`,e[e.BrowserBack=122]=`BrowserBack`,e[e.BrowserForward=123]=`BrowserForward`,e[e.MediaTrackNext=124]=`MediaTrackNext`,e[e.MediaTrackPrevious=125]=`MediaTrackPrevious`,e[e.MediaStop=126]=`MediaStop`,e[e.MediaPlayPause=127]=`MediaPlayPause`,e[e.LaunchMediaPlayer=128]=`LaunchMediaPlayer`,e[e.LaunchMail=129]=`LaunchMail`,e[e.LaunchApp2=130]=`LaunchApp2`,e[e.Clear=131]=`Clear`,e[e.MAX_VALUE=132]=`MAX_VALUE`}(n||(t.KeyCode=n={})),function(e){e[e.DependsOnKbLayout=-1]=`DependsOnKbLayout`,e[e.None=0]=`None`,e[e.Hyper=1]=`Hyper`,e[e.Super=2]=`Super`,e[e.Fn=3]=`Fn`,e[e.FnLock=4]=`FnLock`,e[e.Suspend=5]=`Suspend`,e[e.Resume=6]=`Resume`,e[e.Turbo=7]=`Turbo`,e[e.Sleep=8]=`Sleep`,e[e.WakeUp=9]=`WakeUp`,e[e.KeyA=10]=`KeyA`,e[e.KeyB=11]=`KeyB`,e[e.KeyC=12]=`KeyC`,e[e.KeyD=13]=`KeyD`,e[e.KeyE=14]=`KeyE`,e[e.KeyF=15]=`KeyF`,e[e.KeyG=16]=`KeyG`,e[e.KeyH=17]=`KeyH`,e[e.KeyI=18]=`KeyI`,e[e.KeyJ=19]=`KeyJ`,e[e.KeyK=20]=`KeyK`,e[e.KeyL=21]=`KeyL`,e[e.KeyM=22]=`KeyM`,e[e.KeyN=23]=`KeyN`,e[e.KeyO=24]=`KeyO`,e[e.KeyP=25]=`KeyP`,e[e.KeyQ=26]=`KeyQ`,e[e.KeyR=27]=`KeyR`,e[e.KeyS=28]=`KeyS`,e[e.KeyT=29]=`KeyT`,e[e.KeyU=30]=`KeyU`,e[e.KeyV=31]=`KeyV`,e[e.KeyW=32]=`KeyW`,e[e.KeyX=33]=`KeyX`,e[e.KeyY=34]=`KeyY`,e[e.KeyZ=35]=`KeyZ`,e[e.Digit1=36]=`Digit1`,e[e.Digit2=37]=`Digit2`,e[e.Digit3=38]=`Digit3`,e[e.Digit4=39]=`Digit4`,e[e.Digit5=40]=`Digit5`,e[e.Digit6=41]=`Digit6`,e[e.Digit7=42]=`Digit7`,e[e.Digit8=43]=`Digit8`,e[e.Digit9=44]=`Digit9`,e[e.Digit0=45]=`Digit0`,e[e.Enter=46]=`Enter`,e[e.Escape=47]=`Escape`,e[e.Backspace=48]=`Backspace`,e[e.Tab=49]=`Tab`,e[e.Space=50]=`Space`,e[e.Minus=51]=`Minus`,e[e.Equal=52]=`Equal`,e[e.BracketLeft=53]=`BracketLeft`,e[e.BracketRight=54]=`BracketRight`,e[e.Backslash=55]=`Backslash`,e[e.IntlHash=56]=`IntlHash`,e[e.Semicolon=57]=`Semicolon`,e[e.Quote=58]=`Quote`,e[e.Backquote=59]=`Backquote`,e[e.Comma=60]=`Comma`,e[e.Period=61]=`Period`,e[e.Slash=62]=`Slash`,e[e.CapsLock=63]=`CapsLock`,e[e.F1=64]=`F1`,e[e.F2=65]=`F2`,e[e.F3=66]=`F3`,e[e.F4=67]=`F4`,e[e.F5=68]=`F5`,e[e.F6=69]=`F6`,e[e.F7=70]=`F7`,e[e.F8=71]=`F8`,e[e.F9=72]=`F9`,e[e.F10=73]=`F10`,e[e.F11=74]=`F11`,e[e.F12=75]=`F12`,e[e.PrintScreen=76]=`PrintScreen`,e[e.ScrollLock=77]=`ScrollLock`,e[e.Pause=78]=`Pause`,e[e.Insert=79]=`Insert`,e[e.Home=80]=`Home`,e[e.PageUp=81]=`PageUp`,e[e.Delete=82]=`Delete`,e[e.End=83]=`End`,e[e.PageDown=84]=`PageDown`,e[e.ArrowRight=85]=`ArrowRight`,e[e.ArrowLeft=86]=`ArrowLeft`,e[e.ArrowDown=87]=`ArrowDown`,e[e.ArrowUp=88]=`ArrowUp`,e[e.NumLock=89]=`NumLock`,e[e.NumpadDivide=90]=`NumpadDivide`,e[e.NumpadMultiply=91]=`NumpadMultiply`,e[e.NumpadSubtract=92]=`NumpadSubtract`,e[e.NumpadAdd=93]=`NumpadAdd`,e[e.NumpadEnter=94]=`NumpadEnter`,e[e.Numpad1=95]=`Numpad1`,e[e.Numpad2=96]=`Numpad2`,e[e.Numpad3=97]=`Numpad3`,e[e.Numpad4=98]=`Numpad4`,e[e.Numpad5=99]=`Numpad5`,e[e.Numpad6=100]=`Numpad6`,e[e.Numpad7=101]=`Numpad7`,e[e.Numpad8=102]=`Numpad8`,e[e.Numpad9=103]=`Numpad9`,e[e.Numpad0=104]=`Numpad0`,e[e.NumpadDecimal=105]=`NumpadDecimal`,e[e.IntlBackslash=106]=`IntlBackslash`,e[e.ContextMenu=107]=`ContextMenu`,e[e.Power=108]=`Power`,e[e.NumpadEqual=109]=`NumpadEqual`,e[e.F13=110]=`F13`,e[e.F14=111]=`F14`,e[e.F15=112]=`F15`,e[e.F16=113]=`F16`,e[e.F17=114]=`F17`,e[e.F18=115]=`F18`,e[e.F19=116]=`F19`,e[e.F20=117]=`F20`,e[e.F21=118]=`F21`,e[e.F22=119]=`F22`,e[e.F23=120]=`F23`,e[e.F24=121]=`F24`,e[e.Open=122]=`Open`,e[e.Help=123]=`Help`,e[e.Select=124]=`Select`,e[e.Again=125]=`Again`,e[e.Undo=126]=`Undo`,e[e.Cut=127]=`Cut`,e[e.Copy=128]=`Copy`,e[e.Paste=129]=`Paste`,e[e.Find=130]=`Find`,e[e.AudioVolumeMute=131]=`AudioVolumeMute`,e[e.AudioVolumeUp=132]=`AudioVolumeUp`,e[e.AudioVolumeDown=133]=`AudioVolumeDown`,e[e.NumpadComma=134]=`NumpadComma`,e[e.IntlRo=135]=`IntlRo`,e[e.KanaMode=136]=`KanaMode`,e[e.IntlYen=137]=`IntlYen`,e[e.Convert=138]=`Convert`,e[e.NonConvert=139]=`NonConvert`,e[e.Lang1=140]=`Lang1`,e[e.Lang2=141]=`Lang2`,e[e.Lang3=142]=`Lang3`,e[e.Lang4=143]=`Lang4`,e[e.Lang5=144]=`Lang5`,e[e.Abort=145]=`Abort`,e[e.Props=146]=`Props`,e[e.NumpadParenLeft=147]=`NumpadParenLeft`,e[e.NumpadParenRight=148]=`NumpadParenRight`,e[e.NumpadBackspace=149]=`NumpadBackspace`,e[e.NumpadMemoryStore=150]=`NumpadMemoryStore`,e[e.NumpadMemoryRecall=151]=`NumpadMemoryRecall`,e[e.NumpadMemoryClear=152]=`NumpadMemoryClear`,e[e.NumpadMemoryAdd=153]=`NumpadMemoryAdd`,e[e.NumpadMemorySubtract=154]=`NumpadMemorySubtract`,e[e.NumpadClear=155]=`NumpadClear`,e[e.NumpadClearEntry=156]=`NumpadClearEntry`,e[e.ControlLeft=157]=`ControlLeft`,e[e.ShiftLeft=158]=`ShiftLeft`,e[e.AltLeft=159]=`AltLeft`,e[e.MetaLeft=160]=`MetaLeft`,e[e.ControlRight=161]=`ControlRight`,e[e.ShiftRight=162]=`ShiftRight`,e[e.AltRight=163]=`AltRight`,e[e.MetaRight=164]=`MetaRight`,e[e.BrightnessUp=165]=`BrightnessUp`,e[e.BrightnessDown=166]=`BrightnessDown`,e[e.MediaPlay=167]=`MediaPlay`,e[e.MediaRecord=168]=`MediaRecord`,e[e.MediaFastForward=169]=`MediaFastForward`,e[e.MediaRewind=170]=`MediaRewind`,e[e.MediaTrackNext=171]=`MediaTrackNext`,e[e.MediaTrackPrevious=172]=`MediaTrackPrevious`,e[e.MediaStop=173]=`MediaStop`,e[e.Eject=174]=`Eject`,e[e.MediaPlayPause=175]=`MediaPlayPause`,e[e.MediaSelect=176]=`MediaSelect`,e[e.LaunchMail=177]=`LaunchMail`,e[e.LaunchApp2=178]=`LaunchApp2`,e[e.LaunchApp1=179]=`LaunchApp1`,e[e.SelectTask=180]=`SelectTask`,e[e.LaunchScreenSaver=181]=`LaunchScreenSaver`,e[e.BrowserSearch=182]=`BrowserSearch`,e[e.BrowserHome=183]=`BrowserHome`,e[e.BrowserBack=184]=`BrowserBack`,e[e.BrowserForward=185]=`BrowserForward`,e[e.BrowserStop=186]=`BrowserStop`,e[e.BrowserRefresh=187]=`BrowserRefresh`,e[e.BrowserFavorites=188]=`BrowserFavorites`,e[e.ZoomToggle=189]=`ZoomToggle`,e[e.MailReply=190]=`MailReply`,e[e.MailForward=191]=`MailForward`,e[e.MailSend=192]=`MailSend`,e[e.MAX_VALUE=193]=`MAX_VALUE`}(r||(t.ScanCode=r={}));class i{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||n.Unknown}}let a=new i,o=new i,s=new i;t.EVENT_KEY_CODE_MAP=Array(230),t.NATIVE_WINDOWS_KEY_CODE_TO_KEY_CODE={};let c=[],l=Object.create(null),u=Object.create(null);var d,f;t.ScanCodeUtils={lowerCaseToEnum:e=>u[e]||r.None,toEnum:e=>l[e]||r.None,toString:e=>c[e]||`None`},function(e){e.toString=function(e){return a.keyCodeToStr(e)},e.fromString=function(e){return a.strToKeyCode(e)},e.toUserSettingsUS=function(e){return o.keyCodeToStr(e)},e.toUserSettingsGeneral=function(e){return s.keyCodeToStr(e)},e.fromUserSettings=function(e){return o.strToKeyCode(e)||s.strToKeyCode(e)},e.toElectronAccelerator=function(e){if(e>=n.Numpad0&&e<=n.NumpadDivide)return null;switch(e){case n.UpArrow:return`Up`;case n.DownArrow:return`Down`;case n.LeftArrow:return`Left`;case n.RightArrow:return`Right`}return a.keyCodeToStr(e)}}(d||(t.KeyCodeUtils=d={})),function(e){e[e.CtrlCmd=2048]=`CtrlCmd`,e[e.Shift=1024]=`Shift`,e[e.Alt=512]=`Alt`,e[e.WinCtrl=256]=`WinCtrl`}(f||(t.KeyMod=f={}))},2811:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ResolvedKeybinding=t.ResolvedChord=t.Keybinding=t.ScanCodeChord=t.KeyCodeChord=void 0,t.decodeKeybinding=function(e,t){if(typeof e==`number`){if(e===0)return null;let n=(65535&e)>>>0,r=(4294901760&e)>>>16;return new u(r===0?[s(n,t)]:[s(n,t),s(r,t)])}{let n=[];for(let r=0;r{Object.defineProperty(t,"__esModule",{value:!0}),t.Lazy=void 0,t.Lazy=class{constructor(e){this.executor=e,this._didRun=!1}get hasValue(){return this._didRun}get value(){if(!this._didRun)try{this._value=this.executor()}catch(e){this._error=e}finally{this._didRun=!0}if(this._error)throw this._error;return this._value}get rawValue(){return this._value}}},7150:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.DisposableMap=t.ImmortalReference=t.AsyncReferenceCollection=t.ReferenceCollection=t.SafeDisposable=t.RefCountedDisposable=t.MandatoryMutableDisposable=t.MutableDisposable=t.Disposable=t.DisposableStore=t.DisposableTracker=void 0,t.setDisposableTracker=function(e){c=e},t.trackDisposable=u,t.markAsDisposed=d,t.markAsSingleton=function(e){return c?.markAsSingleton(e),e},t.isDisposable=p,t.dispose=m,t.disposeIfDisposable=function(e){for(let t of e)p(t)&&t.dispose();return[]},t.combinedDisposable=function(...e){let t=h((()=>m(e)));return function(e,t){if(c)for(let n of e)c.setParent(n,t)}(e,t),t},t.toDisposable=h,t.disposeOnReturn=function(e){let t=new g;try{e(t)}finally{t.dispose()}};let r=n(3058),i=n(9087),a=n(2608),o=n(8841),s=n(4218),c=null;class l{constructor(){this.livingDisposables=/* @__PURE__ */ new Map}static{this.idx=0}getDisposableData(e){let t=this.livingDisposables.get(e);return t||(t={parent:null,source:null,isSingleton:!1,value:e,idx:l.idx++},this.livingDisposables.set(e,t)),t}trackDisposable(e){let t=this.getDisposableData(e);t.source||=(/* @__PURE__ */ Error()).stack}setParent(e,t){this.getDisposableData(e).parent=t}markAsDisposed(e){this.livingDisposables.delete(e)}markAsSingleton(e){this.getDisposableData(e).isSingleton=!0}getRootParent(e,t){let n=t.get(e);if(n)return n;let r=e.parent?this.getRootParent(this.getDisposableData(e.parent),t):e;return t.set(e,r),r}getTrackedDisposables(){let e=/* @__PURE__ */ new Map;return[...this.livingDisposables.entries()].filter((([,t])=>t.source!==null&&!this.getRootParent(t,e).isSingleton)).flatMap((([e])=>e))}computeLeakingDisposables(e=10,t){let n;if(t)n=t;else{let e=/* @__PURE__ */ new Map,t=[...this.livingDisposables.values()].filter((t=>t.source!==null&&!this.getRootParent(t,e).isSingleton));if(t.length===0)return;let r=new Set(t.map((e=>e.value)));if(n=t.filter((e=>!(e.parent&&r.has(e.parent)))),n.length===0)throw Error(`There are cyclic diposable chains!`)}if(!n)return;function o(e){let t=e.source.split(` +`).map((e=>e.trim().replace(`at `,``))).filter((e=>e!==``));return function(e,t){for(;e.length>0&&t.some((t=>typeof t==`string`?t===e[0]:e[0].match(t)));)e.shift()}(t,[`Error`,/^trackDisposable \(.*\)$/,/^DisposableTracker.trackDisposable \(.*\)$/]),t.reverse()}let s=new a.SetMap;for(let e of n){let t=o(e);for(let n=0;n<=t.length;n++)s.add(t.slice(0,n).join(` +`),e)}n.sort((0,r.compareBy)((e=>e.idx),r.numberComparator));let c=``,l=0;for(let t of n.slice(0,e)){l++;let e=o(t),r=[];for(let t=0;to(e)[t])),(e=>e));delete l[e[t]];for(let[e,t]of Object.entries(l))r.unshift(` - stacktraces of ${t.length} other leaks continue with ${e}`);r.unshift(a)}c+=`\n\n\n==================== Leaking disposable ${l}/${n.length}: ${t.value.constructor.name} ====================\n${r.join(` +`)}\n============================================================\n\n`}return n.length>e&&(c+=`\n\n\n... and ${n.length-e} more leaking disposables\n\n`),{leaks:n,details:c}}}function u(e){return c?.trackDisposable(e),e}function d(e){c?.markAsDisposed(e)}function f(e,t){c?.setParent(e,t)}function p(e){return typeof e==`object`&&!!e&&typeof e.dispose==`function`&&e.dispose.length===0}function m(e){if(s.Iterable.is(e)){let t=[];for(let n of e)if(n)try{n.dispose()}catch(e){t.push(e)}if(t.length===1)throw t[0];if(t.length>1)throw AggregateError(t,`Encountered errors while disposing of store`);return Array.isArray(e)?[]:e}if(e)return e.dispose(),e}function h(e){let t=u({dispose:(0,o.createSingleCallFunction)((()=>{d(t),e()}))});return t}t.DisposableTracker=l;class g{static{this.DISABLE_DISPOSED_WARNING=!1}constructor(){this._toDispose=/* @__PURE__ */ new Set,this._isDisposed=!1,u(this)}dispose(){this._isDisposed||(d(this),this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{m(this._toDispose)}finally{this._toDispose.clear()}}add(e){if(!e)return e;if(e===this)throw Error(`Cannot register a disposable on itself!`);return f(e,this),this._isDisposed?g.DISABLE_DISPOSED_WARNING||console.warn((/* @__PURE__ */ Error(`Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!`)).stack):this._toDispose.add(e),e}delete(e){if(e){if(e===this)throw Error(`Cannot dispose a disposable on itself!`);this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),f(e,null))}}t.DisposableStore=g;class _{static{this.None=Object.freeze({dispose(){}})}constructor(){this._store=new g,u(this),f(this._store,this)}dispose(){d(this),this._store.dispose()}_register(e){if(e===this)throw Error(`Cannot register a disposable on itself!`);return this._store.add(e)}}t.Disposable=_;class v{constructor(){this._isDisposed=!1,u(this)}get value(){return this._isDisposed?void 0:this._value}set value(e){this._isDisposed||e===this._value||(this._value?.dispose(),e&&f(e,this),this._value=e)}clear(){this.value=void 0}dispose(){this._isDisposed=!0,d(this),this._value?.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e&&f(e,null),e}}t.MutableDisposable=v,t.MandatoryMutableDisposable=class{constructor(e){this._disposable=new v,this._isDisposed=!1,this._disposable.value=e}get value(){return this._disposable.value}set value(e){this._isDisposed||e===this._disposable.value||(this._disposable.value=e)}dispose(){this._isDisposed=!0,this._disposable.dispose()}},t.RefCountedDisposable=class{constructor(e){this._disposable=e,this._counter=1}acquire(){return this._counter++,this}release(){return--this._counter==0&&this._disposable.dispose(),this}},t.SafeDisposable=class{constructor(){this.dispose=()=>{},this.unset=()=>{},this.isset=()=>!1,u(this)}set(e){let t=e;return this.unset=()=>t=void 0,this.isset=()=>t!==void 0,this.dispose=()=>{t&&(t(),t=void 0,d(this))},this}},t.ReferenceCollection=class{constructor(){this.references=/* @__PURE__ */ new Map}acquire(e,...t){let n=this.references.get(e);n||(n={counter:0,object:this.createReferencedObject(e,...t)},this.references.set(e,n));let{object:r}=n,i=(0,o.createSingleCallFunction)((()=>{--n.counter==0&&(this.destroyReferencedObject(e,n.object),this.references.delete(e))}));return n.counter++,{object:r,dispose:i}}},t.AsyncReferenceCollection=class{constructor(e){this.referenceCollection=e}async acquire(e,...t){let n=this.referenceCollection.acquire(e,...t);try{return{object:await n.object,dispose:()=>n.dispose()}}catch(e){throw n.dispose(),e}}},t.ImmortalReference=class{constructor(e){this.object=e}dispose(){}};class y{constructor(){this._store=/* @__PURE__ */ new Map,this._isDisposed=!1,u(this)}dispose(){d(this),this._isDisposed=!0,this.clearAndDisposeAll()}clearAndDisposeAll(){if(this._store.size)try{m(this._store.values())}finally{this._store.clear()}}has(e){return this._store.has(e)}get size(){return this._store.size}get(e){return this._store.get(e)}set(e,t,n=!1){this._isDisposed&&console.warn((/* @__PURE__ */ Error(`Trying to add a disposable to a DisposableMap that has already been disposed of. The added object will be leaked!`)).stack),n||this._store.get(e)?.dispose(),this._store.set(e,t)}deleteAndDispose(e){this._store.get(e)?.dispose(),this._store.delete(e)}deleteAndLeak(e){let t=this._store.get(e);return this._store.delete(e),t}keys(){return this._store.keys()}values(){return this._store.values()}[Symbol.iterator](){return this._store[Symbol.iterator]()}}t.DisposableMap=y},6317:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.LinkedList=void 0;class n{static{this.Undefined=new n(void 0)}constructor(e){this.element=e,this.next=n.Undefined,this.prev=n.Undefined}}class r{constructor(){this._first=n.Undefined,this._last=n.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===n.Undefined}clear(){let e=this._first;for(;e!==n.Undefined;){let t=e.next;e.prev=n.Undefined,e.next=n.Undefined,e=t}this._first=n.Undefined,this._last=n.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){let r=new n(e);if(this._first===n.Undefined)this._first=r,this._last=r;else if(t){let e=this._last;this._last=r,r.prev=e,e.next=r}else{let e=this._first;this._first=r,r.next=e,e.prev=r}this._size+=1;let i=!1;return()=>{i||(i=!0,this._remove(r))}}shift(){if(this._first!==n.Undefined){let e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==n.Undefined){let e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==n.Undefined&&e.next!==n.Undefined){let t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===n.Undefined&&e.next===n.Undefined?(this._first=n.Undefined,this._last=n.Undefined):e.next===n.Undefined?(this._last=this._last.prev,this._last.next=n.Undefined):e.prev===n.Undefined&&(this._first=this._first.next,this._first.prev=n.Undefined);--this._size}*[Symbol.iterator](){let e=this._first;for(;e!==n.Undefined;)yield e.element,e=e.next}}t.LinkedList=r},2608:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.SetMap=t.BidirectionalMap=t.CounterSet=t.Touch=void 0,t.getOrSet=function(e,t,n){let r=e.get(t);return r===void 0&&(r=n,e.set(t,r)),r},t.mapToString=function(e){let t=[];return e.forEach(((e,n)=>{t.push(`${n} => ${e}`)})),`Map(${e.size}) {${t.join(`, `)}}`},t.setToString=function(e){let t=[];return e.forEach((e=>{t.push(e)})),`Set(${e.size}) {${t.join(`, `)}}`},t.mapsStrictEqualIgnoreOrder=function(e,t){if(e===t)return!0;if(e.size!==t.size)return!1;for(let[n,r]of e)if(!t.has(n)||t.get(n)!==r)return!1;for(let[n]of t)if(!e.has(n))return!1;return!0},function(e){e[e.None=0]=`None`,e[e.AsOld=1]=`AsOld`,e[e.AsNew=2]=`AsNew`}(n||(t.Touch=n={})),t.CounterSet=class{constructor(){this.map=/* @__PURE__ */ new Map}add(e){return this.map.set(e,(this.map.get(e)||0)+1),this}delete(e){let t=this.map.get(e)||0;return t!==0&&(t--,t===0?this.map.delete(e):this.map.set(e,t),!0)}has(e){return this.map.has(e)}},t.BidirectionalMap=class{constructor(e){if(this._m1=/* @__PURE__ */ new Map,this._m2=/* @__PURE__ */ new Map,e)for(let[t,n]of e)this.set(t,n)}clear(){this._m1.clear(),this._m2.clear()}set(e,t){this._m1.set(e,t),this._m2.set(t,e)}get(e){return this._m1.get(e)}getKey(e){return this._m2.get(e)}delete(e){let t=this._m1.get(e);return t!==void 0&&(this._m1.delete(e),this._m2.delete(t),!0)}forEach(e,t){this._m1.forEach(((n,r)=>{e.call(t,n,r,this)}))}keys(){return this._m1.keys()}values(){return this._m1.values()}},t.SetMap=class{constructor(){this.map=/* @__PURE__ */ new Map}add(e,t){let n=this.map.get(e);n||(n=/* @__PURE__ */ new Set,this.map.set(e,n)),n.add(t)}delete(e,t){let n=this.map.get(e);n&&(n.delete(t),n.size===0&&this.map.delete(e))}forEach(e,t){let n=this.map.get(e);n&&n.forEach(t)}get(e){return this.map.get(e)||/* @__PURE__ */ new Set}}},7704:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SlidingWindowAverage=t.MovingAverage=t.Counter=void 0,t.clamp=function(e,t,n){return Math.min(Math.max(e,t),n)},t.rot=function(e,t){return(t+e%t)%t},t.isPointWithinTriangle=function(e,t,n,r,i,a,o,s){let c=o-n,l=s-r,u=i-n,d=a-r,f=e-n,p=t-r,m=c*c+l*l,h=c*u+l*d,g=c*f+l*p,_=u*u+d*d,v=u*f+d*p,y=1/(m*_-h*h),b=(_*g-h*v)*y,x=(m*v-h*g)*y;return b>=0&&x>=0&&b+x<1},t.Counter=class{constructor(){this._next=0}getNext(){return this._next++}},t.MovingAverage=class{constructor(){this._n=1,this._val=0}update(e){return this._val+=(e-this._val)/this._n,this._n+=1,this._val}get value(){return this._val}},t.SlidingWindowAverage=class{constructor(e){this._n=0,this._val=0,this._values=[],this._index=0,this._sum=0,this._values=Array(e),this._values.fill(0,0,e)}update(e){let t=this._values[this._index];return this._values[this._index]=e,this._index=(this._index+1)%this._values.length,this._sum-=t,this._sum+=e,this._n{Object.defineProperty(t,"__esModule",{value:!0}),t.isAndroid=t.isEdge=t.isSafari=t.isFirefox=t.isChrome=t.OS=t.OperatingSystem=t.setTimeout0=t.setTimeout0IsFaster=t.translationsConfigFile=t.platformLocale=t.locale=t.Language=t.language=t.userAgent=t.platform=t.isCI=t.isMobile=t.isIOS=t.webWorkerOrigin=t.isWebWorker=t.isWeb=t.isElectron=t.isNative=t.isLinuxSnap=t.isLinux=t.isMacintosh=t.isWindows=t.Platform=t.LANGUAGE_DEFAULT=void 0,t.PlatformToString=function(e){switch(e){case x.Web:return`Web`;case x.Mac:return`Mac`;case x.Linux:return`Linux`;case x.Windows:return`Windows`}},t.isLittleEndian=function(){if(!E){E=!0;let e=/* @__PURE__ */ new Uint8Array(2);e[0]=1,e[1]=2,T=new Uint16Array(e.buffer)[0]===513}return T},t.isBigSurOrNewer=function(e){return parseFloat(e)>=20},t.LANGUAGE_DEFAULT=`en`;let n,r,i,a=!1,o=!1,s=!1,c=!1,l=!1,u=!1,d=!1,f=!1,p=!1,m=!1,h=t.LANGUAGE_DEFAULT,g=t.LANGUAGE_DEFAULT,_=globalThis,v;_.vscode!==void 0&&_.vscode.process!==void 0?v=_.vscode.process:typeof process<`u`&&typeof process?.versions?.node==`string`&&(v=process);let y=typeof v?.versions?.electron==`string`,b=y&&v?.type===`renderer`;if(typeof v==`object`){a=v.platform===`win32`,o=v.platform===`darwin`,s=v.platform===`linux`,c=s&&!!v.env.SNAP&&!!v.env.SNAP_REVISION,d=y,p=!!v.env.CI||!!v.env.BUILD_ARTIFACTSTAGINGDIRECTORY,n=t.LANGUAGE_DEFAULT,h=t.LANGUAGE_DEFAULT;let e=v.env.VSCODE_NLS_CONFIG;if(e)try{let i=JSON.parse(e);n=i.userLocale,g=i.osLocale,h=i.resolvedLanguage||t.LANGUAGE_DEFAULT,r=i.languagePack?.translationsConfigFile}catch{}l=!0}else typeof navigator!=`object`||b?console.error(`Unable to resolve platform.`):(i=navigator.userAgent,a=i.indexOf(`Windows`)>=0,o=i.indexOf(`Macintosh`)>=0,f=(i.indexOf(`Macintosh`)>=0||i.indexOf(`iPad`)>=0||i.indexOf(`iPhone`)>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,s=i.indexOf(`Linux`)>=0,m=i?.indexOf(`Mobi`)>=0,u=!0,h=globalThis._VSCODE_NLS_LANGUAGE||t.LANGUAGE_DEFAULT,n=navigator.language.toLowerCase(),g=n);var x;(function(e){e[e.Web=0]=`Web`,e[e.Mac=1]=`Mac`,e[e.Linux=2]=`Linux`,e[e.Windows=3]=`Windows`})(x||(t.Platform=x={}));let S=x.Web;var C,w;o?S=x.Mac:a?S=x.Windows:s&&(S=x.Linux),t.isWindows=a,t.isMacintosh=o,t.isLinux=s,t.isLinuxSnap=c,t.isNative=l,t.isElectron=d,t.isWeb=u,t.isWebWorker=u&&typeof _.importScripts==`function`,t.webWorkerOrigin=t.isWebWorker?_.origin:void 0,t.isIOS=f,t.isMobile=m,t.isCI=p,t.platform=S,t.userAgent=i,t.language=h,function(e){e.value=function(){return t.language},e.isDefaultVariant=function(){return t.language.length===2?t.language===`en`:t.language.length>=3&&t.language[0]===`e`&&t.language[1]===`n`&&t.language[2]===`-`},e.isDefault=function(){return t.language===`en`}}(C||(t.Language=C={})),t.locale=n,t.platformLocale=g,t.translationsConfigFile=r,t.setTimeout0IsFaster=typeof _.postMessage==`function`&&!_.importScripts,t.setTimeout0=(()=>{if(t.setTimeout0IsFaster){let e=[];_.addEventListener(`message`,(t=>{if(t.data&&t.data.vscodeScheduleAsyncWork)for(let n=0,r=e.length;n{let r=++t;e.push({id:r,callback:n}),_.postMessage({vscodeScheduleAsyncWork:r},`*`)}}return e=>setTimeout(e)})(),function(e){e[e.Windows=1]=`Windows`,e[e.Macintosh=2]=`Macintosh`,e[e.Linux=3]=`Linux`}(w||(t.OperatingSystem=w={})),t.OS=o||f?w.Macintosh:a?w.Windows:w.Linux;let T=!0,E=!1;t.isChrome=!!(t.userAgent&&t.userAgent.indexOf(`Chrome`)>=0),t.isFirefox=!!(t.userAgent&&t.userAgent.indexOf(`Firefox`)>=0),t.isSafari=!!(!t.isChrome&&t.userAgent&&t.userAgent.indexOf(`Safari`)>=0),t.isEdge=!!(t.userAgent&&t.userAgent.indexOf(`Edg/`)>=0),t.isAndroid=!!(t.userAgent&&t.userAgent.indexOf(`Android`)>=0)},9881:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.SmoothScrollingOperation=t.SmoothScrollingUpdate=t.Scrollable=t.ScrollState=t.ScrollbarVisibility=void 0;let r=n(802),i=n(7150);var a;(function(e){e[e.Auto=1]=`Auto`,e[e.Hidden=2]=`Hidden`,e[e.Visible=3]=`Visible`})(a||(t.ScrollbarVisibility=a={}));class o{constructor(e,t,n,r,i,a,o){this._forceIntegerValues=e,this._scrollStateBrand=void 0,this._forceIntegerValues&&(t|=0,n|=0,r|=0,i|=0,a|=0,o|=0),this.rawScrollLeft=r,this.rawScrollTop=o,t<0&&(t=0),r+t>n&&(r=n-t),r<0&&(r=0),i<0&&(i=0),o+i>a&&(o=a-i),o<0&&(o=0),this.width=t,this.scrollWidth=n,this.scrollLeft=r,this.height=i,this.scrollHeight=a,this.scrollTop=o}equals(e){return this.rawScrollLeft===e.rawScrollLeft&&this.rawScrollTop===e.rawScrollTop&&this.width===e.width&&this.scrollWidth===e.scrollWidth&&this.scrollLeft===e.scrollLeft&&this.height===e.height&&this.scrollHeight===e.scrollHeight&&this.scrollTop===e.scrollTop}withScrollDimensions(e,t){return new o(this._forceIntegerValues,e.width===void 0?this.width:e.width,e.scrollWidth===void 0?this.scrollWidth:e.scrollWidth,t?this.rawScrollLeft:this.scrollLeft,e.height===void 0?this.height:e.height,e.scrollHeight===void 0?this.scrollHeight:e.scrollHeight,t?this.rawScrollTop:this.scrollTop)}withScrollPosition(e){return new o(this._forceIntegerValues,this.width,this.scrollWidth,e.scrollLeft===void 0?this.rawScrollLeft:e.scrollLeft,this.height,this.scrollHeight,e.scrollTop===void 0?this.rawScrollTop:e.scrollTop)}createScrollEvent(e,t){let n=this.width!==e.width,r=this.scrollWidth!==e.scrollWidth,i=this.scrollLeft!==e.scrollLeft,a=this.height!==e.height,o=this.scrollHeight!==e.scrollHeight,s=this.scrollTop!==e.scrollTop;return{inSmoothScrolling:t,oldWidth:e.width,oldScrollWidth:e.scrollWidth,oldScrollLeft:e.scrollLeft,width:this.width,scrollWidth:this.scrollWidth,scrollLeft:this.scrollLeft,oldHeight:e.height,oldScrollHeight:e.scrollHeight,oldScrollTop:e.scrollTop,height:this.height,scrollHeight:this.scrollHeight,scrollTop:this.scrollTop,widthChanged:n,scrollWidthChanged:r,scrollLeftChanged:i,heightChanged:a,scrollHeightChanged:o,scrollTopChanged:s}}}t.ScrollState=o;class s extends i.Disposable{constructor(e){super(),this._scrollableBrand=void 0,this._onScroll=this._register(new r.Emitter),this.onScroll=this._onScroll.event,this._smoothScrollDuration=e.smoothScrollDuration,this._scheduleAtNextAnimationFrame=e.scheduleAtNextAnimationFrame,this._state=new o(e.forceIntegerValues,0,0,0,0,0,0),this._smoothScrolling=null}dispose(){this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),super.dispose()}setSmoothScrollDuration(e){this._smoothScrollDuration=e}validateScrollPosition(e){return this._state.withScrollPosition(e)}getScrollDimensions(){return this._state}setScrollDimensions(e,t){let n=this._state.withScrollDimensions(e,t);this._setState(n,!!this._smoothScrolling),this._smoothScrolling?.acceptScrollDimensions(this._state)}getFutureScrollPosition(){return this._smoothScrolling?this._smoothScrolling.to:this._state}getCurrentScrollPosition(){return this._state}setScrollPositionNow(e){let t=this._state.withScrollPosition(e);this._smoothScrolling&&=(this._smoothScrolling.dispose(),null),this._setState(t,!1)}setScrollPositionSmooth(e,t){if(this._smoothScrollDuration===0)return this.setScrollPositionNow(e);if(this._smoothScrolling){e={scrollLeft:e.scrollLeft===void 0?this._smoothScrolling.to.scrollLeft:e.scrollLeft,scrollTop:e.scrollTop===void 0?this._smoothScrolling.to.scrollTop:e.scrollTop};let n=this._state.withScrollPosition(e);if(this._smoothScrolling.to.scrollLeft===n.scrollLeft&&this._smoothScrolling.to.scrollTop===n.scrollTop)return;let r;r=t?new u(this._smoothScrolling.from,n,this._smoothScrolling.startTime,this._smoothScrolling.duration):this._smoothScrolling.combine(this._state,n,this._smoothScrollDuration),this._smoothScrolling.dispose(),this._smoothScrolling=r}else{let t=this._state.withScrollPosition(e);this._smoothScrolling=u.start(this._state,t,this._smoothScrollDuration)}this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame((()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())}))}hasPendingScrollAnimation(){return!!this._smoothScrolling}_performSmoothScrolling(){if(!this._smoothScrolling)return;let e=this._smoothScrolling.tick(),t=this._state.withScrollPosition(e);this._setState(t,!0),this._smoothScrolling&&(e.isDone?(this._smoothScrolling.dispose(),this._smoothScrolling=null):this._smoothScrolling.animationFrameDisposable=this._scheduleAtNextAnimationFrame((()=>{this._smoothScrolling&&(this._smoothScrolling.animationFrameDisposable=null,this._performSmoothScrolling())})))}_setState(e,t){let n=this._state;n.equals(e)||(this._state=e,this._onScroll.fire(this._state.createScrollEvent(n,t)))}}t.Scrollable=s;class c{constructor(e,t,n){this.scrollLeft=e,this.scrollTop=t,this.isDone=n}}function l(e,t){let n=t-e;return function(t){return e+n*(1-(r=1-t,r**3));var r}}t.SmoothScrollingUpdate=c;class u{constructor(e,t,n,r){this.from=e,this.to=t,this.duration=r,this.startTime=n,this.animationFrameDisposable=null,this._initAnimations()}_initAnimations(){this.scrollLeft=this._initAnimation(this.from.scrollLeft,this.to.scrollLeft,this.to.width),this.scrollTop=this._initAnimation(this.from.scrollTop,this.to.scrollTop,this.to.height)}_initAnimation(e,t,n){if(Math.abs(e-t)>2.5*n){let o,s;return e{Object.defineProperty(t,"__esModule",{value:!0}),t.StopWatch=void 0;let n=globalThis.performance&&typeof globalThis.performance.now==`function`;class r{static create(e){return new r(e)}constructor(e){this._now=n&&!1===e?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=this._now(),this._stopTime=-1}elapsed(){return this._stopTime===-1?this._now()-this._startTime:this._stopTime-this._startTime}}t.StopWatch=r},1316:(e,t,n)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.noBreakWhitespace=t.CodePointIterator=void 0,t.isFalsyOrWhitespace=function(e){return!e||typeof e!=`string`||e.trim().length===0},t.format=function(e,...t){return t.length===0?e:e.replace(a,(function(e,n){let r=parseInt(n,10);return isNaN(r)||r<0||r>=t.length?e:t[r]}))},t.format2=function(e,t){return Object.keys(t).length===0?e:e.replace(o,((e,n)=>t[n]??e))},t.htmlAttributeEncodeValue=function(e){return e.replace(/[<>"'&]/g,(e=>{switch(e){case`<`:return`<`;case`>`:return`>`;case`"`:return`"`;case`'`:return`'`;case`&`:return`&`}return e}))},t.escape=function(e){return e.replace(/[<>&]/g,(function(e){switch(e){case`<`:return`<`;case`>`:return`>`;case`&`:return`&`;default:return e}}))},t.escapeRegExpCharacters=s,t.count=function(e,t){let n=0,r=e.indexOf(t);for(;r!==-1;)n++,r=e.indexOf(t,r+t.length);return n},t.truncate=function(e,t,n=`…`){return e.length<=t?e:`${e.substr(0,t)}${n}`},t.truncateMiddle=function(e,t,n=`…`){if(e.length<=t)return e;let r=Math.ceil(t/2)-n.length/2,i=Math.floor(t/2)-n.length/2;return`${e.substr(0,r)}${n}${e.substr(e.length-i)}`},t.trim=function(e,t=` `){return l(c(e,t),t)},t.ltrim=c,t.rtrim=l,t.convertSimple2RegExpPattern=function(e){return e.replace(/[\-\\\{\}\+\?\|\^\$\.\,\[\]\(\)\#\s]/g,`\\$&`).replace(/[\*]/g,`.*`)},t.stripWildcards=function(e){return e.replace(/\*/g,``)},t.createRegExp=function(e,t,n={}){if(!e)throw Error(`Cannot create regex from empty string`);t||(e=s(e)),n.wholeWord&&(/\B/.test(e.charAt(0))||(e=`\\b`+e),/\B/.test(e.charAt(e.length-1))||(e+=`\\b`));let r=``;return n.global&&(r+=`g`),n.matchCase||(r+=`i`),n.multiline&&(r+=`m`),n.unicode&&(r+=`u`),new RegExp(e,r)},t.regExpLeadsToEndlessLoop=function(e){return e.source!==`^`&&e.source!==`^$`&&e.source!==`$`&&e.source!==`^\\s*$`&&!(!e.exec(``)||e.lastIndex!==0)},t.splitLines=function(e){return e.split(/\r\n|\r|\n/)},t.splitLinesIncludeSeparators=function(e){let t=[],n=e.split(/(\r\n|\r|\n)/);for(let e=0;e=0;n--){let t=e.charCodeAt(n);if(t!==r.CharCode.Space&&t!==r.CharCode.Tab)return n}return-1},t.replaceAsync=function(e,t,n){let r=[],i=0;for(let a of e.matchAll(t)){if(r.push(e.slice(i,a.index)),a.index===void 0)throw Error(`match.index should be defined`);i=a.index+a[0].length,r.push(n(a[0],...a.slice(1),a.index,e,a.groups))}return r.push(e.slice(i)),Promise.all(r).then((e=>e.join(``)))},t.compare=function(e,t){return et)},t.compareSubstring=u,t.compareIgnoreCase=function(e,t){return d(e,t,0,e.length,0,t.length)},t.compareSubstringIgnoreCase=d,t.isAsciiDigit=function(e){return e>=r.CharCode.Digit0&&e<=r.CharCode.Digit9},t.isLowerAsciiLetter=f,t.isUpperAsciiLetter=function(e){return e>=r.CharCode.A&&e<=r.CharCode.Z},t.equalsIgnoreCase=function(e,t){return e.length===t.length&&d(e,t)===0},t.startsWithIgnoreCase=function(e,t){let n=t.length;return!(t.length>e.length)&&d(e,t,0,n)===0},t.commonPrefixLength=function(e,t){let n=Math.min(e.length,t.length),r=0;for(;ra)return 1}let o=r-n,s=a-i;return os)}function d(e,t,n=0,r=e.length,i=0,a=t.length){for(;n=128||s>=128)return u(e.toLowerCase(),t.toLowerCase(),n,r,i,a);f(o)&&(o-=32),f(s)&&(s-=32);let c=o-s;if(c!==0)return c}let o=r-n,s=a-i;return os)}function f(e){return e>=r.CharCode.a&&e<=r.CharCode.z}function p(e){return 55296<=e&&e<=56319}function m(e){return 56320<=e&&e<=57343}function h(e,t){return t-56320+(e-55296<<10)+65536}function g(e,t,n){let r=e.charCodeAt(n);if(p(r)&&n+11){let r=e.charCodeAt(t-2);if(p(r))return h(r,n)}return n}(this._str,this._offset);return this._offset-=e>=i.Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN?2:1,e}nextCodePoint(){let e=g(this._str,this._len,this._offset);return this._offset+=e>=i.Constants.UNICODE_SUPPLEMENTARY_PLANE_BEGIN?2:1,e}eol(){return this._offset>=this._len}},t.noBreakWhitespace=`\xA0`},5015:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.MicrotaskDelay=void 0,t.MicrotaskDelay=Symbol(`MicrotaskDelay`)},8960:(e,t)=>{var n;Object.defineProperty(t,"__esModule",{value:!0}),t.Constants=void 0,t.toUint8=function(e){return e<0?0:e>n.MAX_UINT_8?n.MAX_UINT_8:0|e},t.toUint32=function(e){return e<0?0:e>n.MAX_UINT_32?n.MAX_UINT_32:0|e},function(e){e[e.MAX_SAFE_SMALL_INTEGER=1073741824]=`MAX_SAFE_SMALL_INTEGER`,e[e.MIN_SAFE_SMALL_INTEGER=-1073741824]=`MIN_SAFE_SMALL_INTEGER`,e[e.MAX_UINT_8=255]=`MAX_UINT_8`,e[e.MAX_UINT_16=65535]=`MAX_UINT_16`,e[e.MAX_UINT_32=4294967295]=`MAX_UINT_32`,e[e.UNICODE_SUPPLEMENTARY_PLANE_BEGIN=65536]=`UNICODE_SUPPLEMENTARY_PLANE_BEGIN`}(n||(t.Constants=n={}))}},t={};function n(r){var i=t[r];if(i!==void 0)return i.exports;var a=t[r]={exports:{}};return e[r].call(a.exports,a,a.exports,n),a.exports}var r={};return(()=>{var e=r;Object.defineProperty(e,"__esModule",{value:!0}),e.Terminal=void 0;let t=n(7721),i=n(1718),a=n(7150),o=n(3027),s=n(5101),c=n(6097),l=n(4335),u=[`cols`,`rows`],d=0;class f extends a.Disposable{constructor(e){super(),this._core=this._register(new i.CoreBrowserTerminal(e)),this._addonManager=this._register(new o.AddonManager),this._publicOptions={...this._core.options};let t=e=>this._core.options[e],n=(e,t)=>{this._checkReadonlyOptions(e),this._core.options[e]=t};for(let e in this._core.options){let r={get:t.bind(this,e),set:n.bind(this,e)};Object.defineProperty(this._publicOptions,e,r)}}_checkReadonlyOptions(e){if(u.includes(e))throw Error(`Option "${e}" can only be set in the constructor`)}_checkProposedApi(){if(!this._core.optionsService.rawOptions.allowProposedApi)throw Error(`You must set the allowProposedApi option to true to use proposed API`)}get onBell(){return this._core.onBell}get onBinary(){return this._core.onBinary}get onCursorMove(){return this._core.onCursorMove}get onData(){return this._core.onData}get onKey(){return this._core.onKey}get onLineFeed(){return this._core.onLineFeed}get onRender(){return this._core.onRender}get onResize(){return this._core.onResize}get onScroll(){return this._core.onScroll}get onSelectionChange(){return this._core.onSelectionChange}get onTitleChange(){return this._core.onTitleChange}get onWriteParsed(){return this._core.onWriteParsed}get element(){return this._core.element}get parser(){return this._parser||=new c.ParserApi(this._core),this._parser}get unicode(){return this._checkProposedApi(),new l.UnicodeApi(this._core)}get textarea(){return this._core.textarea}get rows(){return this._core.rows}get cols(){return this._core.cols}get buffer(){return this._buffer||=this._register(new s.BufferNamespaceApi(this._core)),this._buffer}get markers(){return this._checkProposedApi(),this._core.markers}get modes(){let e=this._core.coreService.decPrivateModes,t=`none`;switch(this._core.coreMouseService.activeProtocol){case`X10`:t=`x10`;break;case`VT200`:t=`vt200`;break;case`DRAG`:t=`drag`;break;case`ANY`:t=`any`}return{applicationCursorKeysMode:e.applicationCursorKeys,applicationKeypadMode:e.applicationKeypad,bracketedPasteMode:e.bracketedPasteMode,insertMode:this._core.coreService.modes.insertMode,mouseTrackingMode:t,originMode:e.origin,reverseWraparoundMode:e.reverseWraparound,sendFocusMode:e.sendFocus,synchronizedOutputMode:e.synchronizedOutput,wraparoundMode:e.wraparound}}get options(){return this._publicOptions}set options(e){for(let t in e)this._publicOptions[t]=e[t]}blur(){this._core.blur()}focus(){this._core.focus()}input(e,t=!0){this._core.input(e,t)}resize(e,t){this._verifyIntegers(e,t),this._core.resize(e,t)}open(e){this._core.open(e)}attachCustomKeyEventHandler(e){this._core.attachCustomKeyEventHandler(e)}attachCustomWheelEventHandler(e){this._core.attachCustomWheelEventHandler(e)}registerLinkProvider(e){return this._core.registerLinkProvider(e)}registerCharacterJoiner(e){return this._checkProposedApi(),this._core.registerCharacterJoiner(e)}deregisterCharacterJoiner(e){this._checkProposedApi(),this._core.deregisterCharacterJoiner(e)}registerMarker(e=0){return this._verifyIntegers(e),this._core.registerMarker(e)}registerDecoration(e){return this._checkProposedApi(),this._verifyPositiveIntegers(e.x??0,e.width??0,e.height??0),this._core.registerDecoration(e)}hasSelection(){return this._core.hasSelection()}select(e,t,n){this._verifyIntegers(e,t,n),this._core.select(e,t,n)}getSelection(){return this._core.getSelection()}getSelectionPosition(){return this._core.getSelectionPosition()}clearSelection(){this._core.clearSelection()}selectAll(){this._core.selectAll()}selectLines(e,t){this._verifyIntegers(e,t),this._core.selectLines(e,t)}dispose(){super.dispose()}scrollLines(e){this._verifyIntegers(e),this._core.scrollLines(e)}scrollPages(e){this._verifyIntegers(e),this._core.scrollPages(e)}scrollToTop(){this._core.scrollToTop()}scrollToBottom(){this._core.scrollToBottom()}scrollToLine(e){this._verifyIntegers(e),this._core.scrollToLine(e)}clear(){this._core.clear()}write(e,t){this._core.write(e,t)}writeln(e,t){this._core.write(e),this._core.write(`\r +`,t)}paste(e){this._core.paste(e)}refresh(e,t){this._verifyIntegers(e,t),this._core.refresh(e,t)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(e){this._addonManager.loadAddon(this,e)}static get strings(){return{get promptLabel(){return t.promptLabel.get()},set promptLabel(e){t.promptLabel.set(e)},get tooMuchOutput(){return t.tooMuchOutput.get()},set tooMuchOutput(e){t.tooMuchOutput.set(e)}}}_verifyIntegers(...e){for(d of e)if(d===1/0||isNaN(d)||d%1!=0)throw Error(`This API only accepts integers`)}_verifyPositiveIntegers(...e){for(d of e)if(d&&(d===1/0||isNaN(d)||d%1!=0||d<0))throw Error(`This API only accepts positive integers`)}}e.Terminal=f})(),r})()))})),g=/* @__PURE__ */ l(((e,t)=>{(function(n,r){typeof e==`object`&&typeof t==`object`?t.exports=r():typeof define==`function`&&define.amd?define([],r):typeof e==`object`?e.FitAddon=r():n.FitAddon=r()})(globalThis,(()=>(()=>{"use strict";var e={};return(()=>{var t=e;Object.defineProperty(t,"__esModule",{value:!0}),t.FitAddon=void 0,t.FitAddon=class{activate(e){this._terminal=e}dispose(){}fit(){let e=this.proposeDimensions();if(!e||!this._terminal||isNaN(e.cols)||isNaN(e.rows))return;let t=this._terminal._core;this._terminal.rows===e.rows&&this._terminal.cols===e.cols||(t._renderService.clear(),this._terminal.resize(e.cols,e.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;let e=this._terminal._core._renderService.dimensions;if(e.css.cell.width===0||e.css.cell.height===0)return;let t=this._terminal.options.scrollback===0?0:this._terminal.options.overviewRuler?.width||14,n=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(n.getPropertyValue(`height`)),i=Math.max(0,parseInt(n.getPropertyValue(`width`))),a=window.getComputedStyle(this._terminal.element),o=r-(parseInt(a.getPropertyValue(`padding-top`))+parseInt(a.getPropertyValue(`padding-bottom`))),s=i-(parseInt(a.getPropertyValue(`padding-right`))+parseInt(a.getPropertyValue(`padding-left`)))-t;return{cols:Math.max(2,Math.floor(s/e.css.cell.width)),rows:Math.max(1,Math.floor(o/e.css.cell.height))}}}})(),e})()))})),_=h(),v=g();function y({controller:e,visible:t,status:n}){let r=f.default.useRef(null),i=f.default.useRef(null),a=f.default.useRef(null);return f.default.useEffect(()=>{let t=r.current,n=new _.Terminal({cursorBlink:!0,scrollback:3e3,fontSize:13,fontFamily:`ui-monospace, SFMono-Regular, Menlo, monospace`,theme:{background:`#141414`,foreground:`#e5e5e5`},allowProposedApi:!1}),o=new v.FitAddon;n.loadAddon(o),n.open(t),i.current=n,e.terminal=n,a.current=o;let s=n.onData(t=>e.sendRaw(t)),c=n.onBinary(t=>{e.sendFrame({type:`binary`,data:Array.from(t,e=>e.charCodeAt(0))})}),l=n.onResize(({cols:t,rows:n})=>e.resize(t,n)),u=e.subscribeOutput(e=>n.write(e)),d=t=>{t.type===`keydown`&&[`Shift`,`Control`,`Alt`,`Meta`,`CapsLock`].includes(t.key)||[`pointerdown`,`wheel`].includes(t.type)&&n.modes.mouseTrackingMode===`none`||e.markActivity()},f=[`keydown`,`paste`,`beforeinput`,`compositionend`,`pointerdown`,`wheel`];for(let e of f)t.addEventListener(e,d,!0);let p,m=new ResizeObserver(()=>{cancelAnimationFrame(p),p=requestAnimationFrame(()=>{t.clientWidth&&t.clientHeight&&o.fit()})});return m.observe(t),()=>{m.disconnect(),cancelAnimationFrame(p);for(let e of f)t.removeEventListener(e,d,!0);u(),s.dispose(),c.dispose(),l.dispose(),i.current=null,e.terminal===n&&(e.terminal=null),a.current=null,n.dispose()}},[e]),f.default.useEffect(()=>{let o=i.current;if(!o||(o.options.disableStdin=n!==`open`,!t))return;let s=requestAnimationFrame(()=>{r.current?.clientWidth&&r.current?.clientHeight&&(a.current?.fit(),n===`open`&&(e.resize(o.cols,o.rows),o.focus()))});return()=>cancelAnimationFrame(s)},[e,t,n]),f.default.createElement(`div`,{ref:r,"data-terminal-view":``,style:{display:t?`block`:`none`,flex:`1 1 0`,minHeight:0,minWidth:0,overflow:`hidden`}})}let b=`/shell-term-rpc`;var x=class{constructor(e,t){this.connection=e,this.sessionId=t,this.ws=null,this.streamId=null,this.transcript=``,this.outputListeners=/* @__PURE__ */ new Set,this.generation=0,this.disposed=!1,this.activitySent=!1,this.closing=null,this.previewRequest=0,this.historyRequest=0,this.state=(0,m.createSnapshotStore)({status:`closed`,tab:`live`,epoch:0,x:null,y:null,width:640,height:440,history:{entries:[],loading:!1,error:null},preview:null,pendingSelectPath:null,error:null})}async call(e,t={}){return this.connection.rpc.call(b,e,{sessionId:this.sessionId,...t},void 0)}async open(){if(this.disposed||![`closed`,`ended`].includes(this.state.getSnapshot().status))return;let e=++this.generation;this.closeWs(),this.transcript=``,this.activitySent=!1,this.setState({status:`opening`,tab:`live`,epoch:e,error:null,preview:null,pendingSelectPath:null});try{let t=await this.call(`open`);if(!t?.ok)throw Error(t?.error?.message||`open failed`);let{streamId:n}=t.value;if(this.disposed||e!==this.generation){await this.call(`close`,{streamId:n});return}this.streamId=n,this.connectWs(e)}catch(t){e===this.generation&&this.fail(t)}}connectWs(e){let t=location.protocol===`https:`?`wss:`:`ws:`,n=new URLSearchParams({sessionId:this.sessionId,streamId:this.streamId,protocol:`2`}),r=new WebSocket(`${t}//${location.host}/shell-term/ws?${n}`);this.ws=r;let i=()=>!this.disposed&&e===this.generation&&this.ws===r;r.onopen=()=>{i()&&this.setState({status:`open`})},r.onmessage=e=>{if(!i())return;let t;try{t=JSON.parse(e.data)}catch{this.fail(`Invalid terminal stream`);return}if(typeof t!=`object`||!t)this.fail(`Invalid terminal stream`);else if(t.type===`output`&&typeof t.data==`string`){if(this.transcript+=t.data,this.transcript.length>65536){let e=this.transcript.length-65536;this.transcript.charCodeAt(e)>=56320&&this.transcript.charCodeAt(e)<=57343&&e++,this.transcript=this.transcript.slice(e)}for(let e of this.outputListeners)e(t.data)}else t.type===`exit`&&this.exit()},r.onerror=()=>{i()&&this.fail(`终端连接失败,请结束会话后重新打开。`)},r.onclose=()=>{i()&&(this.ws=null,[`closed`,`ended`,`exiting`].includes(this.state.getSnapshot().status)||this.fail(`终端连接已断开,请结束会话后重新打开。`))}}subscribeOutput(e){return this.transcript&&e(this.transcript),this.outputListeners.add(e),()=>this.outputListeners.delete(e)}sendFrame(e){this.state.getSnapshot().status===`open`&&this.ws?.readyState===1&&this.ws.send(JSON.stringify(e))}markActivity(){this.activitySent||this.state.getSnapshot().status!==`open`||(this.sendFrame({type:`activity`}),this.activitySent=!0)}sendRaw(e){this.sendFrame({type:`input`,data:e})}async resize(e,t){if(this.state.getSnapshot().status!==`open`)return;let n=this.generation;try{let r=await this.call(`resize`,{streamId:this.streamId,cols:e,rows:t});if(!r?.ok&&r?.error?.code===`terminal-ended`)return;!r?.ok&&n===this.generation&&this.state.getSnapshot().status===`open`&&this.fail(r?.error?.message||`Terminal resize failed`)}catch(e){n===this.generation&&this.state.getSnapshot().status===`open`&&this.fail(e)}}exit({dismiss:e=!1}={}){if(this.closing)return this.closing;if(!this.streamId)return this.closeWs(),e&&this.setState({status:`closed`}),Promise.resolve();let t=this.generation,n=this.streamId;return this.setState({status:`exiting`}),this.closing=(async()=>{try{let r=await this.call(`close`,{streamId:n});if(!r?.ok&&r?.error?.code===`terminal-stale`){if(t!==this.generation)return;this.closeWs(),this.streamId=null,this.setState({status:`closed`,error:null});return}if(!r?.ok)throw Error(r?.error?.message||`close failed`);if(t!==this.generation)return;this.closeWs(),this.streamId=null;let{transcriptPath:i}=r.value;this.setState({status:e||!i?`closed`:`ended`,tab:`history`,preview:null,pendingSelectPath:i,error:null})}catch(e){t===this.generation&&this.fail(e)}finally{this.closing=null}})(),this.closing}dismiss(){return this.exit({dismiss:!0})}closeWs(){let e=this.ws;if(this.ws=null,e){e.onopen=e.onmessage=e.onclose=e.onerror=null;try{e.close()}catch{}}}dispose(){this.disposed||(this.disposed=!0,++this.generation,++this.previewRequest,++this.historyRequest,this.closeWs(),this.outputListeners.clear(),this.streamId&&!this.closing&&this.call(`close`,{streamId:this.streamId}).catch(()=>{}),this.streamId=null)}fail(e){this.closeWs(),this.setState({status:`error`,error:e instanceof Error?e.message:String(e)})}setState(e){e.preview===null&&++this.previewRequest,this.disposed||this.state.set({...this.state.getSnapshot(),...e})}setGeometry(e){this.setState(e)}setTab(e){++this.previewRequest,this.setState({tab:e,preview:null})}loadHistory(){let e=++this.historyRequest;this.setState({history:{...this.state.getSnapshot().history,loading:!0,error:null}}),this.connection.rpc.call(b,`historyList`,{sessionId:this.sessionId},void 0).then(t=>{e===this.historyRequest&&(t===void 0||!t.ok?this.setState({history:{entries:[],loading:!1,error:t&&t.error?t.error.message:`load failed`}}):this.setState({history:{entries:t.value.entries,loading:!1,error:null}}))}).catch(t=>{e===this.historyRequest&&this.setState({history:{entries:[],loading:!1,error:t instanceof Error?t.message:String(t)}})})}togglePreview(e){let t=++this.previewRequest,n=this.state.getSnapshot().preview;n!==null&&n.path===e?this.setState({preview:null}):(this.setState({preview:{path:e,transcript:null,loading:!0}}),this.connection.rpc.call(b,`historyRead`,{sessionId:this.sessionId,path:e},void 0).then(n=>{t===this.previewRequest&&(n===void 0||!n.ok?this.setState({preview:{path:e,transcript:n&&n.error?n.error.message:`read failed`,loading:!1}}):this.setState({preview:{path:e,transcript:n.value.transcript,loading:!1}}))}).catch(n=>{t===this.previewRequest&&this.setState({preview:{path:e,transcript:n instanceof Error?n.message:String(n),loading:!1}})}))}referenceInject(e,t){return this.connection.rpc.call(b,`historyInject`,{sessionId:this.sessionId,paths:e,notes:t||``},void 0).then(e=>{if(e===void 0||!e.ok)throw Error(e&&e.error?e.error.message:`reference-inject failed`);return e.value})}};function S(e,t,n){return Math.max(t,Math.min(e,n))}let C=[`#2e2e2e`,`#d64545`,`#2e9e4f`,`#c9a227`,`#3b7dd8`,`#9a4ec2`,`#1fa8a0`,`#d8d8d8`],w=[`#555555`,`#ff6b6b`,`#3ddc84`,`#f0d264`,`#6aa5f8`,`#c086e8`,`#3dd0c8`,`#ffffff`];function T(e,t){let n=e.replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g,``),r=/\x1b\[([0-9;?]*[ -/]*)([@-~])/g,i=[],a=0,o=null,s=!1,c=0,l=(e,n,r)=>{if(e.length===0)return;let a={};n!==null&&(a.color=n),r&&(a.fontWeight=`bold`),i.push(f.default.createElement(`span`,{key:`${t}-${c++}`,style:a},e))},u;for(;(u=r.exec(n))!==null;){if(u.index>a&&l(n.slice(a,u.index),o,s),u[2]!==`m`){a=r.lastIndex;continue}let e=u[1],t=e===``?[0]:e.split(`;`).map(e=>Number(e)).filter(e=>!Number.isNaN(e));for(let e of t)e===0?(o=null,s=!1):e===1?s=!0:e===22?s=!1:e>=30&&e<=37?o=C[e-30]:e>=90&&e<=97?o=w[e-90]:e===39&&(o=null);a=r.lastIndex}return a({appearance:`none`,border:`none`,borderBottom:e?`2px solid var(--dsw-alias-state-business-primary, var(--color-accent, #3b7dd8))`:`2px solid transparent`,background:`transparent`,color:e?`inherit`:`var(--dsw-alias-label-secondary, #aaaaaa)`,cursor:`pointer`,fontSize:12,fontWeight:e?700:400,padding:`4px 2px`}),j={overflow:`auto`,whiteSpace:`pre-wrap`,wordBreak:`break-all`,flex:`1 1 auto`,minHeight:60,padding:6,borderRadius:6,background:`var(--dsw-alias-bg-module-platform, rgba(0,0,0,.35))`,lineHeight:1.45},M={appearance:`none`,border:`1px solid color-mix(in srgb, currentColor 24%, transparent)`,borderRadius:7,padding:`3px 10px`,background:`transparent`,color:`inherit`,cursor:`pointer`,fontSize:12},N={flex:1,background:`transparent`,color:`inherit`,border:`1px solid #555`,borderRadius:6,padding:`4px 8px`,fontFamily:`inherit`,fontSize:13},P={position:`absolute`,right:0,bottom:0,width:16,height:16,cursor:`nwse-resize`,background:`linear-gradient(135deg, transparent 50%, color-mix(in srgb, currentColor 35%, transparent) 50%)`},F={display:`flex`,flexDirection:`column`,gap:4,padding:`6px 8px`,borderRadius:6,border:`1px solid color-mix(in srgb, currentColor 14%, transparent)`},I={display:`flex`,alignItems:`center`,gap:8},L=e=>({fontSize:11,padding:`1px 6px`,borderRadius:999,background:e===`warn`?`color-mix(in srgb, #e0b95e 30%, transparent)`:`color-mix(in srgb, currentColor 14%, transparent)`});function R(e,t){let n=f.default.useRef(null);return f.default.useEffect(()=>{let r=r=>{if(n.current===null)return;let{startX:i,startY:a,originX:o,originY:s}=n.current,c=t.width,l=t.height,u=S(o+(r.clientX-i),0,Math.max(0,window.innerWidth-c)),d=S(s+(r.clientY-a),0,Math.max(0,window.innerHeight-l));e.setGeometry({x:u,y:d})},i=()=>{n.current=null};return window.addEventListener(`mousemove`,r),window.addEventListener(`mouseup`,i),()=>{window.removeEventListener(`mousemove`,r),window.removeEventListener(`mouseup`,i)}},[e,t.width,t.height]),e=>{if(e.button!==0)return;let t=e.currentTarget.parentElement.getBoundingClientRect();n.current={startX:e.clientX,startY:e.clientY,originX:t.left,originY:t.top},e.preventDefault()}}function z(e,t){let n=f.default.useRef(null);return f.default.useEffect(()=>{let r=r=>{if(n.current===null)return;let{startX:i,startY:a,startWidth:o,startHeight:s}=n.current,c=Math.max(340,window.innerWidth-(t.x??0)),l=Math.max(220,window.innerHeight-(t.y??0)),u=S(o+(r.clientX-i),340,c),d=S(s+(r.clientY-a),220,l);e.setGeometry({width:u,height:d})},i=()=>{n.current=null};return window.addEventListener(`mousemove`,r),window.addEventListener(`mouseup`,i),()=>{window.removeEventListener(`mousemove`,r),window.removeEventListener(`mouseup`,i)}},[e,t.x,t.y]),e=>{e.button===0&&(n.current={startX:e.clientX,startY:e.clientY,startWidth:t.width,startHeight:t.height},e.preventDefault(),e.stopPropagation())}}function B(e){return e==null?null:e===0?f.default.createElement(`span`,{style:L(`ok`)},`退出码 0`):f.default.createElement(`span`,{style:L(`warn`)},`退出码 ${e}`)}function V({controller:e,state:t}){let{entries:n,loading:r,error:i}=t.history,[a,o]=f.default.useState(()=>t.pendingSelectPath?/* @__PURE__ */ new Set([t.pendingSelectPath]):/* @__PURE__ */ new Set),[s,c]=f.default.useState(``),[l,u]=f.default.useState(null);f.default.useEffect(()=>{e.loadHistory()},[e]),f.default.useEffect(()=>{t.pendingSelectPath&&e.togglePreview(t.pendingSelectPath)},[t.pendingSelectPath,e]);let d=e=>{o(t=>{let n=new Set(t);return n.has(e)?n.delete(e):n.add(e),n})},p=()=>{let t=Array.from(a);t.length!==0&&(u(null),e.referenceInject(t,s).then(e=>{u({kind:`ok`,text:`已引用 ${e.referenced} 段历史记录,模型正在分析…`}),o(/* @__PURE__ */ new Set),c(``)}).catch(e=>u({kind:`error`,text:e instanceof Error?e.message:String(e)})))};return r&&n.length===0?f.default.createElement(`div`,{style:{opacity:.7}},`正在加载历史记录…`):i===null?n.length===0?f.default.createElement(`div`,{style:{opacity:.7}},`暂无历史终端记录。`):f.default.createElement(`div`,{style:{display:`flex`,flexDirection:`column`,gap:8,minHeight:0,flex:`1 1 auto`,overflow:`auto`}},f.default.createElement(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6,overflow:`auto`}},n.map(n=>{let r=t.preview!==null&&t.preview.path===n.path;return f.default.createElement(`div`,{key:n.path,style:F},f.default.createElement(`div`,{style:I},f.default.createElement(`input`,{type:`checkbox`,checked:a.has(n.path),onChange:()=>d(n.path)}),f.default.createElement(`span`,{style:{flex:`1 1 auto`,fontSize:12}},new Date(n.timestamp).toLocaleString()),B(n.exitCode),n.truncated?f.default.createElement(`span`,{style:L(`warn`)},`已截断`):null,f.default.createElement(`button`,{type:`button`,style:{...M,padding:`2px 8px`},onClick:()=>e.togglePreview(n.path)},r?`收起`:`查看`)),r?f.default.createElement(`div`,{style:{...j,maxHeight:160,flex:`0 0 auto`}},t.preview.loading?`正在读取…`:T(t.preview.transcript||``,n.path)):null)})),f.default.createElement(`div`,{style:{display:`flex`,flexDirection:`column`,gap:6,flex:`0 0 auto`,borderTop:`1px solid color-mix(in srgb, currentColor 14%, transparent)`,paddingTop:8}},f.default.createElement(`textarea`,{value:s,placeholder:`(可选)已选中多段记录时,可在此补充自然语言说明…`,onChange:e=>c(e.target.value),style:{...N,minHeight:40,resize:`vertical`,fontFamily:`inherit`}}),f.default.createElement(`div`,{style:{fontSize:11,opacity:.6,marginTop:-2}},`提示:不输入时的默认消息为「请帮我分别分析这些历史终端记录。」`),f.default.createElement(`div`,{style:{display:`flex`,alignItems:`center`,gap:8}},f.default.createElement(`button`,{type:`button`,style:M,disabled:a.size===0,onClick:p},a.size>1?`引用并分析 (${a.size} 段)`:`引用并分析`),t.status===`ended`||t.status===`error`?f.default.createElement(`button`,{type:`button`,style:M,onClick:()=>e.dismiss()},`直接退出,本次不分析`):null,l===null?null:f.default.createElement(`span`,{style:{fontSize:12,color:l.kind===`error`?`var(--color-error, #e06c75)`:`inherit`,opacity:.85}},l.text)))):f.default.createElement(`div`,{style:{color:`var(--color-error, #e06c75)`}},i)}function H({controller:e}){let t=f.default.useSyncExternalStore(t=>e.state.subscribe(t),()=>e.state.getSnapshot()),n=f.default.useRef(null);f.default.useEffect(()=>{if(t.status!==`closed`&&t.x===null){let n=S((window.innerWidth-t.width)/2,0,Math.max(0,window.innerWidth-t.width)),r=S((window.innerHeight-t.height)/2,0,Math.max(0,window.innerHeight-t.height));e.setGeometry({x:n,y:r})}},[e,t.status,t.x,t.width,t.height]);let r=R(e,t),i=z(e,t);if(t.status===`closed`||t.x===null)return null;let a=[],o=t.status===`ended`||t.status===`error`,s=o?t.status===`error`?`关闭`:`关闭面板`:`退出`,c=t.status===`opening`||t.status===`exiting`;a.push(f.default.createElement(`div`,{key:`h`,style:D,onMouseDown:r},f.default.createElement(`span`,{style:{fontWeight:700,flex:`0 0 auto`}},`/terminal`),f.default.createElement(`div`,{style:k,onMouseDown:e=>e.stopPropagation()},f.default.createElement(`button`,{type:`button`,style:A(t.tab===`live`),onClick:()=>e.setTab(`live`)},`会话`),f.default.createElement(`button`,{type:`button`,style:A(t.tab===`history`),onClick:()=>e.setTab(`history`)},`历史`)),f.default.createElement(`button`,{type:`button`,style:{...M,flex:`0 0 auto`},disabled:c,onMouseDown:e=>e.stopPropagation(),onClick:()=>o?e.dismiss():e.exit()},s)));let l=[];l.push(f.default.createElement(y,{key:`terminal-${t.epoch}`,controller:e,visible:t.tab===`live`,status:t.status})),t.tab===`live`&&t.status===`open`&&l.push(f.default.createElement(`div`,{key:`controls`,style:{display:`flex`,gap:8,flex:`0 0 auto`}},...[[`C`,``,`中断`],[`D`,``,`结束/EOF`],[`Z`,``,`挂起`]].map(([t,n,r])=>f.default.createElement(`button`,{key:t,type:`button`,style:M,"aria-label":`Ctrl+${t}(${r})`,title:`Ctrl+${t}(${r})`,onClick:()=>{e.markActivity(),e.sendRaw(n),e.terminal?.focus()}},`^${t}`)))),t.status===`opening`&&l.push(f.default.createElement(`div`,{key:`opening`},`正在打开终端…`)),t.status===`exiting`&&l.push(f.default.createElement(`div`,{key:`exiting`},`正在结束终端会话…`)),t.error&&l.push(f.default.createElement(`div`,{key:`err`,role:`alert`,style:{color:`#e06c75`}},t.error)),t.tab===`history`&&l.push(f.default.createElement(V,{key:`history-${t.pendingSelectPath||`live`}`,controller:e,state:t})),t.tab===`live`&&t.status===`ended`&&l.push(f.default.createElement(`div`,{key:`ended-hint`},`终端会话已结束,如需继续请重新输入 /terminal。`)),a.push(f.default.createElement(`div`,{key:`body`,style:{...O,overflow:`hidden`}},l));let u=f.default.createElement(`div`,{ref:n,style:{...E,left:t.x,top:t.y,width:t.width,height:t.height},role:`dialog`,"aria-label":`shell terminal`},a,f.default.createElement(`div`,{style:P,onMouseDown:i}));return p.default.createPortal(u,document.body)}function U(e){return{token:`/terminal `,hint:`[interactive terminal]`,submit:()=>(e.open(),Promise.resolve({kind:`success`}))}}function W(e,t,n){if(/^\s*\/terminal\s*$/iu.exec(n)!==null)return{claim:U(e(t))}}function G(e){return{trigger:`/`,name:`terminal`,order:-5,candidates(e,t){return t.position!==`leading`||!`terminal`.startsWith(t.query.toLowerCase())?Promise.resolve([]):Promise.resolve([{name:`terminal`,description:`Open an interactive terminal (reference history on demand)`,hint:`[terminal]`}])},onPick(t){return{claim:U(e(t.session.sessionId))}},matchSpace(t,n){return/^\/terminal$/iu.test(n)?{claim:U(e(t.sessionId))}:void 0},matchEnter(t,n){return Promise.resolve(W(e,t.sessionId,n))}}}function K(e){let t=(t,n)=>n.length===0?Promise.resolve({kind:`error`,text:`Usage: /! `}):e.rpc.call(`/shell-bang-rpc`,`run`,{sessionId:t,command:n},void 0).then(e=>e===void 0||!e.ok?{kind:`error`,text:e&&e.error?e.error.message:`command execution failed`}:{kind:`success`}).catch(e=>({kind:`error`,text:e instanceof Error?e.message:String(e)}));return{trigger:`/`,name:`shell-bang`,order:-10,candidates(e,t){return t.position!==`leading`||!`!`.startsWith(t.query.toLowerCase())?Promise.resolve([]):Promise.resolve([{name:`!`,description:`Run a shell command and analyze its output`,hint:``}])},onPick({session:e}){return{claim:{token:`/!`,hint:``,submit:n=>{let r=n.replace(/^\/!\s*/,``).trim();return t(e.sessionId,r)}}}},matchSpace(e,n){if(n===`/!`)return{claim:{token:`/! `,hint:``,submit:n=>{let r=n.replace(/^\/!\s*/,``).trim();return t(e.sessionId,r)}}}},matchEnter(e,n){let r=/^\/!\s*(.+)$/u.exec(n);if(r===null)return Promise.resolve(void 0);let i=r[1].trim();return Promise.resolve({claim:{token:n,hint:``,submit:()=>t(e.sessionId,i)}})}}}let q=[`connection`,`inputTriggers`,`sessions`,`slots`];function J(e){e.effect(()=>{let e=document.createElement(`style`);return e.dataset.dshShellXterm=``,e.textContent=`/** + * Copyright (c) 2014 The xterm.js authors. All rights reserved. + * Copyright (c) 2012-2013, Christopher Jeffrey (MIT License) + * https://github.com/chjj/term.js + * @license MIT * - * Hand-authored (no bundler): registers a standalone `/terminal` command in - * the input trigger and opens a floating (freely movable/resizable) terminal - * panel via a portal to `document.body`. The panel streams the PTY over a - * WebSocket, shows a "会话"/"历史" tab pair. Closing never sends anything to - * the model — it just ends the PTY and (for a session that received input) - * persists the transcript, then the panel stays open, switches to the - * "历史" tab, and pre-selects the just-ended entry so the user can decide - * for themselves whether to reference it via the existing "引用并分析" - * action. The live view is a simple ANSI-stripped scrollback + input line - * (VT100/xterm fidelity is a follow-up). + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + * THE SOFTWARE. + * + * Originally forked from (with the author's permission): + * Fabrice Bellard's javascript vt100 for jslinux: + * http://bellard.org/jslinux/ + * Copyright (c) 2011 Fabrice Bellard + * The original design remains. The terminal itself + * has been extended to include xterm CSI codes, among + * other features. */ -window.__ModuleLoader__.load({ - id: "dsh-shell-command", - factory: (require) => { - var module = { exports: {} }; - var exports = module.exports; - - const reactModule = require("react"); - const React = reactModule && reactModule.default ? reactModule.default : reactModule; - const reactDomModule = require("react-dom"); - const ReactDOM = reactDomModule && reactDomModule.default ? reactDomModule.default : reactDomModule; - const runtime = require("@deepseek-ai/dsh-client-runtime/client"); - const createSnapshotStore = runtime.createSnapshotStore; - - const RPC_CHANNEL = "/shell-term-rpc"; - const RPC_CHANNEL_BANG = "/shell-bang-rpc"; - const WS_PATH = "/shell-term/ws"; - - const PANEL_MIN_WIDTH = 340; - const PANEL_MIN_HEIGHT = 220; - const PANEL_DEFAULT_WIDTH = 460; - const PANEL_DEFAULT_HEIGHT = 420; - - function clampNum(value, min, max) { - return Math.max(min, Math.min(value, max)); - } - - /* ANSI/SGR foreground palette (standard 30–37, bright 90–97). */ - const ANSI_COLORS = ["#2e2e2e", "#d64545", "#2e9e4f", "#c9a227", "#3b7dd8", "#9a4ec2", "#1fa8a0", "#d8d8d8"]; - const ANSI_BRIGHT = ["#555555", "#ff6b6b", "#3ddc84", "#f0d264", "#6aa5f8", "#c086e8", "#3dd0c8", "#ffffff"]; - - /* - * Render ANSI/SGR-colored text as React spans (green prompt, red errors, …). - * Matches the full CSI grammar (cursor moves, clear-line, etc.), not just - * SGR — non-SGR sequences are consumed and dropped rather than leaking raw - * escape bytes into the rendered scrollback (mirrors stripAnsi in inject.js). - */ - function renderAnsi(text, keyPrefix) { - // Strip OSC sequences (e.g. bash's `\x1b]0;title\x07` window-title set) - // before the CSI/SGR tokenizer runs below — otherwise they render as - // literal garbled bytes right before the real (correctly colored) prompt. - // Mirrors stripAnsi's OSC handling in inject.js. - const stripped = text.replace(/\x1b\][^\x07]*(\x07|\x1b\\)/g, ""); - const re = /\x1b\[([0-9;?]*[ -/]*)([@-~])/g; - const elements = []; - let last = 0; - let fg = null; - let bold = false; - let key = 0; - const flush = (chunk, color, weight) => { - if (chunk.length === 0) return; - const style = {}; - if (color !== null) style.color = color; - if (weight) style.fontWeight = "bold"; - elements.push(React.createElement("span", { key: `${keyPrefix}-${key++}`, style }, chunk)); - }; - let match; - while ((match = re.exec(stripped)) !== null) { - if (match.index > last) flush(stripped.slice(last, match.index), fg, bold); - if (match[2] !== "m") { - // Non-SGR CSI (cursor move, clear-line, …): drop, don't render. - last = re.lastIndex; - continue; - } - const raw = match[1]; - const codes = raw === "" ? [0] : raw.split(";").map((n) => Number(n)).filter((n) => !Number.isNaN(n)); - for (const code of codes) { - if (code === 0) { fg = null; bold = false; } - else if (code === 1) bold = true; - else if (code === 22) bold = false; - else if (code >= 30 && code <= 37) fg = ANSI_COLORS[code - 30]; - else if (code >= 90 && code <= 97) fg = ANSI_BRIGHT[code - 90]; - else if (code === 39) fg = null; - } - last = re.lastIndex; - } - if (last < stripped.length) flush(stripped.slice(last), fg, bold); - return elements; - } - - /* One terminal session's client-side state + host bridge. */ - class TerminalController { - constructor(connection, sessionId) { - this.connection = connection; - this.sessionId = sessionId; - this.ws = null; - this.transcript = ""; - // Client-side command history for the ArrowUp/ArrowDown recall in the - // input line. Deliberately not server-side: the shell's own readline - // history lives in a buffer this plugin never round-trips (input is - // sent as whole lines on Enter, not keystroke-by-keystroke), so there's - // no way to drive the PTY's real history without desyncing the local - // draft from whatever the PTY thinks the current line is. Kept as a - // plain array (not snapshot state) since it's read on keypress, not - // rendered directly. Survives across open/close (unlike this.transcript, - // which is server PTY content and must reset) — it's the user's own - // typed history for this terminal window, which persisting feels right. - this.submittedLines = []; - this.state = createSnapshotStore({ - status: "closed", - tab: "live", - // Floating panel geometry — freely movable/resizable, portal-rendered. - x: null, - y: null, - width: PANEL_DEFAULT_WIDTH, - height: PANEL_DEFAULT_HEIGHT, - history: { entries: [], loading: false, error: null }, - preview: null, // { path, transcript } | null - pendingSelectPath: null, // path to pre-check in the history tab after a non-empty close - }); - } - - open() { - // Allowed from "closed" (fresh /terminal) and "ended" (the PTY was - // closed but the panel stayed open showing history — reopen in place - // rather than forcing the user to dismiss and re-invoke /terminal). - const status = this.state.getSnapshot().status; - if (status !== "closed" && status !== "ended") return; - // this.transcript is an instance field that outlives one open/close - // cycle (the controller is cached per sessionId across many - // /terminal invocations). The server always hands back a fresh PTY - // on open, so the client buffer must reset here too — otherwise the - // previous session's scrollback leaks into the new one's. - this.transcript = ""; - this.setState({ status: "opening", tab: "live", transcript: "", pendingSelectPath: null }); - this.connection.rpc.call(RPC_CHANNEL, "open", { sessionId: this.sessionId }, undefined) - .then((result) => { - if (result === undefined || !result.ok) { - this.setState({ status: "error", error: result && result.error ? result.error.message : "open failed" }); - return; - } - this.connectWs(); - this.setState({ status: "open", transcript: this.transcript }); - }) - .catch((error) => this.setState({ status: "error", error: error instanceof Error ? error.message : String(error) })); - } - - connectWs() { - const proto = typeof location !== "undefined" && location.protocol === "https:" ? "wss:" : "ws:"; - const host = typeof location !== "undefined" ? location.host : ""; - this.ws = new WebSocket(`${proto}//${host}${WS_PATH}?sessionId=${encodeURIComponent(this.sessionId)}`); - this.ws.onmessage = (event) => { - this.transcript += event.data; - // Keep the client-side buffer bounded (tail retained); rendering a - // megabyte of spans would freeze the UI. Cut on a UTF-16 code-unit - // boundary that isn't inside a surrogate pair (emoji, some CJK - // extensions), or the split half renders as a replacement glyph. - if (this.transcript.length > 65536) { - let cut = this.transcript.length - 65536; - const code = this.transcript.charCodeAt(cut); - if (code >= 0xdc00 && code <= 0xdfff) cut += 1; - this.transcript = this.transcript.slice(cut); - } - const current = this.state.getSnapshot(); - if (current.status === "open") this.setState({ status: "open", transcript: this.transcript }); - }; - this.ws.onclose = () => { this.ws = null; }; - } - - send(text) { - if (this.ws !== null && this.ws.readyState === 1) this.ws.send(text + "\n"); - if (text.trim() !== "") { - this.submittedLines.push(text); - if (this.submittedLines.length > 500) this.submittedLines.shift(); - } - } - - /** Send a raw byte sequence immediately (control chars: Ctrl+C/D/Z), bypassing line buffering. */ - sendRaw(bytes) { - if (this.ws !== null && this.ws.readyState === 1) this.ws.send(bytes); - } - - /** - * End the PTY session. Never asks for consent and never sends anything - * to the model — purely: end the process, and if it received any input - * (server-side `hasInput` check), persist the transcript. A non-empty - * close lands in "ended" (panel stays open, jumps to the history tab - * with the new entry pre-selected); an empty one closes the panel - * outright, leaving no trace. - */ - exit() { - this.setState({ status: "exiting", transcript: this.transcript }); - this.connection.rpc.call(RPC_CHANNEL, "close", { sessionId: this.sessionId }, undefined) - .then((result) => { - this.closeWs(); - if (result === undefined || !result.ok) { - this.setState({ status: "error", error: result && result.error ? result.error.message : "close failed" }); - return; - } - const { transcriptPath } = result.value; - if (transcriptPath !== null) { - this.setState({ status: "ended", tab: "history", preview: null, pendingSelectPath: transcriptPath }); - } else { - this.setState({ status: "closed" }); - } - }) - .catch((error) => { - this.closeWs(); - this.setState({ status: "error", error: error instanceof Error ? error.message : String(error) }); - }); - } - - dismiss() { - this.closeWs(); - this.setState({ status: "closed" }); - } - - closeWs() { - if (this.ws !== null) { - try { this.ws.close(); } catch { /* ignore */ } - this.ws = null; - } - } - - dispose() { - this.closeWs(); - } - - setState(next) { - this.state.set({ ...this.state.getSnapshot(), ...next }); - } - - /* ---- panel geometry (drag/resize) ---- */ - setGeometry(patch) { - this.setState(patch); - } - - /* ---- history tab ---- */ - setTab(tab) { - // HistoryTab's own mount effect calls loadHistory() when it mounts - // (it unmounts/remounts on every tab switch), so no need to trigger - // a second fetch here. - this.setState({ tab, preview: null }); - } - - loadHistory() { - this.setState({ history: { ...this.state.getSnapshot().history, loading: true, error: null } }); - this.connection.rpc.call(RPC_CHANNEL, "historyList", { sessionId: this.sessionId }, undefined) - .then((result) => { - if (result === undefined || !result.ok) { - this.setState({ history: { entries: [], loading: false, error: result && result.error ? result.error.message : "load failed" } }); - return; - } - this.setState({ history: { entries: result.value.entries, loading: false, error: null } }); - }) - .catch((error) => this.setState({ history: { entries: [], loading: false, error: error instanceof Error ? error.message : String(error) } })); - } - - togglePreview(path) { - const current = this.state.getSnapshot().preview; - if (current !== null && current.path === path) { - this.setState({ preview: null }); - return; - } - this.setState({ preview: { path, transcript: null, loading: true } }); - this.connection.rpc.call(RPC_CHANNEL, "historyRead", { sessionId: this.sessionId, path }, undefined) - .then((result) => { - if (result === undefined || !result.ok) { - this.setState({ preview: { path, transcript: result && result.error ? result.error.message : "read failed", loading: false } }); - return; - } - this.setState({ preview: { path, transcript: result.value.transcript, loading: false } }); - }) - .catch((error) => this.setState({ preview: { path, transcript: error instanceof Error ? error.message : String(error), loading: false } })); - } - - /** Reference-inject the given transcript paths (multi-select) + notes; non-waking. */ - referenceInject(paths, notes) { - return this.connection.rpc.call(RPC_CHANNEL, "historyInject", { sessionId: this.sessionId, paths, notes: notes || "" }, undefined) - .then((result) => { - if (result === undefined || !result.ok) { - throw new Error(result && result.error ? result.error.message : "reference-inject failed"); - } - return result.value; - }); - } - } - - /* ---- React component ---- */ - const panelStyle = { - boxSizing: "border-box", - position: "fixed", - zIndex: 1000, - display: "flex", - flexDirection: "column", - border: "1px solid var(--dsw-alias-border-l1, color-mix(in srgb, currentColor 22%, transparent))", - borderRadius: 12, - background: "var(--color-surface, #141414)", - color: "var(--color-text, inherit)", - fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", - fontSize: 13, - boxShadow: "0 8px 30px rgba(0,0,0,.35)", - overflow: "hidden", - }; - const headerStyle = { - display: "flex", - alignItems: "center", - gap: 8, - justifyContent: "space-between", - padding: "8px 10px", - cursor: "move", - userSelect: "none", - borderBottom: "1px solid color-mix(in srgb, currentColor 16%, transparent)", - flex: "0 0 auto", - }; - const bodyStyle = { - flex: "1 1 auto", - display: "flex", - flexDirection: "column", - gap: 8, - padding: "10px 12px", - overflow: "auto", - minHeight: 0, - }; - const tabRowStyle = { display: "flex", gap: 4, flex: "0 0 auto" }; - const tabButtonStyle = (active) => ({ - appearance: "none", - border: "none", - borderBottom: active ? "2px solid var(--color-accent, #3b7dd8)" : "2px solid transparent", - background: "transparent", - color: active ? "inherit" : "color-mix(in srgb, currentColor 60%, transparent)", - cursor: "pointer", - fontSize: 12, - fontWeight: active ? 700 : 400, - padding: "4px 2px", - }); - const scrollStyle = { - overflow: "auto", - whiteSpace: "pre-wrap", - wordBreak: "break-all", - flex: "1 1 auto", - minHeight: 60, - padding: 6, - borderRadius: 6, - background: "rgba(0,0,0,.35)", - lineHeight: 1.45, - }; - // Ctrl+ -> raw control byte sent immediately (bypasses line buffering). - const CTRL_KEY_BYTES = { c: "\x03", d: "\x04", z: "\x1a" }; - const inputRowStyle = { display: "flex", gap: 8, flex: "0 0 auto" }; - const ctrlButtonStyle = { - appearance: "none", - border: "1px solid color-mix(in srgb, currentColor 24%, transparent)", - borderRadius: 7, - padding: "3px 8px", - background: "transparent", - color: "inherit", - cursor: "pointer", - fontSize: 11, - flex: "0 0 auto", - }; - const inputStyle = { - flex: 1, - background: "transparent", - border: "1px solid color-mix(in srgb, currentColor 22%, transparent)", - borderRadius: 6, - padding: "4px 8px", - color: "inherit", - fontFamily: "inherit", - fontSize: 13, - }; - const buttonStyle = { - appearance: "none", - border: "1px solid color-mix(in srgb, currentColor 24%, transparent)", - borderRadius: 7, - padding: "3px 10px", - background: "transparent", - color: "inherit", - cursor: "pointer", - fontSize: 12, - }; - const resizeGripStyle = { - position: "absolute", - right: 0, - bottom: 0, - width: 16, - height: 16, - cursor: "nwse-resize", - background: "linear-gradient(135deg, transparent 50%, color-mix(in srgb, currentColor 35%, transparent) 50%)", - }; - const historyRowStyle = { - display: "flex", - flexDirection: "column", - gap: 4, - padding: "6px 8px", - borderRadius: 6, - border: "1px solid color-mix(in srgb, currentColor 14%, transparent)", - }; - const historyHeaderRowStyle = { display: "flex", alignItems: "center", gap: 8 }; - const badgeStyle = (tone) => ({ - fontSize: 11, - padding: "1px 6px", - borderRadius: 999, - background: tone === "warn" ? "color-mix(in srgb, #e0b95e 30%, transparent)" : "color-mix(in srgb, currentColor 14%, transparent)", - }); - - /** Drag the header to move the panel; clamps to the viewport. */ - function useDrag(controller, state) { - const dragRef = React.useRef(null); - const onHeaderMouseDown = (event) => { - if (event.button !== 0) return; - const rect = event.currentTarget.parentElement.getBoundingClientRect(); - dragRef.current = { startX: event.clientX, startY: event.clientY, originX: rect.left, originY: rect.top }; - event.preventDefault(); - }; - React.useEffect(() => { - const onMove = (event) => { - if (dragRef.current === null) return; - const { startX, startY, originX, originY } = dragRef.current; - const width = state.width; - const height = state.height; - const nextX = clampNum(originX + (event.clientX - startX), 0, Math.max(0, window.innerWidth - width)); - const nextY = clampNum(originY + (event.clientY - startY), 0, Math.max(0, window.innerHeight - height)); - controller.setGeometry({ x: nextX, y: nextY }); - }; - const onUp = () => { dragRef.current = null; }; - window.addEventListener("mousemove", onMove); - window.addEventListener("mouseup", onUp); - return () => { - window.removeEventListener("mousemove", onMove); - window.removeEventListener("mouseup", onUp); - }; - }, [controller, state.width, state.height]); - return onHeaderMouseDown; - } - - /** Drag the corner grip to resize the panel; clamps to a minimum and the viewport. */ - function useResize(controller, state) { - const resizeRef = React.useRef(null); - const onGripMouseDown = (event) => { - if (event.button !== 0) return; - resizeRef.current = { startX: event.clientX, startY: event.clientY, startWidth: state.width, startHeight: state.height }; - event.preventDefault(); - event.stopPropagation(); - }; - React.useEffect(() => { - const onMove = (event) => { - if (resizeRef.current === null) return; - const { startX, startY, startWidth, startHeight } = resizeRef.current; - const maxWidth = Math.max(PANEL_MIN_WIDTH, window.innerWidth - (state.x ?? 0)); - const maxHeight = Math.max(PANEL_MIN_HEIGHT, window.innerHeight - (state.y ?? 0)); - const nextWidth = clampNum(startWidth + (event.clientX - startX), PANEL_MIN_WIDTH, maxWidth); - const nextHeight = clampNum(startHeight + (event.clientY - startY), PANEL_MIN_HEIGHT, maxHeight); - controller.setGeometry({ width: nextWidth, height: nextHeight }); - }; - const onUp = () => { resizeRef.current = null; }; - window.addEventListener("mousemove", onMove); - window.addEventListener("mouseup", onUp); - return () => { - window.removeEventListener("mousemove", onMove); - window.removeEventListener("mouseup", onUp); - }; - }, [controller, state.x, state.y]); - return onGripMouseDown; - } - - function formatExitBadge(exitCode) { - if (exitCode === null || exitCode === undefined) return null; - return exitCode === 0 - ? React.createElement("span", { style: badgeStyle("ok") }, "退出码 0") - : React.createElement("span", { style: badgeStyle("warn") }, `退出码 ${exitCode}`); - } - - function HistoryTab({ controller, state }) { - const { entries, loading, error } = state.history; - // HistoryTab remounts on every tab switch (see setTab's comment), so - // this initializer runs exactly once per mount — good enough to - // pre-check the entry a just-ended close jumped here to show, without - // needing an extra effect to keep it in sync. - const [selected, setSelected] = React.useState(() => - state.pendingSelectPath ? new Set([state.pendingSelectPath]) : new Set()); - const [notes, setNotes] = React.useState(""); - const [status, setStatus] = React.useState(null); // { kind: "ok" | "error", text } - - React.useEffect(() => { controller.loadHistory(); /* refresh on mount */ }, [controller]); - - // Auto-expand the just-closed entry's preview when the panel jumps here - // after exit() (only for pendingSelectPath, not for manually-selected entries). - React.useEffect(() => { - if (state.pendingSelectPath) { - controller.togglePreview(state.pendingSelectPath); - } - }, [state.pendingSelectPath, controller]); - - const toggleSelected = (path) => { - setSelected((prev) => { - const next = new Set(prev); - if (next.has(path)) next.delete(path); else next.add(path); - return next; - }); - }; - - const onReferenceInject = () => { - const paths = Array.from(selected); - if (paths.length === 0) return; - setStatus(null); - controller.referenceInject(paths, notes) - .then((value) => { - setStatus({ kind: "ok", text: `已引用 ${value.referenced} 段历史记录,模型正在分析…` }); - setSelected(new Set()); - setNotes(""); - }) - .catch((err) => setStatus({ kind: "error", text: err instanceof Error ? err.message : String(err) })); - }; - - if (loading && entries.length === 0) { - return React.createElement("div", { style: { opacity: .7 } }, "正在加载历史记录…"); - } - if (error !== null) { - return React.createElement("div", { style: { color: "var(--color-error, #e06c75)" } }, error); - } - if (entries.length === 0) { - return React.createElement("div", { style: { opacity: .7 } }, "暂无历史终端记录。"); - } - - return React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 8, minHeight: 0, flex: "1 1 auto", overflow: "auto" } }, - React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 6, overflow: "auto" } }, - entries.map((entry) => { - const isOpen = state.preview !== null && state.preview.path === entry.path; - return React.createElement("div", { key: entry.path, style: historyRowStyle }, - React.createElement("div", { style: historyHeaderRowStyle }, - React.createElement("input", { - type: "checkbox", - checked: selected.has(entry.path), - onChange: () => toggleSelected(entry.path), - }), - React.createElement("span", { style: { flex: "1 1 auto", fontSize: 12 } }, new Date(entry.timestamp).toLocaleString()), - formatExitBadge(entry.exitCode), - entry.truncated ? React.createElement("span", { style: badgeStyle("warn") }, "已截断") : null, - React.createElement("button", { - type: "button", - style: { ...buttonStyle, padding: "2px 8px" }, - onClick: () => controller.togglePreview(entry.path), - }, isOpen ? "收起" : "查看"), - ), - isOpen ? React.createElement("div", { style: { ...scrollStyle, maxHeight: 160, flex: "0 0 auto" } }, - state.preview.loading ? "正在读取…" : renderAnsi(state.preview.transcript || "", entry.path), - ) : null, - ); - }), - ), - React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 6, flex: "0 0 auto", borderTop: "1px solid color-mix(in srgb, currentColor 14%, transparent)", paddingTop: 8 } }, - React.createElement("textarea", { - value: notes, - placeholder: "(可选)已选中多段记录时,可在此补充自然语言说明…", - onChange: (event) => setNotes(event.target.value), - style: { ...inputStyle, minHeight: 40, resize: "vertical", fontFamily: "inherit" }, - }), - React.createElement("div", { style: { fontSize: 11, opacity: 0.6, marginTop: -2 } }, - "提示:不输入时的默认消息为「请帮我分别分析这些历史终端记录。」" - ), - React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8 } }, - React.createElement("button", { - type: "button", - style: buttonStyle, - disabled: selected.size === 0, - onClick: onReferenceInject, - }, selected.size > 1 ? `引用并分析 (${selected.size} 段)` : "引用并分析"), - // Only offered once the just-closed session has actually ended (or - // errored) — dismiss() only tears down client-side UI state, it never - // calls the close RPC. Surfacing this while a PTY is still "open" - // would let a user believe they've skipped a session that's actually - // still running server-side (mirrors why the header button only - // becomes "关闭面板" in this same state — see isEnded in ShellTerminal). - (state.status === "ended" || state.status === "error") ? React.createElement("button", { - type: "button", - style: buttonStyle, - onClick: () => controller.dismiss(), - }, "直接退出,本次不分析") : null, - status !== null ? React.createElement("span", { - style: { fontSize: 12, color: status.kind === "error" ? "var(--color-error, #e06c75)" : "inherit", opacity: .85 }, - }, status.text) : null, - ), - ), - ); - } - - function ShellTerminal({ controller }) { - const state = React.useSyncExternalStore( - (listener) => controller.state.subscribe(listener), - () => controller.state.getSnapshot(), - ); - const [draft, setDraft] = React.useState(""); - // historyIndex === null means "not browsing history" (typing a fresh - // line); otherwise it's the current position in controller.submittedLines. - // historyDraft holds whatever the user was typing before they started - // browsing, so ArrowDown past the newest entry can restore it. - const [historyIndex, setHistoryIndex] = React.useState(null); - const [historyDraft, setHistoryDraft] = React.useState(""); - const scrollRef = React.useRef(null); - const panelRef = React.useRef(null); - - React.useEffect(() => { - if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; - }, [state.transcript, state.status, state.tab]); - - // First open: default to a centered position now that we know the viewport. - React.useEffect(() => { - if (state.status !== "closed" && state.x === null) { - const x = clampNum((window.innerWidth - state.width) / 2, 0, Math.max(0, window.innerWidth - state.width)); - const y = clampNum((window.innerHeight - state.height) / 2, 0, Math.max(0, window.innerHeight - state.height)); - controller.setGeometry({ x, y }); - } - }, [controller, state.status, state.x, state.width, state.height]); - - const onHeaderMouseDown = useDrag(controller, state); - const onGripMouseDown = useResize(controller, state); - - if (state.status === "closed" || state.x === null) return null; - - const onInputKeyDown = (event) => { - if (event.key === "Enter") { - event.preventDefault(); - controller.send(draft); - setDraft(""); - setHistoryIndex(null); - return; - } - // Recall previously-submitted lines, browser-address-bar style. This - // is client-side only (see controller.submittedLines's comment) — it - // never touches the PTY, so it can't desync from the shell's own - // readline state. - if (event.key === "ArrowUp") { - const lines = controller.submittedLines; - if (lines.length === 0) return; - event.preventDefault(); - const nextIndex = historyIndex === null ? lines.length - 1 : Math.max(0, historyIndex - 1); - if (historyIndex === null) setHistoryDraft(draft); - setHistoryIndex(nextIndex); - setDraft(lines[nextIndex]); - return; - } - if (event.key === "ArrowDown") { - if (historyIndex === null) return; - event.preventDefault(); - const lines = controller.submittedLines; - const nextIndex = historyIndex + 1; - if (nextIndex >= lines.length) { - setHistoryIndex(null); - setDraft(historyDraft); - } else { - setHistoryIndex(nextIndex); - setDraft(lines[nextIndex]); - } - return; - } - // Control chars (SIGINT/EOF/SIGTSTP) must land immediately, not wait - // for Enter — you're often interrupting a command that's still - // running, e.g. Ctrl+C on a stuck `sleep 100`. The browser doesn't - // intercept these combos for a plain , so they reach us here. - if (event.ctrlKey && !event.altKey && !event.metaKey) { - const raw = CTRL_KEY_BYTES[event.key.toLowerCase()]; - if (raw !== undefined) { - event.preventDefault(); - controller.sendRaw(raw); - } - } - }; - - const children = []; - - // Header (drag handle). "退出" ends the live PTY (a pure persistence - // step, no consent prompt); once ended, the same slot becomes "关闭 - // 面板" to dismiss the panel entirely (the panel stays open after - // exit() so the user can act on the history tab it jumps to). - const isEnded = state.status === "ended" || state.status === "error"; - const headerButtonLabel = isEnded ? (state.status === "error" ? "关闭" : "关闭面板") : "退出"; - const headerButtonDisabled = state.status === "opening" || state.status === "exiting"; - children.push(React.createElement("div", { - key: "h", - style: headerStyle, - onMouseDown: onHeaderMouseDown, - }, - React.createElement("span", { style: { fontWeight: 700, flex: "0 0 auto" } }, "/terminal"), - React.createElement("div", { style: tabRowStyle, onMouseDown: (event) => event.stopPropagation() }, - React.createElement("button", { type: "button", style: tabButtonStyle(state.tab === "live"), onClick: () => controller.setTab("live") }, "会话"), - React.createElement("button", { type: "button", style: tabButtonStyle(state.tab === "history"), onClick: () => controller.setTab("history") }, "历史"), - ), - React.createElement("button", { - type: "button", - style: { ...buttonStyle, flex: "0 0 auto" }, - disabled: headerButtonDisabled, - onMouseDown: (event) => event.stopPropagation(), - onClick: () => (isEnded ? controller.dismiss() : controller.exit()), - }, headerButtonLabel), - )); - - const body = []; - if (state.status === "opening") { - body.push(React.createElement("div", { key: "opening", style: { opacity: .7 } }, "正在打开终端…")); - } else if (state.status === "error") { - body.push(React.createElement("div", { key: "err", style: { color: "var(--color-error, #e06c75)" } }, state.error)); - } else if (state.status === "exiting") { - body.push(React.createElement("div", { key: "exiting", style: { opacity: .7 } }, "正在结束终端会话…")); - } else if (state.tab === "history") { - body.push(React.createElement(HistoryTab, { key: "history", controller, state })); - } else if (state.status === "ended") { - // Live tab after the PTY has ended: read-only final scrollback, no - // input/Ctrl row (there's no WS to send anything to anymore). - body.push(React.createElement("div", { key: "scroll", ref: scrollRef, style: scrollStyle }, renderAnsi(state.transcript || "", "scroll"))); - body.push(React.createElement("div", { key: "ended-hint", style: { opacity: .7, fontSize: 12 } }, "终端会话已结束,如需继续请重新输入 /terminal。")); - } else { - // "open" + live tab: scrollback + input line - body.push(React.createElement("div", { key: "scroll", ref: scrollRef, style: scrollStyle }, renderAnsi(state.transcript || "", "scroll"))); - body.push(React.createElement("div", { key: "row", style: inputRowStyle }, - React.createElement("input", { - autoFocus: true, - value: draft, - placeholder: "输入命令,回车执行…(支持 Ctrl+C/D/Z,↑↓ 历史命令)", - onChange: (event) => setDraft(event.target.value), - onKeyDown: onInputKeyDown, - style: inputStyle, - }), - React.createElement("button", { type: "button", title: "Ctrl+C(中断)", style: ctrlButtonStyle, onClick: () => controller.sendRaw(CTRL_KEY_BYTES.c) }, "^C"), - React.createElement("button", { type: "button", title: "Ctrl+D(结束/EOF)", style: ctrlButtonStyle, onClick: () => controller.sendRaw(CTRL_KEY_BYTES.d) }, "^D"), - React.createElement("button", { type: "button", title: "Ctrl+Z(挂起)", style: ctrlButtonStyle, onClick: () => controller.sendRaw(CTRL_KEY_BYTES.z) }, "^Z"), - )); - } - children.push(React.createElement("div", { key: "body", style: bodyStyle }, body)); - - const panel = React.createElement("div", { - ref: panelRef, - style: { ...panelStyle, left: state.x, top: state.y, width: state.width, height: state.height }, - role: "dialog", - "aria-label": "shell terminal", - }, - children, - React.createElement("div", { style: resizeGripStyle, onMouseDown: onGripMouseDown }), - ); - - return ReactDOM.createPortal(panel, document.body); - } - - /* ---- input trigger source: a standalone /terminal command (no host-command - * collision, unlike `/shell --terminal` which the command directory claims - * first). Mirrors dsh-btw's /btw source exactly: candidates + onPick + - * matchSpace + a Promise-returning matchEnter. ---- */ - function terminalClaim(controller) { - return { - token: "/terminal ", - hint: "[interactive terminal]", - submit: () => { - controller.open(); - return Promise.resolve({ kind: "success" }); - }, - }; - } - - function enterClaim(controllerFor, sessionId, line) { - const match = /^\s*\/terminal\s*$/iu.exec(line); - if (match === null) return undefined; - return { claim: terminalClaim(controllerFor(sessionId)) }; - } - - function createTerminalSource(controllerFor) { - return { - trigger: "/", - name: "terminal", - order: -5, - candidates(_session, request) { - if (request.position !== "leading" || !"terminal".startsWith(request.query.toLowerCase())) return Promise.resolve([]); - return Promise.resolve([{ - name: "terminal", - description: "Open an interactive terminal (inject its transcript on exit)", - hint: "[terminal]", - }]); - }, - onPick(pick) { - return { claim: terminalClaim(controllerFor(pick.session.sessionId)) }; - }, - matchSpace(session, token) { - return /^\/terminal$/iu.test(token) ? { claim: terminalClaim(controllerFor(session.sessionId)) } : undefined; - }, - matchEnter(session, line) { - return Promise.resolve(enterClaim(controllerFor, session.sessionId, line)); - }, - }; - } - - /* ---- '/!' shell command trigger source: one-shot command execution + analysis ---- */ - function createBangSource(connection) { - // Shared RPC invoker - const runCommand = (sessionId, command) => { - if (command.length === 0) { - return Promise.resolve({ kind: "error", text: "Usage: /! " }); - } - return connection.rpc.call(RPC_CHANNEL_BANG, "run", { sessionId, command }, undefined) - .then((result) => { - if (result === undefined || !result.ok) { - return { kind: "error", text: result && result.error ? result.error.message : "command execution failed" }; - } - return { kind: "success" }; - }) - .catch((error) => ({ kind: "error", text: error instanceof Error ? error.message : String(error) })); - }; - - return { - trigger: "/", - name: "shell-bang", - order: -10, - candidates(_session, request) { - if (request.position !== "leading") return Promise.resolve([]); - if (!"!".startsWith(request.query.toLowerCase())) return Promise.resolve([]); - return Promise.resolve([{ - name: "!", - description: "Run a shell command and analyze its output", - hint: "", - }]); - }, - onPick({ session }) { - return { - claim: { - token: "/!", - hint: "", - submit: (line) => { - const command = line.replace(/^\/!\s*/, "").trim(); - return runCommand(session.sessionId, command); - }, - }, - }; - }, - matchSpace(session, token) { - if (token !== "/!") return undefined; - return { - claim: { - token: "/! ", - hint: "", - submit: (line) => { - const command = line.replace(/^\/!\s*/, "").trim(); - return runCommand(session.sessionId, command); - }, - }, - }; - }, - matchEnter(session, line) { - const match = /^\/!\s*(.+)$/u.exec(line); - if (match === null) return Promise.resolve(undefined); - const command = match[1].trim(); - return Promise.resolve({ - claim: { - token: line, - hint: "", - submit: () => runCommand(session.sessionId, command), - }, - }); - }, - }; - } - - /* ---- plugin apply ---- */ - const name = "shell-command-client"; - const inject = ["connection", "inputTriggers", "sessions", "slots"]; - - function apply(ctx) { - const connection = ctx.get("connection"); - const inputTriggers = ctx.get("inputTriggers"); - const sessions = ctx.get("sessions"); - const slots = ctx.slots; - if (connection === undefined || inputTriggers === undefined || sessions === undefined || slots === undefined) { - throw new Error("dsh-shell-command/client requires connection, inputTriggers, sessions, and slots"); - } - - const controllers = new Map(); - const controllerFor = (sessionId) => { - let controller = controllers.get(sessionId); - if (controller === undefined) { - controller = new TerminalController(connection, sessionId); - controllers.set(sessionId, controller); - } - return controller; - }; - - ctx.effect(() => inputTriggers.registerSource(createTerminalSource(controllerFor)), "shell-command: terminal input source"); - ctx.effect(() => inputTriggers.registerSource(createBangSource(connection)), "shell-command: bang input source"); - ctx.effect(() => () => { - for (const controller of controllers.values()) controller.dispose(); - controllers.clear(); - }, "shell-command: terminal controllers"); - - // The panel is portal-rendered to document.body (see ShellTerminal), so - // this slot registration only needs to mount the component once per - // session — it no longer occupies visible space in the input dock. - ctx.slots.inject("conversation.input.dock", () => ctx.slots.register({ - name: "conversation.input.dock", - id: "shell-term-panel", - order: 3, - inject: (sessionId) => { - const actx = sessions.scope(sessionId); - if (actx === undefined) throw new Error(`dsh-shell-command: session "${String(sessionId)}" resolved no client scope`); - const controller = controllerFor(sessionId); - actx.effect(() => () => { - if (controllers.get(sessionId) === controller) controllers.delete(sessionId); - controller.dispose(); - }, "shell-command: session terminal"); - return { controller }; - }, - }, ShellTerminal)); - } - - exports.apply = apply; - exports.inject = inject; - exports.name = name; - return module.exports; - } -}); + +/** + * Default styles for xterm.js + */ + +.xterm { + cursor: text; + position: relative; + user-select: none; + -ms-user-select: none; + -webkit-user-select: none; +} + +.xterm.focus, +.xterm:focus { + outline: none; +} + +.xterm .xterm-helpers { + position: absolute; + top: 0; + /** + * The z-index of the helpers must be higher than the canvases in order for + * IMEs to appear on top. + */ + z-index: 5; +} + +.xterm .xterm-helper-textarea { + padding: 0; + border: 0; + margin: 0; + /* Move textarea out of the screen to the far left, so that the cursor is not visible */ + position: absolute; + opacity: 0; + left: -9999em; + top: 0; + width: 0; + height: 0; + z-index: -5; + /** Prevent wrapping so the IME appears against the textarea at the correct position */ + white-space: nowrap; + overflow: hidden; + resize: none; +} + +.xterm .composition-view { + /* TODO: Composition position got messed up somewhere */ + background: #000; + color: #FFF; + display: none; + position: absolute; + white-space: nowrap; + z-index: 1; +} + +.xterm .composition-view.active { + display: block; +} + +.xterm .xterm-viewport { + /* On OS X this is required in order for the scroll bar to appear fully opaque */ + background-color: #000; + overflow-y: scroll; + cursor: default; + position: absolute; + right: 0; + left: 0; + top: 0; + bottom: 0; +} + +.xterm .xterm-screen { + position: relative; +} + +.xterm .xterm-screen canvas { + position: absolute; + left: 0; + top: 0; +} + +.xterm-char-measure-element { + display: inline-block; + visibility: hidden; + position: absolute; + top: 0; + left: -9999em; + line-height: normal; +} + +.xterm.enable-mouse-events { + /* When mouse events are enabled (eg. tmux), revert to the standard pointer cursor */ + cursor: default; +} + +.xterm.xterm-cursor-pointer, +.xterm .xterm-cursor-pointer { + cursor: pointer; +} + +.xterm.column-select.focus { + /* Column selection mode */ + cursor: crosshair; +} + +.xterm .xterm-accessibility:not(.debug), +.xterm .xterm-message { + position: absolute; + left: 0; + top: 0; + bottom: 0; + right: 0; + z-index: 10; + color: transparent; + pointer-events: none; +} + +.xterm .xterm-accessibility-tree:not(.debug) *::selection { + color: transparent; +} + +.xterm .xterm-accessibility-tree { + font-family: monospace; + user-select: text; + white-space: pre; +} + +.xterm .xterm-accessibility-tree > div { + transform-origin: left; + width: fit-content; +} + +.xterm .live-region { + position: absolute; + left: -9999px; + width: 1px; + height: 1px; + overflow: hidden; +} + +.xterm-dim { + /* Dim should not apply to background, so the opacity of the foreground color is applied + * explicitly in the generated class and reset to 1 here */ + opacity: 1 !important; +} + +.xterm-underline-1 { text-decoration: underline; } +.xterm-underline-2 { text-decoration: double underline; } +.xterm-underline-3 { text-decoration: wavy underline; } +.xterm-underline-4 { text-decoration: dotted underline; } +.xterm-underline-5 { text-decoration: dashed underline; } + +.xterm-overline { + text-decoration: overline; +} + +.xterm-overline.xterm-underline-1 { text-decoration: overline underline; } +.xterm-overline.xterm-underline-2 { text-decoration: overline double underline; } +.xterm-overline.xterm-underline-3 { text-decoration: overline wavy underline; } +.xterm-overline.xterm-underline-4 { text-decoration: overline dotted underline; } +.xterm-overline.xterm-underline-5 { text-decoration: overline dashed underline; } + +.xterm-strikethrough { + text-decoration: line-through; +} + +.xterm-screen .xterm-decoration-container .xterm-decoration { + z-index: 6; + position: absolute; +} + +.xterm-screen .xterm-decoration-container .xterm-decoration.xterm-decoration-top-layer { + z-index: 7; +} + +.xterm-decoration-overview-ruler { + z-index: 8; + position: absolute; + top: 0; + right: 0; + pointer-events: none; +} + +.xterm-decoration-top { + z-index: 2; + position: relative; +} + + + +/* Derived from vs/base/browser/ui/scrollbar/media/scrollbar.css */ + +/* xterm.js customization: Override xterm's cursor style */ +.xterm .xterm-scrollable-element > .scrollbar { + cursor: default; +} + +/* Arrows */ +.xterm .xterm-scrollable-element > .scrollbar > .scra { + cursor: pointer; + font-size: 11px !important; +} + +.xterm .xterm-scrollable-element > .visible { + opacity: 1; + + /* Background rule added for IE9 - to allow clicks on dom node */ + background:rgba(0,0,0,0); + + transition: opacity 100ms linear; + /* In front of peek view */ + z-index: 11; +} +.xterm .xterm-scrollable-element > .invisible { + opacity: 0; + pointer-events: none; +} +.xterm .xterm-scrollable-element > .invisible.fade { + transition: opacity 800ms linear; +} + +/* Scrollable Content Inset Shadow */ +.xterm .xterm-scrollable-element > .shadow { + position: absolute; + display: none; +} +.xterm .xterm-scrollable-element > .shadow.top { + display: block; + top: 0; + left: 3px; + height: 3px; + width: 100%; + box-shadow: var(--vscode-scrollbar-shadow, #000) 0 6px 6px -6px inset; +} +.xterm .xterm-scrollable-element > .shadow.left { + display: block; + top: 3px; + left: 0; + height: 100%; + width: 3px; + box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset; +} +.xterm .xterm-scrollable-element > .shadow.top-left-corner { + display: block; + top: 0; + left: 0; + height: 3px; + width: 3px; +} +.xterm .xterm-scrollable-element > .shadow.top.left { + box-shadow: var(--vscode-scrollbar-shadow, #000) 6px 0 6px -6px inset; +} +`,document.head.appendChild(e),()=>e.remove()},`shell-command: xterm styles`);let t=e.get(`connection`),n=e.get(`inputTriggers`),r=e.get(`sessions`),i=e.slots;if(t===void 0||n===void 0||r===void 0||i===void 0)throw Error(`dsh-shell-command/client requires connection, inputTriggers, sessions, and slots`);let a=/* @__PURE__ */ new Map,o=e=>{let n=a.get(e);return n===void 0&&(n=new x(t,e),a.set(e,n)),n};e.effect(()=>n.registerSource(G(o)),`shell-command: terminal input source`),e.effect(()=>n.registerSource(K(t)),`shell-command: bang input source`),e.effect(()=>()=>{for(let e of a.values())e.dispose();a.clear()},`shell-command: terminal controllers`),e.slots.inject(`conversation.input.dock`,()=>e.slots.register({name:`conversation.input.dock`,id:`shell-term-panel`,order:3,inject:e=>{let t=r.scope(e);if(t===void 0)throw Error(`dsh-shell-command: session "${String(e)}" resolved no client scope`);let n=o(e);return t.effect(()=>()=>{a.get(e)===n&&a.delete(e),n.dispose()},`shell-command: session terminal`),{controller:n}}},H))}return n.apply=J,n.inject=q,n.name=`shell-command-client`,t.exports}}); \ No newline at end of file diff --git a/lib/exec.js b/lib/exec.js index 696b506..2638684 100644 --- a/lib/exec.js +++ b/lib/exec.js @@ -8,8 +8,8 @@ * bounded tail-retaining output collection. This is the same seam the * official bash/pwsh tools use. * 2. `node:child_process` fallback: scrubbed environment (via the exported - * `scrubbedParentEnv`), bounded in-memory buffers, and a process (not tree) - * kill on abort. Used only when the seam is unavailable in the profile. + * `scrubbedParentEnv`), bounded in-memory buffers, and process-group + * termination on abort. Used only when the seam is unavailable in the profile. * * Timeout and cancellation are classified from the caller-owned signals, never * guessed from the exit facts. @@ -53,7 +53,7 @@ export async function runCommand(input) { graceMs, maxOutputBytes, subprocess, - signal, + signal = new AbortController().signal, } = input; const timeoutSignal = AbortSignal.timeout(timeoutMs); @@ -62,7 +62,7 @@ export async function runCommand(input) { const outcome = subprocess !== undefined ? await runViaSubprocess({ argv, cwd, graceMs, maxOutputBytes, subprocess, combinedSignal }) - : await runViaChildProcess({ argv, cwd, maxOutputBytes, combinedSignal }); + : await runViaChildProcess({ argv, cwd, graceMs, maxOutputBytes, combinedSignal }); return { ...outcome, @@ -116,16 +116,20 @@ function readCollected(reader) { return { text: read.text, truncated: read.lossy }; } -/** child_process fallback: scrubbed env, bounded buffers, process-level kill. */ -function runViaChildProcess({ argv, cwd, maxOutputBytes, combinedSignal }) { +/** child_process fallback: isolated process group and TERM → grace → KILL. */ +function runViaChildProcess({ argv, cwd, graceMs, maxOutputBytes, combinedSignal }) { return new Promise((resolve) => { + if (combinedSignal.aborted) { + resolve({ ok: true, stdout: { text: "", truncated: false }, stderr: { text: "", truncated: false }, exitCode: null, signal: "SIGTERM" }); + return; + } let child; try { child = spawnChild(argv[0], argv.slice(1), { cwd, env: scrubbedParentEnv(), stdio: ["ignore", "pipe", "pipe"], - signal: combinedSignal, + detached: process.platform !== "win32", }); } catch (error) { resolve({ ok: false, error }); @@ -134,24 +138,61 @@ function runViaChildProcess({ argv, cwd, maxOutputBytes, combinedSignal }) { const stdout = bounded(); const stderr = bounded(); + let killTimer, drainTimer, closeFacts; + let terminating = false; + const groupAlive = () => { + if (!child.pid || process.platform === "win32") return false; + try { process.kill(-child.pid, 0); return true; } catch { return false; } + }; + const kill = (signal) => { + if (!child.pid) return; + if (process.platform === "win32") { + // taskkill is an OS utility; use argv, never a shell command string. + const task = spawnChild("taskkill", ["/pid", String(child.pid), "/T", "/F"], { stdio: "ignore", windowsHide: true }); + task.on("error", () => { try { child.kill("SIGKILL"); } catch { /* exited */ } }); + } else { + try { process.kill(-child.pid, signal); } catch { /* process group exited */ } + } + }; + const finish = (outcome) => { + clearTimeout(killTimer); + clearTimeout(drainTimer); + combinedSignal.removeEventListener("abort", terminate); + resolve(outcome); + }; + const terminate = () => { + if (terminating) return; + terminating = true; + kill("SIGTERM"); + killTimer = setTimeout(() => { + kill("SIGKILL"); + killTimer = undefined; + if (closeFacts) finish(closeFacts); + else { + // An escaped descendant may still hold a pipe. Bound the drain. + drainTimer = setTimeout(() => { child.stdout.destroy(); child.stderr.destroy(); }, graceMs); + } + }, graceMs); + }; child.stdout.on("data", (chunk) => stdout.push(chunk, maxOutputBytes)); child.stderr.on("data", (chunk) => stderr.push(chunk, maxOutputBytes)); child.on("error", (error) => { - // An abort-triggered kill surfaces as an error event ("The operation - // was aborted") BEFORE the close event; let `close` classify it as a - // timeout/cancellation rather than a spawn failure. - if (combinedSignal.aborted) return; - resolve({ ok: false, error }); + finish({ ok: false, error }); }); child.on("close", (exitCode, signal) => { - resolve({ + closeFacts = { ok: true, stdout: stdout.result(), stderr: stderr.result(), exitCode, signal: signal ?? null, - }); + }; + // Do not cancel escalation merely because the root exited: an ignoring + // descendant with redirected stdio can still be alive in its group. + if (!terminating || !killTimer || !groupAlive()) finish(closeFacts); }); + combinedSignal.addEventListener("abort", terminate, { once: true }); + if (combinedSignal.aborted) terminate(); }); } @@ -168,7 +209,9 @@ function bounded() { } }, result() { - return { text: buffer.toString("utf8"), truncated }; + let start = 0; + if (truncated) while (start < buffer.length && (buffer[start] & 0xc0) === 0x80) start++; + return { text: buffer.subarray(start).toString("utf8"), truncated }; }, }; } diff --git a/lib/index.js b/lib/index.js index aef97a8..87fa46e 100644 --- a/lib/index.js +++ b/lib/index.js @@ -16,6 +16,7 @@ * @module dsh-shell-command */ import z from "@deepseek-ai/schemastery"; +import { randomUUID } from "node:crypto"; import { runCommand, resolveShell, PLATFORM_ARGS } from "./exec.js"; import { formatResult, formatSummary } from "./format.js"; import { createAnalysisMessage } from "./message.js"; @@ -27,12 +28,10 @@ export const name = "shell-command"; /** * Required services. `connection` powers the RPC bridge for the `!` trigger; - * `agents` resolves session IDs to agents; `connection`, `agents`, and - * `webServer` power the multi-command terminal mode (RPC + PTY WebSocket). - * Cordis loads all of them before `apply` runs, so `ctx.get(...)` returns - * live services rather than `undefined`. + * `agents` resolves session IDs to agents. `webServer` powers only the + * optional terminal mode and must not gate /!. */ -export const inject = ["connection", "agents", "webServer"]; +export const inject = ["connection", "agents"]; /** Fail-loud config contract; normalized through schemastery on load. */ const Config = z.object({ @@ -61,13 +60,17 @@ export function apply(ctx, rawConfig = {}) { const connection = ctx.get("connection"); const agents = ctx.get("agents"); - // Multi-command terminal mode: interactive PTY popup + exit consent gate. + // Multi-command terminal mode: xterm PTY popup with explicit history reference. // Best-effort; degrades to a no-op (with a warning) when node-pty/ws or the // required services are unavailable. if (effective.terminalEnabled) { - ctx.effect(async () => { - return await setupTerminalMode(ctx, effective); - }, "shell-command terminal lifecycle"); + // Bind only this child lifecycle to the optional service. If webServer + // arrives late (or reloads), terminal mode starts without suspending /!. + if (typeof ctx.inject === "function") { + ctx.inject(["webServer"], terminalCtx => setupTerminalMode(terminalCtx, effective)); + } else { + ctx.effect(() => setupTerminalMode(ctx, effective), "shell-command terminal lifecycle"); + } } // RPC handler for the `!` bang trigger. @@ -81,49 +84,63 @@ export function apply(ctx, rawConfig = {}) { if (agent === undefined) { return { ok: false, error: { code: "session-not-found", message: `no live agent owns session "${String(payload?.sessionId)}"`, details: { issues: [] } } }; } + if (agent.session.requestHeader?.() === undefined) { + return { ok: false, error: { code: "bad-request", message: "No model request exists yet. Send a message before using /! commands.", details: { issues: [] } } }; + } const parsed = parseLine(String(payload?.command || "")); if (parsed.kind === "usage") { return { ok: false, error: { code: "bad-request", message: USAGE, details: { issues: [] } } }; } - const cwd = agentCwd(agent); - const shell = await resolveShell(effective.shell, subprocess, signal); + const commandId = `shell-${randomUUID()}`; + let started = false; + let settled = false; + try { + if (signal?.aborted) throw signal.reason ?? new Error("Command cancelled"); + agent.session.append("command/run", { commandId, name: "!", args: parsed.command, source: { kind: "user" } }); + started = true; + const cwd = agentCwd(agent); + const shell = await resolveShell(effective.shell, subprocess, signal); - const outcome = await runCommand({ - command: parsed.command, - shell, - shellArgs, - cwd, - timeoutMs: effective.timeoutMs, - graceMs: effective.graceMs, - maxOutputBytes: effective.maxOutputBytes, - subprocess, - signal, - }); + const outcome = await runCommand({ + command: parsed.command, + shell, + shellArgs, + cwd, + timeoutMs: effective.timeoutMs, + graceMs: effective.graceMs, + maxOutputBytes: effective.maxOutputBytes, + subprocess, + signal, + }); - if (!outcome.ok) { - return { - ok: false, - error: { - code: "internal", - message: outcome.error instanceof Error ? outcome.error.message : String(outcome.error), - details: { issues: [] }, - }, - }; - } + if (!outcome.ok) { + throw outcome.error; + } - const outputText = formatResult(outcome); - const message = createAnalysisMessage({ - command: parsed.command, - cwd, - outputText, - summary: formatSummary(parsed.command), - template: effective.analysisPrompt, - }); - agent.followup(message); + const outputText = formatResult(outcome); + const message = createAnalysisMessage({ + command: parsed.command, + cwd, + outputText, + summary: formatSummary(parsed.command), + template: effective.analysisPrompt, + }); + agent.followup(message); + agent.session.append("command/done", { commandId, + kind: outcome.exitCode === 0 && !outcome.timedOut && !outcome.cancelled ? "success" : "error", text: outputText }); + settled = true; - return { ok: true, value: {} }; + return { ok: true, value: {} }; + } catch (error) { + const text = error instanceof Error ? error.message : String(error); + if (started && !settled) { + try { agent.session.append("command/done", { commandId, kind: "error", text }); } + catch (appendError) { ctx.logger?.warn?.(`dsh-shell-command: command audit failed: ${appendError?.message ?? appendError}`); } + } + return { ok: false, error: { code: "internal", message: text, details: { issues: [] } } }; + } }, { authority: "trusted-host" }), "shell-command bang RPC"); } } diff --git a/lib/inject.js b/lib/inject.js index c2ecd24..162efd3 100644 --- a/lib/inject.js +++ b/lib/inject.js @@ -21,17 +21,17 @@ const DEFAULT_HISTORY_NOTES = "请帮我分别分析这些历史终端记录。" /** Strip common ANSI/SGR escape sequences so model context stays readable. */ export function stripAnsi(text) { // eslint-disable-next-line no-control-regex - return text.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/\x1b\][^\x07]*(\x07|\x1b\\)/g, ""); + return text.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "").replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, ""); } /** Tail-retain a transcript down to `maxBytes` (UTF-8, on character boundaries). */ export function tailTranscript(text, maxBytes) { - if (Buffer.byteLength(text, "utf8") <= maxBytes) return { text, truncated: false }; - let slice = text; - while (Buffer.byteLength(slice, "utf8") > maxBytes && slice.length > 1) { - slice = slice.slice(Math.floor(slice.length / 2)); - } - return { text: slice, truncated: true }; + const bytes = Buffer.from(text, "utf8"); + if (bytes.length <= maxBytes) return { text, truncated: false }; + let start = bytes.length - maxBytes; + // Skip continuation bytes instead of returning a partial UTF-8 character. + while (start < bytes.length && (bytes[start] & 0xc0) === 0x80) start++; + return { text: bytes.subarray(start).toString("utf8"), truncated: true }; } /** diff --git a/lib/message.js b/lib/message.js index 601bacc..ba24f05 100644 --- a/lib/message.js +++ b/lib/message.js @@ -37,10 +37,7 @@ function defaultPrompt(command, cwd, outputText) { */ export function createAnalysisMessage({ command, cwd, outputText, summary, template }) { const text = template - ? template - .replaceAll("{command}", command) - .replaceAll("{cwd}", cwd) - .replaceAll("{output}", outputText) + ? template.replace(/\{(command|cwd|output)\}/g, (_match, key) => ({ command, cwd, output: outputText })[key]) : defaultPrompt(command, cwd, outputText); return buildPluginMessage(text, summary); diff --git a/lib/rpc.js b/lib/rpc.js index 119fdd6..17e4c40 100644 --- a/lib/rpc.js +++ b/lib/rpc.js @@ -22,6 +22,11 @@ import { agentCwd } from "./util.js"; const RPC_CHANNEL = "/shell-term-rpc"; const WS_PATH = "/shell-term/ws"; +// Bound PTY allocation and reject coercible strings, fractions, NaN and Infinity. +function validSize(cols, rows) { + return [cols, rows].every((value) => Number.isInteger(value) && value >= 2 && value <= 1000); +} + /** Resolve the owning agent from a client-supplied session id. */ function resolveAgent(agents, sessionId) { return typeof sessionId === "string" ? agents?.get(sessionId) : undefined; @@ -46,17 +51,35 @@ export function registerTerminalRpc(deps) { return connection.rpc.handle(RPC_CHANNEL, async (endpoint, payload, _signal) => { const agent = resolveAgent(agents, payload?.sessionId); if (agent === undefined) return fail("session-not-found", `no live agent owns session "${String(payload?.sessionId)}"`); + const current = manager.get(String(agent.id)); + if (payload?.streamId !== undefined && payload.streamId !== current?.streamId) { + return fail("terminal-stale", "terminal stream is no longer current"); + } switch (endpoint) { case "open": { + if (!validSize(payload?.cols ?? 80, payload?.rows ?? 24)) return fail("bad-request", "invalid terminal dimensions"); const cwd = agentCwd(agent); - const handle = manager.open(String(agent.id), { - cwd, - cols: payload?.cols ?? 80, - rows: payload?.rows ?? 24, - }); + let handle; + try { + if (current && (current.exited || current.cwd !== cwd)) await manager.finish(String(agent.id)); + handle = manager.open(String(agent.id), { + cwd, + cols: payload?.cols ?? 80, + rows: payload?.rows ?? 24, + }); + } catch (error) { + return fail("internal", error instanceof Error ? error.message : String(error)); + } return ok({ streamId: handle.streamId, cwd }); } + case "resize": { + if (!validSize(payload?.cols, payload?.rows)) return fail("bad-request", "invalid terminal dimensions"); + if (current === undefined || current.exited) return fail("terminal-ended", "no live terminal"); + try { manager.resize(String(agent.id), payload.cols, payload.rows); } + catch (error) { return fail("internal", error instanceof Error ? error.message : String(error)); } + return ok({}); + } case "transcript": { const handle = manager.get(String(agent.id)); if (handle === undefined) return ok({ transcript: "", truncated: false, exitCode: null }); @@ -97,24 +120,12 @@ export function registerTerminalRpc(deps) { * no persisted file, no `.meta.json` sidecar, no history-tab entry. */ async function closeEndpoint({ manager, agent, logger }) { - const id = String(agent.id); - const { transcript, truncated, exitCode, hasInput } = manager.close(id); - - if (!hasInput) { - return ok({ transcriptPath: null, bytes: 0, exitCode }); - } - - const cwd = agentCwd(agent); - const bytes = Buffer.byteLength(transcript, "utf8"); - let transcriptPath; try { - transcriptPath = manager.persist(cwd, id, transcript, { exitCode, truncated }); + return ok(await manager.finish(String(agent.id))); } catch (error) { logger?.warn?.(`dsh-shell-command: transcript persist failed: ${error?.message ?? error}`); - transcriptPath = null; + return fail("internal", error instanceof Error ? error.message : String(error)); } - - return ok({ transcriptPath, bytes, exitCode }); } /** @@ -149,13 +160,15 @@ function historyReadEndpoint({ manager, agent, payload }) { * reference transcripts that actually belong to its own session. */ function historyInjectEndpoint({ manager, agent, payload }) { - const paths = Array.isArray(payload?.paths) ? payload.paths.filter((p) => typeof p === "string") : []; - if (paths.length === 0) return fail("bad-request", "paths must be a non-empty array of strings"); + if (!Array.isArray(payload?.paths) || payload.paths.length === 0 || payload.paths.some(p => typeof p !== "string")) { + return fail("bad-request", "paths must be a non-empty array of strings"); + } + const paths = [...new Set(payload.paths)]; const cwd = agentCwd(agent); const known = new Map(manager.list(cwd, String(agent.id)).map((entry) => [entry.path, entry])); - const entries = paths.map((p) => known.get(p)).filter((entry) => entry !== undefined); - if (entries.length === 0) return fail("bad-request", "no matching transcripts for this session"); + if (paths.some(p => !known.has(p))) return fail("bad-request", "one or more transcripts are no longer available for this session"); + const entries = paths.map(p => known.get(p)); const notes = typeof payload?.notes === "string" ? payload.notes : ""; agent.inject(buildHistoryNotesMessage(notes)); @@ -184,7 +197,10 @@ export function registerTerminalWs(deps) { return; } wss.handleUpgrade(req, socket, head, (ws) => { - manager.attachWs(sessionId, ws); + manager.attachWs(sessionId, ws, { + structured: url.searchParams.get("protocol") === "2", + streamId: url.searchParams.get("streamId") ?? undefined, + }); }); }, }), "shell-command terminal WebSocket"); @@ -202,8 +218,8 @@ export async function setupTerminalMode(ctx, config) { const connection = ctx.get("connection"); const agents = ctx.get("agents"); const webServer = ctx.get("webServer"); - if (connection === undefined || agents === undefined) { - ctx.logger?.warn?.("dsh-shell-command: terminal mode disabled (missing connection/agents services)"); + if (connection === undefined || agents === undefined || webServer === undefined) { + ctx.logger?.warn?.("dsh-shell-command: terminal mode disabled (missing connection/agents/webServer services)"); return () => {}; } @@ -227,6 +243,7 @@ export async function setupTerminalMode(ctx, config) { maxTranscriptBytes: config.terminalMaxTranscriptBytes, transcriptDir: config.terminalTranscriptDir, transcriptKeep: config.terminalTranscriptKeep, + graceMs: config.graceMs, logger: ctx.logger, }); diff --git a/lib/terminal.js b/lib/terminal.js index 03db92a..68a43a3 100644 --- a/lib/terminal.js +++ b/lib/terminal.js @@ -10,6 +10,7 @@ */ import { mkdirSync, writeFileSync, rmSync, readdirSync, readFileSync, statSync } from "node:fs"; import { join } from "node:path"; +import { randomUUID } from "node:crypto"; import { scrubbedParentEnv } from "@deepseek-ai/dsh-subprocess"; import { tailTranscript } from "./inject.js"; import { PLATFORM_SHELL } from "./exec.js"; @@ -33,7 +34,7 @@ export function defaultShell() { * WebSocket watchers streaming its output. */ class TerminalHandle { - constructor(pty, streamId, cwd, maxTranscriptBytes) { + constructor(pty, streamId, cwd, maxTranscriptBytes, onExit) { this.pty = pty; this.streamId = streamId; this.cwd = cwd; @@ -42,9 +43,13 @@ class TerminalHandle { this.transcriptTruncated = false; this.exited = false; this.exitCode = null; + this.closing = false; + this.transcriptPath = null; + this.done = new Promise((resolve) => { this.resolveExit = resolve; }); this.watchers = new Set(); - // True once any user-originated input frame is seen (WS message or the - // write() fallback). A PTY prints its shell banner/prompt unprompted, so + this.structuredWatchers = new Set(); + // True after an activity marker, legacy raw input, or write(). Structured + // input can be an automatic reply. A PTY prints its prompt unprompted, so // `transcript` is never truly empty — this is the real "did the user do // anything" signal, used to skip persisting/surfacing no-op sessions. this.hasInput = false; @@ -53,6 +58,13 @@ class TerminalHandle { this.pty.onExit(({ exitCode }) => { this.exited = true; this.exitCode = exitCode; + this.resolveExit(); + // Save before notifying clients. Natural exit must also be durable + // when no browser is connected to request a close RPC. + if (!this.closing) onExit(this); + for (const ws of this.structuredWatchers) { + if (ws.readyState === 1) ws.send(JSON.stringify({ type: "exit", exitCode })); + } }); } @@ -63,7 +75,8 @@ class TerminalHandle { this.transcript = tail.text; if (tail.truncated) this.transcriptTruncated = true; for (const ws of this.watchers) { - if (ws.readyState === 1 /* OPEN */) ws.send(data); + if (ws.readyState === 1 /* OPEN */) ws.send(this.structuredWatchers.has(ws) + ? JSON.stringify({ type: "output", data }) : data); } } } @@ -86,6 +99,7 @@ export function createTerminalManager(deps) { maxTranscriptBytes = 1 << 20, transcriptDir = ".dsh-shell-transcripts", transcriptKeep = 10, + graceMs = 3000, logger = { warn: () => {} }, } = deps; @@ -115,12 +129,24 @@ export function createTerminalManager(deps) { } opening.add(sessionId); - if (existing !== undefined) killQuiet(existing); - const streamId = `term-${sessionId}`; - const handle = new TerminalHandle(spawn(sessionId, cwd, cols, rows), streamId, cwd, maxTranscriptBytes); - sessions.set(sessionId, handle); - opening.delete(sessionId); - return handle; + try { + if (existing !== undefined) { + existing.closing = true; + killQuiet(existing); + saveHandle(sessionId, existing); + } + sessions.delete(sessionId); + const streamId = `term-${sessionId}-${randomUUID()}`; + const handle = new TerminalHandle(spawn(sessionId, cwd, cols, rows), streamId, cwd, maxTranscriptBytes, + (ended) => { + try { saveHandle(sessionId, ended); } + catch (error) { logger.warn?.(`dsh-shell-command: transcript persist failed: ${error?.message ?? error}`); } + }); + sessions.set(sessionId, handle); + return handle; + } finally { + opening.delete(sessionId); + } } /** Resolve the live terminal for a session, or undefined. */ @@ -129,25 +155,51 @@ export function createTerminalManager(deps) { } /** Attach a WebSocket: replay the transcript, then stream bytes both ways. */ - function attachWs(sessionId, ws) { + function attachWs(sessionId, ws, { structured = false, streamId } = {}) { const handle = get(sessionId); - if (handle === undefined) { + if (handle === undefined || (streamId !== undefined && streamId !== handle.streamId)) { ws.close(1011, "no terminal session"); return; } + const detach = () => { + handle.watchers.delete(ws); + handle.structuredWatchers.delete(ws); + }; + // Protocol/transport errors are emitted by ws, outside the JSON handler. + // They must not become an unhandled EventEmitter error in the host. + ws.on("error", detach); + ws.on("close", detach); handle.watchers.add(ws); - if (handle.transcript !== "") ws.send(handle.transcript); + if (structured) handle.structuredWatchers.add(ws); + if (handle.transcript !== "") ws.send(structured + ? JSON.stringify({ type: "output", data: handle.transcript }) : handle.transcript); + if (structured && handle.exited) ws.send(JSON.stringify({ type: "exit", exitCode: handle.exitCode })); ws.on("message", (data) => { - handle.hasInput = true; + if (handle.exited || handle.closing || !handle.watchers.has(ws) || get(sessionId) !== handle) return; + let input = data.toString("utf8"); + if (structured) { + let message; + try { message = JSON.parse(input); } catch { return; } + if (message?.type === "activity") { + handle.hasInput = true; + return; + } + if (message?.type === "binary" && Array.isArray(message.data) + && message.data.every((byte) => Number.isInteger(byte) && byte >= 0 && byte <= 255)) { + try { handle.pty.write(Buffer.from(message.data)); } catch { /* exited */ } + return; + } + if (message?.type !== "input" || typeof message.data !== "string") return; + input = message.data; + } else if (input !== "") { + handle.hasInput = true; + } try { - handle.pty.write(data.toString("utf8")); + handle.pty.write(input); } catch { // The PTY exited between the last frame and this write. } }); - ws.on("close", () => { - handle.watchers.delete(ws); - }); } function resize(sessionId, cols, rows) { @@ -169,8 +221,44 @@ export function createTerminalManager(deps) { const handle = sessions.get(sessionId); if (handle === undefined) return { transcript: "", truncated: false, exitCode: null, hasInput: false }; sessions.delete(sessionId); + handle.closing = true; killQuiet(handle); - return { transcript: handle.transcript, truncated: handle.transcriptTruncated, exitCode: handle.exitCode, hasInput: handle.hasInput }; + return { transcript: handle.transcript, truncated: handle.transcriptTruncated, exitCode: handle.exitCode, + hasInput: handle.hasInput, cwd: handle.cwd, transcriptPath: handle.transcriptPath }; + } + + function saveHandle(sessionId, handle) { + if (!handle.hasInput || handle.transcriptPath) return; + handle.transcriptPath = persist(handle.cwd, sessionId, handle.transcript, + { exitCode: handle.exitCode, truncated: handle.transcriptTruncated }); + } + + /** Drain exit output before persisting; failed writes remain retryable. */ + async function finish(sessionId) { + const handle = get(sessionId); + if (!handle) return { transcriptPath: null, bytes: 0, exitCode: null }; + if (handle.finishing) return handle.finishing; + handle.finishing = (async () => { + handle.closing = true; + killQuiet(handle); + const waitForExit = async () => { + let timer; + try { + return await Promise.race([handle.done.then(() => true), + new Promise(resolve => { timer = setTimeout(() => resolve(false), graceMs); })]); + } finally { clearTimeout(timer); } + }; + if (!handle.exited && !await waitForExit()) { + try { handle.pty.kill("SIGKILL"); } catch { /* exit may be in flight */ } + if (!await waitForExit()) throw new Error("Terminal did not exit after SIGKILL"); + } + saveHandle(sessionId, handle); + if (get(sessionId) === handle) sessions.delete(sessionId); + return { transcriptPath: handle.transcriptPath, + bytes: handle.hasInput ? Buffer.byteLength(handle.transcript, "utf8") : 0, exitCode: handle.exitCode }; + })(); + try { return await handle.finishing; } + finally { handle.finishing = null; } } /** @@ -219,10 +307,10 @@ export function createTerminalManager(deps) { return []; } const logs = names - .filter((name) => name.startsWith(`${sessionId}-`) && name.endsWith(".log")) + .filter((name) => ownsLog(name, sessionId)) .sort() .reverse(); - return logs.map((name) => { + return logs.flatMap((name) => { const file = join(dir, name); const metaFile = join(dir, name.replace(/\.log$/, ".meta.json")); let meta; @@ -231,15 +319,17 @@ export function createTerminalManager(deps) { } catch { meta = null; } - const stat = statSync(file); - return { + let stat; + try { stat = statSync(file); } catch { return []; } + if (!stat.isFile()) return []; + return [{ path: file, name, bytes: stat.size, timestamp: meta?.timestamp ?? stat.mtime.toISOString(), exitCode: meta?.exitCode ?? null, truncated: meta?.truncated === true, - }; + }]; }); } @@ -252,7 +342,7 @@ export function createTerminalManager(deps) { function prune(dir, sessionId) { try { const files = readdirSync(dir) - .filter((name) => name.startsWith(`${sessionId}-`) && name.endsWith(".log")) + .filter((name) => ownsLog(name, sessionId)) .sort() .reverse(); for (const name of files.slice(transcriptKeep)) { @@ -268,9 +358,15 @@ export function createTerminalManager(deps) { } } + function ownsLog(name, sessionId) { + // A prefix check alone lets owner "a" see/prune owner "a-b"'s logs. + return name.startsWith(`${sessionId}-`) + && /^\d{4}-\d{2}-\d{2}T\d{2}-\d{2}-\d{2}-\d{3}Z(?:-\d+)?\.log$/.test(name.slice(sessionId.length + 1)); + } + function killQuiet(handle) { try { - handle.pty.kill(); + if (!handle.exited) handle.pty.kill(); } catch { // Already dead; ignore. } @@ -282,6 +378,7 @@ export function createTerminalManager(deps) { } } handle.watchers.clear(); + handle.structuredWatchers.clear(); } function disposeAll() { @@ -289,5 +386,5 @@ export function createTerminalManager(deps) { sessions.clear(); } - return { open, get, attachWs, resize, write, close, persist, list, readTranscript, disposeAll }; + return { open, get, attachWs, resize, write, close, finish, persist, list, readTranscript, disposeAll }; } diff --git a/package.json b/package.json index b7c0883..4505a9d 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "dsh-shell-command", - "version": "0.1.0", + "version": "0.2.0", "description": "DeepSeek Harness (DSH) plugin: a /! command trigger (run one command, analyze output, inspired by Claude Code's ! gesture) and a /terminal command (interactive PTY popup with on-demand history reference).", "license": "MIT", "type": "module", @@ -24,10 +24,15 @@ "files": [ "lib/**", "cordis.patch.yml", - "LICENSE" + "LICENSE", + "scripts/setup-local.mjs", + "README.zh.md", + "CHANGELOG.md", + "THIRD_PARTY_NOTICES.md" ], "publishConfig": { - "access": "public" + "access": "public", + "registry": "https://registry.npmjs.org" }, "dsh": { "bundle": { @@ -47,17 +52,19 @@ "dependencies": { "@deepseek-ai/schemastery": "^3.18.1", "node-pty": "^1.1.0", - "ws": "^8.21.0" + "ws": "^8.21.0", + "@xterm/xterm": "6.0.0", + "@xterm/addon-fit": "0.11.0" }, "peerDependencies": { "@deepseek-ai/cordis": "^4.0.1", - "@deepseek-ai/dsh-agent": "^0.1.0-rc.6", - "@deepseek-ai/dsh-client-connection": "^0.1.0-rc.6", - "@deepseek-ai/dsh-client-runtime": "^0.1.0-rc.6", - "@deepseek-ai/dsh-client-ui-input-trigger": "^0.1.0-rc.6", - "@deepseek-ai/dsh-client-ui-slots": "^0.1.0-rc.6", - "@deepseek-ai/dsh-llm": "^0.1.0-rc.6", - "@deepseek-ai/dsh-subprocess": "^0.1.0-rc.6" + "@deepseek-ai/dsh-agent": "^0.1.0-rc.6 || ^0.1.1-rc.2", + "@deepseek-ai/dsh-client-connection": "^0.1.0-rc.6 || ^0.1.1-rc.2", + "@deepseek-ai/dsh-client-runtime": "^0.1.0-rc.6 || ^0.1.1-rc.2", + "@deepseek-ai/dsh-client-ui-input-trigger": "^0.1.0-rc.6 || ^0.1.1-rc.2", + "@deepseek-ai/dsh-client-ui-slots": "^0.1.0-rc.6 || ^0.1.1-rc.2", + "@deepseek-ai/dsh-llm": "^0.1.0-rc.6 || ^0.1.1-rc.2", + "@deepseek-ai/dsh-subprocess": "^0.1.0-rc.6 || ^0.1.1-rc.2" }, "keywords": [ "dsh", @@ -68,5 +75,32 @@ "slash-command", "terminal", "claude-code" - ] + ], + "scripts": { + "setup:local": "node scripts/setup-local.mjs", + "test": "node test/setup-local.mjs && node test/unit.mjs && node test/smoke.mjs && node test/smoke-terminal.mjs && node test/terminal-protocol.mjs && node test/regressions.mjs", + "prepublishOnly": "npm run build && npm test && npm run test:browser", + "build": "node scripts/build-client.mjs", + "test:browser": "node test/browser.mjs" + }, + "peerDependenciesMeta": { + "@deepseek-ai/dsh-client-connection": { + "optional": true + }, + "@deepseek-ai/dsh-client-runtime": { + "optional": true + }, + "@deepseek-ai/dsh-client-ui-input-trigger": { + "optional": true + }, + "@deepseek-ai/dsh-client-ui-slots": { + "optional": true + } + }, + "devDependencies": { + "tsdown": "0.23.1", + "playwright": "1.64.1", + "react": "18.3.1", + "react-dom": "18.3.1" + } } diff --git a/scripts/build-client.mjs b/scripts/build-client.mjs new file mode 100644 index 0000000..3f53f6f --- /dev/null +++ b/scripts/build-client.mjs @@ -0,0 +1,31 @@ +import { build } from "tsdown"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { resolve } from "node:path"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const css = readFileSync(new URL(import.meta.resolve("@xterm/xterm/css/xterm.css")), "utf8"); +await build({ + cwd: root, + entry: { client: "src/client.js" }, + outDir: "lib", + clean: false, + format: "cjs", + platform: "browser", + target: "es2022", + dts: false, + sourcemap: false, + minify: true, + outputOptions: { + entryFileNames: "[name].js", + banner: 'window.__ModuleLoader__.load({ id: "dsh-shell-command", factory: (require) => {\nvar module = { exports: {} }; var exports = module.exports;', + footer: "return module.exports;\n} });", + }, + deps: { + onlyBundle: [/^@xterm\//], + alwaysBundle: [/^@xterm\//], + neverBundle: ["react", "react-dom", /^@deepseek-ai\//], + }, + define: { __XTERM_CSS__: JSON.stringify(css) }, +}); +console.log(`DSH browser bundle ready: ${resolve(root, "lib/client.js")}`); diff --git a/scripts/setup-local.mjs b/scripts/setup-local.mjs new file mode 100644 index 0000000..57041c9 --- /dev/null +++ b/scripts/setup-local.mjs @@ -0,0 +1,72 @@ +// Initialize a link: checkout with this DSH installation's host peer packages. +import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, symlinkSync } from 'node:fs'; +import { homedir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { spawnSync } from 'node:child_process'; + +const root = fileURLToPath(new URL('../', import.meta.url)); +const manifest = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')); +const args = process.argv.slice(2); +if (args.some(arg => arg !== '--skip-install')) { + console.error('Usage: npm run setup:local -- [--skip-install]'); + process.exit(1); +} + +try { + let home = process.env.DSH_HOME?.trim() || join(homedir(), '.dsh'); + if (home === '~') home = homedir(); + else if (home.startsWith('~/')) home = join(homedir(), home.slice(2)); + const shared = join(resolve(home), 'profiles', 'node_modules'); + const peers = []; + for (const name of Object.keys(manifest.peerDependencies)) { + const source = join(shared, name); + if (!existsSync(source)) { + if (manifest.peerDependenciesMeta?.[name]?.optional) continue; + throw new Error(`Missing host peer ${name}. Initialize a DSH web profile first (${shared}).`); + } + peers.push({ name, source, target: join(root, 'node_modules', name) }); + } + + // Check before installation; never overwrite an unrelated peer or broken link. + const checkTarget = ({ source, target }) => { + try { + lstatSync(target); + } catch (error) { + if (error.code === 'ENOENT') return false; + throw error; + } + if (!existsSync(target) || realpathSync(target) !== realpathSync(source)) { + throw new Error(`Inspect the existing peer before retrying: ${target}`); + } + return true; + }; + peers.forEach(checkTarget); + if (!args.includes('--skip-install')) { + const npmCli = process.env.npm_execpath; + const command = npmCli ? process.execPath : process.platform === 'win32' ? 'npm.cmd' : 'npm'; + const installArgs = ['install', '--legacy-peer-deps', '--package-lock=false', '--no-audit', '--no-fund']; + const result = spawnSync(command, npmCli ? [npmCli, ...installArgs] : installArgs, { cwd: root, stdio: 'inherit' }); + if (result.error) throw result.error; + if (result.status !== 0) throw new Error(`Dependency installation failed (exit ${result.status}).`); + } + for (const peer of peers) { + if (checkTarget(peer)) continue; + mkdirSync(dirname(peer.target), { recursive: true }); + symlinkSync(peer.source, peer.target, process.platform === 'win32' ? 'junction' : 'dir'); + console.log(`Linked ${peer.name}`); + } + // Verify ESM imports from the checkout's own paths, including native PTY load. + await import(new URL('../lib/index.js', import.meta.url)); + await import('node-pty'); + await import('ws'); + if (existsSync(join(root, 'src/client.js'))) { + const build = spawnSync(process.execPath, [join(root, 'scripts/build-client.mjs')], { cwd: root, stdio: 'inherit' }); + if (build.error) throw build.error; + if (build.status !== 0) throw new Error(`Browser build failed (exit ${build.status}).`); + } + console.log('Local dependencies ready. Run npm test, then restart dsh web.'); +} catch (error) { + console.error(`Local setup failed: ${error.message}`); + process.exitCode = 1; +} diff --git a/src/client.js b/src/client.js new file mode 100644 index 0000000..1fcd882 --- /dev/null +++ b/src/client.js @@ -0,0 +1,599 @@ +// Browser source. scripts/build-client.mjs produces lib/client.js. +import React from "react"; +import ReactDOM from "react-dom"; +import { TerminalView } from "./terminal-view.js"; +import { TerminalController } from "./terminal-controller.js"; + +const RPC_CHANNEL_BANG = "/shell-bang-rpc"; + +const PANEL_MIN_WIDTH = 340; +const PANEL_MIN_HEIGHT = 220; + +function clampNum(value, min, max) { + return Math.max(min, Math.min(value, max)); +} + +/* ANSI/SGR foreground palette (standard 30–37, bright 90–97). */ +const ANSI_COLORS = ["#2e2e2e", "#d64545", "#2e9e4f", "#c9a227", "#3b7dd8", "#9a4ec2", "#1fa8a0", "#d8d8d8"]; +const ANSI_BRIGHT = ["#555555", "#ff6b6b", "#3ddc84", "#f0d264", "#6aa5f8", "#c086e8", "#3dd0c8", "#ffffff"]; + +/* + * Render ANSI/SGR-colored text as React spans (green prompt, red errors, …). + * Matches the full CSI grammar (cursor moves, clear-line, etc.), not just + * SGR — non-SGR sequences are consumed and dropped rather than leaking raw + * escape bytes into the rendered scrollback (mirrors stripAnsi in inject.js). + */ +function renderAnsi(text, keyPrefix) { + // Strip OSC sequences (e.g. bash's `\x1b]0;title\x07` window-title set) + // before the CSI/SGR tokenizer runs below — otherwise they render as + // literal garbled bytes right before the real (correctly colored) prompt. + // Mirrors stripAnsi's OSC handling in inject.js. + const stripped = text.replace(/\x1b\][\s\S]*?(?:\x07|\x1b\\)/g, ""); + const re = /\x1b\[([0-9;?]*[ -/]*)([@-~])/g; + const elements = []; + let last = 0; + let fg = null; + let bold = false; + let key = 0; + const flush = (chunk, color, weight) => { + if (chunk.length === 0) return; + const style = {}; + if (color !== null) style.color = color; + if (weight) style.fontWeight = "bold"; + elements.push(React.createElement("span", { key: `${keyPrefix}-${key++}`, style }, chunk)); + }; + let match; + while ((match = re.exec(stripped)) !== null) { + if (match.index > last) flush(stripped.slice(last, match.index), fg, bold); + if (match[2] !== "m") { + // Non-SGR CSI (cursor move, clear-line, …): drop, don't render. + last = re.lastIndex; + continue; + } + const raw = match[1]; + const codes = raw === "" ? [0] : raw.split(";").map((n) => Number(n)).filter((n) => !Number.isNaN(n)); + for (const code of codes) { + if (code === 0) { fg = null; bold = false; } + else if (code === 1) bold = true; + else if (code === 22) bold = false; + else if (code >= 30 && code <= 37) fg = ANSI_COLORS[code - 30]; + else if (code >= 90 && code <= 97) fg = ANSI_BRIGHT[code - 90]; + else if (code === 39) fg = null; + } + last = re.lastIndex; + } + if (last < stripped.length) flush(stripped.slice(last), fg, bold); + return elements; +} + +/* ---- React component ---- */ +const panelStyle = { + boxSizing: "border-box", + position: "fixed", + zIndex: 1000, + display: "flex", + flexDirection: "column", + border: "1px solid var(--dsw-alias-border-l1, color-mix(in srgb, currentColor 22%, transparent))", + borderRadius: 12, + // Portaled outside the chat: use the host's actual theme aliases as a pair. + background: "var(--dsw-alias-bg-layer-1, var(--color-surface, #141414))", + color: "var(--dsw-alias-label-primary, var(--color-text, #eeeeee))", + fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", + fontSize: 13, + boxShadow: "0 8px 30px rgba(0,0,0,.35)", + overflow: "hidden", +}; +const headerStyle = { + display: "flex", + alignItems: "center", + gap: 8, + justifyContent: "space-between", + padding: "8px 10px", + cursor: "move", + userSelect: "none", + borderBottom: "1px solid color-mix(in srgb, currentColor 16%, transparent)", + flex: "0 0 auto", +}; +const bodyStyle = { + flex: "1 1 auto", + display: "flex", + flexDirection: "column", + gap: 8, + padding: "10px 12px", + overflow: "auto", + minHeight: 0, +}; +const tabRowStyle = { display: "flex", gap: 4, flex: "0 0 auto" }; +const tabButtonStyle = (active) => ({ + appearance: "none", + border: "none", + borderBottom: active ? "2px solid var(--dsw-alias-state-business-primary, var(--color-accent, #3b7dd8))" : "2px solid transparent", + background: "transparent", + color: active ? "inherit" : "var(--dsw-alias-label-secondary, #aaaaaa)", + cursor: "pointer", + fontSize: 12, + fontWeight: active ? 700 : 400, + padding: "4px 2px", +}); +const scrollStyle = { + overflow: "auto", + whiteSpace: "pre-wrap", + wordBreak: "break-all", + flex: "1 1 auto", + minHeight: 60, + padding: 6, + borderRadius: 6, + background: "var(--dsw-alias-bg-module-platform, rgba(0,0,0,.35))", + lineHeight: 1.45, +}; +const buttonStyle = { + appearance: "none", + border: "1px solid color-mix(in srgb, currentColor 24%, transparent)", + borderRadius: 7, + padding: "3px 10px", + background: "transparent", + color: "inherit", + cursor: "pointer", + fontSize: 12, +}; +const inputStyle = { + flex: 1, background: "transparent", color: "inherit", border: "1px solid #555", + borderRadius: 6, padding: "4px 8px", fontFamily: "inherit", fontSize: 13, +}; +const resizeGripStyle = { + position: "absolute", + right: 0, + bottom: 0, + width: 16, + height: 16, + cursor: "nwse-resize", + background: "linear-gradient(135deg, transparent 50%, color-mix(in srgb, currentColor 35%, transparent) 50%)", +}; +const historyRowStyle = { + display: "flex", + flexDirection: "column", + gap: 4, + padding: "6px 8px", + borderRadius: 6, + border: "1px solid color-mix(in srgb, currentColor 14%, transparent)", +}; +const historyHeaderRowStyle = { display: "flex", alignItems: "center", gap: 8 }; +const badgeStyle = (tone) => ({ + fontSize: 11, + padding: "1px 6px", + borderRadius: 999, + background: tone === "warn" ? "color-mix(in srgb, #e0b95e 30%, transparent)" : "color-mix(in srgb, currentColor 14%, transparent)", +}); + +/** Drag the header to move the panel; clamps to the viewport. */ +function useDrag(controller, state) { + const dragRef = React.useRef(null); + const onHeaderMouseDown = (event) => { + if (event.button !== 0) return; + const rect = event.currentTarget.parentElement.getBoundingClientRect(); + dragRef.current = { startX: event.clientX, startY: event.clientY, originX: rect.left, originY: rect.top }; + event.preventDefault(); + }; + React.useEffect(() => { + const onMove = (event) => { + if (dragRef.current === null) return; + const { startX, startY, originX, originY } = dragRef.current; + const width = state.width; + const height = state.height; + const nextX = clampNum(originX + (event.clientX - startX), 0, Math.max(0, window.innerWidth - width)); + const nextY = clampNum(originY + (event.clientY - startY), 0, Math.max(0, window.innerHeight - height)); + controller.setGeometry({ x: nextX, y: nextY }); + }; + const onUp = () => { dragRef.current = null; }; + window.addEventListener("mousemove", onMove); + window.addEventListener("mouseup", onUp); + return () => { + window.removeEventListener("mousemove", onMove); + window.removeEventListener("mouseup", onUp); + }; + }, [controller, state.width, state.height]); + return onHeaderMouseDown; +} + +/** Drag the corner grip to resize the panel; clamps to a minimum and the viewport. */ +function useResize(controller, state) { + const resizeRef = React.useRef(null); + const onGripMouseDown = (event) => { + if (event.button !== 0) return; + resizeRef.current = { startX: event.clientX, startY: event.clientY, startWidth: state.width, startHeight: state.height }; + event.preventDefault(); + event.stopPropagation(); + }; + React.useEffect(() => { + const onMove = (event) => { + if (resizeRef.current === null) return; + const { startX, startY, startWidth, startHeight } = resizeRef.current; + const maxWidth = Math.max(PANEL_MIN_WIDTH, window.innerWidth - (state.x ?? 0)); + const maxHeight = Math.max(PANEL_MIN_HEIGHT, window.innerHeight - (state.y ?? 0)); + const nextWidth = clampNum(startWidth + (event.clientX - startX), PANEL_MIN_WIDTH, maxWidth); + const nextHeight = clampNum(startHeight + (event.clientY - startY), PANEL_MIN_HEIGHT, maxHeight); + controller.setGeometry({ width: nextWidth, height: nextHeight }); + }; + const onUp = () => { resizeRef.current = null; }; + window.addEventListener("mousemove", onMove); + window.addEventListener("mouseup", onUp); + return () => { + window.removeEventListener("mousemove", onMove); + window.removeEventListener("mouseup", onUp); + }; + }, [controller, state.x, state.y]); + return onGripMouseDown; +} + +function formatExitBadge(exitCode) { + if (exitCode === null || exitCode === undefined) return null; + return exitCode === 0 + ? React.createElement("span", { style: badgeStyle("ok") }, "退出码 0") + : React.createElement("span", { style: badgeStyle("warn") }, `退出码 ${exitCode}`); +} + +function HistoryTab({ controller, state }) { + const { entries, loading, error } = state.history; + // HistoryTab remounts on every tab switch (see setTab's comment), so + // this initializer runs exactly once per mount — good enough to + // pre-check the entry a just-ended close jumped here to show, without + // needing an extra effect to keep it in sync. + const [selected, setSelected] = React.useState(() => + state.pendingSelectPath ? new Set([state.pendingSelectPath]) : new Set()); + const [notes, setNotes] = React.useState(""); + const [status, setStatus] = React.useState(null); // { kind: "ok" | "error", text } + + React.useEffect(() => { controller.loadHistory(); /* refresh on mount */ }, [controller]); + +// Auto-expand the just-closed entry's preview when the panel jumps here +// after exit() (only for pendingSelectPath, not for manually-selected entries). +React.useEffect(() => { + if (state.pendingSelectPath) { + controller.togglePreview(state.pendingSelectPath); + } +}, [state.pendingSelectPath, controller]); + + const toggleSelected = (path) => { + setSelected((prev) => { + const next = new Set(prev); + if (next.has(path)) next.delete(path); else next.add(path); + return next; + }); + }; + + const onReferenceInject = () => { + const paths = Array.from(selected); + if (paths.length === 0) return; + setStatus(null); + controller.referenceInject(paths, notes) + .then((value) => { + setStatus({ kind: "ok", text: `已引用 ${value.referenced} 段历史记录,模型正在分析…` }); + setSelected(new Set()); + setNotes(""); + }) + .catch((err) => setStatus({ kind: "error", text: err instanceof Error ? err.message : String(err) })); + }; + + if (loading && entries.length === 0) { + return React.createElement("div", { style: { opacity: .7 } }, "正在加载历史记录…"); + } + if (error !== null) { + return React.createElement("div", { style: { color: "var(--color-error, #e06c75)" } }, error); + } + if (entries.length === 0) { + return React.createElement("div", { style: { opacity: .7 } }, "暂无历史终端记录。"); + } + + return React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 8, minHeight: 0, flex: "1 1 auto", overflow: "auto" } }, + React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 6, overflow: "auto" } }, + entries.map((entry) => { + const isOpen = state.preview !== null && state.preview.path === entry.path; + return React.createElement("div", { key: entry.path, style: historyRowStyle }, + React.createElement("div", { style: historyHeaderRowStyle }, + React.createElement("input", { + type: "checkbox", + checked: selected.has(entry.path), + onChange: () => toggleSelected(entry.path), + }), + React.createElement("span", { style: { flex: "1 1 auto", fontSize: 12 } }, new Date(entry.timestamp).toLocaleString()), + formatExitBadge(entry.exitCode), + entry.truncated ? React.createElement("span", { style: badgeStyle("warn") }, "已截断") : null, + React.createElement("button", { + type: "button", + style: { ...buttonStyle, padding: "2px 8px" }, + onClick: () => controller.togglePreview(entry.path), + }, isOpen ? "收起" : "查看"), + ), + isOpen ? React.createElement("div", { style: { ...scrollStyle, maxHeight: 160, flex: "0 0 auto" } }, + state.preview.loading ? "正在读取…" : renderAnsi(state.preview.transcript || "", entry.path), + ) : null, + ); + }), + ), + React.createElement("div", { style: { display: "flex", flexDirection: "column", gap: 6, flex: "0 0 auto", borderTop: "1px solid color-mix(in srgb, currentColor 14%, transparent)", paddingTop: 8 } }, + React.createElement("textarea", { + value: notes, + placeholder: "(可选)已选中多段记录时,可在此补充自然语言说明…", + onChange: (event) => setNotes(event.target.value), + style: { ...inputStyle, minHeight: 40, resize: "vertical", fontFamily: "inherit" }, + }), + React.createElement("div", { style: { fontSize: 11, opacity: 0.6, marginTop: -2 } }, + "提示:不输入时的默认消息为「请帮我分别分析这些历史终端记录。」" + ), + React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 8 } }, + React.createElement("button", { + type: "button", + style: buttonStyle, + disabled: selected.size === 0, + onClick: onReferenceInject, + }, selected.size > 1 ? `引用并分析 (${selected.size} 段)` : "引用并分析"), + // Dismiss also closes any remaining server handle after a stream error. + (state.status === "ended" || state.status === "error") ? React.createElement("button", { + type: "button", + style: buttonStyle, + onClick: () => controller.dismiss(), + }, "直接退出,本次不分析") : null, + status !== null ? React.createElement("span", { + style: { fontSize: 12, color: status.kind === "error" ? "var(--color-error, #e06c75)" : "inherit", opacity: .85 }, + }, status.text) : null, + ), + ), + ); +} + +function ShellTerminal({ controller }) { + const state = React.useSyncExternalStore( + (listener) => controller.state.subscribe(listener), + () => controller.state.getSnapshot(), + ); + const panelRef = React.useRef(null); + + // First open: default to a centered position now that we know the viewport. + React.useEffect(() => { + if (state.status !== "closed" && state.x === null) { + const x = clampNum((window.innerWidth - state.width) / 2, 0, Math.max(0, window.innerWidth - state.width)); + const y = clampNum((window.innerHeight - state.height) / 2, 0, Math.max(0, window.innerHeight - state.height)); + controller.setGeometry({ x, y }); + } + }, [controller, state.status, state.x, state.width, state.height]); + + const onHeaderMouseDown = useDrag(controller, state); + const onGripMouseDown = useResize(controller, state); + + if (state.status === "closed" || state.x === null) return null; + + const children = []; + + // Header (drag handle). "退出" ends the live PTY (a pure persistence + // step, no consent prompt); once ended, the same slot becomes "关闭 + // 面板" to dismiss the panel entirely (the panel stays open after + // exit() so the user can act on the history tab it jumps to). + const isEnded = state.status === "ended" || state.status === "error"; + const headerButtonLabel = isEnded ? (state.status === "error" ? "关闭" : "关闭面板") : "退出"; + const headerButtonDisabled = state.status === "opening" || state.status === "exiting"; + children.push(React.createElement("div", { + key: "h", + style: headerStyle, + onMouseDown: onHeaderMouseDown, + }, + React.createElement("span", { style: { fontWeight: 700, flex: "0 0 auto" } }, "/terminal"), + React.createElement("div", { style: tabRowStyle, onMouseDown: (event) => event.stopPropagation() }, + React.createElement("button", { type: "button", style: tabButtonStyle(state.tab === "live"), onClick: () => controller.setTab("live") }, "会话"), + React.createElement("button", { type: "button", style: tabButtonStyle(state.tab === "history"), onClick: () => controller.setTab("history") }, "历史"), + ), + React.createElement("button", { + type: "button", + style: { ...buttonStyle, flex: "0 0 auto" }, + disabled: headerButtonDisabled, + onMouseDown: (event) => event.stopPropagation(), + onClick: () => (isEnded ? controller.dismiss() : controller.exit()), + }, headerButtonLabel), + )); + + const body = []; + // Keep xterm mounted while browsing history: its cursor and alt buffer are stateful. + body.push(React.createElement(TerminalView, { key: `terminal-${state.epoch}`, controller, + visible: state.tab === "live", status: state.status })); + if (state.tab === "live" && state.status === "open") { + body.push(React.createElement("div", { key: "controls", style: { display: "flex", gap: 8, flex: "0 0 auto" } }, + ...[["C", "\x03", "中断"], ["D", "\x04", "结束/EOF"], ["Z", "\x1a", "挂起"]].map(([key, bytes, label]) => + React.createElement("button", { key, type: "button", style: buttonStyle, + "aria-label": `Ctrl+${key}(${label})`, title: `Ctrl+${key}(${label})`, + onClick: () => { controller.markActivity(); controller.sendRaw(bytes); controller.terminal?.focus(); }, + }, `^${key}`)), + )); + } + if (state.status === "opening") body.push(React.createElement("div", { key: "opening" }, "正在打开终端…")); + if (state.status === "exiting") body.push(React.createElement("div", { key: "exiting" }, "正在结束终端会话…")); + if (state.error) body.push(React.createElement("div", { key: "err", role: "alert", style: { color: "#e06c75" } }, state.error)); + if (state.tab === "history") body.push(React.createElement(HistoryTab, { key: `history-${state.pendingSelectPath || "live"}`, controller, state })); + if (state.tab === "live" && state.status === "ended") body.push(React.createElement("div", { key: "ended-hint" }, "终端会话已结束,如需继续请重新输入 /terminal。")); + children.push(React.createElement("div", { key: "body", style: { ...bodyStyle, overflow: "hidden" } }, body)); + + const panel = React.createElement("div", { + ref: panelRef, + style: { ...panelStyle, left: state.x, top: state.y, width: state.width, height: state.height }, + role: "dialog", + "aria-label": "shell terminal", + }, + children, + React.createElement("div", { style: resizeGripStyle, onMouseDown: onGripMouseDown }), + ); + + return ReactDOM.createPortal(panel, document.body); +} + +/* ---- input trigger source: a standalone /terminal command (no host-command + * collision, unlike `/shell --terminal` which the command directory claims + * first). Mirrors dsh-btw's /btw source exactly: candidates + onPick + + * matchSpace + a Promise-returning matchEnter. ---- */ +function terminalClaim(controller) { + return { + token: "/terminal ", + hint: "[interactive terminal]", + submit: () => { + controller.open(); + return Promise.resolve({ kind: "success" }); + }, + }; +} + +function enterClaim(controllerFor, sessionId, line) { + const match = /^\s*\/terminal\s*$/iu.exec(line); + if (match === null) return undefined; + return { claim: terminalClaim(controllerFor(sessionId)) }; +} + +function createTerminalSource(controllerFor) { + return { + trigger: "/", + name: "terminal", + order: -5, + candidates(_session, request) { + if (request.position !== "leading" || !"terminal".startsWith(request.query.toLowerCase())) return Promise.resolve([]); + return Promise.resolve([{ + name: "terminal", + description: "Open an interactive terminal (reference history on demand)", + hint: "[terminal]", + }]); + }, + onPick(pick) { + return { claim: terminalClaim(controllerFor(pick.session.sessionId)) }; + }, + matchSpace(session, token) { + return /^\/terminal$/iu.test(token) ? { claim: terminalClaim(controllerFor(session.sessionId)) } : undefined; + }, + matchEnter(session, line) { + return Promise.resolve(enterClaim(controllerFor, session.sessionId, line)); + }, + }; +} + +/* ---- '/!' shell command trigger source: one-shot command execution + analysis ---- */ +function createBangSource(connection) { + // Shared RPC invoker + const runCommand = (sessionId, command) => { + if (command.length === 0) { + return Promise.resolve({ kind: "error", text: "Usage: /! " }); + } + return connection.rpc.call(RPC_CHANNEL_BANG, "run", { sessionId, command }, undefined) + .then((result) => { + if (result === undefined || !result.ok) { + return { kind: "error", text: result && result.error ? result.error.message : "command execution failed" }; + } + return { kind: "success" }; + }) + .catch((error) => ({ kind: "error", text: error instanceof Error ? error.message : String(error) })); + }; + + return { + trigger: "/", + name: "shell-bang", + order: -10, + candidates(_session, request) { + if (request.position !== "leading") return Promise.resolve([]); + if (!"!".startsWith(request.query.toLowerCase())) return Promise.resolve([]); + return Promise.resolve([{ + name: "!", + description: "Run a shell command and analyze its output", + hint: "", + }]); + }, + onPick({ session }) { + return { + claim: { + token: "/!", + hint: "", + submit: (line) => { + const command = line.replace(/^\/!\s*/, "").trim(); + return runCommand(session.sessionId, command); + }, + }, + }; + }, + matchSpace(session, token) { + if (token !== "/!") return undefined; + return { + claim: { + token: "/! ", + hint: "", + submit: (line) => { + const command = line.replace(/^\/!\s*/, "").trim(); + return runCommand(session.sessionId, command); + }, + }, + }; + }, + matchEnter(session, line) { + const match = /^\/!\s*(.+)$/u.exec(line); + if (match === null) return Promise.resolve(undefined); + const command = match[1].trim(); + return Promise.resolve({ + claim: { + token: line, + hint: "", + submit: () => runCommand(session.sessionId, command), + }, + }); + }, + }; +} + +/* ---- plugin apply ---- */ +const name = "shell-command-client"; +const inject = ["connection", "inputTriggers", "sessions", "slots"]; + +function apply(ctx) { + ctx.effect(() => { + const style = document.createElement("style"); + style.dataset.dshShellXterm = ""; + style.textContent = __XTERM_CSS__; + document.head.appendChild(style); + return () => style.remove(); + }, "shell-command: xterm styles"); + const connection = ctx.get("connection"); + const inputTriggers = ctx.get("inputTriggers"); + const sessions = ctx.get("sessions"); + const slots = ctx.slots; + if (connection === undefined || inputTriggers === undefined || sessions === undefined || slots === undefined) { + throw new Error("dsh-shell-command/client requires connection, inputTriggers, sessions, and slots"); + } + + const controllers = new Map(); + const controllerFor = (sessionId) => { + let controller = controllers.get(sessionId); + if (controller === undefined) { + controller = new TerminalController(connection, sessionId); + controllers.set(sessionId, controller); + } + return controller; + }; + + ctx.effect(() => inputTriggers.registerSource(createTerminalSource(controllerFor)), "shell-command: terminal input source"); + ctx.effect(() => inputTriggers.registerSource(createBangSource(connection)), "shell-command: bang input source"); + ctx.effect(() => () => { + for (const controller of controllers.values()) controller.dispose(); + controllers.clear(); + }, "shell-command: terminal controllers"); + + // The panel is portal-rendered to document.body (see ShellTerminal), so + // this slot registration only needs to mount the component once per + // session — it no longer occupies visible space in the input dock. + ctx.slots.inject("conversation.input.dock", () => ctx.slots.register({ + name: "conversation.input.dock", + id: "shell-term-panel", + order: 3, + inject: (sessionId) => { + const actx = sessions.scope(sessionId); + if (actx === undefined) throw new Error(`dsh-shell-command: session "${String(sessionId)}" resolved no client scope`); + const controller = controllerFor(sessionId); + actx.effect(() => () => { + if (controllers.get(sessionId) === controller) controllers.delete(sessionId); + controller.dispose(); + }, "shell-command: session terminal"); + return { controller }; + }, + }, ShellTerminal)); +} + +export { apply, inject, name }; diff --git a/src/terminal-controller.js b/src/terminal-controller.js new file mode 100644 index 0000000..62a12ca --- /dev/null +++ b/src/terminal-controller.js @@ -0,0 +1,253 @@ +import { createSnapshotStore } from "@deepseek-ai/dsh-client-runtime/client"; +const RPC_CHANNEL = "/shell-term-rpc"; + +/** Owns one PTY stream; rendering never buffers input or replays on tab switches. */ +class TerminalController { + constructor(connection, sessionId) { + this.connection = connection; + this.sessionId = sessionId; + this.ws = null; + this.streamId = null; + this.transcript = ""; + this.outputListeners = new Set(); + this.generation = 0; + this.disposed = false; + this.activitySent = false; + this.closing = null; + this.previewRequest = 0; + this.historyRequest = 0; + this.state = createSnapshotStore({ + status: "closed", tab: "live", epoch: 0, x: null, y: null, + width: 640, height: 440, + history: { entries: [], loading: false, error: null }, + preview: null, pendingSelectPath: null, error: null, + }); + } + + async call(endpoint, payload = {}) { + return this.connection.rpc.call(RPC_CHANNEL, endpoint, { sessionId: this.sessionId, ...payload }, undefined); + } + + async open() { + if (this.disposed || !["closed", "ended"].includes(this.state.getSnapshot().status)) return; + const generation = ++this.generation; + this.closeWs(); + this.transcript = ""; + this.activitySent = false; + this.setState({ status: "opening", tab: "live", epoch: generation, error: null, preview: null, pendingSelectPath: null }); + try { + const result = await this.call("open"); + if (!result?.ok) throw new Error(result?.error?.message || "open failed"); + const { streamId } = result.value; + if (this.disposed || generation !== this.generation) { + await this.call("close", { streamId }); + return; + } + this.streamId = streamId; + this.connectWs(generation); + } catch (error) { + if (generation === this.generation) this.fail(error); + } + } + + connectWs(generation) { + const proto = location.protocol === "https:" ? "wss:" : "ws:"; + const query = new URLSearchParams({ sessionId: this.sessionId, streamId: this.streamId, protocol: "2" }); + const ws = new WebSocket(`${proto}//${location.host}/shell-term/ws?${query}`); + this.ws = ws; + const current = () => !this.disposed && generation === this.generation && this.ws === ws; + ws.onopen = () => { if (current()) this.setState({ status: "open" }); }; + ws.onmessage = (event) => { + if (!current()) return; + let message; + try { message = JSON.parse(event.data); } catch { this.fail("Invalid terminal stream"); return; } + if (message === null || typeof message !== "object") { this.fail("Invalid terminal stream"); return; } + if (message.type === "output" && typeof message.data === "string") { + this.transcript += message.data; + if (this.transcript.length > 65536) { + let cut = this.transcript.length - 65536; + if (this.transcript.charCodeAt(cut) >= 0xdc00 && this.transcript.charCodeAt(cut) <= 0xdfff) cut++; + this.transcript = this.transcript.slice(cut); + } + for (const listener of this.outputListeners) listener(message.data); + } else if (message.type === "exit") { + this.exit(); + } + }; + ws.onerror = () => { if (current()) this.fail("终端连接失败,请结束会话后重新打开。"); }; + ws.onclose = () => { + if (!current()) return; + this.ws = null; + if (!["closed", "ended", "exiting"].includes(this.state.getSnapshot().status)) { + this.fail("终端连接已断开,请结束会话后重新打开。"); + } + }; + } + + subscribeOutput(listener) { + if (this.transcript) listener(this.transcript); + this.outputListeners.add(listener); + return () => this.outputListeners.delete(listener); + } + + sendFrame(frame) { + if (this.state.getSnapshot().status !== "open" || this.ws?.readyState !== 1) return; + this.ws.send(JSON.stringify(frame)); + } + + // Called only by DOM input gestures, never by xterm's automatic device replies. + markActivity() { + if (this.activitySent || this.state.getSnapshot().status !== "open") return; + this.sendFrame({ type: "activity" }); + this.activitySent = true; + } + + sendRaw(data) { this.sendFrame({ type: "input", data }); } + + async resize(cols, rows) { + if (this.state.getSnapshot().status !== "open") return; + const generation = this.generation; + try { + const result = await this.call("resize", { streamId: this.streamId, cols, rows }); + // Exit notification travels over WS and may arrive after this RPC reply. + if (!result?.ok && result?.error?.code === "terminal-ended") return; + // A late resize rejection during normal exit must not undo the close state. + if (!result?.ok && generation === this.generation && this.state.getSnapshot().status === "open") { + this.fail(result?.error?.message || "Terminal resize failed"); + } + } catch (error) { + if (generation === this.generation && this.state.getSnapshot().status === "open") this.fail(error); + } + } + + exit({ dismiss = false } = {}) { + if (this.closing) return this.closing; + if (!this.streamId) { + this.closeWs(); + if (dismiss) this.setState({ status: "closed" }); + return Promise.resolve(); + } + const generation = this.generation; + const streamId = this.streamId; + this.setState({ status: "exiting" }); + this.closing = (async () => { + try { + const result = await this.call("close", { streamId }); + // Another client/host cleanup may have already removed this generation. + // Dismiss locally without ever closing the replacement generation. + if (!result?.ok && result?.error?.code === "terminal-stale") { + if (generation !== this.generation) return; + this.closeWs(); + this.streamId = null; + this.setState({ status: "closed", error: null }); + return; + } + if (!result?.ok) throw new Error(result?.error?.message || "close failed"); + if (generation !== this.generation) return; + this.closeWs(); + this.streamId = null; + const { transcriptPath } = result.value; + this.setState({ status: dismiss || !transcriptPath ? "closed" : "ended", + tab: "history", preview: null, pendingSelectPath: transcriptPath, error: null }); + } catch (error) { + if (generation === this.generation) this.fail(error); + } finally { this.closing = null; } + })(); + return this.closing; + } + + dismiss() { return this.exit({ dismiss: true }); } + + closeWs() { + const ws = this.ws; + this.ws = null; + if (ws) { + ws.onopen = ws.onmessage = ws.onclose = ws.onerror = null; + try { ws.close(); } catch { /* already closed */ } + } + } + + dispose() { + if (this.disposed) return; + this.disposed = true; + ++this.generation; + ++this.previewRequest; + ++this.historyRequest; + this.closeWs(); + this.outputListeners.clear(); + if (this.streamId && !this.closing) this.call("close", { streamId: this.streamId }).catch(() => {}); + this.streamId = null; + } + + fail(error) { + this.closeWs(); + this.setState({ status: "error", error: error instanceof Error ? error.message : String(error) }); + } + + setState(next) { + if (next.preview === null) ++this.previewRequest; + if (!this.disposed) this.state.set({ ...this.state.getSnapshot(), ...next }); + } + setGeometry(patch) { this.setState(patch); } + + /* ---- history tab ---- */ + setTab(tab) { + // HistoryTab's own mount effect calls loadHistory() when it mounts + // (it unmounts/remounts on every tab switch), so no need to trigger + // a second fetch here. + ++this.previewRequest; + this.setState({ tab, preview: null }); + } + + loadHistory() { + const request = ++this.historyRequest; + this.setState({ history: { ...this.state.getSnapshot().history, loading: true, error: null } }); + this.connection.rpc.call(RPC_CHANNEL, "historyList", { sessionId: this.sessionId }, undefined) + .then((result) => { + if (request !== this.historyRequest) return; + if (result === undefined || !result.ok) { + this.setState({ history: { entries: [], loading: false, error: result && result.error ? result.error.message : "load failed" } }); + return; + } + this.setState({ history: { entries: result.value.entries, loading: false, error: null } }); + }) + .catch((error) => { + if (request === this.historyRequest) this.setState({ history: { entries: [], loading: false, error: error instanceof Error ? error.message : String(error) } }); + }); + } + + togglePreview(path) { + const request = ++this.previewRequest; + const current = this.state.getSnapshot().preview; + if (current !== null && current.path === path) { + this.setState({ preview: null }); + return; + } + this.setState({ preview: { path, transcript: null, loading: true } }); + this.connection.rpc.call(RPC_CHANNEL, "historyRead", { sessionId: this.sessionId, path }, undefined) + .then((result) => { + if (request !== this.previewRequest) return; + if (result === undefined || !result.ok) { + this.setState({ preview: { path, transcript: result && result.error ? result.error.message : "read failed", loading: false } }); + return; + } + this.setState({ preview: { path, transcript: result.value.transcript, loading: false } }); + }) + .catch((error) => { + if (request === this.previewRequest) this.setState({ preview: { path, transcript: error instanceof Error ? error.message : String(error), loading: false } }); + }); + } + + /** Reference-inject the given transcript paths (multi-select) + notes; non-waking. */ + referenceInject(paths, notes) { + return this.connection.rpc.call(RPC_CHANNEL, "historyInject", { sessionId: this.sessionId, paths, notes: notes || "" }, undefined) + .then((result) => { + if (result === undefined || !result.ok) { + throw new Error(result && result.error ? result.error.message : "reference-inject failed"); + } + return result.value; + }); + } +} + +export { TerminalController }; diff --git a/src/terminal-view.js b/src/terminal-view.js new file mode 100644 index 0000000..d95da6d --- /dev/null +++ b/src/terminal-view.js @@ -0,0 +1,82 @@ +import React from "react"; +import { Terminal } from "@xterm/xterm"; +import { FitAddon } from "@xterm/addon-fit"; + +/** A single emulator survives live/history tab switches for the whole PTY epoch. */ +export function TerminalView({ controller, visible, status }) { + const container = React.useRef(null); + const terminal = React.useRef(null); + const fit = React.useRef(null); + + React.useEffect(() => { + const element = container.current; + const term = new Terminal({ + cursorBlink: true, scrollback: 3000, fontSize: 13, + fontFamily: "ui-monospace, SFMono-Regular, Menlo, monospace", + theme: { background: "#141414", foreground: "#e5e5e5" }, + allowProposedApi: false, + }); + const addon = new FitAddon(); + term.loadAddon(addon); + term.open(element); + terminal.current = term; + controller.terminal = term; + fit.current = addon; + const data = term.onData((value) => controller.sendRaw(value)); + const binary = term.onBinary((value) => { + // Legacy mouse reporting may emit non-UTF8 bytes. Send byte values intact. + controller.sendFrame({ type: "binary", data: Array.from(value, (c) => c.charCodeAt(0)) }); + }); + const resize = term.onResize(({ cols, rows }) => controller.resize(cols, rows)); + const unsubscribe = controller.subscribeOutput((value) => term.write(value)); + // Device-status responses also emit onData. Only DOM input gestures set + // hasInput; merely receiving a shell prompt/query leaves an empty session. + const activity = (event) => { + if (event.type === "keydown" && ["Shift", "Control", "Alt", "Meta", "CapsLock"].includes(event.key)) return; + if (["pointerdown", "wheel"].includes(event.type) && term.modes.mouseTrackingMode === "none") return; + controller.markActivity(); + }; + const events = ["keydown", "paste", "beforeinput", "compositionend", "pointerdown", "wheel"]; + for (const name of events) element.addEventListener(name, activity, true); + let frame; + const observer = new ResizeObserver(() => { + cancelAnimationFrame(frame); + frame = requestAnimationFrame(() => { + if (element.clientWidth && element.clientHeight) addon.fit(); + }); + }); + observer.observe(element); + return () => { + observer.disconnect(); + cancelAnimationFrame(frame); + for (const name of events) element.removeEventListener(name, activity, true); + unsubscribe(); data.dispose(); binary.dispose(); resize.dispose(); + terminal.current = null; + if (controller.terminal === term) controller.terminal = null; + fit.current = null; + term.dispose(); + }; + }, [controller]); + + React.useEffect(() => { + const term = terminal.current; + if (!term) return; + term.options.disableStdin = status !== "open"; + if (!visible) return; + const frame = requestAnimationFrame(() => { + if (!container.current?.clientWidth || !container.current?.clientHeight) return; + fit.current?.fit(); + // Opening at an already-fitted size does not emit onResize again. + if (status === "open") { + controller.resize(term.cols, term.rows); + term.focus(); + } + }); + return () => cancelAnimationFrame(frame); + }, [controller, visible, status]); + + return React.createElement("div", { + ref: container, "data-terminal-view": "", + style: { display: visible ? "block" : "none", flex: "1 1 0", minHeight: 0, minWidth: 0, overflow: "hidden" }, + }); +} diff --git a/test/browser-host.js b/test/browser-host.js new file mode 100644 index 0000000..a493de0 --- /dev/null +++ b/test/browser-host.js @@ -0,0 +1,49 @@ +// Small host-service fixture; the production bundle itself is loaded unchanged. +import React from "react"; +import ReactDOM from "react-dom"; +import { createRoot } from "react-dom/client"; + +const cleanups = []; +const root = createRoot(document.getElementById("root")); +const sources = new Map(); +const fixture = window.fixture = { controller: null, sources, root }; +function createSnapshotStore(initial) { + let snapshot = initial; + const listeners = new Set(); + return { getSnapshot: () => snapshot, set(next) { snapshot = next; for (const fn of listeners) fn(); }, + subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn); } }; +} +const effect = (fn) => { const dispose = fn(); if (typeof dispose === "function") cleanups.push(dispose); return dispose; }; +const connection = { rpc: { async call(channel, endpoint, payload) { + return (await fetch("/rpc", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ channel, endpoint, payload }) })).json(); +} } }; +window.__ModuleLoader__ = { load(registration) { + fixture.registration = registration; +} }; +window.mountShell = () => { + const dependencies = { react: React, "react-dom": ReactDOM, + "@deepseek-ai/dsh-client-runtime/client": { createSnapshotStore } }; + // Match DSH's two stages: script evaluation registers, then materialize with host requires. + fixture.plugin = fixture.registration.factory((id) => { + if (!(id in dependencies)) throw new Error(`Unexpected external dependency: ${id}`); + return dependencies[id]; + }); + const slots = { + inject(_name, fn) { effect(fn); }, + register(descriptor, Component) { + const props = descriptor.inject("browser-session"); + fixture.controller = props.controller; + root.render(React.createElement(Component, props)); + return () => root.unmount(); + }, + }; + fixture.plugin.apply({ effect, slots, get(name) { + return { connection, inputTriggers: { registerSource(source) { sources.set(source.name, source); return () => sources.delete(source.name); } }, + sessions: { scope() { return { effect }; } } }[name]; + } }); +}; +fixture.open = async () => { + const result = await sources.get("terminal").matchEnter({ sessionId: "browser-session" }, "/terminal"); + await result.claim.submit(); +}; +fixture.dispose = () => { for (const dispose of cleanups.splice(0).reverse()) dispose(); }; diff --git a/test/browser.mjs b/test/browser.mjs new file mode 100644 index 0000000..e6596c8 --- /dev/null +++ b/test/browser.mjs @@ -0,0 +1,449 @@ +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { readFileSync, writeFileSync, mkdtempSync, rmSync, existsSync } from "node:fs"; +import { join } from "node:path"; +import { tmpdir } from "node:os"; +import { fileURLToPath } from "node:url"; +import { spawnSync } from "node:child_process"; +import { build } from "tsdown"; +import { chromium } from "playwright"; +import * as nativePty from "node-pty"; +import { WebSocketServer, WebSocket } from "ws"; +import { createTerminalManager } from "../lib/terminal.js"; +import { registerTerminalRpc, registerTerminalWs } from "../lib/rpc.js"; +import { apply as applyShell } from "../lib/index.js"; +import { stripAnsi } from "../lib/inject.js"; + +const root = fileURLToPath(new URL("../", import.meta.url)); +const cwd = mkdtempSync(join(tmpdir(), "dsh-xterm-browser-")); +const input = []; +const followups = [], injections = []; +let requestActive = true; +const audit = []; +const agent = { id: "browser-session", session: { header: { cwd }, requestHeader: () => requestActive ? { cwd } : undefined, + append(type, data) { audit.push({ type, data }); } }, + inject(message) { injections.push(message); }, followup(message) { followups.push(message); } }; +const manager = createTerminalManager({ + shell: "/bin/bash", transcriptKeep: 20, + pty: { spawn(shell, _args, options) { + const term = nativePty.spawn(shell, ["--noprofile", "--norc", "-i"], { + ...options, env: { ...options.env, PS1: "DSH_TEST> ", PROMPT_COMMAND: "", HISTFILE: "/dev/null", INPUTRC: "/dev/null" }, + }); + const write = term.write.bind(term); + term.write = (data) => { input.push(data); write(data); }; + return term; + } }, +}); +let rpc, bangRpc, browser, server, page, disposeWs; +const effects = []; +const ctx = { effect(fn) { const dispose = fn(); effects.push(dispose); return dispose; } }; +const capturePath = process.env.DSH_BROWSER_SCREENSHOT; +const errors = []; +const waitFor = async (predicate, label, timeout = 8000) => { + const end = Date.now() + timeout; + while (Date.now() < end) { + if (await predicate()) return; + await new Promise((resolve) => setTimeout(resolve, 30)); + } + throw new Error(`Timed out: ${label}`); +}; + +try { + writeFileSync(join(cwd, "completion-target.txt"), "COMPLETION_RESULT_5931\n"); + await build({ cwd: root, entry: { host: "test/browser-host.js" }, outDir: cwd, clean: false, + format: "iife", platform: "browser", target: "es2022", dts: false, + deps: { onlyBundle: [/^react(?:-dom)?(?:\/|$)/, "scheduler"], alwaysBundle: [/^react(?:-dom)?(?:\/|$)/] }, define: { "process.env.NODE_ENV": '"production"' } }); + registerTerminalRpc({ manager, agents: { get: (id) => id === agent.id ? agent : undefined }, + connection: { rpc: { handle(_channel, handler) { rpc = handler; return () => {}; } } } }); + applyShell({ effect: ctx.effect, get(name) { + return { agents: { get: id => id === agent.id ? agent : undefined }, + connection: { rpc: { handle(_channel, handler) { bangRpc = handler; return () => {}; } } } }[name]; + } }, { terminalEnabled: false }); + server = createServer(async (req, res) => { + try { + if (req.url === "/rpc") { + let body = ""; + for await (const chunk of req) body += chunk; + const { channel, endpoint, payload } = JSON.parse(body); + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify(await (channel === "/shell-bang-rpc" ? bangRpc : rpc)(endpoint, payload, new AbortController().signal))); + } else if (req.url === "/host.js" || req.url === "/client.js") { + res.setHeader("content-type", "text/javascript"); + res.end(readFileSync(req.url === "/host.js" ? join(cwd, "host.iife.js") : join(root, "lib/client.js"))); + } else { + res.setHeader("content-type", "text/html"); + res.end('
'); + } + } catch (error) { errors.push(error.message); res.statusCode = 500; res.end(String(error)); } + }); + disposeWs = registerTerminalWs({ manager, WebSocketServer, ctx, webServer: { + registerUpgrade({ handler }) { server.on("upgrade", handler); return () => server.off("upgrade", handler); }, + } }); + await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", resolve); }); + browser = await chromium.launch({ headless: true, + ...(process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH ? { executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH } : {}), + }); + console.log(`BROWSER: Chromium ${browser.version()}, Node ${process.version}`); + page = await browser.newPage({ viewport: { width: 1200, height: 850 } }); + page.on("pageerror", (error) => errors.push(error.message)); + await page.goto(`http://127.0.0.1:${server.address().port}`); + await page.waitForFunction(() => window.fixture?.controller); + assert.equal(await page.locator("style[data-dsh-shell-xterm]").count(), 1, "CSS ships inside the bundle"); + const open = async () => { + await page.evaluate(() => fixture.open()); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "open" && fixture.controller.terminal); + await waitFor(() => manager.get(agent.id)?.transcript.includes("DSH_TEST>"), "shell prompt"); + }; + const screen = () => page.evaluate(() => { + const buffer = fixture.controller.terminal.buffer.active; + return Array.from({ length: buffer.length }, (_, i) => { + const line = buffer.getLine(i); + return (line?.isWrapped ? "" : "\n") + (line?.translateToString(true) || ""); + }).join(""); + }); + const command = async (line, expected, waitPrompt = true) => { + const start = manager.get(agent.id).transcript.length; + await page.locator(".xterm-helper-textarea").focus(); + await page.keyboard.type(line); + await page.keyboard.press("Enter"); + if (waitPrompt) await waitFor(() => { + // Bash 5 (Linux) places bracketed-paste mode controls and an extra CR + // between the echoed newline and the prompt, unlike macOS Bash 3. + const tail = manager.get(agent.id)?.transcript.slice(start) ?? ""; + return stripAnsi(tail).replace(/\r/g, "").includes("\nDSH_TEST> "); + }, `prompt after ${line}`); + if (expected) await waitFor(async () => (await screen()).split("\n").includes(expected), `output line ${expected}`); + }; + const checkChromeContrast = async () => { + const values = await page.getByRole("dialog", { name: "shell terminal" }).evaluate((panel) => ({ + background: getComputedStyle(panel).backgroundColor, + labels: Array.from(panel.querySelectorAll("button")).filter(button => ["会话", "历史", "退出", "关闭面板", "^C", "^D", "^Z", "引用并分析", "直接退出,本次不分析"].includes(button.textContent)) + .map(button => ({ name: button.textContent, color: getComputedStyle(button).color })), + })); + const luminance = (color) => { + const [r, g, b] = color.match(/[\d.]+/g).slice(0, 3).map(Number).map(value => { + const channel = value / 255; + return channel <= 0.04045 ? channel / 12.92 : ((channel + 0.055) / 1.055) ** 2.4; + }); + return 0.2126 * r + 0.7152 * g + 0.0722 * b; + }; + const bg = luminance(values.background); + for (const label of values.labels) { + const fg = luminance(label.color); + assert.ok((Math.max(fg, bg) + 0.05) / (Math.min(fg, bg) + 0.05) >= 4.5, `${label.name} readable against ${values.background}`); + } + }; + + await open(); + await checkChromeContrast(); + await page.evaluate(() => { + document.body.style.setProperty("--dsw-alias-bg-layer-1", "#141414"); + document.body.style.setProperty("--dsw-alias-label-primary", "#eeeeee"); + document.body.style.setProperty("--dsw-alias-label-secondary", "#aaaaaa"); + }); + await checkChromeContrast(); + await page.evaluate(() => { + for (const key of ["--dsw-alias-bg-layer-1", "--dsw-alias-label-primary", "--dsw-alias-label-secondary"]) document.body.style.removeProperty(key); + }); + await checkChromeContrast(); + await page.evaluate(() => { + document.body.style.setProperty("--dsw-alias-bg-layer-1", "#ffffff"); + document.body.style.setProperty("--dsw-alias-label-primary", "#0f1115"); + document.body.style.setProperty("--dsw-alias-label-secondary", "#61666b"); + }); + console.log("BROWSER: light, dark and fallback panel labels have readable contrast"); + const emptyHandle = manager.get(agent.id); + emptyHandle.appendTranscript("\x1b[6n"); + await waitFor(() => input.some((data) => /\x1b\[\d+;\d+R/.test(data)), "xterm device-status response"); + assert.equal(emptyHandle.hasInput, false); + await page.getByRole("button", { name: "退出", exact: true }).click(); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "closed"); + assert.equal(manager.list(cwd, agent.id).length, 0); + console.log("BROWSER: empty close and automatic replies passed"); + + // Previous releases wrote raw .log files without a metadata sidecar. + const oldLog = manager.persist(cwd, agent.id, "\x1b]0;before\x1b\\PREVIOUS_VERSION_HISTORY\x1b]0;after\x1b\\\n"); + rmSync(oldLog.replace(/\.log$/, ".meta.json")); + const otherLog = manager.persist(cwd, agent.id, "SECOND_HISTORY_RECORD\n", { exitCode: 3 }); + await open(); + await page.getByRole("button", { name: "历史", exact: true }).click(); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().history.entries.length === 2); + const oldIndex = await page.evaluate((path) => fixture.controller.state.getSnapshot().history.entries.findIndex(entry => entry.path === path), oldLog); + await page.getByRole("button", { name: "查看", exact: true }).nth(oldIndex).click(); + await page.getByText("PREVIOUS_VERSION_HISTORY", { exact: true }).waitFor(); + await page.getByRole("button", { name: "收起", exact: true }).click(); + await page.getByRole("checkbox").nth(0).check(); + await page.getByRole("checkbox").nth(1).check(); + const notes = "请分析这两段旧终端记录"; + await page.getByPlaceholder("(可选)已选中多段记录时,可在此补充自然语言说明…").fill(notes); + await page.getByRole("button", { name: "引用并分析 (2 段)", exact: true }).click(); + await waitFor(() => followups.length === 1 && injections.length === 1, "previous history multi-reference"); + assert.equal(injections[0].content[0].text, notes); + assert.ok(followups[0].content[0].text.includes(oldLog) && followups[0].content[0].text.includes(otherLog)); + assert.equal(await page.getByRole("button", { name: "直接退出,本次不分析", exact: true }).count(), 0, "live PTY cannot be silently dismissed"); + await page.getByRole("button", { name: "会话", exact: true }).click(); + await page.getByRole("button", { name: "退出", exact: true }).click(); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "closed"); + console.log("BROWSER: legacy logs, expand/collapse preview, multi-select and notes preserved"); + + await open(); + const firstStream = manager.get(agent.id).streamId; + await page.keyboard.type("printf"); + await waitFor(() => input.includes("p"), "per-keystroke PTY input"); + await page.keyboard.type(" 'KEY_READY\\n'"); + await page.keyboard.press("Enter"); + await waitFor(async () => (await screen()).split("\n").includes("KEY_READY"), "key output"); + await command("mkdir child; cd child; export DSH_XTERM_TEST=retained"); + await command("printf '%s|%s\\n' \"$PWD\" \"$DSH_XTERM_TEST\"", `${cwd}/child|retained`); + await page.keyboard.type("cat ../completion-t"); + await page.keyboard.press("Tab"); + await page.keyboard.press("Enter"); + await waitFor(async () => (await screen()).includes("COMPLETION_RESULT_5931"), "shell tab completion"); + await page.keyboard.press("ArrowUp"); + await page.keyboard.press("Enter"); + await waitFor(async () => (await screen()).split("COMPLETION_RESULT_5931").length >= 3, "shell history recall"); + + await page.evaluate(() => { + const transfer = new DataTransfer(); + transfer.setData("text/plain", "printf '%s\\n' '你好🦊'"); + document.querySelector(".xterm-helper-textarea").dispatchEvent(new ClipboardEvent("paste", { clipboardData: transfer, bubbles: true, cancelable: true })); + }); + await page.keyboard.press("Enter"); + await waitFor(async () => (await screen()).includes("你好🦊"), "Unicode paste"); + await page.keyboard.type("printf '%s\\n' '"); + await page.evaluate(() => { + const textarea = document.querySelector(".xterm-helper-textarea"); + const base = textarea.value; + textarea.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true, data: "" })); + textarea.value = base + "中文输入"; + textarea.setSelectionRange(textarea.value.length, textarea.value.length); + textarea.dispatchEvent(new CompositionEvent("compositionupdate", { bubbles: true, data: "中文输入" })); + textarea.dispatchEvent(new InputEvent("input", { bubbles: true, data: "中文输入", inputType: "insertCompositionText", isComposing: true })); + textarea.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true, data: "中文输入" })); + }); + await waitFor(() => input.some((data) => String(data).includes("中文输入")), "IME composition forwarding"); + await page.keyboard.type("'"); + await page.keyboard.press("Enter"); + await waitFor(async () => (await screen()).includes("中文输入"), "IME output"); + console.log("BROWSER: keystrokes, persistent shell, completion, history, CJK paste/composition passed"); + + await command("sleep 30", undefined, false); + await waitFor(() => spawnSync("pgrep", ["-P", String(manager.get(agent.id).pty.pid), "-x", "sleep"]).status === 0, "sleep child running before Ctrl+C"); + let signalStart = manager.get(agent.id).transcript.length; + await page.keyboard.press("Control+c"); + await waitFor(() => manager.get(agent.id).transcript.slice(signalStart).includes("DSH_TEST> "), "prompt after Ctrl+C"); + await command("printf 'INTERRUPT_OK\\n'", "INTERRUPT_OK"); + await command("sleep 30", undefined, false); + await waitFor(() => spawnSync("pgrep", ["-P", String(manager.get(agent.id).pty.pid), "-x", "sleep"]).status === 0, "sleep child running before Ctrl+Z"); + signalStart = manager.get(agent.id).transcript.length; + await page.getByRole("button", { name: "Ctrl+Z(挂起)", exact: true }).click(); + await waitFor(() => manager.get(agent.id).transcript.slice(signalStart).includes("DSH_TEST> "), "prompt after Ctrl+Z"); + await command("kill %1; wait %1 2>/dev/null; printf 'JOB_STOP_OK\\n'", "JOB_STOP_OK"); + assert.ok(input.includes("\x03") && input.includes("\x1a")); + await command("printf '\\rOLD_FRAME\\rNEW_FRAME\\033[K\\n'", "NEW_FRAME"); + const progress = await screen(); + assert.match(progress, /\nNEW_FRAME\n/, "CR overwrites the displayed line"); + await command("printf '\\033[?1049hALT_SCREEN\\n'"); + await page.waitForFunction(() => fixture.controller.terminal.buffer.active.type === "alternate"); + await page.evaluate(() => { fixture.originalTerminal = fixture.controller.terminal; }); + await page.getByRole("button", { name: "历史", exact: true }).click(); + await page.getByRole("button", { name: "会话", exact: true }).click(); + assert.equal(await page.evaluate(() => fixture.originalTerminal === fixture.controller.terminal), true); + assert.equal((await screen()).split("ALT_SCREEN").length, 2, "tab switch never replays output"); + await command("printf '\\033[?1049l\\n'"); + await page.waitForFunction(() => fixture.controller.terminal.buffer.active.type === "normal"); + + await page.evaluate(() => fixture.controller.setGeometry({ width: 850, height: 560 })); + await waitFor(async () => { + const size = await page.evaluate(() => ({ cols: fixture.controller.terminal.cols, rows: fixture.controller.terminal.rows })); + return size.cols > 80 && size.rows > 20; + }, "container refit"); + const size = await page.evaluate(() => ({ cols: fixture.controller.terminal.cols, rows: fixture.controller.terminal.rows })); + await command("stty size"); + await waitFor(() => manager.get(agent.id).transcript.includes(`${size.rows} ${size.cols}`), "real PTY dimensions"); + console.log("BROWSER: Ctrl+C/Z, progress overwrite, alternate screen, tab preservation and resize passed"); + + if (spawnSync("vim", ["--version"], { encoding: "utf8" }).status === 0) { + await command("vim -Nu NONE -n fixture.txt", undefined, false); + await page.waitForFunction(() => fixture.controller.terminal.buffer.active.type === "alternate"); + await page.keyboard.type("iVIM_EDIT_CONFIRMED"); + await page.keyboard.press("Escape"); + await page.keyboard.type(":wq"); + await page.keyboard.press("Enter"); + await waitFor(() => existsSync(join(cwd, "child/fixture.txt")) && readFileSync(join(cwd, "child/fixture.txt"), "utf8").includes("VIM_EDIT_CONFIRMED"), "vim saved edit"); + await page.waitForFunction(() => fixture.controller.terminal.buffer.active.type === "normal"); + console.log("BROWSER: real vim edit/save/exit passed"); + } else console.log("BROWSER: vim unavailable; alternate screen verified independently"); + if (spawnSync("htop", ["--version"], { encoding: "utf8" }).status === 0) { + await command("htop", undefined, false); + await page.waitForFunction(() => fixture.controller.terminal.buffer.active.type === "alternate"); + await page.keyboard.press("q"); + await page.waitForFunction(() => fixture.controller.terminal.buffer.active.type === "normal"); + console.log("BROWSER: htop passed"); + } else console.log("BROWSER: htop unavailable (optional)"); + + if (capturePath) await page.screenshot({ path: capturePath }); + await page.keyboard.press("Control+d"); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "ended"); + assert.ok(input.includes("\x04")); + assert.equal(manager.get(agent.id), undefined, "natural exit releases the PTY registry"); + assert.equal(manager.list(cwd, agent.id).length, 3); + assert.equal(followups.length, 1, "close itself never wakes the model"); + assert.equal(injections.length, 1); + assert.equal(await page.getByRole("checkbox").first().isChecked(), true); + await page.getByRole("button", { name: "收起", exact: true }).waitFor(); + await checkChromeContrast(); + if (capturePath) await page.screenshot({ path: capturePath.replace(/\.png$/, "-history.png") }); + await page.getByRole("button", { name: "引用并分析", exact: true }).click(); + await waitFor(() => followups.length === 2 && injections.length === 2, "history reference"); + await page.getByRole("button", { name: "直接退出,本次不分析", exact: true }).click(); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "closed"); + assert.equal(followups.length, 2, "dismiss never wakes the model"); + + await open(); + assert.notEqual(manager.get(agent.id).streamId, firstStream); + assert.doesNotMatch(await screen(), /VIM_EDIT_CONFIRMED|COMPLETION_RESULT_5931/, "reopen has clean buffers"); + await command("printf 'DISCONNECT_TEST\\n'", "DISCONNECT_TEST"); + for (const ws of manager.get(agent.id).watchers) ws.terminate(); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "error"); + const writesBefore = input.length; + await page.evaluate(() => fixture.controller.sendRaw("must-not-arrive")); + assert.equal(input.length, writesBefore, "disconnect disables input"); + await page.getByRole("button", { name: "关闭", exact: true }).click(); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "closed"); + assert.equal(manager.get(agent.id), undefined, "closing a disconnected panel cleans the PTY"); + + await open(); + await command("printf 'OFFLINE_EXIT_RECORD\\n'", "OFFLINE_EXIT_RECORD"); + const offline = manager.get(agent.id); + const historyBeforeOfflineExit = manager.list(cwd, agent.id).length; + for (const ws of offline.watchers) ws.terminate(); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "error"); + offline.pty.write("exit 9\r"); + await waitFor(() => offline.exited && manager.list(cwd, agent.id).length === historyBeforeOfflineExit + 1, "offline natural exit persists on host"); + const offlinePath = manager.list(cwd, agent.id)[0].path; + assert.match(manager.readTranscript(offlinePath), /OFFLINE_EXIT_RECORD/); + await page.getByRole("button", { name: "关闭", exact: true }).click(); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "closed"); + assert.equal(manager.list(cwd, agent.id).length, historyBeforeOfflineExit + 1, "late close never duplicates the offline record"); + assert.equal(manager.list(cwd, agent.id)[0].exitCode, 9); + console.log("BROWSER: disconnected natural exit persists exactly once with the final exit code"); + await open(); + await rpc("close", { sessionId: agent.id, streamId: manager.get(agent.id).streamId }); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "error"); + await page.getByRole("button", { name: "关闭", exact: true }).click(); + await page.waitForFunction(() => fixture.controller.state.getSnapshot().status === "closed"); + await open(); + await page.evaluate(() => fixture.dispose()); + await waitFor(() => manager.get(agent.id) === undefined, "scope disposal closes server PTY"); + assert.equal(await page.locator("style[data-dsh-shell-xterm]").count(), 0); + assert.equal(await page.locator(".xterm").count(), 0); + assert.equal(await page.evaluate(() => fixture.controller.outputListeners.size), 0); + // A session scope can disappear while the open RPC is still in flight. + await page.reload(); + await page.waitForFunction(() => window.fixture?.controller); + let releaseOpen; + const gate = new Promise((resolve) => { releaseOpen = resolve; }); + let heldOpen = false; + await page.route("**/rpc", async (route) => { + if (route.request().postDataJSON().endpoint !== "open") return route.continue(); + const response = await route.fetch(); + heldOpen = true; + await gate; + await route.fulfill({ response }); + }); + await page.evaluate(() => { fixture.open(); fixture.open(); }); + await waitFor(() => heldOpen && manager.get(agent.id), "pending open created PTY"); + await page.evaluate(() => fixture.dispose()); + releaseOpen(); + await waitFor(() => manager.get(agent.id) === undefined, "disposed pending open cleans its late result"); + await page.unroute("**/rpc"); + + // Use the actual shipped controller with explicitly reordered transport replies. + await page.reload(); + await page.waitForFunction(() => window.fixture?.controller); + const races = await page.evaluate(async () => { + const controller = fixture.controller; + const original = controller.connection; + const pending = []; + controller.connection = { rpc: { call(_channel, endpoint, payload) { + return new Promise((resolve, reject) => pending.push({ endpoint, payload, resolve, reject })); + } } }; + const success = transcript => ({ ok: true, value: { transcript } }); + const flush = async () => { await Promise.resolve(); await Promise.resolve(); }; + try { + controller.togglePreview("A"); controller.togglePreview("B"); + pending[1].resolve(success("B content")); await flush(); + pending[0].resolve(success("A content")); await flush(); + const newest = controller.state.getSnapshot().preview.path; + controller.togglePreview("collapse"); controller.togglePreview("collapse"); + pending[2].resolve(success("must remain hidden")); await flush(); + const collapsed = controller.state.getSnapshot().preview; + controller.togglePreview("old-error"); controller.togglePreview("latest"); + pending[4].resolve(success("latest")); pending[3].reject(new Error("old failure")); await flush(); + const lateError = controller.state.getSnapshot().preview.path; + controller.togglePreview("before-tab-switch"); controller.setTab("live"); + pending[5].resolve(success("must not reopen preview")); await flush(); + const switched = controller.state.getSnapshot().preview; + controller.loadHistory(); controller.loadHistory(); + pending[7].resolve({ ok: true, value: { entries: [{ path: "new" }] } }); await flush(); + pending[6].resolve({ ok: true, value: { entries: [{ path: "old" }] } }); await flush(); + const history = controller.state.getSnapshot().history.entries[0].path; + return { newest, collapsed, lateError, switched, history }; + } finally { controller.connection = original; } + }); + assert.deepEqual(races, { newest: "B", collapsed: null, lateError: "latest", switched: null, history: "new" }); + console.log("BROWSER: out-of-order preview/history replies, collapse, tab switch and stale errors passed"); + + await open(); + const live = manager.get(agent.id); + const malformed = new WebSocket(`ws://127.0.0.1:${server.address().port}/shell-term/ws?sessionId=${agent.id}&streamId=${live.streamId}&protocol=2`); + malformed.on("error", () => {}); + await new Promise((resolve, reject) => { malformed.once("open", resolve); malformed.once("error", reject); }); + const malformedClosed = new Promise(resolve => malformed.once("close", resolve)); + // Unmasked client text frame: valid HTTP upgrade, invalid RFC 6455 framing. + malformed._socket.write(Buffer.from([0x81, 0x01, 0x61])); + await malformedClosed; + assert.equal(manager.get(agent.id), live, "one malformed socket cannot take down the host or the PTY"); + assert.equal(live.hasInput, false); + await page.evaluate(() => fixture.controller.dismiss()); + assert.equal(manager.get(agent.id), undefined); + console.log("BROWSER: malformed WebSocket wire frame is isolated without a host crash"); + + const bang = await page.evaluate(async () => { + const source = fixture.sources.get("shell-bang"); + const session = { sessionId: "browser-session" }; + const claim = await source.matchEnter(session, "/! printf 'BANG_BROWSER_OK'"); + return claim.claim.submit(); + }); + assert.equal(bang.kind, "success"); + assert.match(followups.at(-1).content[0].text, /BANG_BROWSER_OK/); + assert.deepEqual(audit.slice(-2).map(event => event.type), ["command/run", "command/done"]); + const auditCount = audit.length; + const followupCount = followups.length; + requestActive = false; + const beforeFirstRequest = await page.evaluate(async () => { + const claim = await fixture.sources.get("shell-bang").matchEnter({ sessionId: "browser-session" }, "/! printf never-execute"); + return claim.claim.submit(); + }); + assert.equal(beforeFirstRequest.kind, "error"); + assert.match(beforeFirstRequest.text, /No model request exists yet/); + assert.equal(audit.length, auditCount); + assert.equal(followups.length, followupCount); + console.log("BROWSER: /! trigger executes, audits, analyzes and rejects a conversation without a model request"); + assert.deepEqual(errors, []); + console.log("BROWSER TESTS PASSED: natural Ctrl+D exit, history reference, clean reopen, disconnect, disposal and pending-open race"); +} catch (error) { + console.error("Browser errors:", errors); + console.error("PTY tail:", manager.get(agent.id)?.transcript.slice(-4000)); + if (page) console.error("Browser state:", await page.evaluate(() => fixture.controller.state.getSnapshot()).catch(() => null)); + throw error; +} finally { + await browser?.close(); + manager.disposeAll(); + disposeWs?.(); + for (const dispose of effects.reverse()) dispose?.(); + server?.closeAllConnections(); + if (server?.listening) await new Promise((resolve) => server.close(resolve)); + rmSync(cwd, { recursive: true, force: true }); +} diff --git a/test/regressions.mjs b/test/regressions.mjs new file mode 100644 index 0000000..3ec16ac --- /dev/null +++ b/test/regressions.mjs @@ -0,0 +1,202 @@ +// Requirements-driven regressions: real OS commands, Cordis dependency gating, +// UTF-8 retention, and persistence without a connected browser. +import assert from "node:assert/strict"; +import { mkdtempSync, rmSync, writeFileSync, existsSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Context } from "@deepseek-ai/cordis"; +import * as plugin from "../lib/index.js"; +import { runCommand } from "../lib/exec.js"; +import { tailTranscript } from "../lib/inject.js"; +import { createAnalysisMessage } from "../lib/message.js"; +import { createTerminalManager } from "../lib/terminal.js"; +import { registerTerminalRpc } from "../lib/rpc.js"; + +const cwd = mkdtempSync(join(tmpdir(), "dsh-review-regressions-")); +const quote = value => "'" + value.replaceAll("'", "'\\''") + "'"; +const delay = ms => new Promise(resolve => setTimeout(resolve, ms)); +try { + // Compare retained text with an independent code-point suffix oracle. + for (const text of ["123456789", "aaaa😀xxxx", "中", "你😀好é\r\n尾巴", "😀".repeat(20)]) { + for (let cap = 1; cap <= Buffer.byteLength(text) + 1; cap++) { + let expected = ""; + for (const character of Array.from(text).reverse()) { + if (Buffer.byteLength(character + expected) > cap) break; + expected = character + expected; + } + const actual = tailTranscript(text, cap); + assert.equal(actual.text, expected); + assert.ok(actual.text.isWellFormed()); + assert.ok(Buffer.byteLength(actual.text) <= cap); + } + } + const literal = createAnalysisMessage({ command: "echo '$& {output}'", cwd: "/tmp/{command}", + outputText: "$` $' {cwd}", template: "{command}|{cwd}|{output}", summary: "test" }); + assert.equal(literal.content[0].text, "echo '$& {output}'|/tmp/{command}|$` $' {cwd}"); + + // Real Cordis must load /! without the optional web service. + const ctx = new Context(); + const handlers = new Map(); + ctx.provide("connection", { rpc: { handle(channel, handler) { handlers.set(channel, handler); return () => handlers.delete(channel); } } }); + ctx.provide("agents", { get() {} }); + const fiber = ctx.plugin(plugin, { terminalEnabled: false }); + await fiber; + assert.equal(typeof handlers.get("/shell-bang-rpc"), "function"); + await fiber.dispose(); + assert.equal(handlers.size, 0); + const optional = ctx.plugin(plugin, { terminalEnabled: true }); + await optional; + assert.equal(typeof handlers.get("/shell-bang-rpc"), "function"); + assert.equal(handlers.has("/shell-term-rpc"), false); + ctx.provide("webServer", { registerUpgrade() { return () => {}; } }); + for (let attempt = 0; attempt < 100 && !handlers.has("/shell-term-rpc"); attempt++) await delay(10); + assert.equal(typeof handlers.get("/shell-term-rpc"), "function", "late optional service enables terminal mode"); + await optional.dispose(); + assert.equal(handlers.size, 0); + + // Verify the preferred subprocess seam's real contract, including failure. + let spawnSpec; + const subprocess = { spawn(spec) { + spawnSpec = spec; + return { done: Promise.resolve({ exitCode: 2, signal: null }), collected: { + stdout: { readFrom(offset) { assert.equal(offset, 0); return { text: "retained tail", lossy: true }; } }, + stderr: { readFrom() { return { text: "diagnostic", lossy: false }; } }, + } }; + } }; + const managedInput = { command: "test command", shell: "/configured/shell", shellArgs: ["-c"], + cwd, timeoutMs: 5000, graceMs: 100, maxOutputBytes: 16, subprocess }; + const managed = await runCommand(managedInput); + assert.deepEqual(spawnSpec.argv, ["/configured/shell", "-c", "test command"]); + assert.equal(spawnSpec.cwd, cwd); + assert.equal(spawnSpec.stdio.stdout.maxBytes, 16); + assert.equal(spawnSpec.graceMs, 100); + assert.equal(managed.exitCode, 2); + assert.deepEqual(managed.stdout, { text: "retained tail", truncated: true }); + assert.deepEqual(managed.stderr, { text: "diagnostic", truncated: false }); + const failedManaged = await runCommand({ ...managedInput, subprocess: { + spawn() { return { done: Promise.reject(new Error("spawn rejected")) }; }, + } }); + assert.equal(failedManaged.ok, false); + assert.match(failedManaged.error.message, /spawn rejected/); + + if (process.platform !== "win32") { + const base = { shell: "/bin/bash", shellArgs: ["-c"], cwd, timeoutMs: 150, + graceMs: 80, maxOutputBytes: 1024 }; + const started = Date.now(); + const timeout = await runCommand({ ...base, command: "trap '' TERM; sleep 2; printf should-not-run" }); + assert.equal(timeout.timedOut, true); + assert.ok(Date.now() - started < 1500, "ignoring TERM cannot bypass the deadline"); + assert.doesNotMatch(timeout.stdout.text, /should-not-run/); + + const cancelled = new AbortController(); + cancelled.abort(); + const marker = join(cwd, "pre-cancelled"); + const result = await runCommand({ ...base, command: `printf bad > ${quote(marker)}`, signal: cancelled.signal }); + assert.equal(result.cancelled, true); + assert.equal(existsSync(marker), false, "pre-cancelled requests must never spawn"); + + const descendantMarker = join(cwd, "surviving-descendant"); + await runCommand({ ...base, + command: `trap 'exit 0' TERM; (trap '' TERM; sleep 1; printf bad > ${quote(descendantMarker)}) /dev/null 2>&1 & wait` }); + await delay(1100); + assert.equal(existsSync(descendantMarker), false, "escalation must survive root exit and closed pipes"); + + const text = await runCommand({ ...base, command: "printf 'aaaa😀xxxx'", timeoutMs: 1000, maxOutputBytes: 7 }); + assert.equal(text.stdout.text, "xxxx", "bounded command output cannot start in the middle of UTF-8"); + const missing = await runCommand({ ...base, command: "echo never", shell: join(cwd, "missing-shell") }); + assert.equal(missing.ok, false); + const runningCancel = new AbortController(); + const pending = runCommand({ ...base, command: "trap '' TERM; sleep 2", timeoutMs: 5000, signal: runningCancel.signal }); + setTimeout(() => runningCancel.abort(), 100); + const stopped = await pending; + assert.equal(stopped.cancelled, true); + assert.equal(stopped.timedOut, false); + const prior = process.env.DSH_REVIEW_HIDDEN; + process.env.DSH_REVIEW_HIDDEN = "private-test-value"; + try { + const env = await runCommand({ ...base, command: 'printf "%s" "${DSH_REVIEW_HIDDEN-unset}"', timeoutMs: 1000 }); + assert.equal(env.stdout.text, "unset", "DSH environment facts must not leak to the command"); + } finally { + if (prior === undefined) delete process.env.DSH_REVIEW_HIDDEN; + else process.env.DSH_REVIEW_HIDDEN = prior; + } + } + + const pty = { spawn() { return { + onData(cb) { this.output = cb; }, onExit(cb) { this.end = cb; }, write() {}, resize() {}, + kill(signal) { this.kills = (this.kills ?? 0) + 1; this.output("final shutdown output\n"); this.end({ exitCode: signal === "SIGKILL" ? 137 : 0 }); }, + }; } }; + const manager = createTerminalManager({ pty, graceMs: 20 }); + try { + let rpc; + const agent = { id: "owner", session: { header: { cwd } }, + inject() { throw new Error("closing must not inject"); }, followup() { throw new Error("closing must not wake"); } }; + registerTerminalRpc({ manager, agents: { get: id => id === agent.id ? agent : undefined }, + connection: { rpc: { handle(_channel, handler) { rpc = handler; return () => {}; } } } }); + const call = (endpoint, extra = {}) => rpc(endpoint, { sessionId: agent.id, ...extra }); + await call("open"); + const offline = manager.get(agent.id); + manager.write(agent.id, "echo results\r"); + offline.pty.output("important offline results\n"); + offline.pty.end({ exitCode: 7 }); + assert.equal(manager.list(cwd, agent.id).length, 1, "natural exit persists without any socket"); + const oldPath = manager.list(cwd, agent.id)[0].path; + const close = await call("close", { streamId: offline.streamId }); + assert.equal(close.value.transcriptPath, oldPath, "close reuses the already-persisted file"); + assert.equal(manager.list(cwd, agent.id).length, 1, "natural exit and close never duplicate history"); + assert.equal(close.value.exitCode, 7); + await call("open"); + assert.equal(manager.list(cwd, agent.id).length, 1); + assert.equal(manager.get(agent.id).transcript, ""); + await call("close"); + + const empty = manager.open("empty", { cwd }); + empty.pty.output("prompt"); empty.pty.end({ exitCode: 0 }); + assert.equal(manager.list(cwd, "empty").length, 0); + await manager.finish("empty"); + + // Late PTY output and the final exit status must be captured on close. + const draining = manager.open("drain", { cwd }); + manager.write("drain", "input"); + draining.pty.kill = function () { setTimeout(() => { this.output("late final output"); this.end({ exitCode: 3 }); }, 5); }; + const drained = await manager.finish("drain"); + assert.equal(drained.exitCode, 3); + assert.match(manager.readTranscript(drained.transcriptPath), /late final output/); + + const stubborn = manager.open("stubborn", { cwd }); + stubborn.pty.kill = function(signal) { if (signal === "SIGKILL") this.end({ exitCode: 137 }); }; + assert.equal((await manager.finish("stubborn")).exitCode, 137); + + // Failed persistence is an error, with the transcript still available for retry. + const retryCwd = join(cwd, "retry"); mkdirSync(retryCwd); + const blocker = join(retryCwd, ".dsh-shell-transcripts"); writeFileSync(blocker, "blocked"); + manager.open("retry", { cwd: retryCwd }); manager.write("retry", "input"); + await assert.rejects(manager.finish("retry")); + assert.ok(manager.get("retry")); + rmSync(blocker); + const retried = await manager.finish("retry"); + assert.ok(existsSync(retried.transcriptPath)); + assert.equal(manager.get("retry"), undefined); + + // Prefix-related owner ids must neither read nor prune one another's files. + const owned = manager.persist(cwd, "prefix-other", "private record"); + assert.equal(manager.list(cwd, "prefix").length, 0); + const RealDate = Date; + globalThis.Date = class extends RealDate { + constructor(...args) { super(...(args.length ? args : ["2026-10-19T01:02:03.004Z"])); } + }; + try { for (let i = 0; i < 12; i++) manager.persist(cwd, "prefix", `own ${i}`); } + finally { globalThis.Date = RealDate; } + assert.ok(existsSync(owned)); + assert.equal(manager.list(cwd, "prefix").length, 10); + assert.deepEqual(manager.list(cwd, "prefix").map(entry => manager.readTranscript(entry.path)), + Array.from({ length: 10 }, (_, index) => `own ${11 - index}`), "same-millisecond collisions keep the newest records in order"); + assert.equal(manager.list(cwd, "prefix-other").length, 1); + const legacyPath = manager.persist(cwd, "legacy", "legacy record"); + const { renameSync } = await import("node:fs"); + const legacyName = legacyPath.replace(/-\d+\.log$/, ".log"); + renameSync(legacyPath, legacyName); + assert.equal(manager.list(cwd, "legacy")[0].path, legacyName, "legacy filenames without counters still work"); + } finally { manager.disposeAll(); } + console.log("REQUIREMENTS REGRESSIONS PASSED"); +} finally { rmSync(cwd, { recursive: true, force: true }); } diff --git a/test/setup-local.mjs b/test/setup-local.mjs new file mode 100644 index 0000000..0fdebec --- /dev/null +++ b/test/setup-local.mjs @@ -0,0 +1,50 @@ +import assert from 'node:assert/strict'; +import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { spawnSync } from 'node:child_process'; + +const fixture = mkdtempSync(join(tmpdir(), 'dsh-local-setup-')); +const put = (path, text) => { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, text); }; +try { + const root = join(fixture, 'checkout'); + const home = join(fixture, 'home'); + const peer = join(home, 'profiles/node_modules/host-peer'); + mkdirSync(join(root, 'scripts'), { recursive: true }); + copyFileSync(new URL('../scripts/setup-local.mjs', import.meta.url), join(root, 'scripts/setup-local.mjs')); + put(join(root, 'package.json'), JSON.stringify({ + type: 'module', peerDependencies: { 'host-peer': '*', 'browser-peer': '*' }, + peerDependenciesMeta: { 'browser-peer': { optional: true } }, + })); + put(join(root, 'lib/index.js'), 'export const name = "fixture";'); + for (const name of ['ws', 'node-pty']) { + put(join(root, 'node_modules', name, 'package.json'), JSON.stringify({ type: 'module', main: 'index.js' })); + put(join(root, 'node_modules', name, 'index.js'), 'export default {};'); + } + const run = (...args) => spawnSync(process.execPath, [join(root, 'scripts/setup-local.mjs'), ...args], { + cwd: fixture, encoding: 'utf8', env: { ...process.env, DSH_HOME: home }, + }); + const target = join(root, 'node_modules/host-peer'); + const missing = run('--skip-install'); + assert.notEqual(missing.status, 0); + assert.match(missing.stderr, /Missing host peer/); + assert.equal(existsSync(target), false); + + put(join(peer, 'package.json'), '{}'); + const first = run('--skip-install'); + assert.equal(first.status, 0, first.stderr); + assert.equal(realpathSync(target), realpathSync(peer)); + assert.equal(run('--skip-install').status, 0, 'repeated setup is safe'); + + rmSync(target); + put(join(target, 'keep.txt'), 'unrelated peer'); + assert.notEqual(run('--skip-install').status, 0); + assert.equal(readFileSync(join(target, 'keep.txt'), 'utf8'), 'unrelated peer'); + rmSync(target, { recursive: true }); + symlinkSync(join(fixture, 'missing'), target, process.platform === 'win32' ? 'junction' : 'dir'); + assert.match(run('--skip-install').stderr, /Inspect the existing peer/); + assert.match(run('--unexpected').stderr, /Usage:/); + console.log('LOCAL SETUP TESTS PASSED'); +} finally { + rmSync(fixture, { recursive: true, force: true }); +} diff --git a/test/smoke-terminal.mjs b/test/smoke-terminal.mjs index 0a1deac..a9ff78c 100644 --- a/test/smoke-terminal.mjs +++ b/test/smoke-terminal.mjs @@ -92,6 +92,7 @@ assert.match(historyNotesDefault.content[0].text, /请帮我分别分析这些 // pure helpers assert.equal(stripAnsi("\x1b[31mred\x1b[0m"), "red"); +assert.equal(stripAnsi("\x1b]0;first\x1b\\visible text\x1b]0;second\x1b\\"), "visible text", "OSC title changes cannot swallow intervening output"); assert.equal(tailTranscript("0123456789", 5).truncated, true); // ---- close / history RPC flow ---- @@ -185,6 +186,12 @@ assert.doesNotMatch(followups[0].content[0].text, /对比一下这两次的输 const historyInjectEmpty = await rpcHandler("historyInject", { sessionId: "sess-2", paths: [] }); assert.equal(historyInjectEmpty.ok, false, "empty selection rejected"); +const invalidMixed = await rpcHandler("historyInject", { sessionId: "sess-2", paths: [older.path, "/not-owned.log"] }); +assert.equal(invalidMixed.ok, false, "a mixed or stale selection must not silently analyze a subset"); +assert.equal(followups.length, 1); +assert.equal(injects.length, 1); +const duplicates = await rpcHandler("historyInject", { sessionId: "sess-2", paths: [older.path, older.path] }); +assert.equal(duplicates.value.referenced, 1, "a repeated path is referenced once"); rmSync(cwd, { recursive: true, force: true }); console.log("SMOKE-TERMINAL TEST DONE"); diff --git a/test/smoke.mjs b/test/smoke.mjs index d5939c9..98b3043 100644 --- a/test/smoke.mjs +++ b/test/smoke.mjs @@ -18,10 +18,12 @@ const dir = mkdtempSync(join(tmpdir(), "shell-cmd-smoke-")); let rpcHandler; const followups = []; +const audit = []; const agent = { id: "smoke-1", session: { header: { cwd: dir }, + append(type, data) { audit.push({ type, data }); }, requestHeader() { return { cwd: dir }; }, @@ -77,6 +79,9 @@ assert.equal(followups[0].source.kind, "plugin"); assert.equal(followups[0].source.plugin, "shell-command"); assert.match(followups[0].content[0].text, /hello/); assert.match(followups[0].content[0].text, /exit code 0/); +assert.deepEqual(audit.map(event => event.type), ["command/run", "command/done"]); +assert.equal(audit[0].data.args, "printf hello"); +assert.equal(audit[0].data.commandId, audit[1].data.commandId); // Another command await invoke("printf world"); @@ -104,6 +109,8 @@ const r7 = await invoke("sleep 5"); assert.equal(r7.ok, true); assert.match(followups[4].content[0].text, /timed out after 1500ms/); assert.ok(Date.now() - started < 5000, "timeout fired promptly"); +await invoke("pwd"); +assert.ok(followups.at(-1).content[0].text.includes(dir), "command runs in the receiving session workspace"); // session without followup (to test that RPC properly checks for it) const agentNoFollowup = { @@ -145,9 +152,10 @@ const ctxNoFollowupApplied = { }; apply(ctxNoFollowupApplied, { terminalEnabled: false }); -// This should work now - no requestHeader check +// A new conversation must be rejected before any shell side effect. const r8 = await rpcHandlerNoFollowup("run", { sessionId: "no-followup", command: "echo test" }, signal); -assert.equal(r8.ok, true, "command should execute without requestHeader check"); +assert.equal(r8.ok, false); +assert.match(r8.error.message, /No model request exists yet/); rmSync(dir, { recursive: true, force: true }); console.log("SMOKE TEST DONE"); diff --git a/test/terminal-protocol.mjs b/test/terminal-protocol.mjs new file mode 100644 index 0000000..c381537 --- /dev/null +++ b/test/terminal-protocol.mjs @@ -0,0 +1,150 @@ +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { createTerminalManager } from "../lib/terminal.js"; +import { registerTerminalRpc, registerTerminalWs, setupTerminalMode } from "../lib/rpc.js"; + +const cwd = mkdtempSync(join(tmpdir(), "dsh-term-protocol-")); +const instances = []; +let failSpawn = false; +const pty = { spawn() { + if (failSpawn) throw new Error("spawn failed"); + const process = { inputs: [], sizes: [], kills: 0, + onData(cb) { this.emit = cb; }, onExit(cb) { this.end = cb; }, + write(data) { this.inputs.push(data); }, resize(...size) { this.sizes.push(size); }, + kill() { this.kills++; this.end?.({ exitCode: 0 }); }, + }; + instances.push(process); + return process; +} }; +const manager = createTerminalManager({ pty, maxTranscriptBytes: 1024 }); +const agent = { id: "owner", session: { header: { cwd } }, + inject() { throw new Error("close must not inject"); }, followup() { throw new Error("close must not wake"); } }; +let rpc; +const agents = { get: (id) => id === agent.id ? agent : undefined }; +registerTerminalRpc({ manager, agents, connection: { rpc: { handle(_channel, handler) { rpc = handler; return () => {}; } } } }); +const call = (endpoint, payload = {}) => rpc(endpoint, { sessionId: "owner", ...payload }); +function socket() { + const ws = new EventEmitter(); + ws.readyState = 1; + ws.sent = []; + ws.send = (data) => ws.sent.push(data); + ws.close = () => { ws.readyState = 3; ws.emit("close"); }; + ws.input = (frame) => ws.emit("message", Buffer.from(JSON.stringify(frame))); + return ws; +} + +try { + failSpawn = true; + assert.equal((await call("open")).ok, false); + failSpawn = false; + const opened = await call("open"); + assert.equal(opened.ok, true, "failed spawn clears its opening guard"); + const streamId = opened.value.streamId; + assert.equal((await call("open")).value.streamId, streamId, "repeated open reuses the PTY"); + assert.equal(instances.length, 1); + const handle = manager.get("owner"); + handle.pty.emit("prompt\x1b[6n"); + const ws = socket(); + manager.attachWs("owner", ws, { structured: true, streamId }); + assert.deepEqual(JSON.parse(ws.sent[0]), { type: "output", data: "prompt\x1b[6n" }); + ws.input({ type: "input", data: "\x1b[1;1R" }); + assert.equal(handle.hasInput, false, "device-status replies are not user input"); + assert.equal(handle.pty.inputs[0], "\x1b[1;1R"); + ws.emit("message", Buffer.from("bad json")); + ws.input({ type: "unknown" }); + ws.input({ type: "input", data: 4 }); + assert.equal(handle.pty.inputs.length, 1); + const broken = socket(); + manager.attachWs("owner", broken, { structured: true, streamId }); + assert.doesNotThrow(() => broken.emit("error", new Error("invalid WebSocket frame"))); + assert.equal(handle.watchers.has(broken), false, "failed transport is detached without crashing the host"); + assert.equal((await call("close", { streamId })).value.transcriptPath, null); + assert.equal(manager.list(cwd, "owner").length, 0, "automatic responses leave no history"); + + const next = (await call("open")).value.streamId; + assert.notEqual(next, streamId); + const restarted = createTerminalManager({ pty }); + const restartedHandle = restarted.open("owner", { cwd }); + assert.notEqual(restartedHandle.streamId, streamId, "host reload cannot reuse an old generation id"); + const beforeReload = socket(); + restarted.attachWs("owner", beforeReload, { streamId }); + assert.equal(beforeReload.readyState, 3, "old streams cannot attach after host reload"); + restarted.disposeAll(); + const stale = socket(); + manager.attachWs("owner", stale, { streamId }); + assert.equal(stale.readyState, 3, "late attach cannot reach a new PTY"); + assert.equal((await call("close", { streamId })).ok, false, "late close cannot kill a new PTY"); + const nextHandle = manager.get("owner"); + const nextWs = socket(); + manager.attachWs("owner", nextWs, { structured: true, streamId: next }); + assert.equal((await call("resize", { cols: 120, rows: 35, streamId: next })).ok, true); + assert.deepEqual(nextHandle.pty.sizes, [[120, 35]]); + for (const value of [0, -1, 1, 2.5, "80", null, Infinity, NaN, 1001]) { + assert.equal((await call("resize", { cols: value, rows: 24 })).ok, false, `reject dimension ${value}`); + } + assert.equal((await rpc("resize", { sessionId: "missing", cols: 80, rows: 24 })).error.code, "session-not-found"); + assert.equal(nextHandle.pty.sizes.length, 1, "invalid requests never resize"); + nextWs.input({ type: "activity" }); + nextWs.input({ type: "input", data: "你\t\x03" }); + nextWs.input({ type: "binary", data: [255, 0, 27] }); + nextWs.input({ type: "binary", data: [256] }); + assert.equal(nextHandle.hasInput, true); + assert.equal(nextHandle.pty.inputs[0], "你\t\x03", "input is passed through without appended newlines"); + assert.deepEqual(nextHandle.pty.inputs[1], Buffer.from([255, 0, 27])); + assert.equal(nextHandle.pty.inputs.length, 2); + nextHandle.pty.emit("vim\x1b[?1049h\rprogress"); + nextHandle.pty.end({ exitCode: 7 }); + assert.deepEqual(JSON.parse(nextWs.sent.at(-1)), { type: "exit", exitCode: 7 }); + assert.equal((await call("resize", { cols: 80, rows: 24 })).ok, false); + nextWs.input({ type: "input", data: "ignored" }); + assert.equal(nextHandle.pty.inputs.length, 2, "exited PTYs cannot receive input"); + const late = socket(); + manager.attachWs("owner", late, { structured: true }); + assert.equal(JSON.parse(late.sent.at(-1)).exitCode, 7, "exit before attach is reported"); + const closed = await call("close", { streamId: next }); + assert.equal(closed.value.exitCode, 7); + assert.equal(manager.list(cwd, "owner").length, 1); + assert.equal(nextHandle.watchers.size, 0); + assert.equal(nextHandle.structuredWatchers.size, 0); + assert.match(manager.readTranscript(closed.value.transcriptPath), /\x1b\[\?1049h/); + + const legacy = manager.open("legacy", { cwd }); + const legacyWs = socket(); + manager.attachWs("legacy", legacyWs); + legacyWs.emit("message", Buffer.from("pwd\n")); + assert.equal(legacy.hasInput, true, "raw clients retain their original input tracking"); + legacy.pty.emit("raw output"); + assert.equal(legacyWs.sent.at(-1), "raw output"); + legacyWs.close(); + assert.equal(legacy.watchers.size, 0); + failSpawn = true; + assert.throws(() => manager.open("legacy", { cwd: join(cwd, "changed") }), /spawn failed/); + assert.equal(manager.get("legacy"), undefined, "failed replacement never returns the killed previous PTY"); + failSpawn = false; + manager.open("legacy", { cwd }); + manager.disposeAll(); + assert.equal(manager.get("legacy"), undefined); + + // Exercise production URL parsing, not just direct manager attachment. + let upgrade, attach; + class Server { handleUpgrade(_req, _socket, _head, cb) { cb({}); } close() {} } + const dispose = registerTerminalWs({ + manager: { attachWs(...args) { attach = args; } }, WebSocketServer: Server, + webServer: { registerUpgrade(value) { upgrade = value.handler; return () => {}; } }, + ctx: { effect(fn) { fn(); } }, + }); + upgrade({ url: "/shell-term/ws?sessionId=owner&streamId=stream&protocol=2" }, {}, Buffer.alloc(0)); + assert.deepEqual(attach, ["owner", {}, { structured: true, streamId: "stream" }]); + dispose(); + const warnings = []; + const noop = await setupTerminalMode({ get() {}, logger: { warn(text) { warnings.push(text); } } }, {}); + noop(); + assert.match(warnings[0], /disabled/); + console.log("TERMINAL PROTOCOL TESTS PASSED"); +} finally { + manager.disposeAll(); + rmSync(cwd, { recursive: true, force: true }); +}