Merge pull request #9 from newbietan/test

feat: 双环境部署支持、SSH 协议稳定性修复及文档更新
This commit is contained in:
TanXin authored and GitHub committed 2026-06-24 12:27:58 +08:00
commit 579314b77c
12 files changed
+383 -144

No files matched your search

+10 -2
View File
@@ -2,7 +2,7 @@ name: Deploy to Cloudflare Workers
on:
push:
branches: [test]
branches: [test, main]
jobs:
deploy:
@@ -23,7 +23,15 @@ jobs:
pnpm install
cd frontend && pnpm install
- name: Build frontend and deploy
- name: Build frontend and deploy (test)
if: github.ref == 'refs/heads/test'
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
run: pnpm run deploy:test
- name: Build frontend and deploy (production)
if: github.ref == 'refs/heads/main'
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
+64 -14
View File
@@ -39,7 +39,13 @@
- [核心特性](#features)
- [架构说明](#architecture)
- [快速部署](#quick-start)
- [GitHub 绑定自动部署](#方式一通过-github-绑定自动部署推荐)
- [本地命令行部署](#方式二本地命令行部署)
- [配置 Turnstile](#可选配置-turnstile-人机验证)
- [配置 GitHub OAuth](#可选配置-github-oauth-登录与服务器管理)
- [开发说明](#development)
- [本地开发](#本地开发)
- [技术栈](#技术栈)
- [开源协议](#license)
<a id="highlights"></a>
@@ -152,10 +158,12 @@ flowchart TB
#### 方式一:通过 GitHub 绑定自动部署(推荐)
1. **Fork 本仓库** 到你的 GitHub 账号。
2. **一键部署**:登录 Cloudflare,进入 Workers & Pages 绑定你的 GitHub 账号,选择刚才 Fork 的仓库进行应用创建。
3. **填写构建命令**:在部署设置中,请务必将"构建命令"(Build command)填写为 `pnpm run build:frontend`,然后点击保存并部署(无需填写构建输出目录)。
2. **创建 Worker 应用**:登录 Cloudflare,进入 Workers & Pages,点击创建应用,绑定你的 GitHub 账号,选择 Fork 的仓库。
3. **填写构建命令**:在部署设置中,将"构建命令"(Build command)填写为 `pnpm run build:frontend`,点击保存并部署。
4. **访问应用**:部署成功后,可通过默认域名 `https://cloudssh.<你的子域>.workers.dev` 访问。
5. **绑定自定义域名**(可选):在 Cloudflare Dashboard 的 Workers 设置中,进入 "Triggers" → "Custom Domains" 添加你的域名。
5. **绑定自定义域名**(可选):进入 Worker 的 Settings → Domains & Routes → Add,输入你的域名并确认。
> **说明**:如需部署 test 环境,可 Fork 后在 `test` 分支上重复上述步骤,创建独立的 Worker(如 `cloudssh-test`),两个 Worker 共享相同的 DO 类名即可实现数据互通。
#### 方式二:本地命令行部署
@@ -169,6 +177,7 @@ flowchart TB
```bash
npm install -g pnpm
pnpm install
cd frontend && pnpm install
```
3. **登录 Cloudflare**
@@ -176,14 +185,22 @@ flowchart TB
npx wrangler login
```
4. **一键部署**
4. **部署生产环境**
```bash
pnpm run deploy
```
部署完成后,Wrangler 会输出你的 Worker URL。打开浏览器访问该 URL,即可开始使用你的 Web SSH 终端。
5. **部署测试环境**(可选)
```bash
pnpm run deploy:test
```
5. **绑定自定义域名**(可选):在 Cloudflare Dashboard 的 Workers 设置中,进入 "Triggers" → "Custom Domains" 添加你的域名。
| 环境 | 命令 | 默认域名 | 说明 |
|------|------|---------|------|
| Production | `pnpm run deploy` | `cloudssh.<子域>.workers.dev` | main 分支代码 |
| Test | `pnpm run deploy:test` | `cloudssh-test.<子域>.workers.dev` | test 分支代码,与生产环境共享 DO 数据 |
> **说明**:两个环境的 Durable Objects 绑定相同的 class_name,数据完全共享。部署完成后可在 Cloudflare Dashboard 中分别绑定不同的自定义域名(Settings → Domains & Routes)。
#### 可选:配置 Turnstile 人机验证
@@ -242,21 +259,54 @@ CloudSSH/
### 本地开发
1. **安装依赖**
#### 环境准备
1. **Fork 并克隆仓库**
```bash
git clone https://github.com/<你的用户名>/CloudSSH.git
cd CloudSSH
```
2. **安装依赖**(需分别安装根目录和前端依赖)
```bash
pnpm install
cd frontend && pnpm install
```
2. **启动开发服务器**
3. **登录 Cloudflare**(首次需要,后续会缓存凭据)
```bash
pnpm run dev
npx wrangler login
```
此命令将构建前端并启动 Wrangler 本地开发环境。
> **说明**:本地开发使用 Wrangler Dev 时,会连接到你的 Cloudflare 账号以使用 Durable Objects 和 TCP Sockets。SSH 连接的真实 TCP 流量会通过 Cloudflare 的基础设施转发。
3. **仅构建前端**
```bash
pnpm run build:frontend
```
#### 启动开发服务器
```bash
pnpm run dev
```
此命令将构建前端并启动 Wrangler 本地开发环境,支持:
- 前端代码变更自动重新构建
- Worker 代码变更自动重新加载
- 完整的 Durable Objects 和 TCP Sockets 功能
开发服务器启动后,访问终端输出的本地地址(通常为 `http://localhost:8787`)即可进行调试。
#### 常用开发命令
| 命令 | 说明 |
|------|------|
| `pnpm run dev` | 构建前端 + 启动 Wrangler 开发服务器 |
| `pnpm run build:frontend` | 仅构建前端(输出到 `frontend/dist/`) |
| `pnpm test` | 运行测试 |
#### 提交 PR 的流程
1. 基于 `main` 分支创建你的特性分支:`git checkout -b feat/your-feature`
2. 进行开发并本地测试
3. 提交 PR 到 `main` 分支
> **说明**:`test` 分支为预发布分支,用于部署测试环境,普通开发请基于 `main` 分支工作。
### 技术栈
+65 -15
View File
@@ -39,7 +39,13 @@
- [Features](#features)
- [Architecture](#architecture)
- [Quick Deployment](#quick-start)
- [GitHub Integration](#method-1-deploy-via-github-integration-recommended)
- [Local CLI Deployment](#method-2-local-cli-deployment)
- [Configure Turnstile](#optional-configure-turnstile-human-verification)
- [Configure GitHub OAuth](#optional-configure-github-oauth-login--server-management)
- [Development](#development)
- [Local Development](#local-development)
- [Tech Stack](#tech-stack)
- [License](#license)
<a id="highlights"></a>
@@ -152,10 +158,12 @@ This project implements a complete SSH-2.0 protocol stack:
#### Method 1: Deploy via GitHub Integration (Recommended)
1. **Fork this repository** to your GitHub account.
2. **Setup Deployment**: Log in to the Cloudflare dashboard, go to Workers & Pages to connect your GitHub account, and select the forked repository.
3. **Build Command**: During the deployment configuration, make sure to enter `pnpm run build:frontend` as the Build command, then deploy with one click (the build output directory can be left blank).
4. **Access the App**: After successful deployment, you can access it via the default domain `https://cloudssh.<your-subdomain>.workers.dev`.
5. **Bind Custom Domain** (Optional): In the Cloudflare Dashboard Workers settings, go to "Triggers" → "Custom Domains" to add your domain.
2. **Create Worker App**: Log in to Cloudflare, go to Workers & Pages, click Create Application, connect your GitHub account, and select the forked repository.
3. **Build Command**: During deployment settings, enter `pnpm run build:frontend` as the Build command, then save and deploy.
4. **Access the App**: After successful deployment, access via the default domain `https://cloudssh.<your-subdomain>.workers.dev`.
5. **Bind Custom Domain** (Optional): Go to Worker Settings → Domains & Routes → Add, enter your domain and confirm.
> **Note**: To deploy a test environment, repeat the above steps on the `test` branch to create a separate Worker (e.g., `cloudssh-test`). Both Workers share the same DO class names for data synchronization.
#### Method 2: Local CLI Deployment
@@ -169,6 +177,7 @@ This project implements a complete SSH-2.0 protocol stack:
```bash
npm install -g pnpm
pnpm install
cd frontend && pnpm install
```
3. **Login to Cloudflare**
@@ -176,14 +185,22 @@ This project implements a complete SSH-2.0 protocol stack:
npx wrangler login
```
4. **One-Click Deploy**
4. **Deploy Production**
```bash
pnpm run deploy
```
Once deployed, Wrangler will output your Worker URL. Open that URL in your browser to start using your Web SSH terminal.
5. **Deploy Test Environment** (Optional)
```bash
pnpm run deploy:test
```
5. **Bind Custom Domain** (Optional): In the Cloudflare Dashboard Workers settings, go to "Triggers" → "Custom Domains" to add your domain.
| Environment | Command | Default Domain | Description |
|-------------|---------|---------------|-------------|
| Production | `pnpm run deploy` | `cloudssh.<subdomain>.workers.dev` | main branch code |
| Test | `pnpm run deploy:test` | `cloudssh-test.<subdomain>.workers.dev` | test branch code, shares DO data with production |
> **Note**: Both environments bind to Durable Objects with the same `class_name`, sharing data completely. After deployment, you can bind different custom domains for each environment in the Cloudflare Dashboard (Settings → Domains & Routes).
#### Optional: Configure Turnstile Human Verification
@@ -242,21 +259,54 @@ CloudSSH/
### Local Development
1. **Install Dependencies**
#### Environment Setup
1. **Fork and Clone the Repository**
```bash
git clone https://github.com/<your-username>/CloudSSH.git
cd CloudSSH
```
2. **Install Dependencies** (root and frontend separately)
```bash
pnpm install
cd frontend && pnpm install
```
2. **Start Development Server**
3. **Login to Cloudflare** (required on first run, credentials are cached afterward)
```bash
pnpm run dev
npx wrangler login
```
This command builds the frontend and starts the Wrangler local development environment.
> **Note**: When using Wrangler Dev for local development, it connects to your Cloudflare account to access Durable Objects and TCP Sockets. Real SSH TCP traffic is forwarded through Cloudflare's infrastructure.
3. **Build Frontend Only**
```bash
pnpm run build:frontend
```
#### Start Development Server
```bash
pnpm run dev
```
This command builds the frontend and starts the Wrangler local development environment, supporting:
- Automatic rebuild on frontend code changes
- Automatic reload on Worker code changes
- Full Durable Objects and TCP Sockets functionality
After the dev server starts, visit the local address shown in the terminal (usually `http://localhost:8787`) to start debugging.
#### Common Development Commands
| Command | Description |
|---------|-------------|
| `pnpm run dev` | Build frontend + start Wrangler dev server |
| `pnpm run build:frontend` | Build frontend only (output to `frontend/dist/`) |
| `pnpm test` | Run tests |
#### Submitting a PR
1. Create your feature branch from `main`: `git checkout -b feat/your-feature`
2. Develop and test locally
3. Submit a PR to the `main` branch
> **Note**: The `test` branch is a pre-release branch for deploying the test environment. For regular development, work based on the `main` branch.
### Tech Stack
+27 -20
View File
@@ -9,6 +9,10 @@ let connectionForm: ConnectionForm | null = null;
let serverList: ServerList | null = null;
let isLoggedIn = false;
terminal.setSessionClosedHandler(() => {
showOfflineUI();
});
// ==================== 独立终端标签页模式 ====================
function isTerminalTab(): boolean {
@@ -38,12 +42,6 @@ function initTerminalTab(): void {
const ws = new WebSocket(wsUrl);
ws.binaryType = 'arraybuffer';
terminal.connectWithWebSocket(ws);
// 断开连接时关闭标签页
document.getElementById('disconnect-btn')?.addEventListener('click', () => {
terminal.disconnect();
window.close();
});
}
// ==================== 页面切换 ====================
@@ -81,6 +79,28 @@ function showUserSpace(user: { id: number; github_id: number; username: string;
);
}
function showOfflineUI(): void {
if (isTerminalTab()) {
window.close();
return;
}
const termSection = document.getElementById('terminal-section');
if (termSection) {
termSection.classList.add('hidden');
termSection.classList.remove('flex');
}
if (isLoggedIn) {
document.getElementById('user-space-section')?.classList.remove('hidden');
document.getElementById('user-space-section')?.classList.add('flex');
} else {
showAuthSection();
}
document.getElementById('status-text')!.innerHTML = '<span class="w-2 h-2 bg-[#353534] inline-block"></span> STATUS: OFFLINE';
}
function showTerminalFromServer(wsUrl: string, serverName: string): void {
document.getElementById('auth-section')!.classList.add('hidden');
document.getElementById('user-space-section')!.classList.add('hidden');
@@ -105,20 +125,7 @@ function showTerminalFromServer(wsUrl: string, serverName: string): void {
document.getElementById('disconnect-btn')?.addEventListener('click', () => {
terminal.disconnect();
const termSection = document.getElementById('terminal-section')!;
termSection.classList.add('hidden');
termSection.classList.remove('flex');
if (isLoggedIn) {
// 已登录用户回到用户空间
document.getElementById('user-space-section')!.classList.remove('hidden');
document.getElementById('user-space-section')!.classList.add('flex');
} else {
// 匿名用户回到连接表单
document.getElementById('auth-section')!.classList.remove('hidden');
}
document.getElementById('status-text')!.innerHTML = '<span class="w-2 h-2 bg-[#353534] inline-block"></span> STATUS: OFFLINE';
showOfflineUI();
});
// ==================== 主题切换 ====================
+45 -11
View File
@@ -51,6 +51,7 @@ export class SSHTerminal {
private maxReconnectAttempts: number = 5;
private reconnectTimeout: ReturnType<typeof setTimeout> | null = null;
private lastConfig: SSHConnectionConfig | null = null;
private onSessionClosed?: (event: CloseEvent) => void;
constructor(containerId: string) {
this.container = document.getElementById(containerId)!;
@@ -104,6 +105,10 @@ export class SSHTerminal {
this.terminal.options.theme = THEMES[themeName];
}
setSessionClosedHandler(handler: (event: CloseEvent) => void): void {
this.onSessionClosed = handler;
}
mount(): void {
this.terminal.open(this.container);
@@ -152,6 +157,7 @@ export class SSHTerminal {
password: config.password,
authMethod: config.authMethod,
privateKey: config.privateKey,
...this.getTerminalSize(),
}));
this.startHeartbeat();
@@ -188,14 +194,20 @@ export class SSHTerminal {
ws.onopen = () => {
this.terminal.writeln('\x1b[32m[+] WebSocket connected, authenticating...\x1b[0m');
this.sendResize();
this.startHeartbeat();
};
if (ws.readyState === WebSocket.OPEN) {
this.sendResize();
}
this.setupWebSocketHandlers();
}
private setupWebSocketHandlers(rejectFn?: (reason?: any) => void): void {
if (!this.ws) return;
const socket = this.ws;
// Trzsz file transfer support
this.trzszFilter = new TrzszFilter({
@@ -234,6 +246,9 @@ export class SSHTerminal {
case 'error':
this.terminal.writeln(`\x1b[31m[!] ${msg.message}\x1b[0m`);
break;
case 'debug':
this.terminal.writeln(`\x1b[90m[DEBUG] ${msg.message}\x1b[0m`);
break;
case 'pong':
break;
}
@@ -248,6 +263,8 @@ export class SSHTerminal {
};
this.ws.onclose = (event) => {
if (socket !== this.ws) return;
this.stopHeartbeat();
this.terminal.writeln(
`\x1b[33m[*] Connection closed (code=${event.code})\x1b[0m`
@@ -257,7 +274,12 @@ export class SSHTerminal {
const statusText = document.getElementById('status-text');
if (statusText) statusText.innerHTML = '<span class="w-2 h-2 bg-[#353534] inline-block"></span> STATUS: OFFLINE';
if (event.code !== 1000 && this.lastConfig && this.reconnectAttempts < this.maxReconnectAttempts) {
if (event.code === 1000) {
this.onSessionClosed?.(event);
return;
}
if (this.lastConfig && this.reconnectAttempts < this.maxReconnectAttempts) {
this.scheduleReconnect();
}
};
@@ -284,13 +306,7 @@ export class SSHTerminal {
// Terminal resize: send to server + update trzsz column count
this.disposables.push(
this.terminal.onResize(({ cols, rows }) => {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({
type: 'resize',
cols,
rows,
}));
}
this.sendResize({ cols, rows });
this.trzszFilter?.setTerminalColumns(cols);
})
);
@@ -309,6 +325,22 @@ export class SSHTerminal {
}, 30000);
}
private getTerminalSize(): { cols: number; rows: number } {
return {
cols: this.terminal.cols,
rows: this.terminal.rows,
};
}
private sendResize(size = this.getTerminalSize()): void {
if (this.ws?.readyState === WebSocket.OPEN) {
this.ws.send(JSON.stringify({
type: 'resize',
...size,
}));
}
}
private stopHeartbeat(): void {
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
@@ -333,11 +365,13 @@ export class SSHTerminal {
this.clearReconnectTimeout();
this.disposeConnectionDisposables();
if (this.ws && this.ws.readyState !== WebSocket.CLOSED && this.ws.readyState !== WebSocket.CLOSING) {
this.ws.close(1000);
}
const socket = this.ws;
this.ws = null;
this.trzszFilter = null;
if (socket && socket.readyState !== WebSocket.CLOSED && socket.readyState !== WebSocket.CLOSING) {
socket.close(1000);
}
}
private scheduleReconnect(): void {
+1
View File
@@ -6,6 +6,7 @@
"scripts": {
"dev": "node scripts/build-html.js && wrangler dev",
"deploy": "node scripts/build-html.js && wrangler deploy",
"deploy:test": "node scripts/build-html.js && wrangler deploy --env test",
"build:frontend": "node scripts/build-html.js",
"test": "vitest run"
},
+9
View File
@@ -46,6 +46,13 @@ export interface SSHConnectionConfig {
password: string;
authMethod?: 'password' | 'publickey';
privateKey?: string;
cols?: number;
rows?: number;
}
export interface TerminalSize {
cols: number;
rows: number;
}
export interface Env {
@@ -62,6 +69,8 @@ export interface Env {
BASE_URL?: string;
// 主机密钥验证严格模式(默认 true,设为 false 可跳过签名验证失败)
STRICT_HOST_KEY_VERIFY?: string;
// 调试模式(设为 true 启用调试日志输出到前端)
DEBUG_MODE?: string;
}
export interface UserInfo {
+67 -15
View File
@@ -1,4 +1,4 @@
import { Env, SSHConnectionConfig } from '../types';
import { Env, SSHConnectionConfig, TerminalSize } from '../types';
import { SSHSession } from './ssh-session';
/**
@@ -38,6 +38,7 @@ export class SSHSessionDO {
private env: Env;
private sessions: Map<WebSocket, SSHSession> = new Map();
private _pendingTimeouts: Map<WebSocket, ReturnType<typeof setTimeout>> = new Map();
private pendingTerminalSizes: Map<WebSocket, TerminalSize> = new Map();
constructor(state: DurableObjectState, env: Env) {
this.state = state;
@@ -105,26 +106,43 @@ export class SSHSessionDO {
return;
}
if (typeof message !== 'string') {
return;
}
let msg: any;
try {
msg = JSON.parse(message);
} catch {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid credentials format' }));
ws.close(1011, 'Invalid format');
return;
}
if (msg.type === 'resize') {
this.rememberTerminalSize(ws, msg.cols, msg.rows);
return;
}
if (msg.type === 'ping') {
ws.send(JSON.stringify({ type: 'pong' }));
return;
}
const timeout = this._pendingTimeouts.get(ws);
if (timeout) {
clearTimeout(timeout);
this._pendingTimeouts.delete(ws);
}
try {
const config = JSON.parse(message as string) as SSHConnectionConfig;
const config = msg as SSHConnectionConfig;
if (!config.host || !config.username || (!config.password && !config.privateKey)) {
ws.send(JSON.stringify({ type: 'error', message: 'Missing credentials' }));
ws.close(1011, 'Invalid credentials');
return;
}
await this.initSSHSession(ws, config);
} catch (e) {
ws.send(JSON.stringify({ type: 'error', message: 'Invalid credentials format' }));
ws.close(1011, 'Invalid format');
if (!config.host || !config.username || (!config.password && !config.privateKey)) {
ws.send(JSON.stringify({ type: 'error', message: 'Missing credentials' }));
ws.close(1011, 'Invalid credentials');
return;
}
await this.initSSHSession(ws, config);
}
async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean): Promise<void> {
@@ -138,6 +156,7 @@ export class SSHSessionDO {
clearTimeout(timeout);
this._pendingTimeouts.delete(ws);
}
this.pendingTerminalSizes.delete(ws);
}
async webSocketError(ws: WebSocket, error: unknown): Promise<void> {
@@ -165,18 +184,51 @@ export class SSHSessionDO {
await socket.opened;
const strictVerify = this.env.STRICT_HOST_KEY_VERIFY !== 'false';
const session = new SSHSession(ws, socket, config, strictVerify);
const debugMode = this.env.DEBUG_MODE === 'true';
const pendingSize = this.pendingTerminalSizes.get(ws);
if (pendingSize) {
config.cols = pendingSize.cols;
config.rows = pendingSize.rows;
}
const session = new SSHSession(ws, socket, config, strictVerify, debugMode);
this.sessions.set(ws, session);
this.pendingTerminalSizes.delete(ws);
await session.startHandshake();
} catch (error) {
const errMsg = error instanceof Error ? error.message : String(error);
console.error('[SSH] Session error:', errMsg);
try {
ws.send(JSON.stringify({ type: 'error', message: `连接失败: ${errMsg}` }));
ws.close(1011, 'SSH connection failed');
} catch {}
}
}
private rememberTerminalSize(ws: WebSocket, cols: unknown, rows: unknown): void {
const size = this.normalizeTerminalSize(cols, rows);
if (size) this.pendingTerminalSizes.set(ws, size);
}
private normalizeTerminalSize(cols: unknown, rows: unknown): TerminalSize | null {
if (
typeof cols !== 'number' ||
typeof rows !== 'number' ||
!Number.isFinite(cols) ||
!Number.isFinite(rows)
) {
return null;
}
const size = {
cols: Math.floor(cols),
rows: Math.floor(rows),
};
if (size.cols < 10 || size.cols > 1000 || size.rows < 5 || size.rows > 1000) {
return null;
}
return size;
}
}
+16 -16
View File
@@ -41,15 +41,15 @@ export const HTML = `<!DOCTYPE html>
}
</script>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
<script type="module">var ao=Object.defineProperty;var ho=(i,e,t)=>e in i?ao(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Q=(i,e,t)=>ho(i,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const o of n)if(o.type==="childList")for(const _ of o.addedNodes)_.tagName==="LINK"&&_.rel==="modulepreload"&&r(_)}).observe(document,{childList:!0,subtree:!0});function t(n){const o={};return n.integrity&&(o.integrity=n.integrity),n.referrerPolicy&&(o.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?o.credentials="include":n.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(n){if(n.ep)return;n.ep=!0;const o=t(n);fetch(n.href,o)}})();var Hi={exports:{}},$s;function lo(){return $s||($s=1,(function(i,e){(function(t,r){i.exports=r()})(globalThis,(()=>(()=>{var t={4567:function(_,s,h){var a=this&&this.__decorate||function(l,c,v,y){var S,x=arguments.length,b=x<3?c:y===null?y=Object.getOwnPropertyDescriptor(c,v):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")b=Reflect.decorate(l,c,v,y);else for(var E=l.length-1;E>=0;E--)(S=l[E])&&(b=(x<3?S(b):x>3?S(c,v,b):S(c,v))||b);return x>3&&b&&Object.defineProperty(c,v,b),b},d=this&&this.__param||function(l,c){return function(v,y){c(v,y,l)}};Object.defineProperty(s,"__esModule",{value:!0}),s.AccessibilityManager=void 0;const u=h(9042),p=h(9924),m=h(844),C=h(4725),w=h(2585),f=h(3656);let g=s.AccessibilityManager=class extends m.Disposable{constructor(l,c,v,y){super(),this._terminal=l,this._coreBrowserService=v,this._renderService=y,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let S=0;S<this._terminal.rows;S++)this._rowElements[S]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[S]);if(this._topBoundaryFocusListener=S=>this._handleBoundaryFocus(S,0),this._bottomBoundaryFocusListener=S=>this._handleBoundaryFocus(S,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new p.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((S=>this._handleResize(S.rows)))),this.register(this._terminal.onRender((S=>this._refreshRows(S.start,S.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((S=>this._handleChar(S)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(\`
<script type="module">var lo=Object.defineProperty;var co=(i,e,t)=>e in i?lo(i,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):i[e]=t;var Q=(i,e,t)=>co(i,typeof e!="symbol"?e+"":e,t);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const n of document.querySelectorAll('link[rel="modulepreload"]'))r(n);new MutationObserver(n=>{for(const o of n)if(o.type==="childList")for(const _ of o.addedNodes)_.tagName==="LINK"&&_.rel==="modulepreload"&&r(_)}).observe(document,{childList:!0,subtree:!0});function t(n){const o={};return n.integrity&&(o.integrity=n.integrity),n.referrerPolicy&&(o.referrerPolicy=n.referrerPolicy),n.crossOrigin==="use-credentials"?o.credentials="include":n.crossOrigin==="anonymous"?o.credentials="omit":o.credentials="same-origin",o}function r(n){if(n.ep)return;n.ep=!0;const o=t(n);fetch(n.href,o)}})();var Hi={exports:{}},Hs;function uo(){return Hs||(Hs=1,(function(i,e){(function(t,r){i.exports=r()})(globalThis,(()=>(()=>{var t={4567:function(_,s,h){var a=this&&this.__decorate||function(l,c,v,y){var S,x=arguments.length,b=x<3?c:y===null?y=Object.getOwnPropertyDescriptor(c,v):y;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")b=Reflect.decorate(l,c,v,y);else for(var E=l.length-1;E>=0;E--)(S=l[E])&&(b=(x<3?S(b):x>3?S(c,v,b):S(c,v))||b);return x>3&&b&&Object.defineProperty(c,v,b),b},d=this&&this.__param||function(l,c){return function(v,y){c(v,y,l)}};Object.defineProperty(s,"__esModule",{value:!0}),s.AccessibilityManager=void 0;const u=h(9042),p=h(9924),m=h(844),C=h(4725),w=h(2585),f=h(3656);let g=s.AccessibilityManager=class extends m.Disposable{constructor(l,c,v,y){super(),this._terminal=l,this._coreBrowserService=v,this._renderService=y,this._rowColumns=new WeakMap,this._liveRegionLineCount=0,this._charsToConsume=[],this._charsToAnnounce="",this._accessibilityContainer=this._coreBrowserService.mainDocument.createElement("div"),this._accessibilityContainer.classList.add("xterm-accessibility"),this._rowContainer=this._coreBrowserService.mainDocument.createElement("div"),this._rowContainer.setAttribute("role","list"),this._rowContainer.classList.add("xterm-accessibility-tree"),this._rowElements=[];for(let S=0;S<this._terminal.rows;S++)this._rowElements[S]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[S]);if(this._topBoundaryFocusListener=S=>this._handleBoundaryFocus(S,0),this._bottomBoundaryFocusListener=S=>this._handleBoundaryFocus(S,1),this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions(),this._accessibilityContainer.appendChild(this._rowContainer),this._liveRegion=this._coreBrowserService.mainDocument.createElement("div"),this._liveRegion.classList.add("live-region"),this._liveRegion.setAttribute("aria-live","assertive"),this._accessibilityContainer.appendChild(this._liveRegion),this._liveRegionDebouncer=this.register(new p.TimeBasedDebouncer(this._renderRows.bind(this))),!this._terminal.element)throw new Error("Cannot enable accessibility before Terminal.open");this._terminal.element.insertAdjacentElement("afterbegin",this._accessibilityContainer),this.register(this._terminal.onResize((S=>this._handleResize(S.rows)))),this.register(this._terminal.onRender((S=>this._refreshRows(S.start,S.end)))),this.register(this._terminal.onScroll((()=>this._refreshRows()))),this.register(this._terminal.onA11yChar((S=>this._handleChar(S)))),this.register(this._terminal.onLineFeed((()=>this._handleChar(\`
\`)))),this.register(this._terminal.onA11yTab((S=>this._handleTab(S)))),this.register(this._terminal.onKey((S=>this._handleKey(S.key)))),this.register(this._terminal.onBlur((()=>this._clearLiveRegion()))),this.register(this._renderService.onDimensionsChange((()=>this._refreshRowsDimensions()))),this.register((0,f.addDisposableDomListener)(document,"selectionchange",(()=>this._handleSelectionChange()))),this.register(this._coreBrowserService.onDprChange((()=>this._refreshRowsDimensions()))),this._refreshRows(),this.register((0,m.toDisposable)((()=>{this._accessibilityContainer.remove(),this._rowElements.length=0})))}_handleTab(l){for(let c=0;c<l;c++)this._handleChar(" ")}_handleChar(l){this._liveRegionLineCount<21&&(this._charsToConsume.length>0?this._charsToConsume.shift()!==l&&(this._charsToAnnounce+=l):this._charsToAnnounce+=l,l===\`
\`&&(this._liveRegionLineCount++,this._liveRegionLineCount===21&&(this._liveRegion.textContent+=u.tooMuchOutput)))}_clearLiveRegion(){this._liveRegion.textContent="",this._liveRegionLineCount=0}_handleKey(l){this._clearLiveRegion(),new RegExp("\\\\p{Control}","u").test(l)||this._charsToConsume.push(l)}_refreshRows(l,c){this._liveRegionDebouncer.refresh(l,c,this._terminal.rows)}_renderRows(l,c){const v=this._terminal.buffer,y=v.lines.length.toString();for(let S=l;S<=c;S++){const x=v.lines.get(v.ydisp+S),b=[],E=(x==null?void 0:x.translateToString(!0,void 0,void 0,b))||"",B=(v.ydisp+S+1).toString(),T=this._rowElements[S];T&&(E.length===0?(T.innerText=" ",this._rowColumns.set(T,[0,1])):(T.textContent=E,this._rowColumns.set(T,b)),T.setAttribute("aria-posinset",B),T.setAttribute("aria-setsize",y))}this._announceCharacters()}_announceCharacters(){this._charsToAnnounce.length!==0&&(this._liveRegion.textContent+=this._charsToAnnounce,this._charsToAnnounce="")}_handleBoundaryFocus(l,c){const v=l.target,y=this._rowElements[c===0?1:this._rowElements.length-2];if(v.getAttribute("aria-posinset")===(c===0?"1":\`\${this._terminal.buffer.lines.length}\`)||l.relatedTarget!==y)return;let S,x;if(c===0?(S=v,x=this._rowElements.pop(),this._rowContainer.removeChild(x)):(S=this._rowElements.shift(),x=v,this._rowContainer.removeChild(S)),S.removeEventListener("focus",this._topBoundaryFocusListener),x.removeEventListener("focus",this._bottomBoundaryFocusListener),c===0){const b=this._createAccessibilityTreeNode();this._rowElements.unshift(b),this._rowContainer.insertAdjacentElement("afterbegin",b)}else{const b=this._createAccessibilityTreeNode();this._rowElements.push(b),this._rowContainer.appendChild(b)}this._rowElements[0].addEventListener("focus",this._topBoundaryFocusListener),this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._terminal.scrollLines(c===0?-1:1),this._rowElements[c===0?1:this._rowElements.length-2].focus(),l.preventDefault(),l.stopImmediatePropagation()}_handleSelectionChange(){var E;if(this._rowElements.length===0)return;const l=document.getSelection();if(!l)return;if(l.isCollapsed)return void(this._rowContainer.contains(l.anchorNode)&&this._terminal.clearSelection());if(!l.anchorNode||!l.focusNode)return void console.error("anchorNode and/or focusNode are null");let c={node:l.anchorNode,offset:l.anchorOffset},v={node:l.focusNode,offset:l.focusOffset};if((c.node.compareDocumentPosition(v.node)&Node.DOCUMENT_POSITION_PRECEDING||c.node===v.node&&c.offset>v.offset)&&([c,v]=[v,c]),c.node.compareDocumentPosition(this._rowElements[0])&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_FOLLOWING)&&(c={node:this._rowElements[0].childNodes[0],offset:0}),!this._rowContainer.contains(c.node))return;const y=this._rowElements.slice(-1)[0];if(v.node.compareDocumentPosition(y)&(Node.DOCUMENT_POSITION_CONTAINED_BY|Node.DOCUMENT_POSITION_PRECEDING)&&(v={node:y,offset:((E=y.textContent)==null?void 0:E.length)??0}),!this._rowContainer.contains(v.node))return;const S=({node:B,offset:T})=>{const M=B instanceof Text?B.parentNode:B;let k=parseInt(M==null?void 0:M.getAttribute("aria-posinset"),10)-1;if(isNaN(k))return console.warn("row is invalid. Race condition?"),null;const I=this._rowColumns.get(M);if(!I)return console.warn("columns is null. Race condition?"),null;let F=T<I.length?I[T]:I.slice(-1)[0]+1;return F>=this._terminal.cols&&(++k,F=0),{row:k,column:F}},x=S(c),b=S(v);if(x&&b){if(x.row>b.row||x.row===b.row&&x.column>=b.column)throw new Error("invalid range");this._terminal.select(x.column,x.row,(b.row-x.row)*this._terminal.cols-x.column+b.column)}}_handleResize(l){this._rowElements[this._rowElements.length-1].removeEventListener("focus",this._bottomBoundaryFocusListener);for(let c=this._rowContainer.children.length;c<this._terminal.rows;c++)this._rowElements[c]=this._createAccessibilityTreeNode(),this._rowContainer.appendChild(this._rowElements[c]);for(;this._rowElements.length>l;)this._rowContainer.removeChild(this._rowElements.pop());this._rowElements[this._rowElements.length-1].addEventListener("focus",this._bottomBoundaryFocusListener),this._refreshRowsDimensions()}_createAccessibilityTreeNode(){const l=this._coreBrowserService.mainDocument.createElement("div");return l.setAttribute("role","listitem"),l.tabIndex=-1,this._refreshRowDimensions(l),l}_refreshRowsDimensions(){if(this._renderService.dimensions.css.cell.height){this._accessibilityContainer.style.width=\`\${this._renderService.dimensions.css.canvas.width}px\`,this._rowElements.length!==this._terminal.rows&&this._handleResize(this._terminal.rows);for(let l=0;l<this._terminal.rows;l++)this._refreshRowDimensions(this._rowElements[l])}}_refreshRowDimensions(l){l.style.height=\`\${this._renderService.dimensions.css.cell.height}px\`}};s.AccessibilityManager=g=a([d(1,w.IInstantiationService),d(2,C.ICoreBrowserService),d(3,C.IRenderService)],g)},3614:(_,s)=>{function h(p){return p.replace(/\\r?\\n/g,"\\Line truncated
WARNING: This link could potentially be dangerous\`)){const g=window.open();if(g){try{g.opener=null}catch{}g.location.href=f}else console.warn("Opening link blocked as opener could not be cleared")}}s.OscLinkProvider=m=a([d(0,p.IBufferService),d(1,p.IOptionsService),d(2,p.IOscLinkService)],m)},6193:(_,s)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.RenderDebouncer=void 0,s.RenderDebouncer=class{constructor(h,a){this._renderCallback=h,this._coreBrowserService=a,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(h){return this._refreshCallbacks.push(h),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh()))),this._animationFrame}refresh(h,a,d){this._rowCount=d,h=h!==void 0?h:0,a=a!==void 0?a:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,h):h,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,a):a,this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const h=Math.max(this._rowStart,0),a=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(h,a),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const h of this._refreshCallbacks)h(0);this._refreshCallbacks=[]}}},3236:(_,s,h)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.Terminal=void 0;const a=h(3614),d=h(3656),u=h(3551),p=h(9042),m=h(3730),C=h(1680),w=h(3107),f=h(5744),g=h(2950),l=h(1296),c=h(428),v=h(4269),y=h(5114),S=h(8934),x=h(3230),b=h(9312),E=h(4725),B=h(6731),T=h(8055),M=h(8969),k=h(8460),I=h(844),F=h(6114),H=h(8437),z=h(2584),$=h(7399),L=h(5941),R=h(9074),D=h(2585),P=h(5435),U=h(4567),j=h(779);class G extends M.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(O={}){super(O),this.browser=F,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new I.MutableDisposable),this._onCursorMove=this.register(new k.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new k.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new k.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new k.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new k.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new k.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new k.EventEmitter),this._onBlur=this.register(new k.EventEmitter),this._onA11yCharEmitter=this.register(new k.EventEmitter),this._onA11yTabEmitter=this.register(new k.EventEmitter),this._onWillOpen=this.register(new k.EventEmitter),this._setup(),this._decorationService=this._instantiationService.createInstance(R.DecorationService),this._instantiationService.setService(D.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(j.LinkProviderService),this._instantiationService.setService(E.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(m.OscLinkProvider)),this.register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this.register(this._inputHandler.onRequestRefreshRows(((A,N)=>this.refresh(A,N)))),this.register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register(this._inputHandler.onRequestWindowsOptionsReport((A=>this._reportWindowsOptions(A)))),this.register(this._inputHandler.onColor((A=>this._handleColorEvent(A)))),this.register((0,k.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,k.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,k.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,k.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize((A=>this._afterResize(A.cols,A.rows)))),this.register((0,I.toDisposable)((()=>{var A,N;this._customKeyEventHandler=void 0,(N=(A=this.element)==null?void 0:A.parentNode)==null||N.removeChild(this.element)})))}_handleColorEvent(O){if(this._themeService)for(const A of O){let N,W="";switch(A.index){case 256:N="foreground",W="10";break;case 257:N="background",W="11"; Line truncated
WARNING: This link could potentially be dangerous\`)){const g=window.open();if(g){try{g.opener=null}catch{}g.location.href=f}else console.warn("Opening link blocked as opener could not be cleared")}}s.OscLinkProvider=m=a([d(0,p.IBufferService),d(1,p.IOptionsService),d(2,p.IOscLinkService)],m)},6193:(_,s)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.RenderDebouncer=void 0,s.RenderDebouncer=class{constructor(h,a){this._renderCallback=h,this._coreBrowserService=a,this._refreshCallbacks=[]}dispose(){this._animationFrame&&(this._coreBrowserService.window.cancelAnimationFrame(this._animationFrame),this._animationFrame=void 0)}addRefreshCallback(h){return this._refreshCallbacks.push(h),this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh()))),this._animationFrame}refresh(h,a,d){this._rowCount=d,h=h!==void 0?h:0,a=a!==void 0?a:this._rowCount-1,this._rowStart=this._rowStart!==void 0?Math.min(this._rowStart,h):h,this._rowEnd=this._rowEnd!==void 0?Math.max(this._rowEnd,a):a,this._animationFrame||(this._animationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._innerRefresh())))}_innerRefresh(){if(this._animationFrame=void 0,this._rowStart===void 0||this._rowEnd===void 0||this._rowCount===void 0)return void this._runRefreshCallbacks();const h=Math.max(this._rowStart,0),a=Math.min(this._rowEnd,this._rowCount-1);this._rowStart=void 0,this._rowEnd=void 0,this._renderCallback(h,a),this._runRefreshCallbacks()}_runRefreshCallbacks(){for(const h of this._refreshCallbacks)h(0);this._refreshCallbacks=[]}}},3236:(_,s,h)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.Terminal=void 0;const a=h(3614),d=h(3656),u=h(3551),p=h(9042),m=h(3730),C=h(1680),w=h(3107),f=h(5744),g=h(2950),l=h(1296),c=h(428),v=h(4269),y=h(5114),S=h(8934),x=h(3230),b=h(9312),E=h(4725),B=h(6731),T=h(8055),M=h(8969),k=h(8460),I=h(844),F=h(6114),H=h(8437),z=h(2584),$=h(7399),L=h(5941),R=h(9074),D=h(2585),P=h(5435),U=h(4567),j=h(779);class G extends M.CoreTerminal{get onFocus(){return this._onFocus.event}get onBlur(){return this._onBlur.event}get onA11yChar(){return this._onA11yCharEmitter.event}get onA11yTab(){return this._onA11yTabEmitter.event}get onWillOpen(){return this._onWillOpen.event}constructor(O={}){super(O),this.browser=F,this._keyDownHandled=!1,this._keyDownSeen=!1,this._keyPressHandled=!1,this._unprocessedDeadKey=!1,this._accessibilityManager=this.register(new I.MutableDisposable),this._onCursorMove=this.register(new k.EventEmitter),this.onCursorMove=this._onCursorMove.event,this._onKey=this.register(new k.EventEmitter),this.onKey=this._onKey.event,this._onRender=this.register(new k.EventEmitter),this.onRender=this._onRender.event,this._onSelectionChange=this.register(new k.EventEmitter),this.onSelectionChange=this._onSelectionChange.event,this._onTitleChange=this.register(new k.EventEmitter),this.onTitleChange=this._onTitleChange.event,this._onBell=this.register(new k.EventEmitter),this.onBell=this._onBell.event,this._onFocus=this.register(new k.EventEmitter),this._onBlur=this.register(new k.EventEmitter),this._onA11yCharEmitter=this.register(new k.EventEmitter),this._onA11yTabEmitter=this.register(new k.EventEmitter),this._onWillOpen=this.register(new k.EventEmitter),this._setup(),this._decorationService=this._instantiationService.createInstance(R.DecorationService),this._instantiationService.setService(D.IDecorationService,this._decorationService),this._linkProviderService=this._instantiationService.createInstance(j.LinkProviderService),this._instantiationService.setService(E.ILinkProviderService,this._linkProviderService),this._linkProviderService.registerLinkProvider(this._instantiationService.createInstance(m.OscLinkProvider)),this.register(this._inputHandler.onRequestBell((()=>this._onBell.fire()))),this.register(this._inputHandler.onRequestRefreshRows(((A,N)=>this.refresh(A,N)))),this.register(this._inputHandler.onRequestSendFocus((()=>this._reportFocus()))),this.register(this._inputHandler.onRequestReset((()=>this.reset()))),this.register(this._inputHandler.onRequestWindowsOptionsReport((A=>this._reportWindowsOptions(A)))),this.register(this._inputHandler.onColor((A=>this._handleColorEvent(A)))),this.register((0,k.forwardEvent)(this._inputHandler.onCursorMove,this._onCursorMove)),this.register((0,k.forwardEvent)(this._inputHandler.onTitleChange,this._onTitleChange)),this.register((0,k.forwardEvent)(this._inputHandler.onA11yChar,this._onA11yCharEmitter)),this.register((0,k.forwardEvent)(this._inputHandler.onA11yTab,this._onA11yTabEmitter)),this.register(this._bufferService.onResize((A=>this._afterResize(A.cols,A.rows)))),this.register((0,I.toDisposable)((()=>{var A,N;this._customKeyEventHandler=void 0,(N=(A=this.element)==null?void 0:A.parentNode)==null||N.removeChild(this.element)})))}_handleColorEvent(O){if(this._themeService)for(const A of O){let N,W="";switch(A.index){case 256:N="foreground",W="10";break;case 257:N="background",W="11"; Line truncated
\`:\`
\`)}clearSelection(){this._model.clearSelection(),this._removeMouseDownListeners(),this.refresh(),this._onSelectionChange.fire()}refresh(b){this._refreshAnimationFrame||(this._refreshAnimationFrame=this._coreBrowserService.window.requestAnimationFrame((()=>this._refresh()))),g.isLinux&&b&&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(b){const E=this._getMouseBufferCoords(b),B=this._model.finalSelectionStart,T=this._model.finalSelectionEnd;return!!(B&&T&&E)&&this._areCoordsInSelection(E,B,T)}isCellInSelection(b,E){const B=this._model.finalSelectionStart,T=this._model.finalSelectionEnd;return!(!B||!T)&&this._areCoordsInSelection([b,E],B,T)}_areCoordsInSelection(b,E,B){return b[1]>E[1]&&b[1]<B[1]||E[1]===B[1]&&b[1]===E[1]&&b[0]>=E[0]&&b[0]<B[0]||E[1]<B[1]&&b[1]===B[1]&&b[0]<B[0]||E[1]<B[1]&&b[1]===E[1]&&b[0]>=E[0]}_selectWordAtCursor(b,E){var M,k;const B=(k=(M=this._linkifier.currentLink)==null?void 0:M.link)==null?void 0:k.range;if(B)return this._model.selectionStart=[B.start.x-1,B.start.y-1],this._model.selectionStartLength=(0,l.getRangeLength)(B,this._bufferService.cols),this._model.selectionEnd=void 0,!0;const T=this._getMouseBufferCoords(b);return!!T&&(this._selectWordAt(T,E),this._model.selectionEnd=void 0,!0)}selectAll(){this._model.isSelectAllActive=!0,this.refresh(),this._onSelectionChange.fire()}selectLines(b,E){this._model.clearSelection(),b=Math.max(b,0),E=Math.min(E,this._bufferService.buffer.lines.length-1),this._model.selectionStart=[0,b],this._model.selectionEnd=[this._bufferService.cols,E],this.refresh(),this._onSelectionChange.fire()}_handleTrim(b){this._model.handleTrim(b)&&this.refresh()}_getMouseBufferCoords(b){const E=this._mouseService.getCoords(b,this._screenElement,this._bufferService.cols,this._bufferService.rows,!0);if(E)return E[0]--,E[1]--,E[1]+=this._bufferService.buffer.ydisp,E}_getMouseEventScrollAmount(b){let E=(0,u.getCoordsRelativeToElement)(this._coreBrowserService.window,b,this._screenElement)[1];const B=this._renderService.dimensions.css.canvas.height;return E>=0&&E<=B?0:(E>B&&(E-=B),E=Math.min(Math.max(E,-50),50),E/=50,E/Math.abs(E)+Math.round(14*E))}shouldForceSelection(b){return g.isMac?b.altKey&&this._optionsService.rawOptions.macOptionClickForcesSelection:b.shiftKey}handleMouseDown(b){if(this._mouseDownTimeStamp=b.timeStamp,(b.button!==2||!this.hasSelection)&&b.button===0){if(!this._enabled){if(!this.shouldForceSelection(b))return;b.stopPropagation()}b.preventDefault(),this._dragScrollAmount=0,this._enabled&&b.shiftKey?this._handleIncrementalClick(b):b.detail===1?this._handleSingleClick(b):b.detail===2?this._handleDoubleClick(b):b.detail===3&&this._handleTripleClick(b),this._addMouseDownListeners(),this.refresh(!0)}}_addMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.addEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.addEventListener("mouseup",this._mouseUpListener)),this._dragScrollIntervalTimer=this._coreBrowserService.window.setInterval((()=>this._dragScroll()),50)}_removeMouseDownListeners(){this._screenElement.ownerDocument&&(this._screenElement.ownerDocument.removeEventListener("mousemove",this._mouseMoveListener),this._screenElement.ownerDocument.removeEventListener("mouseup",this._mouseUpListener)),this._coreBrowserService.window.clearInterval(this._dragScrollIntervalTimer),this._dragScrollIntervalTimer=void 0}_handleIncrementalClick(b){this._model.selectionStart&&(this._model.selectionEnd=this._getMouseBufferCoords(b))}_handleSingleClick(b){if(this._model.selectionStartLength=0,this._model.isSelectAllActive=!1,this._activeSelectionMode=this.shouldColumnSelect(b)?3:0,this._model.selectionStart=this._getMouseBufferCoords(b),!this._model.selectionStart)return;this._model.selectionEnd=void 0;const E=this._bufferService.buffer.lines.get(this._model.selectionStart[1]);E&&E.length!==this._model.selectionStart[0]&&E.hasWidth(this._model.selectionStart[0])===0&&this._model.selectionStart[0]++}_handleDoubleClick(b){this._selectWordAtCursor(b,!0)&&(this._activeSelectionMode=1)}_handleTripleClick(b){const E=this._getMouseBufferCoords(b);E&&(this._activeSelectionMode=2,this._selectLineAt(E[1]))}shouldColumnSelect(b){return b.altKey&&!(g.isMac&&this._optionsService.rawOptions.macOptionClickForcesSelection)}_handleMouseMove(b){if(b.stopImmediatePropagation(),!this._model.selectionStart)return;const E=this._model.selectionEnd?[this._model.selectionEnd[0],this._model.selectionEnd[1]]:null;if(this._model.selectionEnd=this._getMouseBufferCoords(b),!this._model.selectionEnd)return void this.refresh(!0);this._activeSelectionMode===2?this._model.selectionEnd[1]<this._model.selectionStart[1]?this._model.selectionEnd[0]=0:this._model.selectionEnd[0]=this._buf Line truncated
\`,u.VT="\\v",u.FF="\\f",u.CR="\\r",u.SO="",u.SI="",u.DLE="",u.DC1="",u.DC2="",u.DC3="",u.DC4="",u.NAK="",u.SYN="",u.ETB="",u.CAN="",u.EM="",u.SUB="",u.ESC="\\x1B",u.FS="",u.GS="",u.RS="",u.US="",u.SP=" ",u.DEL=""})(h||(s.C0=h={})),(function(u){u.PAD="€",u.HOP="",u.BPH="‚",u.NBH="ƒ",u.IND="„",u.NEL="…",u.SSA="†",u.ESA="‡",u.HTS="ˆ",u.HTJ="‰",u.VTS="Š",u.PLD="‹",u.PLU="Œ",u.RI="",u.SS2="Ž",u.SS3="",u.DCS="",u.PU1="‘",u.PU2="’",u.STS="“",u.CCH="”",u.MW="•",u.SPA="–",u.EPA="—",u.SOS="˜",u.SGCI="™",u.SCI="š",u.CSI="›",u.ST="œ",u.OSC="",u.PM="ž",u.APC="Ÿ"})(a||(s.C1=a={})),(function(u){u.ST=\`\${h.ESC}\\\\\`})(d||(s.C1_ESCAPED=d={}))},7399:(_,s,h)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.evaluateKeyboardEvent=void 0;const a=h(2584),d={48:["0",")"],49:["1","!"],50:["2","@"],51:["3","#"],52:["4","$"],53:["5","%"],54:["6","^"],55:["7","&"],56:["8","*"],57:["9","("],186:[";",":"],187:["=","+"],188:[",","<"],189:["-","_"],190:[".",">"],191:["/","?"],192:["\`","~"],219:["[","{"],220:["\\\\","|"],221:["]","}"],222:["'",'"']};s.evaluateKeyboardEvent=function(u,p,m,C){const w={type:0,cancel:!1,key:void 0},f=(u.shiftKey?1:0)|(u.altKey?2:0)|(u.ctrlKey?4:0)|(u.metaKey?8:0);switch(u.keyCode){case 0:u.key==="UIKeyInputUpArrow"?w.key=p?a.C0.ESC+"OA":a.C0.ESC+"[A":u.key==="UIKeyInputLeftArrow"?w.key=p?a.C0.ESC+"OD":a.C0.ESC+"[D":u.key==="UIKeyInputRightArrow"?w.key=p?a.C0.ESC+"OC":a.C0.ESC+"[C":u.key==="UIKeyInputDownArrow"&&(w.key=p?a.C0.ESC+"OB":a.C0.ESC+"[B");break;case 8:w.key=u.ctrlKey?"\\b":a.C0.DEL,u.altKey&&(w.key=a.C0.ESC+w.key);break;case 9:if(u.shiftKey){w.key=a.C0.ESC+"[Z";break}w.key=a.C0.HT,w.cancel=!0;break;case 13:w.key=u.altKey?a.C0.ESC+a.C0.CR:a.C0.CR,w.cancel=!0;break;case 27:w.key=a.C0.ESC,u.altKey&&(w.key=a.C0.ESC+a.C0.ESC),w.cancel=!0;break;case 37:if(u.metaKey)break;f?(w.key=a.C0.ESC+"[1;"+(f+1)+"D",w.key===a.C0.ESC+"[1;3D"&&(w.key=a.C0.ESC+(m?"b":"[1;5D"))):w.key=p?a.C0.ESC+"OD":a.C0.ESC+"[D";break;case 39:if(u.metaKey)break;f?(w.key=a.C0.ESC+"[1;"+(f+1)+"C",w.key===a.C0.ESC+"[1;3C"&&(w.key=a.C0.ESC+(m?"f":"[1;5C"))):w.key=p?a.C0.ESC+"OC":a.C0.ESC+"[C";break;case 38:if(u.metaKey)break;f?(w.key=a.C0.ESC+"[1;"+(f+1)+"A",m||w.key!==a.C0.ESC+"[1;3A"||(w.key=a.C0.ESC+"[1;5A")):w.key=p?a.C0.ESC+"OA":a.C0.ESC+"[A";break;case 40:if(u.metaKey)break;f?(w.key=a.C0.ESC+"[1;"+(f+1)+"B",m||w.key!==a.C0.ESC+"[1;3B"||(w.key=a.C0.ESC+"[1;5B")):w.key=p?a.C0.ESC+"OB":a.C0.ESC+"[B";break;case 45:u.shiftKey||u.ctrlKey||(w.key=a.C0.ESC+"[2~");break;case 46:w.key=f?a.C0.ESC+"[3;"+(f+1)+"~":a.C0.ESC+"[3~";break;case 36:w.key=f?a.C0.ESC+"[1;"+(f+1)+"H":p?a.C0.ESC+"OH":a.C0.ESC+"[H";break;case 35:w.key=f?a.C0.ESC+"[1;"+(f+1)+"F":p?a.C0.ESC+"OF":a.C0.ESC+"[F";break;case 33:u.shiftKey?w.type=2:u.ctrlKey?w.key=a.C0.ESC+"[5;"+(f+1)+"~":w.key=a.C0.ESC+"[5~";break;case 34:u.shiftKey?w.type=3:u.ctrlKey?w.key=a.C0.ESC+"[6;"+(f+1)+"~":w.key=a.C0.ESC+"[6~";break;case 112:w.key=f?a.C0.ESC+"[1;"+(f+1)+"P":a.C0.ESC+"OP";break;case 113:w.key=f?a.C0.ESC+"[1;"+(f+1)+"Q":a.C0.ESC+"OQ";break;case 114:w.key=f?a.C0.ESC+"[1;"+(f+1)+"R":a.C0.ESC+"OR";break;case 115:w.key=f?a.C0.ESC+"[1;"+(f+1)+"S":a.C0.ESC+"OS";break;case 116:w.key=f?a.C0.ESC+"[15;"+(f+1)+"~":a.C0.ESC+"[15~";break;case 117:w.key=f?a.C0.ESC+"[17;"+(f+1)+"~":a.C0.ESC+"[17~";break;case 118:w.key=f?a.C0.ESC+"[18;"+(f+1)+"~":a.C0.ESC+"[18~";break;case 119:w.key=f?a.C0.ESC+"[19;"+(f+1)+"~":a.C0.ESC+"[19~";break;case 120:w.key=f?a.C0.ESC+"[20;"+(f+1)+"~":a.C0.ESC+"[20~";break;case 121:w.key=f?a.C0.ESC+"[21;"+(f+1)+"~":a.C0.ESC+"[21~";break;case 122:w.key=f?a.C0.ESC+"[23;"+(f+1)+"~":a.C0.ESC+"[23~";break;case 123:w.key=f?a.C0.ESC+"[24;"+(f+1)+"~":a.C0.ESC+"[24~";break;default:if(!u.ctrlKey||u.shiftKey||u.altKey||u.metaKey)if(m&&!C||!u.altKey||u.metaKey)!m||u.altKey||u.ctrlKey||u.shiftKey||!u.metaKey?u.key&&!u.ctrlKey&&!u.altKey&&!u.metaKey&&u.keyCode>=48&&u.key.length===1?w.key=u.key:u.key&&u.ctrlKey&&(u.key==="_"&&(w.key=a.C0.US),u.key==="@"&&(w.key=a.C0.NUL)):u.keyCode===65&&(w.type=1);else{const g=d[u.keyCode],l=g==null?void 0:g[u.shiftKey?1:0];if(l)w.key=a.C0.ESC+l;else if(u.keyCode>=65&&u.keyCode<=90){const c=u.ctrlKey?u.keyCode-64:u.keyCode+32;let v=String.fromCharCode(c);u.shiftKey&&(v=v.toUpperCase()),w.key=a.C0.ESC+v}else if(u.keyCode===32)w.key=a.C0.ESC+(u.ctrlKey?a.C0.NUL:" ");else if(u.key==="Dead"&&u.code.startsWith("Key")){let c=u.code.slice(3,4);u.shiftKey||(c=c.toLowerCase()),w.key=a.C0.ESC+c,w.cancel=!0}}else u.keyCode>=65&&u.keyCode<=90?w.key=String.fromCharCode(u.keyCode-64):u.keyCode===32?w.key=a.C0.NUL:u.keyCode>=51&&u.keyCode<=55?w.key=String.fromCharCode(u.keyCode-51+27):u.keyCode===56?w.key=a.C0.DEL:u.keyCode===219?w.key=a.C0.ESC:u.keyCode===220?w.key=a.C0.FS:u.keyCode===221&&(w.key=a.C0.GS)}return w}},482:(_,s)=>{Object.defineProperty(s,"__esModule",{value:!0}),s.Utf8ToUtf32=s.StringToUtf32=s.utf32ToString=s.stringFromCodePoint=void 0,s.stringFromCodePoint=function(h){return h>65535?(h-=65536,String.f Line truncated
\`,l)}paste(g){this._core.paste(g)}refresh(g,l){this._verifyIntegers(g,l),this._core.refresh(g,l)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(g){this._addonManager.loadAddon(this,g)}static get strings(){return s}_verifyIntegers(...g){for(const l of g)if(l===1/0||isNaN(l)||l%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...g){for(const l of g)if(l&&(l===1/0||isNaN(l)||l%1!=0||l<0))throw new Error("This API only accepts positive integers")}}_.Terminal=w})(),o})()))})(Hi)),Hi.exports}var co=lo(),zi={exports:{}},Hs;function uo(){return Hs||(Hs=1,(function(i,e){(function(t,r){i.exports=r()})(self,(()=>(()=>{var t={};return(()=>{var r=t;Object.defineProperty(r,"__esModule",{value:!0}),r.FitAddon=void 0,r.FitAddon=class{activate(n){this._terminal=n}dispose(){}fit(){const n=this.proposeDimensions();if(!n||!this._terminal||isNaN(n.cols)||isNaN(n.rows))return;const o=this._terminal._core;this._terminal.rows===n.rows&&this._terminal.cols===n.cols||(o._renderService.clear(),this._terminal.resize(n.cols,n.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const n=this._terminal._core,o=n._renderService.dimensions;if(o.css.cell.width===0||o.css.cell.height===0)return;const _=this._terminal.options.scrollback===0?0:n.viewport.scrollBarWidth,s=window.getComputedStyle(this._terminal.element.parentElement),h=parseInt(s.getPropertyValue("height")),a=Math.max(0,parseInt(s.getPropertyValue("width"))),d=window.getComputedStyle(this._terminal.element),u=h-(parseInt(d.getPropertyValue("padding-top"))+parseInt(d.getPropertyValue("padding-bottom"))),p=a-(parseInt(d.getPropertyValue("padding-right"))+parseInt(d.getPropertyValue("padding-left")))-_;return{cols:Math.max(2,Math.floor(p/o.css.cell.width)),rows:Math.max(1,Math.floor(u/o.css.cell.height))}}}})(),t})()))})(zi)),zi.exports}var fo=uo(),Wi={exports:{}},zs;function _o(){return zs||(zs=1,(function(i,e){(function(t,r){i.exports=r()})(self,(()=>(()=>{var t={6:(_,s)=>{function h(d){try{const u=new URL(d),p=u.password&&u.username?\`\${u.protocol}//\${u.username}:\${u.password}@\${u.host}\`:u.username?\`\${u.protocol}//\${u.username}@\${u.host}\`:\`\${u.protocol}//\${u.host}\`;return d.toLocaleLowerCase().startsWith(p.toLocaleLowerCase())}catch{return!1}}Object.defineProperty(s,"__esModule",{value:!0}),s.LinkComputer=s.WebLinkProvider=void 0,s.WebLinkProvider=class{constructor(d,u,p,m={}){this._terminal=d,this._regex=u,this._handler=p,this._options=m}provideLinks(d,u){const p=a.computeLink(d,this._regex,this._terminal,this._handler);u(this._addCallbacks(p))}_addCallbacks(d){return d.map((u=>(u.leave=this._options.leave,u.hover=(p,m)=>{if(this._options.hover){const{range:C}=u;this._options.hover(p,m,C)}},u)))}};class a{static computeLink(u,p,m,C){const w=new RegExp(p.source,(p.flags||"")+"g"),[f,g]=a._getWindowedLineStrings(u-1,m),l=f.join("");let c;const v=[];for(;c=w.exec(l);){const y=c[0];if(!h(y))continue;const[S,x]=a._mapStrIdx(m,g,0,c.index),[b,E]=a._mapStrIdx(m,S,x,y.length);if(S===-1||x===-1||b===-1||E===-1)continue;const B={start:{x:x+1,y:S+1},end:{x:E,y:b+1}};v.push({range:B,text:y,activate:C})}return v}static _getWindowedLineStrings(u,p){let m,C=u,w=u,f=0,g="";const l=[];if(m=p.buffer.active.getLine(u)){const c=m.translateToString(!0);if(m.isWrapped&&c[0]!==" "){for(f=0;(m=p.buffer.active.getLine(--C))&&f<2048&&(g=m.translateToString(!0),f+=g.length,l.push(g),m.isWrapped&&g.indexOf(" ")===-1););l.reverse()}for(l.push(c),f=0;(m=p.buffer.active.getLine(++w))&&m.isWrapped&&f<2048&&(g=m.translateToString(!0),f+=g.length,l.push(g),g.indexOf(" ")===-1););}return[l,C]}static _mapStrIdx(u,p,m,C){const w=u.buffer.active,f=w.getNullCell();let g=m;for(;C;){const l=w.getLine(p);if(!l)return[-1,-1];for(let c=g;c<l.length;++c){l.getCell(c,f);const v=f.getChars();if(f.getWidth()&&(C-=v.length||1,c===l.length-1&&v==="")){const y=w.getLine(p+1);y&&y.isWrapped&&(y.getCell(0,f),f.getWidth()===2&&(C+=1))}if(C<0)return[p,c]}p++,g=0}return[p,g]}}s.LinkComputer=a}},r={};function n(_){var s=r[_];if(s!==void 0)return s.exports;var h=r[_]={exports:{}};return t[_](h,h.exports,n),h.exports}var o={};return(()=>{var _=o;Object.defineProperty(_,"__esModule",{value:!0}),_.WebLinksAddon=void 0;const s=n(6),h=/(https?|HTTPS?):[/]{2}[^\\s"'!*(){}|\\\\\\^<>\`]*[^\\s"':,.!?{}|\\\\\\^~\\[\\]\`()<>]/;function a(d,u){const p=window.open();if(p){try{p.opener=null}catch{}p.location.href=u}else console.warn("Opening link blocked as opener could not be cleared")}_.WebLinksAddon=class{constructor(d=a,u={}){this._handler=d,this._options=u}activate(d){this._terminal=d;const u=this._options,p=u.urlRegex||h;this._linkProvider=this._terminal.registerLinkProvider(new s.WebLinkProvider(this._terminal,p,this._handler,u))}dispose(){var d;(d=this._linkProvider)==null||d.dispose()}}})(),o})()))})(Wi)),Wi.exports}var go=_o();/**
\`,l)}paste(g){this._core.paste(g)}refresh(g,l){this._verifyIntegers(g,l),this._core.refresh(g,l)}reset(){this._core.reset()}clearTextureAtlas(){this._core.clearTextureAtlas()}loadAddon(g){this._addonManager.loadAddon(this,g)}static get strings(){return s}_verifyIntegers(...g){for(const l of g)if(l===1/0||isNaN(l)||l%1!=0)throw new Error("This API only accepts integers")}_verifyPositiveIntegers(...g){for(const l of g)if(l&&(l===1/0||isNaN(l)||l%1!=0||l<0))throw new Error("This API only accepts positive integers")}}_.Terminal=w})(),o})()))})(Hi)),Hi.exports}var fo=uo(),zi={exports:{}},zs;function _o(){return zs||(zs=1,(function(i,e){(function(t,r){i.exports=r()})(self,(()=>(()=>{var t={};return(()=>{var r=t;Object.defineProperty(r,"__esModule",{value:!0}),r.FitAddon=void 0,r.FitAddon=class{activate(n){this._terminal=n}dispose(){}fit(){const n=this.proposeDimensions();if(!n||!this._terminal||isNaN(n.cols)||isNaN(n.rows))return;const o=this._terminal._core;this._terminal.rows===n.rows&&this._terminal.cols===n.cols||(o._renderService.clear(),this._terminal.resize(n.cols,n.rows))}proposeDimensions(){if(!this._terminal||!this._terminal.element||!this._terminal.element.parentElement)return;const n=this._terminal._core,o=n._renderService.dimensions;if(o.css.cell.width===0||o.css.cell.height===0)return;const _=this._terminal.options.scrollback===0?0:n.viewport.scrollBarWidth,s=window.getComputedStyle(this._terminal.element.parentElement),h=parseInt(s.getPropertyValue("height")),a=Math.max(0,parseInt(s.getPropertyValue("width"))),d=window.getComputedStyle(this._terminal.element),u=h-(parseInt(d.getPropertyValue("padding-top"))+parseInt(d.getPropertyValue("padding-bottom"))),p=a-(parseInt(d.getPropertyValue("padding-right"))+parseInt(d.getPropertyValue("padding-left")))-_;return{cols:Math.max(2,Math.floor(p/o.css.cell.width)),rows:Math.max(1,Math.floor(u/o.css.cell.height))}}}})(),t})()))})(zi)),zi.exports}var go=_o(),Wi={exports:{}},Ws;function po(){return Ws||(Ws=1,(function(i,e){(function(t,r){i.exports=r()})(self,(()=>(()=>{var t={6:(_,s)=>{function h(d){try{const u=new URL(d),p=u.password&&u.username?\`\${u.protocol}//\${u.username}:\${u.password}@\${u.host}\`:u.username?\`\${u.protocol}//\${u.username}@\${u.host}\`:\`\${u.protocol}//\${u.host}\`;return d.toLocaleLowerCase().startsWith(p.toLocaleLowerCase())}catch{return!1}}Object.defineProperty(s,"__esModule",{value:!0}),s.LinkComputer=s.WebLinkProvider=void 0,s.WebLinkProvider=class{constructor(d,u,p,m={}){this._terminal=d,this._regex=u,this._handler=p,this._options=m}provideLinks(d,u){const p=a.computeLink(d,this._regex,this._terminal,this._handler);u(this._addCallbacks(p))}_addCallbacks(d){return d.map((u=>(u.leave=this._options.leave,u.hover=(p,m)=>{if(this._options.hover){const{range:C}=u;this._options.hover(p,m,C)}},u)))}};class a{static computeLink(u,p,m,C){const w=new RegExp(p.source,(p.flags||"")+"g"),[f,g]=a._getWindowedLineStrings(u-1,m),l=f.join("");let c;const v=[];for(;c=w.exec(l);){const y=c[0];if(!h(y))continue;const[S,x]=a._mapStrIdx(m,g,0,c.index),[b,E]=a._mapStrIdx(m,S,x,y.length);if(S===-1||x===-1||b===-1||E===-1)continue;const B={start:{x:x+1,y:S+1},end:{x:E,y:b+1}};v.push({range:B,text:y,activate:C})}return v}static _getWindowedLineStrings(u,p){let m,C=u,w=u,f=0,g="";const l=[];if(m=p.buffer.active.getLine(u)){const c=m.translateToString(!0);if(m.isWrapped&&c[0]!==" "){for(f=0;(m=p.buffer.active.getLine(--C))&&f<2048&&(g=m.translateToString(!0),f+=g.length,l.push(g),m.isWrapped&&g.indexOf(" ")===-1););l.reverse()}for(l.push(c),f=0;(m=p.buffer.active.getLine(++w))&&m.isWrapped&&f<2048&&(g=m.translateToString(!0),f+=g.length,l.push(g),g.indexOf(" ")===-1););}return[l,C]}static _mapStrIdx(u,p,m,C){const w=u.buffer.active,f=w.getNullCell();let g=m;for(;C;){const l=w.getLine(p);if(!l)return[-1,-1];for(let c=g;c<l.length;++c){l.getCell(c,f);const v=f.getChars();if(f.getWidth()&&(C-=v.length||1,c===l.length-1&&v==="")){const y=w.getLine(p+1);y&&y.isWrapped&&(y.getCell(0,f),f.getWidth()===2&&(C+=1))}if(C<0)return[p,c]}p++,g=0}return[p,g]}}s.LinkComputer=a}},r={};function n(_){var s=r[_];if(s!==void 0)return s.exports;var h=r[_]={exports:{}};return t[_](h,h.exports,n),h.exports}var o={};return(()=>{var _=o;Object.defineProperty(_,"__esModule",{value:!0}),_.WebLinksAddon=void 0;const s=n(6),h=/(https?|HTTPS?):[/]{2}[^\\s"'!*(){}|\\\\\\^<>\`]*[^\\s"':,.!?{}|\\\\\\^~\\[\\]\`()<>]/;function a(d,u){const p=window.open();if(p){try{p.opener=null}catch{}p.location.href=u}else console.warn("Opening link blocked as opener could not be cleared")}_.WebLinksAddon=class{constructor(d=a,u={}){this._handler=d,this._options=u}activate(d){this._terminal=d;const u=this._options,p=u.urlRegex||h;this._linkProvider=this._terminal.registerLinkProvider(new s.WebLinkProvider(this._terminal,p,this._handler,u))}dispose(){var d;(d=this._linkProvider)==null||d.dispose()}}})(),o})()))})(Wi)),Wi.exports}var vo=po();/**
* Copyright (c) 2014-2024 The xterm.js authors. All rights reserved.
* @license MIT
*
@@ -60,13 +60,13 @@ WARNING: This link could potentially be dangerous\`)){const g=window.open();if(g
* Fabrice Bellard's javascript vt100 for jslinux:
* http://bellard.org/jslinux/
* Copyright (c) 2011 Fabrice Bellard
*/var po=(i,e,t,r)=>{for(var n=e,o=i.length-1,_;o>=0;o--)(_=i[o])&&(n=_(n)||n);return n},vo=(i,e)=>(t,r)=>e(t,r,i),mo=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Ws.isErrorNoTelemetry(e)?new Ws(e.message+\`
*/var mo=(i,e,t,r)=>{for(var n=e,o=i.length-1,_;o>=0;o--)(_=i[o])&&(n=_(n)||n);return n},wo=(i,e)=>(t,r)=>e(t,r,i),bo=class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout(()=>{throw e.stack?Us.isErrorNoTelemetry(e)?new Us(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)}},wo=new mo;function Ui(i){bo(i)||wo.onUnexpectedError(i)}var ws="Canceled";function bo(i){return i instanceof So?!0:i instanceof Error&&i.name===ws&&i.message===ws}var So=class extends Error{constructor(){super(ws),this.name=this.message}},Ws=class bs extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof bs)return e;let t=new bs;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}},yo;(i=>{function e(o){return o<0}i.isLessThan=e;function t(o){return o<=0}i.isLessThanOrEqual=t;function r(o){return o>0}i.isGreaterThan=r;function n(o){return o===0}i.isNeitherLessOrGreaterThan=n,i.greaterThan=1,i.lessThan=-1,i.neitherLessOrGreaterThan=0})(yo||(yo={}));function Co(i,e){let t=this,r=!1,n;return function(){return r||(r=!0,e||(n=i.apply(t,arguments))),n}}var sn;(i=>{function e(v){return v&&typeof v=="object"&&typeof v[Symbol.iterator]=="function"}i.is=e;let t=Object.freeze([]);function r(){return t}i.empty=r;function*n(v){yield v}i.single=n;function o(v){return e(v)?v:n(v)}i.wrap=o;function _(v){return v||t}i.from=_;function*s(v){for(let y=v.length-1;y>=0;y--)yield v[y]}i.reverse=s;function h(v){return!v||v[Symbol.iterator]().next().done===!0}i.isEmpty=h;function a(v){return v[Symbol.iterator]().next().value}i.first=a;function d(v,y){let S=0;for(let x of v)if(y(x,S++))return!0;return!1}i.some=d;function u(v,y){for(let S of v)if(y(S))return S}i.find=u;function*p(v,y){for(let S of v)y(S)&&(yield S)}i.filter=p;function*m(v,y){let S=0;for(let x of v)yield y(x,S++)}i.map=m;function*C(v,y){let S=0;for(let x of v)yield*y(x,S++)}i.flatMap=C;function*w(...v){for(let y of v)yield*y}i.concat=w;function f(v,y,S){let x=S;for(let b of v)x=y(x,b);return x}i.reduce=f;function*g(v,y,S=v.length){for(y<0&&(y+=v.length),S<0?S+=v.length:S>v.length&&(S=v.length);y<S;y++)yield v[y]}i.slice=g;function l(v,y=Number.POSITIVE_INFINITY){let S=[];if(y===0)return[S,v];let x=v[Symbol.iterator]();for(let b=0;b<y;b++){let E=x.next();if(E.done)return[S,i.empty()];S.push(E.value)}return[S,{[Symbol.iterator](){return x}}]}i.consume=l;async function c(v){let y=[];for await(let S of v)y.push(S);return Promise.resolve(y)}i.asyncToArray=c})(sn||(sn={}));function rn(i){if(sn.is(i)){let e=[];for(let t of i)if(t)try{t.dispose()}catch(r){e.push(r)}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 nn(...i){return Se(()=>rn(i))}function Se(i){return{dispose:Co(()=>{i()})}}var on=class an{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{rn(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?an.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),void 0)}};on.DISABLE_DISPOSED_WARNING=!1;var kt=on,Pe=class{constructor(){this._store=new kt,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)}};Pe.None=Object.freeze({dispose(){}});var Ot=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Ts=typeof process<"u"&&"title"in process,Ii=Ts?"node":navigator.userAgent,xo=Ts?"node":navigator.platform,Eo=Ii.includes("Firefox"),Lo=Ii.includes("Edge"),hn=/^((?!chrome|android).)*safari/i.test(Ii);function ko(){if(!hn)return 0;let i=Ii.match(/Version\\/(\\d+)/);return i===null||i.length<2?0:parseInt(i[1])}xo.indexOf("Linux")>=0;var Ao="",_e=0,ge=0,pe=0,le=0,Re={css:"#00000000",rgba:0},Ce;(i=>{function e(n,o,_,s){return s!==void 0?\`#\${lt(n)}\${lt(o)}\${lt(_)}\${lt(s)}\`:\`#\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)}},So=new bo;function Ui(i){yo(i)||So.onUnexpectedError(i)}var ws="Canceled";function yo(i){return i instanceof Co?!0:i instanceof Error&&i.name===ws&&i.message===ws}var Co=class extends Error{constructor(){super(ws),this.name=this.message}},Us=class bs extends Error{constructor(e){super(e),this.name="CodeExpectedError"}static fromError(e){if(e instanceof bs)return e;let t=new bs;return t.message=e.message,t.stack=e.stack,t}static isErrorNoTelemetry(e){return e.name==="CodeExpectedError"}},xo;(i=>{function e(o){return o<0}i.isLessThan=e;function t(o){return o<=0}i.isLessThanOrEqual=t;function r(o){return o>0}i.isGreaterThan=r;function n(o){return o===0}i.isNeitherLessOrGreaterThan=n,i.greaterThan=1,i.lessThan=-1,i.neitherLessOrGreaterThan=0})(xo||(xo={}));function Eo(i,e){let t=this,r=!1,n;return function(){return r||(r=!0,e||(n=i.apply(t,arguments))),n}}var rn;(i=>{function e(v){return v&&typeof v=="object"&&typeof v[Symbol.iterator]=="function"}i.is=e;let t=Object.freeze([]);function r(){return t}i.empty=r;function*n(v){yield v}i.single=n;function o(v){return e(v)?v:n(v)}i.wrap=o;function _(v){return v||t}i.from=_;function*s(v){for(let y=v.length-1;y>=0;y--)yield v[y]}i.reverse=s;function h(v){return!v||v[Symbol.iterator]().next().done===!0}i.isEmpty=h;function a(v){return v[Symbol.iterator]().next().value}i.first=a;function d(v,y){let S=0;for(let x of v)if(y(x,S++))return!0;return!1}i.some=d;function u(v,y){for(let S of v)if(y(S))return S}i.find=u;function*p(v,y){for(let S of v)y(S)&&(yield S)}i.filter=p;function*m(v,y){let S=0;for(let x of v)yield y(x,S++)}i.map=m;function*C(v,y){let S=0;for(let x of v)yield*y(x,S++)}i.flatMap=C;function*w(...v){for(let y of v)yield*y}i.concat=w;function f(v,y,S){let x=S;for(let b of v)x=y(x,b);return x}i.reduce=f;function*g(v,y,S=v.length){for(y<0&&(y+=v.length),S<0?S+=v.length:S>v.length&&(S=v.length);y<S;y++)yield v[y]}i.slice=g;function l(v,y=Number.POSITIVE_INFINITY){let S=[];if(y===0)return[S,v];let x=v[Symbol.iterator]();for(let b=0;b<y;b++){let E=x.next();if(E.done)return[S,i.empty()];S.push(E.value)}return[S,{[Symbol.iterator](){return x}}]}i.consume=l;async function c(v){let y=[];for await(let S of v)y.push(S);return Promise.resolve(y)}i.asyncToArray=c})(rn||(rn={}));function nn(i){if(rn.is(i)){let e=[];for(let t of i)if(t)try{t.dispose()}catch(r){e.push(r)}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 on(...i){return Se(()=>nn(i))}function Se(i){return{dispose:Eo(()=>{i()})}}var an=class hn{constructor(){this._toDispose=new Set,this._isDisposed=!1}dispose(){this._isDisposed||(this._isDisposed=!0,this.clear())}get isDisposed(){return this._isDisposed}clear(){if(this._toDispose.size!==0)try{nn(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?hn.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),void 0)}};an.DISABLE_DISPOSED_WARNING=!1;var kt=an,Pe=class{constructor(){this._store=new kt,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)}};Pe.None=Object.freeze({dispose(){}});var Ot=class{constructor(){this._isDisposed=!1}get value(){return this._isDisposed?void 0:this._value}set value(e){var t;this._isDisposed||e===this._value||((t=this._value)==null||t.dispose(),this._value=e)}clear(){this.value=void 0}dispose(){var e;this._isDisposed=!0,(e=this._value)==null||e.dispose(),this._value=void 0}clearAndLeak(){let e=this._value;return this._value=void 0,e}},Ts=typeof process<"u"&&"title"in process,Ii=Ts?"node":navigator.userAgent,Lo=Ts?"node":navigator.platform,ko=Ii.includes("Firefox"),Ao=Ii.includes("Edge"),ln=/^((?!chrome|android).)*safari/i.test(Ii);function Ro(){if(!ln)return 0;let i=Ii.match(/Version\\/(\\d+)/);return i===null||i.length<2?0:parseInt(i[1])}Lo.indexOf("Linux")>=0;var Bo="",_e=0,ge=0,pe=0,le=0,Re={css:"#00000000",rgba:0},Ce;(i=>{function e(n,o,_,s){return s!==void 0?\`#\${lt(n)}\${lt(o)}\${lt(_)}\${lt(s)}\`:\`#\Line truncated
\`).slice(2).join(\`
\`))}},ia=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},sa=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},ra=0,ji=class{constructor(e){this.value=e,this.id=ra++}},na=2,oa,re=class{constructor(e){var t,r,n,o;this._size=0,this._options=e,this._leakageMon=(t=this._options)!=null&&t.leakWarningThreshold?new ea((e==null?void 0:e.onListenerError)??Ui,((r=this._options)==null?void 0:r.leakWarningThreshold)??Qo):void 0,this._perfMon=(n=this._options)!=null&&n._profName?new Jo(this._options._profName):void 0,this._deliveryQueue=(o=this._options)==null?void 0:o.deliveryQueue}dispose(){var e,t,r,n;this._disposed||(this._disposed=!0,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(r=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null||r.call(t),(n=this._leakageMon)==null||n.dispose())}get event(){return this._event??(this._event=(e,t,r)=>{var s,h,a,d,u;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let p=\`[\${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (\${this._size} vs \${this._leakageMon.threshold})\`;console.warn(p);let m=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],C=new sa(\`\${p}. HINT: Stack shows most frequent listener (\${m[1]}-times)\`,m[0]);return(((s=this._options)==null?void 0:s.onListenerError)||Ui)(C),Pe.None}if(this._disposed)return Pe.None;t&&(e=e.bind(t));let n=new ji(e),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(n.stack=ta.create(),o=this._leakageMon.check(n.stack,this._size+1)),this._listeners?this._listeners instanceof ji?(this._deliveryQueue??(this._deliveryQueue=new aa),this._listeners=[this._listeners,n]):this._listeners.push(n):((a=(h=this._options)==null?void 0:h.onWillAddFirstListener)==null||a.call(h,this),this._listeners=n,(u=(d=this._options)==null?void 0:d.onDidAddFirstListener)==null||u.call(d,this)),this._size++;let _=Se(()=>{o==null||o(),this._removeListener(n)});return r instanceof kt?r.add(_):Array.isArray(r)&&r.push(_),_}),this._event}_removeListener(e){var o,_,s,h;if((_=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||_.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(h=(s=this._options)==null?void 0:s.onDidRemoveLastListener)==null||h.call(s,this),this._size=0;return}let t=this._listeners,r=t.indexOf(e);if(r===-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[r]=void 0;let n=this._deliveryQueue.current===this;if(this._size*na<=t.length){let a=0;for(let d=0;d<t.length;d++)t[d]?t[a++]=t[d]:n&&(this._deliveryQueue.end--,a<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=a}}_deliver(e,t){var n;if(!e)return;let r=((n=this._options)==null?void 0:n.onListenerError)||Ui;if(!r){e.value(t);return}try{e.value(t)}catch(o){r(o)}}_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,r,n,o;if((t=this._deliveryQueue)!=null&&t.current&&(this._deliverQueue(this._deliveryQueue),(r=this._perfMon)==null||r.stop()),(n=this._perfMon)==null||n.start(this._size),this._listeners)if(this._listeners instanceof ji)this._deliver(this._listeners,e);else{let _=this._deliveryQueue;_.enqueue(this,e,this._listeners.length),this._deliverQueue(_)}(o=this._perfMon)==null||o.stop()}hasListeners(){return this._size>0}},aa=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,r){this.i=0,this.end=r,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Ks={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}},Ft=2,$t,st=class Ct{constructor(e,t,r){this._document=e,this._config=t,this._unicodeService=r,this._didWarmUp=!1,this._cacheMap=new qs,this._cacheMapCombined=new qs,this._pages=[],this._activePages=[],this._workBoundingBox={top:0,left:0,bottom:0,right:0},this._workAttributeData=new xt,this._textureSize=512,this._onAddTextureAtlasCanvas=new re,this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=new re,this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._requestClearModel=!1,this._createNewPage(),this._tmpCanvas=Sn(e,this._config.deviceCellWidth*4+Ft*2,this._config.deviceCellHeight+Ft*2),this._tmpCtx=ce(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:!0}))}get pages(){return this._pages}dispose(){this._tmpCanvas.remove();for(let e of this.pages)e.canvas.remove();this._onAddTextureAtlasCanvas.dispose()}warmUp(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)}_doWarmUp(){let e=new Zo;for(let t=33;t<126;t++)e.enqueue(()=>{if Line truncated
\`))}},ra=class extends Error{constructor(e,t){super(e),this.name="ListenerLeakError",this.stack=t}},na=class extends Error{constructor(e,t){super(e),this.name="ListenerRefusalError",this.stack=t}},oa=0,ji=class{constructor(e){this.value=e,this.id=oa++}},aa=2,ha,re=class{constructor(e){var t,r,n,o;this._size=0,this._options=e,this._leakageMon=(t=this._options)!=null&&t.leakWarningThreshold?new ia((e==null?void 0:e.onListenerError)??Ui,((r=this._options)==null?void 0:r.leakWarningThreshold)??ta):void 0,this._perfMon=(n=this._options)!=null&&n._profName?new ea(this._options._profName):void 0,this._deliveryQueue=(o=this._options)==null?void 0:o.deliveryQueue}dispose(){var e,t,r,n;this._disposed||(this._disposed=!0,((e=this._deliveryQueue)==null?void 0:e.current)===this&&this._deliveryQueue.reset(),this._listeners&&(this._listeners=void 0,this._size=0),(r=(t=this._options)==null?void 0:t.onDidRemoveLastListener)==null||r.call(t),(n=this._leakageMon)==null||n.dispose())}get event(){return this._event??(this._event=(e,t,r)=>{var s,h,a,d,u;if(this._leakageMon&&this._size>this._leakageMon.threshold**2){let p=\`[\${this._leakageMon.name}] REFUSES to accept new listeners because it exceeded its threshold by far (\${this._size} vs \${this._leakageMon.threshold})\`;console.warn(p);let m=this._leakageMon.getMostFrequentStack()??["UNKNOWN stack",-1],C=new na(\`\${p}. HINT: Stack shows most frequent listener (\${m[1]}-times)\`,m[0]);return(((s=this._options)==null?void 0:s.onListenerError)||Ui)(C),Pe.None}if(this._disposed)return Pe.None;t&&(e=e.bind(t));let n=new ji(e),o;this._leakageMon&&this._size>=Math.ceil(this._leakageMon.threshold*.2)&&(n.stack=sa.create(),o=this._leakageMon.check(n.stack,this._size+1)),this._listeners?this._listeners instanceof ji?(this._deliveryQueue??(this._deliveryQueue=new la),this._listeners=[this._listeners,n]):this._listeners.push(n):((a=(h=this._options)==null?void 0:h.onWillAddFirstListener)==null||a.call(h,this),this._listeners=n,(u=(d=this._options)==null?void 0:d.onDidAddFirstListener)==null||u.call(d,this)),this._size++;let _=Se(()=>{o==null||o(),this._removeListener(n)});return r instanceof kt?r.add(_):Array.isArray(r)&&r.push(_),_}),this._event}_removeListener(e){var o,_,s,h;if((_=(o=this._options)==null?void 0:o.onWillRemoveListener)==null||_.call(o,this),!this._listeners)return;if(this._size===1){this._listeners=void 0,(h=(s=this._options)==null?void 0:s.onDidRemoveLastListener)==null||h.call(s,this),this._size=0;return}let t=this._listeners,r=t.indexOf(e);if(r===-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[r]=void 0;let n=this._deliveryQueue.current===this;if(this._size*aa<=t.length){let a=0;for(let d=0;d<t.length;d++)t[d]?t[a++]=t[d]:n&&(this._deliveryQueue.end--,a<this._deliveryQueue.i&&this._deliveryQueue.i--);t.length=a}}_deliver(e,t){var n;if(!e)return;let r=((n=this._options)==null?void 0:n.onListenerError)||Ui;if(!r){e.value(t);return}try{e.value(t)}catch(o){r(o)}}_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,r,n,o;if((t=this._deliveryQueue)!=null&&t.current&&(this._deliverQueue(this._deliveryQueue),(r=this._perfMon)==null||r.stop()),(n=this._perfMon)==null||n.start(this._size),this._listeners)if(this._listeners instanceof ji)this._deliver(this._listeners,e);else{let _=this._deliveryQueue;_.enqueue(this,e,this._listeners.length),this._deliverQueue(_)}(o=this._perfMon)==null||o.stop()}hasListeners(){return this._size>0}},la=class{constructor(){this.i=-1,this.end=0}enqueue(e,t,r){this.i=0,this.end=r,this.current=e,this.value=t}reset(){this.i=this.end,this.current=void 0,this.value=void 0}},Vs={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}},Ft=2,$t,st=class Ct{constructor(e,t,r){this._document=e,this._config=t,this._unicodeService=r,this._didWarmUp=!1,this._cacheMap=new Ks,this._cacheMapCombined=new Ks,this._pages=[],this._activePages=[],this._workBoundingBox={top:0,left:0,bottom:0,right:0},this._workAttributeData=new xt,this._textureSize=512,this._onAddTextureAtlasCanvas=new re,this.onAddTextureAtlasCanvas=this._onAddTextureAtlasCanvas.event,this._onRemoveTextureAtlasCanvas=new re,this.onRemoveTextureAtlasCanvas=this._onRemoveTextureAtlasCanvas.event,this._requestClearModel=!1,this._createNewPage(),this._tmpCanvas=yn(e,this._config.deviceCellWidth*4+Ft*2,this._config.deviceCellHeight+Ft*2),this._tmpCtx=ce(this._tmpCanvas.getContext("2d",{alpha:this._config.allowTransparency,willReadFrequently:!0}))}get pages(){return this._pages}dispose(){this._tmpCanvas.remove();for(let e of this.pages)e.canvas.remove();this._onAddTextureAtlasCanvas.dispose()}warmUp(){this._didWarmUp||(this._doWarmUp(),this._didWarmUp=!0)}_doWarmUp(){let e=new Yo;for(let t=33;t<126;t++)e.enqueue(()=>{if Line truncated
layout (location = 0) in vec2 a_unitquad;
layout (location = 1) in vec2 a_cellpos;
layout (location = 2) in vec2 a_offset;
@@ -86,7 +86,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 pa(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 ma(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;
@@ -100,7 +100,7 @@ void main() {
if (v_texpage == 0) {
outColor = texture(u_texture[0], v_texcoord);
} \${e}
}\`}var rt=11,bt=rt*Float32Array.BYTES_PER_ELEMENT,va=2,he=0,se,Vi=0,Ht=0,ma=class extends Pe{constructor(e,t,r,n){super(),this._terminal=e,this._gl=t,this._dimensions=r,this._optionsService=n,this._activeBuffer=0,this._vertices={count:0,attributes:new Float32Array(0),attributesBuffers:[new Float32Array(0),new Float32Array(0)]};let o=this._gl;st.maxAtlasPages===void 0&&(st.maxAtlasPages=Math.min(32,ce(o.getParameter(o.MAX_TEXTURE_IMAGE_UNITS))),st.maxTextureSize=ce(o.getParameter(o.MAX_TEXTURE_SIZE))),this._program=ce(En(o,ga,pa(st.maxAtlasPages))),this._register(Se(()=>o.deleteProgram(this._program))),this._projectionLocation=ce(o.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=ce(o.getUniformLocation(this._program,"u_resolution")),this._textureLocation=ce(o.getUniformLocation(this._program,"u_texture")),this._vertexArrayObject=o.createVertexArray(),o.bindVertexArray(this._vertexArrayObject);let _=new Float32Array([0,0,1,0,0,1,1,1]),s=o.createBuffer();this._register(Se(()=>o.deleteBuffer(s))),o.bindBuffer(o.ARRAY_BUFFER,s),o.bufferData(o.ARRAY_BUFFER,_,o.STATIC_DRAW),o.enableVertexAttribArray(0),o.vertexAttribPointer(0,2,this._gl.FLOAT,!1,0,0);let h=new Uint8Array([0,1,2,3]),a=o.createBuffer();this._register(Se(()=>o.deleteBuffer(a))),o.bindBuffer(o.ELEMENT_ARRAY_BUFFER,a),o.bufferData(o.ELEMENT_ARRAY_BUFFER,h,o.STATIC_DRAW),this._attributesBuffer=ce(o.createBuffer()),this._register(Se(()=>o.deleteBuffer(this._attributesBuffer))),o.bindBuffer(o.ARRAY_BUFFER,this._attributesBuffer),o.enableVertexAttribArray(2),o.vertexAttribPointer(2,2,o.FLOAT,!1,bt,0),o.vertexAttribDivisor(2,1),o.enableVertexAttribArray(3),o.vertexAttribPointer(3,2,o.FLOAT,!1,bt,2*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(3,1),o.enableVertexAttribArray(4),o.vertexAttribPointer(4,1,o.FLOAT,!1,bt,4*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(4,1),o.enableVertexAttribArray(5),o.vertexAttribPointer(5,2,o.FLOAT,!1,bt,5*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(5,1),o.enableVertexAttribArray(6),o.vertexAttribPointer(6,2,o.FLOAT,!1,bt,7*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(6,1),o.enableVertexAttribArray(1),o.vertexAttribPointer(1,2,o.FLOAT,!1,bt,9*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(1,1),o.useProgram(this._program);let d=new Int32Array(st.maxAtlasPages);for(let u=0;u<st.maxAtlasPages;u++)d[u]=u;o.uniform1iv(this._textureLocation,d),o.uniformMatrix4fv(this._projectionLocation,!1,xn),this._atlasTextures=[];for(let u=0;u<st.maxAtlasPages;u++){let p=new _a(ce(o.createTexture()));this._register(Se(()=>o.deleteTexture(p.texture))),o.activeTexture(o.TEXTURE0+u),o.bindTexture(o.TEXTURE_2D,p.texture),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,1,1,0,o.RGBA,o.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[u]=p}o.enable(o.BLEND),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){return this._atlas?this._atlas.beginFrame():!0}updateCell(e,t,r,n,o,_,s,h,a){this._updateCell(this._vertices.attributes,e,t,r,n,o,_,s,h,a)}_updateCell(e,t,r,n,o,_,s,h,a,d){if(he=(r*this._terminal.cols+t)*rt,n===0||n===void 0){e.fill(0,he,he+rt-1-va);return}this._atlas&&(h&&h.length>1?se=this._atlas.getRasterizedGlyphCombinedChar(h,o,_,s,!1,this._terminal.element):se=this._atlas.getRasterizedGlyph(n,o,_,s,!1,this._terminal.element),Vi=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),o!==d&&se.offset.x>Vi?(Ht=se.offset.x-Vi,e[he]=-(se.offset.x-Ht)+this._dimensions.device.char.left,e[he+1]=-se.offset.y+this._dimensions.device.char.top,e[he+2]=(se.size.x-Ht)/this._dimensions.device.canvas.width,e[he+3]=se.size.y/this._dimensions.device.canvas.height,e[he+4]=se.texturePage,e[he+5]=se.texturePositionClipSpace.x+Ht/this._atlas.pages[se.texturePage].canvas.width,e[he+6]=se.texturePositionClipSpace.y,e[he+7]=se.sizeClipSpace.x-Ht/this._atlas.pages[se.texturePage].canvas.width,e[he+8]=se.sizeClipSpace.y):(e[he]=-se.offset.x+this._dimensions.device.char.left,e[he+1]=-se.offset.y+this._dimensions.device.char.top,e[he+2]=se.size.x/this._dimensions.device.canvas.width,e[he+3]=se.size.y/this._dimensions.device.canvas.height,e[he+4]=se.texturePage,e[he+5]=se.texturePositionClipSpace.x,e[he+6]=se.texturePositionClipSpace.y,e[he+7]=se.sizeClipSpace.x,e[he+8]=se.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&Io(n,a,se.size.x,this._dimensions.device.cell.width)&&(e[he+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width))}clear(){let e=this._terminal,t=e.cols*e.rows*rt;this._vertices.count!==t?this._vertices.attributes=new Float32Array(t):this._vertices.attributes.fill(0);let r=0;for(;r<this._vertices.attributesBuffers.length;r++)this._vertices.count!==t?this._vertices.attributesBuffers[r]=new Float32Array(t):this._vertices.attributesBuffers[r].fill(0);this Line truncated
}\`}var rt=11,bt=rt*Float32Array.BYTES_PER_ELEMENT,wa=2,he=0,se,Vi=0,Ht=0,ba=class extends Pe{constructor(e,t,r,n){super(),this._terminal=e,this._gl=t,this._dimensions=r,this._optionsService=n,this._activeBuffer=0,this._vertices={count:0,attributes:new Float32Array(0),attributesBuffers:[new Float32Array(0),new Float32Array(0)]};let o=this._gl;st.maxAtlasPages===void 0&&(st.maxAtlasPages=Math.min(32,ce(o.getParameter(o.MAX_TEXTURE_IMAGE_UNITS))),st.maxTextureSize=ce(o.getParameter(o.MAX_TEXTURE_SIZE))),this._program=ce(Ln(o,va,ma(st.maxAtlasPages))),this._register(Se(()=>o.deleteProgram(this._program))),this._projectionLocation=ce(o.getUniformLocation(this._program,"u_projection")),this._resolutionLocation=ce(o.getUniformLocation(this._program,"u_resolution")),this._textureLocation=ce(o.getUniformLocation(this._program,"u_texture")),this._vertexArrayObject=o.createVertexArray(),o.bindVertexArray(this._vertexArrayObject);let _=new Float32Array([0,0,1,0,0,1,1,1]),s=o.createBuffer();this._register(Se(()=>o.deleteBuffer(s))),o.bindBuffer(o.ARRAY_BUFFER,s),o.bufferData(o.ARRAY_BUFFER,_,o.STATIC_DRAW),o.enableVertexAttribArray(0),o.vertexAttribPointer(0,2,this._gl.FLOAT,!1,0,0);let h=new Uint8Array([0,1,2,3]),a=o.createBuffer();this._register(Se(()=>o.deleteBuffer(a))),o.bindBuffer(o.ELEMENT_ARRAY_BUFFER,a),o.bufferData(o.ELEMENT_ARRAY_BUFFER,h,o.STATIC_DRAW),this._attributesBuffer=ce(o.createBuffer()),this._register(Se(()=>o.deleteBuffer(this._attributesBuffer))),o.bindBuffer(o.ARRAY_BUFFER,this._attributesBuffer),o.enableVertexAttribArray(2),o.vertexAttribPointer(2,2,o.FLOAT,!1,bt,0),o.vertexAttribDivisor(2,1),o.enableVertexAttribArray(3),o.vertexAttribPointer(3,2,o.FLOAT,!1,bt,2*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(3,1),o.enableVertexAttribArray(4),o.vertexAttribPointer(4,1,o.FLOAT,!1,bt,4*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(4,1),o.enableVertexAttribArray(5),o.vertexAttribPointer(5,2,o.FLOAT,!1,bt,5*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(5,1),o.enableVertexAttribArray(6),o.vertexAttribPointer(6,2,o.FLOAT,!1,bt,7*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(6,1),o.enableVertexAttribArray(1),o.vertexAttribPointer(1,2,o.FLOAT,!1,bt,9*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(1,1),o.useProgram(this._program);let d=new Int32Array(st.maxAtlasPages);for(let u=0;u<st.maxAtlasPages;u++)d[u]=u;o.uniform1iv(this._textureLocation,d),o.uniformMatrix4fv(this._projectionLocation,!1,En),this._atlasTextures=[];for(let u=0;u<st.maxAtlasPages;u++){let p=new pa(ce(o.createTexture()));this._register(Se(()=>o.deleteTexture(p.texture))),o.activeTexture(o.TEXTURE0+u),o.bindTexture(o.TEXTURE_2D,p.texture),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_S,o.CLAMP_TO_EDGE),o.texParameteri(o.TEXTURE_2D,o.TEXTURE_WRAP_T,o.CLAMP_TO_EDGE),o.texImage2D(o.TEXTURE_2D,0,o.RGBA,1,1,0,o.RGBA,o.UNSIGNED_BYTE,new Uint8Array([255,0,0,255])),this._atlasTextures[u]=p}o.enable(o.BLEND),o.blendFunc(o.SRC_ALPHA,o.ONE_MINUS_SRC_ALPHA),this.handleResize()}beginFrame(){return this._atlas?this._atlas.beginFrame():!0}updateCell(e,t,r,n,o,_,s,h,a){this._updateCell(this._vertices.attributes,e,t,r,n,o,_,s,h,a)}_updateCell(e,t,r,n,o,_,s,h,a,d){if(he=(r*this._terminal.cols+t)*rt,n===0||n===void 0){e.fill(0,he,he+rt-1-wa);return}this._atlas&&(h&&h.length>1?se=this._atlas.getRasterizedGlyphCombinedChar(h,o,_,s,!1,this._terminal.element):se=this._atlas.getRasterizedGlyph(n,o,_,s,!1,this._terminal.element),Vi=Math.floor((this._dimensions.device.cell.width-this._dimensions.device.char.width)/2),o!==d&&se.offset.x>Vi?(Ht=se.offset.x-Vi,e[he]=-(se.offset.x-Ht)+this._dimensions.device.char.left,e[he+1]=-se.offset.y+this._dimensions.device.char.top,e[he+2]=(se.size.x-Ht)/this._dimensions.device.canvas.width,e[he+3]=se.size.y/this._dimensions.device.canvas.height,e[he+4]=se.texturePage,e[he+5]=se.texturePositionClipSpace.x+Ht/this._atlas.pages[se.texturePage].canvas.width,e[he+6]=se.texturePositionClipSpace.y,e[he+7]=se.sizeClipSpace.x-Ht/this._atlas.pages[se.texturePage].canvas.width,e[he+8]=se.sizeClipSpace.y):(e[he]=-se.offset.x+this._dimensions.device.char.left,e[he+1]=-se.offset.y+this._dimensions.device.char.top,e[he+2]=se.size.x/this._dimensions.device.canvas.width,e[he+3]=se.size.y/this._dimensions.device.canvas.height,e[he+4]=se.texturePage,e[he+5]=se.texturePositionClipSpace.x,e[he+6]=se.texturePositionClipSpace.y,e[he+7]=se.sizeClipSpace.x,e[he+8]=se.sizeClipSpace.y),this._optionsService.rawOptions.rescaleOverlappingGlyphs&&Oo(n,a,se.size.x,this._dimensions.device.cell.width)&&(e[he+2]=(this._dimensions.device.cell.width-1)/this._dimensions.device.canvas.width))}clear(){let e=this._terminal,t=e.cols*e.rows*rt;this._vertices.count!==t?this._vertices.attributes=new Float32Array(t):this._vertices.attributes.fill(0);let r=0;for(;r<this._vertices.attributesBuffers.length;r++)this._vertices.count!==t?this._vertices.attributesBuffers[r]=new Float32Array(t):this._vertices.attributesBuffers[r].fill(0);this Line truncated
layout (location = 0) in vec2 a_position;
layout (location = 1) in vec2 a_size;
layout (location = 2) in vec4 a_color;
@@ -114,7 +114,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;
}\`,xa=\`#version 300 es
}\`,La=\`#version 300 es
precision lowp float;
in vec4 v_color;
@@ -123,16 +123,16 @@ out vec4 outColor;
void main() {
outColor = v_color;
}\`,Ge=8,Zi=Ge*Float32Array.BYTES_PER_ELEMENT,Ea=20*Ge,Js=class{constructor(){this.attributes=new Float32Array(Ea),this.count=0}},Ke=0,Qs=0,er=0,tr=0,ir=0,sr=0,rr=0,La=class extends Pe{constructor(e,t,r,n){super(),this._terminal=e,this._gl=t,this._dimensions=r,this._themeService=n,this._vertices=new Js,this._verticesCursor=new Js;let o=this._gl;this._program=ce(En(o,Ca,xa)),this._register(Se(()=>o.deleteProgram(this._program))),this._projectionLocation=ce(o.getUniformLocation(this._program,"u_projection")),this._vertexArrayObject=o.createVertexArray(),o.bindVertexArray(this._vertexArrayObject);let _=new Float32Array([0,0,1,0,0,1,1,1]),s=o.createBuffer();this._register(Se(()=>o.deleteBuffer(s))),o.bindBuffer(o.ARRAY_BUFFER,s),o.bufferData(o.ARRAY_BUFFER,_,o.STATIC_DRAW),o.enableVertexAttribArray(3),o.vertexAttribPointer(3,2,this._gl.FLOAT,!1,0,0);let h=new Uint8Array([0,1,2,3]),a=o.createBuffer();this._register(Se(()=>o.deleteBuffer(a))),o.bindBuffer(o.ELEMENT_ARRAY_BUFFER,a),o.bufferData(o.ELEMENT_ARRAY_BUFFER,h,o.STATIC_DRAW),this._attributesBuffer=ce(o.createBuffer()),this._register(Se(()=>o.deleteBuffer(this._attributesBuffer))),o.bindBuffer(o.ARRAY_BUFFER,this._attributesBuffer),o.enableVertexAttribArray(0),o.vertexAttribPointer(0,2,o.FLOAT,!1,Zi,0),o.vertexAttribDivisor(0,1),o.enableVertexAttribArray(1),o.vertexAttribPointer(1,2,o.FLOAT,!1,Zi,2*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(1,1),o.enableVertexAttribArray(2),o.vertexAttribPointer(2,4,o.FLOAT,!1,Zi,4*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(2,1),this._updateCachedColors(n.colors),this._register(this._themeService.onChangeColors(d=>{this._updateCachedColors(d),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,!1,xn),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,r=this._vertices,n=1,o,_,s,h,a,d,u,p,m,C,w;for(o=0;o<t.rows;o++){for(s=-1,h=0,a=0,d=!1,_=0;_<t.cols;_++)u=(o*t.cols+_)*Ai,p=e.cells[u+xi],m=e.cells[u+Ei],C=!!(m&67108864),(p!==h||m!==a&&(d||C))&&((h!==0||d&&a!==0)&&(w=n++*Ge,this._updateRectangle(r,w,a,h,s,_,o)),s=_,h=p,a=m,d=C);(h!==0||d&&a!==0)&&(w=n++*Ge,this._updateRectangle(r,w,a,h,s,t.cols,o))}r.count=n}updateCursor(e){let t=this._verticesCursor,r=e.cursor;if(!r||r.style==="block"){t.count=0;return}let n,o=0;(r.style==="bar"||r.style==="outline")&&(n=o++*Ge,this._addRectangleFloat(t.attributes,n,r.x*this._dimensions.device.cell.width,r.y*this._dimensions.device.cell.height,r.style==="bar"?r.dpr*r.cursorWidth:r.dpr,this._dimensions.device.cell.height,this._cursorFloat)),(r.style==="underline"||r.style==="outline")&&(n=o++*Ge,this._addRectangleFloat(t.attributes,n,r.x*this._dimensions.device.cell.width,(r.y+1)*this._dimensions.device.cell.height-r.dpr,r.width*this._dimensions.device.cell.width,r.dpr,this._cursorFloat)),r.style==="outline"&&(n=o++*Ge,this._addRectangleFloat(t.attributes,n,r.x*this._dimensions.device.cell.width,r.y*this._dimensions.device.cell.height,r.width*this._dimensions.device.cell.width,r.dpr,this._cursorFloat),n=o++*Ge,this._addRectangleFloat(t.attributes,n,(r.x+r.width)*this._dimensions.device.cell.width-r.dpr,r.y*this._dimensions.device.cell.height,r.dpr,this._dimensions.device.cell.height,this._cursorFloat)),t.count=o}_updateRectangle(e,t,r,n,o,_,s){if(r&67108864)switch(r&50331648){case 16777216:case 33554432:Ke=this._themeService.colors.ansi[r&255].rgba;break;case 50331648:Ke=(r&16777215)<<8;break;case 0:default:Ke=this._themeService.colors.foreground.rgba}else switch(n&50331648){case 16777216:case 33554432:Ke=this._themeService.colors.ansi[n&255].rgba;break;case 50331648:Ke=(n&16777215)<<8;break;case 0:default:Ke=this._themeService.colors.background.rgba}e.attributes.length<t+4&&(e.attributes=fa(e.attributes,this._terminal.rows*this._terminal.cols*Ge)),Qs=o*this._dimensions.device.cell.width,er=s*this._dimensions.device.cell.height,tr=(Ke>>24&255)/255,ir=(Ke>>16&255)/255,sr=(Ke>>8&255)/255,rr=1,this._addRectangle(e.attributes,t,Qs,er,(_-o)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,tr,ir,sr,rr)}_addRectangle(e,t,r,n,o,_,s,h,a,d){e[t]=r/this._dimensions.device.canvas.width,e[t+1]=n/this._dimensions.device.canvas.heig Line truncated
- \`)}const te=eo("fs"),Je=eo("path");function eo(i){try{return require(i)}catch{return{}}}(function(i,e){for(const t of e)i[t+"Async"]=(...r)=>new Promise(n=>{i[t](...r,o=>n(!o))})})(te,["rm","rmdir","unlink","access"]),(function(i,e){for(const t of e)i[t+"Async"]=(...r)=>new Promise((n,o)=>{i[t](...r,(_,s)=>{_?o(_):n(s)})})})(te,["stat","mkdir","readdir","close","open","realpath","write"]);class $r{constructor(e,t,r,n,o){this.closed=!1,this.fd=null,this.pathId=e,this.absPath=t,this.relPath=r,this.dir=n,this.size=o}getPathId(){return this.pathId}getRelPath(){return this.relPath}isDir(){return this.dir}getSize(){return this.size}readFile(e){return q(this,void 0,void 0,function*(){if(this.closed)throw new X(\`File closed: \${this.absPath}\`,null,!0);this.fd===null&&(this.fd=yield te.openAsync(this.absPath,"r"));const t=new Uint8Array(e);return(function(r,n,o,_,s){return q(this,void 0,void 0,function*(){return new Promise((h,a)=>te.read(r,n,o,_,s,(d,u,p)=>{d?a(d):h(p.subarray(0,u))}))})})(this.fd,t,0,t.length,null)})}closeFile(){return q(this,void 0,void 0,function*(){this.closed||(this.closed=!0,this.fd!==null&&(yield te.closeAsync(this.fd),this.fd=null))})}}function to(i,e,t,r,n,o){return q(this,void 0,void 0,function*(){if(!t.isDirectory()){if(!t.isFile())throw new X(\`Not a regular file: \${e}\`);if(!(yield te.accessAsync(e,te.constants.R_OK)))throw new X(\`No permission to read: \${e}\`);return void r.push(new $r(i,e,n,!1,t.size))}const _=yield te.realpathAsync(e);if(o.has(_))throw new X(\`Duplicate link: \${e}\`);o.add(_),r.push(new $r(i,e,n,!0,0));const s=yield te.readdirAsync(e);for(const h of s){const a=Je.join(e,h),d=yield te.statAsync(a);yield to(i,a,d,r,[...n,h],o)}})}function Hr(i){return q(this,arguments,void 0,function*(e,t=!1){if(!e||!e.length)return;const r=[],n=e.entries();for(const[o,_]of n){const s=Je.resolve(_);if(!(yield te.accessAsync(s)))throw new X(\`No such file: \${s}\`);const h=yield te.statAsync(s);if(!t&&h.isDirectory())throw new X(\`Is a directory: \${s}\`);const a=new Set;yield to(o,s,h,r,[Je.basename(s)],a)}return r})}class ps{constructor(e,t,r,n,o=!1){this.closed=!1,this.absPath=e,this.fileName=t,this.localName=r,this.fd=n,this.dir=o}getFileName(){return this.fileName}getLocalName(){return this.localName}isDir(){return this.dir}writeFile(e){return q(this,void 0,void 0,function*(){yield te.writeAsync(this.fd,e)})}closeFile(){return q(this,void 0,void 0,function*(){this.closed||(this.closed=!0,this.fd!==null&&(yield te.closeAsync(this.fd),this.fd=null))})}deleteFile(){return q(this,void 0,void 0,function*(){if(!this.absPath||!(yield te.accessAsync(this.absPath)))return"";try{if(yield this.closeFile(),typeof te.rm=="function"){if(yield te.rmAsync(this.absPath,{recursive:!0}))return this.absPath}else if(this.isDir){if(yield te.rmdirAsync(this.absPath,{recursive:!0}))return this.absPath}else if(yield te.unlinkAsync(this.absPath))return this.absPath}catch(e){console.log(\`delete [\${this.absPath}] failed\`,e)}return""})}}function zr(i,e){return q(this,void 0,void 0,function*(){if(!(yield te.accessAsync(Je.join(i,e))))return e;for(let t=0;t<1e3;t++){const r=\`\${e}.\${t}\`;if(!(yield te.accessAsync(Je.join(i,r))))return r}throw new X("Fail to assign new file name")})}function Wr(i){return q(this,void 0,void 0,function*(){try{return yield te.openAsync(i,"w")}catch(e){throw e.errno===-13||e.errno===-4048?new X(\`No permission to write: \${i}\`):e.errno===-21||e.errno===-4068?new X(\`Is a directory: \${i}\`):e}})}function Ur(i){return q(this,void 0,void 0,function*(){if(!(yield te.accessAsync(i)))return yield te.mkdirAsync(i,{recursive:!0,mode:493}),!0;if(!(yield te.statAsync(i)).isDirectory())throw new X(\`Not a directory: \${i}\`);return!1})}function el(i,e,t,r){return q(this,void 0,void 0,function*(){if(!t)return(function(h,a,d){return q(this,void 0,void 0,function*(){const u=d?a:yield zr(h,a),p=Je.join(h,u),m=yield Wr(p);return new ps(p,a,u,m)})})(i.path,e,r);const n=JSON.parse(e);if(!n.hasOwnProperty("path_name")||!n.hasOwnProperty("path_id")||!n.hasOwnProperty("is_dir")||n.path_name.length<1)throw new X(\`Invalid name: \${e}\`);let o,_;if(e=n.path_name[n.path_name.length-1],r?o=n.path_name[0]:i.maps.has(n.path_id)?o=i.maps.get(n.path_id):(o=yield zr(i.path,n.path_name[0]),i.maps.set(n.path_id,o)),n.path_name.length>1){const h=Je.join(i.path,o,...n.path_name.slice(1,n.path_name.length-1));yield Ur(h),_=Je.join(h,e)}else _=Je.join(i.path,o);if(n.is_dir===!0){let h="";return(yield Ur(_))&&(h=_),new ps(h,e,o,null,!0)}const s=yield Wr(_);return new ps(_,e,o,s)})}class ai{constructor(e,t,r,n){this.closed=!1,this.pos=0,this.pathId=e,this.relPath=t,this.file=r,this.dir=n}getPathId(){return this.pathId}getRelPath(){return this.relPath}isDir(){return this.dir}getSize(){return this.file.size}readFile(e){return q(this,void 0,void 0,function*(){if(this.pos>=this.file.size)return new Uint8Array(0);try{const t=Math.min(e.byteLength,this.file.size-this.pos),r=this.file.slice(this.pos,this.pos+t Line truncated
}\`,Ge=8,Zi=Ge*Float32Array.BYTES_PER_ELEMENT,ka=20*Ge,Qs=class{constructor(){this.attributes=new Float32Array(ka),this.count=0}},Ke=0,er=0,tr=0,ir=0,sr=0,rr=0,nr=0,Aa=class extends Pe{constructor(e,t,r,n){super(),this._terminal=e,this._gl=t,this._dimensions=r,this._themeService=n,this._vertices=new Qs,this._verticesCursor=new Qs;let o=this._gl;this._program=ce(Ln(o,Ea,La)),this._register(Se(()=>o.deleteProgram(this._program))),this._projectionLocation=ce(o.getUniformLocation(this._program,"u_projection")),this._vertexArrayObject=o.createVertexArray(),o.bindVertexArray(this._vertexArrayObject);let _=new Float32Array([0,0,1,0,0,1,1,1]),s=o.createBuffer();this._register(Se(()=>o.deleteBuffer(s))),o.bindBuffer(o.ARRAY_BUFFER,s),o.bufferData(o.ARRAY_BUFFER,_,o.STATIC_DRAW),o.enableVertexAttribArray(3),o.vertexAttribPointer(3,2,this._gl.FLOAT,!1,0,0);let h=new Uint8Array([0,1,2,3]),a=o.createBuffer();this._register(Se(()=>o.deleteBuffer(a))),o.bindBuffer(o.ELEMENT_ARRAY_BUFFER,a),o.bufferData(o.ELEMENT_ARRAY_BUFFER,h,o.STATIC_DRAW),this._attributesBuffer=ce(o.createBuffer()),this._register(Se(()=>o.deleteBuffer(this._attributesBuffer))),o.bindBuffer(o.ARRAY_BUFFER,this._attributesBuffer),o.enableVertexAttribArray(0),o.vertexAttribPointer(0,2,o.FLOAT,!1,Zi,0),o.vertexAttribDivisor(0,1),o.enableVertexAttribArray(1),o.vertexAttribPointer(1,2,o.FLOAT,!1,Zi,2*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(1,1),o.enableVertexAttribArray(2),o.vertexAttribPointer(2,4,o.FLOAT,!1,Zi,4*Float32Array.BYTES_PER_ELEMENT),o.vertexAttribDivisor(2,1),this._updateCachedColors(n.colors),this._register(this._themeService.onChangeColors(d=>{this._updateCachedColors(d),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,!1,En),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,r=this._vertices,n=1,o,_,s,h,a,d,u,p,m,C,w;for(o=0;o<t.rows;o++){for(s=-1,h=0,a=0,d=!1,_=0;_<t.cols;_++)u=(o*t.cols+_)*Ai,p=e.cells[u+xi],m=e.cells[u+Ei],C=!!(m&67108864),(p!==h||m!==a&&(d||C))&&((h!==0||d&&a!==0)&&(w=n++*Ge,this._updateRectangle(r,w,a,h,s,_,o)),s=_,h=p,a=m,d=C);(h!==0||d&&a!==0)&&(w=n++*Ge,this._updateRectangle(r,w,a,h,s,t.cols,o))}r.count=n}updateCursor(e){let t=this._verticesCursor,r=e.cursor;if(!r||r.style==="block"){t.count=0;return}let n,o=0;(r.style==="bar"||r.style==="outline")&&(n=o++*Ge,this._addRectangleFloat(t.attributes,n,r.x*this._dimensions.device.cell.width,r.y*this._dimensions.device.cell.height,r.style==="bar"?r.dpr*r.cursorWidth:r.dpr,this._dimensions.device.cell.height,this._cursorFloat)),(r.style==="underline"||r.style==="outline")&&(n=o++*Ge,this._addRectangleFloat(t.attributes,n,r.x*this._dimensions.device.cell.width,(r.y+1)*this._dimensions.device.cell.height-r.dpr,r.width*this._dimensions.device.cell.width,r.dpr,this._cursorFloat)),r.style==="outline"&&(n=o++*Ge,this._addRectangleFloat(t.attributes,n,r.x*this._dimensions.device.cell.width,r.y*this._dimensions.device.cell.height,r.width*this._dimensions.device.cell.width,r.dpr,this._cursorFloat),n=o++*Ge,this._addRectangleFloat(t.attributes,n,(r.x+r.width)*this._dimensions.device.cell.width-r.dpr,r.y*this._dimensions.device.cell.height,r.dpr,this._dimensions.device.cell.height,this._cursorFloat)),t.count=o}_updateRectangle(e,t,r,n,o,_,s){if(r&67108864)switch(r&50331648){case 16777216:case 33554432:Ke=this._themeService.colors.ansi[r&255].rgba;break;case 50331648:Ke=(r&16777215)<<8;break;case 0:default:Ke=this._themeService.colors.foreground.rgba}else switch(n&50331648){case 16777216:case 33554432:Ke=this._themeService.colors.ansi[n&255].rgba;break;case 50331648:Ke=(n&16777215)<<8;break;case 0:default:Ke=this._themeService.colors.background.rgba}e.attributes.length<t+4&&(e.attributes=ga(e.attributes,this._terminal.rows*this._terminal.cols*Ge)),er=o*this._dimensions.device.cell.width,tr=s*this._dimensions.device.cell.height,ir=(Ke>>24&255)/255,sr=(Ke>>16&255)/255,rr=(Ke>>8&255)/255,nr=1,this._addRectangle(e.attributes,t,er,tr,(_-o)*this._dimensions.device.cell.width,this._dimensions.device.cell.height,ir,sr,rr,nr)}_addRectangle(e,t,r,n,o,_,s,h,a,d){e[t]=r/this._dimensions.device.canvas.width,e[t+1]=n/this._dimensions.device.canvas.heig Line truncated
- \`)}const te=to("fs"),Je=to("path");function to(i){try{return require(i)}catch{return{}}}(function(i,e){for(const t of e)i[t+"Async"]=(...r)=>new Promise(n=>{i[t](...r,o=>n(!o))})})(te,["rm","rmdir","unlink","access"]),(function(i,e){for(const t of e)i[t+"Async"]=(...r)=>new Promise((n,o)=>{i[t](...r,(_,s)=>{_?o(_):n(s)})})})(te,["stat","mkdir","readdir","close","open","realpath","write"]);class Hr{constructor(e,t,r,n,o){this.closed=!1,this.fd=null,this.pathId=e,this.absPath=t,this.relPath=r,this.dir=n,this.size=o}getPathId(){return this.pathId}getRelPath(){return this.relPath}isDir(){return this.dir}getSize(){return this.size}readFile(e){return q(this,void 0,void 0,function*(){if(this.closed)throw new X(\`File closed: \${this.absPath}\`,null,!0);this.fd===null&&(this.fd=yield te.openAsync(this.absPath,"r"));const t=new Uint8Array(e);return(function(r,n,o,_,s){return q(this,void 0,void 0,function*(){return new Promise((h,a)=>te.read(r,n,o,_,s,(d,u,p)=>{d?a(d):h(p.subarray(0,u))}))})})(this.fd,t,0,t.length,null)})}closeFile(){return q(this,void 0,void 0,function*(){this.closed||(this.closed=!0,this.fd!==null&&(yield te.closeAsync(this.fd),this.fd=null))})}}function io(i,e,t,r,n,o){return q(this,void 0,void 0,function*(){if(!t.isDirectory()){if(!t.isFile())throw new X(\`Not a regular file: \${e}\`);if(!(yield te.accessAsync(e,te.constants.R_OK)))throw new X(\`No permission to read: \${e}\`);return void r.push(new Hr(i,e,n,!1,t.size))}const _=yield te.realpathAsync(e);if(o.has(_))throw new X(\`Duplicate link: \${e}\`);o.add(_),r.push(new Hr(i,e,n,!0,0));const s=yield te.readdirAsync(e);for(const h of s){const a=Je.join(e,h),d=yield te.statAsync(a);yield io(i,a,d,r,[...n,h],o)}})}function zr(i){return q(this,arguments,void 0,function*(e,t=!1){if(!e||!e.length)return;const r=[],n=e.entries();for(const[o,_]of n){const s=Je.resolve(_);if(!(yield te.accessAsync(s)))throw new X(\`No such file: \${s}\`);const h=yield te.statAsync(s);if(!t&&h.isDirectory())throw new X(\`Is a directory: \${s}\`);const a=new Set;yield io(o,s,h,r,[Je.basename(s)],a)}return r})}class ps{constructor(e,t,r,n,o=!1){this.closed=!1,this.absPath=e,this.fileName=t,this.localName=r,this.fd=n,this.dir=o}getFileName(){return this.fileName}getLocalName(){return this.localName}isDir(){return this.dir}writeFile(e){return q(this,void 0,void 0,function*(){yield te.writeAsync(this.fd,e)})}closeFile(){return q(this,void 0,void 0,function*(){this.closed||(this.closed=!0,this.fd!==null&&(yield te.closeAsync(this.fd),this.fd=null))})}deleteFile(){return q(this,void 0,void 0,function*(){if(!this.absPath||!(yield te.accessAsync(this.absPath)))return"";try{if(yield this.closeFile(),typeof te.rm=="function"){if(yield te.rmAsync(this.absPath,{recursive:!0}))return this.absPath}else if(this.isDir){if(yield te.rmdirAsync(this.absPath,{recursive:!0}))return this.absPath}else if(yield te.unlinkAsync(this.absPath))return this.absPath}catch(e){console.log(\`delete [\${this.absPath}] failed\`,e)}return""})}}function Wr(i,e){return q(this,void 0,void 0,function*(){if(!(yield te.accessAsync(Je.join(i,e))))return e;for(let t=0;t<1e3;t++){const r=\`\${e}.\${t}\`;if(!(yield te.accessAsync(Je.join(i,r))))return r}throw new X("Fail to assign new file name")})}function Ur(i){return q(this,void 0,void 0,function*(){try{return yield te.openAsync(i,"w")}catch(e){throw e.errno===-13||e.errno===-4048?new X(\`No permission to write: \${i}\`):e.errno===-21||e.errno===-4068?new X(\`Is a directory: \${i}\`):e}})}function Nr(i){return q(this,void 0,void 0,function*(){if(!(yield te.accessAsync(i)))return yield te.mkdirAsync(i,{recursive:!0,mode:493}),!0;if(!(yield te.statAsync(i)).isDirectory())throw new X(\`Not a directory: \${i}\`);return!1})}function il(i,e,t,r){return q(this,void 0,void 0,function*(){if(!t)return(function(h,a,d){return q(this,void 0,void 0,function*(){const u=d?a:yield Wr(h,a),p=Je.join(h,u),m=yield Ur(p);return new ps(p,a,u,m)})})(i.path,e,r);const n=JSON.parse(e);if(!n.hasOwnProperty("path_name")||!n.hasOwnProperty("path_id")||!n.hasOwnProperty("is_dir")||n.path_name.length<1)throw new X(\`Invalid name: \${e}\`);let o,_;if(e=n.path_name[n.path_name.length-1],r?o=n.path_name[0]:i.maps.has(n.path_id)?o=i.maps.get(n.path_id):(o=yield Wr(i.path,n.path_name[0]),i.maps.set(n.path_id,o)),n.path_name.length>1){const h=Je.join(i.path,o,...n.path_name.slice(1,n.path_name.length-1));yield Nr(h),_=Je.join(h,e)}else _=Je.join(i.path,o);if(n.is_dir===!0){let h="";return(yield Nr(_))&&(h=_),new ps(h,e,o,null,!0)}const s=yield Ur(_);return new ps(_,e,o,s)})}class ai{constructor(e,t,r,n){this.closed=!1,this.pos=0,this.pathId=e,this.relPath=t,this.file=r,this.dir=n}getPathId(){return this.pathId}getRelPath(){return this.relPath}isDir(){return this.dir}getSize(){return this.file.size}readFile(e){return q(this,void 0,void 0,function*(){if(this.pos>=this.file.size)return new Uint8Array(0);try{const t=Math.min(e.byteLength,this.file.size-this.pos),r=this.file.slice(this.pos,this.pos+t Line truncated
\`,this.writer=e,this.isWindowsShell=t,this.maxDataChunkSize=r}cleanup(){for(const e of this.openedFiles)e.closeFile()}addReceivedData(e){this.stopped||this.buffer.addBuffer(e),this.lastInputTime=Date.now()}stopTransferring(){return q(this,void 0,void 0,function*(){this.cleanTimeoutInMilliseconds=Math.max(2*this.maxChunkTimeInMilliseconds,500),this.stopped=!0,this.buffer.stopBuffer()})}cleanInput(e){return q(this,void 0,void 0,function*(){for(this.stopped=!0,this.buffer.drainBuffer(),this.lastInputTime=Date.now();;){const t=e-(Date.now()-this.lastInputTime);if(t<=0)return;yield new Promise(r=>setTimeout(r,t))}})}sendLine(e,t){return q(this,void 0,void 0,function*(){this.writer(\`#\${e}:\${t}\${this.protocolNewline}\`)})}recvLine(e){return q(this,arguments,void 0,function*(t,r=!1){if(this.stopped)throw new X("Stopped");if(this.isWindowsShell||this.remoteIsWindows){let o=yield this.buffer.readLineOnWindows();const _=o.lastIndexOf("#"+t+":");if(_>=0)o=o.substring(_);else{const s=o.lastIndexOf("#");s>0&&(o=o.substring(s))}return o}let n=yield this.buffer.readLine();if(this.tmuxOutputJunk||r){if(n.length>0)for(;n[n.length-1]==="\\r";)n=n.substring(0,n.length-1)+(yield this.buffer.readLine());const o=n.lastIndexOf("#"+t+":");if(o>=0)n=n.substring(o);else{const _=n.lastIndexOf("#");_>0&&(n=n.substring(_))}n=(function(_){for(;;){const s=_.indexOf("\\x1BP=");if(s<0)return _;let h=s+3;const a=_.substring(h).indexOf("\\x1BP=");if(a<0)return _.substring(0,s);h+=a+3;const d=_.substring(h).indexOf("\\x1B\\\\");if(d<0)return _.substring(0,s);h+=d+2,_=_.substring(0,s)+_.substring(h)}})(n)}return n})}recvCheck(e){return q(this,arguments,void 0,function*(t,r=!1){const n=yield this.recvLine(t,r),o=n.indexOf(":");if(o<1)throw new X(gs(n),"colon",!0);const _=n.substring(1,o),s=n.substring(o+1);if(_!=t)throw new X(s,_,!0);return s})}sendInteger(e,t){return q(this,void 0,void 0,function*(){yield this.sendLine(e,t.toString())})}recvInteger(e){return q(this,arguments,void 0,function*(t,r=!1){const n=yield this.recvCheck(t,r);return Number(n)})}checkInteger(e){return q(this,void 0,void 0,function*(){const t=yield this.recvInteger("SUCC");if(t!==e)throw new X(\`Integer check [\${t}] <> [\${e}]\`,null,!0)})}sendString(e,t){return q(this,void 0,void 0,function*(){yield this.sendLine(e,gs(t))})}recvString(e){return q(this,arguments,void 0,function*(t,r=!1){return Di(As(yield this.recvCheck(t,r)),"utf8")})}checkString(e){return q(this,void 0,void 0,function*(){const t=yield this.recvString("SUCC");if(t!==e)throw new X(\`String check [\${t}] <> [\${e}]\`,null,!0)})}sendBinary(e,t){return q(this,void 0,void 0,function*(){yield this.sendLine(e,gs(t))})}recvBinary(e){return q(this,arguments,void 0,function*(t,r=!1){return As(yield this.recvCheck(t,r))})}checkBinary(e){return q(this,void 0,void 0,function*(){const t=yield this.recvBinary("SUCC");if(t.length!=e.length)throw new X(\`Binary length check [\${t.length}] <> [\${e.length}]\`,null,!0);for(let r=0;r<t.length;r++)if(t[r]!=e[r])throw new X(\`Binary check [\${t[r]}] <> [\${e[r]}]\`,null,!0)})}sendData(e,t,r){return q(this,void 0,void 0,function*(){if(!t)return void(yield this.sendBinary("DATA",e));const n=(function(o,_){if(!_.length)return o;const s=new Uint8Array(2*o.length);let h=0;for(let a=0;a<o.length;a++){let d=-1;for(let u=0;u<_.length;u++)if(o[a]==_[u][0]){d=u;break}d<0?s[h++]=o[a]:(s[h++]=_[d][1],s[h++]=_[d][2])}return s.subarray(0,h)})(e,r);this.writer(\`#DATA:\${n.length}
\`),this.writer(n)})}recvData(e,t,r){return q(this,void 0,void 0,function*(){return yield Promise.race([new Promise((n,o)=>setTimeout(()=>{this.cleanTimeoutInMilliseconds=3e3,o(new X("Receive data timeout"))},r)),q(this,void 0,void 0,function*(){if(!e)return yield this.recvBinary("DATA");const n=yield this.recvInteger("DATA");return(function(o,_){if(!_.length)return o;const s=new Uint8Array(o.length);let h=0;for(let a=0;a<o.length;a++){let d=-1;if(a<o.length-1){for(let u=0;u<_.length;u++)if(o[a]==_[u][1]&&o[a+1]==_[u][2]){d=u;break}}d<0?s[h++]=o[a]:(s[h++]=_[d][0],a++)}return s.subarray(0,h)})(yield this.buffer.readBinary(n),t)})])})}sendAction(e,t){return q(this,void 0,void 0,function*(){const r={lang:"js",confirm:e,version:"1.1.6",support_dir:!0};(this.isWindowsShell||t)&&(r.binary=!1,r.newline=\`!
\`),t&&(this.remoteIsWindows=!0,this.protocolNewline=\`!
\`),yield this.sendString("ACT",JSON.stringify(r))})}recvAction(){return q(this,void 0,void 0,function*(){const e=yield this.recvString("ACT",!0),t=JSON.parse(e);return t.newline&&(this.protocolNewline=t.newline),t})}sendConfig(e,t,r,n){return q(this,void 0,void 0,function*(){const o={lang:"js"};e.quiet&&(o.quiet=!0),e.binary&&(o.binary=!0,o.escape_chars=t),e.directory&&(o.directory=!0),e.bufsize&&(o.bufsize=e.bufsize),e.timeout&&(o.timeout=e.timeout),e.overwrite&&(o.overwrite=!0),r==Qh&&(o.tmux_output_junk=!0),n>0&&(o.tmux_pane_width=n);let _=JSON.stringify(o);_=_.replace(/[\\u007F-\\uFFFF]/g,function(s){return"\\\\u"+("0000"+s.charCodeAt(0).toString(16)).slice(-4)}),this.transferConfig=o,yield this.sendString("CFG",_)})}recvConfig(){return q(this,void 0,void 0,function*(){const e=yield this.recvString("CFG",!0);return this.transferConfig=JSON.parse(e),this.tmuxOutputJunk=this.transferConfig.tmux_output_junk===!0,this.transferConfig})}clientExit(e){return q(this,void 0,void 0,function*(){yield this.sendString("EXIT",e)})}recvExit(){return q(this,void 0,void 0,function*(){return this.recvString("EXIT")})}serverExit(e){return q(this,void 0,void 0,function*(){yield this.cleanInput(500),yield(function(){return q(this,void 0,void 0,function*(){})})(),this.isWindowsShell?(e=e.replace(/\\n/g,\`\\r
\`),yield this.sendString("ACT",JSON.stringify(r))})}recvAction(){return q(this,void 0,void 0,function*(){const e=yield this.recvString("ACT",!0),t=JSON.parse(e);return t.newline&&(this.protocolNewline=t.newline),t})}sendConfig(e,t,r,n){return q(this,void 0,void 0,function*(){const o={lang:"js"};e.quiet&&(o.quiet=!0),e.binary&&(o.binary=!0,o.escape_chars=t),e.directory&&(o.directory=!0),e.bufsize&&(o.bufsize=e.bufsize),e.timeout&&(o.timeout=e.timeout),e.overwrite&&(o.overwrite=!0),r==tl&&(o.tmux_output_junk=!0),n>0&&(o.tmux_pane_width=n);let _=JSON.stringify(o);_=_.replace(/[\\u007F-\\uFFFF]/g,function(s){return"\\\\u"+("0000"+s.charCodeAt(0).toString(16)).slice(-4)}),this.transferConfig=o,yield this.sendString("CFG",_)})}recvConfig(){return q(this,void 0,void 0,function*(){const e=yield this.recvString("CFG",!0);return this.transferConfig=JSON.parse(e),this.tmuxOutputJunk=this.transferConfig.tmux_output_junk===!0,this.transferConfig})}clientExit(e){return q(this,void 0,void 0,function*(){yield this.sendString("EXIT",e)})}recvExit(){return q(this,void 0,void 0,function*(){return this.recvString("EXIT")})}serverExit(e){return q(this,void 0,void 0,function*(){yield this.cleanInput(500),yield(function(){return q(this,void 0,void 0,function*(){})})(),this.isWindowsShell?(e=e.replace(/\\n/g,\`\\r
\`),process.stdout.write("\\x1B[H\\x1B[2J\\x1B[?1049l")):process.stdout.write("\\x1B8\\x1B[0J"),process.stdout.write(e),process.stdout.write(\`\\r
\`),process.stdout.write("\\x1B[?25h"),this.transferConfig.tmux_output_junk&&(yield(function(){return q(this,void 0,void 0,function*(){yield require("util").promisify(require("child_process").exec)("tmux refresh-client")})})())})}deleteCreatedFiles(){return q(this,void 0,void 0,function*(){const e=[];for(const t of this.createdFiles){const r=yield t.deleteFile();r&&e.push(r)}return e})}clientError(e){return q(this,void 0,void 0,function*(){yield this.cleanInput(this.cleanTimeoutInMilliseconds);const t=X.getErrorMessage(e);let r=!0;if(e instanceof X){if(r=e.isTraceBack(),e.isRemoteExit())return;if(e.isRemoteFail())return void(r&&console.log(t))}yield this.sendString(r?"FAIL":"fail",t),r&&console.log(t)})}serverError(e){return q(this,void 0,void 0,function*(){yield this.cleanInput(this.cleanTimeoutInMilliseconds);const t=X.getErrorMessage(e);let r=!0;if(e instanceof X){if(e.isStopAndDelete()){const n=yield this.deleteCreatedFiles();if(n&&n.length)return void(yield this.serverExit([e.message+":"].concat(n).join(\`\\r
- \`)))}if(r=e.isTraceBack(),e.isRemoteExit()||e.isRemoteFail())return void(yield this.serverExit(t))}yield this.sendString(r?"FAIL":"fail",t),yield this.serverExit(t)})}sendFileNum(e,t){return q(this,void 0,void 0,function*(){yield this.sendInteger("NUM",e),yield this.checkInteger(e),t&&t.onNum(e)})}sendFileName(e,t,r){return q(this,void 0,void 0,function*(){const n=e.getRelPath(),o=n[n.length-1];if(t){const s={path_id:e.getPathId(),path_name:n,is_dir:e.isDir()};yield this.sendString("NAME",JSON.stringify(s))}else yield this.sendString("NAME",o);const _=yield this.recvString("SUCC");return r&&r.onName(o),_})}sendFileSize(e,t){return q(this,void 0,void 0,function*(){yield this.sendInteger("SIZE",e),yield this.checkInteger(e),t&&t.onSize(e)})}sendFileData(e,t,r,n,o,_){return q(this,void 0,void 0,function*(){let s=0;_&&_.onStep(s);let h=1024,a=new ArrayBuffer(h);const d=new hi;for(;s<t;){const u=Date.now(),p=yield e.readFile(a);yield this.sendData(p,r,n),d.appendByteArray(p),yield this.checkInteger(p.length),s+=p.length,_&&_.onStep(s);const m=Date.now()-u;p.length==h&&m<500&&h<o?(h=Math.min(2*h,o),a=new ArrayBuffer(h)):m>=2e3&&h>1024&&(h=1024,a=new ArrayBuffer(h)),m>this.maxChunkTimeInMilliseconds&&(this.maxChunkTimeInMilliseconds=m)}return new Uint8Array(d.end(!0).buffer)})}sendFileMD5(e,t){return q(this,void 0,void 0,function*(){yield this.sendBinary("MD5",e),yield this.checkBinary(e),t&&t.onDone()})}sendFiles(e,t){return q(this,void 0,void 0,function*(){this.openedFiles.push(...e);const r=this.transferConfig.binary===!0,n=this.transferConfig.directory===!0,o=this.transferConfig.bufsize?Math.min(this.transferConfig.bufsize,this.maxDataChunkSize):this.maxDataChunkSize,_=this.transferConfig.escape_chars?qr(this.transferConfig.escape_chars):[];yield this.sendFileNum(e.length,t);const s=[];for(const h of e){const a=yield this.sendFileName(h,n,t);if(s.includes(a)||s.push(a),h.isDir())continue;const d=h.getSize();yield this.sendFileSize(d,t);const u=yield this.sendFileData(h,d,r,_,o,t);h.closeFile(),yield this.sendFileMD5(u,t)}return s})}recvFileNum(e){return q(this,void 0,void 0,function*(){const t=yield this.recvInteger("NUM");return yield this.sendInteger("SUCC",t),e&&e.onNum(t),t})}recvFileName(e,t,r,n,o){return q(this,void 0,void 0,function*(){const _=yield this.recvString("NAME"),s=yield t(e,_,r,n);return this.createdFiles.push(s),yield this.sendString("SUCC",s.getLocalName()),o&&o.onName(s.getFileName()),s})}recvFileSize(e){return q(this,void 0,void 0,function*(){const t=yield this.recvInteger("SIZE");return yield this.sendInteger("SUCC",t),e&&e.onSize(t),t})}recvFileData(e,t,r,n,o,_){return q(this,void 0,void 0,function*(){let s=0;_&&_.onStep(s);const h=new hi;for(;s<t;){const a=Date.now(),d=yield this.recvData(r,n,o);yield e.writeFile(d),s+=d.length,_&&_.onStep(s),yield this.sendInteger("SUCC",d.length),h.appendByteArray(d);const u=Date.now()-a;u>this.maxChunkTimeInMilliseconds&&(this.maxChunkTimeInMilliseconds=u)}return new Uint8Array(h.end(!0).buffer)})}recvFileMD5(e,t){return q(this,void 0,void 0,function*(){const r=yield this.recvBinary("MD5");if(e.length!=r.length)throw new X("Check MD5 failed");for(let n=0;n<e.length;n++)if(e[n]!=r[n])throw new X("Check MD5 failed");yield this.sendBinary("SUCC",e),t&&t.onDone()})}recvFiles(e,t,r){return q(this,void 0,void 0,function*(){const n=this.transferConfig.binary===!0,o=this.transferConfig.directory===!0,_=this.transferConfig.overwrite===!0,s=this.transferConfig.timeout?1e3*this.transferConfig.timeout:1e5,h=this.transferConfig.escape_chars?qr(this.transferConfig.escape_chars):[],a=yield this.recvFileNum(r),d=[];for(let u=0;u<a;u++){const p=yield this.recvFileName(e,t,o,_,r);if(d.includes(p.getLocalName())||d.push(p.getLocalName()),p.isDir())continue;this.openedFiles.push(p);const m=yield this.recvFileSize(r),C=yield this.recvFileData(p,m,n,h,s,r);p.closeFile(),yield this.recvFileMD5(C,r)}return d})}}function Ci(i,e){e-=3;let t=0,r="";for(let n=0;n<i.length;n++){if(i.charCodeAt(n)>=19968&&i.charCodeAt(n)<=40869){if(t+2>e)return{sub:r+"...",len:t+3};t+=2}else{if(t+1>e)return{sub:r+"...",len:t+3};t+=1}r+=i[n]}return{sub:r+"...",len:t+3}}function Kr(i){let e="B";do{if(i<1024||(e="KB",(i/=1024)<1024)||(e="MB",(i/=1024)<1024)||(e="GB",(i/=1024)<1024))break;i/=1024,e="TB"}while(!1);return i>=100?\`\${i.toFixed(0)} \${e}\`:i>=10?\`\${i.toFixed(1)} \${e}\`:\`\${i.toFixed(2)} \${e}\`}Oi.MAX_DATA_CHUNK_SIZE=10485760;class ol{constructor(e,t,r=void 0){this.lastUpdateTime=0,this.firstWrite=!0,this.speedCnt=0,this.speedIdx=0,this.timeArray=new Array(30),this.stepArray=new Array(30),this.writer=e,this.tmuxPaneColumns=r||0,this.columns=this.tmuxPaneColumns>1?this.tmuxPaneColumns-1:t}setTerminalColumns(e){this.columns=e,this.tmuxPaneColumns>0&&(this.tmuxPaneColumns=0)}onNum(e){this.fileCount=e,this.fileIdx=0}onName(e){this.fileName=e,this.fileIdx+=1,this.startTime=Date.now(),this.timeArray[0]=this.startTime,this.stepArray[0]=0,this.speedCnt=1,this.speedIdx=1,this.fileStep=- Line truncated
\`)}setTimeout(()=>this.detectAndHandleTrzsz(e),10),this.writeToTerminal(e)}}processTerminalInput(e){this.isTransferringFiles()?e===""&&this.stopTransferringFiles():this.sendToServer(e)}processBinaryInput(e){this.isTransferringFiles()||this.sendToServer(Ti(e))}setTerminalColumns(e){this.terminalColumns=e,this.textProgressBar!=null&&this.textProgressBar.setTerminalColumns(e)}isTransferringFiles(){return this.trzszTransfer!=null}stopTransferringFiles(){this.isTransferringFiles()&&this.trzszTransfer.stopTransferring()}uploadFiles(e){return q(this,void 0,void 0,function*(){if(this.uploadFilesList||this.isTransferringFiles())throw new Error("The previous upload has not been completed yet");if(!Ut&&(function(r,n){if(!Array.isArray(r))return!1;for(const o of r)if(typeof o!==n)return!1;return!0})(e,"string"))this.uploadFilesList=yield Hr(e,!0);else{if(!(typeof DataTransferItemList<"u"&&e instanceof DataTransferItemList))throw new Error("The upload items type is not supported");this.uploadFilesList=yield(function(r){return q(this,void 0,void 0,function*(){const n=[],o=[];for(const _ of r)o.push(_.webkitGetAsEntry());for(let _=0;_<o.length;_++){const s=o[_];s&&(yield io(_,s,n,[s.name]))}return n})})(e)}if(!this.uploadFilesList||!this.uploadFilesList.length)throw this.uploadFilesList=null,new Error("No files to upload");let t=!1;for(const r of this.uploadFilesList)if(r.isDir()||r.getRelPath().length>1){t=!0;break}return this.uploadInterrupting=!0,this.sendToServer(""),yield new Promise(r=>setTimeout(r,200)),this.uploadInterrupting=!1,this.uploadSkipTrzCommand=!0,this.sendToServer(t?"trz -d\\r":"trz\\r"),setTimeout(()=>{this.uploadFilesList&&(this.uploadFilesList=null,this.uploadFilesResolve=null,this.uploadFilesReject&&(this.uploadFilesReject("Upload does not start"),this.uploadFilesReject=null))},this.dragInitTimeout),new Promise((r,n)=>{this.uploadFilesResolve=r,this.uploadFilesReject=n})})}uniqueIdExists(e){if(e.length<8||!this.isWindowsShell&&e.length==14&&e.endsWith("00"))return!1;if(this.uniqueIdMaps.has(e))return!0;if(this.uniqueIdMaps.size>=100){const t=new Map;for(const[r,n]of this.uniqueIdMaps)n>=50&&t.set(r,n-50);this.uniqueIdMaps=t}return this.uniqueIdMaps.set(e,this.uniqueIdMaps.size),!1}detectAndHandleTrzsz(e){return q(this,void 0,void 0,function*(){const t=yield(function(h){return q(this,void 0,void 0,function*(){if(typeof h=="string"){const p=h.lastIndexOf(so);return p<0?null:h.substring(p)}let a;if(h instanceof ArrayBuffer)a=new Uint8Array(h);else if(h instanceof Uint8Array)a=h;else{if(!(h instanceof Blob))return null;a=new Uint8Array(yield h.arrayBuffer())}if(a.length<26)return null;let d=-1,u=-1;for(;;){if(d=a.indexOf(58,d+1),d<0||a.length-d<26)return u>=0?Di(a.subarray(u)):null;const p=new Float64Array(a.buffer.slice(a.byteOffset+d,a.byteOffset+d+16));p[0]==Vr[0]&&p[1]==Vr[1]&&(u=d,d+=25)}})})(e);if(!t)return;const r=t.match(al);if(!r)return;const n=r.length>3?r[3]:"";if(this.uniqueIdExists(n))return;const o=r[1],_=r[2];let s=!1;(n==":1"||n.length==14&&n.endsWith("10"))&&(s=!0);try{this.trzszTransfer=new Oi(this.sendToServer,this.isWindowsShell,this.maxDataChunkSize),o==="S"?yield this.handleTrzszDownloadFiles(_,s):o==="R"?yield this.handleTrzszUploadFiles(_,!1,s):o==="D"&&(yield this.handleTrzszUploadFiles(_,!0,s)),this.uploadFilesResolve&&this.uploadFilesResolve()}catch(h){yield this.trzszTransfer.clientError(h),this.uploadFilesReject&&this.uploadFilesReject(h)}finally{this.uploadFilesResolve=null,this.uploadFilesReject=null,this.trzszTransfer.cleanup(),this.textProgressBar&&this.textProgressBar.showCursor(),this.textProgressBar=null,this.trzszTransfer=null}})}createProgressBar(e,t){e!==!0?(this.textProgressBar=new ol(this.writeToTerminal,this.terminalColumns,t),this.textProgressBar.hideCursor()):this.textProgressBar=null}handleTrzszDownloadFiles(e,t){return q(this,void 0,void 0,function*(){let r,n,o;if(Ut){const h=yield(function(){return q(this,void 0,void 0,function*(){if(typeof window.showDirectoryPicker!="function")throw Bs();try{return yield window.showDirectoryPicker({id:"trzsz_download",startIn:"downloads",mode:"readwrite"})}catch(a){if(a.name==="AbortError")return;throw a}})})();if(!h)return void(yield this.trzszTransfer.sendAction(!1,t));r=h.name,n={handle:h,maps:new Map},o=il}else{if(r=yield this.chooseSaveDirectory(),!r)return void(yield this.trzszTransfer.sendAction(!1,t));yield(function(h){return q(this,void 0,void 0,function*(){if(!h)return!1;if(!(yield te.accessAsync(h)))throw new X(\`No such directory: \${h}\`);if(!(yield te.statAsync(h)).isDirectory())throw new X(\`Not a directory: \${h}\`);if(!(yield te.accessAsync(h,te.constants.W_OK)))throw new X(\`No permission to write: \${h}\`);return!0})})(r),n={path:r,maps:new Map},o=el}yield this.trzszTransfer.sendAction(!0,t);const _=yield this.trzszTransfer.recvConfig();this.createProgressBar(_.quiet,_.tmux_pane_width);const s=yield this.trzszTransfer.recvFiles(n,o,this.textProgressBar);yield this.trzszTransfer.clientExit(Fr(s,r))}) Line truncated
- \`)))}if(r=e.isTraceBack(),e.isRemoteExit()||e.isRemoteFail())return void(yield this.serverExit(t))}yield this.sendString(r?"FAIL":"fail",t),yield this.serverExit(t)})}sendFileNum(e,t){return q(this,void 0,void 0,function*(){yield this.sendInteger("NUM",e),yield this.checkInteger(e),t&&t.onNum(e)})}sendFileName(e,t,r){return q(this,void 0,void 0,function*(){const n=e.getRelPath(),o=n[n.length-1];if(t){const s={path_id:e.getPathId(),path_name:n,is_dir:e.isDir()};yield this.sendString("NAME",JSON.stringify(s))}else yield this.sendString("NAME",o);const _=yield this.recvString("SUCC");return r&&r.onName(o),_})}sendFileSize(e,t){return q(this,void 0,void 0,function*(){yield this.sendInteger("SIZE",e),yield this.checkInteger(e),t&&t.onSize(e)})}sendFileData(e,t,r,n,o,_){return q(this,void 0,void 0,function*(){let s=0;_&&_.onStep(s);let h=1024,a=new ArrayBuffer(h);const d=new hi;for(;s<t;){const u=Date.now(),p=yield e.readFile(a);yield this.sendData(p,r,n),d.appendByteArray(p),yield this.checkInteger(p.length),s+=p.length,_&&_.onStep(s);const m=Date.now()-u;p.length==h&&m<500&&h<o?(h=Math.min(2*h,o),a=new ArrayBuffer(h)):m>=2e3&&h>1024&&(h=1024,a=new ArrayBuffer(h)),m>this.maxChunkTimeInMilliseconds&&(this.maxChunkTimeInMilliseconds=m)}return new Uint8Array(d.end(!0).buffer)})}sendFileMD5(e,t){return q(this,void 0,void 0,function*(){yield this.sendBinary("MD5",e),yield this.checkBinary(e),t&&t.onDone()})}sendFiles(e,t){return q(this,void 0,void 0,function*(){this.openedFiles.push(...e);const r=this.transferConfig.binary===!0,n=this.transferConfig.directory===!0,o=this.transferConfig.bufsize?Math.min(this.transferConfig.bufsize,this.maxDataChunkSize):this.maxDataChunkSize,_=this.transferConfig.escape_chars?Kr(this.transferConfig.escape_chars):[];yield this.sendFileNum(e.length,t);const s=[];for(const h of e){const a=yield this.sendFileName(h,n,t);if(s.includes(a)||s.push(a),h.isDir())continue;const d=h.getSize();yield this.sendFileSize(d,t);const u=yield this.sendFileData(h,d,r,_,o,t);h.closeFile(),yield this.sendFileMD5(u,t)}return s})}recvFileNum(e){return q(this,void 0,void 0,function*(){const t=yield this.recvInteger("NUM");return yield this.sendInteger("SUCC",t),e&&e.onNum(t),t})}recvFileName(e,t,r,n,o){return q(this,void 0,void 0,function*(){const _=yield this.recvString("NAME"),s=yield t(e,_,r,n);return this.createdFiles.push(s),yield this.sendString("SUCC",s.getLocalName()),o&&o.onName(s.getFileName()),s})}recvFileSize(e){return q(this,void 0,void 0,function*(){const t=yield this.recvInteger("SIZE");return yield this.sendInteger("SUCC",t),e&&e.onSize(t),t})}recvFileData(e,t,r,n,o,_){return q(this,void 0,void 0,function*(){let s=0;_&&_.onStep(s);const h=new hi;for(;s<t;){const a=Date.now(),d=yield this.recvData(r,n,o);yield e.writeFile(d),s+=d.length,_&&_.onStep(s),yield this.sendInteger("SUCC",d.length),h.appendByteArray(d);const u=Date.now()-a;u>this.maxChunkTimeInMilliseconds&&(this.maxChunkTimeInMilliseconds=u)}return new Uint8Array(h.end(!0).buffer)})}recvFileMD5(e,t){return q(this,void 0,void 0,function*(){const r=yield this.recvBinary("MD5");if(e.length!=r.length)throw new X("Check MD5 failed");for(let n=0;n<e.length;n++)if(e[n]!=r[n])throw new X("Check MD5 failed");yield this.sendBinary("SUCC",e),t&&t.onDone()})}recvFiles(e,t,r){return q(this,void 0,void 0,function*(){const n=this.transferConfig.binary===!0,o=this.transferConfig.directory===!0,_=this.transferConfig.overwrite===!0,s=this.transferConfig.timeout?1e3*this.transferConfig.timeout:1e5,h=this.transferConfig.escape_chars?Kr(this.transferConfig.escape_chars):[],a=yield this.recvFileNum(r),d=[];for(let u=0;u<a;u++){const p=yield this.recvFileName(e,t,o,_,r);if(d.includes(p.getLocalName())||d.push(p.getLocalName()),p.isDir())continue;this.openedFiles.push(p);const m=yield this.recvFileSize(r),C=yield this.recvFileData(p,m,n,h,s,r);p.closeFile(),yield this.recvFileMD5(C,r)}return d})}}function Ci(i,e){e-=3;let t=0,r="";for(let n=0;n<i.length;n++){if(i.charCodeAt(n)>=19968&&i.charCodeAt(n)<=40869){if(t+2>e)return{sub:r+"...",len:t+3};t+=2}else{if(t+1>e)return{sub:r+"...",len:t+3};t+=1}r+=i[n]}return{sub:r+"...",len:t+3}}function Vr(i){let e="B";do{if(i<1024||(e="KB",(i/=1024)<1024)||(e="MB",(i/=1024)<1024)||(e="GB",(i/=1024)<1024))break;i/=1024,e="TB"}while(!1);return i>=100?\`\${i.toFixed(0)} \${e}\`:i>=10?\`\${i.toFixed(1)} \${e}\`:\`\${i.toFixed(2)} \${e}\`}Oi.MAX_DATA_CHUNK_SIZE=10485760;class hl{constructor(e,t,r=void 0){this.lastUpdateTime=0,this.firstWrite=!0,this.speedCnt=0,this.speedIdx=0,this.timeArray=new Array(30),this.stepArray=new Array(30),this.writer=e,this.tmuxPaneColumns=r||0,this.columns=this.tmuxPaneColumns>1?this.tmuxPaneColumns-1:t}setTerminalColumns(e){this.columns=e,this.tmuxPaneColumns>0&&(this.tmuxPaneColumns=0)}onNum(e){this.fileCount=e,this.fileIdx=0}onName(e){this.fileName=e,this.fileIdx+=1,this.startTime=Date.now(),this.timeArray[0]=this.startTime,this.stepArray[0]=0,this.speedCnt=1,this.speedIdx=1,this.fileStep=- Line truncated
\`)}setTimeout(()=>this.detectAndHandleTrzsz(e),10),this.writeToTerminal(e)}}processTerminalInput(e){this.isTransferringFiles()?e===""&&this.stopTransferringFiles():this.sendToServer(e)}processBinaryInput(e){this.isTransferringFiles()||this.sendToServer(Ti(e))}setTerminalColumns(e){this.terminalColumns=e,this.textProgressBar!=null&&this.textProgressBar.setTerminalColumns(e)}isTransferringFiles(){return this.trzszTransfer!=null}stopTransferringFiles(){this.isTransferringFiles()&&this.trzszTransfer.stopTransferring()}uploadFiles(e){return q(this,void 0,void 0,function*(){if(this.uploadFilesList||this.isTransferringFiles())throw new Error("The previous upload has not been completed yet");if(!Ut&&(function(r,n){if(!Array.isArray(r))return!1;for(const o of r)if(typeof o!==n)return!1;return!0})(e,"string"))this.uploadFilesList=yield zr(e,!0);else{if(!(typeof DataTransferItemList<"u"&&e instanceof DataTransferItemList))throw new Error("The upload items type is not supported");this.uploadFilesList=yield(function(r){return q(this,void 0,void 0,function*(){const n=[],o=[];for(const _ of r)o.push(_.webkitGetAsEntry());for(let _=0;_<o.length;_++){const s=o[_];s&&(yield so(_,s,n,[s.name]))}return n})})(e)}if(!this.uploadFilesList||!this.uploadFilesList.length)throw this.uploadFilesList=null,new Error("No files to upload");let t=!1;for(const r of this.uploadFilesList)if(r.isDir()||r.getRelPath().length>1){t=!0;break}return this.uploadInterrupting=!0,this.sendToServer(""),yield new Promise(r=>setTimeout(r,200)),this.uploadInterrupting=!1,this.uploadSkipTrzCommand=!0,this.sendToServer(t?"trz -d\\r":"trz\\r"),setTimeout(()=>{this.uploadFilesList&&(this.uploadFilesList=null,this.uploadFilesResolve=null,this.uploadFilesReject&&(this.uploadFilesReject("Upload does not start"),this.uploadFilesReject=null))},this.dragInitTimeout),new Promise((r,n)=>{this.uploadFilesResolve=r,this.uploadFilesReject=n})})}uniqueIdExists(e){if(e.length<8||!this.isWindowsShell&&e.length==14&&e.endsWith("00"))return!1;if(this.uniqueIdMaps.has(e))return!0;if(this.uniqueIdMaps.size>=100){const t=new Map;for(const[r,n]of this.uniqueIdMaps)n>=50&&t.set(r,n-50);this.uniqueIdMaps=t}return this.uniqueIdMaps.set(e,this.uniqueIdMaps.size),!1}detectAndHandleTrzsz(e){return q(this,void 0,void 0,function*(){const t=yield(function(h){return q(this,void 0,void 0,function*(){if(typeof h=="string"){const p=h.lastIndexOf(ro);return p<0?null:h.substring(p)}let a;if(h instanceof ArrayBuffer)a=new Uint8Array(h);else if(h instanceof Uint8Array)a=h;else{if(!(h instanceof Blob))return null;a=new Uint8Array(yield h.arrayBuffer())}if(a.length<26)return null;let d=-1,u=-1;for(;;){if(d=a.indexOf(58,d+1),d<0||a.length-d<26)return u>=0?Di(a.subarray(u)):null;const p=new Float64Array(a.buffer.slice(a.byteOffset+d,a.byteOffset+d+16));p[0]==Gr[0]&&p[1]==Gr[1]&&(u=d,d+=25)}})})(e);if(!t)return;const r=t.match(ll);if(!r)return;const n=r.length>3?r[3]:"";if(this.uniqueIdExists(n))return;const o=r[1],_=r[2];let s=!1;(n==":1"||n.length==14&&n.endsWith("10"))&&(s=!0);try{this.trzszTransfer=new Oi(this.sendToServer,this.isWindowsShell,this.maxDataChunkSize),o==="S"?yield this.handleTrzszDownloadFiles(_,s):o==="R"?yield this.handleTrzszUploadFiles(_,!1,s):o==="D"&&(yield this.handleTrzszUploadFiles(_,!0,s)),this.uploadFilesResolve&&this.uploadFilesResolve()}catch(h){yield this.trzszTransfer.clientError(h),this.uploadFilesReject&&this.uploadFilesReject(h)}finally{this.uploadFilesResolve=null,this.uploadFilesReject=null,this.trzszTransfer.cleanup(),this.textProgressBar&&this.textProgressBar.showCursor(),this.textProgressBar=null,this.trzszTransfer=null}})}createProgressBar(e,t){e!==!0?(this.textProgressBar=new hl(this.writeToTerminal,this.terminalColumns,t),this.textProgressBar.hideCursor()):this.textProgressBar=null}handleTrzszDownloadFiles(e,t){return q(this,void 0,void 0,function*(){let r,n,o;if(Ut){const h=yield(function(){return q(this,void 0,void 0,function*(){if(typeof window.showDirectoryPicker!="function")throw Bs();try{return yield window.showDirectoryPicker({id:"trzsz_download",startIn:"downloads",mode:"readwrite"})}catch(a){if(a.name==="AbortError")return;throw a}})})();if(!h)return void(yield this.trzszTransfer.sendAction(!1,t));r=h.name,n={handle:h,maps:new Map},o=rl}else{if(r=yield this.chooseSaveDirectory(),!r)return void(yield this.trzszTransfer.sendAction(!1,t));yield(function(h){return q(this,void 0,void 0,function*(){if(!h)return!1;if(!(yield te.accessAsync(h)))throw new X(\`No such directory: \${h}\`);if(!(yield te.statAsync(h)).isDirectory())throw new X(\`Not a directory: \${h}\`);if(!(yield te.accessAsync(h,te.constants.W_OK)))throw new X(\`No permission to write: \${h}\`);return!0})})(r),n={path:r,maps:new Map},o=il}yield this.trzszTransfer.sendAction(!0,t);const _=yield this.trzszTransfer.recvConfig();this.createProgressBar(_.quiet,_.tmux_pane_width);const s=yield this.trzszTransfer.recvFiles(n,o,this.textProgressBar);yield this.trzszTransfer.clientExit($r(s,r))}) Line truncated
<button type="button" id="github-login-btn" class="github-login-btn text-[11px] font-bold tracking-[0.1em] text-[#bbccb0] hover:text-[#4af626] transition-all cursor-pointer flex items-center gap-1.5 bg-transparent border border-[#3c4b36] px-3 py-1 hover:border-[#4af626]">
<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>
LOGIN
@@ -198,7 +198,7 @@ void main() {
<span id="github-login-placeholder"></span>
</div>
</form>
\`,document.getElementById("connect-btn").addEventListener("click",()=>{this.handleConnect()}),document.getElementById("connection-form").addEventListener("keypress",t=>{t.key==="Enter"&&this.handleConnect()}),document.getElementById("auth-tab-password").addEventListener("click",()=>{this.setAuthMode("password")}),document.getElementById("auth-tab-key").addEventListener("click",()=>{this.setAuthMode("key")})}setAuthMode(e){this.authMode=e;const t=document.getElementById("auth-tab-password"),r=document.getElementById("auth-tab-key"),n=document.getElementById("auth-password-section"),o=document.getElementById("auth-key-section");e==="password"?(t.style.background="#4af626",t.style.color="#0a0a0a",t.style.borderColor="#4af626",r.style.background="transparent",r.style.color="#bbccb0",r.style.borderColor="#3c4b36",n.style.display="",o.style.display="none"):(r.style.background="#4af626",r.style.color="#0a0a0a",r.style.borderColor="#4af626",t.style.background="transparent",t.style.color="#bbccb0",t.style.borderColor="#3c4b36",o.style.display="",n.style.display="none")}async loadSavedCredentials(){const e=localStorage.getItem("cloudssh_cred");if(!e)return;const t=await dl(e);if(!t){localStorage.removeItem("cloudssh_cred");return}document.getElementById("host").value=t.host||"",document.getElementById("port").value=t.port||"22",document.getElementById("username").value=t.username||"",document.getElementById("password").value=t.password||"",document.getElementById("private-key").value=t.privateKey||"",document.getElementById("remember-me").checked=!0,t.authMethod==="key"?this.setAuthMode("key"):this.setAuthMode("password")}async handleConnect(){const t=document.getElementById("host").value.replace(/^\\[|\\]$/g,"").trim(),r=parseInt(document.getElementById("port").value||"22"),n=document.getElementById("username").value,o=document.getElementById("password").value,_=document.getElementById("private-key").value,s=document.getElementById("remember-me").checked;if(!t||!n){alert("请填写主机名和用户名");return}if(this.authMode==="password"&&!o){alert("请输入密码");return}if(this.authMode==="key"&&!_){alert("请粘贴私钥内容");return}if(this.turnstileEnabled&&!this.turnstileVerified){alert("请完成人机验证");return}if(s){const d=await cl({host:t,port:r.toString(),username:n,password:o,privateKey:_,authMethod:this.authMode==="key"?"publickey":"password"});localStorage.setItem("cloudssh_cred",d)}else localStorage.removeItem("cloudssh_cred");const h=document.getElementById("auth-section"),a=document.getElementById("terminal-section");h.classList.add("hidden"),a.classList.remove("hidden"),a.classList.add("flex"),document.getElementById("term-host").textContent="Host: "+t,document.getElementById("term-user").textContent="User: "+n,document.getElementById("term-port").textContent="Port: "+r,this.terminal.mount();try{await this.terminal.connect({host:t,port:r,username:n,password:o,authMethod:this.authMode==="key"?"publickey":"password",privateKey:_})}catch{a.classList.add("hidden"),a.classList.remove("flex"),h.classList.remove("hidden"),document.getElementById("status-text").innerHTML='<span class="w-2 h-2 bg-[#353534] inline-block"></span> STATUS: OFFLINE'}}}class fl{constructor(e,t){Q(this,"user");Q(this,"servers",[]);Q(this,"onLogout");Q(this,"editingServerId",null);Q(this,"modalAuthMode","password");this.user=e,this.onLogout=t,this.init()}async init(){this.renderUserInfo(),this.bindEvents(),await this.fetchServers();const e=document.getElementById("user-copyright-year");e&&(e.textContent=new Date().getFullYear().toString())}renderUserInfo(){const e=document.getElementById("user-info");e&&(e.innerHTML=\`
\`,document.getElementById("connect-btn").addEventListener("click",()=>{this.handleConnect()}),document.getElementById("connection-form").addEventListener("keypress",t=>{t.key==="Enter"&&this.handleConnect()}),document.getElementById("auth-tab-password").addEventListener("click",()=>{this.setAuthMode("password")}),document.getElementById("auth-tab-key").addEventListener("click",()=>{this.setAuthMode("key")})}setAuthMode(e){this.authMode=e;const t=document.getElementById("auth-tab-password"),r=document.getElementById("auth-tab-key"),n=document.getElementById("auth-password-section"),o=document.getElementById("auth-key-section");e==="password"?(t.style.background="#4af626",t.style.color="#0a0a0a",t.style.borderColor="#4af626",r.style.background="transparent",r.style.color="#bbccb0",r.style.borderColor="#3c4b36",n.style.display="",o.style.display="none"):(r.style.background="#4af626",r.style.color="#0a0a0a",r.style.borderColor="#4af626",t.style.background="transparent",t.style.color="#bbccb0",t.style.borderColor="#3c4b36",o.style.display="",n.style.display="none")}async loadSavedCredentials(){const e=localStorage.getItem("cloudssh_cred");if(!e)return;const t=await fl(e);if(!t){localStorage.removeItem("cloudssh_cred");return}document.getElementById("host").value=t.host||"",document.getElementById("port").value=t.port||"22",document.getElementById("username").value=t.username||"",document.getElementById("password").value=t.password||"",document.getElementById("private-key").value=t.privateKey||"",document.getElementById("remember-me").checked=!0,t.authMethod==="key"?this.setAuthMode("key"):this.setAuthMode("password")}async handleConnect(){const t=document.getElementById("host").value.replace(/^\\[|\\]$/g,"").trim(),r=parseInt(document.getElementById("port").value||"22"),n=document.getElementById("username").value,o=document.getElementById("password").value,_=document.getElementById("private-key").value,s=document.getElementById("remember-me").checked;if(!t||!n){alert("请填写主机名和用户名");return}if(this.authMode==="password"&&!o){alert("请输入密码");return}if(this.authMode==="key"&&!_){alert("请粘贴私钥内容");return}if(this.turnstileEnabled&&!this.turnstileVerified){alert("请完成人机验证");return}if(s){const d=await ul({host:t,port:r.toString(),username:n,password:o,privateKey:_,authMethod:this.authMode==="key"?"publickey":"password"});localStorage.setItem("cloudssh_cred",d)}else localStorage.removeItem("cloudssh_cred");const h=document.getElementById("auth-section"),a=document.getElementById("terminal-section");h.classList.add("hidden"),a.classList.remove("hidden"),a.classList.add("flex"),document.getElementById("term-host").textContent="Host: "+t,document.getElementById("term-user").textContent="User: "+n,document.getElementById("term-port").textContent="Port: "+r,this.terminal.mount();try{await this.terminal.connect({host:t,port:r,username:n,password:o,authMethod:this.authMode==="key"?"publickey":"password",privateKey:_})}catch{a.classList.add("hidden"),a.classList.remove("flex"),h.classList.remove("hidden"),document.getElementById("status-text").innerHTML='<span class="w-2 h-2 bg-[#353534] inline-block"></span> STATUS: OFFLINE'}}}class gl{constructor(e,t){Q(this,"user");Q(this,"servers",[]);Q(this,"onLogout");Q(this,"editingServerId",null);Q(this,"modalAuthMode","password");this.user=e,this.onLogout=t,this.init()}async init(){this.renderUserInfo(),this.bindEvents(),await this.fetchServers();const e=document.getElementById("user-copyright-year");e&&(e.textContent=new Date().getFullYear().toString())}renderUserInfo(){const e=document.getElementById("user-info");e&&(e.innerHTML=\`
<img src="\${this.user.avatar_url}" alt="\${this.user.username}" class="user-avatar w-8 h-8" />
<span class="text-xs font-bold tracking-[0.1em] text-[#bbccb0]">\${this.user.username}</span>
\`)}bindEvents(){var e,t,r,n,o,_,s,h,a;(e=document.getElementById("logout-btn"))==null||e.addEventListener("click",()=>this.logout()),(t=document.getElementById("add-server-btn"))==null||t.addEventListener("click",()=>this.showModal("add")),(r=document.getElementById("empty-add-btn"))==null||r.addEventListener("click",()=>this.showModal("add")),(n=document.getElementById("modal-close-btn"))==null||n.addEventListener("click",()=>this.hideModal()),(o=document.getElementById("modal-backdrop"))==null||o.addEventListener("click",()=>this.hideModal()),(_=document.getElementById("server-submit-btn"))==null||_.addEventListener("click",()=>this.handleSubmit()),(s=document.getElementById("modal-auth-tab-password"))==null||s.addEventListener("click",()=>this.setModalAuthMode("password")),(h=document.getElementById("modal-auth-tab-key"))==null||h.addEventListener("click",()=>this.setModalAuthMode("key")),(a=document.getElementById("server-form"))==null||a.addEventListener("keypress",d=>{d.key==="Enter"&&(d.preventDefault(),this.handleSubmit())})}async fetchServers(){try{const e=await fetch("/api/servers");if(!e.ok)throw new Error("Failed to fetch servers");this.servers=await e.json(),this.renderServerGrid()}catch(e){console.error("Failed to fetch servers:",e),this.servers=[],this.renderServerGrid()}}renderServerGrid(){const e=document.getElementById("server-grid"),t=document.getElementById("empty-state");if(!(!e||!t)){if(this.servers.length===0){e.innerHTML="",t.classList.remove("hidden"),t.classList.add("flex");return}t.classList.add("hidden"),t.classList.remove("flex"),e.innerHTML=this.servers.map(r=>this.renderServerCard(r)).join(""),this.servers.forEach(r=>{var n,o,_;(n=document.getElementById(\`connect-\${r.id}\`))==null||n.addEventListener("click",()=>this.connectServer(r.id)),(o=document.getElementById(\`edit-\${r.id}\`))==null||o.addEventListener("click",()=>this.showModal("edit",r)),(_=document.getElementById(\`delete-\${r.id}\`))==null||_.addEventListener("click",()=>this.deleteServer(r.id))})}}renderServerCard(e){const t=e.auth_method==="publickey"?"vpn_key":"password",r=e.auth_method==="publickey"?"KEY":"PWD";return\`
@@ -258,7 +258,7 @@ void main() {
\`;try{const d={name:e,host:t,port:r,username:n,auth_method:s};h&&(d.credential=h);let u;if(this.editingServerId?u=await fetch(\`/api/servers/\${this.editingServerId}\`,{method:"PUT",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}):u=await fetch("/api/servers",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d)}),!u.ok){const p=await u.json();throw new Error(p.error||"Save failed")}this.hideModal(),await this.fetchServers()}catch(d){alert(\`保存失败: \${d instanceof Error?d.message:String(d)}\`)}finally{a.disabled=!1,a.innerHTML=\`
<span class="material-symbols-outlined" style="font-size: 18px;">save</span>
\${this.editingServerId?"UPDATE_SERVER":"SAVE_SERVER"}
\`}}async logout(){try{await fetch("/api/auth/logout",{method:"POST"})}catch{}this.onLogout()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}const Rt=new ll("terminal-container");let Zr=null,Ms=!1;function _l(){return new URLSearchParams(window.location.search).has("wsUrl")}function gl(){var n;const i=new URLSearchParams(window.location.search),e=i.get("wsUrl"),t=i.get("name")||"Server";document.getElementById("auth-section").classList.add("hidden"),document.getElementById("user-space-section").classList.add("hidden"),document.getElementById("user-space-section").classList.remove("flex"),document.getElementById("terminal-section").classList.remove("hidden"),document.getElementById("terminal-section").classList.add("flex"),document.getElementById("term-host").textContent=\`Server: \${t}\`,document.getElementById("term-user").textContent="",document.getElementById("term-port").textContent="",Rt.mount();const r=new WebSocket(e);r.binaryType="arraybuffer",Rt.connectWithWebSocket(r),(n=document.getElementById("disconnect-btn"))==null||n.addEventListener("click",()=>{Rt.disconnect(),window.close()})}function no(){document.getElementById("auth-section").classList.remove("hidden"),document.getElementById("user-space-section").classList.add("hidden"),document.getElementById("user-space-section").classList.remove("flex"),document.getElementById("terminal-section").classList.add("hidden"),document.getElementById("terminal-section").classList.remove("flex"),document.getElementById("server-modal").classList.add("hidden"),document.getElementById("server-modal").classList.remove("flex"),Zr||(Zr=new ul(Rt))}function pl(i){Ms=!0,document.getElementById("auth-section").classList.add("hidden"),document.getElementById("user-space-section").classList.remove("hidden"),document.getElementById("user-space-section").classList.add("flex"),document.getElementById("terminal-section").classList.add("hidden"),document.getElementById("terminal-section").classList.remove("flex"),new fl(i,()=>{Ms=!1,no()})}var Qr;(Qr=document.getElementById("disconnect-btn"))==null||Qr.addEventListener("click",()=>{Rt.disconnect();const i=document.getElementById("terminal-section");i.classList.add("hidden"),i.classList.remove("flex"),Ms?(document.getElementById("user-space-section").classList.remove("hidden"),document.getElementById("user-space-section").classList.add("flex")):document.getElementById("auth-section").classList.remove("hidden"),document.getElementById("status-text").innerHTML='<span class="w-2 h-2 bg-[#353534] inline-block"></span> STATUS: OFFLINE'});var en;(en=document.getElementById("theme-selector"))==null||en.addEventListener("change",i=>{const e=i.target.value;Rt.setTheme(e)});async function vl(){const i=document.getElementById("copyright-year");if(i&&(i.textContent=new Date().getFullYear().toString()),_l()){gl();return}try{const e=await fetch("/api/auth/me");if(e.ok){const t=await e.json();pl(t);return}}catch{}no()}vl();
\`}}async logout(){try{await fetch("/api/auth/logout",{method:"POST"})}catch{}this.onLogout()}escapeHtml(e){const t=document.createElement("div");return t.textContent=e,t.innerHTML}}const Rt=new dl("terminal-container");let Xr=null,Ms=!1;Rt.setSessionClosedHandler(()=>{ao()});function oo(){return new URLSearchParams(window.location.search).has("wsUrl")}function pl(){const i=new URLSearchParams(window.location.search),e=i.get("wsUrl"),t=i.get("name")||"Server";document.getElementById("auth-section").classList.add("hidden"),document.getElementById("user-space-section").classList.add("hidden"),document.getElementById("user-space-section").classList.remove("flex"),document.getElementById("terminal-section").classList.remove("hidden"),document.getElementById("terminal-section").classList.add("flex"),document.getElementById("term-host").textContent=\`Server: \${t}\`,document.getElementById("term-user").textContent="",document.getElementById("term-port").textContent="",Rt.mount();const r=new WebSocket(e);r.binaryType="arraybuffer",Rt.connectWithWebSocket(r)}function $s(){document.getElementById("auth-section").classList.remove("hidden"),document.getElementById("user-space-section").classList.add("hidden"),document.getElementById("user-space-section").classList.remove("flex"),document.getElementById("terminal-section").classList.add("hidden"),document.getElementById("terminal-section").classList.remove("flex"),document.getElementById("server-modal").classList.add("hidden"),document.getElementById("server-modal").classList.remove("flex"),Xr||(Xr=new _l(Rt))}function vl(i){Ms=!0,document.getElementById("auth-section").classList.add("hidden"),document.getElementById("user-space-section").classList.remove("hidden"),document.getElementById("user-space-section").classList.add("flex"),document.getElementById("terminal-section").classList.add("hidden"),document.getElementById("terminal-section").classList.remove("flex"),new gl(i,()=>{Ms=!1,$s()})}function ao(){var e,t;if(oo()){window.close();return}const i=document.getElementById("terminal-section");i&&(i.classList.add("hidden"),i.classList.remove("flex")),Ms?((e=document.getElementById("user-space-section"))==null||e.classList.remove("hidden"),(t=document.getElementById("user-space-section"))==null||t.classList.add("flex")):$s(),document.getElementById("status-text").innerHTML='<span class="w-2 h-2 bg-[#353534] inline-block"></span> STATUS: OFFLINE'}var en;(en=document.getElementById("disconnect-btn"))==null||en.addEventListener("click",()=>{Rt.disconnect(),ao()});var tn;(tn=document.getElementById("theme-selector"))==null||tn.addEventListener("change",i=>{const e=i.target.value;Rt.setTheme(e)});async function ml(){const i=document.getElementById("copyright-year");if(i&&(i.textContent=new Date().getFullYear().toString()),oo()){pl();return}try{const e=await fetch("/api/auth/me");if(e.ok){const t=await e.json();vl(t);return}}catch{}$s()}ml();
</script>
<style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:JetBrains Mono,monospace;background-color:#0a0a0a;color:#4af626;min-height:100vh;overflow:hidden}.scanlines{position:fixed;top:0;left:0;width:100vw;height:100vh;background:linear-gradient(to bottom,#fff0,#fff0 50%,#0000001a 50%,#0000001a);background-size:100% 4px;pointer-events:none;z-index:50}.flicker{animation:flicker .15s infinite;pointer-events:none;position:fixed;top:0;left:0;width:100%;height:100%;background:#4af62605;z-index:49}@keyframes flicker{0%{opacity:.8}50%{opacity:1}to{opacity:.9}}.terminal-input{background:transparent;border:none;border-bottom:1px solid #3c4b36;color:#4af626;font-family:JetBrains Mono,monospace;padding:8px 0;width:100%;outline:none;transition:border-color .2s}.terminal-input:focus{border-bottom:1px solid #4af626;box-shadow:none}.terminal-input::placeholder{color:#3c4b36}.blinking-cursor:after{content:"█";color:#14d1ff;animation:blink 1s step-end infinite;margin-left:4px;font-size:.9em}@keyframes blink{0%,to{opacity:1}50%{opacity:0}}.cyber-box{background-color:#121212;border:1px solid #1f1f1f}.cyber-button{border:1px solid #4af626;color:#4af626;transition:all .2s ease;position:relative;overflow:hidden;cursor:pointer}.cyber-button:hover{background-color:#4af626;color:#0a0a0a}.cursor-blink{animation:blink 1s step-end infinite}.scanline{background:linear-gradient(to bottom,#fff0,#fff0 50%,#0000001a 50%,#0000001a);background-size:100% 4px}.custom-scrollbar::-webkit-scrollbar{width:8px}.custom-scrollbar::-webkit-scrollbar-track{background:#1c1b1b80}.custom-scrollbar::-webkit-scrollbar-thumb{background:#3c4b36cc;border-radius:4px}.custom-scrollbar::-webkit-scrollbar-thumb:hover{background:#86957dcc}.server-card{background-color:#121212;border:1px solid #1f1f1f;transition:all .3s ease;position:relative}.server-card:hover{border-color:#4af626;transform:translateY(-2px);box-shadow:0 4px 20px #4af62614}.server-card.removing{animation:fadeOut .3s ease forwards}@keyframes fadeOut{to{opacity:0;transform:translateY(-10px)}}.modal-overlay{background:#000c;-webkit-backdrop-filter:blur(4px);backdrop-filter:blur(4px)}.user-avatar{border:2px solid #4af626;border-radius:50%;transition:border-color .2s}.user-avatar:hover{border-color:#14d1ff}.github-login-btn{transition:all .2s ease}.github-login-btn:hover{border-color:#4af626;color:#4af626}.animate-spin{animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0)}to{transform:rotate(360deg)}}/**
* Copyright (c) 2014 The xterm.js authors. All rights reserved.
+54 -32
View File
@@ -1,4 +1,4 @@
import { SSHConnectionConfig, SessionKeys, SSHPacket } from '../types';
import { SSHConnectionConfig, SessionKeys, SSHPacket, TerminalSize } from '../types';
import {
SSH_MSG_KEXINIT,
SSH_MSG_NEWKEYS,
@@ -83,21 +83,26 @@ export class SSHSession {
private keepaliveInterval: ReturnType<typeof setInterval> | null = null;
private shellReadyTimeout: ReturnType<typeof setTimeout> | null = null;
private terminalSize: TerminalSize = { cols: 120, rows: 40 };
private debugMode: boolean = false;
constructor(
ws: WebSocket,
socket: any,
config: SSHConnectionConfig,
strictHostKeyVerify: boolean = true
strictHostKeyVerify: boolean = true,
debugMode: boolean = false
) {
this.ws = ws;
this.socket = socket;
this.config = config;
this.strictHostKeyVerify = strictHostKeyVerify;
this.debugMode = debugMode;
this.transport = new SSHTransport();
this.packetParser = new SSHPacketParser();
this.channel = new SSHChannel();
this.updateTerminalSize(config.cols, config.rows);
}
async startHandshake(): Promise<void> {
@@ -126,7 +131,6 @@ export class SSHSession {
} else {
const result = await reader.read();
if (result.done) {
console.log('[SSH] Socket closed (EOF)');
this.sendError('SSH 服务器断开连接 (Socket closed by remote)');
this.close();
break;
@@ -170,19 +174,16 @@ export class SSHSession {
versionFound = true;
break;
} else {
console.log('[SSH] Pre-version banner: ' + lineStr);
}
}
if (versionFound) {
this.versionRawBuffer = new Uint8Array(0);
console.log('[SSH] Version exchange complete, remote=' + this.transport.getRemoteVersion());
this.sendStatus('版本交换完成,正在密钥协商...');
this.state = 'kex';
await this.startKEX();
if (remaining.length > 0) {
console.log('[SSH] Remaining data after version: ' + remaining.length + ' bytes');
this.packetParser.feed(remaining);
await this.processPackets();
}
@@ -192,14 +193,12 @@ export class SSHSession {
}
}
} else {
console.log('[SSH] Received ' + value.length + ' bytes, state=' + this.state);
this.packetParser.feed(value);
await this.processPackets();
}
}
} catch (error) {
const errMsg = error instanceof Error ? error.message : String(error);
console.error('[SSH] Read loop error:', errMsg, error instanceof Error ? error.stack : '');
try {
this.ws.send(JSON.stringify({ type: 'error', message: 'SSH 连接异常: ' + errMsg }));
} catch {}
@@ -207,14 +206,12 @@ export class SSHSession {
}
private async startKEX(): Promise<void> {
console.log('[KEX] Starting key exchange');
this.kexInitLocal = KEXInitBuilder.build();
const packet = await SSHPacketBuilder.build(
this.kexInitLocal, 8, null, this.seqNumSend++
);
await this.writeSocket(packet);
console.log('[KEX] KEXINIT sent');
}
private async sendKEXECDHInit(): Promise<void> {
@@ -241,7 +238,6 @@ export class SSHSession {
kexInit, 8, null, this.seqNumSend++
);
await this.writeSocket(ecdhPacket);
console.log(`[KEX] ECDH_INIT sent using ${this.negotiatedKexAlgorithm}, waiting for server reply`);
}
private async writeSocket(data: Uint8Array): Promise<void> {
@@ -778,13 +774,8 @@ export class SSHSession {
new DataView(serviceRequest.buffer).setUint32(1, nameBytes.length, false);
serviceRequest.set(nameBytes, 5);
console.log('[AUTH] SERVICE_REQUEST payload len=' + serviceRequest.length + ', seqNum=' + this.seqNumSend);
console.log('[AUTH] encryptCipher exists=' + !!this.encryptCipher);
const packet = await this.buildEncryptedPacket(serviceRequest);
console.log('[AUTH] Encrypted packet len=' + packet.length + ', first16=' + Array.from(packet.slice(0, 16)).map(b => b.toString(16).padStart(2, '0')).join(''));
await this.writeSocket(packet);
console.log('[AUTH] SERVICE_REQUEST sent to socket');
}
private async authenticate(): Promise<void> {
@@ -828,7 +819,6 @@ export class SSHSession {
break;
case SSH_MSG_UNIMPLEMENTED:
console.warn('[AUTH] Server sent UNIMPLEMENTED');
break;
}
}
@@ -842,7 +832,7 @@ export class SSHSession {
switch (msgType) {
case SSH_MSG_CHANNEL_OPEN_CONFIRMATION:
this.channel.handleOpenConfirmation(payload);
const ptyReq = this.channel.buildPTYRequest(120, 40);
const ptyReq = this.channel.buildPTYRequest(this.terminalSize.cols, this.terminalSize.rows);
await this.sendEncrypted(ptyReq);
break;
@@ -922,38 +912,70 @@ export class SSHSession {
}
async handleWebSocketMessage(data: string | ArrayBuffer): Promise<void> {
if (this.state !== 'ready') return;
if (typeof data === 'string') {
if (data === '{"type":"ping"}') {
this.ws.send(JSON.stringify({ type: 'pong' }));
return;
}
if (data.startsWith('{"type":"resize"')) {
if (data.startsWith('{"type"')) {
try {
const msg = JSON.parse(data);
if (msg.type === 'ping') {
this.ws.send(JSON.stringify({ type: 'pong' }));
return;
}
if (msg.type === 'resize') {
await this.handleResize(msg.cols, msg.rows);
return;
}
} catch {}
}
if (this.state !== 'ready') return;
const encoded = new TextEncoder().encode(data);
const channelData = this.channel.buildChannelData(encoded);
await this.sendEncrypted(channelData);
} else {
if (this.state !== 'ready') return;
const channelData = this.channel.buildChannelData(new Uint8Array(data));
await this.sendEncrypted(channelData);
}
}
private async handleResize(cols: number, rows: number): Promise<void> {
const resizeMsg = this.channel.buildWindowChange(cols, rows);
private async handleResize(cols: unknown, rows: unknown): Promise<void> {
if (!this.updateTerminalSize(cols, rows)) return;
if (this.state !== 'ready') return;
const resizeMsg = this.channel.buildWindowChange(this.terminalSize.cols, this.terminalSize.rows);
await this.sendEncrypted(resizeMsg);
}
private updateTerminalSize(cols: unknown, rows: unknown): boolean {
if (
typeof cols !== 'number' ||
typeof rows !== 'number' ||
!Number.isFinite(cols) ||
!Number.isFinite(rows)
) {
return false;
}
const nextSize = {
cols: Math.floor(cols),
rows: Math.floor(rows),
};
if (
nextSize.cols < 10 ||
nextSize.cols > 1000 ||
nextSize.rows < 5 ||
nextSize.rows > 1000
) {
return false;
}
this.terminalSize = nextSize;
return true;
}
private async sendEncrypted(payload: Uint8Array): Promise<void> {
const operation = this.sendMutex.then(async () => {
const encrypted = await this.buildEncryptedPacket(payload);
@@ -977,10 +999,10 @@ export class SSHSession {
}
private sendDebug(message: string): void {
// console.log('[DEBUG] ' + message);
// try {
// this.ws.send(JSON.stringify({ type: 'status', message: '[DEBUG] ' + message }));
// } catch {}
if (!this.debugMode) return;
try {
this.ws.send(JSON.stringify({ type: 'debug', message }));
} catch {}
}
close(normal: boolean = false): void {
-2
View File
@@ -130,7 +130,6 @@ export class UserDBDO {
return Response.json({ error: 'Not Found' }, { status: 404 });
} catch (e) {
const msg = e instanceof Error ? e.message : String(e);
console.error('[UserDBDO] Error:', msg);
return Response.json({ error: msg }, { status: 500 });
}
}
@@ -471,7 +470,6 @@ export class UserDBDO {
crypto.getRandomValues(bytes);
secret = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
this.db.exec("INSERT INTO system_config (key, value) VALUES ('session_secret', ?)", secret);
console.log('[UserDBDO] Auto-generated and stored a new SESSION_SECRET');
}
}
+25 -17
View File
@@ -2,29 +2,20 @@ name = "cloudssh"
main = "src/worker/index.ts"
compatibility_date = "2024-12-01"
compatibility_flags = ["nodejs_compat"]
# no_bundle = true
workers_dev = true
[vars]
DEBUG_MODE = "false"
# 构建监视路径:仅源代码变动时触发重新构建
[build]
watch_dir = "."
# 下述注释的配置推荐采用环境变量的形式在worker页面直接手动添加
# GitHub OAuth(可选,不配置则登录功能自动隐藏)
# 创建 GitHub OAuth App 后,取消下方注释并填入你的 Client ID
# [vars]
# GITHUB_CLIENT_ID = "your-github-oauth-client-id"
# BASE_URL = "https://your-domain.com"
# Turnstile 验证(可选)
# 在 Cloudflare Dashboard 中创建 Turnstile Widget 后,将密钥配置为环境变量
# [vars]
# TURNSTILE_SECRET = "your-turnstile-secret-key"
# TURNSTILE_SITEKEY = "your-turnstile-site-key"
#[[routes]]
#pattern = "自定义域名"
#custom_domain = true
# 下述注释的配置推荐采用环境变量的形式在 Cloudflare Dashboard 中直接添加:
# - GITHUB_CLIENT_ID / GITHUB_CLIENT_SECRET(GitHub OAuth)
# - SESSION_SECRET(凭据加密密钥)
# - TURNSTILE_SECRET / TURNSTILE_SITEKEY(Bot 验证)
# - BASE_URL(OAuth 回调地址,需与实际域名一致)
[[durable_objects.bindings]]
name = "SSH_SESSION"
@@ -38,3 +29,20 @@ class_name = "UserDBDO"
[[migrations]]
tag = "v1"
new_sqlite_classes = ["SSHSessionDO", "UserDBDO"]
# ========== Test 环境 ==========
# test 分支部署到独立 worker,共享 DO
# 自定义域名请在 Cloudflare Dashboard 中手动绑定
[env.test]
name = "cloudssh-test"
[env.test.vars]
DEBUG_MODE = "true"
[[env.test.durable_objects.bindings]]
name = "SSH_SESSION"
class_name = "SSHSessionDO"
[[env.test.durable_objects.bindings]]
name = "USER_DB"
class_name = "UserDBDO"