release: 发布 v1.13.0 Theme V3 主题系统版本 (#107)

## 发布说明

**v1.13.0 Theme V3 主题系统版本**

### 关联 Issue

- 关联 #99(「能不能直接在网页加个密码?」):本版本实现其中**主题苹果风**部分——新增 Apple 内置主题(macOS
风格浅色)并落地 Theme V3 主题系统;**网页访问密码**部分未包含在本版本,issue 保持开启、留待后续版本。

### 版本亮点

- **内置主题 5 → 7 款**:新增 CRT Amber(CRT 磷光深色:径向暗角背景 + 扫描线/闪烁/辉光/噪点全开 + 方形
mono 造型)与 Glass(蓝紫浅色玻璃态:mesh 粉彩漂移背景 + 强表面模糊 + 1.4× 圆角 + 分段控件);Glacier
替换为 Apple(macOS 风格浅色,完整 ANSI 16 色无障碍变体)
- **Theme V3 声明式令牌系统**(schemaVersion
3):`background`(solid/linear/radial/mesh 四类型、停靠点白名单、读性遮罩下限
0.25/0.35、drift 动画)、`effects`(scanline/flicker/glow/noise 强度钳制
0-1、data-fx-* 门控、Cyberpunk
默认视觉不变)、`typography`(字号/圆角缩放)、`appearance.blur` 独立表面模糊档位
- **零 DOM 操作、前后端同源校验**:背景/效果全部 CSS 变量 + 属性驱动;V2 主题数据自动升级、glacier
baseTheme 优雅降级;导入/导出双向兼容
- **在线主题编辑器支持 V3**:背景层/效果/版式三组面板 + blur 档位,导出 schemaVersion 3
- **全量文档对齐**:README/tests README/AGENTS/CHANGELOG 与当前实现同步

### 提交列表

| 提交 | 说明 |
| ---- | ---- |
| 268a892 | feat: 内置主题 Glacier 替换为 Apple 浅色主题 |
| 86e3ddf | feat: Theme V3 主题系统落地——背景层、效果注册表与版式缩放 |
| 9092e2a | release: 发布 v1.13.0(版本号 + CHANGELOG) |
| c098a7c | docs: 全量文档与当前实现对齐(测试清单 + 措辞修正) |

### 验证结果

- ✅ typecheck(worker + frontend + tests 三工程)
- ✅ vitest 54 文件 / 649 用例
- ✅ build:frontend 可复现内联构建(html.ts 再生成)
- ✅ 主题 e2e 6/6(含 CRT/Glass 切换、drift 属性、强模糊与 body::before 背景计算值断言)

---------

Co-authored-by: TanXin <tanxin@example.com>
This commit is contained in:
TanXinandTanXin authored and GitHub committed 2026-08-27 16:05:14 +08:00
1 parent 185011066b
commit 7e20e2d117
18 files changed
+1377 -209

No files matched your search

+3 -3
View File
@@ -64,7 +64,7 @@ src/
│ ├── utils.ts # Binary utilities
│ ├── sftp.ts # SFTP v3 client implementation
│ └── sftp-types.ts # SFTP protocol constants and types
├── theme-schema.ts # Theme V2 shared validation, allowlists, enums, and size limits
├── theme-schema.ts # Theme V3 shared validation(外观/背景/效果/版式模块、白名单与读性遮罩下限)
├── snippet-schema.ts # Command snippet shared validation, limits, and normalization (UserDBDO + localStorage)
└── types.ts # Shared TypeScript type definitions
@@ -82,7 +82,7 @@ frontend/
│ ├── os-icons.ts # 操作系统品牌图标(内嵌 simple-icons SVG)
│ ├── port.ts # 端口解析与 1-65535 校验
│ ├── regions.ts # DO locationHint 区域选项共享数据(Auto + 白名单)
│ ├── theme.ts # Theme V2 内置主题、UI CSS 变量与外观预设
│ ├── theme.ts # Theme V3 内置主题、UI CSS 变量、外观预设、背景/效果合成与版式缩放
│ ├── auth-challenge-dialog.ts # RFC 4256 multi-round authentication prompt UI
│ ├── mobile-terminal.ts # Mobile viewport, shortcut toolbar, clipboard and landscape controller
│ ├── mobile-input.ts # Pure iOS IME diff and one-shot modifier helpers
@@ -308,7 +308,7 @@ release: 发布 vX.Y.Z <主题>版本(如 `release: 发布 v1.10.2 工作流
13. **SFTP selection model** - file selection supports single, Cmd/Ctrl toggle, Shift range and select-all. Batch download reuses the sequential download queue; batch delete waits for all delete/rmdir results before refreshing.
14. **Agent terminal selection context** - “Ask AI assistant” attaches one immutable selection snapshot per tab and never sends it by itself. New selections replace the pending snapshot; successful sends and session teardown clear it. Preserve the untrusted-data/non-authorization boundary in `terminal-selection-context.ts`.
15. **Region inference privacy** - Saving or changing a Cloudflare-direct server host calls the third-party IPinfo service and persists the inferred locationHint. Servers with `jump_server_id` are downstream nodes: never query their hosts, ignore and clear their own region hints, and infer once if they later become direct Auto entries. Keep the provider name and disclosure synchronized across README/code comments; failures must continue to fall back to Cloudflare's default placement.
16. **Theme editor ownership** - The full visual editor and JSON export live in `docs/theme-editor/index.html` for GitHub Pages and never authenticate against CloudSSH. `scripts/sync-theme-editor.js` keeps its built-in colors and resolved appearance presets aligned with `frontend/src/theme.ts`; the application and Worker share Theme V2 validation through `src/theme-schema.ts`. The application only imports JSON themes and synchronizes the single custom-theme slot through `/api/user/theme` for signed-in users; later imports replace the previous theme, while anonymous themes remain local.
16. **Theme editor ownership** - The full visual editor and JSON export live in `docs/theme-editor/index.html` for GitHub Pages and never authenticate against CloudSSH. `scripts/sync-theme-editor.js` keeps its built-in colors, resolved appearance presets, background layers and effect presets aligned with `frontend/src/theme.ts`; the application and Worker share Theme V3 validation through `src/theme-schema.ts` (appearance enums + V3 background/effects/typography modules, all declarative and whitelist-validated). The application only imports JSON themes and synchronizes the single custom-theme slot through `/api/user/theme` for signed-in users; later imports replace the previous theme, while anonymous themes remain local. V3 effect/background layers are driven by CSS variables and data attributes only — no user CSS/JS is ever evaluated, and background gradients compose exclusively from whitelist-validated color stops.
17. **Mobile terminal input and recovery** - Mobile shortcuts and the iOS keyCode 229 fallback must continue through `TrzszFilter.processTerminalInput`; never send them directly to the WebSocket, and do not permit any terminal input until `shell_ready`. For iOS IME fallback, capture the textarea baseline on `keydown=229` but flush on the corresponding `keyup` regardless of its key code, since Safari commonly reports 32 for Space and 0 for punctuation; xterm `onData` remains authoritative to prevent duplicate input. Keep the explicit mobile selection mode isolated from desktop mouse auto-copy, map touch drags through xterm's public selection API instead of native long-press selection, and debounce visual viewport refits. Enable background-return visibility recovery only when the device has touch points and a coarse primary pointer, so desktop tab changes do not emit recovery logs or probes. A mobile background return must validate the WebSocket with a bounded ID-matched heartbeat instead of trusting `readyState`; anonymous reconnects may reuse only the current in-memory config, while saved-server reconnects must request a fresh one-time token from `/api/servers/:id/connect`. Never report a connection as online before the replacement Shell is ready.
18. **Saved-server OS detection** - Run OS detection only for signed-in saved servers without a persisted result, through a separate non-blocking SSH exec channel after Shell readiness. Never persist `unknown`; host or port changes must clear the stored OS, and background metadata updates must not change `updated_at` or server ordering. Keep backend canonical keys synchronized with frontend labels/icon fallbacks.
19. **Keyboard-interactive authentication** - Begin user authentication with the RFC 4252 `none` probe and choose only methods advertised by the server, while retaining the bounded compatibility fallback for servers that omit the list. RFC 4256 challenges are event-driven during the SSH auth state. Keep method-specific message type 60 disambiguated by the active auth method, use `partial_success` to advance bounded multi-factor stages, and only fall back without partial success when the server no longer offers the configured primary method. Bind browser responses and `auth_challenge_ack` display acknowledgements to one random challenge ID and originating WebSocket, distinguish an undisplayed challenge from an acknowledged but unanswered challenge, never log responses, clear pending challenges on timeout/reconnect/close, require explicit user action before substituting a stored password, and close authentication timeouts normally so older frontends cannot reconnect repeatedly. Treat ordinary server-side credential rejection as an expected close rather than WebSocket error 1011.
+20
View File
@@ -5,6 +5,26 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [1.13.0] - 2026-08-27
### Added
- **Theme V3 背景层**:新增 `background` 顶层模块(schemaVersion 3),支持 solid / linear / radial / mesh 四类背景,最多 5 个停靠点(均过白名单颜色校验)、线性角度(0–360)、读性遮罩(scrim,渐变背景强制暗色 ≥0.25 / 浅色 ≥0.35 的下限)与缓慢漂移(drift)动画;背景由 `body::before` 固定全屏层承载,纯 CSS 变量驱动、零 DOM 改动。
- **Theme V3 效果注册表**:新增 `effects` 模块(scanline / flicker / glow / noise),强度钳制在 0–1;扫描线与闪烁门控从「cyberpunk 风格硬编码」泛化为 `data-fx-*` 属性驱动(Cyberpunk 内置主题迁移为参数化配置,默认视觉不变);噪点使用内联 feTurbulence SVG 纹理,无外部请求。
- **Theme V3 版式与表面**:新增 `typography` 模块(字号缩放 0.85–1.25、圆角缩放 0.5–2,均叠加在密度/形状档位之上)与独立的 `appearance.blur` 表面模糊档位(none / subtle / strong);动效门控(`data-ui-motion`)与 `prefers-reduced-motion` 双重视角约束背景漂移与闪烁。
- **两套旗舰内置主题**:内置主题从 5 款扩至 7 款,新增 **CRT Amber**(琥珀磷光深色主题:径向暗角背景 + 扫描线/闪烁/辉光/噪点全开 + 方形 mono 造型)与 **Glass**(蓝紫浅色玻璃态主题:mesh 粉彩漂移背景 + 强表面模糊 + 1.4× 圆角 + 分段控件);两者明暗对比、质感与动效差异显著。
- **Apple 浅色主题**:内置主题 Glacier 替换为 Apple(macOS 风格浅色),占用 soft 风格预设占位并保持四种 UI 风格全覆盖;终端 ANSI 16 色采用 Apple 系统色无障碍变体,UI 变量取材 Apple 设计语言(#f5f5f7 背景、#0066da 链接蓝、#5856d6 systemIndigo Agent 色),文本/强调/错误色全部通过 4.5:1 对比度并纳入测试断言。
- **在线主题编辑器支持 V3**:新增背景层(类型/角度/遮罩/动画/停靠点)、效果(四项强度滑杆)与版式缩放(字号/圆角)三组面板及 blur 档位;导出升级为 schemaVersion 3 并携带新模块,导入按与后端同源的钳制/白名单规则消毒;同步脚本提取 `BUILT_IN_BACKGROUND` / `BUILT_IN_EFFECTS` / `BUILT_IN_TYPOGRAPHY` 注入预设。
### Changed
- `THEME_SCHEMA_VERSION` 升至 3;V2 主题数据自动升级(新模块缺省即旧行为),存量 `baseTheme: 'glacier'` 主题导入时优雅降级(字段丢弃、按明暗模式回退基底),旧版 glacier 选择在 localStorage 中一次性迁移到 Standard Dark。
- 表面模糊由 shadow 预设派生值改为独立 blur 档位完全接管(后置规则同优先级胜出),geometry 变量(圆角/字号)改为 calc 乘法组合缩放。
### Fixed
- 补充既有 lint 清洁(forEach 回调返回值、未使用导入)。
## [1.12.2] - 2026-08-27
### Changed
+2 -2
View File
@@ -94,7 +94,7 @@
- **全功能极客终端**:基于 `@xterm/xterm` 与 `@xterm/addon-webgl` 硬件加速渲染引擎,保证海量日志输出顺滑不卡顿。
- **可靠的终端剪贴板交互**:鼠标完成终端选区后自动复制,右键可直接粘贴;触摸设备点击快捷键栏的复制按钮进入选择模式,拖动选择文本后再次点击完成复制,避免依赖不稳定的长按选区,粘贴则使用独立按钮。粘贴统一经过 xterm.js 原生输入管线,仅在远端应用启用 bracketed paste 模式时发送对应控制序列,并自动规范化换行,兼容 Vim 等交互式编辑器和普通 Shell。
- **移动端终端适配**:针对手机和平板提供动态可视高度、软键盘与安全区适配、iOS 中文输入法兼容、紧凑工具栏、一次性 Ctrl/Alt、Esc/Tab/方向键/Home/End/PgUp/PgDn 等快捷键,以及移动端全屏 Agent/SFTP 面板。页面从后台返回后会主动验证 WebSocket,淘汰表面在线但已失效的连接;匿名会话使用当前内存凭据重新建立 SSH,登录用户的已保存服务器则重新申请一次性连接令牌,且只有收到 `shell_ready` 后才恢复“已连接”状态和终端输入。用户可主动尝试“全屏横屏”;浏览器不支持方向锁定时会回退为手动旋转提示,不会强制改变桌面端布局。移动系统若彻底回收网页,当前 Shell 仍无法无缝续接。
- **个性化 UI**:Theme V2 系统提供 Standard Dark、Standard Light、Cyberpunk、Glacier、Gruvbox 五款内置主题。配套 [GitHub Pages 主题编辑器](https://newbietan.github.io/CloudSSH/)可实时调整颜色、形状、密度、字体、阴影、动效及按钮/输入框/卡片/标签页样式,并预览登录页、服务器列表、终端 + SFTP 和 AI Agent 面板。主题通过 JSON 文件导入、导出、备份与分享;登录用户在应用中导入后会同步到账号并可跨浏览器恢复,匿名用户仅保存在当前浏览器。
- **个性化 UI**:Theme V3 系统提供 Standard Dark、Standard Light、Cyberpunk、Apple、Gruvbox、CRT Amber、Glass 七款内置主题。V3 支持渐变/网格背景层(含读性遮罩与缓慢漂移动画)、扫描线/闪烁/辉光/噪点效果注册表、独立表面模糊档位与版式缩放,主体风格间差异显著。配套 [GitHub Pages 主题编辑器](https://newbietan.github.io/CloudSSH/)可实时调整颜色、形状、密度、字体、阴影、动效、背景层、效果及按钮/输入框/卡片/标签页样式,并预览登录页、服务器列表、终端 + SFTP 和 AI Agent 面板。主题通过 JSON 文件导入、导出、备份与分享;登录用户在应用中导入后会同步到账号并可跨浏览器恢复,匿名用户仅保存在当前浏览器。
- **SFTP 图形化文件管理**:集成完整的 SFTP v3 文件传输协议,提供图形化文件浏览器界面。支持目录浏览、文件上传/下载、新建文件夹、文件重命名与删除等操作;支持普通单选、`Cmd/Ctrl` 切换选择、`Shift` 连选、全选,以及批量下载文件和批量删除。基于 SSH 子系统实现,与终端会话并行运行,互不干扰,支持下载队列及上传取消。
- **原生文件传输**:集成 [trzsz.js](https://github.com/trzsz/trzsz.js),支持 `trz`(上传)/ `tsz`(下载)命令进行文件传输,兼容 tmux 会话。还支持拖拽文件到终端窗口直接上传、目录传输及断点续传等高级功能。(需远程服务器安装 [trzsz](https://trzsz.github.io/))
- **中英文界面**:内置简体中文与英文两套 UI 词条,自动跟随浏览器语言并提供手动切换,选择通过 URL 参数或本地存储(`cloudssh_locale`)持久化。
@@ -412,7 +412,7 @@ test 分支(开发/测试) ──合并──> main 分支(生产)
| ------------ | ---------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| **前端** | TypeScript + Vite + xterm.js | Web 终端模拟器,WebGL 硬件加速 |
| **国际化** | 自研轻量 i18n(`frontend/src/i18n`) | 简体中文 / English 双语言界面,浏览器语言自动识别与手动切换 |
| **UI 框架** | Tailwind CSS(Vite/PostCSS 本地构建)+ Theme V2 系统 | 应用支持内置主题切换、自定义主题 JSON 导入及登录账号同步;主题编辑与导出由 GitHub Pages 提供 |
| **UI 框架** | Tailwind CSS(Vite/PostCSS 本地构建)+ Theme V3 系统 | 应用支持内置主题切换、自定义主题 JSON 导入及登录账号同步;主题编辑与导出由 GitHub Pages 提供 |
| **文件传输** | trzsz.js | 支持 trz/tsz 命令、拖拽上传、断点续传 |
| **AI 助手** | BYOK + OpenAI 兼容接口 | 自带 API Key,支持 DeepSeek 等兼容模型 |
| **后端** | Cloudflare Workers | Serverless 边缘计算 |
+2 -2
View File
@@ -94,7 +94,7 @@
- **Geek Terminal Experience**: Powered by `@xterm/xterm` and the `@xterm/addon-webgl` hardware acceleration rendering engine, ensuring silky smooth scrolling even with massive log outputs.
- **Reliable Terminal Clipboard Interaction**: Completing a terminal selection with a mouse automatically copies it, and right-click pastes directly. On touch devices, tapping Copy in the shortcut bar enters selection mode; drag across terminal text and tap Copy again to finish, avoiding unreliable long-press selection, while Paste remains a separate action. Paste data follows xterm.js's native input pipeline, emits bracketed-paste control sequences only when the remote application enables that mode, and normalizes line endings for compatibility with Vim and regular shells.
- **Mobile Terminal Support**: Phones and tablets get dynamic visual-viewport sizing, soft-keyboard and safe-area handling, iOS Chinese IME compatibility, a compact action bar, one-shot Ctrl/Alt, Esc/Tab/arrows/Home/End/PgUp/PgDn shortcuts, and full-screen Agent/SFTP panels. After a page returns from the background, CloudSSH actively validates the WebSocket and replaces connections that only appear open. Anonymous sessions rebuild SSH from the current in-memory credentials, while signed-in saved servers request a fresh one-time connection token; the UI and terminal input return to the connected state only after `shell_ready`. Users may explicitly request fullscreen landscape; unsupported orientation locks fall back to a manual rotation hint without changing desktop layouts. If the mobile OS completely discards the page, the current shell cannot be resumed seamlessly.
- **Customizable UI**: Theme V2 includes Standard Dark, Standard Light, Cyberpunk, Glacier, and Gruvbox. The companion [GitHub Pages theme editor](https://newbietan.github.io/CloudSSH/) provides live controls for colors, shape, density, font, shadows, motion, and button/input/card/tab styles, with previews for login, server list, terminal + SFTP, and the AI Agent panel. Themes are imported, exported, backed up, and shared as JSON files. Signed-in users sync imported themes to their account for cross-browser restoration, while anonymous users keep them in the current browser only.
- **Customizable UI**: Theme V3 offers built-in Standard Dark, Standard Light, Cyberpunk, Apple, Gruvbox, CRT Amber, and Glass themes. V3 adds gradient/mesh background layers (with a readability scrim and a slow drift animation), a scanline/flicker/glow/noise effect registry, an independent surface-blur tier, and typography scaling, so themes differ far beyond color swaps. The companion [GitHub Pages theme editor](https://newbietan.github.io/CloudSSH/) provides live controls for colors, shape, density, font, shadows, motion, background layers, effects, and button/input/card/tab styles, with previews for login, server list, terminal + SFTP, and the AI Agent panel. Themes are imported, exported, backed up, and shared as JSON files. Signed-in users sync imported themes to their account for cross-browser restoration, while anonymous users keep them in the current browser only.
- **SFTP Graphical File Manager**: Integrated with a complete SFTP v3 file transfer protocol, providing a graphical file browser interface. Supports directory browsing, file upload/download, creating new folders, file renaming, and deletion, plus plain selection, `Cmd/Ctrl` toggle selection, `Shift` range selection, select all, batch file downloads, and batch deletion. Built on the SSH subsystem, it runs alongside terminal sessions without interference and supports download queues and upload cancellation.
- **Native File Transfer**: Integrated with [trzsz.js](https://github.com/trzsz/trzsz.js), supporting `trz` (upload) / `tsz` (download) commands for file transfer, fully compatible with tmux sessions. Also supports drag-and-drop file upload to the terminal, directory transfer, and resumable transfers. (Requires [trzsz](https://trzsz.github.io/) installed on the remote server)
- **Bilingual UI**: Ships built-in Simplified Chinese and English translations, automatically following the browser language with a manual override; the choice is persisted via a URL parameter or local storage (`cloudssh_locale`).
@@ -412,7 +412,7 @@ test branch (dev/test) ──merge──> main branch (production)
| ------- | ------------ | ------------- |
| **Frontend** | TypeScript + Vite + xterm.js | Web terminal emulator, WebGL hardware acceleration |
| **i18n** | Lightweight custom i18n (`frontend/src/i18n`) | Simplified Chinese / English dual-language UI with automatic browser detection and manual switching |
| **UI Framework** | Tailwind CSS (local Vite/PostCSS build) + Theme V2 | The app supports built-in theme switching, custom JSON import, and signed-in account sync; editing and export live on GitHub Pages |
| **UI Framework** | Tailwind CSS (local Vite/PostCSS build) + Theme V3 | The app supports built-in theme switching, custom JSON import, and signed-in account sync; editing and export live on GitHub Pages |
| **File Transfer** | trzsz.js | Supports trz/tsz commands, drag-and-drop upload, resumable transfers |
| **AI Assistant** | BYOK + OpenAI-compatible API | Bring your own API key, supports DeepSeek and other compatible models |
| **Backend** | Cloudflare Workers | Serverless edge computing |
+566 -42
View File
@@ -261,7 +261,7 @@
font-size: 11px;
}
.setting-row input,
.setting-row input:not([type='range']),
.setting-row select {
width: 100%;
min-width: 0;
@@ -274,6 +274,16 @@
outline: none;
}
.setting-row:has(input[type='range']) {
grid-template-columns: minmax(110px, 1fr) minmax(96px, 1fr) 44px;
}
.setting-row .range-value {
font-size: 11px;
color: var(--editor-muted);
text-align: right;
}
.setting-row input:focus,
.setting-row select:focus {
border-color: var(--editor-accent);
@@ -365,6 +375,58 @@
--hover-lift: -2px;
font-family: var(--font-ui);
font-size: calc(1em * var(--font-size-scale));
position: relative;
isolation: isolate;
background-color: var(--bg);
background-image: var(--app-bg-stack, none);
}
/* V3:预览背景漂移(motion=none 时显式停止) */
.theme-scope[data-bg-animation='drift'] {
background-size: 200% 200%;
animation: theme-editor-bg-drift 40s ease-in-out infinite alternate;
}
.theme-scope[data-ui-motion='none'] {
animation: none;
}
@keyframes theme-editor-bg-drift {
0% {
background-position: 0% 0%;
}
100% {
background-position: 100% 100%;
}
}
/* V3:预览噪点层(垫在内容之下,仅作用于背景) */
.theme-scope[data-fx-noise='on']::after {
content: '';
position: absolute;
inset: 0;
z-index: -1;
pointer-events: none;
opacity: var(--fx-noise-opacity, 0.05);
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='en'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23en)'/%3E%3C/svg%3E");
}
/* V3:表面模糊档位(后置覆盖 shadow 派生值) */
.theme-scope[data-ui-blur='none'] {
--surface-blur: 0px;
}
.theme-scope[data-ui-blur='subtle'] {
--surface-blur: 6px;
}
.theme-scope[data-ui-blur='strong'] {
--surface-blur: 16px;
}
/* V3:预览辉光 */
.theme-scope[data-fx-glow='on'] .server-card {
box-shadow: var(--shadow-card), 0 4px calc(24px * var(--fx-glow-strength, 0.6)) var(--accent-glow);
}
.theme-scope[data-ui-shape="square"] {
@@ -589,12 +651,19 @@
display: none;
}
.theme-scope[data-ui-style="standard"] :is(.scanlines, .scanline, .flicker),
.theme-scope[data-ui-style="soft"] :is(.scanlines, .scanline, .flicker),
.theme-scope[data-ui-style="dense"] :is(.scanlines, .scanline, .flicker) {
.theme-scope:not([data-fx-scanline='on']) :is(.scanlines, .scanline),
.theme-scope:not([data-fx-flicker='on']) .flicker {
display: none;
}
.theme-scope[data-fx-scanline='on'] .scanlines {
opacity: var(--fx-scanline-opacity, 1);
}
.theme-scope[data-fx-flicker='on'] .flicker {
animation-duration: var(--fx-flicker-speed, 0.15s);
}
.theme-scope[data-ui-motion="none"] * {
animation: none !important;
transition: none !important;
@@ -2115,8 +2184,10 @@
<option value="standard-dark">Standard Dark</option>
<option value="standard-light">Standard Light</option>
<option value="cyberpunk" selected>Cyberpunk</option>
<option value="glacier">Glacier</option>
<option value="apple">Apple</option>
<option value="gruvbox">Gruvbox</option>
<option value="crt">CRT Amber</option>
<option value="glass">Glass</option>
</select>
<span class="material-symbols-outlined" aria-hidden="true">expand_more</span>
</div>
@@ -2400,8 +2471,10 @@
<option value="standard-dark">Standard Dark</option>
<option value="standard-light">Standard Light</option>
<option value="cyberpunk" selected>Cyberpunk</option>
<option value="glacier">Glacier</option>
<option value="apple">Apple</option>
<option value="gruvbox">Gruvbox</option>
<option value="crt">CRT Amber</option>
<option value="glass">Glass</option>
</select>
<span class="material-symbols-outlined terminal-tool-icon">upload_file</span>
<span class="material-symbols-outlined terminal-tool-icon">folder_open</span>
@@ -2714,6 +2787,23 @@ const TRANSLATIONS = {
'group.basic': '主题信息',
'group.appearance': '整体外观',
'group.componentStyles': '组件样式',
'group.themeV3Background': '背景层(V3)',
'group.themeV3Effects': '效果(V3)',
'group.themeV3Typography': '版式缩放(V3)',
'background.type': '背景类型',
'background.angle': '渐变角度',
'background.scrim': '读性遮罩',
'background.animation': '背景动画',
'background.stop1': '停靠点 1',
'background.stop2': '停靠点 2',
'background.stop3': '停靠点 3',
'background.stop4': '停靠点 4',
'effects.scanline': '扫描线',
'effects.flicker': '闪烁',
'effects.glow': '辉光',
'effects.noise': '噪点',
'typography.fontScale': '字号缩放',
'typography.radiusScale': '圆角缩放',
'appearance.name': '主题名称',
'appearance.colorScheme': '明暗模式',
'appearance.style': '整体风格',
@@ -2722,6 +2812,7 @@ const TRANSLATIONS = {
'appearance.font': '字体',
'appearance.shadow': '阴影',
'appearance.motion': '动效',
'appearance.blur': '表面模糊',
'appearance.button': '按钮',
'appearance.input': '输入框',
'appearance.card': '卡片',
@@ -2742,6 +2833,11 @@ const TRANSLATIONS = {
'option.none': '无',
'option.subtle': '轻微',
'option.elevated': '悬浮',
'option.solid': '纯色',
'option.linear': '线性渐变',
'option.radial': '径向渐变',
'option.mesh': '网格渐变',
'option.drift': '缓慢漂移',
'option.reduced': '精简',
'option.full': '完整',
'option.outline': '描边',
@@ -2870,6 +2966,23 @@ const TRANSLATIONS = {
'group.basic': 'THEME INFORMATION',
'group.appearance': 'APPEARANCE',
'group.componentStyles': 'COMPONENT STYLES',
'group.themeV3Background': 'BACKGROUND (V3)',
'group.themeV3Effects': 'EFFECTS (V3)',
'group.themeV3Typography': 'TYPOGRAPHY SCALE (V3)',
'background.type': 'Background type',
'background.angle': 'Gradient angle',
'background.scrim': 'Readability scrim',
'background.animation': 'Background animation',
'background.stop1': 'Stop 1',
'background.stop2': 'Stop 2',
'background.stop3': 'Stop 3',
'background.stop4': 'Stop 4',
'effects.scanline': 'Scanline',
'effects.flicker': 'Flicker',
'effects.glow': 'Glow',
'effects.noise': 'Noise',
'typography.fontScale': 'Font scale',
'typography.radiusScale': 'Radius scale',
'appearance.name': 'Theme name',
'appearance.colorScheme': 'Color scheme',
'appearance.style': 'Style',
@@ -2878,6 +2991,7 @@ const TRANSLATIONS = {
'appearance.font': 'Font',
'appearance.shadow': 'Shadow',
'appearance.motion': 'Motion',
'appearance.blur': 'Surface blur',
'appearance.button': 'Button',
'appearance.input': 'Input',
'appearance.card': 'Card',
@@ -2898,6 +3012,11 @@ const TRANSLATIONS = {
'option.none': 'None',
'option.subtle': 'Subtle',
'option.elevated': 'Elevated',
'option.solid': 'Solid',
'option.linear': 'Linear',
'option.radial': 'Radial',
'option.mesh': 'Mesh',
'option.drift': 'Drift',
'option.reduced': 'Reduced',
'option.full': 'Full',
'option.outline': 'Outline',
@@ -3030,6 +3149,7 @@ const PRESETS = /* THEME_PRESETS_START */ {
"font": "system",
"shadow": "subtle",
"motion": "reduced",
"blur": "subtle",
"components": {
"button": "solid",
"input": "boxed",
@@ -3101,6 +3221,7 @@ const PRESETS = /* THEME_PRESETS_START */ {
"font": "system",
"shadow": "subtle",
"motion": "reduced",
"blur": "subtle",
"components": {
"button": "solid",
"input": "boxed",
@@ -3173,6 +3294,7 @@ const PRESETS = /* THEME_PRESETS_START */ {
"font": "mono",
"shadow": "none",
"motion": "full",
"blur": "none",
"components": {
"button": "outline",
"input": "underline",
@@ -3180,6 +3302,20 @@ const PRESETS = /* THEME_PRESETS_START */ {
"tabs": "underline"
}
},
"background": {
"type": "linear",
"stops": [
"#0a0a0a",
"#11170c"
],
"angle": 165,
"scrim": 0.3,
"animation": "none"
},
"effects": {
"scanline": 1,
"flicker": 1
},
"terminal": {
"background": "#0a0a0a",
"foreground": "#4af626",
@@ -3217,9 +3353,9 @@ const PRESETS = /* THEME_PRESETS_START */ {
"--agent-agent-color": "#14d1ff"
}
},
"glacier": {
"name": "Glacier",
"colorScheme": "dark",
"apple": {
"name": "Apple",
"colorScheme": "light",
"appearance": {
"style": "soft",
"shape": "soft",
@@ -3227,6 +3363,7 @@ const PRESETS = /* THEME_PRESETS_START */ {
"font": "system",
"shadow": "elevated",
"motion": "reduced",
"blur": "strong",
"components": {
"button": "soft",
"input": "boxed",
@@ -3235,40 +3372,58 @@ const PRESETS = /* THEME_PRESETS_START */ {
}
},
"terminal": {
"background": "#0a192f",
"foreground": "#64ffda",
"cursor": "#e6f1ff",
"cursorAccent": "#0a192f",
"selectionBackground": "#112240"
"background": "#ffffff",
"foreground": "#1d1d1f",
"cursor": "#0066da",
"cursorAccent": "#ffffff",
"selectionBackground": "#b3d7ff",
"selectionForeground": "#1d1d1f",
"selectionInactiveBackground": "#dde8f7",
"black": "#1d1d1f",
"red": "#d70015",
"green": "#248a3d",
"yellow": "#b25000",
"blue": "#0040dd",
"magenta": "#8944ab",
"cyan": "#0b7285",
"white": "#8e8e93",
"brightBlack": "#6e6e73",
"brightRed": "#ff3b30",
"brightGreen": "#34c759",
"brightYellow": "#c93400",
"brightBlue": "#0071e3",
"brightMagenta": "#af52de",
"brightCyan": "#30b0c7",
"brightWhite": "#1d1d1f"
},
"ui": {
"--bg": "#0a192f",
"--bg-surface": "#0d2137",
"--bg-elevated": "#112240",
"--bg-terminal": "#061526",
"--text": "#64ffda",
"--text-muted": "#8892b0",
"--text-dim": "#495670",
"--accent": "#64ffda",
"--accent-secondary": "#e6f1ff",
"--accent-secondary-light": "#ccd6f6",
"--border": "#1d3557",
"--border-strong": "#495670",
"--error": "#ff6b6b",
"--error-bg": "#3d0000",
"--on-accent": "#0a192f",
"--surface-dot": "#1d3557",
"--scrollbar-track": "rgba(10, 25, 47, 0.5)",
"--scrollbar-thumb": "rgba(100, 255, 218, 0.2)",
"--scrollbar-thumb-hover": "rgba(100, 255, 218, 0.4)",
"--scanline-tint": "rgba(100, 255, 218, 0.02)",
"--accent-glow": "rgba(100, 255, 218, 0.08)",
"--accent-bg": "rgba(100, 255, 218, 0.1)",
"--modal-overlay": "rgba(0, 0, 0, 0.85)",
"--on-surface": "#e6f1ff",
"--on-surface-variant": "#8892b0",
"--agent-user-color": "#64ffda",
"--agent-agent-color": "#e6f1ff"
"--bg": "#f5f5f7",
"--bg-surface": "#ffffff",
"--bg-elevated": "#ffffff",
"--bg-terminal": "#ffffff",
"--text": "#1d1d1f",
"--text-muted": "#636368",
"--text-dim": "#6e6e73",
"--accent": "#0066da",
"--accent-secondary": "#0052b4",
"--accent-secondary-light": "#cce4ff",
"--border": "#d2d2d7",
"--border-strong": "#aeaeb2",
"--error": "#d70015",
"--error-bg": "#ffebe9",
"--on-accent": "#ffffff",
"--surface-dot": "#e8e8ed",
"--scrollbar-track": "rgba(210, 210, 215, 0.45)",
"--scrollbar-thumb": "rgba(99, 99, 104, 0.35)",
"--scrollbar-thumb-hover": "rgba(99, 99, 104, 0.55)",
"--scanline-tint": "transparent",
"--accent-glow": "rgba(0, 102, 218, 0.08)",
"--accent-bg": "rgba(0, 102, 218, 0.1)",
"--modal-overlay": "rgba(0, 0, 0, 0.32)",
"--on-surface": "#1d1d1f",
"--on-surface-variant": "#636368",
"--agent-user-color": "#0066da",
"--agent-agent-color": "#5856d6"
}
},
"gruvbox": {
@@ -3281,6 +3436,7 @@ const PRESETS = /* THEME_PRESETS_START */ {
"font": "mono",
"shadow": "none",
"motion": "reduced",
"blur": "none",
"components": {
"button": "outline",
"input": "boxed",
@@ -3324,6 +3480,189 @@ const PRESETS = /* THEME_PRESETS_START */ {
"--agent-user-color": "#b8bb26",
"--agent-agent-color": "#83a598"
}
},
"crt": {
"name": "CRT Amber",
"colorScheme": "dark",
"appearance": {
"style": "cyberpunk",
"shape": "square",
"density": "compact",
"font": "mono",
"shadow": "none",
"motion": "full",
"blur": "none",
"components": {
"button": "outline",
"input": "underline",
"card": "outlined",
"tabs": "underline"
}
},
"background": {
"type": "radial",
"stops": [
"#261b00",
"#0f0a00"
],
"angle": 160,
"scrim": 0.3,
"animation": "none"
},
"effects": {
"scanline": 1,
"flicker": 0.6,
"glow": 0.5
},
"typography": {
"fontScale": 1,
"radiusScale": 0.75
},
"terminal": {
"background": "#0f0a00",
"foreground": "#ffb000",
"cursor": "#ffd257",
"cursorAccent": "#0f0a00",
"selectionBackground": "#3d2e00",
"selectionForeground": "#ffb000",
"selectionInactiveBackground": "#2a2000",
"black": "#241a00",
"red": "#ff6b4a",
"green": "#d4a017",
"yellow": "#ffb000",
"blue": "#f0c040",
"magenta": "#e08e39",
"cyan": "#c8b04a",
"white": "#d9c08a",
"brightBlack": "#8a7440",
"brightRed": "#ffa080",
"brightGreen": "#ffd257",
"brightYellow": "#ffe08a",
"brightBlue": "#ffe8b0",
"brightMagenta": "#ffc27a",
"brightCyan": "#e8d89a",
"brightWhite": "#fff3c4"
},
"ui": {
"--bg": "#0f0a00",
"--bg-surface": "#171000",
"--bg-elevated": "#1d1600",
"--bg-terminal": "#0f0a00",
"--text": "#ffb000",
"--text-muted": "#bfa06a",
"--text-dim": "#937c46",
"--accent": "#ffb000",
"--accent-secondary": "#ffd257",
"--accent-secondary-light": "#ffe08a",
"--border": "#3d2e00",
"--border-strong": "#5c470a",
"--error": "#ff6b4a",
"--error-bg": "#3d1200",
"--on-accent": "#0f0a00",
"--surface-dot": "#3d2e00",
"--scrollbar-track": "rgba(23, 16, 0, 0.5)",
"--scrollbar-thumb": "rgba(255, 176, 0, 0.25)",
"--scrollbar-thumb-hover": "rgba(255, 176, 0, 0.45)",
"--scanline-tint": "rgba(255, 176, 0, 0.03)",
"--accent-glow": "rgba(255, 176, 0, 0.12)",
"--accent-bg": "rgba(255, 176, 0, 0.12)",
"--modal-overlay": "rgba(0, 0, 0, 0.8)",
"--on-surface": "#fff3c4",
"--on-surface-variant": "#bfa06a",
"--agent-user-color": "#ffb000",
"--agent-agent-color": "#ffd257"
}
},
"glass": {
"name": "Glass",
"colorScheme": "light",
"appearance": {
"style": "soft",
"shape": "soft",
"density": "comfortable",
"font": "system",
"shadow": "elevated",
"motion": "reduced",
"blur": "strong",
"components": {
"button": "soft",
"input": "boxed",
"card": "elevated",
"tabs": "segmented"
}
},
"background": {
"type": "mesh",
"stops": [
"#d3e3f8",
"#e8edf5",
"#ece0f6"
],
"angle": 135,
"scrim": 0.35,
"animation": "drift"
},
"effects": {
"glow": 0.4
},
"typography": {
"fontScale": 1.05,
"radiusScale": 1.4
},
"terminal": {
"background": "#ffffff",
"foreground": "#1a2332",
"cursor": "#235cd8",
"cursorAccent": "#ffffff",
"selectionBackground": "#c4d8f7",
"selectionForeground": "#1a2332",
"selectionInactiveBackground": "#dde8f7",
"black": "#1a2332",
"red": "#c03528",
"green": "#1e7d3c",
"yellow": "#8a5a00",
"blue": "#235cd8",
"magenta": "#7c4dcc",
"cyan": "#0e6e86",
"white": "#56637a",
"brightBlack": "#56637a",
"brightRed": "#d9483b",
"brightGreen": "#2a944f",
"brightYellow": "#a86e10",
"brightBlue": "#3870e8",
"brightMagenta": "#8f5ce6",
"brightCyan": "#2a8ba3",
"brightWhite": "#0e1626"
},
"ui": {
"--bg": "#e8edf5",
"--bg-surface": "#f4f7fb",
"--bg-elevated": "#ffffff",
"--bg-terminal": "#ffffff",
"--text": "#1a2332",
"--text-muted": "#4d5a70",
"--text-dim": "#56637a",
"--accent": "#235cd8",
"--accent-secondary": "#3870e8",
"--accent-secondary-light": "#c4d8f7",
"--border": "#c9d4e3",
"--border-strong": "#a9b8cc",
"--error": "#c03528",
"--error-bg": "#f9e3e0",
"--on-accent": "#ffffff",
"--surface-dot": "#d5deea",
"--scrollbar-track": "rgba(201, 212, 227, 0.45)",
"--scrollbar-thumb": "rgba(77, 90, 112, 0.3)",
"--scrollbar-thumb-hover": "rgba(77, 90, 112, 0.5)",
"--scanline-tint": "transparent",
"--accent-glow": "rgba(35, 92, 216, 0.1)",
"--accent-bg": "rgba(35, 92, 216, 0.08)",
"--modal-overlay": "rgba(26, 35, 50, 0.35)",
"--on-surface": "#1a2332",
"--on-surface-variant": "#4d5a70",
"--agent-user-color": "#235cd8",
"--agent-agent-color": "#7c4dcc"
}
}
} /* THEME_PRESETS_END */;
@@ -3374,6 +3713,9 @@ let activePreset = 'cyberpunk';
let colorScheme = 'dark';
let themeName = 'Cyberpunk';
let appearance = {};
let background = null;
let effects = {};
let typography = null;
const THEME_MAX_BYTES = 64 * 1024;
const invalidColorProperties = new Set();
@@ -3384,6 +3726,7 @@ const APPEARANCE_FIELDS = [
{ key: 'font', labelKey: 'appearance.font', values: ['mono', 'system'] },
{ key: 'shadow', labelKey: 'appearance.shadow', values: ['none', 'subtle', 'elevated'] },
{ key: 'motion', labelKey: 'appearance.motion', values: ['none', 'reduced', 'full'] },
{ key: 'blur', labelKey: 'appearance.blur', values: ['none', 'subtle', 'strong'] },
];
const COMPONENT_FIELDS = [
@@ -3413,6 +3756,9 @@ function initTheme(presetName) {
...preset.appearance,
components: { ...preset.appearance.components },
};
background = preset.background ? structuredClone(preset.background) : null;
effects = { ...(preset.effects || {}) };
typography = preset.typography ? { ...preset.typography } : null;
renderControls();
applyTheme();
syncThemeSelectors(presetName);
@@ -3454,6 +3800,26 @@ function renderControls() {
))
.join('');
// V3:背景层 / 效果 / 版式面板
html += `<div class="section-title">${t('group.themeV3Background')}</div>`;
html += settingSelect('background.type', background?.type || 'solid', ['solid', 'linear', 'radial', 'mesh'], 'data-background="type"');
html += settingRange('background.angle', background?.angle ?? 160, 0, 360, 1, 'data-background="angle"');
html += settingRange('background.scrim', background?.scrim ?? 0.3, 0, 0.85, 0.01, 'data-background="scrim"');
html += settingSelect('background.animation', background?.animation || 'none', ['none', 'drift'], 'data-background="animation"');
for (let i = 0; i < 4; i++) {
html += settingInput(`background.stop${i + 1}`, background?.stops?.[i] || '', `data-background-stop="${i}"`);
}
html += `<div class="section-title">${t('group.themeV3Effects')}</div>`;
html += settingRange('effects.scanline', effects.scanline ?? 0, 0, 1, 0.05, 'data-effect="scanline"');
html += settingRange('effects.flicker', effects.flicker ?? 0, 0, 1, 0.05, 'data-effect="flicker"');
html += settingRange('effects.glow', effects.glow ?? 0, 0, 1, 0.05, 'data-effect="glow"');
html += settingRange('effects.noise', effects.noise ?? 0, 0, 1, 0.01, 'data-effect="noise"');
html += `<div class="section-title">${t('group.themeV3Typography')}</div>`;
html += settingRange('typography.fontScale', typography?.fontScale ?? 1, 0.85, 1.25, 0.01, 'data-typography="fontScale"');
html += settingRange('typography.radiusScale', typography?.radiusScale ?? 1, 0.5, 2, 0.05, 'data-typography="radiusScale"');
for (const group of VARIABLE_GROUPS) {
html += `<div class="section-title">${t(group.titleKey)}</div>`;
for (const varName of group.vars) {
@@ -3500,6 +3866,69 @@ function renderControls() {
});
});
// V3:背景层 / 效果 / 版式控件事件
container.querySelectorAll('[data-background]').forEach(control => {
control.addEventListener('input', (event) => {
const target = event.target;
const key = target.dataset.background;
background = normalizeBackgroundState(background);
if (key === 'angle' || key === 'scrim') {
background[key] = Number(target.value);
} else {
background[key] = target.value;
}
markThemeCustomized();
applyTheme();
});
});
container.querySelectorAll('[data-background-stop]').forEach(input => {
input.addEventListener('input', (event) => {
const target = event.target;
const index = Number(target.dataset.backgroundStop);
background = normalizeBackgroundState(background);
const stops = [...(background.stops || [])];
const value = target.value.trim();
if (value === '') {
delete stops[index];
} else if (isSafeColor(value)) {
stops[index] = value;
target.setAttribute('aria-invalid', 'false');
} else {
target.setAttribute('aria-invalid', 'true');
}
background.stops = stops.filter(stop => stop !== undefined);
markThemeCustomized();
applyTheme();
});
});
container.querySelectorAll('[data-effect]').forEach(input => {
input.addEventListener('input', (event) => {
const key = event.target.dataset.effect;
const value = Number(event.target.value);
if (value > 0) effects[key] = value;
else delete effects[key];
markThemeCustomized();
applyTheme();
});
});
container.querySelectorAll('[data-typography]').forEach(input => {
input.addEventListener('input', (event) => {
const key = event.target.dataset.typography;
const value = Number(event.target.value);
typography = {
fontScale: typography?.fontScale ?? 1,
radiusScale: typography?.radiusScale ?? 1,
[key]: value,
};
if (typography.fontScale === 1 && typography.radiusScale === 1) typography = null;
markThemeCustomized();
applyTheme();
});
});
container.querySelectorAll('input[type="color"]').forEach(input => {
input.addEventListener('input', (e) => {
const varName = e.target.dataset.var;
@@ -3566,6 +3995,23 @@ function settingSelect(labelKey, value, values, attribute) {
+ `<select ${attribute} aria-label="${escapeAttribute(t(labelKey))}">${options}</select></div>`;
}
function settingRange(labelKey, value, min, max, step, attribute) {
return `<div class="setting-row"><label>${t(labelKey)}</label>`
+ `<input type="range" min="${min}" max="${max}" step="${step}" value="${value}" ${attribute} aria-label="${escapeAttribute(t(labelKey))}">`
+ `<span class="range-value">${value}</span></div>`;
}
function normalizeBackgroundState(current) {
if (current) return current;
return {
type: 'linear',
stops: ['#0a0a0a'],
angle: 160,
scrim: 0.3,
animation: 'none',
};
}
function applyTheme() {
const scope = document.getElementById('theme-scope');
scope.style.colorScheme = colorScheme;
@@ -3576,6 +4022,7 @@ function applyTheme() {
scope.dataset.uiFont = appearance.font;
scope.dataset.uiShadow = appearance.shadow;
scope.dataset.uiMotion = appearance.motion;
scope.dataset.uiBlur = appearance.blur;
scope.dataset.componentButton = appearance.components.button;
scope.dataset.componentInput = appearance.components.input;
scope.dataset.componentCard = appearance.components.card;
@@ -3583,6 +4030,40 @@ function applyTheme() {
for (const [varName, val] of Object.entries(theme)) {
scope.style.setProperty(varName, val);
}
// V3:背景栈(含读性遮罩)与效果开关(与应用同构)
if (background && background.type !== 'solid' && (background.stops || []).length >= 2 && background.stops.every(isSafeColor)) {
const channel = colorScheme === 'dark' ? '0, 0, 0' : '255, 255, 255';
const scrimAlpha = background.scrim ?? 0.3;
const scrim = `linear-gradient(rgba(${channel}, ${scrimAlpha}), rgba(${channel}, ${scrimAlpha}))`;
let gradient;
if (background.type === 'linear') {
gradient = `linear-gradient(${background.angle ?? 160}deg, ${background.stops.join(', ')})`;
} else if (background.type === 'radial') {
gradient = `radial-gradient(ellipse at 50% 25%, ${background.stops.join(', ')})`;
} else {
const [a, b, c] = background.stops;
gradient = [
`radial-gradient(at 18% 22%, ${a} 0px, transparent 55%)`,
`radial-gradient(at 82% 28%, ${b || a} 0px, transparent 50%)`,
`radial-gradient(at 50% 88%, ${c || b || a} 0px, transparent 60%)`,
].join(', ');
}
scope.style.setProperty('--app-bg-stack', `${scrim}, ${gradient}`);
scope.dataset.bgAnimation = background.animation === 'drift' ? 'drift' : 'none';
} else {
scope.style.setProperty('--app-bg-stack', 'none');
scope.dataset.bgAnimation = 'none';
}
scope.dataset.fxScanline = effects.scanline ? 'on' : 'off';
scope.dataset.fxFlicker = effects.flicker ? 'on' : 'off';
scope.dataset.fxGlow = effects.glow ? 'on' : 'off';
scope.dataset.fxNoise = effects.noise ? 'on' : 'off';
scope.style.setProperty('--fx-scanline-opacity', String(effects.scanline ?? 1));
scope.style.setProperty('--fx-flicker-speed', `${0.32 - 0.2 * (effects.flicker ?? 1)}s`);
scope.style.setProperty('--fx-glow-strength', String(effects.glow ?? 0.6));
scope.style.setProperty('--fx-noise-opacity', String(effects.noise ?? 0.05));
scope.style.setProperty('--radius-scale', String(typography?.radiusScale ?? 1));
scope.style.setProperty('--type-scale', String(typography?.fontScale ?? 1));
}
// Preset selector
@@ -3633,6 +4114,11 @@ document.getElementById('import-input').addEventListener('change', (e) => {
? data.name.trim().slice(0, 80)
: 'Custom';
appearance = mergeAppearance(fallbackPreset.appearance, importedAppearance);
background = sanitizeBackground(data.background, importedScheme)
|| structuredClone(fallbackPreset.background || null);
effects = { ...(fallbackPreset.effects || {}), ...(sanitizeEffects(data.effects) || {}) };
typography = sanitizeTypography(data.typography)
|| (fallbackPreset.typography ? { ...fallbackPreset.typography } : null);
activePreset = requestedBase;
invalidColorProperties.clear();
syncThemeSelectors('custom');
@@ -3660,7 +4146,7 @@ document.getElementById('btn-export').addEventListener('click', () => {
Object.keys(PRESETS['standard-dark'].terminal),
);
const output = {
schemaVersion: 2,
schemaVersion: 3,
name: themeName.trim() || 'Custom',
baseTheme: activePreset || (colorScheme === 'light' ? 'standard-light' : 'cyberpunk'),
colorScheme,
@@ -3678,6 +4164,12 @@ document.getElementById('btn-export').addEventListener('click', () => {
},
ui: safeUiTheme,
};
const safeBackground = sanitizeBackground(background, colorScheme);
if (safeBackground) output.background = safeBackground;
const safeEffects = sanitizeEffects(effects);
if (safeEffects) output.effects = safeEffects;
const safeTypography = sanitizeTypography(typography);
if (safeTypography) output.typography = safeTypography;
const json = JSON.stringify(output, null, 2);
const blob = new Blob([json], { type: 'application/json' });
@@ -3730,6 +4222,38 @@ function sanitizeAppearance(value) {
return Object.keys(result).length > 1 || Object.keys(result.components).length ? result : null;
}
function sanitizeBackground(value, scheme) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const stops = Array.isArray(value.stops)
? value.stops.filter(s => typeof s === 'string' && isSafeColor(s)).slice(0, 5)
: [];
if (stops.length === 0) return null;
const type = ['solid', 'linear', 'radial', 'mesh'].includes(value.type) ? value.type : 'linear';
const animation = value.animation === 'drift' ? 'drift' : 'none';
const angle = Math.min(360, Math.max(0, Number(value.angle) || 160));
let scrim = Math.min(0.85, Math.max(0, Number(value.scrim) || 0));
if (type !== 'solid') scrim = Math.max(scrim, scheme === 'light' ? 0.35 : 0.25);
return { type, stops, angle, scrim, animation };
}
function sanitizeEffects(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
const result = {};
for (const name of ['scanline', 'flicker', 'glow', 'noise']) {
const raw = Number(value[name]);
if (Number.isFinite(raw) && raw > 0) result[name] = Math.min(1, raw);
}
return Object.keys(result).length ? result : undefined;
}
function sanitizeTypography(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) return null;
const fontScale = Math.min(1.25, Math.max(0.85, Number(value.fontScale) || 1));
const radiusScale = Math.min(2, Math.max(0.5, Number(value.radiusScale) || 1));
if (fontScale === 1 && radiusScale === 1) return null;
return { fontScale, radiusScale };
}
function mergeAppearance(fallback, imported) {
return {
...fallback,
+9 -3
View File
@@ -124,8 +124,10 @@
<option value="standard-dark">Standard Dark</option>
<option value="standard-light">Standard Light</option>
<option value="cyberpunk">Cyberpunk</option>
<option value="glacier">Glacier · Soft</option>
<option value="apple">Apple · Soft</option>
<option value="gruvbox">Gruvbox · Dense</option>
<option value="crt">CRT Amber</option>
<option value="glass">Glass · Soft</option>
</select>
<button
data-theme-import
@@ -727,8 +729,10 @@
<option value="standard-dark">Standard Dark</option>
<option value="standard-light">Standard Light</option>
<option value="cyberpunk">Cyberpunk</option>
<option value="glacier">Glacier · Soft</option>
<option value="apple">Apple · Soft</option>
<option value="gruvbox">Gruvbox · Dense</option>
<option value="crt">CRT Amber</option>
<option value="glass">Glass · Soft</option>
</select>
<button
id="import-theme-btn"
@@ -851,8 +855,10 @@
<option value="standard-dark">Standard Dark</option>
<option value="standard-light">Standard Light</option>
<option value="cyberpunk">Cyberpunk</option>
<option value="glacier">Glacier · Soft</option>
<option value="apple">Apple · Soft</option>
<option value="gruvbox">Gruvbox · Dense</option>
<option value="crt">CRT Amber</option>
<option value="glass">Glass · Soft</option>
</select>
</label>
<button id="mobile-search-btn" type="button">
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cloudssh-frontend",
"version": "1.12.2",
"version": "1.13.0",
"type": "module",
"scripts": {
"dev": "vite",
+8
View File
@@ -566,6 +566,14 @@ function restoreTheme(): void {
const selection = localStorage.getItem('cloudssh_theme_selection');
localStorage.removeItem('cloudssh_theme');
// glacier 内置主题已被 Apple 主题取代:旧选择一次性迁移到同为深色的 Standard Dark
if (selection === 'glacier') {
localStorage.setItem('cloudssh_theme_selection', 'standard-dark');
applyBuiltInTheme('standard-dark');
syncThemeSelectors('standard-dark');
return;
}
if (isBuiltInTheme(selection)) {
applyBuiltInTheme(selection);
syncThemeSelectors(selection);
+93 -16
View File
@@ -77,28 +77,28 @@
}
html[data-ui-shape="square"] {
--control-radius: 2px;
--card-radius: 0px;
--modal-radius: 0px;
--control-radius: calc(2px * var(--radius-scale, 1));
--card-radius: calc(0px * var(--radius-scale, 1));
--modal-radius: calc(0px * var(--radius-scale, 1));
--terminal-frame-gap: 4px;
}
html[data-ui-shape="rounded"] {
--control-radius: 6px;
--card-radius: 9px;
--modal-radius: 12px;
--control-radius: calc(6px * var(--radius-scale, 1));
--card-radius: calc(9px * var(--radius-scale, 1));
--modal-radius: calc(12px * var(--radius-scale, 1));
--terminal-frame-gap: 7px;
}
html[data-ui-shape="soft"] {
--control-radius: 10px;
--card-radius: 15px;
--modal-radius: 18px;
--control-radius: calc(10px * var(--radius-scale, 1));
--card-radius: calc(15px * var(--radius-scale, 1));
--modal-radius: calc(18px * var(--radius-scale, 1));
--terminal-frame-gap: 10px;
}
html[data-ui-density="compact"] {
--font-size-scale: 0.94;
--font-size-scale: calc(0.94 * var(--type-scale, 1));
--space-scale: 0.84;
--control-padding-x: 0.62rem;
--control-padding-y: 0.36rem;
@@ -108,7 +108,7 @@ html[data-ui-density="compact"] {
}
html[data-ui-density="comfortable"] {
--font-size-scale: 1;
--font-size-scale: calc(1 * var(--type-scale, 1));
--space-scale: 1;
--control-padding-x: 0.78rem;
--control-padding-y: 0.5rem;
@@ -118,7 +118,7 @@ html[data-ui-density="comfortable"] {
}
html[data-ui-density="spacious"] {
--font-size-scale: 1.04;
--font-size-scale: calc(1.04 * var(--type-scale, 1));
--space-scale: 1.12;
--control-padding-x: 0.92rem;
--control-padding-y: 0.62rem;
@@ -156,6 +156,19 @@ html[data-ui-shadow="elevated"] {
--surface-blur: 10px;
}
/* V3:表面模糊独立档位,覆盖 shadow 预设派生值(后置规则同优先级胜出) */
html[data-ui-blur='none'] {
--surface-blur: 0px;
}
html[data-ui-blur='subtle'] {
--surface-blur: 6px;
}
html[data-ui-blur='strong'] {
--surface-blur: 16px;
}
html[data-ui-motion="none"] {
--motion-fast: 0ms;
--motion-normal: 0ms;
@@ -184,6 +197,65 @@ body {
min-height: 100vh;
}
/* ==================== Theme V3:背景层 / 效果 / 版式缩放 ==================== */
/* 背景层:固定全屏伪元素承载渐变栈;--app-bg-stack 为 none 时与 V2 纯色完全一致 */
body::before {
content: '';
position: fixed;
inset: 0;
z-index: -1;
pointer-events: none;
background-image: var(--app-bg-stack, none);
}
/* 环境背景漂移:主题显式声明 drift 时启用;motion=none 与系统级减少动态时停止 */
html[data-bg-animation='drift'] body::before {
background-size: 200% 200%;
animation: theme-bg-drift 40s ease-in-out infinite alternate;
}
html[data-ui-motion='none'] body::before {
animation: none;
}
@media (prefers-reduced-motion: reduce) {
html[data-bg-animation='drift'] body::before {
animation: none;
}
}
@keyframes theme-bg-drift {
0% {
background-position: 0% 0%;
}
100% {
background-position: 100% 100%;
}
}
/* 噪点:内联 feTurbulence 纹理(静态资源,非主题数据),强度驱动透明度 */
html[data-fx-noise='on'] body::after {
content: '';
position: fixed;
inset: 0;
z-index: -1;
pointer-events: none;
opacity: var(--fx-noise-opacity, 0.05);
background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.9' numOctaves='2' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
}
/* 辉光:效果开启时卡片/按钮静止态即带强调辉光(hover 态全主题通用不变) */
html[data-fx-glow='on'] .server-card {
box-shadow:
var(--shadow-card),
0 4px calc(24px * var(--fx-glow-strength, 0.6)) var(--accent-glow);
}
html[data-fx-glow='on'] .cyber-button {
box-shadow: 0 0 calc(12px * var(--fx-glow-strength, 0.6)) var(--accent-glow);
}
.language-toggle {
display: inline-flex;
align-items: center;
@@ -298,12 +370,17 @@ body.terminal-active {
cursor: crosshair;
}
html:not([data-ui-style="cyberpunk"]) .scanlines,
html:not([data-ui-style="cyberpunk"]) .scanline {
/* V3 效果注册表:扫描线/闪烁按 fx 开关门控(取代旧的 style=cyberpunk 硬编码) */
html:not([data-fx-scanline='on']) .scanlines,
html:not([data-fx-scanline='on']) .scanline {
display: none;
}
html:not([data-ui-style="cyberpunk"]) .flicker {
html[data-fx-scanline='on'] .scanlines {
opacity: var(--fx-scanline-opacity, 1);
}
html:not([data-fx-flicker='on']) .flicker {
animation: none;
display: none;
}
@@ -352,7 +429,7 @@ html:not([data-ui-style="cyberpunk"]) .flicker {
}
.flicker {
animation: flicker 0.15s infinite;
animation: flicker var(--fx-flicker-speed, 0.15s) infinite;
pointer-events: none;
position: fixed;
top: 0;
+303 -44
View File
@@ -4,9 +4,11 @@ import {
type ColorScheme,
type NormalizedThemeData,
normalizeThemeData,
THEME_MAX_BYTES,
THEME_SCHEMA_VERSION,
type ThemeBackground,
type ThemeEffects,
type ThemeTypography,
type ThemeAppearance,
type ThemeBlur,
type ThemeComponentStyles,
type ThemeDensity,
type ThemeFont,
@@ -19,9 +21,13 @@ import {
export {
type BuiltInThemeName,
type ColorScheme,
type ThemeBackground,
type ThemeEffects,
type ThemeTypography,
THEME_MAX_BYTES,
THEME_SCHEMA_VERSION,
type ThemeAppearance,
type ThemeBlur,
type ThemeComponentStyles,
type ThemeDensity,
type ThemeFont,
@@ -38,6 +44,7 @@ export interface ResolvedThemeAppearance {
font: ThemeFont;
shadow: ThemeShadow;
motion: ThemeMotion;
blur: ThemeBlur;
components: ThemeComponentStyles;
}
@@ -58,6 +65,7 @@ export const UI_STYLE_PRESETS: Record<UIStylePresetName, ResolvedThemeAppearance
font: 'system',
shadow: 'subtle',
motion: 'reduced',
blur: 'subtle',
components: {
button: 'solid',
input: 'boxed',
@@ -72,6 +80,7 @@ export const UI_STYLE_PRESETS: Record<UIStylePresetName, ResolvedThemeAppearance
font: 'mono',
shadow: 'none',
motion: 'full',
blur: 'none',
components: {
button: 'outline',
input: 'underline',
@@ -86,6 +95,7 @@ export const UI_STYLE_PRESETS: Record<UIStylePresetName, ResolvedThemeAppearance
font: 'system',
shadow: 'elevated',
motion: 'reduced',
blur: 'strong',
components: {
button: 'soft',
input: 'boxed',
@@ -100,6 +110,7 @@ export const UI_STYLE_PRESETS: Record<UIStylePresetName, ResolvedThemeAppearance
font: 'mono',
shadow: 'none',
motion: 'reduced',
blur: 'none',
components: {
button: 'outline',
input: 'boxed',
@@ -166,12 +177,30 @@ export const THEMES = {
cursorAccent: '#0a0a0a',
selectionBackground: '#273747',
},
glacier: {
background: '#0a192f',
foreground: '#64ffda',
cursor: '#e6f1ff',
cursorAccent: '#0a192f',
selectionBackground: '#112240',
apple: {
background: '#ffffff',
foreground: '#1d1d1f',
cursor: '#0066da',
cursorAccent: '#ffffff',
selectionBackground: '#b3d7ff',
selectionForeground: '#1d1d1f',
selectionInactiveBackground: '#dde8f7',
black: '#1d1d1f',
red: '#d70015',
green: '#248a3d',
yellow: '#b25000',
blue: '#0040dd',
magenta: '#8944ab',
cyan: '#0b7285',
white: '#8e8e93',
brightBlack: '#6e6e73',
brightRed: '#ff3b30',
brightGreen: '#34c759',
brightYellow: '#c93400',
brightBlue: '#0071e3',
brightMagenta: '#af52de',
brightCyan: '#30b0c7',
brightWhite: '#1d1d1f',
},
gruvbox: {
background: '#282828',
@@ -180,6 +209,56 @@ export const THEMES = {
cursorAccent: '#282828',
selectionBackground: '#504945',
},
crt: {
background: '#0f0a00',
foreground: '#ffb000',
cursor: '#ffd257',
cursorAccent: '#0f0a00',
selectionBackground: '#3d2e00',
selectionForeground: '#ffb000',
selectionInactiveBackground: '#2a2000',
black: '#241a00',
red: '#ff6b4a',
green: '#d4a017',
yellow: '#ffb000',
blue: '#f0c040',
magenta: '#e08e39',
cyan: '#c8b04a',
white: '#d9c08a',
brightBlack: '#8a7440',
brightRed: '#ffa080',
brightGreen: '#ffd257',
brightYellow: '#ffe08a',
brightBlue: '#ffe8b0',
brightMagenta: '#ffc27a',
brightCyan: '#e8d89a',
brightWhite: '#fff3c4',
},
glass: {
background: '#ffffff',
foreground: '#1a2332',
cursor: '#235cd8',
cursorAccent: '#ffffff',
selectionBackground: '#c4d8f7',
selectionForeground: '#1a2332',
selectionInactiveBackground: '#dde8f7',
black: '#1a2332',
red: '#c03528',
green: '#1e7d3c',
yellow: '#8a5a00',
blue: '#235cd8',
magenta: '#7c4dcc',
cyan: '#0e6e86',
white: '#56637a',
brightBlack: '#56637a',
brightRed: '#d9483b',
brightGreen: '#2a944f',
brightYellow: '#a86e10',
brightBlue: '#3870e8',
brightMagenta: '#8f5ce6',
brightCyan: '#2a8ba3',
brightWhite: '#0e1626',
},
} satisfies Record<string, ITheme>;
export const UI_THEMES: Record<BuiltInThemeName, Record<string, string>> = {
@@ -270,34 +349,34 @@ export const UI_THEMES: Record<BuiltInThemeName, Record<string, string>> = {
'--agent-user-color': '#4af626',
'--agent-agent-color': '#14d1ff',
},
glacier: {
'--bg': '#0a192f',
'--bg-surface': '#0d2137',
'--bg-elevated': '#112240',
'--bg-terminal': '#061526',
'--text': '#64ffda',
'--text-muted': '#8892b0',
'--text-dim': '#495670',
'--accent': '#64ffda',
'--accent-secondary': '#e6f1ff',
'--accent-secondary-light': '#ccd6f6',
'--border': '#1d3557',
'--border-strong': '#495670',
'--error': '#ff6b6b',
'--error-bg': '#3d0000',
'--on-accent': '#0a192f',
'--surface-dot': '#1d3557',
'--scrollbar-track': 'rgba(10, 25, 47, 0.5)',
'--scrollbar-thumb': 'rgba(100, 255, 218, 0.2)',
'--scrollbar-thumb-hover': 'rgba(100, 255, 218, 0.4)',
'--scanline-tint': 'rgba(100, 255, 218, 0.02)',
'--accent-glow': 'rgba(100, 255, 218, 0.08)',
'--accent-bg': 'rgba(100, 255, 218, 0.1)',
'--modal-overlay': 'rgba(0, 0, 0, 0.85)',
'--on-surface': '#e6f1ff',
'--on-surface-variant': '#8892b0',
'--agent-user-color': '#64ffda',
'--agent-agent-color': '#e6f1ff',
apple: {
'--bg': '#f5f5f7',
'--bg-surface': '#ffffff',
'--bg-elevated': '#ffffff',
'--bg-terminal': '#ffffff',
'--text': '#1d1d1f',
'--text-muted': '#636368',
'--text-dim': '#6e6e73',
'--accent': '#0066da',
'--accent-secondary': '#0052b4',
'--accent-secondary-light': '#cce4ff',
'--border': '#d2d2d7',
'--border-strong': '#aeaeb2',
'--error': '#d70015',
'--error-bg': '#ffebe9',
'--on-accent': '#ffffff',
'--surface-dot': '#e8e8ed',
'--scrollbar-track': 'rgba(210, 210, 215, 0.45)',
'--scrollbar-thumb': 'rgba(99, 99, 104, 0.35)',
'--scrollbar-thumb-hover': 'rgba(99, 99, 104, 0.55)',
'--scanline-tint': 'transparent',
'--accent-glow': 'rgba(0, 102, 218, 0.08)',
'--accent-bg': 'rgba(0, 102, 218, 0.1)',
'--modal-overlay': 'rgba(0, 0, 0, 0.32)',
'--on-surface': '#1d1d1f',
'--on-surface-variant': '#636368',
'--agent-user-color': '#0066da',
'--agent-agent-color': '#5856d6',
},
gruvbox: {
'--bg': '#282828',
@@ -328,22 +407,122 @@ export const UI_THEMES: Record<BuiltInThemeName, Record<string, string>> = {
'--agent-user-color': '#b8bb26',
'--agent-agent-color': '#83a598',
},
crt: {
'--bg': '#0f0a00',
'--bg-surface': '#171000',
'--bg-elevated': '#1d1600',
'--bg-terminal': '#0f0a00',
'--text': '#ffb000',
'--text-muted': '#bfa06a',
'--text-dim': '#937c46',
'--accent': '#ffb000',
'--accent-secondary': '#ffd257',
'--accent-secondary-light': '#ffe08a',
'--border': '#3d2e00',
'--border-strong': '#5c470a',
'--error': '#ff6b4a',
'--error-bg': '#3d1200',
'--on-accent': '#0f0a00',
'--surface-dot': '#3d2e00',
'--scrollbar-track': 'rgba(23, 16, 0, 0.5)',
'--scrollbar-thumb': 'rgba(255, 176, 0, 0.25)',
'--scrollbar-thumb-hover': 'rgba(255, 176, 0, 0.45)',
'--scanline-tint': 'rgba(255, 176, 0, 0.03)',
'--accent-glow': 'rgba(255, 176, 0, 0.12)',
'--accent-bg': 'rgba(255, 176, 0, 0.12)',
'--modal-overlay': 'rgba(0, 0, 0, 0.8)',
'--on-surface': '#fff3c4',
'--on-surface-variant': '#bfa06a',
'--agent-user-color': '#ffb000',
'--agent-agent-color': '#ffd257',
},
glass: {
'--bg': '#e8edf5',
'--bg-surface': '#f4f7fb',
'--bg-elevated': '#ffffff',
'--bg-terminal': '#ffffff',
'--text': '#1a2332',
'--text-muted': '#4d5a70',
'--text-dim': '#56637a',
'--accent': '#235cd8',
'--accent-secondary': '#3870e8',
'--accent-secondary-light': '#c4d8f7',
'--border': '#c9d4e3',
'--border-strong': '#a9b8cc',
'--error': '#c03528',
'--error-bg': '#f9e3e0',
'--on-accent': '#ffffff',
'--surface-dot': '#d5deea',
'--scrollbar-track': 'rgba(201, 212, 227, 0.45)',
'--scrollbar-thumb': 'rgba(77, 90, 112, 0.3)',
'--scrollbar-thumb-hover': 'rgba(77, 90, 112, 0.5)',
'--scanline-tint': 'transparent',
'--accent-glow': 'rgba(35, 92, 216, 0.1)',
'--accent-bg': 'rgba(35, 92, 216, 0.08)',
'--modal-overlay': 'rgba(26, 35, 50, 0.35)',
'--on-surface': '#1a2332',
'--on-surface-variant': '#4d5a70',
'--agent-user-color': '#235cd8',
'--agent-agent-color': '#7c4dcc',
},
};
export const BUILT_IN_APPEARANCE: Record<BuiltInThemeName, ThemeAppearance> = {
'standard-dark': { style: 'standard' },
'standard-light': { style: 'standard' },
cyberpunk: { style: 'cyberpunk' },
glacier: { style: 'soft' },
apple: { style: 'soft' },
gruvbox: { style: 'dense' },
crt: { style: 'cyberpunk' },
glass: { style: 'soft', blur: 'strong' },
};
const COLOR_SCHEMES: Record<BuiltInThemeName, ColorScheme> = {
'standard-dark': 'dark',
'standard-light': 'light',
cyberpunk: 'dark',
glacier: 'dark',
apple: 'light',
gruvbox: 'dark',
crt: 'dark',
glass: 'light',
};
/** V3 内置主题的背景层配置(未列出的主题保持纯色背景) */
export const BUILT_IN_BACKGROUND: Partial<Record<BuiltInThemeName, ThemeBackground>> = {
cyberpunk: {
type: 'linear',
stops: ['#0a0a0a', '#11170c'],
angle: 165,
scrim: 0.3,
animation: 'none',
},
crt: {
type: 'radial',
stops: ['#261b00', '#0f0a00'],
angle: 160,
scrim: 0.3,
animation: 'none',
},
glass: {
type: 'mesh',
stops: ['#d3e3f8', '#e8edf5', '#ece0f6'],
angle: 135,
scrim: 0.35,
animation: 'drift',
},
};
/** V3 内置主题的效果配置(键存在且 >0 即启用) */
export const BUILT_IN_EFFECTS: Partial<Record<BuiltInThemeName, ThemeEffects>> = {
cyberpunk: { scanline: 1, flicker: 1 },
crt: { scanline: 1, flicker: 0.6, glow: 0.5 },
glass: { glow: 0.4 },
};
/** V3 内置主题的版式缩放(缺省 1/1) */
export const BUILT_IN_TYPOGRAPHY: Partial<Record<BuiltInThemeName, ThemeTypography>> = {
crt: { fontScale: 1, radiusScale: 0.75 },
glass: { fontScale: 1.05, radiusScale: 1.4 },
};
let activeTerminalTheme: ITheme = THEMES.cyberpunk;
@@ -362,7 +541,10 @@ export function applyBuiltInTheme(themeName: BuiltInThemeName): void {
THEMES[themeName],
COLOR_SCHEMES[themeName],
themeName,
resolveThemeAppearance(BUILT_IN_APPEARANCE[themeName])
resolveThemeAppearance(BUILT_IN_APPEARANCE[themeName]),
BUILT_IN_BACKGROUND[themeName],
BUILT_IN_EFFECTS[themeName],
BUILT_IN_TYPOGRAPHY[themeName]
);
}
@@ -376,7 +558,10 @@ export function applyImportedTheme(data: ImportedThemeData): void {
const terminal = { ...THEMES[fallbackName], ...normalized.terminal };
const fallbackAppearance = resolveThemeAppearance(BUILT_IN_APPEARANCE[fallbackName]);
const appearance = resolveThemeAppearance(normalized.appearance, fallbackAppearance);
applyTheme(ui, terminal, colorScheme, 'custom', appearance);
const background = normalized.background ?? BUILT_IN_BACKGROUND[fallbackName];
const effects = { ...BUILT_IN_EFFECTS[fallbackName], ...normalized.effects };
const typography = normalized.typography ?? BUILT_IN_TYPOGRAPHY[fallbackName];
applyTheme(ui, terminal, colorScheme, 'custom', appearance, background, effects, typography);
}
export function normalizeImportedTheme(data: unknown): ImportedThemeData | null {
@@ -412,7 +597,10 @@ function applyTheme(
terminal: ITheme,
colorScheme: ColorScheme,
themeName: BuiltInThemeName | 'custom',
appearance: ResolvedThemeAppearance
appearance: ResolvedThemeAppearance,
background?: ThemeBackground,
effects?: ThemeEffects,
typography?: ThemeTypography
): void {
activeTerminalTheme = terminal;
activeColorScheme = colorScheme;
@@ -420,7 +608,9 @@ function applyTheme(
if (typeof document !== 'undefined') {
const root = document.documentElement;
Object.entries(ui).forEach(([property, value]) => root.style.setProperty(property, value));
Object.entries(ui).forEach(([property, value]) => {
root.style.setProperty(property, value);
});
root.dataset.theme = themeName;
root.dataset.colorScheme = colorScheme;
root.dataset.uiStyle = appearance.style;
@@ -429,16 +619,82 @@ function applyTheme(
root.dataset.uiFont = appearance.font;
root.dataset.uiShadow = appearance.shadow;
root.dataset.uiMotion = appearance.motion;
root.dataset.uiBlur = appearance.blur;
root.dataset.componentButton = appearance.components.button;
root.dataset.componentInput = appearance.components.input;
root.dataset.componentCard = appearance.components.card;
root.dataset.componentTabs = appearance.components.tabs;
root.style.colorScheme = colorScheme;
root.classList.toggle('dark', colorScheme === 'dark');
applyThemeV3Layers(root, background, effects, typography, colorScheme);
}
terminalThemeListeners.forEach((listener) => listener(terminal));
colorSchemeListeners.forEach((listener) => listener(colorScheme));
terminalThemeListeners.forEach((listener) => {
listener(terminal);
});
colorSchemeListeners.forEach((listener) => {
listener(colorScheme);
});
}
/** V3 增量层:背景/效果/版式缩放全部走变量与 data 属性,不碰 DOM 结构 */
function applyThemeV3Layers(
root: HTMLElement,
background: ThemeBackground | undefined,
effects: ThemeEffects | undefined,
typography: ThemeTypography | undefined,
colorScheme: ColorScheme
): void {
root.style.setProperty('--app-bg-stack', resolveBackgroundStack(background, colorScheme));
root.dataset.bgAnimation =
background && background.animation === 'drift' && background.type !== 'solid'
? 'drift'
: 'none';
root.dataset.fxScanline = effects?.scanline ? 'on' : 'off';
root.dataset.fxFlicker = effects?.flicker ? 'on' : 'off';
root.dataset.fxGlow = effects?.glow ? 'on' : 'off';
root.dataset.fxNoise = effects?.noise ? 'on' : 'off';
root.style.setProperty('--fx-scanline-opacity', String(effects?.scanline ?? 1));
// 闪烁频率随强度在 0.32s–0.12s 之间收紧
root.style.setProperty('--fx-flicker-speed', `${0.32 - 0.2 * (effects?.flicker ?? 1)}s`);
root.style.setProperty('--fx-glow-strength', String(effects?.glow ?? 0.6));
root.style.setProperty('--fx-noise-opacity', String(effects?.noise ?? 0.05));
root.style.setProperty('--radius-scale', String(typography?.radiusScale ?? 1));
root.style.setProperty('--type-scale', String(typography?.fontScale ?? 1));
}
/** 合成含读性遮罩的完整背景栈;无渐变时为 none,body 的 --bg 纯色兜底 */
function resolveBackgroundStack(
background: ThemeBackground | undefined,
colorScheme: ColorScheme
): string {
if (!background || background.type === 'solid' || background.stops.length < 2) return 'none';
const channel = colorScheme === 'dark' ? '0, 0, 0' : '255, 255, 255';
const scrim = `linear-gradient(rgba(${channel}, ${background.scrim}), rgba(${channel}, ${background.scrim}))`;
return `${scrim}, ${resolveBackgroundCss(background)}`;
}
/** 由 schema 背景配置合成 CSS 渐变串(停靠点均已过白名单校验,拼接安全) */
export function resolveBackgroundCss(background: ThemeBackground | undefined): string {
if (!background || background.type === 'solid' || background.stops.length < 2) {
return 'var(--bg)';
}
switch (background.type) {
case 'linear':
return `linear-gradient(${background.angle}deg, ${background.stops.join(', ')})`;
case 'radial':
return `radial-gradient(ellipse at 50% 25%, ${background.stops.join(', ')})`;
case 'mesh': {
const [first, second, third] = background.stops;
return [
`radial-gradient(at 18% 22%, ${first} 0px, transparent 55%)`,
`radial-gradient(at 82% 28%, ${second ?? first} 0px, transparent 50%)`,
`radial-gradient(at 50% 88%, ${third ?? second ?? first} 0px, transparent 60%)`,
].join(', ');
}
}
}
export function resolveThemeAppearance(
@@ -463,6 +719,9 @@ export function resolveThemeAppearance(
motion: isOneOf(appearance?.motion, ['none', 'reduced', 'full'])
? appearance.motion
: preset.motion,
blur: isOneOf(appearance?.blur, ['none', 'subtle', 'strong'])
? appearance.blur
: preset.blur,
components: {
button: isOneOf(appearance?.components?.button, ['outline', 'solid', 'soft'])
? appearance.components.button
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "cloudssh",
"version": "1.12.2",
"version": "1.13.0",
"packageManager": "pnpm@11.8.0",
"description": "纯 Cloudflare 架构 Web SSH 工具",
"main": "src/worker/index.ts",
+11 -1
View File
@@ -13,12 +13,17 @@ const uiThemes = readObjectLiteral(themeSource, 'export const UI_THEMES:');
const stylePresets = readObjectLiteral(themeSource, 'export const UI_STYLE_PRESETS:');
const builtInAppearances = readObjectLiteral(themeSource, 'export const BUILT_IN_APPEARANCE:');
const colorSchemes = readObjectLiteral(themeSource, 'const COLOR_SCHEMES:');
const builtInBackgrounds = readObjectLiteral(themeSource, 'export const BUILT_IN_BACKGROUND:');
const builtInEffects = readObjectLiteral(themeSource, 'export const BUILT_IN_EFFECTS:');
const builtInTypography = readObjectLiteral(themeSource, 'export const BUILT_IN_TYPOGRAPHY:');
const labels = {
'standard-dark': 'Standard Dark',
'standard-light': 'Standard Light',
cyberpunk: 'Cyberpunk',
glacier: 'Glacier',
apple: 'Apple',
gruvbox: 'Gruvbox',
crt: 'CRT Amber',
glass: 'Glass',
};
const presets = Object.fromEntries(
@@ -39,6 +44,11 @@ const presets = Object.fromEntries(
...(appearance.components || {}),
},
},
...(builtInBackgrounds[themeName] ? { background: builtInBackgrounds[themeName] } : {}),
...(Object.keys(builtInEffects[themeName] || {}).length
? { effects: builtInEffects[themeName] }
: {}),
...(builtInTypography[themeName] ? { typography: builtInTypography[themeName] } : {}),
terminal: terminalThemes[themeName],
ui: uiThemes[themeName],
},
+116 -7
View File
@@ -1,12 +1,14 @@
export const THEME_SCHEMA_VERSION = 2;
export const THEME_SCHEMA_VERSION = 3;
export const THEME_MAX_BYTES = 64 * 1024;
export const BUILT_IN_THEME_NAMES = [
'standard-dark',
'standard-light',
'cyberpunk',
'glacier',
'apple',
'gruvbox',
'crt',
'glass',
] as const;
export const SAFE_UI_THEME_PROPERTIES = [
@@ -71,10 +73,17 @@ const THEME_DENSITIES = ['compact', 'comfortable', 'spacious'] as const;
const THEME_FONTS = ['mono', 'system'] as const;
const THEME_SHADOWS = ['none', 'subtle', 'elevated'] as const;
const THEME_MOTIONS = ['none', 'reduced', 'full'] as const;
const THEME_BLURS = ['none', 'subtle', 'strong'] as const;
const BUTTON_STYLES = ['outline', 'solid', 'soft'] as const;
const INPUT_STYLES = ['underline', 'boxed'] as const;
const CARD_STYLES = ['outlined', 'flat', 'elevated'] as const;
const TAB_STYLES = ['underline', 'segmented'] as const;
const BACKGROUND_TYPES = ['solid', 'linear', 'radial', 'mesh'] as const;
const BACKGROUND_ANIMATIONS = ['none', 'drift'] as const;
const BACKGROUND_MAX_STOPS = 5;
/** 渐变背景的读性遮罩下限:把背景拉回基色,保证正文对比度不因背景而崩塌 */
const BACKGROUND_SCRIM_FLOOR: Record<ColorScheme, number> = { light: 0.35, dark: 0.25 };
export const THEME_EFFECT_NAMES = ['scanline', 'flicker', 'glow', 'noise'] as const;
export type ColorScheme = 'dark' | 'light';
export type BuiltInThemeName = (typeof BUILT_IN_THEME_NAMES)[number];
@@ -84,10 +93,13 @@ export type ThemeDensity = (typeof THEME_DENSITIES)[number];
export type ThemeFont = (typeof THEME_FONTS)[number];
export type ThemeShadow = (typeof THEME_SHADOWS)[number];
export type ThemeMotion = (typeof THEME_MOTIONS)[number];
export type ThemeBlur = (typeof THEME_BLURS)[number];
export type ThemeButtonStyle = (typeof BUTTON_STYLES)[number];
export type ThemeInputStyle = (typeof INPUT_STYLES)[number];
export type ThemeCardStyle = (typeof CARD_STYLES)[number];
export type ThemeTabStyle = (typeof TAB_STYLES)[number];
export type ThemeBackgroundType = (typeof BACKGROUND_TYPES)[number];
export type ThemeBackgroundAnimation = (typeof BACKGROUND_ANIMATIONS)[number];
export interface ThemeComponentStyles {
button: ThemeButtonStyle;
@@ -103,9 +115,37 @@ export interface ThemeAppearance {
font?: ThemeFont;
shadow?: ThemeShadow;
motion?: ThemeMotion;
/** 独立于 shadow 档位的表面模糊覆盖(缺省时跟随 shadow 预设派生值) */
blur?: ThemeBlur;
components?: Partial<ThemeComponentStyles>;
}
export interface ThemeBackground {
type: ThemeBackgroundType;
/** 渐变停靠点(1–5 个,均通过 isSafeThemeColor 白名单校验) */
stops: string[];
/** linear 渐变角度,0–360 */
angle: number;
/** 读性遮罩强度 0–0.85,渐变背景会被抬到明暗方案对应的下限 */
scrim: number;
animation: ThemeBackgroundAnimation;
}
export interface ThemeEffects {
/** 键存在且 > 0 即启用对应效果,数值为 0–1 的强度参数 */
scanline?: number;
flicker?: number;
glow?: number;
noise?: number;
}
export interface ThemeTypography {
/** UI 字号缩放 0.85–1.25,叠加在密度档位基准之上 */
fontScale: number;
/** 圆角缩放 0.5–2,叠加在形状档位基准之上 */
radiusScale: number;
}
export interface NormalizedThemeData {
schemaVersion: typeof THEME_SCHEMA_VERSION;
name?: string;
@@ -114,6 +154,9 @@ export interface NormalizedThemeData {
terminal?: Record<string, string>;
ui?: Record<string, string>;
appearance?: ThemeAppearance;
background?: ThemeBackground;
effects?: ThemeEffects;
typography?: ThemeTypography;
}
const SAFE_UI_PROPERTY_SET = new Set<string>(SAFE_UI_THEME_PROPERTIES);
@@ -126,17 +169,29 @@ export function normalizeThemeData(data: unknown): NormalizedThemeData | null {
const ui = sanitizeColorRecord(input.ui, SAFE_UI_PROPERTY_SET);
const terminal = sanitizeColorRecord(input.terminal, SAFE_TERMINAL_PROPERTY_SET);
const appearance = sanitizeThemeAppearance(input.appearance);
const colorScheme =
input.colorScheme === 'light' || input.colorScheme === 'dark'
? input.colorScheme
: inferColorScheme(ui['--bg'] || terminal.background);
const background = sanitizeBackground(input.background, colorScheme);
const effects = sanitizeEffects(input.effects);
const typography = sanitizeTypography(input.typography);
if (!Object.keys(ui).length && !Object.keys(terminal).length && !appearance) return null;
if (
!Object.keys(ui).length &&
!Object.keys(terminal).length &&
!appearance &&
!background &&
!effects &&
!typography
) {
return null;
}
const baseTheme =
typeof input.baseTheme === 'string' && BUILT_IN_THEME_SET.has(input.baseTheme)
? (input.baseTheme as BuiltInThemeName)
: undefined;
const colorScheme =
input.colorScheme === 'light' || input.colorScheme === 'dark'
? input.colorScheme
: inferColorScheme(ui['--bg'] || terminal.background);
const name = typeof input.name === 'string' ? input.name.trim().slice(0, 80) : '';
return {
@@ -147,6 +202,9 @@ export function normalizeThemeData(data: unknown): NormalizedThemeData | null {
...(Object.keys(ui).length ? { ui } : {}),
...(Object.keys(terminal).length ? { terminal } : {}),
...(appearance ? { appearance } : {}),
...(background ? { background } : {}),
...(effects ? { effects } : {}),
...(typography ? { typography } : {}),
};
}
@@ -195,6 +253,7 @@ function sanitizeThemeAppearance(value: unknown): ThemeAppearance | undefined {
if (isOneOf(input.font, THEME_FONTS)) appearance.font = input.font;
if (isOneOf(input.shadow, THEME_SHADOWS)) appearance.shadow = input.shadow;
if (isOneOf(input.motion, THEME_MOTIONS)) appearance.motion = input.motion;
if (isOneOf(input.blur, THEME_BLURS)) appearance.blur = input.blur;
const components: Partial<ThemeComponentStyles> = {};
if (isOneOf(componentsInput.button, BUTTON_STYLES)) components.button = componentsInput.button;
@@ -206,6 +265,56 @@ function sanitizeThemeAppearance(value: unknown): ThemeAppearance | undefined {
return Object.keys(appearance).length ? appearance : undefined;
}
function sanitizeBackground(value: unknown, colorScheme: ColorScheme): ThemeBackground | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
const input = value as Record<string, unknown>;
const stops = Array.isArray(input.stops)
? input.stops
.filter((stop): stop is string => typeof stop === 'string' && isSafeThemeColor(stop))
.slice(0, BACKGROUND_MAX_STOPS)
: [];
// 背景模块存在但没有任何合法停靠点:整块丢弃,回退纯色背景
if (stops.length === 0) return undefined;
const type = isOneOf(input.type, BACKGROUND_TYPES) ? input.type : 'linear';
const animation = isOneOf(input.animation, BACKGROUND_ANIMATIONS)
? input.animation
: ('none' as const);
const angle = clampFinite(input.angle, 0, 360, 160);
let scrim = clampFinite(input.scrim, 0, 0.85, 0);
if (type !== 'solid') {
scrim = Math.max(scrim, BACKGROUND_SCRIM_FLOOR[colorScheme]);
}
return { type, stops, angle, scrim, animation };
}
function sanitizeEffects(value: unknown): ThemeEffects | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
const input = value as Record<string, unknown>;
const effects: ThemeEffects = {};
for (const name of THEME_EFFECT_NAMES) {
const raw = input[name];
if (typeof raw === 'number' && Number.isFinite(raw)) {
const clamped = Math.min(1, Math.max(0, raw));
if (clamped > 0) effects[name] = clamped;
}
}
return Object.keys(effects).length ? effects : undefined;
}
function sanitizeTypography(value: unknown): ThemeTypography | undefined {
if (!value || typeof value !== 'object' || Array.isArray(value)) return undefined;
const input = value as Record<string, unknown>;
const fontScale = clampFinite(input.fontScale, 0.85, 1.25, 1);
const radiusScale = clampFinite(input.radiusScale, 0.5, 2, 1);
if (fontScale === 1 && radiusScale === 1) return undefined;
return { fontScale, radiusScale };
}
function clampFinite(value: unknown, min: number, max: number, fallback: number): number {
const numeric = typeof value === 'number' && Number.isFinite(value) ? value : fallback;
return Math.min(max, Math.max(min, numeric));
}
function isOneOf<T extends string>(value: unknown, values: readonly T[]): value is T {
return typeof value === 'string' && values.includes(value as T);
}
+76 -70
View File
@@ -23,10 +23,10 @@ export const HTML = `<!doctype html>
async
defer
></script>
<script type="module">var n_=Object.defineProperty;var o_=(i,e,t)=>e in i?n_(i,e,{enumerable:true,configurable:true,writable:true,value:t}):i[e]=t;var w=(i,e,t)=>o_(i,typeof e!=="symbol"?e+"":e,t);const Xf={"terminal.status.jumpHopConnecting":"Connecting to jump host {index}/{total}: {name} ({host}:{port})","terminal.status.jumpTargetConnecting":"Connecting to target through the jump chain: {host}:{port}","server.jumpHost":"Jump host","server.jumpHostNone":"No jump host (direct)","server.jumpHostHint":"Choose a saved server; up to 3 recursive hops","server.jumpPath":"Path","terminal.moreActions":"More actions","terminal.searchMobile":"Search","terminal.landscapeMode":"Fullscreen landscape","terminal.exitFullscreen":"Exit fullscreen","terminal.landscapeUnsupported":"This browser cannot enter fullscreen landscape. Rotate the device manually.","terminal.rotateManually":"Fullscreen is active. Rotate the device to landscape manually.","terminal.mobileKeyboard":"Terminal shortcut keys","terminal.arrowLeft":"Left arrow","terminal.arrowUp":"Up arrow","terminal.arrowDown":"Down arrow","terminal.arrowRight":"Right arrow","terminal.copySelection":"Copy selection","terminal.paste":"Paste","terminal.hideKeyboard":"Hide keyboard","terminal.noSelection":"Select terminal text first.","terminal.mobileSelectionHint":"Selection mode is on. Drag across terminal text, then tap Copy again.","terminal.pasteFailed":"Could not read the clipboard. Check browser permissions.","language.label":"Language","language.zhCN":"简体中文","language.enUS":"English","language.switchTo":"Switch to {language}","common.confirm":"Confirm","common.cancel":"Cancel","common.close":"Close","common.back":"Back","common.save":"Save","common.delete":"Delete","common.edit":"Edit","common.connect":"Connect","common.loading":"Loading…","common.optional":"Optional","common.auto":"Auto","common.password":"Password","common.privateKey":"Private key","common.documentation":"Documentation","feedback.info":"Notice","feedback.success":"Success","feedback.warning":"Attention","feedback.danger":"Operation failed","feedback.closeNotification":"Close notification","dialog.promptTitle":"Input required","dialog.confirmTitle":"Confirm action","dialog.inputLabel":"Input","dialog.inputRequired":"Please enter a value","authChallenge.title":"Interactive authentication required","authChallenge.target":"Target host: {host}:{port}","authChallenge.unknownHost":"Unknown host","authChallenge.remoteRequest":"The following content is provided by the remote SSH server. Only submit authentication information requested by that server.","authChallenge.promptFallback":"Response {index}","authChallenge.sensitiveHint":"Responses are sent directly to the current SSH connection. Verify the target host before continuing.","authChallenge.useStoredPassword":"Use current connection password","authChallenge.continue":"Continue","authChallenge.respond":"Submit response","authChallenge.invalid":"The remote server sent an invalid interactive authentication request. Automatic reconnect has been stopped.","auth.connectionParameters":"Connection parameters","auth.systemReady":"System ready. Waiting for input.","auth.host":"Host address","auth.port":"Port","auth.user":"Username","auth.method":"Authentication method","auth.keyPlaceholder":"-----BEGIN OPENSSH PRIVATE KEY-----\\n...paste private key here...\\n-----END OPENSSH PRIVATE KEY-----","auth.chooseKeyFile":"Choose key file","auth.regionHint":"Connection region","auth.regionOptional":"Optional; Auto lets Cloudflare choose","auth.remember":"Remember connection","auth.execute":"Connect","auth.statusOffline":"Status: Offline","auth.statusOnline":"Status: Online","auth.recent":"Recent connections","auth.login":"Sign in with GitHub","auth.logout":"Sign out","auth.githubRequired":"This CloudSSH instance requires GitHub sign-in","auth.githubRequiredHint":"Sign in with an administrator-approved account before using SSH and account features.","auth.githubNotConfigured":"GitHub OAuth is not fully configured, so sign-in is currently unavailable.","auth.validationHostUser":"Enter a host address and username.","auth.validationPort":"Port must be an integer from 1 to 65535.","auth.validationPassword":"Enter a password.","auth.validationPrivateKey":"Enter a private key.","auth.readKeyFailed":"Could not read the private key file.","auth.readKeyTitle":"Could not read file","auth.removeHistory":"Remove from history","auth.incompleteConnection":"Connection details incomplete","auth.incompleteCredentials":"Credentials incomplete","auth.turnstileRequired":"Complete the verification first.","auth.verificationRequired":"Verification required","auth.connectFailed":"Connection failed: {message}","server.list":"Server list","server.manage":"Manage your SSH connections","server.searchLabel":"Search servers","server.searchPlaceholder":"Search by name, host, or username","server.clearSearch":"Clear search","server.tagFilter":"Filter by tag","server.allTags":"All tags"Line truncated
<script type="module">var c_=Object.defineProperty;var d_=(i,e,t)=>e in i?c_(i,e,{enumerable:true,configurable:true,writable:true,value:t}):i[e]=t;var w=(i,e,t)=>d_(i,typeof e!=="symbol"?e+"":e,t);const Zf={"terminal.status.jumpHopConnecting":"Connecting to jump host {index}/{total}: {name} ({host}:{port})","terminal.status.jumpTargetConnecting":"Connecting to target through the jump chain: {host}:{port}","server.jumpHost":"Jump host","server.jumpHostNone":"No jump host (direct)","server.jumpHostHint":"Choose a saved server; up to 3 recursive hops","server.jumpPath":"Path","terminal.moreActions":"More actions","terminal.searchMobile":"Search","terminal.landscapeMode":"Fullscreen landscape","terminal.exitFullscreen":"Exit fullscreen","terminal.landscapeUnsupported":"This browser cannot enter fullscreen landscape. Rotate the device manually.","terminal.rotateManually":"Fullscreen is active. Rotate the device to landscape manually.","terminal.mobileKeyboard":"Terminal shortcut keys","terminal.arrowLeft":"Left arrow","terminal.arrowUp":"Up arrow","terminal.arrowDown":"Down arrow","terminal.arrowRight":"Right arrow","terminal.copySelection":"Copy selection","terminal.paste":"Paste","terminal.hideKeyboard":"Hide keyboard","terminal.noSelection":"Select terminal text first.","terminal.mobileSelectionHint":"Selection mode is on. Drag across terminal text, then tap Copy again.","terminal.pasteFailed":"Could not read the clipboard. Check browser permissions.","language.label":"Language","language.zhCN":"简体中文","language.enUS":"English","language.switchTo":"Switch to {language}","common.confirm":"Confirm","common.cancel":"Cancel","common.close":"Close","common.back":"Back","common.save":"Save","common.delete":"Delete","common.edit":"Edit","common.connect":"Connect","common.loading":"Loading…","common.optional":"Optional","common.auto":"Auto","common.password":"Password","common.privateKey":"Private key","common.documentation":"Documentation","feedback.info":"Notice","feedback.success":"Success","feedback.warning":"Attention","feedback.danger":"Operation failed","feedback.closeNotification":"Close notification","dialog.promptTitle":"Input required","dialog.confirmTitle":"Confirm action","dialog.inputLabel":"Input","dialog.inputRequired":"Please enter a value","authChallenge.title":"Interactive authentication required","authChallenge.target":"Target host: {host}:{port}","authChallenge.unknownHost":"Unknown host","authChallenge.remoteRequest":"The following content is provided by the remote SSH server. Only submit authentication information requested by that server.","authChallenge.promptFallback":"Response {index}","authChallenge.sensitiveHint":"Responses are sent directly to the current SSH connection. Verify the target host before continuing.","authChallenge.useStoredPassword":"Use current connection password","authChallenge.continue":"Continue","authChallenge.respond":"Submit response","authChallenge.invalid":"The remote server sent an invalid interactive authentication request. Automatic reconnect has been stopped.","auth.connectionParameters":"Connection parameters","auth.systemReady":"System ready. Waiting for input.","auth.host":"Host address","auth.port":"Port","auth.user":"Username","auth.method":"Authentication method","auth.keyPlaceholder":"-----BEGIN OPENSSH PRIVATE KEY-----\\n...paste private key here...\\n-----END OPENSSH PRIVATE KEY-----","auth.chooseKeyFile":"Choose key file","auth.regionHint":"Connection region","auth.regionOptional":"Optional; Auto lets Cloudflare choose","auth.remember":"Remember connection","auth.execute":"Connect","auth.statusOffline":"Status: Offline","auth.statusOnline":"Status: Online","auth.recent":"Recent connections","auth.login":"Sign in with GitHub","auth.logout":"Sign out","auth.githubRequired":"This CloudSSH instance requires GitHub sign-in","auth.githubRequiredHint":"Sign in with an administrator-approved account before using SSH and account features.","auth.githubNotConfigured":"GitHub OAuth is not fully configured, so sign-in is currently unavailable.","auth.validationHostUser":"Enter a host address and username.","auth.validationPort":"Port must be an integer from 1 to 65535.","auth.validationPassword":"Enter a password.","auth.validationPrivateKey":"Enter a private key.","auth.readKeyFailed":"Could not read the private key file.","auth.readKeyTitle":"Could not read file","auth.removeHistory":"Remove from history","auth.incompleteConnection":"Connection details incomplete","auth.incompleteCredentials":"Credentials incomplete","auth.turnstileRequired":"Complete the verification first.","auth.verificationRequired":"Verification required","auth.connectFailed":"Connection failed: {message}","server.list":"Server list","server.manage":"Manage your SSH connections","server.searchLabel":"Search servers","server.searchPlaceholder":"Search by name, host, or username","server.clearSearch":"Clear search","server.tagFilter":"Filter by tag","server.allTags":"All tags"Line truncated
<span class="material-symbols-outlined language-toggle__icon" aria-hidden="true">language</span>
<span data-language-toggle-label></span>
\`;t.addEventListener("click",()=>d_(Jf(pr)));e.appendChild(t)});Qf()}function d_(i,e={}){pr=i;if(typeof document!=="undefined"){document.documentElement.lang=i;Oi();Qf()}if(e.persist!==false&&typeof localStorage!=="undefined"){try{localStorage.setItem(Zf,i)}catch{}}Cl.forEach(t=>t(i))}function $s(i){Cl.add(i);return()=>Cl.delete(i)}function u_(){let i=null;try{i=localStorage.getItem(Zf)}catch{}const e=l_({urlLocale:new URLSearchParams(window.location.search).get("lang"),storedLocale:i,browserLocales:navigator.languages});pr=e;document.documentElement.lang=e;ep();Oi();return e}class f_{constructor(){w(this,"modalEl",null)}show(){if(!this.modalEl)this.render();this.modalEl.classList.remove("hidden");void this.loadConfig()}hide(){var e;(e=this.modalEl)==null?void 0:e.classList.add("hidden")}render(){var e,t,s,r;this.modalEl=document.createElement("div");this.modalEl.id="ai-config-modal";this.modalEl.className="responsive-modal hidden fixed inset-0 z-[100] flex items-center justify-center";this.modalEl.innerHTML=\`
\`;t.addEventListener("click",()=>g_(Qf(pr)));e.appendChild(t)});ep()}function g_(i,e={}){pr=i;if(typeof document!=="undefined"){document.documentElement.lang=i;Oi();ep()}if(e.persist!==false&&typeof localStorage!=="undefined"){try{localStorage.setItem(Jf,i)}catch{}}El.forEach(t=>t(i))}function Os(i){El.add(i);return()=>El.delete(i)}function __(){let i=null;try{i=localStorage.getItem(Jf)}catch{}const e=f_({urlLocale:new URLSearchParams(window.location.search).get("lang"),storedLocale:i,browserLocales:navigator.languages});pr=e;document.documentElement.lang=e;tp();Oi();return e}class v_{constructor(){w(this,"modalEl",null)}show(){if(!this.modalEl)this.render();this.modalEl.classList.remove("hidden");void this.loadConfig()}hide(){var e;(e=this.modalEl)==null?void 0:e.classList.add("hidden")}render(){var e,t,s,r;this.modalEl=document.createElement("div");this.modalEl.id="ai-config-modal";this.modalEl.className="responsive-modal hidden fixed inset-0 z-[100] flex items-center justify-center";this.modalEl.innerHTML=\`
<div class="modal-overlay absolute inset-0" id="ai-modal-backdrop"></div>
<div class="responsive-modal-panel cyber-box p-6 shadow-2xl relative z-10 w-full max-w-md mx-4">
<div class="theme-accent-line absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-transparent via-[var(--accent-secondary)] to-transparent opacity-50"></div>
@@ -72,7 +72,7 @@ export const HTML = `<!doctype html>
</div>
</form>
</div>
\`;Oi(this.modalEl);document.body.appendChild(this.modalEl);(e=this.modalEl.querySelector("#ai-modal-close-btn"))==null?void 0:e.addEventListener("click",()=>this.hide());(t=this.modalEl.querySelector("#ai-modal-backdrop"))==null?void 0:t.addEventListener("click",()=>this.hide());(s=this.modalEl.querySelector("#ai-fetch-models-btn"))==null?void 0:s.addEventListener("click",()=>this.fetchModels());(r=this.modalEl.querySelector("#ai-save-btn"))==null?void 0:r.addEventListener("click",()=>this.saveConfig())}async loadConfig(){var e,t,s;try{const r=await fetch("/api/ai/config");if(r.ok){const n=await r.json();if(n.configured){const o=(e=this.modalEl)==null?void 0:e.querySelector("#ai-base-url");const a=(t=this.modalEl)==null?void 0:t.querySelector("#ai-model");const h=(s=this.modalEl)==null?void 0:s.querySelector("#ai-key-hint");if(o)o.value=n.base_url||"";if(a)a.value=n.model||"";if(h&&n.api_key_last4){h.textContent=m("aiConfig.currentKey",{last4:n.api_key_last4})}}}}catch{}}async fetchModels(){var a,h,l,c,d;const e=(a=this.modalEl)==null?void 0:a.querySelector("#ai-base-url");const t=(h=this.modalEl)==null?void 0:h.querySelector("#ai-api-key");const s=(l=this.modalEl)==null?void 0:l.querySelector("#ai-model-list");const r=(c=this.modalEl)==null?void 0:c.querySelector("#ai-fetch-models-btn");const n=e==null?void 0:e.value.trim();const o=t==null?void 0:t.value.trim();if(!n||!o){this.showFetchStatus(m("aiConfig.credentialsRequired"),true);return}if(r)r.disabled=true;this.showFetchStatus(m("aiConfig.loadingModels"));try{const u=await fetch("/api/ai/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({base_url:n,api_key:o})});const f=await u.json();if(f.error){this.showFetchStatus(f.error,true);return}if(f.fallback&&((d=f.models)==null?void 0:d.length)===0){const b=f.reason?\` (\${f.reason})\`:"";this.showFetchStatus(m("aiConfig.manualModel",{reason:b}),false);return}const p=f.models||[];if(s){s.innerHTML="";for(const b of p){const v=document.createElement("option");v.value=b.id;s.appendChild(v)}}this.showFetchStatus(m("aiConfig.modelsLoaded",{count:p.length}),false)}catch(u){this.showFetchStatus(m("aiConfig.loadFailed",{message:u instanceof Error?u.message:m("aiConfig.networkError")}),true)}finally{if(r)r.disabled=false}}showFetchStatus(e,t=false){var r;const s=(r=this.modalEl)==null?void 0:r.querySelector("#ai-fetch-status");if(s){s.textContent=e;s.className=\`text-[10px] mt-1 \${t?"text-[var(--error)]":"text-[var(--accent)]"}\`}}async saveConfig(){var o,a,h,l,c,d,u,f;const e=(a=(o=this.modalEl)==null?void 0:o.querySelector("#ai-base-url"))==null?void 0:a.value.trim();const t=(l=(h=this.modalEl)==null?void 0:h.querySelector("#ai-api-key"))==null?void 0:l.value.trim();const s=(d=(c=this.modalEl)==null?void 0:c.querySelector("#ai-model"))==null?void 0:d.value.trim();const r=(u=this.modalEl)==null?void 0:u.querySelector("#ai-config-error");const n=(f=this.modalEl)==null?void 0:f.querySelector("#ai-config-success");r==null?void 0:r.classList.add("hidden");n==null?void 0:n.classList.add("hidden");if(!e||!s){if(r){r.textContent=m("aiConfig.required");r.classList.remove("hidden")}return}try{const p={base_url:e,model:s};if(t)p.api_key=t;const b=await fetch("/api/ai/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});if(b.ok){if(n){n.textContent=m("aiConfig.saved");n.classList.remove("hidden")}setTimeout(()=>this.hide(),1500)}else{const v=await b.json();if(r){r.textContent=v.error||m("feedback.danger");r.classList.remove("hidden")}}}catch{if(r){r.textContent=m("aiConfig.networkError");r.classList.remove("hidden")}}}}const kl="cloudssh_known_hosts";const p_=/^SHA256:[A-Za-z0-9+/]{43}$/;const zc=2048;const m_=128;function fo(i,e){if(typeof i!=="string")return null;const t=i.trim();if(!t||t.length>e)return null;return t}function Lo(i){const e=fo(i,80);return e&&p_.test(e)?e:null}function g_(i){return Number.isInteger(i)&&Number(i)>=1&&Number(i)<=65535?Number(i):null}function tp(i){if(!i||typeof i!=="object")return null;const e=i;const t=Lo(e.fingerprint);const s=fo(e.host,zc);const r=g_(e.port);const n=fo(e.keyType,m_);const o=fo(e.displayHost,zc)??s;if(!t||!s||!r||!n||!o)return null;return{fingerprint:t,host:s,port:r,keyType:n,displayHost:o}}function __(i){const e=tp(i);if(!e||typeof i.firstSeen!=="boolean")return null;return{...e,firstSeen:i.firstSeen}}function v_(i){const e=tp(i);if(!e)return null;const t=Lo(i.expectedFingerprint);return t?{...e,expectedFingerprint:t}:null}function Nc(i,e,t){try{const s=localStorage.getItem(kl);const r=s?JSON.parse(s):{};r[\`\${i}:\${e}\`]=t;localStorage.setItem(kl,JSON.stringify(r));return true}catch{return false}}async function Hc(i,e,t,s=false){const r=s?false:Nc(i,e,t);let n=false;try{const o=await fetch("/api/known-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({host:i,port:e,fingerprint:t})});n=o.ok;if(!o.ok&&s)throw new Error(\`Known-host update failed (\${o.statusLine truncated
\`;Oi(this.modalEl);document.body.appendChild(this.modalEl);(e=this.modalEl.querySelector("#ai-modal-close-btn"))==null?void 0:e.addEventListener("click",()=>this.hide());(t=this.modalEl.querySelector("#ai-modal-backdrop"))==null?void 0:t.addEventListener("click",()=>this.hide());(s=this.modalEl.querySelector("#ai-fetch-models-btn"))==null?void 0:s.addEventListener("click",()=>this.fetchModels());(r=this.modalEl.querySelector("#ai-save-btn"))==null?void 0:r.addEventListener("click",()=>this.saveConfig())}async loadConfig(){var e,t,s;try{const r=await fetch("/api/ai/config");if(r.ok){const n=await r.json();if(n.configured){const o=(e=this.modalEl)==null?void 0:e.querySelector("#ai-base-url");const a=(t=this.modalEl)==null?void 0:t.querySelector("#ai-model");const h=(s=this.modalEl)==null?void 0:s.querySelector("#ai-key-hint");if(o)o.value=n.base_url||"";if(a)a.value=n.model||"";if(h&&n.api_key_last4){h.textContent=m("aiConfig.currentKey",{last4:n.api_key_last4})}}}}catch{}}async fetchModels(){var a,h,l,c,d;const e=(a=this.modalEl)==null?void 0:a.querySelector("#ai-base-url");const t=(h=this.modalEl)==null?void 0:h.querySelector("#ai-api-key");const s=(l=this.modalEl)==null?void 0:l.querySelector("#ai-model-list");const r=(c=this.modalEl)==null?void 0:c.querySelector("#ai-fetch-models-btn");const n=e==null?void 0:e.value.trim();const o=t==null?void 0:t.value.trim();if(!n||!o){this.showFetchStatus(m("aiConfig.credentialsRequired"),true);return}if(r)r.disabled=true;this.showFetchStatus(m("aiConfig.loadingModels"));try{const u=await fetch("/api/ai/models",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({base_url:n,api_key:o})});const f=await u.json();if(f.error){this.showFetchStatus(f.error,true);return}if(f.fallback&&((d=f.models)==null?void 0:d.length)===0){const b=f.reason?\` (\${f.reason})\`:"";this.showFetchStatus(m("aiConfig.manualModel",{reason:b}),false);return}const p=f.models||[];if(s){s.innerHTML="";for(const b of p){const v=document.createElement("option");v.value=b.id;s.appendChild(v)}}this.showFetchStatus(m("aiConfig.modelsLoaded",{count:p.length}),false)}catch(u){this.showFetchStatus(m("aiConfig.loadFailed",{message:u instanceof Error?u.message:m("aiConfig.networkError")}),true)}finally{if(r)r.disabled=false}}showFetchStatus(e,t=false){var r;const s=(r=this.modalEl)==null?void 0:r.querySelector("#ai-fetch-status");if(s){s.textContent=e;s.className=\`text-[10px] mt-1 \${t?"text-[var(--error)]":"text-[var(--accent)]"}\`}}async saveConfig(){var o,a,h,l,c,d,u,f;const e=(a=(o=this.modalEl)==null?void 0:o.querySelector("#ai-base-url"))==null?void 0:a.value.trim();const t=(l=(h=this.modalEl)==null?void 0:h.querySelector("#ai-api-key"))==null?void 0:l.value.trim();const s=(d=(c=this.modalEl)==null?void 0:c.querySelector("#ai-model"))==null?void 0:d.value.trim();const r=(u=this.modalEl)==null?void 0:u.querySelector("#ai-config-error");const n=(f=this.modalEl)==null?void 0:f.querySelector("#ai-config-success");r==null?void 0:r.classList.add("hidden");n==null?void 0:n.classList.add("hidden");if(!e||!s){if(r){r.textContent=m("aiConfig.required");r.classList.remove("hidden")}return}try{const p={base_url:e,model:s};if(t)p.api_key=t;const b=await fetch("/api/ai/config",{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(p)});if(b.ok){if(n){n.textContent=m("aiConfig.saved");n.classList.remove("hidden")}setTimeout(()=>this.hide(),1500)}else{const v=await b.json();if(r){r.textContent=v.error||m("feedback.danger");r.classList.remove("hidden")}}}catch{if(r){r.textContent=m("aiConfig.networkError");r.classList.remove("hidden")}}}}const Tl="cloudssh_known_hosts";const b_=/^SHA256:[A-Za-z0-9+/]{43}$/;const Nc=2048;const y_=128;function fo(i,e){if(typeof i!=="string")return null;const t=i.trim();if(!t||t.length>e)return null;return t}function Ao(i){const e=fo(i,80);return e&&b_.test(e)?e:null}function w_(i){return Number.isInteger(i)&&Number(i)>=1&&Number(i)<=65535?Number(i):null}function ip(i){if(!i||typeof i!=="object")return null;const e=i;const t=Ao(e.fingerprint);const s=fo(e.host,Nc);const r=w_(e.port);const n=fo(e.keyType,y_);const o=fo(e.displayHost,Nc)??s;if(!t||!s||!r||!n||!o)return null;return{fingerprint:t,host:s,port:r,keyType:n,displayHost:o}}function S_(i){const e=ip(i);if(!e||typeof i.firstSeen!=="boolean")return null;return{...e,firstSeen:i.firstSeen}}function x_(i){const e=ip(i);if(!e)return null;const t=Ao(i.expectedFingerprint);return t?{...e,expectedFingerprint:t}:null}function Hc(i,e,t){try{const s=localStorage.getItem(Tl);const r=s?JSON.parse(s):{};r[\`\${i}:\${e}\`]=t;localStorage.setItem(Tl,JSON.stringify(r));return true}catch{return false}}async function Wc(i,e,t,s=false){const r=s?false:Hc(i,e,t);let n=false;try{const o=await fetch("/api/known-hosts",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({host:i,port:e,fingerprint:t})});n=o.ok;if(!o.ok&&s)throw new Error(\`Known-host update failed (\${o.statusLine truncated
<form class="app-dialog__panel" method="dialog" novalidate>
<div class="app-dialog__accent" aria-hidden="true"></div>
<div class="app-dialog__header">
@@ -90,7 +90,7 @@ export const HTML = `<!doctype html>
<button class="app-dialog__button app-dialog__button--confirm" type="submit"></button>
</div>
</form>
\`;this.dialog=e;this.titleEl=e.querySelector(".app-dialog__title");this.messageEl=e.querySelector(".app-dialog__message");this.iconEl=e.querySelector(".app-dialog__icon");this.inputGroup=e.querySelector(".app-dialog__input-group");this.inputLabel=e.querySelector(".app-dialog__label");this.input=e.querySelector(".app-dialog__input");this.inputError=e.querySelector(".app-dialog__error");this.confirmButton=e.querySelector(".app-dialog__button--confirm");this.cancelButton=e.querySelector(".app-dialog__button--cancel");(s=e.querySelector("form"))==null?void 0:s.addEventListener("submit",a=>{a.preventDefault();this.submit()});(r=this.cancelButton)==null?void 0:r.addEventListener("click",()=>this.cancel());e.addEventListener("cancel",a=>{a.preventDefault();this.cancel()});e.addEventListener("keydown",a=>{if(a.key==="Escape"){a.preventDefault();this.cancel()}});e.addEventListener("click",a=>{if(a.target===e)this.cancel()});(n=this.input)==null?void 0:n.addEventListener("input",()=>this.clearInputError());(o=this.input)==null?void 0:o.addEventListener("keydown",a=>{if(a.key==="Enter"){a.preventDefault();this.submit()}});document.body.appendChild(e)}showNext(){if(this.active||this.queue.length===0)return;this.ensureDialog();const e=this.queue.shift();e.previousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;this.active=e;const t=e.options;const s=t.variant??"info";this.dialog.dataset.variant=s;this.titleEl.textContent=t.title??m(e.kind==="prompt"?"dialog.promptTitle":"dialog.confirmTitle");this.messageEl.textContent=t.message;this.iconEl.textContent=lp[s];this.confirmButton.textContent=t.confirmText??m("common.confirm");this.cancelButton.textContent=t.cancelText??m("common.cancel");this.clearInputError();if(e.kind==="prompt"){this.inputGroup.hidden=false;this.inputLabel.textContent=e.options.label??m("dialog.inputLabel");this.input.value=e.options.defaultValue??"";this.input.placeholder=e.options.placeholder??"";if(e.options.maxLength){this.input.maxLength=e.options.maxLength}else{this.input.removeAttribute("maxlength")}}else{this.inputGroup.hidden=true;this.input.value=""}this.dialog.showModal();requestAnimationFrame(()=>{var r,n,o,a;if(e.kind==="prompt"){(r=this.input)==null?void 0:r.focus();(n=this.input)==null?void 0:n.select()}else if(s==="danger"){(o=this.cancelButton)==null?void 0:o.focus()}else{(a=this.confirmButton)==null?void 0:a.focus()}})}submit(){var r;if(!this.active)return;if(this.active.kind==="confirm"){this.settle(true);return}const e=((r=this.input)==null?void 0:r.value)??"";const t=this.active.options;let s=null;if((t.required??true)&&!e.trim()){s=m("dialog.inputRequired")}else if(t.validate){s=t.validate(e)}if(s){this.inputError.textContent=s;this.input.setAttribute("aria-invalid","true");this.input.setAttribute("aria-describedby","app-dialog-error");this.input.focus();return}this.settle(e)}clearInputError(){if(!this.input||!this.inputError)return;this.inputError.textContent="";this.input.removeAttribute("aria-invalid");this.input.removeAttribute("aria-describedby")}cancel(){if(!this.active)return;this.settle(this.active.kind==="confirm"?false:null)}settle(e){var s,r;const t=this.active;if(!t)return;this.active=null;(s=this.dialog)==null?void 0:s.close();if(t.kind==="confirm"){t.resolve(e===true)}else{t.resolve(typeof e==="string"?e:null)}if(this.queue.length>0){queueMicrotask(()=>this.showNext())}else{(r=t.previousFocus)==null?void 0:r.focus()}}}const hp=new X_;function Ms(i){return hp.enqueueConfirm(i)}function Uc(i){return hp.enqueuePrompt(i)}async function cp(i){const e=new TextEncoder().encode(window.location.origin+":cloudssh");const t=await crypto.subtle.importKey("raw",e,"PBKDF2",false,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:i,iterations:1e5,hash:"SHA-256"},t,{name:"AES-GCM",length:256},false,["encrypt","decrypt"])}async function Z_(i){const e=crypto.getRandomValues(new Uint8Array(16));const t=crypto.getRandomValues(new Uint8Array(12));const s=await cp(e);const r=new TextEncoder().encode(JSON.stringify(i));const n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:t},s,r));const o=new Uint8Array(e.length+t.length+n.length);o.set(e,0);o.set(t,e.length);o.set(n,e.length+t.length);let a="";for(let h=0;h<o.length;h++)a+=String.fromCharCode(o[h]);return btoa(a)}async function qc(i){try{const e=Uint8Array.from(atob(i),a=>a.charCodeAt(0));const t=e.slice(0,16);const s=e.slice(16,28);const r=e.slice(28);const n=await cp(t);const o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,r);return JSON.parse(new TextDecoder().decode(o))}catch{return null}}class J_{constructor(e){w(this,"options");w(this,"turnstileEnabled",false);w(this,"turnstileVerified",false);w(this,"turnstileWidgetId",null);w(this,"turnstileSitekey","");w(this,"turnstileTheme",null);w(this,"authMode","password");this.options=e;this.render();j_(t=>{if(this.turnstileEnabled&&this.turnstileSitekey&&!this.turnstileVerified&&this.turnstileTheme!==t){this.renderTu Line truncated
\`;this.dialog=e;this.titleEl=e.querySelector(".app-dialog__title");this.messageEl=e.querySelector(".app-dialog__message");this.iconEl=e.querySelector(".app-dialog__icon");this.inputGroup=e.querySelector(".app-dialog__input-group");this.inputLabel=e.querySelector(".app-dialog__label");this.input=e.querySelector(".app-dialog__input");this.inputError=e.querySelector(".app-dialog__error");this.confirmButton=e.querySelector(".app-dialog__button--confirm");this.cancelButton=e.querySelector(".app-dialog__button--cancel");(s=e.querySelector("form"))==null?void 0:s.addEventListener("submit",a=>{a.preventDefault();this.submit()});(r=this.cancelButton)==null?void 0:r.addEventListener("click",()=>this.cancel());e.addEventListener("cancel",a=>{a.preventDefault();this.cancel()});e.addEventListener("keydown",a=>{if(a.key==="Escape"){a.preventDefault();this.cancel()}});e.addEventListener("click",a=>{if(a.target===e)this.cancel()});(n=this.input)==null?void 0:n.addEventListener("input",()=>this.clearInputError());(o=this.input)==null?void 0:o.addEventListener("keydown",a=>{if(a.key==="Enter"){a.preventDefault();this.submit()}});document.body.appendChild(e)}showNext(){if(this.active||this.queue.length===0)return;this.ensureDialog();const e=this.queue.shift();e.previousFocus=document.activeElement instanceof HTMLElement?document.activeElement:null;this.active=e;const t=e.options;const s=t.variant??"info";this.dialog.dataset.variant=s;this.titleEl.textContent=t.title??m(e.kind==="prompt"?"dialog.promptTitle":"dialog.confirmTitle");this.messageEl.textContent=t.message;this.iconEl.textContent=fp[s];this.confirmButton.textContent=t.confirmText??m("common.confirm");this.cancelButton.textContent=t.cancelText??m("common.cancel");this.clearInputError();if(e.kind==="prompt"){this.inputGroup.hidden=false;this.inputLabel.textContent=e.options.label??m("dialog.inputLabel");this.input.value=e.options.defaultValue??"";this.input.placeholder=e.options.placeholder??"";if(e.options.maxLength){this.input.maxLength=e.options.maxLength}else{this.input.removeAttribute("maxlength")}}else{this.inputGroup.hidden=true;this.input.value=""}this.dialog.showModal();requestAnimationFrame(()=>{var r,n,o,a;if(e.kind==="prompt"){(r=this.input)==null?void 0:r.focus();(n=this.input)==null?void 0:n.select()}else if(s==="danger"){(o=this.cancelButton)==null?void 0:o.focus()}else{(a=this.confirmButton)==null?void 0:a.focus()}})}submit(){var r;if(!this.active)return;if(this.active.kind==="confirm"){this.settle(true);return}const e=((r=this.input)==null?void 0:r.value)??"";const t=this.active.options;let s=null;if((t.required??true)&&!e.trim()){s=m("dialog.inputRequired")}else if(t.validate){s=t.validate(e)}if(s){this.inputError.textContent=s;this.input.setAttribute("aria-invalid","true");this.input.setAttribute("aria-describedby","app-dialog-error");this.input.focus();return}this.settle(e)}clearInputError(){if(!this.input||!this.inputError)return;this.inputError.textContent="";this.input.removeAttribute("aria-invalid");this.input.removeAttribute("aria-describedby")}cancel(){if(!this.active)return;this.settle(this.active.kind==="confirm"?false:null)}settle(e){var s,r;const t=this.active;if(!t)return;this.active=null;(s=this.dialog)==null?void 0:s.close();if(t.kind==="confirm"){t.resolve(e===true)}else{t.resolve(typeof e==="string"?e:null)}if(this.queue.length>0){queueMicrotask(()=>this.showNext())}else{(r=t.previousFocus)==null?void 0:r.focus()}}}const pp=new u1;function Bs(i){return pp.enqueueConfirm(i)}function qc(i){return pp.enqueuePrompt(i)}async function mp(i){const e=new TextEncoder().encode(window.location.origin+":cloudssh");const t=await crypto.subtle.importKey("raw",e,"PBKDF2",false,["deriveKey"]);return crypto.subtle.deriveKey({name:"PBKDF2",salt:i,iterations:1e5,hash:"SHA-256"},t,{name:"AES-GCM",length:256},false,["encrypt","decrypt"])}async function f1(i){const e=crypto.getRandomValues(new Uint8Array(16));const t=crypto.getRandomValues(new Uint8Array(12));const s=await mp(e);const r=new TextEncoder().encode(JSON.stringify(i));const n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:t},s,r));const o=new Uint8Array(e.length+t.length+n.length);o.set(e,0);o.set(t,e.length);o.set(n,e.length+t.length);let a="";for(let h=0;h<o.length;h++)a+=String.fromCharCode(o[h]);return btoa(a)}async function Kc(i){try{const e=Uint8Array.from(atob(i),a=>a.charCodeAt(0));const t=e.slice(0,16);const s=e.slice(16,28);const r=e.slice(28);const n=await mp(t);const o=await crypto.subtle.decrypt({name:"AES-GCM",iv:s},n,r);return JSON.parse(new TextDecoder().decode(o))}catch{return null}}class p1{constructor(e){w(this,"options");w(this,"turnstileEnabled",false);w(this,"turnstileVerified",false);w(this,"turnstileWidgetId",null);w(this,"turnstileSitekey","");w(this,"turnstileTheme",null);w(this,"authMode","password");this.options=e;this.render();n1(t=>{if(this.turnstileEnabled&&this.turnstileSitekey&&!this.turnstileVerified&&this.turnstileTheme!==t){this.renderTu Line truncated
<div class="flex min-h-[320px] flex-col items-center justify-center gap-5 px-4 text-center" id="github-auth-required-panel">
<span class="material-symbols-outlined text-[var(--accent)]" style="font-size: 42px;" aria-hidden="true">lock</span>
<div class="space-y-2">
@@ -104,7 +104,7 @@ export const HTML = `<!doctype html>
<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.013 8.013 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>
<span data-i18n="auth.login">使用 GitHub 登录</span>
</button>
\`;Oi(e);(t=document.getElementById("github-login-btn"))==null?void 0:t.addEventListener("click",()=>{window.location.href="/api/auth/github"})}renderTurnstile(){const e=document.getElementById("turnstile-widget");if(!e||!window.turnstile)return;if(this.turnstileWidgetId){window.turnstile.remove(this.turnstileWidgetId);this.turnstileWidgetId=null;e.replaceChildren()}const t=document.getElementById("turnstile-container");if(t)t.style.display="block";this.turnstileTheme=q_();this.turnstileWidgetId=window.turnstile.render(e,{sitekey:this.turnstileSitekey,theme:this.turnstileTheme,callback:async s=>{try{const r=await fetch("/api/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s})});const n=await r.json();if(n.success){this.turnstileVerified=true;const o=document.getElementById("turnstile-container");if(o)o.style.display="none"}}catch{this.turnstileVerified=false}},"expired-callback":()=>{this.turnstileVerified=false},"error-callback":()=>{this.turnstileVerified=false}})}render(){const e=document.getElementById("connection-form-container");e.innerHTML=\`
\`;Oi(e);(t=document.getElementById("github-login-btn"))==null?void 0:t.addEventListener("click",()=>{window.location.href="/api/auth/github"})}renderTurnstile(){const e=document.getElementById("turnstile-widget");if(!e||!window.turnstile)return;if(this.turnstileWidgetId){window.turnstile.remove(this.turnstileWidgetId);this.turnstileWidgetId=null;e.replaceChildren()}const t=document.getElementById("turnstile-container");if(t)t.style.display="block";this.turnstileTheme=s1();this.turnstileWidgetId=window.turnstile.render(e,{sitekey:this.turnstileSitekey,theme:this.turnstileTheme,callback:async s=>{try{const r=await fetch("/api/verify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:s})});const n=await r.json();if(n.success){this.turnstileVerified=true;const o=document.getElementById("turnstile-container");if(o)o.style.display="none"}}catch{this.turnstileVerified=false}},"expired-callback":()=>{this.turnstileVerified=false},"error-callback":()=>{this.turnstileVerified=false}})}render(){const e=document.getElementById("connection-form-container");e.innerHTML=\`
<form class="space-y-6" id="connection-form">
<div class="grid grid-cols-1 sm:grid-cols-4 gap-4">
<div class="sm:col-span-3">
@@ -184,7 +184,7 @@ export const HTML = `<!doctype html>
<div id="recent-connections-list" class="space-y-2 max-h-[160px] overflow-y-auto custom-scrollbar pr-1"></div>
</div>
</form>
\`;Oi(e);document.getElementById("connection-form").addEventListener("submit",n=>{n.preventDefault();void this.handleConnect()});const t=document.getElementById("anon-region");if(t){Ao(t,"")}document.getElementById("auth-tab-password").addEventListener("click",()=>{this.setAuthMode("password")});document.getElementById("auth-tab-key").addEventListener("click",()=>{this.setAuthMode("key")});const s=document.getElementById("private-key-file");const r=document.getElementById("file-name");s.addEventListener("change",async n=>{var a;const o=(a=n.target.files)==null?void 0:a[0];if(!o)return;try{const h=await o.text();const l=document.getElementById("private-key");l.value=h;if(r){r.textContent=o.name}}catch(h){J(m("auth.readKeyFailed")+" "+(h instanceof Error?h.message:""),{title:m("auth.readKeyTitle"),variant:"danger"})}s.value=""})}setAuthMode(e){this.authMode=e;const t=document.getElementById("auth-tab-password");const s=document.getElementById("auth-tab-key");const r=document.getElementById("auth-password-section");const n=document.getElementById("auth-key-section");t.classList.toggle("auth-tab-active",e==="password");s.classList.toggle("auth-tab-active",e==="key");r.style.display=e==="password"?"":"none";n.style.display=e==="key"?"":"none"}renderRecentConnections(){const e=document.getElementById("recent-connections-section");const t=document.getElementById("recent-connections-list");if(!e||!t)return;const s=localStorage.getItem("cloudssh_recent_connections");let r=[];try{r=s?JSON.parse(s):[];if(!Array.isArray(r))r=[]}catch{r=[]}if(r.length===0){e.classList.add("hidden");return}e.classList.remove("hidden");t.innerHTML="";r.forEach((n,o)=>{const a=document.createElement("div");a.className="flex justify-between items-center text-xs p-2 border border-dim bg-surface/50 hover:bg-surface hover:border-[var(--accent)] transition-all cursor-pointer group relative";const h=n.authMethod==="publickey"?"KEY":"PWD";const l=\`\${n.username}@\${n.host}:\${n.port}\`;a.innerHTML=\`
\`;Oi(e);document.getElementById("connection-form").addEventListener("submit",n=>{n.preventDefault();void this.handleConnect()});const t=document.getElementById("anon-region");if(t){Ro(t,"")}document.getElementById("auth-tab-password").addEventListener("click",()=>{this.setAuthMode("password")});document.getElementById("auth-tab-key").addEventListener("click",()=>{this.setAuthMode("key")});const s=document.getElementById("private-key-file");const r=document.getElementById("file-name");s.addEventListener("change",async n=>{var a;const o=(a=n.target.files)==null?void 0:a[0];if(!o)return;try{const h=await o.text();const l=document.getElementById("private-key");l.value=h;if(r){r.textContent=o.name}}catch(h){J(m("auth.readKeyFailed")+" "+(h instanceof Error?h.message:""),{title:m("auth.readKeyTitle"),variant:"danger"})}s.value=""})}setAuthMode(e){this.authMode=e;const t=document.getElementById("auth-tab-password");const s=document.getElementById("auth-tab-key");const r=document.getElementById("auth-password-section");const n=document.getElementById("auth-key-section");t.classList.toggle("auth-tab-active",e==="password");s.classList.toggle("auth-tab-active",e==="key");r.style.display=e==="password"?"":"none";n.style.display=e==="key"?"":"none"}renderRecentConnections(){const e=document.getElementById("recent-connections-section");const t=document.getElementById("recent-connections-list");if(!e||!t)return;const s=localStorage.getItem("cloudssh_recent_connections");let r=[];try{r=s?JSON.parse(s):[];if(!Array.isArray(r))r=[]}catch{r=[]}if(r.length===0){e.classList.add("hidden");return}e.classList.remove("hidden");t.innerHTML="";r.forEach((n,o)=>{const a=document.createElement("div");a.className="flex justify-between items-center text-xs p-2 border border-dim bg-surface/50 hover:bg-surface hover:border-[var(--accent)] transition-all cursor-pointer group relative";const h=n.authMethod==="publickey"?"KEY":"PWD";const l=\`\${n.username}@\${n.host}:\${n.port}\`;a.innerHTML=\`
<div class="flex items-center gap-2 overflow-hidden mr-2 select-none flex-1">
<span class="material-symbols-outlined text-muted" style="font-size: 14px;">history</span>
<span class="text-on-surface truncate" title="\${l}">\${l}</span>
@@ -193,7 +193,7 @@ export const HTML = `<!doctype html>
<button class="delete-history-btn text-muted hover:text-error flex items-center justify-center p-0.5" title="\${m("auth.removeHistory")}">
<span class="material-symbols-outlined" style="font-size: 14px;">close</span>
</button>
\`;a.addEventListener("click",c=>{if(c.target.closest(".delete-history-btn"))return;this.fillConnection(n)});a.querySelector(".delete-history-btn").addEventListener("click",c=>{c.stopPropagation();this.deleteConnection(o)});t.appendChild(a)})}async fillConnection(e){document.getElementById("host").value=e.host||"";document.getElementById("port").value=(e.port||22).toString();document.getElementById("username").value=e.username||"";const t=document.getElementById("anon-region");if(t){t.value=e.region||""}if(e.authMethod==="publickey"){this.setAuthMode("key")}else{this.setAuthMode("password")}if(e.encryptedCred){const s=await qc(e.encryptedCred);if(s){document.getElementById("password").value=s.password||"";document.getElementById("private-key").value=s.privateKey||"";document.getElementById("remember-me").checked=true}else{document.getElementById("password").value="";document.getElementById("private-key").value="";document.getElementById("remember-me").checked=false}}else{document.getElementById("password").value="";document.getElementById("private-key").value="";document.getElementById("remember-me").checked=false}}deleteConnection(e){const t=localStorage.getItem("cloudssh_recent_connections");let s=[];try{s=t?JSON.parse(t):[]}catch{}if(e>=0&&e<s.length){s.splice(e,1);localStorage.setItem("cloudssh_recent_connections",JSON.stringify(s));this.renderRecentConnections()}}async loadSavedCredentials(){const e=localStorage.getItem("cloudssh_recent_connections");let t=[];try{t=e?JSON.parse(e):[];if(!Array.isArray(t))t=[]}catch{t=[]}const s=localStorage.getItem("cloudssh_cred");if(t.length===0&&s){const r=await qc(s);if(r){const n={id:\`\${r.username}@\${r.host}:\${r.port}\`,host:r.host,port:parseInt(r.port)||22,username:r.username,authMethod:r.authMethod==="publickey"?"publickey":"password",timestamp:Date.now(),encryptedCred:s};t.push(n);localStorage.setItem("cloudssh_recent_connections",JSON.stringify(t));localStorage.removeItem("cloudssh_cred")}}this.renderRecentConnections();if(t.length>0){this.fillConnection(t[0])}}async handleConnect(){var k,D,N,z;const e=document.getElementById("host").value;const t=e.replace(/^\\[|\\]$/g,"").trim();const s=document.getElementById("port");const r=ip(s.value);const n=document.getElementById("username").value;const o=document.getElementById("password").value;const a=document.getElementById("private-key").value;const h=this.authMode==="password"?o:void 0;const l=this.authMode==="key"?a:void 0;const c=document.getElementById("remember-me").checked;const d=document.getElementById("anon-region");const u=d?d.value:"";if(!t||!n){J(m("auth.validationHostUser"),{title:m("auth.incompleteConnection"),variant:"warning"});(k=document.getElementById(t?"username":"host"))==null?void 0:k.focus();return}if(r===null){J(m("auth.validationPort"),{title:m("auth.incompleteConnection"),variant:"warning"});s.focus();return}if(this.authMode==="password"&&!o){J(m("auth.validationPassword"),{title:m("auth.incompleteCredentials"),variant:"warning"});(D=document.getElementById("password"))==null?void 0:D.focus();return}if(this.authMode==="key"&&!a){J(m("auth.validationPrivateKey"),{title:m("auth.incompleteCredentials"),variant:"warning"});(N=document.getElementById("private-key"))==null?void 0:N.focus();return}if(this.turnstileEnabled&&!this.turnstileVerified){J(m("auth.turnstileRequired"),{title:m("auth.verificationRequired"),variant:"warning"});(z=document.getElementById("turnstile-container"))==null?void 0:z.scrollIntoView({behavior:"smooth",block:"center"});return}let f;if(c){f=await Z_({host:t,port:r.toString(),username:n,password:h??"",privateKey:l,authMethod:this.authMode==="key"?"publickey":"password"})}const p=localStorage.getItem("cloudssh_recent_connections");let b=[];try{b=p?JSON.parse(p):[];if(!Array.isArray(b))b=[]}catch{}const v=\`\${n}@\${t}:\${r}\`;const R={id:v,host:t,port:r,username:n,authMethod:this.authMode==="key"?"publickey":"password",timestamp:Date.now(),...u?{region:u}:{},...f?{encryptedCred:f}:{}};b=b.filter(K=>K.id!==v);b.unshift(R);if(b.length>5){b=b.slice(0,5)}localStorage.setItem("cloudssh_recent_connections",JSON.stringify(b));this.renderRecentConnections();const L=this.options.getTabManager();const A=\`\${n}@\${t}\`;document.getElementById("auth-section").classList.add("hidden");document.getElementById("terminal-section").classList.remove("hidden");document.getElementById("terminal-section").classList.add("flex");const g=L.createTab(A,{host:t,port:r,username:n});const E=g.terminal;E.mount();try{const K=await b_(t,r);await E.connect({host:t,port:r,username:n,password:h,authMethod:this.authMode==="key"?"publickey":"password",privateKey:l,expectedFingerprint:K||void 0,locationHint:u||void 0})}catch{L.closeTab(g.id);document.getElementById("status-text").innerHTML=\`<span class="w-2 h-2 bg-surface-dot inline-block"></span> \${m("auth.statusOffline")}\`}}}const Q_=120;const e1=120;const t1="(max-width: 767px), (max-width: 1180px) and (pointer: coarse)";const i1=new Set( Line truncated
\`;a.addEventListener("click",c=>{if(c.target.closest(".delete-history-btn"))return;this.fillConnection(n)});a.querySelector(".delete-history-btn").addEventListener("click",c=>{c.stopPropagation();this.deleteConnection(o)});t.appendChild(a)})}async fillConnection(e){document.getElementById("host").value=e.host||"";document.getElementById("port").value=(e.port||22).toString();document.getElementById("username").value=e.username||"";const t=document.getElementById("anon-region");if(t){t.value=e.region||""}if(e.authMethod==="publickey"){this.setAuthMode("key")}else{this.setAuthMode("password")}if(e.encryptedCred){const s=await Kc(e.encryptedCred);if(s){document.getElementById("password").value=s.password||"";document.getElementById("private-key").value=s.privateKey||"";document.getElementById("remember-me").checked=true}else{document.getElementById("password").value="";document.getElementById("private-key").value="";document.getElementById("remember-me").checked=false}}else{document.getElementById("password").value="";document.getElementById("private-key").value="";document.getElementById("remember-me").checked=false}}deleteConnection(e){const t=localStorage.getItem("cloudssh_recent_connections");let s=[];try{s=t?JSON.parse(t):[]}catch{}if(e>=0&&e<s.length){s.splice(e,1);localStorage.setItem("cloudssh_recent_connections",JSON.stringify(s));this.renderRecentConnections()}}async loadSavedCredentials(){const e=localStorage.getItem("cloudssh_recent_connections");let t=[];try{t=e?JSON.parse(e):[];if(!Array.isArray(t))t=[]}catch{t=[]}const s=localStorage.getItem("cloudssh_cred");if(t.length===0&&s){const r=await Kc(s);if(r){const n={id:\`\${r.username}@\${r.host}:\${r.port}\`,host:r.host,port:parseInt(r.port)||22,username:r.username,authMethod:r.authMethod==="publickey"?"publickey":"password",timestamp:Date.now(),encryptedCred:s};t.push(n);localStorage.setItem("cloudssh_recent_connections",JSON.stringify(t));localStorage.removeItem("cloudssh_cred")}}this.renderRecentConnections();if(t.length>0){this.fillConnection(t[0])}}async handleConnect(){var k,D,N,z;const e=document.getElementById("host").value;const t=e.replace(/^\\[|\\]$/g,"").trim();const s=document.getElementById("port");const r=sp(s.value);const n=document.getElementById("username").value;const o=document.getElementById("password").value;const a=document.getElementById("private-key").value;const h=this.authMode==="password"?o:void 0;const l=this.authMode==="key"?a:void 0;const c=document.getElementById("remember-me").checked;const d=document.getElementById("anon-region");const u=d?d.value:"";if(!t||!n){J(m("auth.validationHostUser"),{title:m("auth.incompleteConnection"),variant:"warning"});(k=document.getElementById(t?"username":"host"))==null?void 0:k.focus();return}if(r===null){J(m("auth.validationPort"),{title:m("auth.incompleteConnection"),variant:"warning"});s.focus();return}if(this.authMode==="password"&&!o){J(m("auth.validationPassword"),{title:m("auth.incompleteCredentials"),variant:"warning"});(D=document.getElementById("password"))==null?void 0:D.focus();return}if(this.authMode==="key"&&!a){J(m("auth.validationPrivateKey"),{title:m("auth.incompleteCredentials"),variant:"warning"});(N=document.getElementById("private-key"))==null?void 0:N.focus();return}if(this.turnstileEnabled&&!this.turnstileVerified){J(m("auth.turnstileRequired"),{title:m("auth.verificationRequired"),variant:"warning"});(z=document.getElementById("turnstile-container"))==null?void 0:z.scrollIntoView({behavior:"smooth",block:"center"});return}let f;if(c){f=await f1({host:t,port:r.toString(),username:n,password:h??"",privateKey:l,authMethod:this.authMode==="key"?"publickey":"password"})}const p=localStorage.getItem("cloudssh_recent_connections");let b=[];try{b=p?JSON.parse(p):[];if(!Array.isArray(b))b=[]}catch{}const v=\`\${n}@\${t}:\${r}\`;const R={id:v,host:t,port:r,username:n,authMethod:this.authMode==="key"?"publickey":"password",timestamp:Date.now(),...u?{region:u}:{},...f?{encryptedCred:f}:{}};b=b.filter(K=>K.id!==v);b.unshift(R);if(b.length>5){b=b.slice(0,5)}localStorage.setItem("cloudssh_recent_connections",JSON.stringify(b));this.renderRecentConnections();const L=this.options.getTabManager();const A=\`\${n}@\${t}\`;document.getElementById("auth-section").classList.add("hidden");document.getElementById("terminal-section").classList.remove("hidden");document.getElementById("terminal-section").classList.add("flex");const g=L.createTab(A,{host:t,port:r,username:n});const E=g.terminal;E.mount();try{const K=await C_(t,r);await E.connect({host:t,port:r,username:n,password:h,authMethod:this.authMode==="key"?"publickey":"password",privateKey:l,expectedFingerprint:K||void 0,locationHint:u||void 0})}catch{L.closeTab(g.id);document.getElementById("status-text").innerHTML=\`<span class="w-2 h-2 bg-surface-dot inline-block"></span> \${m("auth.statusOffline")}\`}}}const m1=120;const g1=120;const _1="(max-width: 767px), (max-width: 1180px) and (pointer: coarse)";const v1=new Set( Line truncated
<div class="modal-overlay absolute inset-0" data-share-close></div>
<div class="responsive-modal-panel cyber-box p-6 shadow-2xl relative z-10 w-full max-w-2xl mx-4 max-h-[85vh] overflow-y-auto custom-scrollbar">
<div class="flex items-center justify-between mb-5 pb-4 border-b border-dim">
@@ -257,40 +257,40 @@ export const HTML = `<!doctype html>
<input id="share-created-url" class="terminal-input flex-1 text-xs" readonly>
<button id="share-copy-btn" type="button" class="cyber-button px-3 text-xs">\${m("common.copy")}</button>
</div>
<p class="text-[10px] text-dim mt-2">\${m("share.expiresAt",{time:qs(a.expiresAt??null)})}</p>
<p class="text-[10px] text-dim mt-2">\${m("share.expiresAt",{time:Ks(a.expiresAt??null)})}</p>
\`;document.getElementById("share-created-url").value=a.url;(n=document.getElementById("share-copy-btn"))==null?void 0:n.addEventListener("click",async()=>{const l=await xn(a.url);J(l?m("share.copied"):m("terminal.copyFailed"),{variant:l?"success":"danger"})})}await this.loadShares()}catch(o){J(o instanceof Error?o.message:m("share.createFailed"),{variant:"danger"})}finally{if(e)e.disabled=false}}async loadShares(){const e=document.getElementById("share-list");if(!e)return;e.innerHTML=\`<p class="text-xs text-muted">\${m("common.loading")}</p>\`;try{const t=await fetch(\`/api/servers/\${this.serverId}/shares\`);const s=await t.json();if(!t.ok)throw new Error(Hr(s,"share.loadFailed"));if(s.length===0){e.innerHTML=\`<p class="text-xs text-muted">\${m("share.none")}</p>\`;return}const r=s.filter(a=>a.auditPurgedAt);const n=s.filter(a=>!a.auditPurgedAt);const o=r.length>0?\`<details class="mb-3 border border-[var(--border)] p-2">
<summary class="text-[10px] text-muted cursor-pointer select-none">
\${m("share.auditCleanupLog")}(\${r.length})
</summary>
<div class="space-y-1 mt-2">
\${r.map(a=>\`<div class="text-[10px] text-muted"><span class="text-dim">\${ri(qs(a.auditPurgedAt??null))}</span> \${ri(m("share.auditCleanupStatus",{status:m(\`share.status.\${a.status}\`),time:qs(a.claimedAt??a.createdAt??null)}))} · \${a.auditPurgeType==="auto"?m("share.auditPurgeAuto"):m("share.auditPurgeManual")}</div>\`).join("")}
\${r.map(a=>\`<div class="text-[10px] text-muted"><span class="text-dim">\${ni(Ks(a.auditPurgedAt??null))}</span> \${ni(m("share.auditCleanupStatus",{status:m(\`share.status.\${a.status}\`),time:Ks(a.claimedAt??a.createdAt??null)}))} · \${a.auditPurgeType==="auto"?m("share.auditPurgeAuto"):m("share.auditPurgeManual")}</div>\`).join("")}
</div>
<p class="text-[10px] text-dim mt-1">\${m("share.auditRemovalHint")}</p>
</details>\`:"";e.innerHTML=o+n.map(a=>{const h=["unused","claimed","active"].includes(a.status);return\`<div class="border border-[var(--border)] p-3" data-share-id="\${ri(a.id)}">
</details>\`:"";e.innerHTML=o+n.map(a=>{const h=["unused","claimed","active"].includes(a.status);return\`<div class="border border-[var(--border)] p-3" data-share-id="\${ni(a.id)}">
<div class="flex items-center justify-between gap-3">
<div class="min-w-0">
<div class="text-xs text-on-surface">\${m(\`share.status.\${a.status}\`)}</div>
<div class="text-[10px] text-muted mt-1">\${m("share.createdAt",{time:qs(a.createdAt)})}</div>
<div class="text-[10px] text-muted">\${m("share.expiresAt",{time:qs(a.expiresAt)})}</div>
<div class="text-[10px] text-muted mt-1">\${m("share.createdAt",{time:Ks(a.createdAt)})}</div>
<div class="text-[10px] text-muted">\${m("share.expiresAt",{time:Ks(a.expiresAt)})}</div>
</div>
<div class="flex gap-2 shrink-0">
<button type="button" data-share-audit="\${ri(a.id)}" class="cyber-button px-2 py-1 text-[10px]">\${m("share.audit")}</button>
\${h?\`<button type="button" data-share-revoke="\${ri(a.id)}" class="cyber-button px-2 py-1 text-[10px] text-error">\${m("share.revoke")}</button>\`:""}
<button type="button" data-share-audit="\${ni(a.id)}" class="cyber-button px-2 py-1 text-[10px]">\${m("share.audit")}</button>
\${h?\`<button type="button" data-share-revoke="\${ni(a.id)}" class="cyber-button px-2 py-1 text-[10px] text-error">\${m("share.revoke")}</button>\`:""}
</div>
</div>
</div>\`}).join("");for(const a of e.querySelectorAll("[data-share-audit]")){const h=a.dataset.shareAudit;if(!h)continue;a.addEventListener("click",()=>void this.loadAudit(h,a))}for(const a of e.querySelectorAll("[data-share-revoke]")){const h=a.dataset.shareRevoke;if(!h)continue;a.addEventListener("click",()=>void this.revokeShare(h))}}catch(t){e.innerHTML=\`<p class="text-xs text-error">\${ri(t instanceof Error?t.message:m("share.loadFailed"))}</p>\`}}async revokeShare(e){const t=await Ms({title:m("share.revokeTitle"),message:m("share.revokeMessage"),confirmText:m("share.revoke"),cancelText:m("common.cancel"),variant:"danger"});if(!t)return;const s=await fetch(\`/api/shares/\${encodeURIComponent(e)}\`,{method:"DELETE"});if(!s.ok){const r=await s.json().catch(()=>({}));J(r.error||m("share.revokeFailed"),{variant:"danger"});return}J(m("share.revoked"),{variant:"success"});await this.loadShares()}async loadAudit(e,t){const s=document.getElementById("share-audit-content");const r=document.getElementById("share-audit-meta");const n=document.getElementById("share-audit-actions");if(!s||!r||!n)return;const o=(t==null?void 0:t.textContent)??null;if(t){t.disabled=true;t.textContent=m("common.loading")}r.textContent="";n.innerHTML="";s.innerHTML=\`<p class="text-xs text-muted">\${m("common.loading")}</p>\`;this.showAuditView();try{const{share:a,events:h}=await this.fetchAllAudit(e);const l=p1(h.filter(u=>u.eventType==="terminal.output").map(u=>String(u.details.text??"")).join(""));const c=h.filter(u=>u.eventType!=="terminal.output");const d=(a==null?void 0:a.status)==="closed"||(a==null?void 0:a.status)==="revoked"||(a==null?void 0:a.status)==="expired";r.textContent=\`\${f1(a==null?void 0:a.status)} · \${Math.ceil(((a==null?void 0:a.auditBytes)||0)/1024)} KiB\`;n.innerHTML=\`
</div>\`}).join("");for(const a of e.querySelectorAll("[data-share-audit]")){const h=a.dataset.shareAudit;if(!h)continue;a.addEventListener("click",()=>void this.loadAudit(h,a))}for(const a of e.querySelectorAll("[data-share-revoke]")){const h=a.dataset.shareRevoke;if(!h)continue;a.addEventListener("click",()=>void this.revokeShare(h))}}catch(t){e.innerHTML=\`<p class="text-xs text-error">\${ni(t instanceof Error?t.message:m("share.loadFailed"))}</p>\`}}async revokeShare(e){const t=await Bs({title:m("share.revokeTitle"),message:m("share.revokeMessage"),confirmText:m("share.revoke"),cancelText:m("common.cancel"),variant:"danger"});if(!t)return;const s=await fetch(\`/api/shares/\${encodeURIComponent(e)}\`,{method:"DELETE"});if(!s.ok){const r=await s.json().catch(()=>({}));J(r.error||m("share.revokeFailed"),{variant:"danger"});return}J(m("share.revoked"),{variant:"success"});await this.loadShares()}async loadAudit(e,t){const s=document.getElementById("share-audit-content");const r=document.getElementById("share-audit-meta");const n=document.getElementById("share-audit-actions");if(!s||!r||!n)return;const o=(t==null?void 0:t.textContent)??null;if(t){t.disabled=true;t.textContent=m("common.loading")}r.textContent="";n.innerHTML="";s.innerHTML=\`<p class="text-xs text-muted">\${m("common.loading")}</p>\`;this.showAuditView();try{const{share:a,events:h}=await this.fetchAllAudit(e);const l=R1(h.filter(u=>u.eventType==="terminal.output").map(u=>String(u.details.text??"")).join(""));const c=h.filter(u=>u.eventType!=="terminal.output");const d=(a==null?void 0:a.status)==="closed"||(a==null?void 0:a.status)==="revoked"||(a==null?void 0:a.status)==="expired";r.textContent=\`\${A1(a==null?void 0:a.status)} · \${Math.ceil(((a==null?void 0:a.auditBytes)||0)/1024)} KiB\`;n.innerHTML=\`
<button type="button" data-audit-export class="cyber-button px-2 py-1 text-[10px]">\${m("share.auditExport")}</button>
\${d?\`<button type="button" data-audit-purge class="cyber-button px-2 py-1 text-[10px] text-error">\${m("share.auditPurge")}</button>\`:""}
\`;s.innerHTML=\`
<div class="space-y-1 mb-4 max-h-64 overflow-y-auto custom-scrollbar">
\${c.map(u=>\`<div class="text-[10px] text-muted"><span class="text-dim">\${ri(qs(u.occurredAt))}</span> \${ri(this.describeEvent(u))}</div>\`).join("")||\`<p class="text-xs text-muted">\${m("share.auditNone")}</p>\`}
\${c.map(u=>\`<div class="text-[10px] text-muted"><span class="text-dim">\${ni(Ks(u.occurredAt))}</span> \${ni(this.describeEvent(u))}</div>\`).join("")||\`<p class="text-xs text-muted">\${m("share.auditNone")}</p>\`}
</div>
<h4 class="text-[11px] font-bold text-primary mb-2">\${m("share.terminalRecord")}</h4>
<pre class="bg-[var(--bg)] border border-[var(--border)] p-3 text-[11px] text-on-surface whitespace-pre-wrap break-words max-h-[50vh] overflow-auto custom-scrollbar">\${ri(l||m("share.noTerminalOutput"))}</pre>
\`;for(const u of n.querySelectorAll("[data-audit-export]")){u.addEventListener("click",()=>void this.exportAudit(e))}for(const u of n.querySelectorAll("[data-audit-purge]")){u.addEventListener("click",()=>void this.purgeAudit(e))}}catch(a){s.innerHTML=\`<p class="text-xs text-error">\${ri(a instanceof Error?a.message:m("share.auditFailed"))}</p>\`}finally{if(t){t.disabled=false;t.textContent=o}}}async fetchAllAudit(e){const t=[];let s=[];let r=null;let n=0;let o=true;while(o&&t.length<5e3){const a=await fetch(\`/api/shares/\${encodeURIComponent(e)}/audit?after=\${n}&limit=500\`);const h=await a.json().catch(()=>({}));if(!a.ok||!h.share||!h.events)throw new Error(Hr(h,"share.auditFailed"));r={status:h.share.status,auditBytes:h.share.auditBytes};t.push(...h.events);if(h.removals)s=h.removals;o=h.hasMore===true;const l=h.nextAfter??n;if(l<=n)break;n=l}return{share:r,events:t,removals:s}}async exportAudit(e){try{const{share:t,events:s,removals:r}=await this.fetchAllAudit(e);const n={app:"CloudSSH",kind:"share-audit-export",exportedAt:new Date().toISOString(),shareId:e,status:(t==null?void 0:t.status)??null,auditBytes:(t==null?void 0:t.auditBytes)??0,events:s,auditRemovals:r};const o=new Blob([JSON.stringify(n,null,2)],{type:"application/json"});const a=URL.createObjectURL(o);const h=document.createElement("a");h.href=a;h.download=\`cloudssh-share-audit-\${e}-\${new Date().toISOString().slice(0,10)}.json\`;document.body.appendChild(h);h.click();h.remove();URL.revokeObjectURL(a)}catch{J(m("share.auditFailed"),{variant:"danger"})}}async purgeAudit(e){const t=await Ms({title:m("share.auditPurgeTitle"),message:m("share.auditPurgeMessage"),confirmText:m("share.auditPurge"),cancelText:m("common.cancel"),variant:"danger"});if(!t)return;try{const s=await fetch(\`/api/shares/\${encodeURIComponent(e)}/audit\`,{method:"DELETE"});const r=await s.json().catch(()=>({}));if(!s.ok)throw new Error(Hr(r,"share.auditPurgeFailed"));J(m("share.auditPurged"),{variant:"success"});const n=document.getElementById("share-audit-content");if(n){n.innerHTML=""}this.showListView();await this.loadShares()}catch(s){J(s instanceof Error?s.message:m("share.auditPurgeFailed"),{variant:"danger"})}}describeEvent(e){const t=e.details;if(e.eventType==="sftp.request"||e.eventType==="sftp.result"){const s=String(t.operation||"sftp");const r=String(t.path||t.oldPath||"");let n=m("share.auditRequested");if(e.eventType==="sftp.result"){n=t.success===true?m("share.auditSuccess"):m("share.auditFailure")}return\`SFTP \${s}\${r?\` \${r}\`:""} · \${n}\`}return m(\`share.event.\${e.eventType}\`)}}const fp=9;const g1=6;const _1=3;function v1(i,e){if(i<768)return _1;if(i<=1180&&e)return g1;return fp}function jc(){return v1(window.innerWidth,window.matchMedia("(pointer: coarse)").matches)}function b1(i){const e=[];const t=new Set;for(const s of i.split(/[,,]/)){const r=s.trim().replace(/\\s+/g," ").slice(0,24);const n=r.toLocaleLowerCase();if(!r||t.has(n))continue;t.add(n);e.push(r);if(e.length>=10)break}return e}function y1(i,e,t=""){const s=e.trim().toLocaleLowerCase();return i.filter(r=>{const n=!s||[r.name,r.host,r.username].some(a=>a.toLocaleLowerCase().includes(s));const o=!t||(r.tags||[]).some(a=>a.toLocaleLowerCase()===t.toLocaleLowerCase());return n&&o})}function w1(i,e,t=fp){const s=Math.max(1,Math.ceil(i.length/t));const r=Math.min(Math.max(1,Math.floor(e)),s);const n=(r-1)*t;return{items:i.slice(n,n+t),currentPage:r,totalPages:s}}class S1{constructor(e,t,s){w(this,"user");w(this,"servers",[]);w(this,"onLogout");w(this,"onConnect");w(this,"editingServerId",null);w(this,"editingOriginalAuthMethod",null);w(this,"modalAuthMode","password");w(this,"searchQuery","");w(this,"selectedTag","");w(this,"currentPage",1);w(this,"pageSize",jc());w(this,"sharingEnabled",false);w(this,"shareManager",new m1);this.user=e;this.onLogout=t;this.onConnect=s;$s(()=>this.renderServerGrid());this.init()}async init(){this.renderUserInfo();this.bindEvents();await Promise.all([this.fetchSharingConfig(),this.fetchServers()]);this.renderServerGrid();const e=document.getElementById("user-copyright-year");if(e)e.textContent=new Date().getFullYear().toString()}refreshPageSize(){const e=jc();if(e===this.pageSize)return;this.pageSize=e;this.currentPage=1;this.renderServerGrid()}updateServerOS(e,t){const s=this.servers.find(r=>r.id===e);if(!s||s.os===t)return;s.os=t;this.renderServerGrid()}renderUserInfo(){const e=document.getElementById("user-info");if(!e)return;e.innerHTML="";const t=document.createElement("img");t.src=this.user.avatar_url;t.alt=this.user.username;t.className="user-avatar w-8 h-8";e.appendChild(t);const s=document.createElement("span");s.className="text-xs font-bold tracking-[0.1em] text-muted";s.textContent=this.user.username;e.appendChild(s)}bindEvents(){var s,r,n,o,a,h,l,c,d,u,f,p,b;(s=document.getElementById("logout-btn"))==null?void 0:s.addEventListener("click",()=>this.logout());(r=document.getElementById("add-server-btn"))==null?void 0:r.addEventListe Line truncated
<pre class="bg-[var(--bg)] border border-[var(--border)] p-3 text-[11px] text-on-surface whitespace-pre-wrap break-words max-h-[50vh] overflow-auto custom-scrollbar">\${ni(l||m("share.noTerminalOutput"))}</pre>
\`;for(const u of n.querySelectorAll("[data-audit-export]")){u.addEventListener("click",()=>void this.exportAudit(e))}for(const u of n.querySelectorAll("[data-audit-purge]")){u.addEventListener("click",()=>void this.purgeAudit(e))}}catch(a){s.innerHTML=\`<p class="text-xs text-error">\${ni(a instanceof Error?a.message:m("share.auditFailed"))}</p>\`}finally{if(t){t.disabled=false;t.textContent=o}}}async fetchAllAudit(e){const t=[];let s=[];let r=null;let n=0;let o=true;while(o&&t.length<5e3){const a=await fetch(\`/api/shares/\${encodeURIComponent(e)}/audit?after=\${n}&limit=500\`);const h=await a.json().catch(()=>({}));if(!a.ok||!h.share||!h.events)throw new Error(Hr(h,"share.auditFailed"));r={status:h.share.status,auditBytes:h.share.auditBytes};t.push(...h.events);if(h.removals)s=h.removals;o=h.hasMore===true;const l=h.nextAfter??n;if(l<=n)break;n=l}return{share:r,events:t,removals:s}}async exportAudit(e){try{const{share:t,events:s,removals:r}=await this.fetchAllAudit(e);const n={app:"CloudSSH",kind:"share-audit-export",exportedAt:new Date().toISOString(),shareId:e,status:(t==null?void 0:t.status)??null,auditBytes:(t==null?void 0:t.auditBytes)??0,events:s,auditRemovals:r};const o=new Blob([JSON.stringify(n,null,2)],{type:"application/json"});const a=URL.createObjectURL(o);const h=document.createElement("a");h.href=a;h.download=\`cloudssh-share-audit-\${e}-\${new Date().toISOString().slice(0,10)}.json\`;document.body.appendChild(h);h.click();h.remove();URL.revokeObjectURL(a)}catch{J(m("share.auditFailed"),{variant:"danger"})}}async purgeAudit(e){const t=await Bs({title:m("share.auditPurgeTitle"),message:m("share.auditPurgeMessage"),confirmText:m("share.auditPurge"),cancelText:m("common.cancel"),variant:"danger"});if(!t)return;try{const s=await fetch(\`/api/shares/\${encodeURIComponent(e)}/audit\`,{method:"DELETE"});const r=await s.json().catch(()=>({}));if(!s.ok)throw new Error(Hr(r,"share.auditPurgeFailed"));J(m("share.auditPurged"),{variant:"success"});const n=document.getElementById("share-audit-content");if(n){n.innerHTML=""}this.showListView();await this.loadShares()}catch(s){J(s instanceof Error?s.message:m("share.auditPurgeFailed"),{variant:"danger"})}}describeEvent(e){const t=e.details;if(e.eventType==="sftp.request"||e.eventType==="sftp.result"){const s=String(t.operation||"sftp");const r=String(t.path||t.oldPath||"");let n=m("share.auditRequested");if(e.eventType==="sftp.result"){n=t.success===true?m("share.auditSuccess"):m("share.auditFailure")}return\`SFTP \${s}\${r?\` \${r}\`:""} · \${n}\`}return m(\`share.event.\${e.eventType}\`)}}const vp=9;const B1=6;const I1=3;function P1(i,e){if(i<768)return I1;if(i<=1180&&e)return B1;return vp}function Vc(){return P1(window.innerWidth,window.matchMedia("(pointer: coarse)").matches)}function D1(i){const e=[];const t=new Set;for(const s of i.split(/[,,]/)){const r=s.trim().replace(/\\s+/g," ").slice(0,24);const n=r.toLocaleLowerCase();if(!r||t.has(n))continue;t.add(n);e.push(r);if(e.length>=10)break}return e}function $1(i,e,t=""){const s=e.trim().toLocaleLowerCase();return i.filter(r=>{const n=!s||[r.name,r.host,r.username].some(a=>a.toLocaleLowerCase().includes(s));const o=!t||(r.tags||[]).some(a=>a.toLocaleLowerCase()===t.toLocaleLowerCase());return n&&o})}function O1(i,e,t=vp){const s=Math.max(1,Math.ceil(i.length/t));const r=Math.min(Math.max(1,Math.floor(e)),s);const n=(r-1)*t;return{items:i.slice(n,n+t),currentPage:r,totalPages:s}}class F1{constructor(e,t,s){w(this,"user");w(this,"servers",[]);w(this,"onLogout");w(this,"onConnect");w(this,"editingServerId",null);w(this,"editingOriginalAuthMethod",null);w(this,"modalAuthMode","password");w(this,"searchQuery","");w(this,"selectedTag","");w(this,"currentPage",1);w(this,"pageSize",Vc());w(this,"sharingEnabled",false);w(this,"shareManager",new M1);this.user=e;this.onLogout=t;this.onConnect=s;Os(()=>this.renderServerGrid());this.init()}async init(){this.renderUserInfo();this.bindEvents();await Promise.all([this.fetchSharingConfig(),this.fetchServers()]);this.renderServerGrid();const e=document.getElementById("user-copyright-year");if(e)e.textContent=new Date().getFullYear().toString()}refreshPageSize(){const e=Vc();if(e===this.pageSize)return;this.pageSize=e;this.currentPage=1;this.renderServerGrid()}updateServerOS(e,t){const s=this.servers.find(r=>r.id===e);if(!s||s.os===t)return;s.os=t;this.renderServerGrid()}renderUserInfo(){const e=document.getElementById("user-info");if(!e)return;e.innerHTML="";const t=document.createElement("img");t.src=this.user.avatar_url;t.alt=this.user.username;t.className="user-avatar w-8 h-8";e.appendChild(t);const s=document.createElement("span");s.className="text-xs font-bold tracking-[0.1em] text-muted";s.textContent=this.user.username;e.appendChild(s)}bindEvents(){var s,r,n,o,a,h,l,c,d,u,f,p,b;(s=document.getElementById("logout-btn"))==null?void 0:s.addEventListener("click",()=>this.logout());(r=document.getElementById("add-server-btn"))==null?void 0:r.addEventListe Line truncated
<span class="text-dim">\${m("server.jumpPath")}</span>
<span class="text-on-surface min-w-0 truncate" title="\${this.escapeAttr(c.join(" → "))}">\${c.map(v=>this.escapeHtml(v)).join(" → ")}</span>
</div>\`:"";const u=up(e.host);const f=this.escapeAttr(m("server.clickToCopyIP"));const p=u?\`<button type="button" class="host-ip-badge server-host-badge min-w-0 truncate" id="host-badge-\${e.id}" title="\${f}" aria-label="\${f}">\${this.escapeHtml(u)}:\${e.port}</button>\`:\`<span class="text-on-surface min-w-0 truncate">\${this.escapeHtml(e.host)}:\${e.port}</span>\`;const b=this.sharingEnabled?\`<button id="share-\${e.id}" class="cyber-button text-primary py-1.5 px-3 text-[10px] font-bold tracking-[0.1em] flex items-center justify-center" title="\${m("share.create")}">
</div>\`:"";const u=_p(e.host);const f=this.escapeAttr(m("server.clickToCopyIP"));const p=u?\`<button type="button" class="host-ip-badge server-host-badge min-w-0 truncate" id="host-badge-\${e.id}" title="\${f}" aria-label="\${f}">\${this.escapeHtml(u)}:\${e.port}</button>\`:\`<span class="text-on-surface min-w-0 truncate">\${this.escapeHtml(e.host)}:\${e.port}</span>\`;const b=this.sharingEnabled?\`<button id="share-\${e.id}" class="cyber-button text-primary py-1.5 px-3 text-[10px] font-bold tracking-[0.1em] flex items-center justify-center" title="\${m("share.create")}">
<span class="material-symbols-outlined" style="font-size:14px">share</span>
</button>\`:"";return\`
<div class="server-card p-5 relative group" id="card-\${e.id}">
@@ -348,21 +348,21 @@ export const HTML = `<!doctype html>
\`;s.disabled=true}try{const r=await fetch(\`/api/servers/\${e}/connect\`,{method:"POST"});if(!r.ok){const o=r.headers.get("content-type")||"";if(o.includes("application/json")){const a=await r.json();throw new Error(a.error||"Connection failed")}throw new Error(\`服务器错误 (\${r.status})\`)}const{wsUrl:n}=await r.json();this.onConnect(n,t.name,{host:t.host,port:t.port,username:t.username,serverId:t.id})}catch(r){J(r instanceof Error?r.message:String(r),{title:m("server.connectFailed"),variant:"danger"})}finally{if(s){s.innerHTML=\`
<span class="material-symbols-outlined" style="font-size: 14px;">power_settings_new</span>
\${m("common.connect")}
\`;s.disabled=false}}}async deleteServer(e){const t=this.servers.find(r=>r.id===e);if(!t)return;const s=await Ms({title:m("server.deleteTitle"),message:m("server.deleteMessage",{name:t.name}),confirmText:m("common.delete"),cancelText:m("server.keep"),variant:"danger"});if(!s)return;try{const r=document.getElementById(\`card-\${e}\`);if(r)r.classList.add("removing");const n=await fetch(\`/api/servers/\${e}\`,{method:"DELETE"});if(!n.ok){const o=await n.json().catch(()=>({}));throw new Error(o.error||m("server.deleteFailed",{message:n.status}))}await new Promise(o=>setTimeout(o,300));this.servers=this.servers.filter(o=>o.id!==e);this.renderServerGrid()}catch(r){J(r instanceof Error?r.message:String(r),{title:m("feedback.danger"),variant:"danger"});await this.fetchServers()}}showModal(e,t){this.editingServerId=e==="edit"&&t?t.id:null;this.editingOriginalAuthMethod=e==="edit"&&t?t.auth_method:null;const s=document.getElementById("server-modal");const r=document.getElementById("modal-title");const n=document.getElementById("server-submit-btn");if(!s||!r||!n)return;r.textContent=e==="add"?m("server.add"):m("server.edit");n.innerHTML=\`
\`;s.disabled=false}}}async deleteServer(e){const t=this.servers.find(r=>r.id===e);if(!t)return;const s=await Bs({title:m("server.deleteTitle"),message:m("server.deleteMessage",{name:t.name}),confirmText:m("common.delete"),cancelText:m("server.keep"),variant:"danger"});if(!s)return;try{const r=document.getElementById(\`card-\${e}\`);if(r)r.classList.add("removing");const n=await fetch(\`/api/servers/\${e}\`,{method:"DELETE"});if(!n.ok){const o=await n.json().catch(()=>({}));throw new Error(o.error||m("server.deleteFailed",{message:n.status}))}await new Promise(o=>setTimeout(o,300));this.servers=this.servers.filter(o=>o.id!==e);this.renderServerGrid()}catch(r){J(r instanceof Error?r.message:String(r),{title:m("feedback.danger"),variant:"danger"});await this.fetchServers()}}showModal(e,t){this.editingServerId=e==="edit"&&t?t.id:null;this.editingOriginalAuthMethod=e==="edit"&&t?t.auth_method:null;const s=document.getElementById("server-modal");const r=document.getElementById("modal-title");const n=document.getElementById("server-submit-btn");if(!s||!r||!n)return;r.textContent=e==="add"?m("server.add"):m("server.edit");n.innerHTML=\`
<span class="material-symbols-outlined" style="font-size: 18px;">save</span>
\${e==="add"?m("server.save"):m("server.update")}
\`;this.populateJumpHostSelect((t==null?void 0:t.jump_server_id)??null);if(e==="edit"&&t){document.getElementById("server-name").value=t.name;document.getElementById("server-host").value=t.host;document.getElementById("server-port").value=t.port.toString();document.getElementById("server-username").value=t.username;document.getElementById("server-password").value="";document.getElementById("server-private-key").value="";document.getElementById("server-tags").value=(t.tags||[]).join(", ");if(t.auth_method==="publickey"){this.setModalAuthMode("key")}else{this.setModalAuthMode("password")}const o=document.getElementById("server-region");const a=document.getElementById("server-region-inferred");if(o){Ao(o,t.region||"")}if(a){a.dataset.inferredHint=t.jump_server_id?"":t.inferred_hint||""}}else{document.getElementById("server-name").value="";document.getElementById("server-host").value="";document.getElementById("server-port").value="22";document.getElementById("server-username").value="";document.getElementById("server-password").value="";document.getElementById("server-private-key").value="";document.getElementById("server-tags").value="";this.setModalAuthMode("password");const o=document.getElementById("server-region");const a=document.getElementById("server-region-inferred");if(o)Ao(o,"");if(a)a.dataset.inferredHint=""}this.updateRegionControls();s.classList.remove("hidden");s.classList.add("flex");setTimeout(()=>{var o;(o=document.getElementById("server-name"))==null?void 0:o.focus()},100)}hideModal(){const e=document.getElementById("server-modal");if(e){e.classList.add("hidden");e.classList.remove("flex")}this.editingServerId=null;this.editingOriginalAuthMethod=null}setModalAuthMode(e){this.modalAuthMode=e;const t=document.getElementById("modal-auth-tab-password");const s=document.getElementById("modal-auth-tab-key");const r=document.getElementById("modal-password-section");const n=document.getElementById("modal-key-section");t.classList.toggle("auth-tab-active",e==="password");s.classList.toggle("auth-tab-active",e==="key");r.style.display=e==="password"?"":"none";n.style.display=e==="key"?"":"none"}getJumpPath(e){const t=new Map(this.servers.map(o=>[o.id,o]));const s=[];const r=new Set([e.id]);let n=e.jump_server_id??null;while(n!==null&&s.length<3&&!r.has(n)){r.add(n);const o=t.get(n);if(!o)break;s.unshift(o.name);n=o.jump_server_id??null}return s}populateJumpHostSelect(e){const t=document.getElementById("server-jump-host");if(!t)return;t.innerHTML="";const s=document.createElement("option");s.value="";s.textContent=m("server.jumpHostNone");t.appendChild(s);const r=new Map(this.servers.map(n=>[n.id,n]));for(const n of this.servers){if(n.id===this.editingServerId)continue;const o=new Set;let a=n;let h=0;let l=false;while(a){if(o.has(a.id)||a.id===this.editingServerId){l=true;break}o.add(a.id);h++;if(h>3){l=true;break}a=a.jump_server_id?r.get(a.jump_server_id):void 0}if(l)continue;const c=document.createElement("option");c.value=String(n.id);c.textContent=n.name;t.appendChild(c)}t.value=e?String(e):""}updateRegionControls(){const e=document.getElementById("server-jump-host");const t=document.getElementById("server-region");const s=document.getElementById("server-region-inferred");if(!e||!t||!s)return;const r=e.value!=="";t.disabled=r;t.classList.toggle("cursor-not-allowed",r);t.classList.toggle("opacity-60",r);if(r){t.value="";s.textContent=m("server.regionViaJumpHint");return}const n=s.dataset.inferredHint||"";s.textContent=n?m("server.regionInferred",{region:xa(n)}):""}async handleSubmit(){var b,v,R;const e=document.getElementById("server-name").value.trim();const t=document.getElementById("server-host").value.trim();const s=document.getElementById("server-port");const r=ip(s.value);const n=document.getElementById("server-username").value.trim();const o=document.getElementById("server-password").value;const a=document.getElementById("server-private-key").value;const h=b1(document.getElementById("server-tags").value);const l=((b=document.getElementById("server-jump-host"))==null?void 0:b.value)||"";const c=l?Number(l):null;if(!e||!t||!n){J(m("server.detailsRequired"),{title:m("server.detailsTitle"),variant:"warning"});const L=e?t?"server-username":"server-host":"server-name";(v=document.getElementById(L))==null?void 0:v.focus();return}if(r===null){J(m("auth.validationPort"),{title:m("server.detailsTitle"),variant:"warning"});s.focus();return}const d=this.modalAuthMode==="key"?"publickey":"password";const u=d==="publickey"?a:o;const f=this.editingServerId!==null&&this.editingOriginalAuthMethod!==null&&d!==this.editingOriginalAuthMethod;if((!this.editingServerId||f)&&!u){J(f?m("server.credentialRequiredAfterAuthChange"):m(d==="publickey"?"auth.validationPrivateKey":"auth.validationPassword"),{title:m("auth.incompleteCredentials"),variant:"warning"});const L=d==="publickey"?"server-private-key":"server-password";(R=document.getElementById(L))==null?void 0:R.focus();return}const p=document.getElementById Line truncated
\`;this.populateJumpHostSelect((t==null?void 0:t.jump_server_id)??null);if(e==="edit"&&t){document.getElementById("server-name").value=t.name;document.getElementById("server-host").value=t.host;document.getElementById("server-port").value=t.port.toString();document.getElementById("server-username").value=t.username;document.getElementById("server-password").value="";document.getElementById("server-private-key").value="";document.getElementById("server-tags").value=(t.tags||[]).join(", ");if(t.auth_method==="publickey"){this.setModalAuthMode("key")}else{this.setModalAuthMode("password")}const o=document.getElementById("server-region");const a=document.getElementById("server-region-inferred");if(o){Ro(o,t.region||"")}if(a){a.dataset.inferredHint=t.jump_server_id?"":t.inferred_hint||""}}else{document.getElementById("server-name").value="";document.getElementById("server-host").value="";document.getElementById("server-port").value="22";document.getElementById("server-username").value="";document.getElementById("server-password").value="";document.getElementById("server-private-key").value="";document.getElementById("server-tags").value="";this.setModalAuthMode("password");const o=document.getElementById("server-region");const a=document.getElementById("server-region-inferred");if(o)Ro(o,"");if(a)a.dataset.inferredHint=""}this.updateRegionControls();s.classList.remove("hidden");s.classList.add("flex");setTimeout(()=>{var o;(o=document.getElementById("server-name"))==null?void 0:o.focus()},100)}hideModal(){const e=document.getElementById("server-modal");if(e){e.classList.add("hidden");e.classList.remove("flex")}this.editingServerId=null;this.editingOriginalAuthMethod=null}setModalAuthMode(e){this.modalAuthMode=e;const t=document.getElementById("modal-auth-tab-password");const s=document.getElementById("modal-auth-tab-key");const r=document.getElementById("modal-password-section");const n=document.getElementById("modal-key-section");t.classList.toggle("auth-tab-active",e==="password");s.classList.toggle("auth-tab-active",e==="key");r.style.display=e==="password"?"":"none";n.style.display=e==="key"?"":"none"}getJumpPath(e){const t=new Map(this.servers.map(o=>[o.id,o]));const s=[];const r=new Set([e.id]);let n=e.jump_server_id??null;while(n!==null&&s.length<3&&!r.has(n)){r.add(n);const o=t.get(n);if(!o)break;s.unshift(o.name);n=o.jump_server_id??null}return s}populateJumpHostSelect(e){const t=document.getElementById("server-jump-host");if(!t)return;t.innerHTML="";const s=document.createElement("option");s.value="";s.textContent=m("server.jumpHostNone");t.appendChild(s);const r=new Map(this.servers.map(n=>[n.id,n]));for(const n of this.servers){if(n.id===this.editingServerId)continue;const o=new Set;let a=n;let h=0;let l=false;while(a){if(o.has(a.id)||a.id===this.editingServerId){l=true;break}o.add(a.id);h++;if(h>3){l=true;break}a=a.jump_server_id?r.get(a.jump_server_id):void 0}if(l)continue;const c=document.createElement("option");c.value=String(n.id);c.textContent=n.name;t.appendChild(c)}t.value=e?String(e):""}updateRegionControls(){const e=document.getElementById("server-jump-host");const t=document.getElementById("server-region");const s=document.getElementById("server-region-inferred");if(!e||!t||!s)return;const r=e.value!=="";t.disabled=r;t.classList.toggle("cursor-not-allowed",r);t.classList.toggle("opacity-60",r);if(r){t.value="";s.textContent=m("server.regionViaJumpHint");return}const n=s.dataset.inferredHint||"";s.textContent=n?m("server.regionInferred",{region:ka(n)}):""}async handleSubmit(){var b,v,R;const e=document.getElementById("server-name").value.trim();const t=document.getElementById("server-host").value.trim();const s=document.getElementById("server-port");const r=sp(s.value);const n=document.getElementById("server-username").value.trim();const o=document.getElementById("server-password").value;const a=document.getElementById("server-private-key").value;const h=D1(document.getElementById("server-tags").value);const l=((b=document.getElementById("server-jump-host"))==null?void 0:b.value)||"";const c=l?Number(l):null;if(!e||!t||!n){J(m("server.detailsRequired"),{title:m("server.detailsTitle"),variant:"warning"});const L=e?t?"server-username":"server-host":"server-name";(v=document.getElementById(L))==null?void 0:v.focus();return}if(r===null){J(m("auth.validationPort"),{title:m("server.detailsTitle"),variant:"warning"});s.focus();return}const d=this.modalAuthMode==="key"?"publickey":"password";const u=d==="publickey"?a:o;const f=this.editingServerId!==null&&this.editingOriginalAuthMethod!==null&&d!==this.editingOriginalAuthMethod;if((!this.editingServerId||f)&&!u){J(f?m("server.credentialRequiredAfterAuthChange"):m(d==="publickey"?"auth.validationPrivateKey":"auth.validationPassword"),{title:m("auth.incompleteCredentials"),variant:"warning"});const L=d==="publickey"?"server-private-key":"server-password";(R=document.getElementById(L))==null?void 0:R.focus();return}const p=document.getElementById Line truncated
<span class="material-symbols-outlined animate-spin" style="font-size: 18px;">progress_activity</span>
\${m("server.saving")}
\`;try{const L={name:e,host:t,port:r,username:n,auth_method:d,tags:h,jump_server_id:c};if(u)L.credential=u;const A=document.getElementById("server-region");if(A&&c===null){L.region=A.value||""}let g;if(this.editingServerId){g=await fetch(\`/api/servers/\${this.editingServerId}\`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)})}else{g=await fetch("/api/servers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)})}if(!g.ok){const D=await g.json();throw new Error(D.error||"Save failed")}const E=await g.json();const k=Array.isArray(E._debug)?E._debug.filter(D=>typeof D==="string"):null;if(k){console.log("[locationHint 调试信息]");for(const D of k)console.log(D);this.showDebugNotification(k)}if(!k){if(c===null){const D=E.inferred_hint||null;const N=L.region||null;if(N||D){const z=N||D;J(m("server.savedRegion",{region:xa(z)}),{variant:"success"})}else{J(m("server.savedAuto"),{title:m("feedback.success"),variant:"warning"})}}else{J(m("server.savedViaJump"),{variant:"success"})}}this.hideModal();await this.fetchServers()}catch(L){J(L instanceof Error?L.message:String(L),{title:m("feedback.danger"),variant:"danger"})}finally{p.disabled=false;p.innerHTML=\`
\`;try{const L={name:e,host:t,port:r,username:n,auth_method:d,tags:h,jump_server_id:c};if(u)L.credential=u;const A=document.getElementById("server-region");if(A&&c===null){L.region=A.value||""}let g;if(this.editingServerId){g=await fetch(\`/api/servers/\${this.editingServerId}\`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)})}else{g=await fetch("/api/servers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(L)})}if(!g.ok){const D=await g.json();throw new Error(D.error||"Save failed")}const E=await g.json();const k=Array.isArray(E._debug)?E._debug.filter(D=>typeof D==="string"):null;if(k){console.log("[locationHint 调试信息]");for(const D of k)console.log(D);this.showDebugNotification(k)}if(!k){if(c===null){const D=E.inferred_hint||null;const N=L.region||null;if(N||D){const z=N||D;J(m("server.savedRegion",{region:ka(z)}),{variant:"success"})}else{J(m("server.savedAuto"),{title:m("feedback.success"),variant:"warning"})}}else{J(m("server.savedViaJump"),{variant:"success"})}}this.hideModal();await this.fetchServers()}catch(L){J(L instanceof Error?L.message:String(L),{title:m("feedback.danger"),variant:"danger"})}finally{p.disabled=false;p.innerHTML=\`
<span class="material-symbols-outlined" style="font-size: 18px;">save</span>
\${this.editingServerId?m("server.update"):m("server.save")}
\`}}showDebugNotification(e){const t=document.createElement("div");t.className="fixed bottom-4 right-4 z-[200] max-w-md p-4 rounded-lg shadow-2xl border border-[var(--accent)] bg-[var(--bg-surface)] text-[var(--text)] font-mono text-[11px] leading-relaxed custom-scrollbar";t.style.maxHeight="300px";t.style.overflowY="auto";const s=document.createElement("div");s.className="text-[var(--accent)] font-bold mb-2 text-xs";s.textContent="[locationHint 调试信息]";t.appendChild(s);const r=document.createElement("div");r.className="text-muted whitespace-pre-wrap";r.textContent=e.join("\\n");t.appendChild(r);const n=document.createElement("button");n.className="absolute top-2 right-2 text-muted hover:text-[var(--accent)] cursor-pointer";n.innerHTML='<span class="material-symbols-outlined" style="font-size: 16px;">close</span>';n.onclick=()=>t.remove();t.appendChild(n);document.body.appendChild(t);setTimeout(()=>{if(t.parentNode){t.style.transition="opacity 0.3s";t.style.opacity="0";setTimeout(()=>t.remove(),300)}},8e3)}async logout(){try{await fetch("/api/auth/logout",{method:"POST"})}catch{}this.onLogout()}escapeHtml(e){const t=document.createElement("div");t.textContent=e;return t.innerHTML}escapeAttr(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}}const x1="v1";const C1=58e3;function k1(i,e,t){return\`cloudssh-resume:\${x1}:\${i}:\${e}:\${t}\`}const E1="cloudssh_device_identity";const T1=1;const tr="keys";const Vc="share-device-signing-v1";function Nh(){return typeof crypto!=="undefined"&&typeof crypto.subtle!=="undefined"&&typeof crypto.subtle.generateKey==="function"&&typeof indexedDB!=="undefined"}function L1(){return new Promise((i,e)=>{const t=indexedDB.open(E1,T1);t.onupgradeneeded=()=>{if(!t.result.objectStoreNames.contains(tr)){t.result.createObjectStore(tr)}};t.onsuccess=()=>i(t.result);t.onerror=()=>e(t.error??new Error("IndexedDB open failed"))})}async function pp(){const i=await L1();try{const e=await new Promise((s,r)=>{const n=i.transaction(tr,"readonly");const o=n.objectStore(tr).get(Vc);o.onsuccess=()=>s(o.result);o.onerror=()=>r(o.error??new Error("IndexedDB read failed"))});if((e==null?void 0:e.publicKey)&&(e==null?void 0:e.privateKey))return e;const t=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},false,["sign","verify"]);await new Promise((s,r)=>{const n=i.transaction(tr,"readwrite");n.objectStore(tr).put(t,Vc);n.oncomplete=()=>s();n.onerror=()=>r(n.error??new Error("IndexedDB write failed"));n.onabort=()=>r(n.error??new Error("IndexedDB write aborted"))});return t}finally{i.close()}}function mp(i){const e=new Uint8Array(i);let t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t).replace(/\\+/g,"-").replace(/\\//g,"_").replace(/=+$/g,"")}function A1(){const i=crypto.getRandomValues(new Uint8Array(16));let e="";for(let t=0;t<i.length;t++)e+=i[t].toString(16).padStart(2,"0");return e}async function R1(){if(!Nh())return null;try{const i=await Gc();if(!i)return null;const e=await Gc();if(!e||e!==i)return null;return i}catch{return null}}async function Gc(){const{publicKey:i}=await pp();const e=await crypto.subtle.exportKey("spki",i);return mp(e)}async function M1(i){if(!Nh())return null;try{const{privateKey:e}=await pp();const t=A1();const s=Date.now();const r=k1(i,t,s);const n=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,new TextEncoder().encode(r));return{nonce:t,timestamp:s,signature:mp(n)}}catch{return null}}function B1(i){var e;return((e=i.match(/^#\\/share\\/([A-Za-z0-9_-]{40,128})$/))==null?void 0:e[1])??null}function I1(){const i=B1(window.location.hash);if(!i)return null;history.replaceState(null,"",\`\${window.location.pathname}\${window.location.search}\`);return i}function nt(i,e,t){const s=document.createElement(i);if(e)s.className=e;if(t!==void 0)s.textContent=t;return s}function Bl(i,e){const t=document.createElement("span");t.className=\`material-symbols-outlined\${e?" animate-spin":""}\`;t.style.fontSize="18px";t.textContent=e?"progress_activity":"login";const s=document.createElement("span");s.textContent=e?m("share.claiming"):m("share.claimAndConnect");i.replaceChildren(t,s)}function P1(){var a;const i=nt("main","w-full max-w-lg relative z-10");i.id="share-landing-card";const e=nt("div","mb-8 text-center");e.append(nt("div","text-3xl font-bold text-primary tracking-tighter mb-2","CloudSSH"));i.append(e);const t=nt("div","cyber-box p-6 shadow-2xl relative");t.append(nt("div","theme-accent-line absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-transparent via-[var(--accent)] to-transparent opacity-50"));const s=nt("div","flex items-center justify-between mb-5 pb-4 border-b border-dim");s.append(nt("span","text-sm font-bold text-primary",m("share.accessTitle")));s.append(nt("div",void 0));(a=s.lastElementChild)==null?void 0:a.setAttribute("data-language-switcher","");t.append(s);t.append(nt("p","text-sm text-on-surface mb-4",m("share.accessDescription")));const r Line truncated
]\`).replace("lheading",kp).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()};var B0=/^\\\\([!"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_\`{|}~])/;var I0=/^(\`+)([^\`]|[^\`][\\s\\S]*?[^\`])\\1(?!\`)/;var Tp=/^( {2,}|\\\\)\\n(?!\\s*$)/;var P0=/^(\`+|[^\`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[\`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/;var mr=/[\\p{P}\\p{S}]/u;var Xo=/[\\s\\p{P}\\p{S}]/u;var Vh=/[^\\s\\p{P}\\p{S}]/u;var D0=he(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Xo).getRegex();var Lp=/(?!~)[\\p{P}\\p{S}]/u;var $0=/(?!~)[\\s\\p{P}\\p{S}]/u;var O0=/(?:[^\\s\\p{P}\\p{S}]|~)/u;var F0=he(/link|precode-code|html/,"g").replace("link",/\\[(?:[^\\[\\]\`]|(?<a>\`+)[^\`]+\\k<a>(?!\`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/).replace("precode-",b0?"(?<!\`)()":"(^^|[^\`])").replace("code",/(?<b>\`+)[^\`]+\\k<b>(?!\`)/).replace("html",/<(?! )[^<>]*?>/).getRegex();var Ap=/^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/;var z0=he(Ap,"u").replace(/punct/g,mr).getRegex();var N0=he(Ap,"u").replace(/punct/g,Lp).getRegex();var Rp="^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)";var H0=he(Rp,"gu").replace(/notPunctSpace/g,Vh).replace(/punctSpace/g,Xo).replace(/punct/g,mr).getRegex();var W0=he(Rp,"gu").replace(/notPunctSpace/g,O0).replace(/punctSpace/g,$0).replace(/punct/g,Lp).getRegex();var U0=he("^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Vh).replace(/punctSpace/g,Xo).replace(/punct/g,mr).getRegex();var q0=he(/^~~?(?:((?!~)punct)|[^\\s~])/,"u").replace(/punct/g,mr).getRegex();var K0="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)";var j0=he(K0,"gu").replace(/notPunctSpace/g,Vh).replace(/punctSpace/g,Xo).replace(/punct/g,mr).getRegex();var V0=he(/\\\\(punct)/,"gu").replace(/punct/g,mr).getRegex();var G0=he(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_\`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();var Y0=he(Kh).replace("(?:-->|$)","-->").getRegex();var X0=he("^comment|^</[a-zA-Z][\\\\w:-]*\\\\s*>|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>|^<\\\\?[\\\\s\\\\S]*?\\\\?>|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>").replace("comment",Y0).replace("attribute",/\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*"[^"]*"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s"'=<>\`]+)?/).getRegex();var Mo=/(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|\`+(?!\`)[^\`]*?\`+(?!\`)|\`\`+(?=\\])|[^\\[\\]\\\\\`])*?/;var Z0=he(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?\\s*\\)/).replace("label",Mo).replace("href",/<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/).replace("title",/"(?:\\\\"?|[^"\\\\])*"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex();var Mp=he(/^!?\\[(label)\\]\\[(ref)\\]/).replace("label",Mo).replace("ref",qh).getRegex();var Bp=he(/^!?\\[(ref)\\](?:\\[\\])?/).replace("ref",qh).getRegex();var J0=he("reflink|nolink(?!\\\\()","g").replace("reflink",Mp).replace("nolink",Bp).getRegex();var pd=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;var Gh={_backpedal:vs,anyPunctuation:V0,autolink:G0,blockSkip:F0,br:Tp,code:I0,del:vs,delLDelim:vs,delRDelim:vs,emStrongLDelim:z0,emStrongRDelimAst:H0,emStrongRDelimUnd:U0,escape:B0,link:Z0,nolink:Bp,punctuation:D0,reflink:Mp,reflinkSearch:J0,tag:X0,text:P0,url:vs};var Q0={...Gh,link:he(/^!?\\[(label)\\]\\((.*?)\\)/).replace("label",Mo).getRegex(),reflink:he(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace("label",Mo).getRegex()};var Dl={...Gh,emStrongRDelimAst:W0,emStrongLDelim:N0,delLDelim:q0,delRDelim:j0,url:he(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace("protocol",pd).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,text:he(/^([\`~]+|[^\`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_\`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[\`*~_]|\\b_|protocol:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&'*+\\/=?_\`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_\`{\\|} Line truncated
\`}}showDebugNotification(e){const t=document.createElement("div");t.className="fixed bottom-4 right-4 z-[200] max-w-md p-4 rounded-lg shadow-2xl border border-[var(--accent)] bg-[var(--bg-surface)] text-[var(--text)] font-mono text-[11px] leading-relaxed custom-scrollbar";t.style.maxHeight="300px";t.style.overflowY="auto";const s=document.createElement("div");s.className="text-[var(--accent)] font-bold mb-2 text-xs";s.textContent="[locationHint 调试信息]";t.appendChild(s);const r=document.createElement("div");r.className="text-muted whitespace-pre-wrap";r.textContent=e.join("\\n");t.appendChild(r);const n=document.createElement("button");n.className="absolute top-2 right-2 text-muted hover:text-[var(--accent)] cursor-pointer";n.innerHTML='<span class="material-symbols-outlined" style="font-size: 16px;">close</span>';n.onclick=()=>t.remove();t.appendChild(n);document.body.appendChild(t);setTimeout(()=>{if(t.parentNode){t.style.transition="opacity 0.3s";t.style.opacity="0";setTimeout(()=>t.remove(),300)}},8e3)}async logout(){try{await fetch("/api/auth/logout",{method:"POST"})}catch{}this.onLogout()}escapeHtml(e){const t=document.createElement("div");t.textContent=e;return t.innerHTML}escapeAttr(e){return e.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}}const z1="v1";const N1=58e3;function H1(i,e,t){return\`cloudssh-resume:\${z1}:\${i}:\${e}:\${t}\`}const W1="cloudssh_device_identity";const U1=1;const ir="keys";const Gc="share-device-signing-v1";function Hh(){return typeof crypto!=="undefined"&&typeof crypto.subtle!=="undefined"&&typeof crypto.subtle.generateKey==="function"&&typeof indexedDB!=="undefined"}function q1(){return new Promise((i,e)=>{const t=indexedDB.open(W1,U1);t.onupgradeneeded=()=>{if(!t.result.objectStoreNames.contains(ir)){t.result.createObjectStore(ir)}};t.onsuccess=()=>i(t.result);t.onerror=()=>e(t.error??new Error("IndexedDB open failed"))})}async function bp(){const i=await q1();try{const e=await new Promise((s,r)=>{const n=i.transaction(ir,"readonly");const o=n.objectStore(ir).get(Gc);o.onsuccess=()=>s(o.result);o.onerror=()=>r(o.error??new Error("IndexedDB read failed"))});if((e==null?void 0:e.publicKey)&&(e==null?void 0:e.privateKey))return e;const t=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},false,["sign","verify"]);await new Promise((s,r)=>{const n=i.transaction(ir,"readwrite");n.objectStore(ir).put(t,Gc);n.oncomplete=()=>s();n.onerror=()=>r(n.error??new Error("IndexedDB write failed"));n.onabort=()=>r(n.error??new Error("IndexedDB write aborted"))});return t}finally{i.close()}}function yp(i){const e=new Uint8Array(i);let t="";for(let s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return btoa(t).replace(/\\+/g,"-").replace(/\\//g,"_").replace(/=+$/g,"")}function K1(){const i=crypto.getRandomValues(new Uint8Array(16));let e="";for(let t=0;t<i.length;t++)e+=i[t].toString(16).padStart(2,"0");return e}async function j1(){if(!Hh())return null;try{const i=await Yc();if(!i)return null;const e=await Yc();if(!e||e!==i)return null;return i}catch{return null}}async function Yc(){const{publicKey:i}=await bp();const e=await crypto.subtle.exportKey("spki",i);return yp(e)}async function V1(i){if(!Hh())return null;try{const{privateKey:e}=await bp();const t=K1();const s=Date.now();const r=H1(i,t,s);const n=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},e,new TextEncoder().encode(r));return{nonce:t,timestamp:s,signature:yp(n)}}catch{return null}}function G1(i){var e;return((e=i.match(/^#\\/share\\/([A-Za-z0-9_-]{40,128})$/))==null?void 0:e[1])??null}function Y1(){const i=G1(window.location.hash);if(!i)return null;history.replaceState(null,"",\`\${window.location.pathname}\${window.location.search}\`);return i}function nt(i,e,t){const s=document.createElement(i);if(e)s.className=e;if(t!==void 0)s.textContent=t;return s}function Il(i,e){const t=document.createElement("span");t.className=\`material-symbols-outlined\${e?" animate-spin":""}\`;t.style.fontSize="18px";t.textContent=e?"progress_activity":"login";const s=document.createElement("span");s.textContent=e?m("share.claiming"):m("share.claimAndConnect");i.replaceChildren(t,s)}function X1(){var a;const i=nt("main","w-full max-w-lg relative z-10");i.id="share-landing-card";const e=nt("div","mb-8 text-center");e.append(nt("div","text-3xl font-bold text-primary tracking-tighter mb-2","CloudSSH"));i.append(e);const t=nt("div","cyber-box p-6 shadow-2xl relative");t.append(nt("div","theme-accent-line absolute top-0 left-0 w-full h-1 bg-gradient-to-r from-transparent via-[var(--accent)] to-transparent opacity-50"));const s=nt("div","flex items-center justify-between mb-5 pb-4 border-b border-dim");s.append(nt("span","text-sm font-bold text-primary",m("share.accessTitle")));s.append(nt("div",void 0));(a=s.lastElementChild)==null?void 0:a.setAttribute("data-language-switcher","");t.append(s);t.append(nt("p","text-sm text-on-surface mb-4",m("share.accessDescription")));const r Line truncated
]\`).replace("lheading",Rp).replace("|table","").replace("blockquote"," {0,3}>").replace("|fences","").replace("|list","").replace("|html","").replace("|tag","").getRegex()};var G0=/^\\\\([!"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_\`{|}~])/;var Y0=/^(\`+)([^\`]|[^\`][\\s\\S]*?[^\`])\\1(?!\`)/;var Bp=/^( {2,}|\\\\)\\n(?!\\s*$)/;var X0=/^(\`+|[^\`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[\`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/;var mr=/[\\p{P}\\p{S}]/u;var Jo=/[\\s\\p{P}\\p{S}]/u;var Gh=/[^\\s\\p{P}\\p{S}]/u;var Z0=he(/^((?![*_])punctSpace)/,"u").replace(/punctSpace/g,Jo).getRegex();var Ip=/(?!~)[\\p{P}\\p{S}]/u;var J0=/(?!~)[\\s\\p{P}\\p{S}]/u;var Q0=/(?:[^\\s\\p{P}\\p{S}]|~)/u;var ev=he(/link|precode-code|html/,"g").replace("link",/\\[(?:[^\\[\\]\`]|(?<a>\`+)[^\`]+\\k<a>(?!\`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/).replace("precode-",D0?"(?<!\`)()":"(^^|[^\`])").replace("code",/(?<b>\`+)[^\`]+\\k<b>(?!\`)/).replace("html",/<(?! )[^<>]*?>/).getRegex();var Pp=/^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/;var tv=he(Pp,"u").replace(/punct/g,mr).getRegex();var iv=he(Pp,"u").replace(/punct/g,Ip).getRegex();var Dp="^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)";var sv=he(Dp,"gu").replace(/notPunctSpace/g,Gh).replace(/punctSpace/g,Jo).replace(/punct/g,mr).getRegex();var rv=he(Dp,"gu").replace(/notPunctSpace/g,Q0).replace(/punctSpace/g,J0).replace(/punct/g,Ip).getRegex();var nv=he("^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)","gu").replace(/notPunctSpace/g,Gh).replace(/punctSpace/g,Jo).replace(/punct/g,mr).getRegex();var ov=he(/^~~?(?:((?!~)punct)|[^\\s~])/,"u").replace(/punct/g,mr).getRegex();var av="^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)";var lv=he(av,"gu").replace(/notPunctSpace/g,Gh).replace(/punctSpace/g,Jo).replace(/punct/g,mr).getRegex();var hv=he(/\\\\(punct)/,"gu").replace(/punct/g,mr).getRegex();var cv=he(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/).replace("scheme",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace("email",/[a-zA-Z0-9.!#$%&'*+/=?^_\`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex();var dv=he(jh).replace("(?:-->|$)","-->").getRegex();var uv=he("^comment|^</[a-zA-Z][\\\\w:-]*\\\\s*>|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>|^<\\\\?[\\\\s\\\\S]*?\\\\?>|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>").replace("comment",dv).replace("attribute",/\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*"[^"]*"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s"'=<>\`]+)?/).getRegex();var Io=/(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|\`+(?!\`)[^\`]*?\`+(?!\`)|\`\`+(?=\\])|[^\\[\\]\\\\\`])*?/;var fv=he(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?\\s*\\)/).replace("label",Io).replace("href",/<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]*/).replace("title",/"(?:\\\\"?|[^"\\\\])*"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex();var $p=he(/^!?\\[(label)\\]\\[(ref)\\]/).replace("label",Io).replace("ref",Kh).getRegex();var Op=he(/^!?\\[(ref)\\](?:\\[\\])?/).replace("ref",Kh).getRegex();var pv=he("reflink|nolink(?!\\\\()","g").replace("reflink",$p).replace("nolink",Op).getRegex();var md=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/;var Yh={_backpedal:vs,anyPunctuation:hv,autolink:cv,blockSkip:ev,br:Bp,code:Y0,del:vs,delLDelim:vs,delRDelim:vs,emStrongLDelim:tv,emStrongRDelimAst:sv,emStrongRDelimUnd:nv,escape:G0,link:fv,nolink:Op,punctuation:Z0,reflink:$p,reflinkSearch:pv,tag:uv,text:X0,url:vs};var mv={...Yh,link:he(/^!?\\[(label)\\]\\((.*?)\\)/).replace("label",Io).getRegex(),reflink:he(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace("label",Io).getRegex()};var $l={...Yh,emStrongRDelimAst:rv,emStrongLDelim:iv,delLDelim:ov,delRDelim:lv,url:he(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace("protocol",md).replace("email",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'"~)]+(?!$))+/,del:/^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,text:he(/^([\`~]+|[^\`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_\`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[\`*~_]|\\b_|protocol:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&'*+\\/=?_\`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_\`{\\|} Line truncated
\`),t=e.length-1;for(;t>=0&&mt.blankLine.test(e[t]);)t--;return e.length-t<=2?i:e.slice(0,t+1).join(\`
\`)}function iv(i,e){if(i.indexOf(e[1])===-1)return-1;let t=0;for(let s=0;s<i.length;s++)if(i[s]==="\\\\")s++;else if(i[s]===e[0])t++;else if(i[s]===e[1]&&(t--,t<0))return s;return t>0?-2:-1}function sv(i,e=0){let t=e,s="";for(let r of i)if(r===" "){let n=4-t%4;s+=" ".repeat(n),t+=n}else s+=r,t++;return s}function bd(i,e,t,s,r){let n=e.href,o=e.title||null,a=i[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=true;let h={type:i[0].charAt(0)==="!"?"image":"link",raw:t,href:n,title:o,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=false,h}function rv(i,e,t){let s=i.match(t.other.indentCodeCompensation);if(s===null)return e;let r=s[1];return e.split(\`
\`)}function vv(i,e){if(i.indexOf(e[1])===-1)return-1;let t=0;for(let s=0;s<i.length;s++)if(i[s]==="\\\\")s++;else if(i[s]===e[0])t++;else if(i[s]===e[1]&&(t--,t<0))return s;return t>0?-2:-1}function bv(i,e=0){let t=e,s="";for(let r of i)if(r===" "){let n=4-t%4;s+=" ".repeat(n),t+=n}else s+=r,t++;return s}function yd(i,e,t,s,r){let n=e.href,o=e.title||null,a=i[1].replace(r.other.outputLinkReplace,"$1");s.state.inLink=true;let h={type:i[0].charAt(0)==="!"?"image":"link",raw:t,href:n,title:o,text:a,tokens:s.inlineTokens(a)};return s.state.inLink=false,h}function yv(i,e,t){let s=i.match(t.other.indentCodeCompensation);if(s===null)return e;let r=s[1];return e.split(\`
\`).map(n=>{let o=n.match(t.other.beginningSpace);if(o===null)return n;let[a]=o;return a.length>=r.length?n.slice(r.length):n}).join(\`
\`)}var Bo=class ox{constructor(e){w(this,"options");w(this,"rules");w(this,"lexer");this.options=e||Os}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let s=this.options.pedantic?t[0]:vd(t[0]),r=s.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:s,codeBlockStyle:"indented",text:r}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let s=t[0],r=rv(s,t[3]||"",this.rules);return{type:"code",raw:s,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let s=t[2].trim();if(this.rules.other.endingHash.test(s)){let r=qi(s,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(s=r.trim())}return{type:"heading",raw:qi(t[0],\`
\`)}var Po=class Sx{constructor(e){w(this,"options");w(this,"rules");w(this,"lexer");this.options=e||Fs}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:"space",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let s=this.options.pedantic?t[0]:bd(t[0]),r=s.replace(this.rules.other.codeRemoveIndent,"");return{type:"code",raw:s,codeBlockStyle:"indented",text:r}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let s=t[0],r=yv(s,t[3]||"",this.rules);return{type:"code",raw:s,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,"$1"):t[2],text:r}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let s=t[2].trim();if(this.rules.other.endingHash.test(s)){let r=qi(s,"#");(this.options.pedantic||!r||this.rules.other.endingSpaceChar.test(r))&&(s=r.trim())}return{type:"heading",raw:qi(t[0],\`
\`),depth:t[1].length,text:s,tokens:this.lexer.inline(s)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:"hr",raw:qi(t[0],\`
\`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let s=qi(t[0],\`
\`).split(\`
@@ -375,19 +375,19 @@ export const HTML = `<!doctype html>
\`),v=this.blockquote(b);o[o.length-1]=v,r=r.substring(0,r.length-p.raw.length)+v.raw,n=n.substring(0,n.length-p.text.length)+v.text;break}else if((f==null?void 0:f.type)==="list"){let p=f,b=p.raw+\`
\`+s.join(\`
\`),v=this.list(b);o[o.length-1]=v,r=r.substring(0,r.length-f.raw.length)+v.raw,n=n.substring(0,n.length-p.raw.length)+v.raw,s=b.substring(o.at(-1).raw.length).split(\`
\`);continue}}return{type:"blockquote",raw:r,tokens:o,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let s=t[1].trim(),r=s.length>1,n={type:"list",raw:"",ordered:r,start:r?+s.slice(0,-1):"",loose:false,items:[]};s=r?\`\\\\d{1,9}\\\\\${s.slice(-1)}\`:\`\\\\\${s}\`,this.options.pedantic&&(s=r?s:"[*+-]");let o=this.rules.other.listItemRegex(s),a=false;for(;e;){let l=false,c="",d="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let u=sv(t[2].split(\`
\`);continue}}return{type:"blockquote",raw:r,tokens:o,text:n}}}list(e){let t=this.rules.block.list.exec(e);if(t){let s=t[1].trim(),r=s.length>1,n={type:"list",raw:"",ordered:r,start:r?+s.slice(0,-1):"",loose:false,items:[]};s=r?\`\\\\d{1,9}\\\\\${s.slice(-1)}\`:\`\\\\\${s}\`,this.options.pedantic&&(s=r?s:"[*+-]");let o=this.rules.other.listItemRegex(s),a=false;for(;e;){let l=false,c="",d="";if(!(t=o.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let u=bv(t[2].split(\`
\`,1)[0],t[1].length),f=e.split(\`
\`,1)[0],p=!u.trim(),b=0;if(this.options.pedantic?(b=2,d=u.trimStart()):p?b=t[1].length+1:(b=u.search(this.rules.other.nonSpaceChar),b=b>4?1:b,d=u.slice(b),b+=t[1].length),p&&this.rules.other.blankLine.test(f)&&(c+=f+\`
\`,e=e.substring(f.length+1),l=true),!l){let v=this.rules.other.nextBulletRegex(b),R=this.rules.other.hrRegex(b),L=this.rules.other.fencesBeginRegex(b),A=this.rules.other.headingBeginRegex(b),g=this.rules.other.htmlBeginRegex(b),E=this.rules.other.blockquoteBeginRegex(b);for(;e;){let k=e.split(\`
\`,1)[0],D;if(f=k,this.options.pedantic?(f=f.replace(this.rules.other.listReplaceNesting," "),D=f):D=f.replace(this.rules.other.tabCharGlobal," "),L.test(f)||A.test(f)||g.test(f)||E.test(f)||v.test(f)||R.test(f))break;if(D.search(this.rules.other.nonSpaceChar)>=b||!f.trim())d+=\`
\`+D.slice(b);else{if(p||u.replace(this.rules.other.tabCharGlobal," ").search(this.rules.other.nonSpaceChar)>=4||L.test(u)||A.test(u)||R.test(u))break;d+=\`
\`+f}p=!f.trim(),c+=k+\`
\`,e=e.substring(k.length+1),u=D.slice(b)}}n.loose||(a?n.loose=true:this.rules.other.doubleBlankLine.test(c)&&(a=true)),n.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:false,text:d,tokens:[]}),n.raw+=c}let h=n.items.at(-1);if(h)h.raw=h.raw.trimEnd(),h.text=h.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let l of n.items){this.lexer.state.top=false,l.tokens=this.lexer.blockTokens(l.text,[]);let c=l.tokens[0];if(l.task&&((c==null?void 0:c.type)==="text"||(c==null?void 0:c.type)==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let u=this.lexer.inlineQueue.length-1;u>=0;u--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[u].src)){this.lexer.inlineQueue[u].src=this.lexer.inlineQueue[u].src.replace(this.rules.other.listReplaceTask,"");break}let d=this.rules.other.listTaskCheckbox.exec(l.raw);if(d){let u={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};l.checked=u.checked,n.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=u.raw+l.tokens[0].raw,l.tokens[0].text=u.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(u)):l.tokens.unshift({type:"paragraph",raw:u.raw,text:u.raw,tokens:[u]}):l.tokens.unshift(u)}}else l.task&&(l.task=false);if(!n.loose){let d=l.tokens.filter(f=>f.type==="space"),u=d.length>0&&d.some(f=>this.rules.other.anyLine.test(f.raw));n.loose=u}}if(n.loose)for(let l of n.items){l.loose=true;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let s=vd(t[0]);return{type:"html",block:true,raw:s,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:s}}}def(e){let t=this.rules.block.def.exec(e);if(t){let s=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:s,raw:qi(t[0],\`
\`),href:r,title:n}}}table(e){var a;let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let s=_d(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=((a=t[3])==null?void 0:a.trim())?t[3].replace(this.rules.other.tableRowBlankLine,"").split(\`
\`,e=e.substring(k.length+1),u=D.slice(b)}}n.loose||(a?n.loose=true:this.rules.other.doubleBlankLine.test(c)&&(a=true)),n.items.push({type:"list_item",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(d),loose:false,text:d,tokens:[]}),n.raw+=c}let h=n.items.at(-1);if(h)h.raw=h.raw.trimEnd(),h.text=h.text.trimEnd();else return;n.raw=n.raw.trimEnd();for(let l of n.items){this.lexer.state.top=false,l.tokens=this.lexer.blockTokens(l.text,[]);let c=l.tokens[0];if(l.task&&((c==null?void 0:c.type)==="text"||(c==null?void 0:c.type)==="paragraph")){l.text=l.text.replace(this.rules.other.listReplaceTask,""),c.raw=c.raw.replace(this.rules.other.listReplaceTask,""),c.text=c.text.replace(this.rules.other.listReplaceTask,"");for(let u=this.lexer.inlineQueue.length-1;u>=0;u--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[u].src)){this.lexer.inlineQueue[u].src=this.lexer.inlineQueue[u].src.replace(this.rules.other.listReplaceTask,"");break}let d=this.rules.other.listTaskCheckbox.exec(l.raw);if(d){let u={type:"checkbox",raw:d[0]+" ",checked:d[0]!=="[ ]"};l.checked=u.checked,n.loose?l.tokens[0]&&["paragraph","text"].includes(l.tokens[0].type)&&"tokens"in l.tokens[0]&&l.tokens[0].tokens?(l.tokens[0].raw=u.raw+l.tokens[0].raw,l.tokens[0].text=u.raw+l.tokens[0].text,l.tokens[0].tokens.unshift(u)):l.tokens.unshift({type:"paragraph",raw:u.raw,text:u.raw,tokens:[u]}):l.tokens.unshift(u)}}else l.task&&(l.task=false);if(!n.loose){let d=l.tokens.filter(f=>f.type==="space"),u=d.length>0&&d.some(f=>this.rules.other.anyLine.test(f.raw));n.loose=u}}if(n.loose)for(let l of n.items){l.loose=true;for(let c of l.tokens)c.type==="text"&&(c.type="paragraph")}return n}}html(e){let t=this.rules.block.html.exec(e);if(t){let s=bd(t[0]);return{type:"html",block:true,raw:s,pre:t[1]==="pre"||t[1]==="script"||t[1]==="style",text:s}}}def(e){let t=this.rules.block.def.exec(e);if(t){let s=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal," "),r=t[2]?t[2].replace(this.rules.other.hrefBrackets,"$1").replace(this.rules.inline.anyPunctuation,"$1"):"",n=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,"$1"):t[3];return{type:"def",tag:s,raw:qi(t[0],\`
\`),href:r,title:n}}}table(e){var a;let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let s=vd(t[1]),r=t[2].replace(this.rules.other.tableAlignChars,"").split("|"),n=((a=t[3])==null?void 0:a.trim())?t[3].replace(this.rules.other.tableRowBlankLine,"").split(\`
\`):[],o={type:"table",raw:qi(t[0],\`
\`),header:[],align:[],rows:[]};if(s.length===r.length){for(let h of r)this.rules.other.tableAlignRight.test(h)?o.align.push("right"):this.rules.other.tableAlignCenter.test(h)?o.align.push("center"):this.rules.other.tableAlignLeft.test(h)?o.align.push("left"):o.align.push(null);for(let h=0;h<s.length;h++)o.header.push({text:s[h],tokens:this.lexer.inline(s[h]),header:true,align:o.align[h]});for(let h of n)o.rows.push(_d(h,o.header.length).map((l,c)=>({text:l,tokens:this.lexer.inline(l),header:false,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let s=t[1].trim();return{type:"heading",raw:qi(t[0],\`
\`),header:[],align:[],rows:[]};if(s.length===r.length){for(let h of r)this.rules.other.tableAlignRight.test(h)?o.align.push("right"):this.rules.other.tableAlignCenter.test(h)?o.align.push("center"):this.rules.other.tableAlignLeft.test(h)?o.align.push("left"):o.align.push(null);for(let h=0;h<s.length;h++)o.header.push({text:s[h],tokens:this.lexer.inline(s[h]),header:true,align:o.align[h]});for(let h of n)o.rows.push(vd(h,o.header.length).map((l,c)=>({text:l,tokens:this.lexer.inline(l),header:false,align:o.align[c]})));return o}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let s=t[1].trim();return{type:"heading",raw:qi(t[0],\`
\`),depth:t[2].charAt(0)==="="?1:2,text:s,tokens:this.lexer.inline(s)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let s=t[1].charAt(t[1].length-1)===\`
\`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:s,tokens:this.lexer.inline(s)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=true:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=false),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=true:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=false),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:false,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let s=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let o=qi(s.slice(0,-1),"\\\\");if((s.length-o.length)%2===0)return}else{let o=iv(t[2],"()");if(o===-2)return;if(o>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let r=t[2],n="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],n=o[3])}else n=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?r=r.slice(1):r=r.slice(1,-1)),bd(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let s;if((s=this.rules.inline.reflink.exec(e))||(s=this.rules.inline.nolink.exec(e))){let r=(s[2]||s[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=t[r.toLowerCase()];if(!n){let o=s[0].charAt(0);return{type:"text",raw:o,text:o}}return bd(s,n,s[0],this.lexer,this.rules)}}emStrong(e,t,s=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&s.match(this.rules.other.unicodeAlphaNumeric))return;if(!(r[1]||r[3]||"")||!s||this.rules.inline.punctuation.exec(s)){let n=[...r[0]].length-1,o,a,h=n,l=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o)continue;if(a=[...o].length,r[3]||r[4]){h+=a;continue}else if((r[5]||r[6])&&n%3&&!((n+a)%3)){l+=a;continue}if(h-=a,h>0)continue;a=Math.min(a,a+h+l);let d=[...r[0]][0].length,u=e.slice(0,n+r.index+d+a);if(Math.min(n,a)%2){let p=u.slice(1,-1);return{type:"em",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}let f=u.slice(2,-2);return{type:"strong",raw:u,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let s=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(s),n=this.rules.other.startingSpaceChar.test(s)&&this.rules.other.endingSpaceChar.test(s);return r&&n&&(s=s.substring(1,s.length-1)),{type:"codespan",raw:t[0],text:s}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,s=""){let r=this.rules.inline.delLDelim.exec(e);if(!r)return;if(!(r[1]||"")||!s||this.rules.inline.punctuation.exec(s)){let n=[...r[0]].length-1,o,a,h=n,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+n);(r=l.exec(t))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o||(a=[...o].length,a!==n))continue;if(r[3]||r[4]){h+=a;continue}if(h-=a,h>0)continue;a=Math.min(a,a+h);let c=[...r[0]][0].length,d=e.slice(0,n+r.index+c+a),u=d.slice(n,-n);return{type:"del",raw:d,text:u,tokens:this.lexer.inlineTokens(u)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let s,r;return t[2]==="@"?(s=t[1],r="mailto:"+s):(s=t[1],r=s),{type:"link",raw:t[0],text:s,href:r,tokens:[{type:"text",raw:s,text:s}]}}}url(e){var s;let t;if(t=this.rules.inline.url.exec(e)){let r,n;if(t[2]==="@")r=t[0],n="mailto:"+r;else{let o;do o=t[0],t[0]=((s=this.rules.inline._backpedal.exec(t[0]))==null?void 0:s[0])??"";while(o!==t[0]);r=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let s=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:s}}}};var Xt=class $l{constructor(e){w(this,"tokens");w(this,"options");w(this,"state");w(this,"inlineQueue");w(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Os,this.options.tokenizer=this.options.tokenizer||new Bo,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:false,inRawBlock:false,top:true};let t={other:mt,block:Kn.normal,inline:Tr.normal};this.options.peda Line truncated
\`?t[1].slice(0,-1):t[1];return{type:"paragraph",raw:t[0],text:s,tokens:this.lexer.inline(s)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:"text",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:"escape",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=true:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=false),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=true:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=false),{type:"html",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:false,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let s=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(s)){if(!this.rules.other.endAngleBracket.test(s))return;let o=qi(s.slice(0,-1),"\\\\");if((s.length-o.length)%2===0)return}else{let o=vv(t[2],"()");if(o===-2)return;if(o>-1){let a=(t[0].indexOf("!")===0?5:4)+t[1].length+o;t[2]=t[2].substring(0,o),t[0]=t[0].substring(0,a).trim(),t[3]=""}}let r=t[2],n="";if(this.options.pedantic){let o=this.rules.other.pedanticHrefTitle.exec(r);o&&(r=o[1],n=o[3])}else n=t[3]?t[3].slice(1,-1):"";return r=r.trim(),this.rules.other.startAngleBracket.test(r)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(s)?r=r.slice(1):r=r.slice(1,-1)),yd(t,{href:r&&r.replace(this.rules.inline.anyPunctuation,"$1"),title:n&&n.replace(this.rules.inline.anyPunctuation,"$1")},t[0],this.lexer,this.rules)}}reflink(e,t){let s;if((s=this.rules.inline.reflink.exec(e))||(s=this.rules.inline.nolink.exec(e))){let r=(s[2]||s[1]).replace(this.rules.other.multipleSpaceGlobal," "),n=t[r.toLowerCase()];if(!n){let o=s[0].charAt(0);return{type:"text",raw:o,text:o}}return yd(s,n,s[0],this.lexer,this.rules)}}emStrong(e,t,s=""){let r=this.rules.inline.emStrongLDelim.exec(e);if(!r||!r[1]&&!r[2]&&!r[3]&&!r[4]||r[4]&&s.match(this.rules.other.unicodeAlphaNumeric))return;if(!(r[1]||r[3]||"")||!s||this.rules.inline.punctuation.exec(s)){let n=[...r[0]].length-1,o,a,h=n,l=0,c=r[0][0]==="*"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(c.lastIndex=0,t=t.slice(-1*e.length+n);(r=c.exec(t))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o)continue;if(a=[...o].length,r[3]||r[4]){h+=a;continue}else if((r[5]||r[6])&&n%3&&!((n+a)%3)){l+=a;continue}if(h-=a,h>0)continue;a=Math.min(a,a+h+l);let d=[...r[0]][0].length,u=e.slice(0,n+r.index+d+a);if(Math.min(n,a)%2){let p=u.slice(1,-1);return{type:"em",raw:u,text:p,tokens:this.lexer.inlineTokens(p)}}let f=u.slice(2,-2);return{type:"strong",raw:u,text:f,tokens:this.lexer.inlineTokens(f)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let s=t[2].replace(this.rules.other.newLineCharGlobal," "),r=this.rules.other.nonSpaceChar.test(s),n=this.rules.other.startingSpaceChar.test(s)&&this.rules.other.endingSpaceChar.test(s);return r&&n&&(s=s.substring(1,s.length-1)),{type:"codespan",raw:t[0],text:s}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:"br",raw:t[0]}}del(e,t,s=""){let r=this.rules.inline.delLDelim.exec(e);if(!r)return;if(!(r[1]||"")||!s||this.rules.inline.punctuation.exec(s)){let n=[...r[0]].length-1,o,a,h=n,l=this.rules.inline.delRDelim;for(l.lastIndex=0,t=t.slice(-1*e.length+n);(r=l.exec(t))!==null;){if(o=r[1]||r[2]||r[3]||r[4]||r[5]||r[6],!o||(a=[...o].length,a!==n))continue;if(r[3]||r[4]){h+=a;continue}if(h-=a,h>0)continue;a=Math.min(a,a+h);let c=[...r[0]][0].length,d=e.slice(0,n+r.index+c+a),u=d.slice(n,-n);return{type:"del",raw:d,text:u,tokens:this.lexer.inlineTokens(u)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let s,r;return t[2]==="@"?(s=t[1],r="mailto:"+s):(s=t[1],r=s),{type:"link",raw:t[0],text:s,href:r,tokens:[{type:"text",raw:s,text:s}]}}}url(e){var s;let t;if(t=this.rules.inline.url.exec(e)){let r,n;if(t[2]==="@")r=t[0],n="mailto:"+r;else{let o;do o=t[0],t[0]=((s=this.rules.inline._backpedal.exec(t[0]))==null?void 0:s[0])??"";while(o!==t[0]);r=t[0],t[1]==="www."?n="http://"+t[0]:n=t[0]}return{type:"link",raw:t[0],text:r,href:n,tokens:[{type:"text",raw:r,text:r}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let s=this.lexer.state.inRawBlock;return{type:"text",raw:t[0],text:t[0],escaped:s}}}};var Zt=class Ol{constructor(e){w(this,"tokens");w(this,"options");w(this,"state");w(this,"inlineQueue");w(this,"tokenizer");this.tokens=[],this.tokens.links=Object.create(null),this.options=e||Fs,this.options.tokenizer=this.options.tokenizer||new Po,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:false,inRawBlock:false,top:true};let t={other:mt,block:Kn.normal,inline:Tr.normal};this.options.peda Line truncated
\`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let s=this.inlineQueue[t];this.inlineTokens(s.src,s.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],s=false){var n,o,a;this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(mt.tabCharGlobal," ").replace(mt.spaceLine,""));let r=1/0;for(;e;){if(e.length<r)r=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let h;if((o=(n=this.options.extensions)==null?void 0:n.block)==null?void 0:o.some(c=>(h=c.call({lexer:this},e,t))?(e=e.substring(h.raw.length),t.push(h),true):false))continue;if(h=this.tokenizer.space(e)){e=e.substring(h.raw.length);let c=t.at(-1);h.raw.length===1&&c!==void 0?c.raw+=\`
\`:t.push(h);continue}if(h=this.tokenizer.code(e)){e=e.substring(h.raw.length);let c=t.at(-1);(c==null?void 0:c.type)==="paragraph"||(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(\`
\`)?"":\`
@@ -401,9 +401,9 @@ export const HTML = `<!doctype html>
\`+h.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):t.push(h),s=l.length!==e.length,e=e.substring(h.raw.length);continue}if(h=this.tokenizer.text(e)){e=e.substring(h.raw.length);let c=t.at(-1);(c==null?void 0:c.type)==="text"?(c.raw+=(c.raw.endsWith(\`
\`)?"":\`
\`)+h.raw,c.text+=\`
\`+h.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):t.push(h);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=true,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){var l,c,d,u,f;this.tokenizer.lexer=this;let s=e,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let n;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)n=r[2]?r[2].length:0,s=s.slice(0,r.index+n)+"["+"a".repeat(r[0].length-n-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=((c=(l=this.options.hooks)==null?void 0:l.emStrongMask)==null?void 0:c.call({lexer:this},s))??s;let o=false,a="",h=1/0;for(;e;){if(e.length<h)h=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}o||(a=""),o=false;let p;if((u=(d=this.options.extensions)==null?void 0:d.inline)==null?void 0:u.some(v=>(p=v.call({lexer:this},e,t))?(e=e.substring(p.raw.length),t.push(p),true):false))continue;if(p=this.tokenizer.escape(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.tag(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.link(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(p.raw.length);let v=t.at(-1);p.type==="text"&&(v==null?void 0:v.type)==="text"?(v.raw+=p.raw,v.text+=p.text):t.push(p);continue}if(p=this.tokenizer.emStrong(e,s,a)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.codespan(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.br(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.del(e,s,a)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.autolink(e)){e=e.substring(p.raw.length),t.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(e))){e=e.substring(p.raw.length),t.push(p);continue}let b=e;if((f=this.options.extensions)==null?void 0:f.startInline){let v=1/0,R=e.slice(1),L;this.options.extensions.startInline.forEach(A=>{L=A.call({lexer:this},R),typeof L=="number"&&L>=0&&(v=Math.min(v,L))}),v<1/0&&v>=0&&(b=e.substring(0,v+1))}if(p=this.tokenizer.inlineText(b)){e=e.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),o=true;let v=t.at(-1);(v==null?void 0:v.type)==="text"?(v.raw+=p.raw,v.text+=p.text):t.push(p);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}};var Io=class ax{constructor(e){w(this,"options");w(this,"parser");this.options=e||Os}space(e){return""}code({text:e,lang:t,escaped:s}){var o;let r=(o=(t||"").match(mt.notSpaceStart))==null?void 0:o[0],n=e.replace(mt.endingNewline,"")+\`
\`;return r?'<pre><code class="language-'+ci(r)+'">'+(s?n:ci(n,true))+\`</code></pre>
\`:"<pre><code>"+(s?n:ci(n,true))+\`</code></pre>
\`+h.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=c.text):t.push(h);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=true,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){var l,c,d,u,f;this.tokenizer.lexer=this;let s=e,r=null;if(this.tokens.links){let p=Object.keys(this.tokens.links);if(p.length>0)for(;(r=this.tokenizer.rules.inline.reflinkSearch.exec(s))!==null;)p.includes(r[0].slice(r[0].lastIndexOf("[")+1,-1))&&(s=s.slice(0,r.index)+"["+"a".repeat(r[0].length-2)+"]"+s.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(r=this.tokenizer.rules.inline.anyPunctuation.exec(s))!==null;)s=s.slice(0,r.index)+"++"+s.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let n;for(;(r=this.tokenizer.rules.inline.blockSkip.exec(s))!==null;)n=r[2]?r[2].length:0,s=s.slice(0,r.index+n)+"["+"a".repeat(r[0].length-n-2)+"]"+s.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);s=((c=(l=this.options.hooks)==null?void 0:l.emStrongMask)==null?void 0:c.call({lexer:this},s))??s;let o=false,a="",h=1/0;for(;e;){if(e.length<h)h=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}o||(a=""),o=false;let p;if((u=(d=this.options.extensions)==null?void 0:d.inline)==null?void 0:u.some(v=>(p=v.call({lexer:this},e,t))?(e=e.substring(p.raw.length),t.push(p),true):false))continue;if(p=this.tokenizer.escape(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.tag(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.link(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(p.raw.length);let v=t.at(-1);p.type==="text"&&(v==null?void 0:v.type)==="text"?(v.raw+=p.raw,v.text+=p.text):t.push(p);continue}if(p=this.tokenizer.emStrong(e,s,a)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.codespan(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.br(e)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.del(e,s,a)){e=e.substring(p.raw.length),t.push(p);continue}if(p=this.tokenizer.autolink(e)){e=e.substring(p.raw.length),t.push(p);continue}if(!this.state.inLink&&(p=this.tokenizer.url(e))){e=e.substring(p.raw.length),t.push(p);continue}let b=e;if((f=this.options.extensions)==null?void 0:f.startInline){let v=1/0,R=e.slice(1),L;this.options.extensions.startInline.forEach(A=>{L=A.call({lexer:this},R),typeof L=="number"&&L>=0&&(v=Math.min(v,L))}),v<1/0&&v>=0&&(b=e.substring(0,v+1))}if(p=this.tokenizer.inlineText(b)){e=e.substring(p.raw.length),p.raw.slice(-1)!=="_"&&(a=p.raw.slice(-1)),o=true;let v=t.at(-1);(v==null?void 0:v.type)==="text"?(v.raw+=p.raw,v.text+=p.text):t.push(p);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t="Infinite loop on byte: "+e;if(this.options.silent)console.error(t);else throw new Error(t)}};var Do=class xx{constructor(e){w(this,"options");w(this,"parser");this.options=e||Fs}space(e){return""}code({text:e,lang:t,escaped:s}){var o;let r=(o=(t||"").match(mt.notSpaceStart))==null?void 0:o[0],n=e.replace(mt.endingNewline,"")+\`
\`;return r?'<pre><code class="language-'+di(r)+'">'+(s?n:di(n,true))+\`</code></pre>
\`:"<pre><code>"+(s?n:di(n,true))+\`</code></pre>
\`}blockquote({tokens:e}){return\`<blockquote>
\${this.parser.parse(e)}</blockquote>
\`}html({text:e}){return e}def(e){return""}heading({tokens:e,depth:t}){return\`<h\${t}>\${this.parser.parseInline(e)}</h\${t}>
@@ -419,15 +419,15 @@ export const HTML = `<!doctype html>
\`}tablerow({text:e}){return\`<tr>
\${e}</tr>
\`}tablecell(e){let t=this.parser.parseInline(e.tokens),s=e.header?"th":"td";return(e.align?\`<\${s} align="\${e.align}">\`:\`<\${s}>\`)+t+\`</\${s}>
\`}strong({tokens:e}){return\`<strong>\${this.parser.parseInline(e)}</strong>\`}em({tokens:e}){return\`<em>\${this.parser.parseInline(e)}</em>\`}codespan({text:e}){return\`<code>\${ci(e,true)}</code>\`}br(e){return"<br>"}del({tokens:e}){return\`<del>\${this.parser.parseInline(e)}</del>\`}link({href:e,title:t,tokens:s}){let r=this.parser.parseInline(s),n=gd(e);if(n===null)return r;e=n;let o='<a href="'+e+'"';return t&&(o+=' title="'+ci(t)+'"'),o+=">"+r+"</a>",o}image({href:e,title:t,text:s,tokens:r}){r&&(s=this.parser.parseInline(r,this.parser.textRenderer));let n=gd(e);if(n===null)return ci(s);e=n;let o=\`<img src="\${e}" alt="\${ci(s)}"\`;return t&&(o+=\` title="\${ci(t)}"\`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:ci(e.text)}};var Yh=class lx{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}};var Zt=class Ol{constructor(e){w(this,"options");w(this,"renderer");w(this,"textRenderer");this.options=e||Os,this.options.renderer=this.options.renderer||new Io,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Yh}static parse(e,t){return new Ol(t).parse(e)}static parseInline(e,t){return new Ol(t).parseInline(e)}parse(e){var s,r;this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let o=e[n];if((r=(s=this.options.extensions)==null?void 0:s.renderers)==null?void 0:r[o.type]){let h=o,l=this.options.extensions.renderers[h.type].call({parser:this},h);if(l!==false||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(h.type)){t+=l||"";continue}}let a=o;switch(a.type){case"space":{t+=this.renderer.space(a);break}case"hr":{t+=this.renderer.hr(a);break}case"heading":{t+=this.renderer.heading(a);break}case"code":{t+=this.renderer.code(a);break}case"table":{t+=this.renderer.table(a);break}case"blockquote":{t+=this.renderer.blockquote(a);break}case"list":{t+=this.renderer.list(a);break}case"checkbox":{t+=this.renderer.checkbox(a);break}case"html":{t+=this.renderer.html(a);break}case"def":{t+=this.renderer.def(a);break}case"paragraph":{t+=this.renderer.paragraph(a);break}case"text":{t+=this.renderer.text(a);break}default:{let h='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(h),"";throw new Error(h)}}}return t}parseInline(e,t=this.renderer){var r,n;this.renderer.parser=this;let s="";for(let o=0;o<e.length;o++){let a=e[o];if((n=(r=this.options.extensions)==null?void 0:r.renderers)==null?void 0:n[a.type]){let l=this.options.extensions.renderers[a.type].call({parser:this},a);if(l!==false||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){s+=l||"";continue}}let h=a;switch(h.type){case"escape":{s+=t.text(h);break}case"html":{s+=t.html(h);break}case"link":{s+=t.link(h);break}case"image":{s+=t.image(h);break}case"checkbox":{s+=t.checkbox(h);break}case"strong":{s+=t.strong(h);break}case"em":{s+=t.em(h);break}case"codespan":{s+=t.codespan(h);break}case"br":{s+=t.br(h);break}case"del":{s+=t.del(h);break}case"text":{s+=t.text(h);break}default:{let l='Token with "'+h.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return s}};var Qr;var Ur=(Qr=class{constructor(e){w(this,"options");w(this,"block");this.options=e||Os}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Xt.lex:Xt.lexInline}provideParser(e=this.block){return e?Zt.parse:Zt.parseInline}},w(Qr,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),w(Qr,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),Qr);var nv=class hx{constructor(...e){w(this,"defaults",Hh());w(this,"options",this.setOptions);w(this,"parse",this.parseMarkdown(true));w(this,"parseInline",this.parseMarkdown(false));w(this,"Parser",Zt);w(this,"Renderer",Io);w(this,"TextRenderer",Yh);w(this,"Lexer",Xt);w(this,"Tokenizer",Bo);w(this,"Hooks",Ur);this.use(...e)}walkTokens(e,t){var r,n;let s=[];for(let o of e)switch(s=s.concat(t.call(this,o)),o.type){case"table":{let a=o;for(let h of a.header)s=s.concat(this.walkTokens(h.tokens,t));for(let h of a.rows)for(let l of h)s=s.concat(this.walkTokens(l.tokens,t));break}case"list":{let a=o;s=s.concat(this.walkTokens(a.items,t));break}default:{let a=o;((n=(r=this.defaults.extensions)==null?void 0:r.childTokens)==null?void 0:n[a.type])?this.defaults.extensions.childTokens[a.type].forEach(h=>{let l=a[h].flat(1/0);s=s.concat(this.walkTokens(l,t))}):a.tokens&&(s=s.concat(this.walkTokens(a.tokens,t)))}}return s}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(s=>{l Line truncated
Please report this to https://github.com/markedjs/marked.\`,e){let r="<p>An error occurred:</p><pre>"+ci(s.message+"",true)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(s);throw s}}};var Bs=new nv;function fe(i,e){return Bs.parse(i,e)}fe.options=fe.setOptions=function(i){return Bs.setOptions(i),fe.defaults=Bs.defaults,xp(fe.defaults),fe};fe.getDefaults=Hh;fe.defaults=Os;fe.use=function(...i){return Bs.use(...i),fe.defaults=Bs.defaults,xp(fe.defaults),fe};fe.walkTokens=function(i,e){return Bs.walkTokens(i,e)};fe.parseInline=Bs.parseInline;fe.Parser=Zt;fe.parser=Zt.parse;fe.Renderer=Io;fe.TextRenderer=Yh;fe.Lexer=Xt;fe.lexer=Xt.lex;fe.Tokenizer=Bo;fe.Hooks=Ur;fe.parse=fe;fe.options;fe.setOptions;fe.use;fe.walkTokens;fe.parseInline;Zt.parse;Xt.lex;const ov=new Set(["bash","cmd","fish","powershell","pwsh","sh","shell","shellscript","zsh"]);function Ip(i){return(i||"").trim().split(/\\s+/,1)[0].toLowerCase().replace(/^language-/,"")}function av(i,e){if(!ov.has(Ip(i)))return null;const t=e.replace(/\\r\\n?/g,"\\n").trim();if(!t||t.includes("\\n"))return null;if(/[\\u0000-\\u001f\\u007f]/.test(t))return null;return t.startsWith("$ ")?t.slice(2).trimStart()||null:t}function lv(i,e){if(!i.trim())return null;return{content:i,sourceLabel:e.trim(),lineCount:i.split(/\\r\\n|\\r|\\n/).length,characterCount:i.length}}function hv(i,e){return m("agent.selectionContextPrompt",{source:e.sourceLabel||m("agent.selectionUnknownSource"),content:e.content,question:i.trim()})}fe.use({gfm:true,renderer:{code({text:i,lang:e}){const t=Ip(e);const s=t?\`<span class="agent-md-lang">\${be(t)}</span>\`:'<span class="agent-md-lang" aria-hidden="true"></span>';return\`<div class="agent-md-code-block" data-code-language="\${be(t)}">
\`}strong({tokens:e}){return\`<strong>\${this.parser.parseInline(e)}</strong>\`}em({tokens:e}){return\`<em>\${this.parser.parseInline(e)}</em>\`}codespan({text:e}){return\`<code>\${di(e,true)}</code>\`}br(e){return"<br>"}del({tokens:e}){return\`<del>\${this.parser.parseInline(e)}</del>\`}link({href:e,title:t,tokens:s}){let r=this.parser.parseInline(s),n=_d(e);if(n===null)return r;e=n;let o='<a href="'+e+'"';return t&&(o+=' title="'+di(t)+'"'),o+=">"+r+"</a>",o}image({href:e,title:t,text:s,tokens:r}){r&&(s=this.parser.parseInline(r,this.parser.textRenderer));let n=_d(e);if(n===null)return di(s);e=n;let o=\`<img src="\${e}" alt="\${di(s)}"\`;return t&&(o+=\` title="\${di(t)}"\`),o+=">",o}text(e){return"tokens"in e&&e.tokens?this.parser.parseInline(e.tokens):"escaped"in e&&e.escaped?e.text:di(e.text)}};var Xh=class Cx{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return""+e}image({text:e}){return""+e}br(){return""}checkbox({raw:e}){return e}};var Jt=class Fl{constructor(e){w(this,"options");w(this,"renderer");w(this,"textRenderer");this.options=e||Fs,this.options.renderer=this.options.renderer||new Do,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new Xh}static parse(e,t){return new Fl(t).parse(e)}static parseInline(e,t){return new Fl(t).parseInline(e)}parse(e){var s,r;this.renderer.parser=this;let t="";for(let n=0;n<e.length;n++){let o=e[n];if((r=(s=this.options.extensions)==null?void 0:s.renderers)==null?void 0:r[o.type]){let h=o,l=this.options.extensions.renderers[h.type].call({parser:this},h);if(l!==false||!["space","hr","heading","code","table","blockquote","list","html","def","paragraph","text"].includes(h.type)){t+=l||"";continue}}let a=o;switch(a.type){case"space":{t+=this.renderer.space(a);break}case"hr":{t+=this.renderer.hr(a);break}case"heading":{t+=this.renderer.heading(a);break}case"code":{t+=this.renderer.code(a);break}case"table":{t+=this.renderer.table(a);break}case"blockquote":{t+=this.renderer.blockquote(a);break}case"list":{t+=this.renderer.list(a);break}case"checkbox":{t+=this.renderer.checkbox(a);break}case"html":{t+=this.renderer.html(a);break}case"def":{t+=this.renderer.def(a);break}case"paragraph":{t+=this.renderer.paragraph(a);break}case"text":{t+=this.renderer.text(a);break}default:{let h='Token with "'+a.type+'" type was not found.';if(this.options.silent)return console.error(h),"";throw new Error(h)}}}return t}parseInline(e,t=this.renderer){var r,n;this.renderer.parser=this;let s="";for(let o=0;o<e.length;o++){let a=e[o];if((n=(r=this.options.extensions)==null?void 0:r.renderers)==null?void 0:n[a.type]){let l=this.options.extensions.renderers[a.type].call({parser:this},a);if(l!==false||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(a.type)){s+=l||"";continue}}let h=a;switch(h.type){case"escape":{s+=t.text(h);break}case"html":{s+=t.html(h);break}case"link":{s+=t.link(h);break}case"image":{s+=t.image(h);break}case"checkbox":{s+=t.checkbox(h);break}case"strong":{s+=t.strong(h);break}case"em":{s+=t.em(h);break}case"codespan":{s+=t.codespan(h);break}case"br":{s+=t.br(h);break}case"del":{s+=t.del(h);break}case"text":{s+=t.text(h);break}default:{let l='Token with "'+h.type+'" type was not found.';if(this.options.silent)return console.error(l),"";throw new Error(l)}}}return s}};var Qr;var Ur=(Qr=class{constructor(e){w(this,"options");w(this,"block");this.options=e||Fs}preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?Zt.lex:Zt.lexInline}provideParser(e=this.block){return e?Jt.parse:Jt.parseInline}},w(Qr,"passThroughHooks",new Set(["preprocess","postprocess","processAllTokens","emStrongMask"])),w(Qr,"passThroughHooksRespectAsync",new Set(["preprocess","postprocess","processAllTokens"])),Qr);var wv=class kx{constructor(...e){w(this,"defaults",Wh());w(this,"options",this.setOptions);w(this,"parse",this.parseMarkdown(true));w(this,"parseInline",this.parseMarkdown(false));w(this,"Parser",Jt);w(this,"Renderer",Do);w(this,"TextRenderer",Xh);w(this,"Lexer",Zt);w(this,"Tokenizer",Po);w(this,"Hooks",Ur);this.use(...e)}walkTokens(e,t){var r,n;let s=[];for(let o of e)switch(s=s.concat(t.call(this,o)),o.type){case"table":{let a=o;for(let h of a.header)s=s.concat(this.walkTokens(h.tokens,t));for(let h of a.rows)for(let l of h)s=s.concat(this.walkTokens(l.tokens,t));break}case"list":{let a=o;s=s.concat(this.walkTokens(a.items,t));break}default:{let a=o;((n=(r=this.defaults.extensions)==null?void 0:r.childTokens)==null?void 0:n[a.type])?this.defaults.extensions.childTokens[a.type].forEach(h=>{let l=a[h].flat(1/0);s=s.concat(this.walkTokens(l,t))}):a.tokens&&(s=s.concat(this.walkTokens(a.tokens,t)))}}return s}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(s=>{l Line truncated
Please report this to https://github.com/markedjs/marked.\`,e){let r="<p>An error occurred:</p><pre>"+di(s.message+"",true)+"</pre>";return t?Promise.resolve(r):r}if(t)return Promise.reject(s);throw s}}};var Is=new wv;function fe(i,e){return Is.parse(i,e)}fe.options=fe.setOptions=function(i){return Is.setOptions(i),fe.defaults=Is.defaults,Lp(fe.defaults),fe};fe.getDefaults=Wh;fe.defaults=Fs;fe.use=function(...i){return Is.use(...i),fe.defaults=Is.defaults,Lp(fe.defaults),fe};fe.walkTokens=function(i,e){return Is.walkTokens(i,e)};fe.parseInline=Is.parseInline;fe.Parser=Jt;fe.parser=Jt.parse;fe.Renderer=Do;fe.TextRenderer=Xh;fe.Lexer=Zt;fe.lexer=Zt.lex;fe.Tokenizer=Po;fe.Hooks=Ur;fe.parse=fe;fe.options;fe.setOptions;fe.use;fe.walkTokens;fe.parseInline;Jt.parse;Zt.lex;const Sv=new Set(["bash","cmd","fish","powershell","pwsh","sh","shell","shellscript","zsh"]);function Fp(i){return(i||"").trim().split(/\\s+/,1)[0].toLowerCase().replace(/^language-/,"")}function xv(i,e){if(!Sv.has(Fp(i)))return null;const t=e.replace(/\\r\\n?/g,"\\n").trim();if(!t||t.includes("\\n"))return null;if(/[\\u0000-\\u001f\\u007f]/.test(t))return null;return t.startsWith("$ ")?t.slice(2).trimStart()||null:t}function Cv(i,e){if(!i.trim())return null;return{content:i,sourceLabel:e.trim(),lineCount:i.split(/\\r\\n|\\r|\\n/).length,characterCount:i.length}}function kv(i,e){return m("agent.selectionContextPrompt",{source:e.sourceLabel||m("agent.selectionUnknownSource"),content:e.content,question:i.trim()})}fe.use({gfm:true,renderer:{code({text:i,lang:e}){const t=Fp(e);const s=t?\`<span class="agent-md-lang">\${be(t)}</span>\`:'<span class="agent-md-lang" aria-hidden="true"></span>';return\`<div class="agent-md-code-block" data-code-language="\${be(t)}">
<div class="agent-md-code-toolbar">
\${s}
<div class="agent-md-code-meta"></div>
<div class="agent-md-code-actions"></div>
</div>
<pre class="agent-md-pre"><code>\${be(i)}</code></pre>
</div>\`},codespan({text:i}){return\`<code class="agent-md-inline-code">\${be(i)}</code>\`},link({href:i,title:e,text:t}){const s=e?\` title="\${be(e)}"\`:"";return\`<a href="\${be(i)}"\${s} target="_blank" rel="noopener noreferrer" class="agent-md-link">\${t}</a>\`},image({href:i,title:e,text:t}){const s=e?\` title="\${be(e)}"\`:"";return\`<img src="\${be(i)}"\${s} alt="\${be(t)}" class="agent-md-img" loading="lazy">\`}}});function be(i){if(!i)return"";return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class cv{constructor(e,t){w(this,"panelEl",null);w(this,"messagesEl",null);w(this,"contextEl",null);w(this,"inputEl",null);w(this,"sendBtn",null);w(this,"isVisible",false);w(this,"isAgentRunning",false);w(this,"isWaitingConfirmation",false);w(this,"wsSend",null);w(this,"getTerminalFillTarget",null);w(this,"fillTerminalInput",null);w(this,"onLayoutChange");w(this,"streamingEl",null);w(this,"streamingText","");w(this,"thinkingProcessEl",null);w(this,"thinkingStepsEl",null);w(this,"thinkingCurrentEl",null);w(this,"thinkingStatusEl",null);w(this,"thinkingIsDone",false);w(this,"thinkingStepCount",0);w(this,"thinkingLiveEl",null);w(this,"thinkingAllSteps",[]);w(this,"livePreviewCache",[]);w(this,"localeCleanup",null);w(this,"pendingTerminalSelection",null);w(this,"pendingConfirmation",null);this.parentEl=e;this.isLoggedIn=t}setLayoutChangeHandler(e){this.onLayoutChange=e}setWebSocketSend(e){this.wsSend=e}setTerminalFillHandler(e,t){this.getTerminalFillTarget=e;this.fillTerminalInput=t}render(){if(this.panelEl)return;this.panelEl=document.createElement("div");this.panelEl.id="agent-panel";this.panelEl.className="w-[560px] max-w-[calc(100vw-200px)] shrink-0 border-l border-[var(--border)] flex flex-col bg-[var(--bg)] overflow-hidden";this.panelEl.style.display="none";this.panelEl.innerHTML=\`
</div>\`},codespan({text:i}){return\`<code class="agent-md-inline-code">\${be(i)}</code>\`},link({href:i,title:e,text:t}){const s=e?\` title="\${be(e)}"\`:"";return\`<a href="\${be(i)}"\${s} target="_blank" rel="noopener noreferrer" class="agent-md-link">\${t}</a>\`},image({href:i,title:e,text:t}){const s=e?\` title="\${be(e)}"\`:"";return\`<img src="\${be(i)}"\${s} alt="\${be(t)}" class="agent-md-img" loading="lazy">\`}}});function be(i){if(!i)return"";return i.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;")}class Ev{constructor(e,t){w(this,"panelEl",null);w(this,"messagesEl",null);w(this,"contextEl",null);w(this,"inputEl",null);w(this,"sendBtn",null);w(this,"isVisible",false);w(this,"isAgentRunning",false);w(this,"isWaitingConfirmation",false);w(this,"wsSend",null);w(this,"getTerminalFillTarget",null);w(this,"fillTerminalInput",null);w(this,"onLayoutChange");w(this,"streamingEl",null);w(this,"streamingText","");w(this,"thinkingProcessEl",null);w(this,"thinkingStepsEl",null);w(this,"thinkingCurrentEl",null);w(this,"thinkingStatusEl",null);w(this,"thinkingIsDone",false);w(this,"thinkingStepCount",0);w(this,"thinkingLiveEl",null);w(this,"thinkingAllSteps",[]);w(this,"livePreviewCache",[]);w(this,"localeCleanup",null);w(this,"pendingTerminalSelection",null);w(this,"pendingConfirmation",null);this.parentEl=e;this.isLoggedIn=t}setLayoutChangeHandler(e){this.onLayoutChange=e}setWebSocketSend(e){this.wsSend=e}setTerminalFillHandler(e,t){this.getTerminalFillTarget=e;this.fillTerminalInput=t}render(){if(this.panelEl)return;this.panelEl=document.createElement("div");this.panelEl.id="agent-panel";this.panelEl.className="w-[560px] max-w-[calc(100vw-200px)] shrink-0 border-l border-[var(--border)] flex flex-col bg-[var(--bg)] overflow-hidden";this.panelEl.style.display="none";this.panelEl.innerHTML=\`
<div class="agent-panel-header flex items-center justify-between px-4 py-2.5 border-b border-[var(--border)] bg-[var(--bg-elevated)]">
<span class="text-xs font-bold tracking-[0.1em] text-[var(--accent-secondary)]" data-i18n="agent.title">AI Agent 助手</span>
<button id="agent-close-btn" class="agent-close-button text-muted hover:text-primary transition-colors cursor-pointer" data-i18n-title="agent.backToTerminal" data-i18n-aria-label="agent.backToTerminal" title="返回终端" aria-label="返回终端">
@@ -450,7 +450,7 @@ Please report this to https://github.com/markedjs/marked.\`,e){let r="<p>An erro
</button>
</div>
</div>
\`;Oi(this.panelEl);this.localeCleanup=$s(()=>{this.updateInputState();this.renderTerminalSelectionContext();this.refreshCodeBlockActions()});this.parentEl.appendChild(this.panelEl);this.messagesEl=this.panelEl.querySelector("#agent-messages");this.contextEl=this.panelEl.querySelector("#agent-context");this.inputEl=this.panelEl.querySelector("#agent-input");this.sendBtn=this.panelEl.querySelector("#agent-send-btn");this.bindEvents();this.updateInputState()}bindEvents(){var e,t,s,r,n;(t=(e=this.panelEl)==null?void 0:e.querySelector("#agent-close-btn"))==null?void 0:t.addEventListener("click",()=>this.hide());(s=this.sendBtn)==null?void 0:s.addEventListener("click",()=>this.handleSend());(r=this.inputEl)==null?void 0:r.addEventListener("keydown",o=>{if(o.key==="Enter"&&!o.shiftKey){o.preventDefault();this.handleSend()}});(n=this.inputEl)==null?void 0:n.addEventListener("input",()=>{const o=this.inputEl;o.style.height="auto";o.style.height=Math.min(o.scrollHeight,140)+"px";this.updateInputState()})}toggle(){this.isVisible?this.hide():this.show()}show(){var e;if(!this.isLoggedIn)return;this.isVisible=true;if(this.panelEl)this.panelEl.style.display="flex";(e=this.inputEl)==null?void 0:e.focus();requestAnimationFrame(()=>{var t;return(t=this.onLayoutChange)==null?void 0:t.call(this)})}hide(){this.rejectPendingConfirmation(false);this.isVisible=false;if(this.panelEl)this.panelEl.style.display="none";requestAnimationFrame(()=>{var e;return(e=this.onLayoutChange)==null?void 0:e.call(this)})}rejectPendingConfirmation(e=true){this.resolvePendingConfirmation(false,e)}attachTerminalSelection(e,t){var r;const s=lv(e,t);if(!s)return false;this.pendingTerminalSelection=s;this.renderTerminalSelectionContext();this.show();(r=this.inputEl)==null?void 0:r.focus();return true}clearTerminalSelectionContext(){this.pendingTerminalSelection=null;this.renderTerminalSelectionContext()}handleAgentFrame(e){switch(e.subType){case"thinking":this.showThinking(e.iteration);break;case"executing":this.showExecuting(e.tool,e.args);break;case"stream_chunk":this.handleStreamChunk(e.content);break;case"stream_end":this.handleStreamEnd(e.content);this.isAgentRunning=false;this.updateInputState();break;case"response":this.addAgentResponse(e.content);this.isAgentRunning=false;this.updateInputState();break;case"confirm_required":this.showConfirmDialog(e.command,e.reason);break;case"error":this.showError(e.message);this.isAgentRunning=false;this.updateInputState();break;case"progress_extend":this.showProgressExtend(e.message,e.currentIteration,e.newMax,e.reason);break}}handleSend(){var s;const e=((s=this.inputEl)==null?void 0:s.value)||"";const t=this.pendingTerminalSelection;if(!this.sendMessage(e,t))return;this.inputEl.value="";this.inputEl.style.height="auto";if(t)this.clearTerminalSelectionContext();this.updateInputState()}sendMessage(e,t=null){var n;const s=e.trim();if(!s)return false;if(this.isAgentRunning)return false;if(this.isWaitingConfirmation)return false;const r=t?hv(s,t):s;this.streamingEl=null;this.streamingText="";this.removeThinkingProcess();this.thinkingStepCount=0;this.livePreviewCache=[];this.addUserMessage(s,!!t);this.isAgentRunning=true;this.updateInputState();(n=this.wsSend)==null?void 0:n.call(this,JSON.stringify({type:"agent_start",message:r,locale:h_()}));return true}updateInputState(){var t;const e=this.isAgentRunning||this.isWaitingConfirmation;if(this.inputEl){this.inputEl.disabled=e;this.inputEl.placeholder=e?m("agent.thinking"):m("agent.placeholder")}if(this.sendBtn){this.sendBtn.disabled=e||!((t=this.inputEl)==null?void 0:t.value.trim())}}addUserMessage(e,t=false){this.appendMessage("user",e,{hasTerminalSelection:t})}renderTerminalSelectionContext(){var s;if(!this.contextEl)return;const e=this.pendingTerminalSelection;this.contextEl.classList.toggle("hidden",!e);this.contextEl.innerHTML="";if(!e)return;const t=e.sourceLabel||m("agent.selectionUnknownSource");this.contextEl.innerHTML=\`
\`;Oi(this.panelEl);this.localeCleanup=Os(()=>{this.updateInputState();this.renderTerminalSelectionContext();this.refreshCodeBlockActions()});this.parentEl.appendChild(this.panelEl);this.messagesEl=this.panelEl.querySelector("#agent-messages");this.contextEl=this.panelEl.querySelector("#agent-context");this.inputEl=this.panelEl.querySelector("#agent-input");this.sendBtn=this.panelEl.querySelector("#agent-send-btn");this.bindEvents();this.updateInputState()}bindEvents(){var e,t,s,r,n;(t=(e=this.panelEl)==null?void 0:e.querySelector("#agent-close-btn"))==null?void 0:t.addEventListener("click",()=>this.hide());(s=this.sendBtn)==null?void 0:s.addEventListener("click",()=>this.handleSend());(r=this.inputEl)==null?void 0:r.addEventListener("keydown",o=>{if(o.key==="Enter"&&!o.shiftKey){o.preventDefault();this.handleSend()}});(n=this.inputEl)==null?void 0:n.addEventListener("input",()=>{const o=this.inputEl;o.style.height="auto";o.style.height=Math.min(o.scrollHeight,140)+"px";this.updateInputState()})}toggle(){this.isVisible?this.hide():this.show()}show(){var e;if(!this.isLoggedIn)return;this.isVisible=true;if(this.panelEl)this.panelEl.style.display="flex";(e=this.inputEl)==null?void 0:e.focus();requestAnimationFrame(()=>{var t;return(t=this.onLayoutChange)==null?void 0:t.call(this)})}hide(){this.rejectPendingConfirmation(false);this.isVisible=false;if(this.panelEl)this.panelEl.style.display="none";requestAnimationFrame(()=>{var e;return(e=this.onLayoutChange)==null?void 0:e.call(this)})}rejectPendingConfirmation(e=true){this.resolvePendingConfirmation(false,e)}attachTerminalSelection(e,t){var r;const s=Cv(e,t);if(!s)return false;this.pendingTerminalSelection=s;this.renderTerminalSelectionContext();this.show();(r=this.inputEl)==null?void 0:r.focus();return true}clearTerminalSelectionContext(){this.pendingTerminalSelection=null;this.renderTerminalSelectionContext()}handleAgentFrame(e){switch(e.subType){case"thinking":this.showThinking(e.iteration);break;case"executing":this.showExecuting(e.tool,e.args);break;case"stream_chunk":this.handleStreamChunk(e.content);break;case"stream_end":this.handleStreamEnd(e.content);this.isAgentRunning=false;this.updateInputState();break;case"response":this.addAgentResponse(e.content);this.isAgentRunning=false;this.updateInputState();break;case"confirm_required":this.showConfirmDialog(e.command,e.reason);break;case"error":this.showError(e.message);this.isAgentRunning=false;this.updateInputState();break;case"progress_extend":this.showProgressExtend(e.message,e.currentIteration,e.newMax,e.reason);break}}handleSend(){var s;const e=((s=this.inputEl)==null?void 0:s.value)||"";const t=this.pendingTerminalSelection;if(!this.sendMessage(e,t))return;this.inputEl.value="";this.inputEl.style.height="auto";if(t)this.clearTerminalSelectionContext();this.updateInputState()}sendMessage(e,t=null){var n;const s=e.trim();if(!s)return false;if(this.isAgentRunning)return false;if(this.isWaitingConfirmation)return false;const r=t?kv(s,t):s;this.streamingEl=null;this.streamingText="";this.removeThinkingProcess();this.thinkingStepCount=0;this.livePreviewCache=[];this.addUserMessage(s,!!t);this.isAgentRunning=true;this.updateInputState();(n=this.wsSend)==null?void 0:n.call(this,JSON.stringify({type:"agent_start",message:r,locale:p_()}));return true}updateInputState(){var t;const e=this.isAgentRunning||this.isWaitingConfirmation;if(this.inputEl){this.inputEl.disabled=e;this.inputEl.placeholder=e?m("agent.thinking"):m("agent.placeholder")}if(this.sendBtn){this.sendBtn.disabled=e||!((t=this.inputEl)==null?void 0:t.value.trim())}}addUserMessage(e,t=false){this.appendMessage("user",e,{hasTerminalSelection:t})}renderTerminalSelectionContext(){var s;if(!this.contextEl)return;const e=this.pendingTerminalSelection;this.contextEl.classList.toggle("hidden",!e);this.contextEl.innerHTML="";if(!e)return;const t=e.sourceLabel||m("agent.selectionUnknownSource");this.contextEl.innerHTML=\`
<div class="agent-context-chip">
<details class="agent-context-details">
<summary class="agent-context-summary">
@@ -526,7 +526,7 @@ Please report this to https://github.com/markedjs/marked.\`,e){let r="<p>An erro
<div class="shrink-0 mt-0.5">\${c}</div>
<div class="flex-1 min-w-0 text-[13px]">\${d}</div>
</div>
\`}(f=this.messagesEl)==null?void 0:f.appendChild(r);if(o){this.enhanceCodeBlocks(r)}this.scrollToBottom()}renderMarkdown(e){let t;try{t=fe.parse(e,{async:false})}catch{return\`<div class="agent-md-content">\${be(e)}</div>\`}const s=v0.sanitize(t,{ADD_ATTR:["target","rel","class","loading","data-code-language"],ALLOW_UNKNOWN_PROTOCOLS:false,USE_PROFILES:{html:true}});return\`<div class="agent-md-content">\${s}</div>\`}enhanceCodeBlocks(e){e.querySelectorAll(".agent-md-code-block").forEach(t=>{if(t.dataset.actionsReady==="true")return;const s=t.querySelector("code");const r=t.querySelector(".agent-md-code-actions");const n=t.querySelector(".agent-md-code-meta");if(!s||!r||!n)return;const o=s.textContent||"";const a=this.createCodeActionButton("copy","content_copy",m("agent.codeCopy"));a.addEventListener("click",async()=>{const l=await xn(o);this.showCodeActionFeedback(a,l?"check":"error",l?m("agent.codeCopied"):m("agent.codeCopyFailed"))});r.appendChild(a);const h=av(t.dataset.codeLanguage,o);if(h&&this.getTerminalFillTarget&&this.fillTerminalInput){const l=this.getTerminalFillTarget();n.textContent=m("agent.codeTarget",{target:l.label});n.title=l.label;const c=this.createCodeActionButton("fill","input",m("agent.codeFill"));c.disabled=!l.available;c.addEventListener("click",()=>{var f,p;const d=(f=this.getTerminalFillTarget)==null?void 0:f.call(this);const u=!!(d==null?void 0:d.available)&&!!((p=this.fillTerminalInput)==null?void 0:p.call(this,h));this.showCodeActionFeedback(c,u?"check":"error",u?m("agent.codeFilled"):m("agent.codeFillFailed"))});r.appendChild(c)}t.dataset.actionsReady="true"})}refreshCodeBlockActions(){var e;(e=this.panelEl)==null?void 0:e.querySelectorAll(".agent-md-code-block").forEach(t=>{var a;const s=t.querySelector('[data-code-action="copy"]');if(s)this.setCodeActionButton(s,"content_copy",m("agent.codeCopy"));const r=t.querySelector('[data-code-action="fill"]');if(!r)return;this.setCodeActionButton(r,"input",m("agent.codeFill"));const n=(a=this.getTerminalFillTarget)==null?void 0:a.call(this);r.disabled=!(n==null?void 0:n.available);const o=t.querySelector(".agent-md-code-meta");if(o&&n){o.textContent=m("agent.codeTarget",{target:n.label});o.title=n.label}})}createCodeActionButton(e,t,s){const r=document.createElement("button");r.type="button";r.className="agent-md-code-action";r.dataset.codeAction=e;this.setCodeActionButton(r,t,s);return r}setCodeActionButton(e,t,s){e.replaceChildren();const r=document.createElement("span");r.className="material-symbols-outlined";r.setAttribute("aria-hidden","true");r.textContent=t;const n=document.createElement("span");n.textContent=s;e.append(r,n);e.title=s;e.setAttribute("aria-label",s)}showCodeActionFeedback(e,t,s){this.setCodeActionButton(e,t,s);window.setTimeout(()=>{if(!e.isConnected)return;const r=e.dataset.codeAction==="fill";this.setCodeActionButton(e,r?"input":"content_copy",r?m("agent.codeFill"):m("agent.codeCopy"))},1600)}scrollToBottom(){if(this.messagesEl){requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight})}}dispose(){var e,t;this.rejectPendingConfirmation(false);(e=this.localeCleanup)==null?void 0:e.call(this);this.localeCleanup=null;this.pendingTerminalSelection=null;(t=this.panelEl)==null?void 0:t.remove();this.panelEl=null;this.messagesEl=null;this.contextEl=null;this.inputEl=null;this.sendBtn=null;this.isVisible=false}}const dv={cf:{goodMax:100,fairMax:250},ws:{goodMax:100,fairMax:200}};function yd(i,e){const t=dv[e];if(i<=t.goodMax)return"good";if(i<=t.fairMax)return"fair";return"poor"}function uv(i,e,t,s,r){const n=Math.min(Math.max(0,e),Math.max(0,s-1));const o=r.additive?new Set(i):new Set;if(r.range&&t!==null){const a=Math.min(t,n);const h=Math.max(t,n);for(let l=a;l<=h;l++)o.add(l)}else if(r.additive&&o.has(n)){o.delete(n)}else{o.add(n)}return{selected:o,anchor:n}}const wd=128*1024;const fv=8;const pv=1e3;const mv=3e4;function Sd(i){if(i==="."||i==="..")return m("sftp.invalidName");if(i.includes("/")||i.includes("\\0"))return m("sftp.invalidName");return null}class ar{constructor(){w(this,"promise");w(this,"resolve");w(this,"reject");this.promise=new Promise((e,t)=>{this.resolve=e;this.reject=t})}}class gv{constructor(){w(this,"ready",null);w(this,"progress",null);w(this,"complete",null);w(this,"progressQueue",[]);w(this,"progressQueueHead",0)}waitReady(){this.ready=new ar;return this.ready.promise}resolveReady(){var e;(e=this.ready)==null?void 0:e.resolve({status:"ready"});this.ready=null}resolveConflict(e){var t;(t=this.ready)==null?void 0:t.resolve({status:"conflict",conflict:e});this.ready=null}waitProgress(){const e=this.progressQueue[this.progressQueueHead];if(e!==void 0){this.progressQueueHead++;this.compactProgressQueue();return Promise.resolve(e)}this.progress=new ar;return this.progress.promise}resolveProgress(e){if(this.progress){this.progress.resolve(e);this.progress=null;return}this.progressQueue.push(e)}waitComplete(){this.complete=new ar;return this.complete.promise}reso Line truncated
\`}(f=this.messagesEl)==null?void 0:f.appendChild(r);if(o){this.enhanceCodeBlocks(r)}this.scrollToBottom()}renderMarkdown(e){let t;try{t=fe.parse(e,{async:false})}catch{return\`<div class="agent-md-content">\${be(e)}</div>\`}const s=P0.sanitize(t,{ADD_ATTR:["target","rel","class","loading","data-code-language"],ALLOW_UNKNOWN_PROTOCOLS:false,USE_PROFILES:{html:true}});return\`<div class="agent-md-content">\${s}</div>\`}enhanceCodeBlocks(e){e.querySelectorAll(".agent-md-code-block").forEach(t=>{if(t.dataset.actionsReady==="true")return;const s=t.querySelector("code");const r=t.querySelector(".agent-md-code-actions");const n=t.querySelector(".agent-md-code-meta");if(!s||!r||!n)return;const o=s.textContent||"";const a=this.createCodeActionButton("copy","content_copy",m("agent.codeCopy"));a.addEventListener("click",async()=>{const l=await xn(o);this.showCodeActionFeedback(a,l?"check":"error",l?m("agent.codeCopied"):m("agent.codeCopyFailed"))});r.appendChild(a);const h=xv(t.dataset.codeLanguage,o);if(h&&this.getTerminalFillTarget&&this.fillTerminalInput){const l=this.getTerminalFillTarget();n.textContent=m("agent.codeTarget",{target:l.label});n.title=l.label;const c=this.createCodeActionButton("fill","input",m("agent.codeFill"));c.disabled=!l.available;c.addEventListener("click",()=>{var f,p;const d=(f=this.getTerminalFillTarget)==null?void 0:f.call(this);const u=!!(d==null?void 0:d.available)&&!!((p=this.fillTerminalInput)==null?void 0:p.call(this,h));this.showCodeActionFeedback(c,u?"check":"error",u?m("agent.codeFilled"):m("agent.codeFillFailed"))});r.appendChild(c)}t.dataset.actionsReady="true"})}refreshCodeBlockActions(){var e;(e=this.panelEl)==null?void 0:e.querySelectorAll(".agent-md-code-block").forEach(t=>{var a;const s=t.querySelector('[data-code-action="copy"]');if(s)this.setCodeActionButton(s,"content_copy",m("agent.codeCopy"));const r=t.querySelector('[data-code-action="fill"]');if(!r)return;this.setCodeActionButton(r,"input",m("agent.codeFill"));const n=(a=this.getTerminalFillTarget)==null?void 0:a.call(this);r.disabled=!(n==null?void 0:n.available);const o=t.querySelector(".agent-md-code-meta");if(o&&n){o.textContent=m("agent.codeTarget",{target:n.label});o.title=n.label}})}createCodeActionButton(e,t,s){const r=document.createElement("button");r.type="button";r.className="agent-md-code-action";r.dataset.codeAction=e;this.setCodeActionButton(r,t,s);return r}setCodeActionButton(e,t,s){e.replaceChildren();const r=document.createElement("span");r.className="material-symbols-outlined";r.setAttribute("aria-hidden","true");r.textContent=t;const n=document.createElement("span");n.textContent=s;e.append(r,n);e.title=s;e.setAttribute("aria-label",s)}showCodeActionFeedback(e,t,s){this.setCodeActionButton(e,t,s);window.setTimeout(()=>{if(!e.isConnected)return;const r=e.dataset.codeAction==="fill";this.setCodeActionButton(e,r?"input":"content_copy",r?m("agent.codeFill"):m("agent.codeCopy"))},1600)}scrollToBottom(){if(this.messagesEl){requestAnimationFrame(()=>{this.messagesEl.scrollTop=this.messagesEl.scrollHeight})}}dispose(){var e,t;this.rejectPendingConfirmation(false);(e=this.localeCleanup)==null?void 0:e.call(this);this.localeCleanup=null;this.pendingTerminalSelection=null;(t=this.panelEl)==null?void 0:t.remove();this.panelEl=null;this.messagesEl=null;this.contextEl=null;this.inputEl=null;this.sendBtn=null;this.isVisible=false}}const Tv={cf:{goodMax:100,fairMax:250},ws:{goodMax:100,fairMax:200}};function wd(i,e){const t=Tv[e];if(i<=t.goodMax)return"good";if(i<=t.fairMax)return"fair";return"poor"}function Lv(i,e,t,s,r){const n=Math.min(Math.max(0,e),Math.max(0,s-1));const o=r.additive?new Set(i):new Set;if(r.range&&t!==null){const a=Math.min(t,n);const h=Math.max(t,n);for(let l=a;l<=h;l++)o.add(l)}else if(r.additive&&o.has(n)){o.delete(n)}else{o.add(n)}return{selected:o,anchor:n}}const Sd=128*1024;const Av=8;const Rv=1e3;const Mv=3e4;function xd(i){if(i==="."||i==="..")return m("sftp.invalidName");if(i.includes("/")||i.includes("\\0"))return m("sftp.invalidName");return null}class lr{constructor(){w(this,"promise");w(this,"resolve");w(this,"reject");this.promise=new Promise((e,t)=>{this.resolve=e;this.reject=t})}}class Bv{constructor(){w(this,"ready",null);w(this,"progress",null);w(this,"complete",null);w(this,"progressQueue",[]);w(this,"progressQueueHead",0)}waitReady(){this.ready=new lr;return this.ready.promise}resolveReady(){var e;(e=this.ready)==null?void 0:e.resolve({status:"ready"});this.ready=null}resolveConflict(e){var t;(t=this.ready)==null?void 0:t.resolve({status:"conflict",conflict:e});this.ready=null}waitProgress(){const e=this.progressQueue[this.progressQueueHead];if(e!==void 0){this.progressQueueHead++;this.compactProgressQueue();return Promise.resolve(e)}this.progress=new lr;return this.progress.promise}resolveProgress(e){if(this.progress){this.progress.resolve(e);this.progress=null;return}this.progressQueue.push(e)}waitComplete(){this.complete=new lr;return this.complete.promise}reso Line truncated
<div class="flex flex-col w-full h-full bg-surface border-l border-outline-variant text-on-surface">
<!-- Header -->
<div class="sftp-panel-header flex items-center justify-between px-4 h-12 border-b border-outline-variant bg-elevated shrink-0">
@@ -628,7 +628,7 @@ Please report this to https://github.com/markedjs/marked.\`,e){let r="<p>An erro
<span id="sftp-item-count"></span>
</div>
</div>
\`;Oi(e);return e}bindKeyboard(){document.addEventListener("keydown",this.keydownHandler)}bindEvents(){const e=this.container.querySelector("#sftp-close-btn");const t=this.container.querySelector("#sftp-back-btn");const s=this.container.querySelector("#sftp-home-btn");const r=this.container.querySelector("#sftp-refresh-btn");const n=this.container.querySelector("#sftp-go-btn");const o=this.container.querySelector("#sftp-upload-btn");const a=this.container.querySelector("#sftp-mkdir-btn");const h=this.container.querySelector("#sftp-download-btn");const l=this.container.querySelector("#sftp-delete-btn");const c=this.container.querySelector("#sftp-rename-btn");const d=this.container.querySelector("#sftp-transfer-cancel-btn");const u=this.container.querySelector("#sftp-file-input");const f=this.container.querySelector("#sftp-path-input");e.addEventListener("click",()=>this.hide());t.addEventListener("click",()=>this.goBack());s.addEventListener("click",()=>this.navigate("~"));r.addEventListener("click",()=>this.refresh());n.addEventListener("click",()=>this.navigate(f.value));f.addEventListener("keydown",b=>{if(b.key==="Enter")this.navigate(f.value)});o.addEventListener("click",()=>u.click());a.addEventListener("click",()=>this.showMkdirDialog());h.addEventListener("click",()=>this.downloadSelected());l.addEventListener("click",()=>this.deleteSelected());c.addEventListener("click",()=>this.showRenameDialog());d.addEventListener("click",()=>this.cancelCurrentTransfer());u.addEventListener("change",b=>{const v=b.target.files;if(v&&v.length>0){this.queueUploadFiles(Array.from(v))}u.value=""});const p=this.container.querySelector("#sftp-file-list");p.addEventListener("dragover",b=>{b.preventDefault();b.stopPropagation();p.classList.add("bg-surface-variant")});p.addEventListener("dragleave",b=>{b.preventDefault();p.classList.remove("bg-surface-variant")});p.addEventListener("drop",b=>{var L;const v=b;v.preventDefault();v.stopPropagation();p.classList.remove("bg-surface-variant");const R=(L=v.dataTransfer)==null?void 0:L.files;if(R&&R.length>0){this.queueUploadFiles(Array.from(R))}})}show(){if(this.visible)return;this.visible=true;this.container.style.transform="translateX(0)";if(!this.sftpReady&&!this.initializing){this.initializing=true;this.sendJSON({type:"sftp_init"});this.showLoading()}}hide(){this.resetUploadQueue();this.resetDownloadQueue();this.visible=false;this.container.style.transform="translateX(100%)";this.sendJSON({type:"sftp_close"});this.closeWebSocket(1e3,"SFTP panel hidden");this.initializing=false;this.sftpReady=false}toggle(){if(this.visible){this.hide()}else{this.show()}}isVisible(){return this.visible}handleSSHReady(){this.closeWebSocket(1e3,"SSH session refreshed");this.resetUploadQueue();this.resetDownloadQueue();this.uploadWaiter.reset();this.sftpReady=false;this.downloadChunks=[];this.downloadFilename="";this.downloadSize=0;this.hideProgress();this.hideError();if(!this.visible){this.initializing=false;return}this.initializing=true;this.showLoading();this.setStatus(m("sftp.reconnecting"));this.sendJSON({type:"sftp_init"})}sendJSON(e){this.sendRaw(JSON.stringify(e))}sendBinary(e){this.sendRaw(e)}sendRaw(e){var t;if(((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN){this.ws.send(e);return}this.pendingSends.push(e);void this.ensureWebSocket()}async ensureWebSocket(){var t;if(((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN){this.flushPendingSends();return}if(this.connectingPromise){return this.connectingPromise}const e=this.getWebSocketUrl();if(!e){this.setStatus(m("sftp.waitingWebSocket"));if(!this.sftpWsRetryTimer){this.sftpWsRetryTimer=setTimeout(()=>{this.sftpWsRetryTimer=null;void this.ensureWebSocket()},200)}return}this.connectingPromise=new Promise((s,r)=>{const n=new WebSocket(e);this.ws=n;n.binaryType="arraybuffer";n.onopen=()=>{this.connectingPromise=null;this.startHeartbeat();this.flushPendingSends();s()};n.onmessage=o=>{if(typeof o.data==="string"){try{this.handleMessage(JSON.parse(o.data))}catch{this.showError(m("sftp.invalidResponse"))}return}if(o.data instanceof ArrayBuffer){this.handleBinaryData(new Uint8Array(o.data))}};n.onerror=()=>{const o=m("sftp.websocketError");this.stopHeartbeat();this.connectingPromise=null;this.initializing=false;this.sftpReady=false;this.pendingSends=[];this.rejectUploadWaiter(o);this.rejectDownloadWaiter(o);this.showError(o);r(new Error(o))};n.onclose=()=>{this.stopHeartbeat();if(this.ws===n){this.ws=null}this.connectingPromise=null;if(!this.closedByPanel.has(n)){const o=m("sftp.connectionClosed");this.initializing=false;this.sftpReady=false;this.pendingSends=[];this.rejectUploadWaiter(o);this.rejectDownloadWaiter(o);if(this.visible)this.showError(o)}}});try{await this.connectingPromise}catch{}}startHeartbeat(){this.stopHeartbeat();this.heartbeatInterval=setInterval(()=>{var e;if(((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN){this.ws.send(JSON.stringify({type:"ping"}))}},mv)}stopHeartbeat(){if(this.heartbeatInterval){cl Line truncated
\`;Oi(e);return e}bindKeyboard(){document.addEventListener("keydown",this.keydownHandler)}bindEvents(){const e=this.container.querySelector("#sftp-close-btn");const t=this.container.querySelector("#sftp-back-btn");const s=this.container.querySelector("#sftp-home-btn");const r=this.container.querySelector("#sftp-refresh-btn");const n=this.container.querySelector("#sftp-go-btn");const o=this.container.querySelector("#sftp-upload-btn");const a=this.container.querySelector("#sftp-mkdir-btn");const h=this.container.querySelector("#sftp-download-btn");const l=this.container.querySelector("#sftp-delete-btn");const c=this.container.querySelector("#sftp-rename-btn");const d=this.container.querySelector("#sftp-transfer-cancel-btn");const u=this.container.querySelector("#sftp-file-input");const f=this.container.querySelector("#sftp-path-input");e.addEventListener("click",()=>this.hide());t.addEventListener("click",()=>this.goBack());s.addEventListener("click",()=>this.navigate("~"));r.addEventListener("click",()=>this.refresh());n.addEventListener("click",()=>this.navigate(f.value));f.addEventListener("keydown",b=>{if(b.key==="Enter")this.navigate(f.value)});o.addEventListener("click",()=>u.click());a.addEventListener("click",()=>this.showMkdirDialog());h.addEventListener("click",()=>this.downloadSelected());l.addEventListener("click",()=>this.deleteSelected());c.addEventListener("click",()=>this.showRenameDialog());d.addEventListener("click",()=>this.cancelCurrentTransfer());u.addEventListener("change",b=>{const v=b.target.files;if(v&&v.length>0){this.queueUploadFiles(Array.from(v))}u.value=""});const p=this.container.querySelector("#sftp-file-list");p.addEventListener("dragover",b=>{b.preventDefault();b.stopPropagation();p.classList.add("bg-surface-variant")});p.addEventListener("dragleave",b=>{b.preventDefault();p.classList.remove("bg-surface-variant")});p.addEventListener("drop",b=>{var L;const v=b;v.preventDefault();v.stopPropagation();p.classList.remove("bg-surface-variant");const R=(L=v.dataTransfer)==null?void 0:L.files;if(R&&R.length>0){this.queueUploadFiles(Array.from(R))}})}show(){if(this.visible)return;this.visible=true;this.container.style.transform="translateX(0)";if(!this.sftpReady&&!this.initializing){this.initializing=true;this.sendJSON({type:"sftp_init"});this.showLoading()}}hide(){this.resetUploadQueue();this.resetDownloadQueue();this.visible=false;this.container.style.transform="translateX(100%)";this.sendJSON({type:"sftp_close"});this.closeWebSocket(1e3,"SFTP panel hidden");this.initializing=false;this.sftpReady=false}toggle(){if(this.visible){this.hide()}else{this.show()}}isVisible(){return this.visible}handleSSHReady(){this.closeWebSocket(1e3,"SSH session refreshed");this.resetUploadQueue();this.resetDownloadQueue();this.uploadWaiter.reset();this.sftpReady=false;this.downloadChunks=[];this.downloadFilename="";this.downloadSize=0;this.hideProgress();this.hideError();if(!this.visible){this.initializing=false;return}this.initializing=true;this.showLoading();this.setStatus(m("sftp.reconnecting"));this.sendJSON({type:"sftp_init"})}sendJSON(e){this.sendRaw(JSON.stringify(e))}sendBinary(e){this.sendRaw(e)}sendRaw(e){var t;if(((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN){this.ws.send(e);return}this.pendingSends.push(e);void this.ensureWebSocket()}async ensureWebSocket(){var t;if(((t=this.ws)==null?void 0:t.readyState)===WebSocket.OPEN){this.flushPendingSends();return}if(this.connectingPromise){return this.connectingPromise}const e=this.getWebSocketUrl();if(!e){this.setStatus(m("sftp.waitingWebSocket"));if(!this.sftpWsRetryTimer){this.sftpWsRetryTimer=setTimeout(()=>{this.sftpWsRetryTimer=null;void this.ensureWebSocket()},200)}return}this.connectingPromise=new Promise((s,r)=>{const n=new WebSocket(e);this.ws=n;n.binaryType="arraybuffer";n.onopen=()=>{this.connectingPromise=null;this.startHeartbeat();this.flushPendingSends();s()};n.onmessage=o=>{if(typeof o.data==="string"){try{this.handleMessage(JSON.parse(o.data))}catch{this.showError(m("sftp.invalidResponse"))}return}if(o.data instanceof ArrayBuffer){this.handleBinaryData(new Uint8Array(o.data))}};n.onerror=()=>{const o=m("sftp.websocketError");this.stopHeartbeat();this.connectingPromise=null;this.initializing=false;this.sftpReady=false;this.pendingSends=[];this.rejectUploadWaiter(o);this.rejectDownloadWaiter(o);this.showError(o);r(new Error(o))};n.onclose=()=>{this.stopHeartbeat();if(this.ws===n){this.ws=null}this.connectingPromise=null;if(!this.closedByPanel.has(n)){const o=m("sftp.connectionClosed");this.initializing=false;this.sftpReady=false;this.pendingSends=[];this.rejectUploadWaiter(o);this.rejectDownloadWaiter(o);if(this.visible)this.showError(o)}}});try{await this.connectingPromise}catch{}}startHeartbeat(){this.stopHeartbeat();this.heartbeatInterval=setInterval(()=>{var e;if(((e=this.ws)==null?void 0:e.readyState)===WebSocket.OPEN){this.ws.send(JSON.stringify({type:"ping"}))}},Mv)}stopHeartbeat(){if(this.heartbeatInterval){cl Line truncated
<div class="sftp-entry flex items-center gap-2 px-3 py-1.5 hover:bg-surface-variant cursor-pointer transition-colors border-b border-outline-variant/30 text-[12px]"
data-idx="\${n}" data-name="\${this.escapeHtml(r.name)}" data-type="\${r.type}"
role="option" aria-selected="\${this.selectedEntries.has(r.name)}" tabindex="-1">
@@ -643,12 +643,12 @@ Please report this to https://github.com/markedjs/marked.\`,e){let r="<p>An erro
<span class="text-on-surface-variant text-[10px] w-20 text-right shrink-0 hidden md:block">\${r.permissions}</span>
<span class="text-on-surface-variant text-[10px] w-24 text-right shrink-0 hidden lg:block">\${this.formatTimestamp(r.modifiedTime)}</span>
</div>
\`).join("");e.querySelectorAll(".sftp-entry").forEach(r=>{r.addEventListener("click",n=>{const o=r;const a=parseInt(o.dataset["idx"]);this.selectEntry(a,{additive:n.ctrlKey||n.metaKey,range:n.shiftKey})});r.addEventListener("dblclick",()=>{const n=r;const o=parseInt(n.dataset["idx"]);const a=s[o];if(a.isDir){this.navigate(this.currentPath==="/"?\`/\${a.name}\`:\`\${this.currentPath}/\${a.name}\`)}else{this.downloadEntries([a])}});r.addEventListener("contextmenu",n=>{const o=n;o.preventDefault();const a=r;const h=parseInt(a.dataset["idx"]);const l=s[h];if(!this.selectedEntries.has(l.name)){this.selectEntry(h,{additive:false,range:false})}this.showContextMenu(o.clientX,o.clientY,l)})});this.syncSelectionUI()}selectEntry(e,t){const s=new Set;this.renderedEntries.forEach((n,o)=>{if(this.selectedEntries.has(n.name))s.add(o)});const r=uv(s,e,this.selectionAnchorIndex,this.renderedEntries.length,t);this.selectionAnchorIndex=r.anchor;this.selectedEntries.clear();r.selected.forEach(n=>{const o=this.renderedEntries[n];if(o)this.selectedEntries.set(o.name,o)});this.syncSelectionUI();this.updateActionButtons()}clearSelection(){this.selectedEntries.clear();this.selectionAnchorIndex=null;this.syncSelectionUI();this.updateActionButtons()}selectAllEntries(){this.selectedEntries=new Map(this.renderedEntries.map(e=>[e.name,e]));this.selectionAnchorIndex=this.renderedEntries.length>0?this.renderedEntries.length-1:null;this.syncSelectionUI();this.updateActionButtons()}syncSelectionUI(){this.container.querySelectorAll(".sftp-entry").forEach(e=>{const t=this.selectedEntries.has(e.dataset["name"]||"");e.classList.toggle("bg-surface-variant",t);e.setAttribute("aria-selected",String(t))})}updateActionButtons(){const e=this.container.querySelector("#sftp-download-btn");const t=this.container.querySelector("#sftp-delete-btn");const s=this.container.querySelector("#sftp-rename-btn");const r=[...this.selectedEntries.values()];const n=r.length>0;e.disabled=!r.some(o=>!o.isDir);t.disabled=!n;s.disabled=r.length!==1;this.setIdleStatus(n?m("sftp.selectedCount",{count:r.length}):this.getItemsStatus())}showContextMenu(e,t,s){this.hideContextMenu();const r=document.createElement("div");r.id="sftp-context-menu";r.className="fixed z-[200] bg-elevated border border-outline-variant shadow-lg py-1 text-[12px]";r.style.left=e+"px";r.style.top=t+"px";const n=[...this.selectedEntries.values()];const o=[];if(n.length===1){o.push({label:m("sftp.contextOpen"),icon:"open_in_new",action:()=>{if(s.isDir){this.navigate(this.currentPath==="/"?\`/\${s.name}\`:\`\${this.currentPath}/\${s.name}\`)}else{this.downloadEntries([s])}}})}if(n.some(c=>!c.isDir)){o.push({label:m("sftp.contextDownload"),icon:"download",action:()=>this.downloadSelected()})}if(n.length===1){o.push({label:m("sftp.contextRename"),icon:"drive_file_rename_outline",action:()=>{void this.showRenameDialog()}})}o.push({label:m("sftp.contextDelete"),icon:"delete",action:()=>{void this.deleteSelected()},className:"text-error"});r.innerHTML=o.map(c=>\`
\`).join("");e.querySelectorAll(".sftp-entry").forEach(r=>{r.addEventListener("click",n=>{const o=r;const a=parseInt(o.dataset["idx"]);this.selectEntry(a,{additive:n.ctrlKey||n.metaKey,range:n.shiftKey})});r.addEventListener("dblclick",()=>{const n=r;const o=parseInt(n.dataset["idx"]);const a=s[o];if(a.isDir){this.navigate(this.currentPath==="/"?\`/\${a.name}\`:\`\${this.currentPath}/\${a.name}\`)}else{this.downloadEntries([a])}});r.addEventListener("contextmenu",n=>{const o=n;o.preventDefault();const a=r;const h=parseInt(a.dataset["idx"]);const l=s[h];if(!this.selectedEntries.has(l.name)){this.selectEntry(h,{additive:false,range:false})}this.showContextMenu(o.clientX,o.clientY,l)})});this.syncSelectionUI()}selectEntry(e,t){const s=new Set;this.renderedEntries.forEach((n,o)=>{if(this.selectedEntries.has(n.name))s.add(o)});const r=Lv(s,e,this.selectionAnchorIndex,this.renderedEntries.length,t);this.selectionAnchorIndex=r.anchor;this.selectedEntries.clear();r.selected.forEach(n=>{const o=this.renderedEntries[n];if(o)this.selectedEntries.set(o.name,o)});this.syncSelectionUI();this.updateActionButtons()}clearSelection(){this.selectedEntries.clear();this.selectionAnchorIndex=null;this.syncSelectionUI();this.updateActionButtons()}selectAllEntries(){this.selectedEntries=new Map(this.renderedEntries.map(e=>[e.name,e]));this.selectionAnchorIndex=this.renderedEntries.length>0?this.renderedEntries.length-1:null;this.syncSelectionUI();this.updateActionButtons()}syncSelectionUI(){this.container.querySelectorAll(".sftp-entry").forEach(e=>{const t=this.selectedEntries.has(e.dataset["name"]||"");e.classList.toggle("bg-surface-variant",t);e.setAttribute("aria-selected",String(t))})}updateActionButtons(){const e=this.container.querySelector("#sftp-download-btn");const t=this.container.querySelector("#sftp-delete-btn");const s=this.container.querySelector("#sftp-rename-btn");const r=[...this.selectedEntries.values()];const n=r.length>0;e.disabled=!r.some(o=>!o.isDir);t.disabled=!n;s.disabled=r.length!==1;this.setIdleStatus(n?m("sftp.selectedCount",{count:r.length}):this.getItemsStatus())}showContextMenu(e,t,s){this.hideContextMenu();const r=document.createElement("div");r.id="sftp-context-menu";r.className="fixed z-[200] bg-elevated border border-outline-variant shadow-lg py-1 text-[12px]";r.style.left=e+"px";r.style.top=t+"px";const n=[...this.selectedEntries.values()];const o=[];if(n.length===1){o.push({label:m("sftp.contextOpen"),icon:"open_in_new",action:()=>{if(s.isDir){this.navigate(this.currentPath==="/"?\`/\${s.name}\`:\`\${this.currentPath}/\${s.name}\`)}else{this.downloadEntries([s])}}})}if(n.some(c=>!c.isDir)){o.push({label:m("sftp.contextDownload"),icon:"download",action:()=>this.downloadSelected()})}if(n.length===1){o.push({label:m("sftp.contextRename"),icon:"drive_file_rename_outline",action:()=>{void this.showRenameDialog()}})}o.push({label:m("sftp.contextDelete"),icon:"delete",action:()=>{void this.deleteSelected()},className:"text-error"});r.innerHTML=o.map(c=>\`
<div class="flex items-center gap-2 px-3 py-1.5 hover:bg-surface-variant cursor-pointer \${c.className||""}">
<span class="material-symbols-outlined" style="font-size: 14px;">\${c.icon}</span>
\${c.label}
</div>
\`).join("");const a=r.querySelectorAll("div");a.forEach((c,d)=>{c.addEventListener("click",()=>{o[d].action();this.hideContextMenu()})});document.body.appendChild(r);const h=r.getBoundingClientRect();if(h.right>window.innerWidth){r.style.left=Math.max(0,window.innerWidth-h.width-4)+"px"}if(h.bottom>window.innerHeight){r.style.top=Math.max(0,window.innerHeight-h.height-4)+"px"}const l=c=>{if(!r.contains(c.target)){this.hideContextMenu();document.removeEventListener("click",l)}};setTimeout(()=>document.addEventListener("click",l),0)}hideContextMenu(){const e=document.getElementById("sftp-context-menu");if(e)e.remove()}queueUploadFiles(e){const t=e.slice();if(t.length===0)return;const s=this.currentPath;const r=this.uploadQueueGeneration;let n=0;for(const o of t){const a=this.uploadQueuePending>0;this.uploadQueuePending++;if(a){this.uploadQueuedFiles++;n++}const h=this.uploadQueueTail.then(async()=>{if(a){this.uploadQueuedFiles=Math.max(0,this.uploadQueuedFiles-1);this.setQueueStatus()}if(r!==this.uploadQueueGeneration||!this.visible)return;await this.uploadSingleFile(o,s)});this.uploadQueueTail=h.catch(l=>{this.showError(m("sftp.uploadFailed",{message:l instanceof Error?l.message:String(l)}))}).finally(()=>{if(r===this.uploadQueueGeneration){this.uploadQueuePending=Math.max(0,this.uploadQueuePending-1)}})}if(n>0){this.setQueueStatus()}void this.uploadQueueTail}resetUploadQueue(){const e=this.uploadActive;this.uploadQueueGeneration++;this.uploadQueuePending=0;this.uploadQueuedFiles=0;this.uploadActive=false;this.uploadCancelRequested=e;this.uploadCancelConfirmed=true;this.uploadWaiter.reject(m("sftp.uploadCancelled"));this.resolveUploadCancelWaiter();this.uploadQueueTail=Promise.resolve()}async uploadSingleFile(e,t){const s=t==="/"?\`/\${e.name}\`:\`\${t}/\${e.name}\`;let r=0;let n=0;const o=wd*fv;let a=null;let h=null;let l=0;this.uploadActive=true;this.uploadCancelRequested=false;this.uploadCancelConfirmed=false;this.uploadCancelWaiter=null;this.setQueueStatus();try{const c=this.uploadWaiter.waitReady();this.sendJSON({type:"sftp_upload_start",path:s,size:e.size,overwrite:false});let d=await c;if(d.status==="conflict"){const b=await Ms({title:m("sftp.overwriteTitle"),message:m("sftp.overwriteMessage",{name:e.name,existingSize:this.formatSize(d.conflict.existingSize),newSize:this.formatSize(e.size)}),confirmText:m("sftp.overwrite"),cancelText:m("common.cancel"),variant:"danger"});if(!b||this.uploadCancelRequested||!this.visible){this.uploadActive=false;this.setIdleStatus(m("sftp.uploadSkipped"));return}const v=this.uploadWaiter.waitReady();this.sendJSON({type:"sftp_upload_start",path:s,size:e.size,overwrite:true});d=await v}if(d.status!=="ready"){throw new Error(m("sftp.uploadConflictUnresolved"))}a=e.stream().getReader();this.showProgress(m("sftp.uploading",{name:e.name}),0);if(this.uploadCancelRequested){await this.waitForUploadCancel();return}const u=async()=>{while(!h||l>=h.length){const{done:R,value:L}=await a.read();if(R)return null;h=L;l=0}const b=Math.min(l+wd,h.length);const v=h.subarray(l,b);l=b;return v};const f=async()=>{if(this.uploadCancelRequested){throw new Error(m("sftp.uploadCancelled"))}const b=await u();if(!b)return false;this.sendBinary(b);r+=b.length;return true};while(r<e.size&&r-n<o){if(this.uploadCancelRequested){await this.waitForUploadCancel();return}if(!await f()){throw new Error(m("sftp.uploadStreamEnded"))}}while(n<e.size){n=await this.uploadWaiter.waitProgress();if(this.uploadCancelRequested){await this.waitForUploadCancel();return}while(r<e.size&&r-n<o){if(!await f()){throw new Error(m("sftp.uploadStreamEnded"))}}}const p=this.uploadWaiter.waitComplete();this.sendJSON({type:"sftp_upload_end"});await p}catch(c){if(this.uploadCancelRequested){await this.waitForUploadCancel()}else{this.sendJSON({type:"sftp_upload_cancel"});this.showError(m("sftp.uploadFailed",{message:c instanceof Error?c.message:String(c)}))}this.uploadWaiter.reset();return}finally{this.uploadActive=false;this.uploadCancelRequested=false;this.uploadCancelConfirmed=false;this.uploadCancelWaiter=null;a==null?void 0:a.releaseLock()}}downloadSelected(){this.downloadEntries([...this.selectedEntries.values()])}downloadEntries(e){e.filter(t=>!t.isDir).forEach(t=>{const s=this.currentPath==="/"?\`/\${t.name}\`:\`\${this.currentPath}/\${t.name}\`;this.queueDownloadFile(s,t.name)})}queueDownloadFile(e,t){const s=this.downloadQueueGeneration;const r=this.downloadQueuePending>0;this.downloadQueuePending++;if(r){this.downloadQueuedFiles++;this.setQueueStatus()}const n=this.downloadQueueTail.then(async()=>{if(r){this.downloadQueuedFiles=Math.max(0,this.downloadQueuedFiles-1);this.setQueueStatus()}if(s!==this.downloadQueueGeneration||!this.visible)return;await this.downloadFile(e,t)});this.downloadQueueTail=n.catch(o=>{this.showError(m("sftp.downloadFailed",{message:o instanceof Error?o.message:String(o)}))}).finally(()=>{if(s===this.downloadQueueGeneration){this.downloadQueuePending=Math.max(0,this.downloadQueuePending-1) Line truncated
\`).join("");const a=r.querySelectorAll("div");a.forEach((c,d)=>{c.addEventListener("click",()=>{o[d].action();this.hideContextMenu()})});document.body.appendChild(r);const h=r.getBoundingClientRect();if(h.right>window.innerWidth){r.style.left=Math.max(0,window.innerWidth-h.width-4)+"px"}if(h.bottom>window.innerHeight){r.style.top=Math.max(0,window.innerHeight-h.height-4)+"px"}const l=c=>{if(!r.contains(c.target)){this.hideContextMenu();document.removeEventListener("click",l)}};setTimeout(()=>document.addEventListener("click",l),0)}hideContextMenu(){const e=document.getElementById("sftp-context-menu");if(e)e.remove()}queueUploadFiles(e){const t=e.slice();if(t.length===0)return;const s=this.currentPath;const r=this.uploadQueueGeneration;let n=0;for(const o of t){const a=this.uploadQueuePending>0;this.uploadQueuePending++;if(a){this.uploadQueuedFiles++;n++}const h=this.uploadQueueTail.then(async()=>{if(a){this.uploadQueuedFiles=Math.max(0,this.uploadQueuedFiles-1);this.setQueueStatus()}if(r!==this.uploadQueueGeneration||!this.visible)return;await this.uploadSingleFile(o,s)});this.uploadQueueTail=h.catch(l=>{this.showError(m("sftp.uploadFailed",{message:l instanceof Error?l.message:String(l)}))}).finally(()=>{if(r===this.uploadQueueGeneration){this.uploadQueuePending=Math.max(0,this.uploadQueuePending-1)}})}if(n>0){this.setQueueStatus()}void this.uploadQueueTail}resetUploadQueue(){const e=this.uploadActive;this.uploadQueueGeneration++;this.uploadQueuePending=0;this.uploadQueuedFiles=0;this.uploadActive=false;this.uploadCancelRequested=e;this.uploadCancelConfirmed=true;this.uploadWaiter.reject(m("sftp.uploadCancelled"));this.resolveUploadCancelWaiter();this.uploadQueueTail=Promise.resolve()}async uploadSingleFile(e,t){const s=t==="/"?\`/\${e.name}\`:\`\${t}/\${e.name}\`;let r=0;let n=0;const o=Sd*Av;let a=null;let h=null;let l=0;this.uploadActive=true;this.uploadCancelRequested=false;this.uploadCancelConfirmed=false;this.uploadCancelWaiter=null;this.setQueueStatus();try{const c=this.uploadWaiter.waitReady();this.sendJSON({type:"sftp_upload_start",path:s,size:e.size,overwrite:false});let d=await c;if(d.status==="conflict"){const b=await Bs({title:m("sftp.overwriteTitle"),message:m("sftp.overwriteMessage",{name:e.name,existingSize:this.formatSize(d.conflict.existingSize),newSize:this.formatSize(e.size)}),confirmText:m("sftp.overwrite"),cancelText:m("common.cancel"),variant:"danger"});if(!b||this.uploadCancelRequested||!this.visible){this.uploadActive=false;this.setIdleStatus(m("sftp.uploadSkipped"));return}const v=this.uploadWaiter.waitReady();this.sendJSON({type:"sftp_upload_start",path:s,size:e.size,overwrite:true});d=await v}if(d.status!=="ready"){throw new Error(m("sftp.uploadConflictUnresolved"))}a=e.stream().getReader();this.showProgress(m("sftp.uploading",{name:e.name}),0);if(this.uploadCancelRequested){await this.waitForUploadCancel();return}const u=async()=>{while(!h||l>=h.length){const{done:R,value:L}=await a.read();if(R)return null;h=L;l=0}const b=Math.min(l+Sd,h.length);const v=h.subarray(l,b);l=b;return v};const f=async()=>{if(this.uploadCancelRequested){throw new Error(m("sftp.uploadCancelled"))}const b=await u();if(!b)return false;this.sendBinary(b);r+=b.length;return true};while(r<e.size&&r-n<o){if(this.uploadCancelRequested){await this.waitForUploadCancel();return}if(!await f()){throw new Error(m("sftp.uploadStreamEnded"))}}while(n<e.size){n=await this.uploadWaiter.waitProgress();if(this.uploadCancelRequested){await this.waitForUploadCancel();return}while(r<e.size&&r-n<o){if(!await f()){throw new Error(m("sftp.uploadStreamEnded"))}}}const p=this.uploadWaiter.waitComplete();this.sendJSON({type:"sftp_upload_end"});await p}catch(c){if(this.uploadCancelRequested){await this.waitForUploadCancel()}else{this.sendJSON({type:"sftp_upload_cancel"});this.showError(m("sftp.uploadFailed",{message:c instanceof Error?c.message:String(c)}))}this.uploadWaiter.reset();return}finally{this.uploadActive=false;this.uploadCancelRequested=false;this.uploadCancelConfirmed=false;this.uploadCancelWaiter=null;a==null?void 0:a.releaseLock()}}downloadSelected(){this.downloadEntries([...this.selectedEntries.values()])}downloadEntries(e){e.filter(t=>!t.isDir).forEach(t=>{const s=this.currentPath==="/"?\`/\${t.name}\`:\`\${this.currentPath}/\${t.name}\`;this.queueDownloadFile(s,t.name)})}queueDownloadFile(e,t){const s=this.downloadQueueGeneration;const r=this.downloadQueuePending>0;this.downloadQueuePending++;if(r){this.downloadQueuedFiles++;this.setQueueStatus()}const n=this.downloadQueueTail.then(async()=>{if(r){this.downloadQueuedFiles=Math.max(0,this.downloadQueuedFiles-1);this.setQueueStatus()}if(s!==this.downloadQueueGeneration||!this.visible)return;await this.downloadFile(e,t)});this.downloadQueueTail=n.catch(o=>{this.showError(m("sftp.downloadFailed",{message:o instanceof Error?o.message:String(o)}))}).finally(()=>{if(s===this.downloadQueueGeneration){this.downloadQueuePending=Math.max(0,this.downloadQueuePending-1) Line truncated
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
* @license MIT
*
@@ -659,7 +659,7 @@ Please report this to https://github.com/markedjs/marked.\`,e){let r="<p>An erro
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
*/var vv=2;var bv=1;var yv=class cx{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(){var u;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:((u=this._terminal.options.overviewRuler)==null?void 0:u.width)||14,s=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(s.getPropertyValue("height")),n=Math.max(0,parseInt(s.getPropertyValue("width"))),o=window.getComputedStyle(this._terminal.element),a={top:parseInt(o.getPropertyValue("padding-top")),bottom:parseInt(o.getPropertyValue("padding-bottom")),right:parseInt(o.getPropertyValue("padding-right")),left:parseInt(o.getPropertyValue("padding-left"))},h=a.top+a.bottom,l=a.right+a.left,c=r-h,d=n-l-t;return{cols:Math.max(vv,Math.floor(d/e.css.cell.width)),rows:Math.max(bv,Math.floor(c/e.css.cell.height))}}};/**
*/var Pv=2;var Dv=1;var $v=class Ex{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(){var u;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:((u=this._terminal.options.overviewRuler)==null?void 0:u.width)||14,s=window.getComputedStyle(this._terminal.element.parentElement),r=parseInt(s.getPropertyValue("height")),n=Math.max(0,parseInt(s.getPropertyValue("width"))),o=window.getComputedStyle(this._terminal.element),a={top:parseInt(o.getPropertyValue("padding-top")),bottom:parseInt(o.getPropertyValue("padding-bottom")),right:parseInt(o.getPropertyValue("padding-right")),left:parseInt(o.getPropertyValue("padding-left"))},h=a.top+a.bottom,l=a.right+a.left,c=r-h,d=n-l-t;return{cols:Math.max(Pv,Math.floor(d/e.css.cell.width)),rows:Math.max(Dv,Math.floor(c/e.css.cell.height))}}};/**
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
* @license MIT
*
@@ -670,13 +670,13 @@ Please report this to https://github.com/markedjs/marked.\`,e){let r="<p>An erro
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
*/var wv=class dx{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?xd.isErrorNoTelemetry(e)?new xd(e.message+\`
*/var Ov=class Tx{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Cd.isErrorNoTelemetry(e)?new Cd(e.message+\`
\`+e.stack):new 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)}};var Sv=new wv;function Ra(i){xv(i)||Sv.onUnexpectedError(i)}var Fl="Canceled";function xv(i){return i instanceof Cv?true:i instanceof Error&&i.name===Fl&&i.message===Fl}var Cv=class ux extends Error{constructor(){super(Fl),this.name=this.message}};var xd=class zl extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof zl)return e;let t=new zl;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}};var kv;(i=>{function e(n){return n<0}i.isLessThan=e;function t(n){return n<=0}i.isLessThanOrEqual=t;function s(n){return n>0}i.isGreaterThan=s;function r(n){return n===0}i.isNeitherLessOrGreaterThan=r,i.greaterThan=1,i.lessThan=-1,i.neitherLessOrGreaterThan=0})(kv||(kv={}));function Ev(i,e){let t=this,s=false,r;return function(){if(s)return r;if(s=true,e);else r=i.apply(t,arguments);return r}}var Pp;(i=>{function e(g){return g&&typeof g=="object"&&typeof g[Symbol.iterator]=="function"}i.is=e;let t=Object.freeze([]);function s(){return t}i.empty=s;function*r(g){yield g}i.single=r;function n(g){return e(g)?g:r(g)}i.wrap=n;function o(g){return g||t}i.from=o;function*a(g){for(let E=g.length-1;E>=0;E--)yield g[E]}i.reverse=a;function h(g){return!g||g[Symbol.iterator]().next().done===true}i.isEmpty=h;function l(g){return g[Symbol.iterator]().next().value}i.first=l;function c(g,E){let k=0;for(let D of g)if(E(D,k++))return true;return false}i.some=c;function d(g,E){for(let k of g)if(E(k))return k}i.find=d;function*u(g,E){for(let k of g)E(k)&&(yield k)}i.filter=u;function*f(g,E){let k=0;for(let D of g)yield E(D,k++)}i.map=f;function*p(g,E){let k=0;for(let D of g)yield*E(D,k++)}i.flatMap=p;function*b(...g){for(let E of g)yield*E}i.concat=b;function v(g,E,k){let D=k;for(let N of g)D=E(D,N);return D}i.reduce=v;function*R(g,E,k=g.length){for(E<0&&(E+=g.length),k<0?k+=g.length:k>g.length&&(k=g.length);E<k;E++)yield g[E]}i.slice=R;function L(g,E=Number.POSITIVE_INFINITY){let k=[];if(E===0)return[k,g];let D=g[Symbol.iterator]();for(let N=0;N<E;N++){let z=D.next();if(z.done)return[k,i.empty()];k.push(z.value)}return[k,{[Symbol.iterator](){return D}}]}i.consume=L;async function A(g){let E=[];for await(let k of g)E.push(k);return Promise.resolve(E)}i.asyncToArray=A})(Pp||(Pp={}));function Tv(i){return i}function Dp(i,e){}function en(i){if(Pp.is(i)){let e=[];for(let t of i)if(t)try{t.dispose()}catch(s){e.push(s)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"Encountered errors while disposing of store");return Array.isArray(i)?[]:i}else if(i)return i.dispose(),i}function $p(...i){let e=gr(()=>en(i));return e}function gr(i){let e=Tv({dispose:Ev(()=>{i()})});return e}var Op=class Fp{constructor(){this._toDispose=new Set;this._isDisposed=false}dispose(){this._isDisposed||(this._isDisposed=true,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{en(this._toDispose)}finally{this._toDispose.clear()}}add(e){if(!e)return e;if(e===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Fp.DISABLE_DISPOSED_WARNING||console.warn(new 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 new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),Dp())}};Op.DISABLE_DISPOSED_WARNING=false;var Xh=Op;var hs=class fx{constructor(){this._store=new Xh;Dp(this._store)}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};hs.None=Object.freeze({dispose(){}});var Po=class px{constructor(){this._isDisposed=false}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null?void 0:t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=true,(e=this._value)==null?void 0:e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}};var Lv=globalThis.performance&&typeof globalThis.performance.now=="function";var Av=class zp{static create(e){return new zp(e)}constructor(e){this._now=Lv&&e===false?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=th Line truncated
\`+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)}};var Fv=new Ov;function Ba(i){zv(i)||Fv.onUnexpectedError(i)}var zl="Canceled";function zv(i){return i instanceof Nv?true:i instanceof Error&&i.name===zl&&i.message===zl}var Nv=class Lx extends Error{constructor(){super(zl),this.name=this.message}};var Cd=class Nl extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof Nl)return e;let t=new Nl;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}};var Hv;(i=>{function e(n){return n<0}i.isLessThan=e;function t(n){return n<=0}i.isLessThanOrEqual=t;function s(n){return n>0}i.isGreaterThan=s;function r(n){return n===0}i.isNeitherLessOrGreaterThan=r,i.greaterThan=1,i.lessThan=-1,i.neitherLessOrGreaterThan=0})(Hv||(Hv={}));function Wv(i,e){let t=this,s=false,r;return function(){if(s)return r;if(s=true,e);else r=i.apply(t,arguments);return r}}var zp;(i=>{function e(g){return g&&typeof g=="object"&&typeof g[Symbol.iterator]=="function"}i.is=e;let t=Object.freeze([]);function s(){return t}i.empty=s;function*r(g){yield g}i.single=r;function n(g){return e(g)?g:r(g)}i.wrap=n;function o(g){return g||t}i.from=o;function*a(g){for(let E=g.length-1;E>=0;E--)yield g[E]}i.reverse=a;function h(g){return!g||g[Symbol.iterator]().next().done===true}i.isEmpty=h;function l(g){return g[Symbol.iterator]().next().value}i.first=l;function c(g,E){let k=0;for(let D of g)if(E(D,k++))return true;return false}i.some=c;function d(g,E){for(let k of g)if(E(k))return k}i.find=d;function*u(g,E){for(let k of g)E(k)&&(yield k)}i.filter=u;function*f(g,E){let k=0;for(let D of g)yield E(D,k++)}i.map=f;function*p(g,E){let k=0;for(let D of g)yield*E(D,k++)}i.flatMap=p;function*b(...g){for(let E of g)yield*E}i.concat=b;function v(g,E,k){let D=k;for(let N of g)D=E(D,N);return D}i.reduce=v;function*R(g,E,k=g.length){for(E<0&&(E+=g.length),k<0?k+=g.length:k>g.length&&(k=g.length);E<k;E++)yield g[E]}i.slice=R;function L(g,E=Number.POSITIVE_INFINITY){let k=[];if(E===0)return[k,g];let D=g[Symbol.iterator]();for(let N=0;N<E;N++){let z=D.next();if(z.done)return[k,i.empty()];k.push(z.value)}return[k,{[Symbol.iterator](){return D}}]}i.consume=L;async function A(g){let E=[];for await(let k of g)E.push(k);return Promise.resolve(E)}i.asyncToArray=A})(zp||(zp={}));function Uv(i){return i}function Np(i,e){}function en(i){if(zp.is(i)){let e=[];for(let t of i)if(t)try{t.dispose()}catch(s){e.push(s)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"Encountered errors while disposing of store");return Array.isArray(i)?[]:i}else if(i)return i.dispose(),i}function Hp(...i){let e=gr(()=>en(i));return e}function gr(i){let e=Uv({dispose:Wv(()=>{i()})});return e}var Wp=class Up{constructor(){this._toDispose=new Set;this._isDisposed=false}dispose(){this._isDisposed||(this._isDisposed=true,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{en(this._toDispose)}finally{this._toDispose.clear()}}add(e){if(!e)return e;if(e===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Up.DISABLE_DISPOSED_WARNING||console.warn(new 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 new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),Np())}};Wp.DISABLE_DISPOSED_WARNING=false;var Zh=Wp;var hs=class Ax{constructor(){this._store=new Zh;Np(this._store)}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};hs.None=Object.freeze({dispose(){}});var $o=class Rx{constructor(){this._isDisposed=false}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null?void 0:t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=true,(e=this._value)==null?void 0:e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}};var qv=globalThis.performance&&typeof globalThis.performance.now=="function";var Kv=class qp{static create(e){return new qp(e)}constructor(e){this._now=qv&&e===false?Date.now:globalThis.performance.now.bind(globalThis.performance),this._startTime=this._now(),this._stopTime=-1}stop(){this._stopTime=this._now()}reset(){this._startTime=th Line truncated
\`).slice(2).join(\`
\`))}};var Pv=class mx extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}};var Dv=class gx extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}};var $v=0;var Ma=class _x{constructor(e){this.value=e;this.id=$v++}};var Ov=2;var Fv;var ui=class vx{constructor(e){var t,s,r,n;this._size=0;this._options=e,this._leakageMon=((t=this._options)==null?void 0:t.leakWarningThreshold)?new Bv((e==null?void 0:e.onListenerError)??Ra,((s=this._options)==null?void 0:s.leakWarningThreshold)??Mv):void 0,this._perfMon=((r=this._options)==null?void 0:r._profName)?new Rv(this._options._profName):void 0,this._deliveryQueue=(n=this._options)==null?void 0:n.deliveryQueue}dispose(){var e,t,s,r;if(!this._disposed){if(this._disposed=true,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners){this._listeners=void 0,this._size=0}(s=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null?void 0:s.call(t),(r=this._leakageMon)==null?void 0:r.dispose()}}get event(){return this._event??(this._event=(e,t,s)=>{var a,h,l,c,d;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let u=\`[\${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (\${this._size} vs \${this._leakageMon.threshold})\`;console.warn(u);let f=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],p=new Dv(\`\${u}. HINT: Stack shows most frequent listener (\${f[1]}-times)\`,f[0]);return(((a=this._options)==null?void 0:a.onListenerError)||Ra)(p),hs.None}if(this._disposed)return hs.None;t&&(e=e.bind(t));let r=new Ma(e),n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Iv.create(),n=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof Ma?(this._deliveryQueue??(this._deliveryQueue=new zv),this._listeners=[this._listeners,r]):this._listeners.push(r):((l=(h=this._options)==null?void 0:h.onWillAddFirstListener)==null?void 0:l.call(h,this),this._listeners=r,(d=(c=this._options)==null?void 0:c.onDidAddFirstListener)==null?void 0:d.call(c,this)),this._size++;let o=gr(()=>{n==null?void 0:n(),this._removeListener(r)});if(s instanceof Xh?s.add(o):Array.isArray(s)&&s.push(o),Fv);return o}),this._event}_removeListener(e){var n,o,a,h;if((o=(n=this._options)==null?void 0:n.onWillRemoveListener)==null?void 0:o.call(n,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(h=(a=this._options)==null?void 0:a.onDidRemoveLastListener)==null?void 0:h.call(a,this),this._size=0;return}let t=this._listeners,s=t.indexOf(e);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[s]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Ov<=t.length){let l=0;for(let c=0;c<t.length;c++)t[c]?t[l++]=t[c]:r&&(this._deliveryQueue.end--,l<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=l}}_deliver(e,t){var r;if(!e)return;let s=((r=this._options)==null?void 0:r.onListenerError)||Ra;if(!s){e.value(t);return}try{e.value(t)}catch(n){s(n)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,s,r,n;if(((t=this._deliveryQueue)==null?void 0:t.current)&&(this._deliverQueue(this._deliveryQueue),(s=this._perfMon)==null?void 0:s.stop()),(r=this._perfMon)==null?void 0:r.start(this._size),this._listeners)if(this._listeners instanceof Ma)this._deliver(this._listeners,e);else{let o=this._deliveryQueue;o.enqueue(this,e,this._listeners.length),this._deliverQueue(o)}(n=this._perfMon)==null?void 0:n.stop()}hasListeners(){return this._size>0}};var zv=class bx{constructor(){this.i=-1;this.end=0}enqueue(e,t,s){this.i=0,this.end=s,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var Up=Object.freeze(function(i,e){let t=setTimeout(i.bind(e),0);return{dispose(){clearTimeout(t)}}});var Nv;(i=>{function e(t){return t===i.None||t===i.Cancelled||t instanceof Hv?true:!t||typeof t!="object"?false:typeof t.isCancellationRequested=="boolean"&&typeof t.onCancellationRequested=="function"}i.isCancellationToken=e,i.None=Object.freeze({isCancellationRequested:false,onCancellationRequested:Zh.None}),i.Cancelled=Object.freeze({isCancellationRequested:true,onCancellationRequested:Up})})(Nv||(Nv={}));var Hv=class yx{constructor(){this._isCancelled=false;this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=true,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Up:(this._emitter||(this._emitter=new ui),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}};var ir="en";var Ba=false;var jn;var po=ir;var Cd=ir;var Wv;var Vt;var Ts=globalThis;var ot;var If;t Line truncated
\`))}};var Xv=class Mx extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}};var Zv=class Bx extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}};var Jv=0;var Ia=class Ix{constructor(e){this.value=e;this.id=Jv++}};var Qv=2;var e2;var fi=class Px{constructor(e){var t,s,r,n;this._size=0;this._options=e,this._leakageMon=((t=this._options)==null?void 0:t.leakWarningThreshold)?new Gv((e==null?void 0:e.onListenerError)??Ba,((s=this._options)==null?void 0:s.leakWarningThreshold)??Vv):void 0,this._perfMon=((r=this._options)==null?void 0:r._profName)?new jv(this._options._profName):void 0,this._deliveryQueue=(n=this._options)==null?void 0:n.deliveryQueue}dispose(){var e,t,s,r;if(!this._disposed){if(this._disposed=true,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners){this._listeners=void 0,this._size=0}(s=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null?void 0:s.call(t),(r=this._leakageMon)==null?void 0:r.dispose()}}get event(){return this._event??(this._event=(e,t,s)=>{var a,h,l,c,d;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let u=\`[\${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (\${this._size} vs \${this._leakageMon.threshold})\`;console.warn(u);let f=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],p=new Zv(\`\${u}. HINT: Stack shows most frequent listener (\${f[1]}-times)\`,f[0]);return(((a=this._options)==null?void 0:a.onListenerError)||Ba)(p),hs.None}if(this._disposed)return hs.None;t&&(e=e.bind(t));let r=new Ia(e),n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Yv.create(),n=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof Ia?(this._deliveryQueue??(this._deliveryQueue=new t2),this._listeners=[this._listeners,r]):this._listeners.push(r):((l=(h=this._options)==null?void 0:h.onWillAddFirstListener)==null?void 0:l.call(h,this),this._listeners=r,(d=(c=this._options)==null?void 0:c.onDidAddFirstListener)==null?void 0:d.call(c,this)),this._size++;let o=gr(()=>{n==null?void 0:n(),this._removeListener(r)});if(s instanceof Zh?s.add(o):Array.isArray(s)&&s.push(o),e2);return o}),this._event}_removeListener(e){var n,o,a,h;if((o=(n=this._options)==null?void 0:n.onWillRemoveListener)==null?void 0:o.call(n,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(h=(a=this._options)==null?void 0:a.onDidRemoveLastListener)==null?void 0:h.call(a,this),this._size=0;return}let t=this._listeners,s=t.indexOf(e);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[s]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Qv<=t.length){let l=0;for(let c=0;c<t.length;c++)t[c]?t[l++]=t[c]:r&&(this._deliveryQueue.end--,l<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=l}}_deliver(e,t){var r;if(!e)return;let s=((r=this._options)==null?void 0:r.onListenerError)||Ba;if(!s){e.value(t);return}try{e.value(t)}catch(n){s(n)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,s,r,n;if(((t=this._deliveryQueue)==null?void 0:t.current)&&(this._deliverQueue(this._deliveryQueue),(s=this._perfMon)==null?void 0:s.stop()),(r=this._perfMon)==null?void 0:r.start(this._size),this._listeners)if(this._listeners instanceof Ia)this._deliver(this._listeners,e);else{let o=this._deliveryQueue;o.enqueue(this,e,this._listeners.length),this._deliverQueue(o)}(n=this._perfMon)==null?void 0:n.stop()}hasListeners(){return this._size>0}};var t2=class Dx{constructor(){this.i=-1;this.end=0}enqueue(e,t,s){this.i=0,this.end=s,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var Gp=Object.freeze(function(i,e){let t=setTimeout(i.bind(e),0);return{dispose(){clearTimeout(t)}}});var i2;(i=>{function e(t){return t===i.None||t===i.Cancelled||t instanceof s2?true:!t||typeof t!="object"?false:typeof t.isCancellationRequested=="boolean"&&typeof t.onCancellationRequested=="function"}i.isCancellationToken=e,i.None=Object.freeze({isCancellationRequested:false,onCancellationRequested:Jh.None}),i.Cancelled=Object.freeze({isCancellationRequested:true,onCancellationRequested:Gp})})(i2||(i2={}));var s2=class $x{constructor(){this._isCancelled=false;this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=true,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?Gp:(this._emitter||(this._emitter=new fi),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}};var sr="en";var Pa=false;var jn;var mo=sr;var kd=sr;var r2;var Gt;var Ls=globalThis;var ot;var Pf;t Line truncated
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
* @license MIT
*
@@ -687,7 +687,7 @@ Please report this to https://github.com/markedjs/marked.\`,e){let r="<p>An erro
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
*/var t2=class Tx{constructor(e,t,s,r={}){this._terminal=e;this._regex=t;this._handler=s;this._options=r}provideLinks(e,t){let s=s2.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(s))}_addCallbacks(e){return e.map(t=>(t.leave=this._options.leave,t.hover=(s,r)=>{if(this._options.hover){let{range:n}=t;this._options.hover(s,r,n)}},t))}};function i2(i){try{let e=new URL(i),t=e.password&&e.username?\`\${e.protocol}//\${e.username}:\${e.password}@\${e.host}\`:e.username?\`\${e.protocol}//\${e.username}@\${e.host}\`:\`\${e.protocol}//\${e.host}\`;return i.toLocaleLowerCase().startsWith(t.toLocaleLowerCase())}catch{return false}}var s2=class mo{static computeLink(e,t,s,r){let n=new RegExp(t.source,(t.flags||"")+"g"),[o,a]=mo._getWindowedLineStrings(e-1,s),h=o.join(""),l,c=[];for(;l=n.exec(h);){let d=l[0];if(!i2(d))continue;let[u,f]=mo._mapStrIdx(s,a,0,l.index),[p,b]=mo._mapStrIdx(s,u,f,d.length);if(u===-1||f===-1||p===-1||b===-1)continue;let v={start:{x:f+1,y:u+1},end:{x:b,y:p+1}};c.push({range:v,text:d,activate:r})}return c}static _getWindowedLineStrings(e,t){let s,r=e,n=e,o=0,a="",h=[];if(s=t.buffer.active.getLine(e)){let l=s.translateToString(true);if(s.isWrapped&&l[0]!==" "){for(o=0;(s=t.buffer.active.getLine(--r))&&o<2048&&(a=s.translateToString(true),o+=a.length,h.push(a),!(!s.isWrapped||a.indexOf(" ")!==-1)););h.reverse()}for(h.push(l),o=0;(s=t.buffer.active.getLine(++n))&&s.isWrapped&&o<2048&&(a=s.translateToString(true),o+=a.length,h.push(a),a.indexOf(" ")===-1););}return[h,r]}static _mapStrIdx(e,t,s,r){let n=e.buffer.active,o=n.getNullCell(),a=s;for(;r;){let h=n.getLine(t);if(!h)return[-1,-1];for(let l=a;l<h.length;++l){h.getCell(l,o);let c=o.getChars();if(o.getWidth()&&(r-=c.length||1,l===h.length-1&&c==="")){let d=n.getLine(t+1);d&&d.isWrapped&&(d.getCell(0,o),o.getWidth()===2&&(r+=1))}if(r<0)return[t,l]}t++,a=0}return[t,a]}};var r2=/(https?|HTTPS?):[/]{2}[^\\s"'!*(){}|\\\\\\^<>\`]*[^\\s"':,.!?{}|\\\\\\^~\\[\\]\`()<>]/;function n2(i,e){let t=window.open();if(t){try{t.opener=null}catch{}t.location.href=e}else console.warn("Opening link blocked as opener could not be cleared")}var o2=class Lx{constructor(e=n2,t={}){this._handler=e;this._options=t}activate(e){this._terminal=e;let t=this._options,s=t.urlRegex||r2;this._linkProvider=this._terminal.registerLinkProvider(new t2(this._terminal,s,this._handler,t))}dispose(){var e;(e=this._linkProvider)==null?void 0:e.dispose()}};/**
*/var _2=class Ux{constructor(e,t,s,r={}){this._terminal=e;this._regex=t;this._handler=s;this._options=r}provideLinks(e,t){let s=b2.computeLink(e,this._regex,this._terminal,this._handler);t(this._addCallbacks(s))}_addCallbacks(e){return e.map(t=>(t.leave=this._options.leave,t.hover=(s,r)=>{if(this._options.hover){let{range:n}=t;this._options.hover(s,r,n)}},t))}};function v2(i){try{let e=new URL(i),t=e.password&&e.username?\`\${e.protocol}//\${e.username}:\${e.password}@\${e.host}\`:e.username?\`\${e.protocol}//\${e.username}@\${e.host}\`:\`\${e.protocol}//\${e.host}\`;return i.toLocaleLowerCase().startsWith(t.toLocaleLowerCase())}catch{return false}}var b2=class go{static computeLink(e,t,s,r){let n=new RegExp(t.source,(t.flags||"")+"g"),[o,a]=go._getWindowedLineStrings(e-1,s),h=o.join(""),l,c=[];for(;l=n.exec(h);){let d=l[0];if(!v2(d))continue;let[u,f]=go._mapStrIdx(s,a,0,l.index),[p,b]=go._mapStrIdx(s,u,f,d.length);if(u===-1||f===-1||p===-1||b===-1)continue;let v={start:{x:f+1,y:u+1},end:{x:b,y:p+1}};c.push({range:v,text:d,activate:r})}return c}static _getWindowedLineStrings(e,t){let s,r=e,n=e,o=0,a="",h=[];if(s=t.buffer.active.getLine(e)){let l=s.translateToString(true);if(s.isWrapped&&l[0]!==" "){for(o=0;(s=t.buffer.active.getLine(--r))&&o<2048&&(a=s.translateToString(true),o+=a.length,h.push(a),!(!s.isWrapped||a.indexOf(" ")!==-1)););h.reverse()}for(h.push(l),o=0;(s=t.buffer.active.getLine(++n))&&s.isWrapped&&o<2048&&(a=s.translateToString(true),o+=a.length,h.push(a),a.indexOf(" ")===-1););}return[h,r]}static _mapStrIdx(e,t,s,r){let n=e.buffer.active,o=n.getNullCell(),a=s;for(;r;){let h=n.getLine(t);if(!h)return[-1,-1];for(let l=a;l<h.length;++l){h.getCell(l,o);let c=o.getChars();if(o.getWidth()&&(r-=c.length||1,l===h.length-1&&c==="")){let d=n.getLine(t+1);d&&d.isWrapped&&(d.getCell(0,o),o.getWidth()===2&&(r+=1))}if(r<0)return[t,l]}t++,a=0}return[t,a]}};var y2=/(https?|HTTPS?):[/]{2}[^\\s"'!*(){}|\\\\\\^<>\`]*[^\\s"':,.!?{}|\\\\\\^~\\[\\]\`()<>]/;function w2(i,e){let t=window.open();if(t){try{t.opener=null}catch{}t.location.href=e}else console.warn("Opening link blocked as opener could not be cleared")}var S2=class qx{constructor(e=w2,t={}){this._handler=e;this._options=t}activate(e){this._terminal=e;let t=this._options,s=t.urlRegex||y2;this._linkProvider=this._terminal.registerLinkProvider(new _2(this._terminal,s,this._handler,t))}dispose(){var e;(e=this._linkProvider)==null?void 0:e.dispose()}};/**
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
* @license MIT
*
@@ -698,13 +698,13 @@ Please report this to https://github.com/markedjs/marked.\`,e){let r="<p>An erro
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
*/var a2=(i,e,t,s)=>{for(var r=e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=o(r)||r);return r};var l2=(i,e)=>(t,s)=>e(t,s,i);var h2=class Ax{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Ed.isErrorNoTelemetry(e)?new Ed(e.message+\`
*/var x2=(i,e,t,s)=>{for(var r=e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=o(r)||r);return r};var C2=(i,e)=>(t,s)=>e(t,s,i);var k2=class Kx{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Td.isErrorNoTelemetry(e)?new Td(e.message+\`
\`+e.stack):new 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)}};var c2=new h2;function Ia(i){d2(i)||c2.onUnexpectedError(i)}var Wl="Canceled";function d2(i){return i instanceof u2?true:i instanceof Error&&i.name===Wl&&i.message===Wl}var u2=class Rx extends Error{constructor(){super(Wl),this.name=this.message}};var Ed=class Ul extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof Ul)return e;let t=new Ul;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}};var f2;(i=>{function e(n){return n<0}i.isLessThan=e;function t(n){return n<=0}i.isLessThanOrEqual=t;function s(n){return n>0}i.isGreaterThan=s;function r(n){return n===0}i.isNeitherLessOrGreaterThan=r,i.greaterThan=1,i.lessThan=-1,i.neitherLessOrGreaterThan=0})(f2||(f2={}));function p2(i,e){let t=this,s=false,r;return function(){if(s)return r;if(s=true,e);else r=i.apply(t,arguments);return r}}var Kp;(i=>{function e(g){return g&&typeof g=="object"&&typeof g[Symbol.iterator]=="function"}i.is=e;let t=Object.freeze([]);function s(){return t}i.empty=s;function*r(g){yield g}i.single=r;function n(g){return e(g)?g:r(g)}i.wrap=n;function o(g){return g||t}i.from=o;function*a(g){for(let E=g.length-1;E>=0;E--)yield g[E]}i.reverse=a;function h(g){return!g||g[Symbol.iterator]().next().done===true}i.isEmpty=h;function l(g){return g[Symbol.iterator]().next().value}i.first=l;function c(g,E){let k=0;for(let D of g)if(E(D,k++))return true;return false}i.some=c;function d(g,E){for(let k of g)if(E(k))return k}i.find=d;function*u(g,E){for(let k of g)E(k)&&(yield k)}i.filter=u;function*f(g,E){let k=0;for(let D of g)yield E(D,k++)}i.map=f;function*p(g,E){let k=0;for(let D of g)yield*E(D,k++)}i.flatMap=p;function*b(...g){for(let E of g)yield*E}i.concat=b;function v(g,E,k){let D=k;for(let N of g)D=E(D,N);return D}i.reduce=v;function*R(g,E,k=g.length){for(E<0&&(E+=g.length),k<0?k+=g.length:k>g.length&&(k=g.length);E<k;E++)yield g[E]}i.slice=R;function L(g,E=Number.POSITIVE_INFINITY){let k=[];if(E===0)return[k,g];let D=g[Symbol.iterator]();for(let N=0;N<E;N++){let z=D.next();if(z.done)return[k,i.empty()];k.push(z.value)}return[k,{[Symbol.iterator](){return D}}]}i.consume=L;async function A(g){let E=[];for await(let k of g)E.push(k);return Promise.resolve(E)}i.asyncToArray=A})(Kp||(Kp={}));function m2(i){return i}function jp(i,e){}function Vp(i){if(Kp.is(i)){let e=[];for(let t of i)if(t)try{t.dispose()}catch(s){e.push(s)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"Encountered errors while disposing of store");return Array.isArray(i)?[]:i}else if(i)return i.dispose(),i}function Gp(...i){let e=pt(()=>Vp(i));return e}function pt(i){let e=m2({dispose:p2(()=>{i()})});return e}var Yp=class Xp{constructor(){this._toDispose=new Set;this._isDisposed=false}dispose(){this._isDisposed||(this._isDisposed=true,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Vp(this._toDispose)}finally{this._toDispose.clear()}}add(e){if(!e)return e;if(e===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Xp.DISABLE_DISPOSED_WARNING||console.warn(new 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 new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),jp())}};Yp.DISABLE_DISPOSED_WARNING=false;var lr=Yp;var Jt=class Mx{constructor(){this._store=new lr;jp(this._store)}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};Jt.None=Object.freeze({dispose(){}});var Lr=class Bx{constructor(){this._isDisposed=false}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null?void 0:t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=true,(e=this._value)==null?void 0:e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}};var Jh=typeof process<"u"&&"title"in process;var Zo=Jh?"node":navigator.userAgent;var g2=Jh?"node":navigator.platform;var _2=Zo.includes("Firefox");var v2=Zo.includes("Edge");var Zp=/^((?!chrome|android).)*safari/i.test(Zo);function b2(){if(!Zp)return 0;let i=Zo.match(/Version\\/(\\d+)/);return i===null||i.length<2?0:parseInt(i[1])}g2. Line truncated
\`+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)}};var E2=new k2;function Da(i){T2(i)||E2.onUnexpectedError(i)}var Ul="Canceled";function T2(i){return i instanceof L2?true:i instanceof Error&&i.name===Ul&&i.message===Ul}var L2=class jx extends Error{constructor(){super(Ul),this.name=this.message}};var Td=class ql extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof ql)return e;let t=new ql;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}};var A2;(i=>{function e(n){return n<0}i.isLessThan=e;function t(n){return n<=0}i.isLessThanOrEqual=t;function s(n){return n>0}i.isGreaterThan=s;function r(n){return n===0}i.isNeitherLessOrGreaterThan=r,i.greaterThan=1,i.lessThan=-1,i.neitherLessOrGreaterThan=0})(A2||(A2={}));function R2(i,e){let t=this,s=false,r;return function(){if(s)return r;if(s=true,e);else r=i.apply(t,arguments);return r}}var Xp;(i=>{function e(g){return g&&typeof g=="object"&&typeof g[Symbol.iterator]=="function"}i.is=e;let t=Object.freeze([]);function s(){return t}i.empty=s;function*r(g){yield g}i.single=r;function n(g){return e(g)?g:r(g)}i.wrap=n;function o(g){return g||t}i.from=o;function*a(g){for(let E=g.length-1;E>=0;E--)yield g[E]}i.reverse=a;function h(g){return!g||g[Symbol.iterator]().next().done===true}i.isEmpty=h;function l(g){return g[Symbol.iterator]().next().value}i.first=l;function c(g,E){let k=0;for(let D of g)if(E(D,k++))return true;return false}i.some=c;function d(g,E){for(let k of g)if(E(k))return k}i.find=d;function*u(g,E){for(let k of g)E(k)&&(yield k)}i.filter=u;function*f(g,E){let k=0;for(let D of g)yield E(D,k++)}i.map=f;function*p(g,E){let k=0;for(let D of g)yield*E(D,k++)}i.flatMap=p;function*b(...g){for(let E of g)yield*E}i.concat=b;function v(g,E,k){let D=k;for(let N of g)D=E(D,N);return D}i.reduce=v;function*R(g,E,k=g.length){for(E<0&&(E+=g.length),k<0?k+=g.length:k>g.length&&(k=g.length);E<k;E++)yield g[E]}i.slice=R;function L(g,E=Number.POSITIVE_INFINITY){let k=[];if(E===0)return[k,g];let D=g[Symbol.iterator]();for(let N=0;N<E;N++){let z=D.next();if(z.done)return[k,i.empty()];k.push(z.value)}return[k,{[Symbol.iterator](){return D}}]}i.consume=L;async function A(g){let E=[];for await(let k of g)E.push(k);return Promise.resolve(E)}i.asyncToArray=A})(Xp||(Xp={}));function M2(i){return i}function Zp(i,e){}function Jp(i){if(Xp.is(i)){let e=[];for(let t of i)if(t)try{t.dispose()}catch(s){e.push(s)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"Encountered errors while disposing of store");return Array.isArray(i)?[]:i}else if(i)return i.dispose(),i}function Qp(...i){let e=pt(()=>Jp(i));return e}function pt(i){let e=M2({dispose:R2(()=>{i()})});return e}var em=class tm{constructor(){this._toDispose=new Set;this._isDisposed=false}dispose(){this._isDisposed||(this._isDisposed=true,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Jp(this._toDispose)}finally{this._toDispose.clear()}}add(e){if(!e)return e;if(e===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?tm.DISABLE_DISPOSED_WARNING||console.warn(new 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 new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),Zp())}};em.DISABLE_DISPOSED_WARNING=false;var hr=em;var Qt=class Vx{constructor(){this._store=new hr;Zp(this._store)}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};Qt.None=Object.freeze({dispose(){}});var Lr=class Gx{constructor(){this._isDisposed=false}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null?void 0:t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=true,(e=this._value)==null?void 0:e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}};var Qh=typeof process<"u"&&"title"in process;var Qo=Qh?"node":navigator.userAgent;var B2=Qh?"node":navigator.platform;var I2=Qo.includes("Firefox");var P2=Qo.includes("Edge");var im=/^((?!chrome|android).)*safari/i.test(Qo);function D2(){if(!im)return 0;let i=Qo.match(/Version\\/(\\d+)/);return i===null||i.length<2?0:parseInt(i[1])}B2. Line truncated
\`).slice(2).join(\`
\`))}};var G2=class zx extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}};var Y2=class Nx extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}};var X2=0;var Da=class Hx{constructor(e){this.value=e;this.id=X2++}};var Z2=2;var J2;var we=class Wx{constructor(e){var t,s,r,n;this._size=0;this._options=e,this._leakageMon=((t=this._options)==null?void 0:t.leakWarningThreshold)?new j2((e==null?void 0:e.onListenerError)??Ia,((s=this._options)==null?void 0:s.leakWarningThreshold)??K2):void 0,this._perfMon=((r=this._options)==null?void 0:r._profName)?new q2(this._options._profName):void 0,this._deliveryQueue=(n=this._options)==null?void 0:n.deliveryQueue}dispose(){var e,t,s,r;if(!this._disposed){if(this._disposed=true,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners){this._listeners=void 0,this._size=0}(s=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null?void 0:s.call(t),(r=this._leakageMon)==null?void 0:r.dispose()}}get event(){return this._event??(this._event=(e,t,s)=>{var a,h,l,c,d;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let u=\`[\${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (\${this._size} vs \${this._leakageMon.threshold})\`;console.warn(u);let f=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],p=new Y2(\`\${u}. HINT: Stack shows most frequent listener (\${f[1]}-times)\`,f[0]);return(((a=this._options)==null?void 0:a.onListenerError)||Ia)(p),Jt.None}if(this._disposed)return Jt.None;t&&(e=e.bind(t));let r=new Da(e),n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=V2.create(),n=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof Da?(this._deliveryQueue??(this._deliveryQueue=new Q2),this._listeners=[this._listeners,r]):this._listeners.push(r):((l=(h=this._options)==null?void 0:h.onWillAddFirstListener)==null?void 0:l.call(h,this),this._listeners=r,(d=(c=this._options)==null?void 0:c.onDidAddFirstListener)==null?void 0:d.call(c,this)),this._size++;let o=pt(()=>{n==null?void 0:n(),this._removeListener(r)});if(s instanceof lr?s.add(o):Array.isArray(s)&&s.push(o),J2);return o}),this._event}_removeListener(e){var n,o,a,h;if((o=(n=this._options)==null?void 0:n.onWillRemoveListener)==null?void 0:o.call(n,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(h=(a=this._options)==null?void 0:a.onDidRemoveLastListener)==null?void 0:h.call(a,this),this._size=0;return}let t=this._listeners,s=t.indexOf(e);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[s]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Z2<=t.length){let l=0;for(let c=0;c<t.length;c++)t[c]?t[l++]=t[c]:r&&(this._deliveryQueue.end--,l<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=l}}_deliver(e,t){var r;if(!e)return;let s=((r=this._options)==null?void 0:r.onListenerError)||Ia;if(!s){e.value(t);return}try{e.value(t)}catch(n){s(n)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,s,r,n;if(((t=this._deliveryQueue)==null?void 0:t.current)&&(this._deliverQueue(this._deliveryQueue),(s=this._perfMon)==null?void 0:s.stop()),(r=this._perfMon)==null?void 0:r.start(this._size),this._listeners)if(this._listeners instanceof Da)this._deliver(this._listeners,e);else{let o=this._deliveryQueue;o.enqueue(this,e,this._listeners.length),this._deliverQueue(o)}(n=this._perfMon)==null?void 0:n.stop()}hasListeners(){return this._size>0}};var Q2=class Ux{constructor(){this.i=-1;this.end=0}enqueue(e,t,s){this.i=0,this.end=s,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var Md={texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},offset:{x:0,y:0},size:{x:0,y:0},sizeClipSpace:{x:0,y:0}};var Ar=2;var Rr;var Xi=class er{constructor(e,t,s){this._document=e;this._config=t;this._unicodeService=s;this._didWarmUp=false;this._cacheMap=new Rd;this._cacheMapCombined=new Rd;this._pages=[];this._activePages=[];this._workBoundingBox={top:0,left:0,bottom:0,right:0};this._workAttributeData=new sr;this._textureSize=512;this._onAddTextureAtlasCanvas=new we;this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event;this._onRemoveTextureAtlasCanvas=new we;this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event;this._requestClearModel=false;this._createNewPage(),this._tmpCanvas=cm(e,this._config.deviceCellWidth*4+Ar*2,this._config.deviceCellHeight+Ar*2),this._tmpCtx=Oe(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:true}))}get pages(){return this._pages}dispose(){this._tmpCanvas.remove();for(let e of this.pages)e.canvas.remove();t Line truncated
\`))}};var cb=class tC extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}};var db=class iC extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}};var ub=0;var Oa=class sC{constructor(e){this.value=e;this.id=ub++}};var fb=2;var pb;var we=class rC{constructor(e){var t,s,r,n;this._size=0;this._options=e,this._leakageMon=((t=this._options)==null?void 0:t.leakWarningThreshold)?new lb((e==null?void 0:e.onListenerError)??Da,((s=this._options)==null?void 0:s.leakWarningThreshold)??ab):void 0,this._perfMon=((r=this._options)==null?void 0:r._profName)?new ob(this._options._profName):void 0,this._deliveryQueue=(n=this._options)==null?void 0:n.deliveryQueue}dispose(){var e,t,s,r;if(!this._disposed){if(this._disposed=true,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners){this._listeners=void 0,this._size=0}(s=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null?void 0:s.call(t),(r=this._leakageMon)==null?void 0:r.dispose()}}get event(){return this._event??(this._event=(e,t,s)=>{var a,h,l,c,d;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let u=\`[\${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (\${this._size} vs \${this._leakageMon.threshold})\`;console.warn(u);let f=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],p=new db(\`\${u}. HINT: Stack shows most frequent listener (\${f[1]}-times)\`,f[0]);return(((a=this._options)==null?void 0:a.onListenerError)||Da)(p),Qt.None}if(this._disposed)return Qt.None;t&&(e=e.bind(t));let r=new Oa(e),n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=hb.create(),n=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof Oa?(this._deliveryQueue??(this._deliveryQueue=new mb),this._listeners=[this._listeners,r]):this._listeners.push(r):((l=(h=this._options)==null?void 0:h.onWillAddFirstListener)==null?void 0:l.call(h,this),this._listeners=r,(d=(c=this._options)==null?void 0:c.onDidAddFirstListener)==null?void 0:d.call(c,this)),this._size++;let o=pt(()=>{n==null?void 0:n(),this._removeListener(r)});if(s instanceof hr?s.add(o):Array.isArray(s)&&s.push(o),pb);return o}),this._event}_removeListener(e){var n,o,a,h;if((o=(n=this._options)==null?void 0:n.onWillRemoveListener)==null?void 0:o.call(n,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(h=(a=this._options)==null?void 0:a.onDidRemoveLastListener)==null?void 0:h.call(a,this),this._size=0;return}let t=this._listeners,s=t.indexOf(e);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[s]=void 0;let r=this._deliveryQueue.current===this;if(this._size*fb<=t.length){let l=0;for(let c=0;c<t.length;c++)t[c]?t[l++]=t[c]:r&&(this._deliveryQueue.end--,l<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=l}}_deliver(e,t){var r;if(!e)return;let s=((r=this._options)==null?void 0:r.onListenerError)||Da;if(!s){e.value(t);return}try{e.value(t)}catch(n){s(n)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,s,r,n;if(((t=this._deliveryQueue)==null?void 0:t.current)&&(this._deliverQueue(this._deliveryQueue),(s=this._perfMon)==null?void 0:s.stop()),(r=this._perfMon)==null?void 0:r.start(this._size),this._listeners)if(this._listeners instanceof Oa)this._deliver(this._listeners,e);else{let o=this._deliveryQueue;o.enqueue(this,e,this._listeners.length),this._deliverQueue(o)}(n=this._perfMon)==null?void 0:n.stop()}hasListeners(){return this._size>0}};var mb=class nC{constructor(){this.i=-1;this.end=0}enqueue(e,t,s){this.i=0,this.end=s,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var Bd={texturePage:0,texturePosition:{x:0,y:0},texturePositionClipSpace:{x:0,y:0},offset:{x:0,y:0},size:{x:0,y:0},sizeClipSpace:{x:0,y:0}};var Ar=2;var Rr;var Xi=class tr{constructor(e,t,s){this._document=e;this._config=t;this._unicodeService=s;this._didWarmUp=false;this._cacheMap=new Md;this._cacheMapCombined=new Md;this._pages=[];this._activePages=[];this._workBoundingBox={top:0,left:0,bottom:0,right:0};this._workAttributeData=new rr;this._textureSize=512;this._onAddTextureAtlasCanvas=new we;this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event;this._onRemoveTextureAtlasCanvas=new we;this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event;this._requestClearModel=false;this._createNewPage(),this._tmpCanvas=mm(e,this._config.deviceCellWidth*4+Ar*2,this._config.deviceCellHeight+Ar*2),this._tmpCtx=Oe(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:true}))}get pages(){return this._pages}dispose(){this._tmpCanvas.remove();for(let e of this.pages)e.canvas.remove();t Line truncated
layout (location = 0) in vec2 a_unitquad;
layout (location = 1) in vec2 a_cellpos;
layout (location = 2) in vec2 a_offset;
@@ -724,7 +724,7 @@ void main() {
gl_Position = u_projection * vec4(zeroToOne, 0.0, 1.0);
v_texpage = int(a_texpage);
v_texcoord = a_texcoord + a_unitquad * a_texsize;
}\`;function lb(i){let e="";for(let t=1;t<i;t++)e+=\` else if (v_texpage == \${t}) { outColor = texture(u_texture[\${t}], v_texcoord); }\`;return\`#version 300 es
}\`;function Cb(i){let e="";for(let t=1;t<i;t++)e+=\` else if (v_texpage == \${t}) { outColor = texture(u_texture[\${t}], v_texcoord); }\`;return\`#version 300 es
precision lowp float;
in vec2 v_texcoord;
@@ -738,7 +738,7 @@ void main() {
if (v_texpage == 0) {
outColor = texture(u_texture[0], v_texcoord);
} \${e}
}\`}var Zi=11;var Gs=Zi*Float32Array.BYTES_PER_ELEMENT;var hb=2;var Ae=0;var ve;var Fa=0;var Mr=0;var cb=class Vx extends Jt{constructor(e,t,s,r){super();this._terminal=e;this._gl=t;this._dimensions=s;this._optionsService=r;this._activeBuffer=0;this._vertices={count:0,attributes:new Float32Array(0),attributesBuffers:[new Float32Array(0),new Float32Array(0)]};let n=this._gl;Xi.maxAtlasPages===void 0&&(Xi.maxAtlasPages=Math.min(32,Oe(n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS))),Xi.maxTextureSize=Oe(n.getParameter(n.MAX_TEXTURE_SIZE))),this._program=Oe(pm(n,ab,lb(Xi.maxAtlasPages))),this._register(pt(()=>n.deleteProgram(this._program))),this._projectionLocation=Oe(n.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=Oe(n.getUniformLocation(this._program,"u_resolution")),this._textureLocation=Oe(n.getUniformLocation(this._program,"u_texture")),this._vertexArrayObject=n.createVertexArray(),n.bindVertexArray(this._vertexArrayObject);let o=new Float32Array([0,0,1,0,0,1,1,1]),a=n.createBuffer();this._register(pt(()=>n.deleteBuffer(a))),n.bindBuffer(n.ARRAY_BUFFER,a),n.bufferData(n.ARRAY_BUFFER,o,n.STATIC_DRAW),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,2,this._gl.FLOAT,false,0,0);let h=new Uint8Array([0,1,2,3]),l=n.createBuffer();this._register(pt(()=>n.deleteBuffer(l))),n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,l),n.bufferData(n.ELEMENT_ARRAY_BUFFER,h,n.STATIC_DRAW),this._attributesBuffer=Oe(n.createBuffer()),this._register(pt(()=>n.deleteBuffer(this._attributesBuffer))),n.bindBuffer(n.ARRAY_BUFFER,this._attributesBuffer),n.enableVertexAttribArray(2),n.vertexAttribPointer(2,2,n.FLOAT,false,Gs,0),n.vertexAttribDivisor(2,1),n.enableVertexAttribArray(3),n.vertexAttribPointer(3,2,n.FLOAT,false,Gs,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(3,1),n.enableVertexAttribArray(4),n.vertexAttribPointer(4,1,n.FLOAT,false,Gs,4*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(4,1),n.enableVertexAttribArray(5),n.vertexAttribPointer(5,2,n.FLOAT,false,Gs,5*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(5,1),n.enableVertexAttribArray(6),n.vertexAttribPointer(6,2,n.FLOAT,false,Gs,7*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(6,1),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,false,Gs,9*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(1,1),n.useProgram(this._program);let c=new Int32Array(Xi.maxAtlasPages);for(let d=0;d<Xi.maxAtlasPages;d++)c[d]=d;n.uniform1iv(this._textureLocation,c),n.uniformMatrix4fv(this._projectionLocation,false,fm),this._atlasTextures=[];for(let d=0;d<Xi.maxAtlasPages;d++){let u=new ob(Oe(n.createTexture()));this._register(pt(()=>n.deleteTexture(u.texture))),n.activeTexture(n.TEXTURE0+d),n.bindTexture(n.TEXTURE_2D,u.texture),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[d]=u}n.enable(n.BLEND),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){return this._atlas?this._atlas.beginFrame():true}updateCell(e,t,s,r,n,o,a,h,l){this._updateCell(this._vertices.attributes,e,t,s,r,n,o,a,h,l)}_updateCell(e,t,s,r,n,o,a,h,l,c){if(Ae=(s*this._terminal.cols+t)*Zi,r===0||r===void 0){e.fill(0,Ae,Ae+Zi-1-hb);return}this._atlas&&(h&&h.length>1?ve=this._atlas.getRasterizedGlyphCombinedChar(h,n,o,a,false,this._terminal.element):ve=this._atlas.getRasterizedGlyph(r,n,o,a,false,this._terminal.element),Fa=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),n!==c&&ve.offset.x>Fa?(Mr=ve.offset.x-Fa,e[Ae]=-(ve.offset.x-Mr)+this._dimensions.device.char.left,e[Ae+1]=-ve.offset.y+this._dimensions.device.char.top,e[Ae+2]=(ve.size.x-Mr)/this._dimensions.device.canvas.width,e[Ae+3]=ve.size.y/this._dimensions.device.canvas.height,e[Ae+4]=ve.texturePage,e[Ae+5]=ve.texturePositionClipSpace.x+Mr/this._atlas.pages[ve.texturePage].canvas.width,e[Ae+6]=ve.texturePositionClipSpace.y,e[Ae+7]=ve.sizeClipSpace.x-Mr/this._atlas.pages[ve.texturePage].canvas.width,e[Ae+8]=ve.sizeClipSpace.y):(e[Ae]=-ve.offset.x+this._dimensions.device.char.left,e[Ae+1]=-ve.offset.y+this._dimensions.device.char.top,e[Ae+2]=ve.size.x/this._dimensions.device.canvas.width,e[Ae+3]=ve.size.y/this._dimensions.device.canvas.height,e[Ae+4]=ve.texturePage,e[Ae+5]=ve.texturePositionClipSpace.x,e[Ae+6]=ve.texturePositionClipSpace.y,e[Ae+7]=ve.sizeClipSpace.x,e[Ae+8]=ve.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&E2(r,l,ve.size.x,this._dimensions.device.cell.width)&&(e[Ae+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width))}clear(){let e=this._terminal,t=e.cols*e.rows*Zi;this._vertices.count!==t?this._vertices.attributes=new Float32Array(t):this._vertices.attributes.fill(0);let s=0;for(;s<this._vertices.attributesBuffers.length;s++)this._vertices.count!==t?this._vertices.attributesBuffers[s]=new F Line truncated
}\`}var Zi=11;var Ys=Zi*Float32Array.BYTES_PER_ELEMENT;var kb=2;var Ae=0;var ve;var Na=0;var Mr=0;var Eb=class hC extends Qt{constructor(e,t,s,r){super();this._terminal=e;this._gl=t;this._dimensions=s;this._optionsService=r;this._activeBuffer=0;this._vertices={count:0,attributes:new Float32Array(0),attributesBuffers:[new Float32Array(0),new Float32Array(0)]};let n=this._gl;Xi.maxAtlasPages===void 0&&(Xi.maxAtlasPages=Math.min(32,Oe(n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS))),Xi.maxTextureSize=Oe(n.getParameter(n.MAX_TEXTURE_SIZE))),this._program=Oe(bm(n,xb,Cb(Xi.maxAtlasPages))),this._register(pt(()=>n.deleteProgram(this._program))),this._projectionLocation=Oe(n.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=Oe(n.getUniformLocation(this._program,"u_resolution")),this._textureLocation=Oe(n.getUniformLocation(this._program,"u_texture")),this._vertexArrayObject=n.createVertexArray(),n.bindVertexArray(this._vertexArrayObject);let o=new Float32Array([0,0,1,0,0,1,1,1]),a=n.createBuffer();this._register(pt(()=>n.deleteBuffer(a))),n.bindBuffer(n.ARRAY_BUFFER,a),n.bufferData(n.ARRAY_BUFFER,o,n.STATIC_DRAW),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,2,this._gl.FLOAT,false,0,0);let h=new Uint8Array([0,1,2,3]),l=n.createBuffer();this._register(pt(()=>n.deleteBuffer(l))),n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,l),n.bufferData(n.ELEMENT_ARRAY_BUFFER,h,n.STATIC_DRAW),this._attributesBuffer=Oe(n.createBuffer()),this._register(pt(()=>n.deleteBuffer(this._attributesBuffer))),n.bindBuffer(n.ARRAY_BUFFER,this._attributesBuffer),n.enableVertexAttribArray(2),n.vertexAttribPointer(2,2,n.FLOAT,false,Ys,0),n.vertexAttribDivisor(2,1),n.enableVertexAttribArray(3),n.vertexAttribPointer(3,2,n.FLOAT,false,Ys,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(3,1),n.enableVertexAttribArray(4),n.vertexAttribPointer(4,1,n.FLOAT,false,Ys,4*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(4,1),n.enableVertexAttribArray(5),n.vertexAttribPointer(5,2,n.FLOAT,false,Ys,5*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(5,1),n.enableVertexAttribArray(6),n.vertexAttribPointer(6,2,n.FLOAT,false,Ys,7*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(6,1),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,false,Ys,9*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(1,1),n.useProgram(this._program);let c=new Int32Array(Xi.maxAtlasPages);for(let d=0;d<Xi.maxAtlasPages;d++)c[d]=d;n.uniform1iv(this._textureLocation,c),n.uniformMatrix4fv(this._projectionLocation,false,vm),this._atlasTextures=[];for(let d=0;d<Xi.maxAtlasPages;d++){let u=new Sb(Oe(n.createTexture()));this._register(pt(()=>n.deleteTexture(u.texture))),n.activeTexture(n.TEXTURE0+d),n.bindTexture(n.TEXTURE_2D,u.texture),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_S,n.CLAMP_TO_EDGE),n.texParameteri(n.TEXTURE_2D,n.TEXTURE_WRAP_T,n.CLAMP_TO_EDGE),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,1,1,0,n.RGBA,n.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[d]=u}n.enable(n.BLEND),n.blendFunc(n.SRC_ALPHA,n.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){return this._atlas?this._atlas.beginFrame():true}updateCell(e,t,s,r,n,o,a,h,l){this._updateCell(this._vertices.attributes,e,t,s,r,n,o,a,h,l)}_updateCell(e,t,s,r,n,o,a,h,l,c){if(Ae=(s*this._terminal.cols+t)*Zi,r===0||r===void 0){e.fill(0,Ae,Ae+Zi-1-kb);return}this._atlas&&(h&&h.length>1?ve=this._atlas.getRasterizedGlyphCombinedChar(h,n,o,a,false,this._terminal.element):ve=this._atlas.getRasterizedGlyph(r,n,o,a,false,this._terminal.element),Na=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),n!==c&&ve.offset.x>Na?(Mr=ve.offset.x-Na,e[Ae]=-(ve.offset.x-Mr)+this._dimensions.device.char.left,e[Ae+1]=-ve.offset.y+this._dimensions.device.char.top,e[Ae+2]=(ve.size.x-Mr)/this._dimensions.device.canvas.width,e[Ae+3]=ve.size.y/this._dimensions.device.canvas.height,e[Ae+4]=ve.texturePage,e[Ae+5]=ve.texturePositionClipSpace.x+Mr/this._atlas.pages[ve.texturePage].canvas.width,e[Ae+6]=ve.texturePositionClipSpace.y,e[Ae+7]=ve.sizeClipSpace.x-Mr/this._atlas.pages[ve.texturePage].canvas.width,e[Ae+8]=ve.sizeClipSpace.y):(e[Ae]=-ve.offset.x+this._dimensions.device.char.left,e[Ae+1]=-ve.offset.y+this._dimensions.device.char.top,e[Ae+2]=ve.size.x/this._dimensions.device.canvas.width,e[Ae+3]=ve.size.y/this._dimensions.device.canvas.height,e[Ae+4]=ve.texturePage,e[Ae+5]=ve.texturePositionClipSpace.x,e[Ae+6]=ve.texturePositionClipSpace.y,e[Ae+7]=ve.sizeClipSpace.x,e[Ae+8]=ve.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&W2(r,l,ve.size.x,this._dimensions.device.cell.width)&&(e[Ae+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width))}clear(){let e=this._terminal,t=e.cols*e.rows*Zi;this._vertices.count!==t?this._vertices.attributes=new Float32Array(t):this._vertices.attributes.fill(0);let s=0;for(;s<this._vertices.attributesBuffers.length;s++)this._vertices.count!==t?this._vertices.attributesBuffers[s]=new F Line truncated
layout (location = 0) in vec2 a_position;
layout (location = 1) in vec2 a_size;
layout (location = 2) in vec4 a_color;
@@ -752,7 +752,7 @@ void main() {
vec2 zeroToOne = a_position + (a_unitquad * a_size);
gl_Position = u_projection * vec4(zeroToOne, 0.0, 1.0);
v_color = a_color;
}\`;var gb=\`#version 300 es
}\`;var Bb=\`#version 300 es
precision lowp float;
in vec4 v_color;
@@ -761,7 +761,7 @@ out vec4 outColor;
void main() {
outColor = v_color;
}\`;var Mi=8;var Na=Mi*Float32Array.BYTES_PER_ELEMENT;var _b=20*Mi;var Od=class Xx{constructor(){this.attributes=new Float32Array(_b),this.count=0}};var Li=0;var Fd=0;var zd=0;var Nd=0;var Hd=0;var Wd=0;var Ud=0;var vb=class Zx extends Jt{constructor(e,t,s,r){super();this._terminal=e;this._gl=t;this._dimensions=s;this._themeService=r;this._vertices=new Od;this._verticesCursor=new Od;let n=this._gl;this._program=Oe(pm(n,mb,gb)),this._register(pt(()=>n.deleteProgram(this._program))),this._projectionLocation=Oe(n.getUniformLocation(this._program,"u_projection")),this._vertexArrayObject=n.createVertexArray(),n.bindVertexArray(this._vertexArrayObject);let o=new Float32Array([0,0,1,0,0,1,1,1]),a=n.createBuffer();this._register(pt(()=>n.deleteBuffer(a))),n.bindBuffer(n.ARRAY_BUFFER,a),n.bufferData(n.ARRAY_BUFFER,o,n.STATIC_DRAW),n.enableVertexAttribArray(3),n.vertexAttribPointer(3,2,this._gl.FLOAT,false,0,0);let h=new Uint8Array([0,1,2,3]),l=n.createBuffer();this._register(pt(()=>n.deleteBuffer(l))),n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,l),n.bufferData(n.ELEMENT_ARRAY_BUFFER,h,n.STATIC_DRAW),this._attributesBuffer=Oe(n.createBuffer()),this._register(pt(()=>n.deleteBuffer(this._attributesBuffer))),n.bindBuffer(n.ARRAY_BUFFER,this._attributesBuffer),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,2,n.FLOAT,false,Na,0),n.vertexAttribDivisor(0,1),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,false,Na,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(1,1),n.enableVertexAttribArray(2),n.vertexAttribPointer(2,4,n.FLOAT,false,Na,4*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(2,1),this._updateCachedColors(r.colors),this._register(this._themeService.onChangeColors(c=>{this._updateCachedColors(c),this._updateViewportRectangle()}))}renderBackgrounds(){this._renderVertices(this._vertices)}renderCursor(){this._renderVertices(this._verticesCursor)}_renderVertices(e){let t=this._gl;t.useProgram(this._program),t.bindVertexArray(this._vertexArrayObject),t.uniformMatrix4fv(this._projectionLocation,false,fm),t.bindBuffer(t.ARRAY_BUFFER,this._attributesBuffer),t.bufferData(t.ARRAY_BUFFER,e.attributes,t.DYNAMIC_DRAW),t.drawElementsInstanced(this._gl.TRIANGLE_STRIP,4,t.UNSIGNED_BYTE,0,e.count)}handleResize(){this._updateViewportRectangle()}setDimensions(e){this._dimensions=e}_updateCachedColors(e){this._bgFloat=this._colorToFloat32Array(e.background),this._cursorFloat=this._colorToFloat32Array(e.cursor)}_updateViewportRectangle(){this._addRectangleFloat(this._vertices.attributes,0,0,0,this._terminal.cols*this._dimensions.device.cell.width,this._terminal.rows*this._dimensions.device.cell.height,this._bgFloat)}updateBackgrounds(e){let t=this._terminal,s=this._vertices,r=1,n,o,a,h,l,c,d,u,f,p,b;for(n=0;n<t.rows;n++){for(a=-1,h=0,l=0,c=false,o=0;o<t.cols;o++)d=(n*t.cols+o)*Do,u=e.cells[d+go],f=e.cells[d+_o],p=!!(f&67108864),(u!==h||f!==l&&(c||p))&&((h!==0||c&&l!==0)&&(b=r++*Mi,this._updateRectangle(s,b,l,h,a,o,n)),a=o,h=u,l=f,c=p);(h!==0||c&&l!==0)&&(b=r++*Mi,this._updateRectangle(s,b,l,h,a,t.cols,n))}s.count=r}updateCursor(e){let t=this._verticesCursor,s=e.cursor;if(!s||s.style==="block"){t.count=0;return}let r,n=0;(s.style==="bar"||s.style==="outline")&&(r=n++*Mi,this._addRectangleFloat(t.attributes,r,s.x*this._dimensions.device.cell.width,s.y*this._dimensions.device.cell.height,s.style==="bar"?s.dpr*s.cursorWidth:s.dpr,this._dimensions.device.cell.height,this._cursorFloat)),(s.style==="underline"||s.style==="outline")&&(r=n++*Mi,this._addRectangleFloat(t.attributes,r,s.x*this._dimensions.device.cell.width,(s.y+1)*this._dimensions.device.cell.height-s.dpr,s.width*this._dimensions.device.cell.width,s.dpr,this._cursorFloat)),s.style==="outline"&&(r=n++*Mi,this._addRectangleFloat(t.attributes,r,s.x*this._dimensions.device.cell.width,s.y*this._dimensions.device.cell.height,s.width*this._dimensions.device.cell.width,s.dpr,this._cursorFloat),r=n++*Mi,this._addRectangleFloat(t.attributes,r,(s.x+s.width)*this._dimensions.device.cell.width-s.dpr,s.y*this._dimensions.device.cell.height,s.dpr,this._dimensions.device.cell.height,this._cursorFloat)),t.count=n}_updateRectangle(e,t,s,r,n,o,a){if(s&67108864)switch(s&50331648){case 16777216:case 33554432:Li=this._themeService.colors.ansi[s&255].rgba;break;case 50331648:Li=(s&16777215)<<8;break;case 0:default:Li=this._themeService.colors.foreground.rgba}else switch(r&50331648){case 16777216:case 33554432:Li=this._themeService.colors.ansi[r&255].rgba;break;case 50331648:Li=(r&16777215)<<8;break;case 0:default:Li=this._themeService.colors.background.rgba}e.attributes.length<t+4&&(e.attributes=nb(e.attributes,this._terminal.rows*this._terminal.cols*Mi)),Fd=n*this._dimensions.device.cell.width,zd=a*this._dimensions.device.cell.height,Nd=(Li>>24&255)/255,Hd=(Li>>16&255)/255,Wd=(Li>>8&255)/255,Ud=1,this._addRectangle(e.attributes,t,Fd,zd,(o-n)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,Nd,Hd,Wd,Ud)}_addRectangle(e,t,s,r,n,o,a,h,l,c){e[t]=s/this._dim Line truncated
}\`;var Mi=8;var Wa=Mi*Float32Array.BYTES_PER_ELEMENT;var Ib=20*Mi;var Fd=class uC{constructor(){this.attributes=new Float32Array(Ib),this.count=0}};var Li=0;var zd=0;var Nd=0;var Hd=0;var Wd=0;var Ud=0;var qd=0;var Pb=class fC extends Qt{constructor(e,t,s,r){super();this._terminal=e;this._gl=t;this._dimensions=s;this._themeService=r;this._vertices=new Fd;this._verticesCursor=new Fd;let n=this._gl;this._program=Oe(bm(n,Mb,Bb)),this._register(pt(()=>n.deleteProgram(this._program))),this._projectionLocation=Oe(n.getUniformLocation(this._program,"u_projection")),this._vertexArrayObject=n.createVertexArray(),n.bindVertexArray(this._vertexArrayObject);let o=new Float32Array([0,0,1,0,0,1,1,1]),a=n.createBuffer();this._register(pt(()=>n.deleteBuffer(a))),n.bindBuffer(n.ARRAY_BUFFER,a),n.bufferData(n.ARRAY_BUFFER,o,n.STATIC_DRAW),n.enableVertexAttribArray(3),n.vertexAttribPointer(3,2,this._gl.FLOAT,false,0,0);let h=new Uint8Array([0,1,2,3]),l=n.createBuffer();this._register(pt(()=>n.deleteBuffer(l))),n.bindBuffer(n.ELEMENT_ARRAY_BUFFER,l),n.bufferData(n.ELEMENT_ARRAY_BUFFER,h,n.STATIC_DRAW),this._attributesBuffer=Oe(n.createBuffer()),this._register(pt(()=>n.deleteBuffer(this._attributesBuffer))),n.bindBuffer(n.ARRAY_BUFFER,this._attributesBuffer),n.enableVertexAttribArray(0),n.vertexAttribPointer(0,2,n.FLOAT,false,Wa,0),n.vertexAttribDivisor(0,1),n.enableVertexAttribArray(1),n.vertexAttribPointer(1,2,n.FLOAT,false,Wa,2*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(1,1),n.enableVertexAttribArray(2),n.vertexAttribPointer(2,4,n.FLOAT,false,Wa,4*Float32Array.BYTES_PER_ELEMENT),n.vertexAttribDivisor(2,1),this._updateCachedColors(r.colors),this._register(this._themeService.onChangeColors(c=>{this._updateCachedColors(c),this._updateViewportRectangle()}))}renderBackgrounds(){this._renderVertices(this._vertices)}renderCursor(){this._renderVertices(this._verticesCursor)}_renderVertices(e){let t=this._gl;t.useProgram(this._program),t.bindVertexArray(this._vertexArrayObject),t.uniformMatrix4fv(this._projectionLocation,false,vm),t.bindBuffer(t.ARRAY_BUFFER,this._attributesBuffer),t.bufferData(t.ARRAY_BUFFER,e.attributes,t.DYNAMIC_DRAW),t.drawElementsInstanced(this._gl.TRIANGLE_STRIP,4,t.UNSIGNED_BYTE,0,e.count)}handleResize(){this._updateViewportRectangle()}setDimensions(e){this._dimensions=e}_updateCachedColors(e){this._bgFloat=this._colorToFloat32Array(e.background),this._cursorFloat=this._colorToFloat32Array(e.cursor)}_updateViewportRectangle(){this._addRectangleFloat(this._vertices.attributes,0,0,0,this._terminal.cols*this._dimensions.device.cell.width,this._terminal.rows*this._dimensions.device.cell.height,this._bgFloat)}updateBackgrounds(e){let t=this._terminal,s=this._vertices,r=1,n,o,a,h,l,c,d,u,f,p,b;for(n=0;n<t.rows;n++){for(a=-1,h=0,l=0,c=false,o=0;o<t.cols;o++)d=(n*t.cols+o)*Oo,u=e.cells[d+_o],f=e.cells[d+vo],p=!!(f&67108864),(u!==h||f!==l&&(c||p))&&((h!==0||c&&l!==0)&&(b=r++*Mi,this._updateRectangle(s,b,l,h,a,o,n)),a=o,h=u,l=f,c=p);(h!==0||c&&l!==0)&&(b=r++*Mi,this._updateRectangle(s,b,l,h,a,t.cols,n))}s.count=r}updateCursor(e){let t=this._verticesCursor,s=e.cursor;if(!s||s.style==="block"){t.count=0;return}let r,n=0;(s.style==="bar"||s.style==="outline")&&(r=n++*Mi,this._addRectangleFloat(t.attributes,r,s.x*this._dimensions.device.cell.width,s.y*this._dimensions.device.cell.height,s.style==="bar"?s.dpr*s.cursorWidth:s.dpr,this._dimensions.device.cell.height,this._cursorFloat)),(s.style==="underline"||s.style==="outline")&&(r=n++*Mi,this._addRectangleFloat(t.attributes,r,s.x*this._dimensions.device.cell.width,(s.y+1)*this._dimensions.device.cell.height-s.dpr,s.width*this._dimensions.device.cell.width,s.dpr,this._cursorFloat)),s.style==="outline"&&(r=n++*Mi,this._addRectangleFloat(t.attributes,r,s.x*this._dimensions.device.cell.width,s.y*this._dimensions.device.cell.height,s.width*this._dimensions.device.cell.width,s.dpr,this._cursorFloat),r=n++*Mi,this._addRectangleFloat(t.attributes,r,(s.x+s.width)*this._dimensions.device.cell.width-s.dpr,s.y*this._dimensions.device.cell.height,s.dpr,this._dimensions.device.cell.height,this._cursorFloat)),t.count=n}_updateRectangle(e,t,s,r,n,o,a){if(s&67108864)switch(s&50331648){case 16777216:case 33554432:Li=this._themeService.colors.ansi[s&255].rgba;break;case 50331648:Li=(s&16777215)<<8;break;case 0:default:Li=this._themeService.colors.foreground.rgba}else switch(r&50331648){case 16777216:case 33554432:Li=this._themeService.colors.ansi[r&255].rgba;break;case 50331648:Li=(r&16777215)<<8;break;case 0:default:Li=this._themeService.colors.background.rgba}e.attributes.length<t+4&&(e.attributes=wb(e.attributes,this._terminal.rows*this._terminal.cols*Mi)),zd=n*this._dimensions.device.cell.width,Nd=a*this._dimensions.device.cell.height,Hd=(Li>>24&255)/255,Wd=(Li>>16&255)/255,Ud=(Li>>8&255)/255,qd=1,this._addRectangle(e.attributes,t,zd,Nd,(o-n)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,Hd,Wd,Ud,qd)}_addRectangle(e,t,s,r,n,o,a,h,l,c){e[t]=s/this._dim Line truncated
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
* @license MIT
*
@@ -772,29 +772,29 @@ void main() {
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
*/var vm=Object.defineProperty;var Ub=Object.getOwnPropertyDescriptor;var qb=(i,e)=>{for(var t in e)vm(i,t,{get:e[t],enumerable:true})};var Be=(i,e,t,s)=>{for(var r=s>1?void 0:s?Ub(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&vm(e,t,r),r};var q=(i,e)=>(t,s)=>e(t,s,i);var Qd="Terminal input";var Gl={get:()=>Qd,set:i=>Qd=i};var eu="Too much output to announce, navigate to rows manually to read";var Yl={get:()=>eu,set:i=>eu=i};function Kb(i){return i.replace(/\\r?\\n/g,"\\r")}function jb(i,e){return e?"\\x1B[200~"+i+"\\x1B[201~":i}function Vb(i,e){i.clipboardData&&i.clipboardData.setData("text/plain",e.selectionText),i.preventDefault()}function Gb(i,e,t,s){if(i.stopPropagation(),i.clipboardData){let r=i.clipboardData.getData("text/plain");bm(r,e,t,s)}}function bm(i,e,t,s){i=Kb(i),i=jb(i,t.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==true),t.triggerDataEvent(i,true),e.value=""}function ym(i,e,t){let s=t.getBoundingClientRect(),r=i.clientX-s.left-10,n=i.clientY-s.top-10;e.style.width="20px",e.style.height="20px",e.style.left=\`\${r}px\`,e.style.top=\`\${n}px\`,e.style.zIndex="1000",e.focus()}function tu(i,e,t,s,r){ym(i,e,t),r&&s.rightClickSelect(i),e.value=s.selectionText,e.select()}function Ji(i){return i>65535?(i-=65536,String.fromCharCode((i>>10)+55296)+String.fromCharCode(i%1024+56320)):String.fromCharCode(i)}function Jo(i,e=0,t=i.length){let s="";for(let r=e;r<t;++r){let n=i[r];n>65535?(n-=65536,s+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):s+=String.fromCharCode(n)}return s}var Yb=class lC{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let s=e.length;if(!s)return 0;let r=0,n=0;if(this._interim){let o=e.charCodeAt(n++);56320<=o&&o<=57343?t[r++]=(this._interim-55296)*1024+o-56320+65536:(t[r++]=this._interim,t[r++]=o),this._interim=0}for(let o=n;o<s;++o){let a=e.charCodeAt(o);if(55296<=a&&a<=56319){if(++o>=s)return this._interim=a,r;let h=e.charCodeAt(o);56320<=h&&h<=57343?t[r++]=(a-55296)*1024+h-56320+65536:(t[r++]=a,t[r++]=h);continue}a!==65279&&(t[r++]=a)}return r}};var Xb=class hC{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let s=e.length;if(!s)return 0;let r=0,n,o,a,h,l=0,c=0;if(this.interim[0]){let f=false,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let b=0,v;for(;(v=this.interim[++b]&63)&&b<4;)p<<=6,p|=v;let R=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,L=R-b;for(;c<L;){if(c>=s)return 0;if(v=e[c++],(v&192)!==128){c--,f=true;break}else this.interim[b++]=v,p<<=6,p|=v&63}f||(R===2?p<128?c--:t[r++]=p:R===3?p<2048||p>=55296&&p<=57343||p===65279||(t[r++]=p):p<65536||p>1114111||(t[r++]=p)),this.interim.fill(0)}let d=s-4,u=c;for(;u<s;){for(;u<d&&!((n=e[u])&128)&&!((o=e[u+1])&128)&&!((a=e[u+2])&128)&&!((h=e[u+3])&128);)t[r++]=n,t[r++]=o,t[r++]=a,t[r++]=h,u+=4;if(n=e[u++],n<128)t[r++]=n;else if((n&224)===192){if(u>=s)return this.interim[0]=n,r;if(o=e[u++],(o&192)!==128){u--;continue}if(l=(n&31)<<6|o&63,l<128){u--;continue}t[r++]=l}else if((n&240)===224){if(u>=s)return this.interim[0]=n,r;if(o=e[u++],(o&192)!==128){u--;continue}if(u>=s)return this.interim[0]=n,this.interim[1]=o,r;if(a=e[u++],(a&192)!==128){u--;continue}if(l=(n&15)<<12|(o&63)<<6|a&63,l<2048||l>=55296&&l<=57343||l===65279)continue;t[r++]=l}else if((n&248)===240){if(u>=s)return this.interim[0]=n,r;if(o=e[u++],(o&192)!==128){u--;continue}if(u>=s)return this.interim[0]=n,this.interim[1]=o,r;if(a=e[u++],(a&192)!==128){u--;continue}if(u>=s)return this.interim[0]=n,this.interim[1]=o,this.interim[2]=a,r;if(h=e[u++],(h&192)!==128){u--;continue}if(l=(n&7)<<18|(o&63)<<12|(a&63)<<6|h&63,l<65536||l>1114111)continue;t[r++]=l}}return r}};var wm="";var ss=" ";var kn=class Sm{constructor(){this.fg=0;this.bg=0;this.extended=new $o}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let e=new Sm;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:c Line truncated
*/var xm=Object.defineProperty;var ny=Object.getOwnPropertyDescriptor;var oy=(i,e)=>{for(var t in e)xm(i,t,{get:e[t],enumerable:true})};var Be=(i,e,t,s)=>{for(var r=s>1?void 0:s?ny(e,t):e,n=i.length-1,o;n>=0;n--)(o=i[n])&&(r=(s?o(e,t,r):o(r))||r);return s&&r&&xm(e,t,r),r};var q=(i,e)=>(t,s)=>e(t,s,i);var eu="Terminal input";var Yl={get:()=>eu,set:i=>eu=i};var tu="Too much output to announce, navigate to rows manually to read";var Xl={get:()=>tu,set:i=>tu=i};function ay(i){return i.replace(/\\r?\\n/g,"\\r")}function ly(i,e){return e?"\\x1B[200~"+i+"\\x1B[201~":i}function hy(i,e){i.clipboardData&&i.clipboardData.setData("text/plain",e.selectionText),i.preventDefault()}function cy(i,e,t,s){if(i.stopPropagation(),i.clipboardData){let r=i.clipboardData.getData("text/plain");Cm(r,e,t,s)}}function Cm(i,e,t,s){i=ay(i),i=ly(i,t.decPrivateModes.bracketedPasteMode&&s.rawOptions.ignoreBracketedPasteMode!==true),t.triggerDataEvent(i,true),e.value=""}function km(i,e,t){let s=t.getBoundingClientRect(),r=i.clientX-s.left-10,n=i.clientY-s.top-10;e.style.width="20px",e.style.height="20px",e.style.left=\`\${r}px\`,e.style.top=\`\${n}px\`,e.style.zIndex="1000",e.focus()}function iu(i,e,t,s,r){km(i,e,t),r&&s.rightClickSelect(i),e.value=s.selectionText,e.select()}function Ji(i){return i>65535?(i-=65536,String.fromCharCode((i>>10)+55296)+String.fromCharCode(i%1024+56320)):String.fromCharCode(i)}function ea(i,e=0,t=i.length){let s="";for(let r=e;r<t;++r){let n=i[r];n>65535?(n-=65536,s+=String.fromCharCode((n>>10)+55296)+String.fromCharCode(n%1024+56320)):s+=String.fromCharCode(n)}return s}var dy=class CC{constructor(){this._interim=0}clear(){this._interim=0}decode(e,t){let s=e.length;if(!s)return 0;let r=0,n=0;if(this._interim){let o=e.charCodeAt(n++);56320<=o&&o<=57343?t[r++]=(this._interim-55296)*1024+o-56320+65536:(t[r++]=this._interim,t[r++]=o),this._interim=0}for(let o=n;o<s;++o){let a=e.charCodeAt(o);if(55296<=a&&a<=56319){if(++o>=s)return this._interim=a,r;let h=e.charCodeAt(o);56320<=h&&h<=57343?t[r++]=(a-55296)*1024+h-56320+65536:(t[r++]=a,t[r++]=h);continue}a!==65279&&(t[r++]=a)}return r}};var uy=class kC{constructor(){this.interim=new Uint8Array(3)}clear(){this.interim.fill(0)}decode(e,t){let s=e.length;if(!s)return 0;let r=0,n,o,a,h,l=0,c=0;if(this.interim[0]){let f=false,p=this.interim[0];p&=(p&224)===192?31:(p&240)===224?15:7;let b=0,v;for(;(v=this.interim[++b]&63)&&b<4;)p<<=6,p|=v;let R=(this.interim[0]&224)===192?2:(this.interim[0]&240)===224?3:4,L=R-b;for(;c<L;){if(c>=s)return 0;if(v=e[c++],(v&192)!==128){c--,f=true;break}else this.interim[b++]=v,p<<=6,p|=v&63}f||(R===2?p<128?c--:t[r++]=p:R===3?p<2048||p>=55296&&p<=57343||p===65279||(t[r++]=p):p<65536||p>1114111||(t[r++]=p)),this.interim.fill(0)}let d=s-4,u=c;for(;u<s;){for(;u<d&&!((n=e[u])&128)&&!((o=e[u+1])&128)&&!((a=e[u+2])&128)&&!((h=e[u+3])&128);)t[r++]=n,t[r++]=o,t[r++]=a,t[r++]=h,u+=4;if(n=e[u++],n<128)t[r++]=n;else if((n&224)===192){if(u>=s)return this.interim[0]=n,r;if(o=e[u++],(o&192)!==128){u--;continue}if(l=(n&31)<<6|o&63,l<128){u--;continue}t[r++]=l}else if((n&240)===224){if(u>=s)return this.interim[0]=n,r;if(o=e[u++],(o&192)!==128){u--;continue}if(u>=s)return this.interim[0]=n,this.interim[1]=o,r;if(a=e[u++],(a&192)!==128){u--;continue}if(l=(n&15)<<12|(o&63)<<6|a&63,l<2048||l>=55296&&l<=57343||l===65279)continue;t[r++]=l}else if((n&248)===240){if(u>=s)return this.interim[0]=n,r;if(o=e[u++],(o&192)!==128){u--;continue}if(u>=s)return this.interim[0]=n,this.interim[1]=o,r;if(a=e[u++],(a&192)!==128){u--;continue}if(u>=s)return this.interim[0]=n,this.interim[1]=o,this.interim[2]=a,r;if(h=e[u++],(h&192)!==128){u--;continue}if(l=(n&7)<<18|(o&63)<<12|(a&63)<<6|h&63,l<65536||l>1114111)continue;t[r++]=l}}return r}};var Em="";var ss=" ";var kn=class Tm{constructor(){this.fg=0;this.bg=0;this.extended=new Fo}static toColorRGB(e){return[e>>>16&255,e>>>8&255,e&255]}static fromColorRGB(e){return(e[0]&255)<<16|(e[1]&255)<<8|e[2]&255}clone(){let e=new Tm;return e.fg=this.fg,e.bg=this.bg,e.extended=this.extended.clone(),e}isInverse(){return this.fg&67108864}isBold(){return this.fg&134217728}isUnderline(){return this.hasExtendedAttrs()&&this.extended.underlineStyle!==0?1:this.fg&268435456}isBlink(){return this.fg&536870912}isInvisible(){return this.fg&1073741824}isItalic(){return this.bg&67108864}isDim(){return this.bg&134217728}isStrikethrough(){return this.fg&2147483648}isProtected(){return this.bg&536870912}isOverline(){return this.bg&1073741824}getFgColorMode(){return this.fg&50331648}getBgColorMode(){return this.bg&50331648}isFgRGB(){return(this.fg&50331648)===50331648}isBgRGB(){return(this.bg&50331648)===50331648}isFgPalette(){return(this.fg&50331648)===16777216||(this.fg&50331648)===33554432}isBgPalette(){return(this.bg&50331648)===16777216||(this.bg&50331648)===33554432}isFgDefault(){return(this.fg&50331648)===0}isBgDefault(){return(this.bg&50331648)===0}isAttributeDefault(){return this.fg===0&&this.bg===0}getFgColor(){switch(this.fg&50331648){case 16777216:c Line truncated
WARNING: This link could potentially be dangerous\`)){let t=window.open();if(t){try{t.opener=null}catch{}t.location.href=e}else console.warn("Opening link blocked as opener could not be cleared")}}var Qo=it("CharSizeService");var Fi=it("CoreBrowserService");var ic=it("MouseService");var zi=it("RenderService");var iy=it("SelectionService");var Lm=it("CharacterJoinerService");var vr=it("ThemeService");var Am=it("LinkProviderService");var sy=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(i){setTimeout(()=>{throw i.stack?su.isErrorNoTelemetry(i)?new su(i.message+\`
WARNING: This link could potentially be dangerous\`)){let t=window.open();if(t){try{t.opener=null}catch{}t.location.href=e}else console.warn("Opening link blocked as opener could not be cleared")}}var ta=it("CharSizeService");var Fi=it("CoreBrowserService");var sc=it("MouseService");var zi=it("RenderService");var vy=it("SelectionService");var Im=it("CharacterJoinerService");var vr=it("ThemeService");var Pm=it("LinkProviderService");var by=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(i){setTimeout(()=>{throw i.stack?ru.isErrorNoTelemetry(i)?new ru(i.message+\`
\`+i.stack):new Error(i.message+\`
\`+i.stack):i},0)}}addListener(i){return this.listeners.push(i),()=>{this._removeListener(i)}}emit(i){this.listeners.forEach(e=>{e(i)})}_removeListener(i){this.listeners.splice(this.listeners.indexOf(i),1)}setUnexpectedErrorHandler(i){this.unexpectedErrorHandler=i}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(i){this.unexpectedErrorHandler(i),this.emit(i)}onUnexpectedExternalError(i){this.unexpectedErrorHandler(i)}};var ry=new sy;function bo(i){ny(i)||ry.onUnexpectedError(i)}var Jl="Canceled";function ny(i){return i instanceof oy?true:i instanceof Error&&i.name===Jl&&i.message===Jl}var oy=class dC extends Error{constructor(){super(Jl),this.name=this.message}};function ay(i){return new Error(\`Illegal argument: \${i}\`)}var su=class Ql extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof Ql)return e;let t=new Ql;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}};var eh=class Rm extends Error{constructor(e){super(e||"An unexpected bug occurred."),Object.setPrototypeOf(this,Rm.prototype)}};function Rt(i,e=0){return i[i.length-(1+e)]}var ly;(i=>{function e(n){return n<0}i.isLessThan=e;function t(n){return n<=0}i.isLessThanOrEqual=t;function s(n){return n>0}i.isGreaterThan=s;function r(n){return n===0}i.isNeitherLessOrGreaterThan=r,i.greaterThan=1,i.lessThan=-1,i.neitherLessOrGreaterThan=0})(ly||(ly={}));function hy(i,e){let t=this,s=false,r;return function(){if(s)return r;if(s=true,e);else r=i.apply(t,arguments);return r}}var Mm;(i=>{function e(g){return g&&typeof g=="object"&&typeof g[Symbol.iterator]=="function"}i.is=e;let t=Object.freeze([]);function s(){return t}i.empty=s;function*r(g){yield g}i.single=r;function n(g){return e(g)?g:r(g)}i.wrap=n;function o(g){return g||t}i.from=o;function*a(g){for(let E=g.length-1;E>=0;E--)yield g[E]}i.reverse=a;function h(g){return!g||g[Symbol.iterator]().next().done===true}i.isEmpty=h;function l(g){return g[Symbol.iterator]().next().value}i.first=l;function c(g,E){let k=0;for(let D of g)if(E(D,k++))return true;return false}i.some=c;function d(g,E){for(let k of g)if(E(k))return k}i.find=d;function*u(g,E){for(let k of g)E(k)&&(yield k)}i.filter=u;function*f(g,E){let k=0;for(let D of g)yield E(D,k++)}i.map=f;function*p(g,E){let k=0;for(let D of g)yield*E(D,k++)}i.flatMap=p;function*b(...g){for(let E of g)yield*E}i.concat=b;function v(g,E,k){let D=k;for(let N of g)D=E(D,N);return D}i.reduce=v;function*R(g,E,k=g.length){for(E<0&&(E+=g.length),k<0?k+=g.length:k>g.length&&(k=g.length);E<k;E++)yield g[E]}i.slice=R;function L(g,E=Number.POSITIVE_INFINITY){let k=[];if(E===0)return[k,g];let D=g[Symbol.iterator]();for(let N=0;N<E;N++){let z=D.next();if(z.done)return[k,i.empty()];k.push(z.value)}return[k,{[Symbol.iterator](){return D}}]}i.consume=L;async function A(g){let E=[];for await(let k of g)E.push(k);return Promise.resolve(E)}i.asyncToArray=A})(Mm||(Mm={}));function cy(i){return i}function Bm(i,e){}function ru(i){return i}function Is(i){if(Mm.is(i)){let e=[];for(let t of i)if(t)try{t.dispose()}catch(s){e.push(s)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"Encountered errors while disposing of store");return Array.isArray(i)?[]:i}else if(i)return i.dispose(),i}function dy(...i){let e=Ce(()=>Is(i));return e}function Ce(i){let e=cy({dispose:hy(()=>{i()})});return e}var Im=class Pm{constructor(){this._toDispose=new Set;this._isDisposed=false}dispose(){this._isDisposed||(this._isDisposed=true,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Is(this._toDispose)}finally{this._toDispose.clear()}}add(e){if(!e)return e;if(e===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?Pm.DISABLE_DISPOSED_WARNING||console.warn(new 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 new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),Bm())}};Im.DISABLE_DISPOSED_WARNING=false;var rs=Im;var ne=class uC{constructor(){this._store=new rs;Bm(this._store)}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};ne.None=Object.freeze({dispose(){}});var fr=class fC{constructor(){this._isDisposed=false}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null?void 0:t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=true,(e=this._value)==null?void 0:e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}};var Di=typeof window=="object"?window:globalThis;var th=class ih{constructor(e){ Line truncated
\`+i.stack):i},0)}}addListener(i){return this.listeners.push(i),()=>{this._removeListener(i)}}emit(i){this.listeners.forEach(e=>{e(i)})}_removeListener(i){this.listeners.splice(this.listeners.indexOf(i),1)}setUnexpectedErrorHandler(i){this.unexpectedErrorHandler=i}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(i){this.unexpectedErrorHandler(i),this.emit(i)}onUnexpectedExternalError(i){this.unexpectedErrorHandler(i)}};var yy=new by;function yo(i){wy(i)||yy.onUnexpectedError(i)}var Ql="Canceled";function wy(i){return i instanceof Sy?true:i instanceof Error&&i.name===Ql&&i.message===Ql}var Sy=class TC extends Error{constructor(){super(Ql),this.name=this.message}};function xy(i){return new Error(\`Illegal argument: \${i}\`)}var ru=class eh extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof eh)return e;let t=new eh;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}};var th=class Dm extends Error{constructor(e){super(e||"An unexpected bug occurred."),Object.setPrototypeOf(this,Dm.prototype)}};function Rt(i,e=0){return i[i.length-(1+e)]}var Cy;(i=>{function e(n){return n<0}i.isLessThan=e;function t(n){return n<=0}i.isLessThanOrEqual=t;function s(n){return n>0}i.isGreaterThan=s;function r(n){return n===0}i.isNeitherLessOrGreaterThan=r,i.greaterThan=1,i.lessThan=-1,i.neitherLessOrGreaterThan=0})(Cy||(Cy={}));function ky(i,e){let t=this,s=false,r;return function(){if(s)return r;if(s=true,e);else r=i.apply(t,arguments);return r}}var $m;(i=>{function e(g){return g&&typeof g=="object"&&typeof g[Symbol.iterator]=="function"}i.is=e;let t=Object.freeze([]);function s(){return t}i.empty=s;function*r(g){yield g}i.single=r;function n(g){return e(g)?g:r(g)}i.wrap=n;function o(g){return g||t}i.from=o;function*a(g){for(let E=g.length-1;E>=0;E--)yield g[E]}i.reverse=a;function h(g){return!g||g[Symbol.iterator]().next().done===true}i.isEmpty=h;function l(g){return g[Symbol.iterator]().next().value}i.first=l;function c(g,E){let k=0;for(let D of g)if(E(D,k++))return true;return false}i.some=c;function d(g,E){for(let k of g)if(E(k))return k}i.find=d;function*u(g,E){for(let k of g)E(k)&&(yield k)}i.filter=u;function*f(g,E){let k=0;for(let D of g)yield E(D,k++)}i.map=f;function*p(g,E){let k=0;for(let D of g)yield*E(D,k++)}i.flatMap=p;function*b(...g){for(let E of g)yield*E}i.concat=b;function v(g,E,k){let D=k;for(let N of g)D=E(D,N);return D}i.reduce=v;function*R(g,E,k=g.length){for(E<0&&(E+=g.length),k<0?k+=g.length:k>g.length&&(k=g.length);E<k;E++)yield g[E]}i.slice=R;function L(g,E=Number.POSITIVE_INFINITY){let k=[];if(E===0)return[k,g];let D=g[Symbol.iterator]();for(let N=0;N<E;N++){let z=D.next();if(z.done)return[k,i.empty()];k.push(z.value)}return[k,{[Symbol.iterator](){return D}}]}i.consume=L;async function A(g){let E=[];for await(let k of g)E.push(k);return Promise.resolve(E)}i.asyncToArray=A})($m||($m={}));function Ey(i){return i}function Om(i,e){}function nu(i){return i}function Ps(i){if($m.is(i)){let e=[];for(let t of i)if(t)try{t.dispose()}catch(s){e.push(s)}if(e.length===1)throw e[0];if(e.length>1)throw new AggregateError(e,"Encountered errors while disposing of store");return Array.isArray(i)?[]:i}else if(i)return i.dispose(),i}function Ty(...i){let e=Ce(()=>Ps(i));return e}function Ce(i){let e=Ey({dispose:ky(()=>{i()})});return e}var Fm=class zm{constructor(){this._toDispose=new Set;this._isDisposed=false}dispose(){this._isDisposed||(this._isDisposed=true,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{Ps(this._toDispose)}finally{this._toDispose.clear()}}add(e){if(!e)return e;if(e===this)throw new Error("Cannot register a disposable on itself!");return this._isDisposed?zm.DISABLE_DISPOSED_WARNING||console.warn(new 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 new Error("Cannot dispose a disposable on itself!");this._toDispose.delete(e),e.dispose()}}deleteAndLeak(e){e&&this._toDispose.has(e)&&(this._toDispose.delete(e),Om())}};Fm.DISABLE_DISPOSED_WARNING=false;var rs=Fm;var ne=class LC{constructor(){this._store=new rs;Om(this._store)}dispose(){this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}};ne.None=Object.freeze({dispose(){}});var fr=class AC{constructor(){this._isDisposed=false}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null?void 0:t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=true,(e=this._value)==null?void 0:e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}};var Di=typeof window=="object"?window:globalThis;var ih=class sh{constructor(e){ Line truncated
\`).slice(2).join(\`
\`))}};var vy=class extends Error{constructor(i,e){super(i),this.name="ListenerLeakError",this.stack=e}};var by=class extends Error{constructor(i,e){super(i),this.name="ListenerRefusalError",this.stack=e}};var yy=0;var ja=class mC{constructor(e){this.value=e;this.id=yy++}};var wy=2;var Sy;var W=class gC{constructor(e){var t,s,r,n;this._size=0;this._options=e,this._leakageMon=((t=this._options)==null?void 0:t.leakWarningThreshold)?new gy((e==null?void 0:e.onListenerError)??bo,((s=this._options)==null?void 0:s.leakWarningThreshold)??my):void 0,this._perfMon=((r=this._options)==null?void 0:r._profName)?new py(this._options._profName):void 0,this._deliveryQueue=(n=this._options)==null?void 0:n.deliveryQueue}dispose(){var e,t,s,r;if(!this._disposed){if(this._disposed=true,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners){this._listeners=void 0,this._size=0}(s=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null?void 0:s.call(t),(r=this._leakageMon)==null?void 0:r.dispose()}}get event(){return this._event??(this._event=(e,t,s)=>{var a,h,l,c,d;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let u=\`[\${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (\${this._size} vs \${this._leakageMon.threshold})\`;console.warn(u);let f=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],p=new by(\`\${u}. HINT: Stack shows most frequent listener (\${f[1]}-times)\`,f[0]);return(((a=this._options)==null?void 0:a.onListenerError)||bo)(p),ne.None}if(this._disposed)return ne.None;t&&(e=e.bind(t));let r=new ja(e),n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=_y.create(),n=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof ja?(this._deliveryQueue??(this._deliveryQueue=new xy),this._listeners=[this._listeners,r]):this._listeners.push(r):((l=(h=this._options)==null?void 0:h.onWillAddFirstListener)==null?void 0:l.call(h,this),this._listeners=r,(d=(c=this._options)==null?void 0:c.onDidAddFirstListener)==null?void 0:d.call(c,this)),this._size++;let o=Ce(()=>{n==null?void 0:n(),this._removeListener(r)});if(s instanceof rs?s.add(o):Array.isArray(s)&&s.push(o),Sy);return o}),this._event}_removeListener(e){var n,o,a,h;if((o=(n=this._options)==null?void 0:n.onWillRemoveListener)==null?void 0:o.call(n,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(h=(a=this._options)==null?void 0:a.onDidRemoveLastListener)==null?void 0:h.call(a,this),this._size=0;return}let t=this._listeners,s=t.indexOf(e);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[s]=void 0;let r=this._deliveryQueue.current===this;if(this._size*wy<=t.length){let l=0;for(let c=0;c<t.length;c++)t[c]?t[l++]=t[c]:r&&(this._deliveryQueue.end--,l<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=l}}_deliver(e,t){var r;if(!e)return;let s=((r=this._options)==null?void 0:r.onListenerError)||bo;if(!s){e.value(t);return}try{e.value(t)}catch(n){s(n)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,s,r,n;if(((t=this._deliveryQueue)==null?void 0:t.current)&&(this._deliverQueue(this._deliveryQueue),(s=this._perfMon)==null?void 0:s.stop()),(r=this._perfMon)==null?void 0:r.start(this._size),this._listeners)if(this._listeners instanceof ja)this._deliver(this._listeners,e);else{let o=this._deliveryQueue;o.enqueue(this,e,this._listeners.length),this._deliverQueue(o)}(n=this._perfMon)==null?void 0:n.stop()}hasListeners(){return this._size>0}};var xy=class{constructor(){this.i=-1;this.end=0}enqueue(i,e,t){this.i=0,this.end=t,this.current=i,this.value=e}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var nh=class _C{constructor(){this.mapWindowIdToZoomLevel=new Map;this._onDidChangeZoomLevel=new W;this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event;this.mapWindowIdToZoomFactor=new Map;this._onDidChangeFullscreen=new W;this.onDidChangeFullscreen=this._onDidChangeFullscreen.event;this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let s=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(s,e),this._onDidChangeZoomLevel.fire(s)}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 s=this.getWindowId(t);this.mapWindowIdToFullScreen.set(s,e),this._onDidChangeFullscreen.fire(s)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};nh.INSTANCE=new nh;var sc=nh;function Cy(i,e,t){typeof e=="string"& Line truncated
\`)})),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(c=>this._handleScroll(c)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:true,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(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.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=true,this._suppressOnScrollHandler=true,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=false,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=false)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=true;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),s=t-this._bufferService.buffer.ydisp;s!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(s)),this._isHandlingScroll=false}};fh=Be([q(2,wt),q(3,Fi),q(4,km),q(5,vr),q(6,St),q(7,zi)],fh);var ph=class RC extends ne{constructor(e,t,s,r,n){super();this._screenElement=e;this._bufferService=t;this._coreBrowserService=s;this._decorationService=r;this._renderService=n;this._decorationElements=new Map;this._altBufferIsActive=false;this._dimensionsChanged=false;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=true,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(o=>this._removeDecoration(o))),this._register(Ce(()=>{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=false}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var r;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((r=e==null?void 0:e.options)==null?void 0:r.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 s=e.options.x??0;return s&&s>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 s=this._decorationElements.get(e);s||(s=this._createElement(e),e.element=s,this._decorationElements.set(e,s),this._container.appendChild(s),e.onDispose(()=>{this._decorationElements.delete(e),s.remove()})),s.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(s.style.width=\`\${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px\`,s.style.heigh Line truncated
\`,i.VT="\\v",i.FF="\\f",i.CR="\\r",i.SO="",i.SI="",i.DLE="",i.DC1="",i.DC2="",i.DC3="",i.DC4="",i.NAK="",i.SYN="",i.ETB="",i.CAN="",i.EM="",i.SUB="",i.ESC="\\x1B",i.FS="",i.GS="",i.RS="",i.US="",i.SP=" ",i.DEL=""))($||($={}));var So;(i=>(i.PAD="€",i.HOP="",i.BPH="‚",i.NBH="ƒ",i.IND="„",i.NEL="…",i.SSA="†",i.ESA="‡",i.HTS="ˆ",i.HTJ="‰",i.VTS="Š",i.PLD="‹",i.PLU="Œ",i.RI="",i.SS2="Ž",i.SS3="",i.DCS="",i.PU1="‘",i.PU2="’",i.STS="“",i.CCH="”",i.MW="•",i.SPA="–",i.EPA="—",i.SOS="˜",i.SGCI="™",i.SCI="š",i.CSI="›",i.ST="œ",i.OSC="",i.PM="ž",i.APC="Ÿ"))(So||(So={}));var Vm;(i=>i.ST=\`\${$.ESC}\\\\\`)(Vm||(Vm={}));var mh=class BC{constructor(e,t,s,r,n,o){this._textarea=e;this._compositionView=t;this._bufferService=s;this._optionsService=r;this._coreService=n;this._renderService=o;this._isComposing=false,this._isSendingComposition=false,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=true,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(true)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return false;this._finalizeComposition(false)}return e.keyCode===229?(this._handleAnyTextareaChanges(),false):true}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=false,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=true,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=false;let s;t.start+=this._dataAlreadySent.length,this._isComposing?s=this._textarea.value.substring(t.start,this._compositionPosition.start):s=this._textarea.value.substring(t.start),s.length>0&&this._coreService.triggerDataEvent(s,true)}},0)}else{this._isSendingComposition=false;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,true)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,s=t.replace(e,"");this._dataAlreadySent=s,t.length>e.length?this._coreService.triggerDataEvent(s,true):t.length<e.length?this._coreService.triggerDataEvent(\`\${$.DEL}\`,true):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,true)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let t=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),s=this._renderService.dimensions.css.cell.height,r=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,n=t*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=n+"px",this._compositionView.style.top=r+"px",this._compositionView.style.height=s+"px",this._compositionView.style.lineHeight=s+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let o=this._compositionView.getBoundingClientRect();this._textarea.style.left=n+"px",this._textarea.style.top=r+"px",this._textarea.style.width=Math.max(o.width,1)+"px",this._textarea.style.height=Math.max(o.height,1)+"px",this._textarea.style.lineHeight=o.height+"px"}e||setTimeout(()=>this.updateCompositionElements(true),0)}}};mh=Be([q(2,wt),q(3,St),q(4,Fs),q(5,zi)],mh);var Qe=0;var et=0;var tt=0;var Me=0;var yu={css:"#00000000",rgba:0};var Fe;(i=>{function e(r,n,o,a){return a!==void 0?\`#\${ms(r)}\${ms(n)}\${ms(o)}\${ms(a)}\`:\`#\${ms(r)}\${ms(n)}\${ms(o)}\`}i.toCss=e;function t(r,n,o,a=255){return(r<<24|n<<16|o<<8|a)>>>0}i.toRgba=t;function s(r,n,o,a){return{css:i.toCss(r,n,o,a),rgba:i.toRgba(r,n,o,a)}}i.toColor=s})(Fe||(Fe={}));var ye;(i=>{function e(h,l){if(Me=(l.rgba&255)/255,Me===1)return{css:l.css,rgba:l.rgba};let c=l.rgba>>24&255,d=l.rgba>>16&255,u=l.rgba>>8&255,f=h.rgba>>24&255,p=h.rgba>>16&255,b=h.rgba>>8&255;Qe=f+Math.round((c-f)*Me),et=p+Math.round((d-p)*Me),tt=b+Math.round((u-b)*Me);let v=Fe.toCss(Qe,et,tt),R=Fe.toRgba(Qe,et,tt);return{css:v,rgba:R}}i.blend=e;function t(h){return(h.rgba&255)===255}i.isOpaque=t;function s(h,l,c){let d=xo.ensureContrastRatio(h.rgba,l.rgba,c);if(d)return Fe.toColor(d>>24&255,d>>16&255,d>>8&255)}i.ensureContrastRatio=s;function r(h){let l=(h.rgba|255)>>>0;return[Qe,et,tt]=xo.toChannels(l),{css:Fe.toCss(Qe,et,tt),rgba:l}}i.opaque=r;function n(h,l){return Me=Math.round(l*255),[Qe,et,tt]=xo.toChannels(h.rgba),{css:Fe.toCss(Qe,et,tt,Me),rgba:Fe.toRgba(Qe,et,tt,Me)}}i.o Line truncated
\`))}};var Py=class extends Error{constructor(i,e){super(i),this.name="ListenerLeakError",this.stack=e}};var Dy=class extends Error{constructor(i,e){super(i),this.name="ListenerRefusalError",this.stack=e}};var $y=0;var Ga=class MC{constructor(e){this.value=e;this.id=$y++}};var Oy=2;var Fy;var W=class BC{constructor(e){var t,s,r,n;this._size=0;this._options=e,this._leakageMon=((t=this._options)==null?void 0:t.leakWarningThreshold)?new By((e==null?void 0:e.onListenerError)??yo,((s=this._options)==null?void 0:s.leakWarningThreshold)??My):void 0,this._perfMon=((r=this._options)==null?void 0:r._profName)?new Ry(this._options._profName):void 0,this._deliveryQueue=(n=this._options)==null?void 0:n.deliveryQueue}dispose(){var e,t,s,r;if(!this._disposed){if(this._disposed=true,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners){this._listeners=void 0,this._size=0}(s=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null?void 0:s.call(t),(r=this._leakageMon)==null?void 0:r.dispose()}}get event(){return this._event??(this._event=(e,t,s)=>{var a,h,l,c,d;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let u=\`[\${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (\${this._size} vs \${this._leakageMon.threshold})\`;console.warn(u);let f=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],p=new Dy(\`\${u}. HINT: Stack shows most frequent listener (\${f[1]}-times)\`,f[0]);return(((a=this._options)==null?void 0:a.onListenerError)||yo)(p),ne.None}if(this._disposed)return ne.None;t&&(e=e.bind(t));let r=new Ga(e),n;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(r.stack=Iy.create(),n=this._leakageMon.check(r.stack,this._size+1)),this._listeners?this._listeners instanceof Ga?(this._deliveryQueue??(this._deliveryQueue=new zy),this._listeners=[this._listeners,r]):this._listeners.push(r):((l=(h=this._options)==null?void 0:h.onWillAddFirstListener)==null?void 0:l.call(h,this),this._listeners=r,(d=(c=this._options)==null?void 0:c.onDidAddFirstListener)==null?void 0:d.call(c,this)),this._size++;let o=Ce(()=>{n==null?void 0:n(),this._removeListener(r)});if(s instanceof rs?s.add(o):Array.isArray(s)&&s.push(o),Fy);return o}),this._event}_removeListener(e){var n,o,a,h;if((o=(n=this._options)==null?void 0:n.onWillRemoveListener)==null?void 0:o.call(n,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(h=(a=this._options)==null?void 0:a.onDidRemoveLastListener)==null?void 0:h.call(a,this),this._size=0;return}let t=this._listeners,s=t.indexOf(e);if(s===-1)throw console.log("disposed?",this._disposed),console.log("size?",this._size),console.log("arr?",JSON.stringify(this._listeners)),new Error("Attempted to dispose unknown listener");this._size--,t[s]=void 0;let r=this._deliveryQueue.current===this;if(this._size*Oy<=t.length){let l=0;for(let c=0;c<t.length;c++)t[c]?t[l++]=t[c]:r&&(this._deliveryQueue.end--,l<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=l}}_deliver(e,t){var r;if(!e)return;let s=((r=this._options)==null?void 0:r.onListenerError)||yo;if(!s){e.value(t);return}try{e.value(t)}catch(n){s(n)}}_deliverQueue(e){let t=e.current._listeners;for(;e.i<e.end;)this._deliver(t[e.i++],e.value);e.reset()}fire(e){var t,s,r,n;if(((t=this._deliveryQueue)==null?void 0:t.current)&&(this._deliverQueue(this._deliveryQueue),(s=this._perfMon)==null?void 0:s.stop()),(r=this._perfMon)==null?void 0:r.start(this._size),this._listeners)if(this._listeners instanceof Ga)this._deliver(this._listeners,e);else{let o=this._deliveryQueue;o.enqueue(this,e,this._listeners.length),this._deliverQueue(o)}(n=this._perfMon)==null?void 0:n.stop()}hasListeners(){return this._size>0}};var zy=class{constructor(){this.i=-1;this.end=0}enqueue(i,e,t){this.i=0,this.end=t,this.current=i,this.value=e}reset(){this.i=this.end,this.current=void 0,this.value=void 0}};var oh=class IC{constructor(){this.mapWindowIdToZoomLevel=new Map;this._onDidChangeZoomLevel=new W;this.onDidChangeZoomLevel=this._onDidChangeZoomLevel.event;this.mapWindowIdToZoomFactor=new Map;this._onDidChangeFullscreen=new W;this.onDidChangeFullscreen=this._onDidChangeFullscreen.event;this.mapWindowIdToFullScreen=new Map}getZoomLevel(e){return this.mapWindowIdToZoomLevel.get(this.getWindowId(e))??0}setZoomLevel(e,t){if(this.getZoomLevel(t)===e)return;let s=this.getWindowId(t);this.mapWindowIdToZoomLevel.set(s,e),this._onDidChangeZoomLevel.fire(s)}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 s=this.getWindowId(t);this.mapWindowIdToFullScreen.set(s,e),this._onDidChangeFullscreen.fire(s)}isFullscreen(e){return!!this.mapWindowIdToFullScreen.get(this.getWindowId(e))}getWindowId(e){return e.vscodeWindowId}};oh.INSTANCE=new oh;var rc=oh;function Ny(i,e,t){typeof e=="string"& Line truncated
\`)})),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(c=>this._handleScroll(c)))}scrollLines(e){let t=this._scrollableElement.getScrollPosition();this._scrollableElement.setScrollPosition({reuseAnimation:true,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(){var e;return{mouseWheelScrollSensitivity:this._optionsService.rawOptions.scrollSensitivity,fastScrollSensitivity:this._optionsService.rawOptions.fastScrollSensitivity,verticalScrollbarSize:((e=this._optionsService.rawOptions.overviewRuler)==null?void 0:e.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=true,this._suppressOnScrollHandler=true,this._scrollableElement.setScrollDimensions({height:this._renderService.dimensions.css.canvas.height,scrollHeight:this._renderService.dimensions.css.cell.height*this._bufferService.buffer.lines.length}),this._suppressOnScrollHandler=false,e!==this._latestYDisp&&this._scrollableElement.setScrollPosition({scrollTop:e*this._renderService.dimensions.css.cell.height}),this._isSyncing=false)}_handleScroll(e){if(!this._renderService||this._isHandlingScroll||this._suppressOnScrollHandler)return;this._isHandlingScroll=true;let t=Math.round(e.scrollTop/this._renderService.dimensions.css.cell.height),s=t-this._bufferService.buffer.ydisp;s!==0&&(this._latestYDisp=t,this._onRequestScrollLines.fire(s)),this._isHandlingScroll=false}};ph=Be([q(2,wt),q(3,Fi),q(4,Rm),q(5,vr),q(6,St),q(7,zi)],ph);var mh=class jC extends ne{constructor(e,t,s,r,n){super();this._screenElement=e;this._bufferService=t;this._coreBrowserService=s;this._decorationService=r;this._renderService=n;this._decorationElements=new Map;this._altBufferIsActive=false;this._dimensionsChanged=false;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=true,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(o=>this._removeDecoration(o))),this._register(Ce(()=>{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=false}_renderDecoration(e){this._refreshStyle(e),this._dimensionsChanged&&this._refreshXPosition(e)}_createElement(e){var r;let t=this._coreBrowserService.mainDocument.createElement("div");t.classList.add("xterm-decoration"),t.classList.toggle("xterm-decoration-top-layer",((r=e==null?void 0:e.options)==null?void 0:r.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 s=e.options.x??0;return s&&s>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 s=this._decorationElements.get(e);s||(s=this._createElement(e),e.element=s,this._decorationElements.set(e,s),this._container.appendChild(s),e.onDispose(()=>{this._decorationElements.delete(e),s.remove()})),s.style.display=this._altBufferIsActive?"none":"block",this._altBufferIsActive||(s.style.width=\`\${Math.round((e.options.width||1)*this._renderService.dimensions.css.cell.width)}px\`,s.style.heigh Line truncated
\`,i.VT="\\v",i.FF="\\f",i.CR="\\r",i.SO="",i.SI="",i.DLE="",i.DC1="",i.DC2="",i.DC3="",i.DC4="",i.NAK="",i.SYN="",i.ETB="",i.CAN="",i.EM="",i.SUB="",i.ESC="\\x1B",i.FS="",i.GS="",i.RS="",i.US="",i.SP=" ",i.DEL=""))($||($={}));var xo;(i=>(i.PAD="€",i.HOP="",i.BPH="‚",i.NBH="ƒ",i.IND="„",i.NEL="…",i.SSA="†",i.ESA="‡",i.HTS="ˆ",i.HTJ="‰",i.VTS="Š",i.PLD="‹",i.PLU="Œ",i.RI="",i.SS2="Ž",i.SS3="",i.DCS="",i.PU1="‘",i.PU2="’",i.STS="“",i.CCH="”",i.MW="•",i.SPA="–",i.EPA="—",i.SOS="˜",i.SGCI="™",i.SCI="š",i.CSI="›",i.ST="œ",i.OSC="",i.PM="ž",i.APC="Ÿ"))(xo||(xo={}));var Jm;(i=>i.ST=\`\${$.ESC}\\\\\`)(Jm||(Jm={}));var gh=class GC{constructor(e,t,s,r,n,o){this._textarea=e;this._compositionView=t;this._bufferService=s;this._optionsService=r;this._coreService=n;this._renderService=o;this._isComposing=false,this._isSendingComposition=false,this._compositionPosition={start:0,end:0},this._dataAlreadySent=""}get isComposing(){return this._isComposing}compositionstart(){this._isComposing=true,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(true)}keydown(e){if(this._isComposing||this._isSendingComposition){if(e.keyCode===20||e.keyCode===229||e.keyCode===16||e.keyCode===17||e.keyCode===18)return false;this._finalizeComposition(false)}return e.keyCode===229?(this._handleAnyTextareaChanges(),false):true}_finalizeComposition(e){if(this._compositionView.classList.remove("active"),this._isComposing=false,e){let t={start:this._compositionPosition.start,end:this._compositionPosition.end};this._isSendingComposition=true,setTimeout(()=>{if(this._isSendingComposition){this._isSendingComposition=false;let s;t.start+=this._dataAlreadySent.length,this._isComposing?s=this._textarea.value.substring(t.start,this._compositionPosition.start):s=this._textarea.value.substring(t.start),s.length>0&&this._coreService.triggerDataEvent(s,true)}},0)}else{this._isSendingComposition=false;let t=this._textarea.value.substring(this._compositionPosition.start,this._compositionPosition.end);this._coreService.triggerDataEvent(t,true)}}_handleAnyTextareaChanges(){let e=this._textarea.value;setTimeout(()=>{if(!this._isComposing){let t=this._textarea.value,s=t.replace(e,"");this._dataAlreadySent=s,t.length>e.length?this._coreService.triggerDataEvent(s,true):t.length<e.length?this._coreService.triggerDataEvent(\`\${$.DEL}\`,true):t.length===e.length&&t!==e&&this._coreService.triggerDataEvent(t,true)}},0)}updateCompositionElements(e){if(this._isComposing){if(this._bufferService.buffer.isCursorInViewport){let t=Math.min(this._bufferService.buffer.x,this._bufferService.cols-1),s=this._renderService.dimensions.css.cell.height,r=this._bufferService.buffer.y*this._renderService.dimensions.css.cell.height,n=t*this._renderService.dimensions.css.cell.width;this._compositionView.style.left=n+"px",this._compositionView.style.top=r+"px",this._compositionView.style.height=s+"px",this._compositionView.style.lineHeight=s+"px",this._compositionView.style.fontFamily=this._optionsService.rawOptions.fontFamily,this._compositionView.style.fontSize=this._optionsService.rawOptions.fontSize+"px";let o=this._compositionView.getBoundingClientRect();this._textarea.style.left=n+"px",this._textarea.style.top=r+"px",this._textarea.style.width=Math.max(o.width,1)+"px",this._textarea.style.height=Math.max(o.height,1)+"px",this._textarea.style.lineHeight=o.height+"px"}e||setTimeout(()=>this.updateCompositionElements(true),0)}}};gh=Be([q(2,wt),q(3,St),q(4,zs),q(5,zi)],gh);var Qe=0;var et=0;var tt=0;var Me=0;var wu={css:"#00000000",rgba:0};var Fe;(i=>{function e(r,n,o,a){return a!==void 0?\`#\${ms(r)}\${ms(n)}\${ms(o)}\${ms(a)}\`:\`#\${ms(r)}\${ms(n)}\${ms(o)}\`}i.toCss=e;function t(r,n,o,a=255){return(r<<24|n<<16|o<<8|a)>>>0}i.toRgba=t;function s(r,n,o,a){return{css:i.toCss(r,n,o,a),rgba:i.toRgba(r,n,o,a)}}i.toColor=s})(Fe||(Fe={}));var ye;(i=>{function e(h,l){if(Me=(l.rgba&255)/255,Me===1)return{css:l.css,rgba:l.rgba};let c=l.rgba>>24&255,d=l.rgba>>16&255,u=l.rgba>>8&255,f=h.rgba>>24&255,p=h.rgba>>16&255,b=h.rgba>>8&255;Qe=f+Math.round((c-f)*Me),et=p+Math.round((d-p)*Me),tt=b+Math.round((u-b)*Me);let v=Fe.toCss(Qe,et,tt),R=Fe.toRgba(Qe,et,tt);return{css:v,rgba:R}}i.blend=e;function t(h){return(h.rgba&255)===255}i.isOpaque=t;function s(h,l,c){let d=Co.ensureContrastRatio(h.rgba,l.rgba,c);if(d)return Fe.toColor(d>>24&255,d>>16&255,d>>8&255)}i.ensureContrastRatio=s;function r(h){let l=(h.rgba|255)>>>0;return[Qe,et,tt]=Co.toChannels(l),{css:Fe.toCss(Qe,et,tt),rgba:l}}i.opaque=r;function n(h,l){return Me=Math.round(l*255),[Qe,et,tt]=Co.toChannels(h.rgba),{css:Fe.toCss(Qe,et,tt,Me),rgba:Fe.toRgba(Qe,et,tt,Me)}}i.o Line truncated
\`:\`
\`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),cc&&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),s=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!s||!r||!t?false:this._areCoordsInSelection(t,s,r)}isCellInSelection(e,t){let s=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!s||!r?false:this._areCoordsInSelection([e,t],s,r)}_areCoordsInSelection(e,t,s){return e[1]>t[1]&&e[1]<s[1]||t[1]===s[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<s[0]||t[1]<s[1]&&e[1]===s[1]&&e[0]<s[0]||t[1]<s[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){var n,o;let s=(o=(n=this._linkifier.currentLink)==null?void 0:n.link)==null?void 0:o.range;if(s)return this._model.selectionStart=[s.start.x-1,s.start.y-1],this._model.selectionStartLength=xu(s,this._bufferService.cols),this._model.selectionEnd=void 0,true;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,true):false}selectAll(){this._model.isSelectAllActive=true,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,true);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=hc(this._coreBrowserService.window,e,this._screenElement)[1],s=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=s?0:(t>s&&(t-=s),t=Math.min(Math.max(t,-Za),Za),t/=Za,t/Math.abs(t)+Math.round(t*(Jw-1)))}shouldForceSelection(e){return zo?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(true)}}_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(),Qw)}_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=false,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,true)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(zo&&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){this.refresh(true);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWor Line truncated
\`))),this._register(this._terminal.onA11yTab(o=>this._handleTab(o))),this._register(this._terminal.onKey(o=>this._handleKey(o.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(ie(n,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Ce(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<ju+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===\`
\`&&(this._liveRegionLineCount++,this._liveRegionLineCount===ju+1&&(this._liveRegion.textContent+=Yl.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let s=this._terminal.buffer,r=s.lines.length.toString();for(let n=e;n<=t;n++){let o=s.lines.get(s.ydisp+n),a=[],h=(o==null?void 0:o.translateToString(true,void 0,void 0,a))||"",l=(s.ydisp+n+1).toString(),c=this._rowElements[n];c&&(h.length===0?(c.textContent=" ",this._rowColumns.set(c,[0,1])):(c.textContent=h,this._rowColumns.set(c,a)),c.setAttribute("aria-posinset",l),c.setAttribute("aria-setsize",r),this._alignRowWidth(c))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let s=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2],n=s.getAttribute("aria-posinset"),o=t===0?"1":\`\${this._terminal.buffer.lines.length}\`;if(n===o||e.relatedTarget!==r)return;let a,h;if(t===0?(a=s,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(a=this._rowElements.shift(),h=s,this._rowContainer.removeChild(a)),a.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let l=this._createAccessibilityTreeNode();this._rowElements.unshift(l),this._rowContainer.insertAdjacentElement("afterbegin",l)}else{let l=this._createAccessibilityTreeNode();this._rowElements.push(l),this._rowContainer.appendChild(l)}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(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},s={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(s.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===s.node&&t.offset>s.offset)&&([t,s]=[s,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(s.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(s={node:r,offset:((h=r.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(s.node))return;let n=({node:l,offset:c})=>{let d=l instanceof Text?l.parentNode:l,u=parseInt(d==null?void 0:d.getAttribute("aria-posinset"),10)-1;if(isNaN(u))return console.warn("row is invalid. Race condition?"),null;let f=this._rowColumns.get(d);if(!f)return console.warn("columns is null. Race condition?"),null;let p=c<f.length?f[c]:f.slice(-1)[0]+1;return p>=this._terminal.cols&&(++u,p=0),{row:u,column:p}},o=n(t),a=n(s);if(!(!o||!a)){if(o.row>a.row||o.row===a.row&&o.column>=a.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(a.row-o.row)*this._terminal.cols-o.column+a.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)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<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=\`\${this._renderService.dimensions.css.cell.height}px\`}_alignRowWidth(e){var n,o;e.style. Line truncated
\`,e)}paste(i){this._core.paste(i)}refresh(i,e){this._verifyIntegers(i,e),this._core.refresh(i,e)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(i){this._addonManager.loadAddon(this,i)}static get strings(){return{get promptLabel(){return Gl.get()},set promptLabel(i){Gl.set(i)},get tooMuchOutput(){return Yl.get()},set tooMuchOutput(i){Yl.set(i)}}}_verifyIntegers(...i){for(ai of i)if(ai===1/0||isNaN(ai)||ai%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...i){for(ai of i)if(ai&&(ai===1/0||isNaN(ai)||ai%1!==0||ai<0))throw new Error("This API only accepts positive integers")}};function U(i,e,t,s){return new(t||(t=Promise))(function(r,n){function o(l){try{h(s.next(l))}catch(c){n(c)}}function a(l){try{h(s.throw(l))}catch(c){n(c)}}function h(l){var c;l.done?r(l.value):(c=l.value,c instanceof t?c:new t(function(d){d(c)})).then(o,a)}h((s=s.apply(i,e||[])).next())})}function Q5(i){var e="function"==typeof Symbol&&Symbol.iterator,t=e&&i[e],s=0;if(t)return t.call(i);if(i&&"number"==typeof i.length)return{next:function(){return i&&s>=i.length&&(i=void 0),{value:i&&i[s++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function hg(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,t=i[Symbol.asyncIterator];return t?t.call(i):(i=Q5(i),e={},s("next"),s("throw"),s("return"),e[Symbol.asyncIterator]=function(){return this},e);function s(r){e[r]=i[r]&&function(n){return new Promise(function(o,a){(function(h,l,c,d){Promise.resolve(d).then(function(u){h({value:u,done:c})},l)})(o,a,(n=i[r](n)).done,n.value)})}}}function yr(i){let e=i.length;for(;--e>=0;)i[e]=0}const dc=256;const cg=286;const sn=30;const rn=15;const Mh=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);const ko=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);const eS=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);const Gu=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);const Bi=new Array(576);yr(Bi);const nn=new Array(60);yr(nn);const _n=new Array(512);yr(_n);const on=new Array(256);yr(on);const uc=new Array(29);yr(uc);const Wo=new Array(sn);function rl(i,e,t,s,r){this.static_tree=i,this.extra_bits=e,this.extra_base=t,this.elems=s,this.max_length=r,this.has_stree=i&&i.length}let Yu;let Xu;let Zu;function nl(i,e){this.dyn_tree=i,this.max_code=0,this.stat_desc=e}yr(Wo);const dg=i=>i<256?_n[i]:_n[256+(i>>>7)];const vn=(i,e)=>{i.pending_buf[i.pending++]=255&e,i.pending_buf[i.pending++]=e>>>8&255};const Lt=(i,e,t)=>{i.bi_valid>16-t?(i.bi_buf|=e<<i.bi_valid&65535,vn(i,i.bi_buf),i.bi_buf=e>>16-i.bi_valid,i.bi_valid+=t-16):(i.bi_buf|=e<<i.bi_valid&65535,i.bi_valid+=t)};const pi=(i,e,t)=>{Lt(i,t[2*e],t[2*e+1])};const ug=(i,e)=>{let t=0;do{t|=1&i,i>>>=1,t<<=1}while(--e>0);return t>>>1};const fg=(i,e,t)=>{const s=new Array(16);let r,n,o=0;for(r=1;r<=rn;r++)o=o+t[r-1]<<1,s[r]=o;for(n=0;n<=e;n++){let a=i[2*n+1];0!==a&&(i[2*n]=ug(s[a]++,a))}};const pg=i=>{let e;for(e=0;e<cg;e++)i.dyn_ltree[2*e]=0;for(e=0;e<sn;e++)i.dyn_dtree[2*e]=0;for(e=0;e<19;e++)i.bl_tree[2*e]=0;i.dyn_ltree[512]=1,i.opt_len=i.static_len=0,i.sym_next=i.matches=0};const mg=i=>{i.bi_valid>8?vn(i,i.bi_buf):i.bi_valid>0&&(i.pending_buf[i.pending++]=i.bi_buf),i.bi_buf=0,i.bi_valid=0};const Ju=(i,e,t,s)=>{const r=2*e,n=2*t;return i[r]<i[n]||i[r]===i[n]&&s[e]<=s[t]};const ol=(i,e,t)=>{const s=i.heap[t];let r=t<<1;for(;r<=i.heap_len&&(r<i.heap_len&&Ju(e,i.heap[r+1],i.heap[r],i.depth)&&r++,!Ju(e,s,i.heap[r],i.depth));)i.heap[t]=i.heap[r],t=r,r<<=1;i.heap[t]=s};const Qu=(i,e,t)=>{let s,r,n,o,a=0;if(0!==i.sym_next)do{s=255&i.pending_buf[i.sym_buf+a++],s+=(255&i.pending_buf[i.sym_buf+a++])<<8,r=i.pending_buf[i.sym_buf+a++],0===s?pi(i,r,e):(n=on[r],pi(i,n+dc+1,e),o=Mh[n],0!==o&&(r-=uc[n],Lt(i,r,o)),s--,n=dg(s),pi(i,n,t),o=ko[n],0!==o&&(s-=Wo[n],Lt(i,s,o)))}while(a<i.sym_next);pi(i,256,e)};const al=(i,e)=>{const t=e.dyn_tree,s=e.stat_desc.static_tree,r=e.stat_desc.has_stree,n=e.stat_desc.elems;let o,a,h,l=-1;for(i.heap_len=0,i.heap_max=573,o=0;o<n;o++)0!==t[2*o]?(i.heap[++i.heap_len]=l=o,i.depth[o]=0):t[2*o+1]=0;for(;i.heap_len<2;)h=i.heap[++i.heap_len]=l<2?++l:0,t[2*h]=1,i.depth[h]=0,i.opt_len--,r&&(i.static_len-=s[2*h+1]);for(e.max_code=l,o=i.heap_len>>1;o>=1;o--)ol(i,t,o);h=n;do{o=i.heap[1],i.heap[1]=i.heap[i.heap_len--],ol(i,t,1),a=i.heap[1],i.heap[--i.heap_max]=o,i.heap[--i.heap_max]=a,t[2*h]=t[2*o]+t[2*a],i.depth[h]=(i.depth[o]>=i.depth[a]?i.depth[o]:i.depth[a])+1,t[2*o+1]=t[2*a+1]=h,i.heap[1]=h++,ol(i,t,1)}while(i.heap_len>=2);i.heap[--i.heap_max]=i.heap[1],((c,d)=>{const u=d.dyn_tree,f=d.max_code,p=d.stat_desc.static_tree,b=d.stat_desc.has_stree,v=d.stat_desc.extra_bits,R=d.stat_desc.extra_base,L=d.stat_desc.max_length;let A,g,E,k,D,N,z=0;for(k=0;k<=rn;k++)c.bl_count[k]=0;for(u[2*c.heap[c.heap_max]+1]=0,A=c.heap_max+1;A<573;A++)g=c.heap[A],k=u[2*u[2*g+1]+1]+1,k>L&&(k Line truncated
\`),this.writer(r)})}recvData(e,t,s){return U(this,void 0,void 0,function*(){return yield Promise.race([new Promise((r,n)=>setTimeout(()=>{this.cleanTimeoutInMilliseconds=3e3,n(new Z("Receive data timeout"))},s)),(()=>U(this,void 0,void 0,function*(){if(!e)return yield this.recvBinary("DATA");const r=yield this.recvInteger("DATA");return function(n,o){if(!o.length)return n;const a=new Uint8Array(n.length);let h=0;for(let l=0;l<n.length;l++){let c=-1;if(l<n.length-1){for(let d=0;d<o.length;d++)if(n[l]==o[d][1]&&n[l+1]==o[d][2]){c=d;break}}c<0?a[h++]=n[l]:(a[h++]=o[c][0],l++)}return a.subarray(0,h)}(yield this.buffer.readBinary(r),t)}))()])})}sendAction(e,t){return U(this,void 0,void 0,function*(){const s={lang:"js",confirm:e,version:"1.1.6",support_dir:true};(this.isWindowsShell||t)&&(s.binary=false,s.newline="!\\n"),t&&(this.remoteIsWindows=true,this.protocolNewline="!\\n"),yield this.sendString("ACT",JSON.stringify(s))})}recvAction(){return U(this,void 0,void 0,function*(){const e=yield this.recvString("ACT",true),t=JSON.parse(e);return t.newline&&(this.protocolNewline=t.newline),t})}sendConfig(e,t,s,r){return U(this,void 0,void 0,function*(){const n={lang:"js"};e.quiet&&(n.quiet=true),e.binary&&(n.binary=true,n.escape_chars=t),e.directory&&(n.directory=true),e.bufsize&&(n.bufsize=e.bufsize),e.timeout&&(n.timeout=e.timeout),e.overwrite&&(n.overwrite=true),s==t3&&(n.tmux_output_junk=true),r>0&&(n.tmux_pane_width=r);let o=JSON.stringify(n);o=o.replace(/[\\u007F-\\uFFFF]/g,function(a){return"\\\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}),this.transferConfig=n,yield this.sendString("CFG",o)})}recvConfig(){return U(this,void 0,void 0,function*(){const e=yield this.recvString("CFG",true);return this.transferConfig=JSON.parse(e),this.tmuxOutputJunk=true===this.transferConfig.tmux_output_junk,this.transferConfig})}clientExit(e){return U(this,void 0,void 0,function*(){yield this.sendString("EXIT",e)})}recvExit(){return U(this,void 0,void 0,function*(){return this.recvString("EXIT")})}serverExit(e){return U(this,void 0,void 0,function*(){yield this.cleanInput(500),yield function(){return U(this,void 0,void 0,function*(){})}(),this.isWindowsShell?(e=e.replace(/\\n/g,"\\r\\n"),process.stdout.write("\\x1B[H\\x1B[2J\\x1B[?1049l")):process.stdout.write("\\x1B8\\x1B[0J"),process.stdout.write(e),process.stdout.write("\\r\\n"),process.stdout.write("\\x1B[?25h"),this.transferConfig.tmux_output_junk&&(yield function(){return U(this,void 0,void 0,function*(){const t=require("util").promisify(require("child_process").exec);yield t("tmux refresh-client")})}())})}deleteCreatedFiles(){return U(this,void 0,void 0,function*(){const e=[];for(const t of this.createdFiles){const s=yield t.deleteFile();s&&e.push(s)}return e})}clientError(e){return U(this,void 0,void 0,function*(){yield this.cleanInput(this.cleanTimeoutInMilliseconds);const t=Z.getErrorMessage(e);let s=true;if(e instanceof Z){if(s=e.isTraceBack(),e.isRemoteExit())return;if(e.isRemoteFail())return void(s&&console.log(t))}yield this.sendString(s?"FAIL":"fail",t),s&&console.log(t)})}serverError(e){return U(this,void 0,void 0,function*(){yield this.cleanInput(this.cleanTimeoutInMilliseconds);const t=Z.getErrorMessage(e);let s=true;if(e instanceof Z){if(e.isStopAndDelete()){const r=yield this.deleteCreatedFiles();if(r&&r.length)return void(yield this.serverExit([e.message+":"].concat(r).join("\\r\\n- ")))}if(s=e.isTraceBack(),e.isRemoteExit()||e.isRemoteFail())return void(yield this.serverExit(t))}yield this.sendString(s?"FAIL":"fail",t),yield this.serverExit(t)})}sendFileNum(e,t){return U(this,void 0,void 0,function*(){yield this.sendInteger("NUM",e),yield this.checkInteger(e),t&&t.onNum(e)})}sendFileName(e,t,s){return U(this,void 0,void 0,function*(){const r=e.getRelPath(),n=r[r.length-1];if(t){const a={path_id:e.getPathId(),path_name:r,is_dir:e.isDir()};yield this.sendString("NAME",JSON.stringify(a))}else yield this.sendString("NAME",n);const o=yield this.recvString("SUCC");return s&&s.onName(n),o})}sendFileSize(e,t){return U(this,void 0,void 0,function*(){yield this.sendInteger("SIZE",e),yield this.checkInteger(e),t&&t.onSize(e)})}sendFileData(e,t,s,r,n,o){return U(this,void 0,void 0,function*(){let a=0;o&&o.onStep(a);let h=1024,l=new ArrayBuffer(h);const c=new wn;for(;a<t;){const d=Date.now(),u=yield e.readFile(l);yield this.sendData(u,s,r),c.appendByteArray(u),yield this.checkInteger(u.length),a+=u.length,o&&o.onStep(a);const f=Date.now()-d;u.length==h&&f<500&&h<n?(h=Math.min(2*h,n),l=new ArrayBuffer(h)):f>=2e3&&h>1024&&(h=1024,l=new ArrayBuffer(h)),f>this.maxChunkTimeInMilliseconds&&(this.maxChunkTimeInMilliseconds=f)}return new Uint8Array(c.end(true).buffer)})}sendFileMD5(e,t){return U(this,void 0,void 0,function*(){yield this.sendBinary("MD5",e),yield this.checkBinary(e),t&&t.onDone()})}sendFiles(e,t){return U(this,void 0,void 0,function*(){this.openedFiles.push(...e);const s=true===this.transferConfig.binary,r=true===this.transferConfig.directory,n=this.t Line truncated
\`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(e){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame(()=>this._refresh())),dc&&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),s=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!s||!r||!t?false:this._areCoordsInSelection(t,s,r)}isCellInSelection(e,t){let s=this._model.finalSelectionStart,r=this._model.finalSelectionEnd;return!s||!r?false:this._areCoordsInSelection([e,t],s,r)}_areCoordsInSelection(e,t,s){return e[1]>t[1]&&e[1]<s[1]||t[1]===s[1]&&e[1]===t[1]&&e[0]>=t[0]&&e[0]<s[0]||t[1]<s[1]&&e[1]===s[1]&&e[0]<s[0]||t[1]<s[1]&&e[1]===t[1]&&e[0]>=t[0]}_selectWordAtCursor(e,t){var n,o;let s=(o=(n=this._linkifier.currentLink)==null?void 0:n.link)==null?void 0:o.range;if(s)return this._model.selectionStart=[s.start.x-1,s.start.y-1],this._model.selectionStartLength=Cu(s,this._bufferService.cols),this._model.selectionEnd=void 0,true;let r=this._getMouseBufferCoords(e);return r?(this._selectWordAt(r,t),this._model.selectionEnd=void 0,true):false}selectAll(){this._model.isSelectAllActive=true,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,true);if(t)return t[0]--,t[1]--,t[1]+=this._bufferService.buffer.ydisp,t}_getMouseEventScrollAmount(e){let t=cc(this._coreBrowserService.window,e,this._screenElement)[1],s=this._renderService.dimensions.css.canvas.height;return t>=0&&t<=s?0:(t>s&&(t-=s),t=Math.min(Math.max(t,-Qa),Qa),t/=Qa,t/Math.abs(t)+Math.round(t*(p5-1)))}shouldForceSelection(e){return Ho?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(true)}}_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(),m5)}_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=false,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,true)&&(this._activeSelectionMode=1)}_handleTripleClick(e){let t=this._getMouseBufferCoords(e);t&&(this._activeSelectionMode=2,this._selectLineAt(t[1]))}shouldColumnSelect(e){return e.altKey&&!(Ho&&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){this.refresh(true);return}this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._bufferService.cols:this._activeSelectionMode===1&&this._selectToWor Line truncated
\`))),this._register(this._terminal.onA11yTab(o=>this._handleTab(o))),this._register(this._terminal.onKey(o=>this._handleKey(o.key))),this._register(this._terminal.onBlur(()=>this._clearLiveRegion())),this._register(this._renderService.onDimensionsChange(()=>this._refreshRowsDimensions())),this._register(ie(n,"selectionchange",()=>this._handleSelectionChange())),this._register(this._coreBrowserService.onDprChange(()=>this._refreshRowsDimensions())),this._refreshRowsDimensions(),this._refreshRows(),this._register(Ce(()=>{this._accessibilityContainer.remove(),this._rowElements.length=0}))}_handleTab(e){for(let t=0;t<e;t++)this._handleChar(" ")}_handleChar(e){this._liveRegionLineCount<Vu+1&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==e&&(this._charsToAnnounce+=e):this._charsToAnnounce+=e,e===\`
\`&&(this._liveRegionLineCount++,this._liveRegionLineCount===Vu+1&&(this._liveRegion.textContent+=Xl.get())))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(e){this._clearLiveRegion(),new RegExp("\\\\p{Control}","u").test(e)||this._charsToConsume.push(e)}_refreshRows(e,t){this._liveRegionDebouncer.refresh(e,t,this._terminal.rows)}_renderRows(e,t){let s=this._terminal.buffer,r=s.lines.length.toString();for(let n=e;n<=t;n++){let o=s.lines.get(s.ydisp+n),a=[],h=(o==null?void 0:o.translateToString(true,void 0,void 0,a))||"",l=(s.ydisp+n+1).toString(),c=this._rowElements[n];c&&(h.length===0?(c.textContent=" ",this._rowColumns.set(c,[0,1])):(c.textContent=h,this._rowColumns.set(c,a)),c.setAttribute("aria-posinset",l),c.setAttribute("aria-setsize",r),this._alignRowWidth(c))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(e,t){let s=e.target,r=this._rowElements[t===0?1:this._rowElements.length-2],n=s.getAttribute("aria-posinset"),o=t===0?"1":\`\${this._terminal.buffer.lines.length}\`;if(n===o||e.relatedTarget!==r)return;let a,h;if(t===0?(a=s,h=this._rowElements.pop(),this._rowContainer.removeChild(h)):(a=this._rowElements.shift(),h=s,this._rowContainer.removeChild(a)),a.removeEventListener("focus",this._topBoundaryFocusListener),h.removeEventListener("focus",this._bottomBoundaryFocusListener),t===0){let l=this._createAccessibilityTreeNode();this._rowElements.unshift(l),this._rowContainer.insertAdjacentElement("afterbegin",l)}else{let l=this._createAccessibilityTreeNode();this._rowElements.push(l),this._rowContainer.appendChild(l)}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(){var h;if(this._rowElements.length===0)return;let e=this._coreBrowserService.mainDocument.getSelection();if(!e)return;if(e.isCollapsed){this._rowContainer.contains(e.anchorNode)&&this._terminal.clearSelection();return}if(!e.anchorNode||!e.focusNode){console.error("anchorNode and/or focusNode are null");return}let t={node:e.anchorNode,offset:e.anchorOffset},s={node:e.focusNode,offset:e.focusOffset};if((t.node.compareDocumentPosition(s.node)&Node.DOCUMENT_POSITION_PRECEDING||t.node===s.node&&t.offset>s.offset)&&([t,s]=[s,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(s.node.compareDocumentPosition(r)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(s={node:r,offset:((h=r.textContent)==null?void 0:h.length)??0}),!this._rowContainer.contains(s.node))return;let n=({node:l,offset:c})=>{let d=l instanceof Text?l.parentNode:l,u=parseInt(d==null?void 0:d.getAttribute("aria-posinset"),10)-1;if(isNaN(u))return console.warn("row is invalid. Race condition?"),null;let f=this._rowColumns.get(d);if(!f)return console.warn("columns is null. Race condition?"),null;let p=c<f.length?f[c]:f.slice(-1)[0]+1;return p>=this._terminal.cols&&(++u,p=0),{row:u,column:p}},o=n(t),a=n(s);if(!(!o||!a)){if(o.row>a.row||o.row===a.row&&o.column>=a.column)throw new Error("invalid range");this._terminal.select(o.column,o.row,(a.row-o.row)*this._terminal.cols-o.column+a.column)}}_handleResize(e){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let t=this._rowContainer.children.length;t<this._terminal.rows;t++)this._rowElements[t]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[t]);for(;this._rowElements.length>e;)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<this._terminal.rows;e++)this._refreshRowDimensions(this._rowElements[e]),this._alignRowWidth(this._rowElements[e])}}_refreshRowDimensions(e){e.style.height=\`\${this._renderService.dimensions.css.cell.height}px\`}_alignRowWidth(e){var n,o;e.style. Line truncated
\`,e)}paste(i){this._core.paste(i)}refresh(i,e){this._verifyIntegers(i,e),this._core.refresh(i,e)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(i){this._addonManager.loadAddon(this,i)}static get strings(){return{get promptLabel(){return Yl.get()},set promptLabel(i){Yl.set(i)},get tooMuchOutput(){return Xl.get()},set tooMuchOutput(i){Xl.set(i)}}}_verifyIntegers(...i){for(li of i)if(li===1/0||isNaN(li)||li%1!==0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...i){for(li of i)if(li&&(li===1/0||isNaN(li)||li%1!==0||li<0))throw new Error("This API only accepts positive integers")}};function U(i,e,t,s){return new(t||(t=Promise))(function(r,n){function o(l){try{h(s.next(l))}catch(c){n(c)}}function a(l){try{h(s.throw(l))}catch(c){n(c)}}function h(l){var c;l.done?r(l.value):(c=l.value,c instanceof t?c:new t(function(d){d(c)})).then(o,a)}h((s=s.apply(i,e||[])).next())})}function mS(i){var e="function"==typeof Symbol&&Symbol.iterator,t=e&&i[e],s=0;if(t)return t.call(i);if(i&&"number"==typeof i.length)return{next:function(){return i&&s>=i.length&&(i=void 0),{value:i&&i[s++],done:!i}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function pg(i){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e,t=i[Symbol.asyncIterator];return t?t.call(i):(i=mS(i),e={},s("next"),s("throw"),s("return"),e[Symbol.asyncIterator]=function(){return this},e);function s(r){e[r]=i[r]&&function(n){return new Promise(function(o,a){(function(h,l,c,d){Promise.resolve(d).then(function(u){h({value:u,done:c})},l)})(o,a,(n=i[r](n)).done,n.value)})}}}function yr(i){let e=i.length;for(;--e>=0;)i[e]=0}const uc=256;const mg=286;const sn=30;const rn=15;const Bh=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]);const Eo=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]);const gS=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]);const Yu=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);const Bi=new Array(576);yr(Bi);const nn=new Array(60);yr(nn);const _n=new Array(512);yr(_n);const on=new Array(256);yr(on);const fc=new Array(29);yr(fc);const qo=new Array(sn);function ol(i,e,t,s,r){this.static_tree=i,this.extra_bits=e,this.extra_base=t,this.elems=s,this.max_length=r,this.has_stree=i&&i.length}let Xu;let Zu;let Ju;function al(i,e){this.dyn_tree=i,this.max_code=0,this.stat_desc=e}yr(qo);const gg=i=>i<256?_n[i]:_n[256+(i>>>7)];const vn=(i,e)=>{i.pending_buf[i.pending++]=255&e,i.pending_buf[i.pending++]=e>>>8&255};const Lt=(i,e,t)=>{i.bi_valid>16-t?(i.bi_buf|=e<<i.bi_valid&65535,vn(i,i.bi_buf),i.bi_buf=e>>16-i.bi_valid,i.bi_valid+=t-16):(i.bi_buf|=e<<i.bi_valid&65535,i.bi_valid+=t)};const mi=(i,e,t)=>{Lt(i,t[2*e],t[2*e+1])};const _g=(i,e)=>{let t=0;do{t|=1&i,i>>>=1,t<<=1}while(--e>0);return t>>>1};const vg=(i,e,t)=>{const s=new Array(16);let r,n,o=0;for(r=1;r<=rn;r++)o=o+t[r-1]<<1,s[r]=o;for(n=0;n<=e;n++){let a=i[2*n+1];0!==a&&(i[2*n]=_g(s[a]++,a))}};const bg=i=>{let e;for(e=0;e<mg;e++)i.dyn_ltree[2*e]=0;for(e=0;e<sn;e++)i.dyn_dtree[2*e]=0;for(e=0;e<19;e++)i.bl_tree[2*e]=0;i.dyn_ltree[512]=1,i.opt_len=i.static_len=0,i.sym_next=i.matches=0};const yg=i=>{i.bi_valid>8?vn(i,i.bi_buf):i.bi_valid>0&&(i.pending_buf[i.pending++]=i.bi_buf),i.bi_buf=0,i.bi_valid=0};const Qu=(i,e,t,s)=>{const r=2*e,n=2*t;return i[r]<i[n]||i[r]===i[n]&&s[e]<=s[t]};const ll=(i,e,t)=>{const s=i.heap[t];let r=t<<1;for(;r<=i.heap_len&&(r<i.heap_len&&Qu(e,i.heap[r+1],i.heap[r],i.depth)&&r++,!Qu(e,s,i.heap[r],i.depth));)i.heap[t]=i.heap[r],t=r,r<<=1;i.heap[t]=s};const ef=(i,e,t)=>{let s,r,n,o,a=0;if(0!==i.sym_next)do{s=255&i.pending_buf[i.sym_buf+a++],s+=(255&i.pending_buf[i.sym_buf+a++])<<8,r=i.pending_buf[i.sym_buf+a++],0===s?mi(i,r,e):(n=on[r],mi(i,n+uc+1,e),o=Bh[n],0!==o&&(r-=fc[n],Lt(i,r,o)),s--,n=gg(s),mi(i,n,t),o=Eo[n],0!==o&&(s-=qo[n],Lt(i,s,o)))}while(a<i.sym_next);mi(i,256,e)};const hl=(i,e)=>{const t=e.dyn_tree,s=e.stat_desc.static_tree,r=e.stat_desc.has_stree,n=e.stat_desc.elems;let o,a,h,l=-1;for(i.heap_len=0,i.heap_max=573,o=0;o<n;o++)0!==t[2*o]?(i.heap[++i.heap_len]=l=o,i.depth[o]=0):t[2*o+1]=0;for(;i.heap_len<2;)h=i.heap[++i.heap_len]=l<2?++l:0,t[2*h]=1,i.depth[h]=0,i.opt_len--,r&&(i.static_len-=s[2*h+1]);for(e.max_code=l,o=i.heap_len>>1;o>=1;o--)ll(i,t,o);h=n;do{o=i.heap[1],i.heap[1]=i.heap[i.heap_len--],ll(i,t,1),a=i.heap[1],i.heap[--i.heap_max]=o,i.heap[--i.heap_max]=a,t[2*h]=t[2*o]+t[2*a],i.depth[h]=(i.depth[o]>=i.depth[a]?i.depth[o]:i.depth[a])+1,t[2*o+1]=t[2*a+1]=h,i.heap[1]=h++,ll(i,t,1)}while(i.heap_len>=2);i.heap[--i.heap_max]=i.heap[1],((c,d)=>{const u=d.dyn_tree,f=d.max_code,p=d.stat_desc.static_tree,b=d.stat_desc.has_stree,v=d.stat_desc.extra_bits,R=d.stat_desc.extra_base,L=d.stat_desc.max_length;let A,g,E,k,D,N,z=0;for(k=0;k<=rn;k++)c.bl_count[k]=0;for(u[2*c.heap[c.heap_max]+1]=0,A=c.heap_max+1;A<573;A++)g=c.heap[A],k=u[2*u[2*g+1]+1]+1,k>L&&(k Line truncated
\`),this.writer(r)})}recvData(e,t,s){return U(this,void 0,void 0,function*(){return yield Promise.race([new Promise((r,n)=>setTimeout(()=>{this.cleanTimeoutInMilliseconds=3e3,n(new Z("Receive data timeout"))},s)),(()=>U(this,void 0,void 0,function*(){if(!e)return yield this.recvBinary("DATA");const r=yield this.recvInteger("DATA");return function(n,o){if(!o.length)return n;const a=new Uint8Array(n.length);let h=0;for(let l=0;l<n.length;l++){let c=-1;if(l<n.length-1){for(let d=0;d<o.length;d++)if(n[l]==o[d][1]&&n[l+1]==o[d][2]){c=d;break}}c<0?a[h++]=n[l]:(a[h++]=o[c][0],l++)}return a.subarray(0,h)}(yield this.buffer.readBinary(r),t)}))()])})}sendAction(e,t){return U(this,void 0,void 0,function*(){const s={lang:"js",confirm:e,version:"1.1.6",support_dir:true};(this.isWindowsShell||t)&&(s.binary=false,s.newline="!\\n"),t&&(this.remoteIsWindows=true,this.protocolNewline="!\\n"),yield this.sendString("ACT",JSON.stringify(s))})}recvAction(){return U(this,void 0,void 0,function*(){const e=yield this.recvString("ACT",true),t=JSON.parse(e);return t.newline&&(this.protocolNewline=t.newline),t})}sendConfig(e,t,s,r){return U(this,void 0,void 0,function*(){const n={lang:"js"};e.quiet&&(n.quiet=true),e.binary&&(n.binary=true,n.escape_chars=t),e.directory&&(n.directory=true),e.bufsize&&(n.bufsize=e.bufsize),e.timeout&&(n.timeout=e.timeout),e.overwrite&&(n.overwrite=true),s==_3&&(n.tmux_output_junk=true),r>0&&(n.tmux_pane_width=r);let o=JSON.stringify(n);o=o.replace(/[\\u007F-\\uFFFF]/g,function(a){return"\\\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)}),this.transferConfig=n,yield this.sendString("CFG",o)})}recvConfig(){return U(this,void 0,void 0,function*(){const e=yield this.recvString("CFG",true);return this.transferConfig=JSON.parse(e),this.tmuxOutputJunk=true===this.transferConfig.tmux_output_junk,this.transferConfig})}clientExit(e){return U(this,void 0,void 0,function*(){yield this.sendString("EXIT",e)})}recvExit(){return U(this,void 0,void 0,function*(){return this.recvString("EXIT")})}serverExit(e){return U(this,void 0,void 0,function*(){yield this.cleanInput(500),yield function(){return U(this,void 0,void 0,function*(){})}(),this.isWindowsShell?(e=e.replace(/\\n/g,"\\r\\n"),process.stdout.write("\\x1B[H\\x1B[2J\\x1B[?1049l")):process.stdout.write("\\x1B8\\x1B[0J"),process.stdout.write(e),process.stdout.write("\\r\\n"),process.stdout.write("\\x1B[?25h"),this.transferConfig.tmux_output_junk&&(yield function(){return U(this,void 0,void 0,function*(){const t=require("util").promisify(require("child_process").exec);yield t("tmux refresh-client")})}())})}deleteCreatedFiles(){return U(this,void 0,void 0,function*(){const e=[];for(const t of this.createdFiles){const s=yield t.deleteFile();s&&e.push(s)}return e})}clientError(e){return U(this,void 0,void 0,function*(){yield this.cleanInput(this.cleanTimeoutInMilliseconds);const t=Z.getErrorMessage(e);let s=true;if(e instanceof Z){if(s=e.isTraceBack(),e.isRemoteExit())return;if(e.isRemoteFail())return void(s&&console.log(t))}yield this.sendString(s?"FAIL":"fail",t),s&&console.log(t)})}serverError(e){return U(this,void 0,void 0,function*(){yield this.cleanInput(this.cleanTimeoutInMilliseconds);const t=Z.getErrorMessage(e);let s=true;if(e instanceof Z){if(e.isStopAndDelete()){const r=yield this.deleteCreatedFiles();if(r&&r.length)return void(yield this.serverExit([e.message+":"].concat(r).join("\\r\\n- ")))}if(s=e.isTraceBack(),e.isRemoteExit()||e.isRemoteFail())return void(yield this.serverExit(t))}yield this.sendString(s?"FAIL":"fail",t),yield this.serverExit(t)})}sendFileNum(e,t){return U(this,void 0,void 0,function*(){yield this.sendInteger("NUM",e),yield this.checkInteger(e),t&&t.onNum(e)})}sendFileName(e,t,s){return U(this,void 0,void 0,function*(){const r=e.getRelPath(),n=r[r.length-1];if(t){const a={path_id:e.getPathId(),path_name:r,is_dir:e.isDir()};yield this.sendString("NAME",JSON.stringify(a))}else yield this.sendString("NAME",n);const o=yield this.recvString("SUCC");return s&&s.onName(n),o})}sendFileSize(e,t){return U(this,void 0,void 0,function*(){yield this.sendInteger("SIZE",e),yield this.checkInteger(e),t&&t.onSize(e)})}sendFileData(e,t,s,r,n,o){return U(this,void 0,void 0,function*(){let a=0;o&&o.onStep(a);let h=1024,l=new ArrayBuffer(h);const c=new wn;for(;a<t;){const d=Date.now(),u=yield e.readFile(l);yield this.sendData(u,s,r),c.appendByteArray(u),yield this.checkInteger(u.length),a+=u.length,o&&o.onStep(a);const f=Date.now()-d;u.length==h&&f<500&&h<n?(h=Math.min(2*h,n),l=new ArrayBuffer(h)):f>=2e3&&h>1024&&(h=1024,l=new ArrayBuffer(h)),f>this.maxChunkTimeInMilliseconds&&(this.maxChunkTimeInMilliseconds=f)}return new Uint8Array(c.end(true).buffer)})}sendFileMD5(e,t){return U(this,void 0,void 0,function*(){yield this.sendBinary("MD5",e),yield this.checkBinary(e),t&&t.onDone()})}sendFiles(e,t){return U(this,void 0,void 0,function*(){this.openedFiles.push(...e);const s=true===this.transferConfig.binary,r=true===this.transferConfig.directory,n=this.t Line truncated
\\x1B[1;33m║\${e}║\\x1B[0m\\r
\\x1B[1;33m╚══════════════════════════════════╝\\x1B[0m\\r
\\r
\`)}stopHeartbeat(){if(this.heartbeatInterval){clearInterval(this.heartbeatInterval);this.heartbeatInterval=null}if(this.heartbeatResponseTimeout){clearTimeout(this.heartbeatResponseTimeout);this.heartbeatResponseTimeout=null}this.pendingHeartbeatId=null;this.lastPingTime=null}disposeConnectionDisposables(){for(const e of this.disposables)e.dispose();this.disposables=[]}clearReconnectTimeout(){if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);this.reconnectTimeout=null}}resetActiveConnection(){var t;(t=this.authChallengeDialog)==null?void 0:t.dismiss();this.stopHeartbeat();this.clearReconnectTimeout();this.disposeConnectionDisposables();const e=this.ws;this.ws=null;this.sftpAttachUrl=null;this.trzszFilter=null;this.sessionReady=false;this.cfLatency=null;this.cfColo=null;this.wsLatency=null;if(e&&e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING){e.close(1e3)}}hasReconnectStrategy(){if(this.resumeOnlyMode){return this.shareResumeSupported&&Boolean(this.activeSessionId&&this.activeResumeToken)&&(this.shareResumeDeadline===null||Date.now()<this.shareResumeDeadline)}return this.canReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&Boolean(this.lastConfig||this.reconnectWebSocketFactory||this.activeSessionId&&this.activeResumeToken)}async tryResumeSession(){if(!this.activeSessionId||!this.activeResumeToken)return false;try{const e=new URLSearchParams({session:this.activeSessionId,resume_token:this.activeResumeToken,cols:String(this.terminal.cols),rows:String(this.terminal.rows)});const t=await M1(this.activeSessionId);this.shareResumeChallengeMissing=!t&&Nh();if(t){e.set("did_nonce",t.nonce);e.set("did_ts",String(t.timestamp));e.set("did_sig",t.signature)}const s=window.location.protocol==="https:"?"wss:":"ws:";const r=new WebSocket(\`\${s}//\${window.location.host}/api/ssh?\${e.toString()}\`);r.binaryType="arraybuffer";this.resetActiveConnection();this.ws=r;this.setupWebSocketHandlers();return true}catch{this.activeSessionId=null;this.activeResumeToken=null;return false}}scheduleReconnect(){this.clearReconnectTimeout();this.reconnectAttempts++;if(this.resumeOnlyMode){this.scheduleShareResume();return}if(this.reconnectAttempts===1&&this.activeSessionId&&this.activeResumeToken){this.terminal.writeln(\`\\x1B[32m[+] \${m("terminal.reconnecting")}\\x1B[0m\`);void this.tryResumeSession().then(e=>{if(!e)this.scheduleFallbackReconnect()});return}this.scheduleFallbackReconnect()}scheduleShareResume(){if(this.shareSessionEndedByServer){this.finishShareResume();return}if(!this.hasReconnectStrategy()){this.finishShareResume();return}if(this.shareResumeDeadline===null){this.shareResumeDeadline=Date.now()+C1}const e=this.shareResumeDeadline-Date.now();if(e<=$3){this.finishShareResume();return}if(this.reconnectAttempts===1&&this.sessionRequiresDeviceSig&&this.shareResumeChallengeMissing){this.terminal.writeln(\`\\x1B[33m[!] \${m("terminal.shareResumeNoDeviceIdentity")}\\x1B[0m\`)}if(this.reconnectAttempts===2&&this.sessionRequiresDeviceSig&&!this.shareResumeChallengeMissing){this.terminal.writeln(\`\\x1B[33m[!] \${m("terminal.shareResumeEnvironmentHint")}\\x1B[0m\`)}const t=Math.min(1e3*2**Math.max(0,this.reconnectAttempts-1),3e4);const s=t>e;const r=Math.min(t,e);const n=Math.max(1,Math.round(r/1e3));if(s){this.terminal.writeln(\`\\x1B[33m[*] \${m("terminal.shareResumeFinalAttempt")}\\x1B[0m\`)}this.terminal.writeln(\`\\x1B[33m[*] \${m("terminal.resumingSession",{seconds:n,attempt:this.reconnectAttempts})}\\x1B[0m\`);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null;void this.tryResumeSession().then(o=>{if(!o)this.finishShareResume()})},r)}finishShareResume(){this.resumeOnlyMode=false;this.shareResumeDeadline=null;this.shareResumeChallengeMissing=false;this.sessionRequiresDeviceSig=false;this.activeSessionId=null;this.activeResumeToken=null;this.terminal.writeln(\`\\x1B[31m[!] \${m("terminal.shareResumeEnded")}\\x1B[0m\`)}scheduleFallbackReconnect(){this.clearReconnectTimeout();const e=Math.min(1e3*2**this.reconnectAttempts,3e4);this.terminal.writeln(\`\\x1B[33m[*] \${m("terminal.reconnectWait",{seconds:e/1e3,attempt:this.reconnectAttempts,max:this.maxReconnectAttempts})}\\x1B[0m\`);this.reconnectTimeout=setTimeout(async()=>{this.reconnectTimeout=null;if(this.lastConfig){this.terminal.writeln(\`\\x1B[32m[+] \${m("terminal.reconnecting")}\\x1B[0m\`);try{await this.connect(this.lastConfig,{resetDisplay:false})}catch{this.terminal.writeln(\`\\x1B[31m[!] \${m("terminal.reconnectFailed")}\\x1B[0m\`)}}else if(this.reconnectWebSocketFactory){this.terminal.writeln(\`\\x1B[32m[+] \${m("terminal.reconnecting")}\\x1B[0m\`);const t=this.reconnectWebSocketFactory;try{const s=await t();if(this.reconnectWebSocketFactory!==t||!this.canReconnect||this.reconnectAttempts>=this.maxReconnectAttempts){s.close(1e3);return}this.connectWithWebSocket(s,this.lastHostInfo??void 0,{resetDisplay:false,reconnectFactory:t})}catch{this.terminal.writeln(\`\\x1B[31m[!] \${m("terminal.reconnectFailed")}\\x1 Line truncated
\`)}stopHeartbeat(){if(this.heartbeatInterval){clearInterval(this.heartbeatInterval);this.heartbeatInterval=null}if(this.heartbeatResponseTimeout){clearTimeout(this.heartbeatResponseTimeout);this.heartbeatResponseTimeout=null}this.pendingHeartbeatId=null;this.lastPingTime=null}disposeConnectionDisposables(){for(const e of this.disposables)e.dispose();this.disposables=[]}clearReconnectTimeout(){if(this.reconnectTimeout){clearTimeout(this.reconnectTimeout);this.reconnectTimeout=null}}resetActiveConnection(){var t;(t=this.authChallengeDialog)==null?void 0:t.dismiss();this.stopHeartbeat();this.clearReconnectTimeout();this.disposeConnectionDisposables();const e=this.ws;this.ws=null;this.sftpAttachUrl=null;this.trzszFilter=null;this.sessionReady=false;this.cfLatency=null;this.cfColo=null;this.wsLatency=null;if(e&&e.readyState!==WebSocket.CLOSED&&e.readyState!==WebSocket.CLOSING){e.close(1e3)}}hasReconnectStrategy(){if(this.resumeOnlyMode){return this.shareResumeSupported&&Boolean(this.activeSessionId&&this.activeResumeToken)&&(this.shareResumeDeadline===null||Date.now()<this.shareResumeDeadline)}return this.canReconnect&&this.reconnectAttempts<this.maxReconnectAttempts&&Boolean(this.lastConfig||this.reconnectWebSocketFactory||this.activeSessionId&&this.activeResumeToken)}async tryResumeSession(){if(!this.activeSessionId||!this.activeResumeToken)return false;try{const e=new URLSearchParams({session:this.activeSessionId,resume_token:this.activeResumeToken,cols:String(this.terminal.cols),rows:String(this.terminal.rows)});const t=await V1(this.activeSessionId);this.shareResumeChallengeMissing=!t&&Hh();if(t){e.set("did_nonce",t.nonce);e.set("did_ts",String(t.timestamp));e.set("did_sig",t.signature)}const s=window.location.protocol==="https:"?"wss:":"ws:";const r=new WebSocket(\`\${s}//\${window.location.host}/api/ssh?\${e.toString()}\`);r.binaryType="arraybuffer";this.resetActiveConnection();this.ws=r;this.setupWebSocketHandlers();return true}catch{this.activeSessionId=null;this.activeResumeToken=null;return false}}scheduleReconnect(){this.clearReconnectTimeout();this.reconnectAttempts++;if(this.resumeOnlyMode){this.scheduleShareResume();return}if(this.reconnectAttempts===1&&this.activeSessionId&&this.activeResumeToken){this.terminal.writeln(\`\\x1B[32m[+] \${m("terminal.reconnecting")}\\x1B[0m\`);void this.tryResumeSession().then(e=>{if(!e)this.scheduleFallbackReconnect()});return}this.scheduleFallbackReconnect()}scheduleShareResume(){if(this.shareSessionEndedByServer){this.finishShareResume();return}if(!this.hasReconnectStrategy()){this.finishShareResume();return}if(this.shareResumeDeadline===null){this.shareResumeDeadline=Date.now()+N1}const e=this.shareResumeDeadline-Date.now();if(e<=J3){this.finishShareResume();return}if(this.reconnectAttempts===1&&this.sessionRequiresDeviceSig&&this.shareResumeChallengeMissing){this.terminal.writeln(\`\\x1B[33m[!] \${m("terminal.shareResumeNoDeviceIdentity")}\\x1B[0m\`)}if(this.reconnectAttempts===2&&this.sessionRequiresDeviceSig&&!this.shareResumeChallengeMissing){this.terminal.writeln(\`\\x1B[33m[!] \${m("terminal.shareResumeEnvironmentHint")}\\x1B[0m\`)}const t=Math.min(1e3*2**Math.max(0,this.reconnectAttempts-1),3e4);const s=t>e;const r=Math.min(t,e);const n=Math.max(1,Math.round(r/1e3));if(s){this.terminal.writeln(\`\\x1B[33m[*] \${m("terminal.shareResumeFinalAttempt")}\\x1B[0m\`)}this.terminal.writeln(\`\\x1B[33m[*] \${m("terminal.resumingSession",{seconds:n,attempt:this.reconnectAttempts})}\\x1B[0m\`);this.reconnectTimeout=setTimeout(()=>{this.reconnectTimeout=null;void this.tryResumeSession().then(o=>{if(!o)this.finishShareResume()})},r)}finishShareResume(){this.resumeOnlyMode=false;this.shareResumeDeadline=null;this.shareResumeChallengeMissing=false;this.sessionRequiresDeviceSig=false;this.activeSessionId=null;this.activeResumeToken=null;this.terminal.writeln(\`\\x1B[31m[!] \${m("terminal.shareResumeEnded")}\\x1B[0m\`)}scheduleFallbackReconnect(){this.clearReconnectTimeout();const e=Math.min(1e3*2**this.reconnectAttempts,3e4);this.terminal.writeln(\`\\x1B[33m[*] \${m("terminal.reconnectWait",{seconds:e/1e3,attempt:this.reconnectAttempts,max:this.maxReconnectAttempts})}\\x1B[0m\`);this.reconnectTimeout=setTimeout(async()=>{this.reconnectTimeout=null;if(this.lastConfig){this.terminal.writeln(\`\\x1B[32m[+] \${m("terminal.reconnecting")}\\x1B[0m\`);try{await this.connect(this.lastConfig,{resetDisplay:false})}catch{this.terminal.writeln(\`\\x1B[31m[!] \${m("terminal.reconnectFailed")}\\x1B[0m\`)}}else if(this.reconnectWebSocketFactory){this.terminal.writeln(\`\\x1B[32m[+] \${m("terminal.reconnecting")}\\x1B[0m\`);const t=this.reconnectWebSocketFactory;try{const s=await t();if(this.reconnectWebSocketFactory!==t||!this.canReconnect||this.reconnectAttempts>=this.maxReconnectAttempts){s.close(1e3);return}this.connectWithWebSocket(s,this.lastHostInfo??void 0,{resetDisplay:false,reconnectFactory:t})}catch{this.terminal.writeln(\`\\x1B[31m[!] \${m("terminal.reconnectFailed")}\\x1 Line truncated
</script>
<style>*,::before,::after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / 0.5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / 0.5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,::before,::after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}::before,::after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}input:where([type=text]),input:where(:not([type])),input:where([type=email]),input:where([type=url]),input:where([type=password]),input:where([type=number]),input:where([type=date]),input:where([type=datetimLine truncated
<style>*,::before,::after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / 0.5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / 0.5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }*,::before,::after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}::before,::after{--tw-content: ""}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]:where(:not([hidden=until-found])){display:none}input:where([type=text]),input:where(:not([type])),input:where([type=email]),input:where([type=url]),input:where([type=password]),input:where([type=number]),input:where([type=date]),input:where([type=datetimLine truncated
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
* Copyright (c) 2012-2013, Christopher Jeffrey (MIT License)
* https://github.com/chjj/term.js
@@ -928,8 +928,10 @@ WARNING: This link could potentially be dangerous\`)){let t=window.open();if(t){
<option value="standard-dark">Standard Dark</option>
<option value="standard-light">Standard Light</option>
<option value="cyberpunk">Cyberpunk</option>
<option value="glacier">Glacier · Soft</option>
<option value="apple">Apple · Soft</option>
<option value="gruvbox">Gruvbox · Dense</option>
<option value="crt">CRT Amber</option>
<option value="glass">Glass · Soft</option>
</select>
<button
data-theme-import
@@ -1531,8 +1533,10 @@ WARNING: This link could potentially be dangerous\`)){let t=window.open();if(t){
<option value="standard-dark">Standard Dark</option>
<option value="standard-light">Standard Light</option>
<option value="cyberpunk">Cyberpunk</option>
<option value="glacier">Glacier · Soft</option>
<option value="apple">Apple · Soft</option>
<option value="gruvbox">Gruvbox · Dense</option>
<option value="crt">CRT Amber</option>
<option value="glass">Glass · Soft</option>
</select>
<button
id="import-theme-btn"
@@ -1655,8 +1659,10 @@ WARNING: This link could potentially be dangerous\`)){let t=window.open();if(t){
<option value="standard-dark">Standard Dark</option>
<option value="standard-light">Standard Light</option>
<option value="cyberpunk">Cyberpunk</option>
<option value="glacier">Glacier · Soft</option>
<option value="apple">Apple · Soft</option>
<option value="gruvbox">Gruvbox · Dense</option>
<option value="crt">CRT Amber</option>
<option value="glass">Glass · Soft</option>
</select>
</label>
<button id="mobile-search-btn" type="button">
+2 -1
View File
@@ -12,6 +12,7 @@ tests/
├── worker/ # Worker 路由、安全、DNS、UserDB 与标签测试
├── agent-code-actions.test.ts # Agent 代码块复制/填入规则
├── agent-terminal-selection.test.ts # 终端选区附件和非授权安全边界
├── api-errors.test.ts # API 错误信息边界与状态码
├── auth-challenge-dialog.test.ts # RFC 4256 认证挑战对话框交互
├── clipboard.test.ts # Clipboard API 与旧版复制回退
├── frontend-ux.test.ts # 前端关键交互源码回归(标签栏/状态栏渲染等)
@@ -87,7 +88,7 @@ pnpm run verify
- SFTP 单选、Cmd/Ctrl 多选、Shift 连选和全选
- Agent 终端选区附件、问题组合和非授权安全边界
- 终端选区自动复制、指针取消和旧版复制回退
- i18n、主题、终端状态/文本、已知主机与片段本地存储
- i18n、Theme V3 主题(背景/效果/版式钳制、对比度与 schema)、终端状态/文本、已知主机与片段本地存储
- 构建可复现性、xterm 生产构建兼容和原生弹窗禁用
### 浏览器 E2E
+21 -3
View File
@@ -51,11 +51,11 @@ test('内置主题切换 UI 风格但保持服务器列表结构稳定', async (
await expect(card).toHaveCount(1);
await expect(grid).toHaveClass(/grid-cols-1/);
await selector.selectOption('glacier');
await selector.selectOption('apple');
await expect(page.locator('html')).toHaveAttribute('data-ui-style', 'soft');
await expect(page.locator('html')).toHaveAttribute('data-component-card', 'elevated');
await expect(card).toHaveCSS('border-radius', '15px');
await expect(terminalSelector).toHaveValue('glacier');
await expect(terminalSelector).toHaveValue('apple');
await selector.selectOption('gruvbox');
await expect(page.locator('html')).toHaveAttribute('data-ui-style', 'dense');
@@ -77,6 +77,24 @@ test('内置主题切换 UI 风格但保持服务器列表结构稳定', async (
'color',
'rgb(74, 246, 38)'
);
// V3:CRT 与 Glass 内置主题携带背景/效果/模糊配置
await selector.selectOption('crt');
await expect(page.locator('html')).toHaveAttribute('data-theme', 'crt');
await expect(page.locator('html')).toHaveAttribute('data-ui-style', 'cyberpunk');
await expect(page.locator('html')).toHaveAttribute('data-fx-scanline', 'on');
await expect(page.locator('html')).toHaveAttribute('data-fx-glow', 'on');
await expect(terminalSelector).toHaveValue('crt');
await selector.selectOption('glass');
await expect(page.locator('html')).toHaveAttribute('data-theme', 'glass');
await expect(page.locator('html')).toHaveAttribute('data-ui-blur', 'strong');
await expect(page.locator('html')).toHaveAttribute('data-bg-animation', 'drift');
await expect(page.locator('html')).toHaveAttribute('data-fx-glow', 'on');
await expect(card).toHaveCSS('border-radius', '21px');
expect(
await page.evaluate(() => getComputedStyle(document.body, '::before').backgroundImage)
).toContain('radial-gradient');
});
test('云端主题恢复不阻塞用户空间首屏,并避免覆盖加载期间的用户选择', async ({ page }) => {
@@ -140,7 +158,7 @@ test('终端四周留白按形状收窄并为圆角保留安全间距', async ({
await expect(terminalMain).toHaveCSS('padding', '7px');
await expect(terminalWrapper).toHaveCSS('border-radius', '9px');
await selector.selectOption('glacier');
await selector.selectOption('apple');
await expect(terminalMain).toHaveCSS('padding', '10px');
await expect(terminalWrapper).toHaveCSS('border-radius', '15px');
});
+142 -12
View File
@@ -4,6 +4,9 @@ import {
applyBuiltInTheme,
applyImportedTheme,
BUILT_IN_APPEARANCE,
BUILT_IN_BACKGROUND,
BUILT_IN_EFFECTS,
BUILT_IN_TYPOGRAPHY,
getActiveColorScheme,
getActiveTerminalTheme,
getActiveThemeAppearance,
@@ -11,6 +14,7 @@ import {
normalizeImportedTheme,
onColorSchemeChange,
onTerminalThemeChange,
resolveBackgroundCss,
resolveThemeAppearance,
THEME_SCHEMA_VERSION,
THEMES,
@@ -69,7 +73,7 @@ describe('Standard 内置主题', () => {
'brightWhite',
] as const;
for (const themeName of ['standard-dark', 'standard-light'] as const) {
for (const themeName of ['standard-dark', 'standard-light', 'apple', 'crt', 'glass'] as const) {
for (const key of ansiKeys) {
expect(THEMES[themeName][key]).toMatch(/^#[0-9a-f]{6}$/i);
}
@@ -77,7 +81,7 @@ describe('Standard 内置主题', () => {
});
it('主要文本、次要文本和强调色达到普通文字 4.5:1 对比度', () => {
for (const themeName of ['standard-dark', 'standard-light'] as const) {
for (const themeName of ['standard-dark', 'standard-light', 'apple', 'crt', 'glass'] as const) {
const ui = UI_THEMES[themeName];
for (const foreground of ['--text', '--text-muted', '--text-dim', '--accent', '--error']) {
expect(contrastRatio(ui[foreground], ui['--bg'])).toBeGreaterThanOrEqual(4.5);
@@ -129,13 +133,15 @@ describe('Theme V2 界面风格', () => {
afterEach(() => applyBuiltInTheme('cyberpunk'));
it('提供版本化外观结构,并让内置主题覆盖四种风格', () => {
expect(THEME_SCHEMA_VERSION).toBe(2);
expect(THEME_SCHEMA_VERSION).toBe(3);
expect(BUILT_IN_APPEARANCE).toEqual({
'standard-dark': { style: 'standard' },
'standard-light': { style: 'standard' },
cyberpunk: { style: 'cyberpunk' },
glacier: { style: 'soft' },
apple: { style: 'soft' },
gruvbox: { style: 'dense' },
crt: { style: 'cyberpunk' },
glass: { style: 'soft', blur: 'strong' },
});
expect(Object.keys(UI_STYLE_PRESETS).sort()).toEqual([
'cyberpunk',
@@ -146,7 +152,7 @@ describe('Theme V2 界面风格', () => {
});
it('切换内置主题会同步形状、密度、字体、阴影、动效和组件风格', () => {
applyBuiltInTheme('glacier');
applyBuiltInTheme('apple');
expect(getActiveThemeAppearance()).toEqual({
style: 'soft',
shape: 'soft',
@@ -154,6 +160,7 @@ describe('Theme V2 界面风格', () => {
font: 'system',
shadow: 'elevated',
motion: 'reduced',
blur: 'strong',
components: {
button: 'soft',
input: 'boxed',
@@ -196,6 +203,7 @@ describe('Theme V2 界面风格', () => {
font: 'mono',
shadow: 'none',
motion: 'none',
blur: 'strong',
components: {
button: 'solid',
input: 'underline',
@@ -235,7 +243,7 @@ describe('Theme V2 界面风格', () => {
normalizeImportedTheme({
schemaVersion: 999,
name: ' My Theme ',
baseTheme: 'glacier',
baseTheme: 'gruvbox',
colorScheme: 'dark',
ui: {
'--accent': '#abcdef',
@@ -248,9 +256,9 @@ describe('Theme V2 界面风格', () => {
},
})
).toEqual({
schemaVersion: 2,
schemaVersion: 3,
name: 'My Theme',
baseTheme: 'glacier',
baseTheme: 'gruvbox',
colorScheme: 'dark',
ui: { '--accent': '#abcdef' },
appearance: {
@@ -260,6 +268,25 @@ describe('Theme V2 界面风格', () => {
});
});
it('旧版 glacier 基础主题优雅降级:字段被丢弃但主题仍可导入', () => {
expect(
normalizeImportedTheme({
schemaVersion: 2,
name: 'Legacy Glacier Custom',
baseTheme: 'glacier',
colorScheme: 'dark',
ui: { '--accent': '#67e8f9' },
appearance: { style: 'soft' },
})
).toEqual({
schemaVersion: 3,
name: 'Legacy Glacier Custom',
colorScheme: 'dark',
ui: { '--accent': '#67e8f9' },
appearance: { style: 'soft' },
});
});
it('应用与服务端共享 UI 属性白名单,并拒绝 UI 中的外部资源值', () => {
expect([...SAFE_UI_THEME_PROPERTIES].sort()).toEqual(Object.keys(UI_THEMES.cyberpunk).sort());
expect(
@@ -297,6 +324,8 @@ describe('Standard 主题入口和编辑器', () => {
{
ui: Record<string, string>;
appearance: Record<string, unknown>;
background?: Record<string, unknown>;
effects?: Record<string, number>;
}
>;
@@ -314,8 +343,10 @@ describe('Standard 主题入口和编辑器', () => {
expect(appHtml.match(/data-theme-import/g)).toHaveLength(3);
expect(appHtml).not.toContain('data-theme-export');
expect(appHtml).not.toContain('data-theme-delete');
expect(appHtml).toContain('Glacier · Soft');
expect(appHtml).toContain('Apple · Soft');
expect(appHtml).toContain('Gruvbox · Dense');
expect(appHtml).toContain('CRT Amber');
expect(appHtml).toContain('Glass · Soft');
});
it('Pages 保持独立,应用为登录用户同步单个自定义主题', () => {
@@ -327,6 +358,9 @@ describe('Standard 主题入口和编辑器', () => {
expect(mainSource).toContain(
'void restoreCloudTheme(initialThemeSelection, themeSelectionRevision)'
);
// glacier 已被 Apple 取代:旧选择在恢复时迁移到 Standard Dark,避免静默回退到默认主题
expect(mainSource).toContain("selection === 'glacier'");
expect(mainSource).toContain("'standard-dark'");
expect(workerSource).toContain("url.pathname === '/api/user/theme'");
expect(userDbSource).toContain('CREATE TABLE IF NOT EXISTS user_themes');
expect(userDbSource).not.toContain('handleDeleteTheme');
@@ -358,8 +392,10 @@ describe('Standard 主题入口和编辑器', () => {
'standard-dark',
'standard-light',
'cyberpunk',
'glacier',
'apple',
'gruvbox',
'crt',
'glass',
]) {
expect(editorHtml).toContain(`<option value="${themeName}"`);
}
@@ -385,7 +421,7 @@ describe('Standard 主题入口和编辑器', () => {
for (const field of ['button', 'input', 'card', 'tabs']) {
expect(editorHtml).toContain(`key: '${field}'`);
}
expect(editorHtml).toContain('schemaVersion: 2');
expect(editorHtml).toContain('schemaVersion: 3');
expect(editorHtml).toContain('baseTheme: activePreset');
expect(editorHtml).toContain('sanitizeAppearance(data.appearance)');
expect(editorHtml).toContain('file.size > THEME_MAX_BYTES');
@@ -395,11 +431,14 @@ describe('Standard 主题入口和编辑器', () => {
expect(editorHtml).toContain('ui: safeUiTheme');
expect(editorHtml).not.toContain('transition: all');
expect(THEME_MAX_BYTES).toBe(64 * 1024);
expect(editorPresets.glacier.appearance).toMatchObject({
expect(editorPresets.apple.appearance).toMatchObject({
style: 'soft',
shape: 'soft',
density: 'comfortable',
});
expect(editorPresets.crt.background).toMatchObject({ type: 'radial' });
expect(editorPresets.glass.background).toMatchObject({ type: 'mesh', animation: 'drift' });
expect(editorPresets.glass.appearance).toMatchObject({ blur: 'strong' });
});
it('终端订阅全局主题并在销毁时解除订阅', () => {
@@ -407,3 +446,94 @@ describe('Standard 主题入口和编辑器', () => {
expect(terminalSource).toContain('this.themeCleanup()');
});
});
describe('Theme V3 背景层、效果与版式', () => {
afterEach(() => applyBuiltInTheme('cyberpunk'));
it('四种背景类型合成安全 CSS 渐变串,缺省/纯色回退基色', () => {
expect(resolveBackgroundCss(undefined)).toBe('var(--bg)');
expect(
resolveBackgroundCss({ type: 'solid', stops: ['#0a0a0a'], angle: 0, scrim: 0, animation: 'none' })
).toBe('var(--bg)');
expect(
resolveBackgroundCss({
type: 'linear',
stops: ['#0a0a0a', '#11170c'],
angle: 165,
scrim: 0.3,
animation: 'none',
})
).toBe('linear-gradient(165deg, #0a0a0a, #11170c)');
expect(
resolveBackgroundCss({
type: 'radial',
stops: ['#261b00', '#0f0a00'],
angle: 160,
scrim: 0.3,
animation: 'none',
})
).toContain('radial-gradient(ellipse at 50% 25%, #261b00, #0f0a00)');
expect(
resolveBackgroundCss({
type: 'mesh',
stops: ['#d3e3f8', '#e8edf5', '#ece0f6'],
angle: 135,
scrim: 0.35,
animation: 'drift',
})
).toMatch(/^radial-gradient\(at 18% 22%, #d3e3f8 0px, transparent 55%\), radial-gradient/);
});
it('背景停靠点过白名单并截断到 5 个,渐变强制读性遮罩下限', () => {
const normalized = normalizeImportedTheme({
background: {
type: 'linear',
stops: ['#0a0a0a', '#11170c', '#1a2410', '#223018', '#2a3a20', '#324428'],
angle: 999,
scrim: -1,
animation: 'invalid',
},
});
expect(normalized?.background?.stops).toHaveLength(5);
expect(normalized?.background?.angle).toBe(360);
expect(normalized?.background?.scrim).toBeGreaterThanOrEqual(0.25);
expect(normalized?.background?.animation).toBe('none');
const light = normalizeImportedTheme({
colorScheme: 'light',
background: { type: 'mesh', stops: ['#d3e3f8', '#e8edf5'], angle: 135, scrim: 0, animation: 'none' },
});
expect(light?.background?.scrim).toBeGreaterThanOrEqual(0.35);
const unsafe = normalizeImportedTheme({
background: {
type: 'linear',
stops: ['url(https://tracker.example/x.png)'],
angle: 160,
scrim: 0.3,
animation: 'none',
},
});
expect(unsafe?.background).toBeUndefined();
});
it('效果强度钩制在 0-1 且零值不导出,版式缩放钩制到安全区间', () => {
const normalized = normalizeImportedTheme({
effects: { scanline: 5, flicker: -1, glow: 0.4, noise: 0 },
typography: { fontScale: 99, radiusScale: 0.01 },
});
expect(normalized?.effects).toEqual({ scanline: 1, glow: 0.4 });
expect(normalized?.typography).toEqual({ fontScale: 1.25, radiusScale: 0.5 });
expect(normalizeImportedTheme({ effects: { glow: 0 } })).toBeNull();
});
it('内置主题携带差异化的背景、效果与版式配置', () => {
expect(BUILT_IN_BACKGROUND.crt?.type).toBe('radial');
expect(BUILT_IN_BACKGROUND.glass?.type).toBe('mesh');
expect(BUILT_IN_BACKGROUND.glass?.animation).toBe('drift');
expect(BUILT_IN_EFFECTS.cyberpunk).toEqual({ scanline: 1, flicker: 1 });
expect(BUILT_IN_EFFECTS.crt?.glow).toBeGreaterThan(0);
expect(BUILT_IN_TYPOGRAPHY.glass?.radiusScale).toBeGreaterThan(1);
expect(BUILT_IN_BACKGROUND['standard-dark']).toBeUndefined();
});
});
+1 -1
View File
@@ -584,7 +584,7 @@ describe('安全 — 自定义主题接口边界', () => {
expect(res.status).toBe(200);
expect(forwardedBody?.user_id).toBe(12);
expect(JSON.parse(forwardedBody?.theme_data ?? '{}')).toEqual({
schemaVersion: 2,
schemaVersion: 3,
name: 'Shared Theme',
colorScheme: 'dark',
ui: { '--accent': '#abcdef' },