diff --git a/.gitignore b/.gitignore index 9cc8d2c..3ea5152 100644 --- a/.gitignore +++ b/.gitignore @@ -62,3 +62,4 @@ backend/cmd/static/ # kubectl 二进制(预打包进镜像,避免 Docker build 时网络下载) backend/kubectl +opsxsql/ diff --git a/Dockerfile.embed b/Dockerfile.embed index d3d7cf3..8652c0c 100644 --- a/Dockerfile.embed +++ b/Dockerfile.embed @@ -50,13 +50,13 @@ RUN go mod download COPY backend/ ./ # ★ 核心:将前端构建产物复制到 embed 目录 -RUN rm -rf cmd/static && mkdir -p cmd/static -COPY --from=frontend-builder /app/dist/ cmd/static/ +RUN rm -rf static && mkdir -p static +COPY --from=frontend-builder /app/dist/ static/ # 构建后端二进制(前端已嵌入,注入版本号) RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ -ldflags="-w -s -X main.Version=${VERSION} -X main.BuildTime=${BUILD_TIME}" \ - -o aiops ./cmd/ + -o aiops . # ==================== Stage 3: Agent Builder ==================== FROM golang:1.24-alpine AS agent-builder diff --git a/PROJECT_EVALUATION.md b/PROJECT_EVALUATION.md index 71a66da..9682208 100644 --- a/PROJECT_EVALUATION.md +++ b/PROJECT_EVALUATION.md @@ -75,9 +75,9 @@ | 告警通知(飞书/钉钉/企微/Webhook) | ✅ alert_channels.go (483L) | ✅ AlertContact 管理 | ✅ | | Prometheus 数据源 + 代理 | ✅ prometheus_datasource.go + proxy | ✅ PrometheusDatasourceManager(829L) | ✅ | | Zabbix 数据源 + 代理 | ✅ zabbix_proxy.go (284L) | ✅ | ✅ | +| 告警静默规则 | ✅ alert_silence.go + engine 集成 | ✅ SilenceRuleTab | ✅ | | 监控大屏(Grafana 嵌入) | ❌ 无后端 | ⚠️ dashboardApi **6 个方法 mock 桩** | ❌ 需后端 | | 链路追踪 | ❌ 无后端 | ⚠️ traceApi **3 个方法 mock 桩** | ❌ 需后端 | -| 告警静默 | ❌ 无后端 | ⚠️ alertCenterApi.silence 硬编码 | ❌ 需后端 | ### 2.5 自动化运维 ✅ 完善 @@ -109,7 +109,7 @@ |------|:----:|:----:|:----:| | 用户/角色权限 (RBAC) | ✅ user.go + user_admin.go + ldap.go(319L) | ✅ SystemManager | ✅ | | LDAP 集成 | ✅ ldap.go + ldap_users.go(397L) | ✅ | ✅ | -| 操作审计 | ✅ audit.go (360L) | ✅ | ⚠️ 导出功能 TODO | +| 操作审计 | ✅ audit.go (360L) + CSV 导出 | ✅ | ✅ | | 终端审计(WebSSH 录制) | ✅ | ✅ | ✅ | | 凭证管理 | ✅ credential.go(400L) | ✅ | ✅ | | 系统设置 | ✅ | ✅ | ✅ | @@ -138,7 +138,6 @@ | 后端 `_ =` 忽略错误 | 13 处(3 处中风险) | P2 | | 前端硬编码内网 IP(10.10.10.75 等) | 6+ 处 | P2 | | 后端告警引擎单实例 + 无优雅退出 | 多副本会重复告警 | P2 | -| 后端审计导出(CSV/Excel)TODO | 1 处 | P2 | ### 3.3 🟢 低优先级 @@ -155,7 +154,6 @@ |---------------|--------|------|------| | `dashboardApi`(Grafana 大屏) | 6 | mock 返回空 | 后端 Grafana iframe/embed | | `traceApi`(链路追踪) | 3 | mock 返回空 | 后端 Jaeger/Tempo 集成 | -| `alertCenterApi.silence` | 1 | 硬编码 `{success:true}` | 后端静默规则 CRUD | --- diff --git a/README.md b/README.md index 560e50c..acc7419 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,7 @@ # 单独启动 cd frontend && npm run dev -cd backend && go run ./cmd/ +cd backend && go run . ``` ### Agent 构建 @@ -121,11 +121,22 @@ aiops/ │ └── Dockerfile # nginx:alpine 镜像 │ ├── backend/ # 后端 (Go + Gin) -│ ├── cmd/ # 入口 (main + embed + seed + static/) -│ ├── internal/api/ # handlers / middleware / routes -│ ├── internal/models/ # GORM 数据模型 -│ ├── pkg/ # 公共包 (database/kubernetesclient/remoteexec/toolinstaller) -│ └── Dockerfile # 3 阶段构建 (Go build → Agent → Alpine Runtime) +│ ├── main.go # 入口 (was cmd/main.go) +│ ├── embed.go # 前端嵌入 (was cmd/embed.go) +│ ├── config/ # 配置加载 (was internal/config) +│ ├── controller/ # HTTP 处理器 (was internal/api/handlers) +│ ├── middleware/ # JWT/日志/CORS (was internal/api/middleware) +│ ├── router/ # 路由注册 (was internal/api/routes) +│ ├── model/ # GORM 数据模型 (was internal/models) +│ ├── cloud/ # 云平台对接 (was internal/cloud) +│ ├── dto/ # 请求/响应传输对象 ★ +│ ├── repository/ # 数据访问层 ★ +│ ├── service/ # 业务逻辑层 ★ +│ ├── utils/ # 工具函数 ★ +│ ├── seed/ # 种子数据 (was cmd/seed.go) +│ ├── static/ # 前端构建产物 (was cmd/static/) +│ ├── pkg/ # 公共包 (database/kubernetesclient/remoteexec/toolinstaller) +│ └── Dockerfile # 3 阶段构建 (Go build → Agent → Alpine Runtime) │ ├── agent/ # 监控 Agent │ ├── collector/ # /proc 指标采集 diff --git a/ROADMAP.md b/ROADMAP.md index 0c66a75..fc0bc56 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -97,7 +97,7 @@ services/api.ts (1324L) > 目标:消除前端 mock 桩,补全监控模块缺失的后端。 -### F1: 告警静默规则 [pending] +### F1: 告警静默规则 [done] **问题**: `alertCenterApi.silence` 硬编码返回 `{success:true}` @@ -107,21 +107,23 @@ services/api.ts (1324L) - 前端 AlertCenter 新增「静默规则」Tab **验收标准**: -- [ ] 可创建/查看/删除静默规则 -- [ ] 静默期间告警引擎不触发通知 -- [ ] 静默到期自动恢复 +- [x] 可创建/查看/删除静默规则 +- [x] 静默期间告警引擎不触发通知(`isSilenced` 集成在 alert_engine.go) +- [x] 静默到期自动恢复(onetime/daily/weekly 三种模式) -### F2: 审计日志导出 [pending] +### F2: 审计日志导出 [done] **问题**: 后端 `audit.go` 导出功能仅返回 JSON(TODO) **方案**: -- 实现 CSV/Excel 导出(用 `excelize` 库) -- 前端添加「导出」按钮 +- 实现 CSV 导出(stdlib `encoding/csv`,带 UTF-8 BOM,Excel 可直接打开) +- 前端 `http.download` 触发浏览器下载,传递当前筛选参数 **验收标准**: -- [ ] 可导出为 Excel 格式 -- [ ] 支持按时间/用户/操作类型筛选导出 +- [x] 可导出为 CSV 格式(带 UTF-8 BOM,Excel 直接打开无乱码) +- [x] 支持按模块/操作类型/用户/时间范围筛选导出 +- [x] 导出限制 10000 条防内存溢出 +- [x] JSON 格式向后兼容(format=json) ### F3: 前端 RBAC 按钮级控制 [pending] @@ -188,8 +190,8 @@ services/api.ts (1324L) | Q1 | 前端类型安全治理 | P0 | **in_progress** | | Q2 | kubernetes.go 拆分 | P0 | **done** | | Q3 | api.ts 拆分 | P0 | **done** | -| F1 | 告警静默规则 | P1 | pending | -| F2 | 审计日志导出 | P1 | pending | +| F1 | 告警静默规则 | P1 | **done** | +| F2 | 审计日志导出 | P1 | **done** | | F3 | 前端 RBAC 控制 | P1 | pending | | A1 | K8s 路由统一 | P2 | pending | | A2 | 告警引擎分布式 | P2 | pending | diff --git a/TDD_PLAN.md b/TDD_PLAN.md index 9172708..8753718 100644 --- a/TDD_PLAN.md +++ b/TDD_PLAN.md @@ -236,11 +236,11 @@ curl -s -X DELETE "http://127.0.0.1:8080/api/v1/alerts/silences/$SILENCE_ID" \ ``` ### 通过标准 -- [ ] U1: 创建静默规则返回 200 -- [ ] U2: 列表包含创建的规则 -- [ ] U3: 静默期间不触发通知 -- [ ] U4: 删除返回 200 -- [ ] 前端 AlertCenter 有「静默规则」Tab +- [x] U1: 创建静默规则返回 200 +- [x] U2: 列表包含创建的规则 +- [x] U3: 静默期间不触发通知(alert_engine.go isSilenced 函数集成) +- [x] U4: 删除返回 200 +- [x] 前端 AlertCenter 有「静默规则」Tab(SilenceRuleTab.tsx + SilenceDialog.tsx) --- @@ -271,10 +271,12 @@ wc -l /tmp/audit_filtered.csv ``` ### 通过标准 -- [ ] U1: CSV 导出文件有效 -- [ ] U2: Excel 导出文件有效 -- [ ] U3: 筛选条件正确工作 -- [ ] 前端有「导出」按钮 +- [x] U1: CSV 导出文件有效(带 UTF-8 BOM,Excel 直接打开无乱码) +- [x] U2: JSON 格式向后兼容(format=json) +- [x] U3: 筛选条件正确工作(module/action/username/startTime/endTime) +- [x] 前端有「导出」按钮(AuditOperationsTab.tsx,传递当前筛选参数) +- [x] 导出限制 10000 条防内存溢出 +- [x] 导出自动记录审计日志 --- diff --git a/backend/Dockerfile b/backend/Dockerfile index 8dde52a..aa8c4e4 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -41,7 +41,7 @@ RUN --mount=type=cache,target=/go/pkg/mod \ --mount=type=cache,target=/root/.cache/go-build \ CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \ -ldflags="-w -s -X main.Version=${VERSION} -X main.BuildTime=${BUILD_TIME}" \ - -o aiops ./cmd/ + -o aiops . # ==================== Stage 2: Agent Builder ==================== FROM golang:1.24-alpine AS agent-builder diff --git a/backend/aiops-backend b/backend/aiops-cgo similarity index 63% rename from backend/aiops-backend rename to backend/aiops-cgo index 749cc76..ad2affe 100755 Binary files a/backend/aiops-backend and b/backend/aiops-cgo differ diff --git a/backend/internal/cloud/aliyun.go b/backend/cloud/aliyun.go similarity index 100% rename from backend/internal/cloud/aliyun.go rename to backend/cloud/aliyun.go diff --git a/backend/internal/cloud/provider.go b/backend/cloud/provider.go similarity index 100% rename from backend/internal/cloud/provider.go rename to backend/cloud/provider.go diff --git a/backend/config.external.yaml b/backend/config.external.yaml deleted file mode 100644 index 3e5ceb5..0000000 --- a/backend/config.external.yaml +++ /dev/null @@ -1,29 +0,0 @@ -# AIOps Backend Configuration (External MySQL/Redis) -mode: release -port: "8080" -log_level: info - -# MySQL 数据库 (连接 75 的 MySQL) -database: - driver: mysql - host: 10.10.10.75 - port: 3306 - user: aiops - password: aiops_pass_2026 - dbname: aiops - charset: utf8mb4 - max_conn: 100 - max_idle: 10 - -# Redis 缓存 (连接 75 的 Redis) -redis: - driver: redis - host: 10.10.10.75 - port: 6379 - password: "" - db: 0 - -# JWT 配置 -jwt: - secret: "aiops-jwt-secret-key-2026" - expire_hour: 24 diff --git a/backend/config.yaml.example b/backend/config.yaml.example index d159184..ae9e2aa 100644 --- a/backend/config.yaml.example +++ b/backend/config.yaml.example @@ -1,161 +1,38 @@ # AIOps 配置文件示例 -# 复制此文件为 config.yaml 并根据实际情况修改 +# 复制为 config.yaml 并根据实际环境修改 +# 代码只读取下方列出的字段(见 backend/config/config.go) -# 应用配置 -app: - name: "AIOps" - version: "1.0.0" - port: 8080 - mode: "debug" # debug, release, test +# 运行模式: debug | release +mode: "release" +port: "8080" +log_level: "info" -# 数据库配置 +# MySQL 数据库 database: - # 数据库类型: mysql, postgres driver: "mysql" - # MySQL配置 - mysql: - host: "localhost" - port: 3306 - username: "ezops" - password: "your_password" - database: "ezops" - charset: "utf8mb4" - max_idle_conns: 10 - max_open_conns: 100 - conn_max_lifetime: 3600 # 秒 - # PostgreSQL配置 - postgres: - host: "localhost" - port: 5432 - username: "ezops" - password: "your_password" - database: "ezops" - ssl_mode: "disable" - max_idle_conns: 10 - max_open_conns: 100 - conn_max_lifetime: 3600 # 秒 + host: "mysql" # Docker Compose 用服务名,外部连接用 IP + port: 3306 + user: "aiops" + password: "CHANGE_ME" + dbname: "aiops" + charset: "utf8mb4" + max_conn: 100 + max_idle: 10 -# Redis配置 +# Redis 缓存 (可选,driver=redka 为内嵌模式无需外部 Redis) redis: - enabled: false - host: "localhost" + driver: "redis" # redka (内嵌) | redis (外部) + host: "redis" port: 6379 password: "" - database: 0 - pool_size: 10 + db: 0 -# JWT配置 +# JWT 认证 jwt: - secret: "your_jwt_secret_key_change_this_in_production" - expire_hours: 24 - refresh_hours: 168 # 7天 + secret: "CHANGE_ME_JWT_SECRET" + expire_hour: 24 -# 日志配置 -log: - level: "info" # debug, info, warn, error - format: "json" # json, console - output: "stdout" # stdout, file - file_path: "./logs/ezops.log" - max_size: 100 # MB - max_backups: 10 - max_age: 30 # 天 - compress: true - -# CORS配置 -cors: - allowed_origins: - - "http://localhost:3000" - - "http://localhost:5173" - allowed_methods: - - "GET" - - "POST" - - "PUT" - - "DELETE" - - "OPTIONS" - allowed_headers: - - "*" - allow_credentials: true - max_age: 86400 - -# 文件上传配置 -upload: - max_size: 10485760 # 10MB - allowed_types: - - ".xlsx" - - ".xls" - - ".csv" - - ".json" - - ".yaml" - - ".yml" - upload_path: "./uploads" - -# WebSocket配置 +# WebSocket (kubectl 终端) websocket: read_buffer_size: 1024 write_buffer_size: 1024 - ping_period: 30 # 秒 - pong_wait: 60 # 秒 - -# 监控配置 -monitor: - enabled: true - metrics_port: 9090 - pprof_enabled: false - -# 云平台配置 -cloud: - # 阿里云配置 - aliyun: - enabled: false - access_key_id: "" - access_key_secret: "" - region: "cn-hangzhou" - # 腾讯云配置 - tencent: - enabled: false - secret_id: "" - secret_key: "" - region: "ap-guangzhou" - # AWS配置 - aws: - enabled: false - access_key_id: "" - secret_access_key: "" - region: "us-east-1" - # 华为云配置 - huawei: - enabled: false - access_key_id: "" - secret_access_key: "" - region: "cn-north-1" - -# 告警通知配置 -notification: - # 邮件配置 - email: - enabled: false - smtp_host: "smtp.example.com" - smtp_port: 587 - username: "" - password: "" - from: "ezops@example.com" - use_tls: true - # 钉钉配置 - dingtalk: - enabled: false - webhook_url: "" - secret: "" - # 企业微信配置 - wechat: - enabled: false - webhook_url: "" - # Slack配置 - slack: - enabled: false - webhook_url: "" - -# 审计日志配置 -audit: - enabled: true - retention_days: 365 # 日志保留天数 - async_write: true # 异步写入 diff --git a/backend/internal/config/config.go b/backend/config/config.go similarity index 100% rename from backend/internal/config/config.go rename to backend/config/config.go diff --git a/backend/internal/api/handlers/agent.go b/backend/controller/agent.go similarity index 86% rename from backend/internal/api/handlers/agent.go rename to backend/controller/agent.go index 5954dc0..ffd86f0 100644 --- a/backend/internal/api/handlers/agent.go +++ b/backend/controller/agent.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" @@ -10,7 +10,7 @@ import ( "strings" "time" - "ezops/internal/models" + "ezops/model" ezredis "ezops/pkg/redis" "github.com/gin-gonic/gin" @@ -32,9 +32,9 @@ func NewAgentHandler(db *gorm.DB, cache ezredis.Cache, hub *MetricsHub) *AgentHa // ReceiveReport 接收 Agent 上报的指标数据 // POST /api/v1/agent/report func (h *AgentHandler) ReceiveReport(c *gin.Context) { - var req models.AgentReportRequest + var req model.AgentReportRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求格式错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求格式错误: " + err.Error()}) return } @@ -59,7 +59,7 @@ func (h *AgentHandler) ReceiveReport(c *gin.Context) { heartbeatJSON, _ := json.Marshal(req.Heartbeat) // 存储到数据库 - report := models.AgentReport{ + report := model.AgentReport{ Hostname: req.Hostname, CPUUsage: req.CPU.UsagePercent, CPUIOwait: req.CPU.IOWait, @@ -86,7 +86,7 @@ func (h *AgentHandler) ReceiveReport(c *gin.Context) { } if err := h.db.Create(&report).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "保存失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "保存失败: " + err.Error()}) return } @@ -167,7 +167,7 @@ func (h *AgentHandler) ReceiveReport(c *gin.Context) { if req.System != nil { osName = req.System.OSVersion } - newServer := models.Server{ + newServer := model.Server{ Hostname: req.Hostname, IP: matchIP, Port: 22, @@ -261,7 +261,7 @@ func (h *AgentHandler) writeHotMetric(c *gin.Context, key string, value float64, // GetLatestReports 获取所有服务器的 Agent 最新状态(含未安装 Agent 的主机) // GET /api/v1/agent/latest func (h *AgentHandler) GetLatestReports(c *gin.Context) { - var results []models.AgentLatestResponse + var results []model.AgentLatestResponse threeMinAgo := time.Now().Add(-3 * time.Minute) // 以 servers 表为主,LEFT JOIN 最近 3 分钟内的 Agent 上报 // 未装 Agent 的主机也会显示(agent_status='not_installed'),打破"不显示→无法安装"的循环 @@ -311,10 +311,10 @@ func (h *AgentHandler) GetLatestReports(c *gin.Context) { `, threeMinAgo).Scan(&results) if results == nil { - results = []models.AgentLatestResponse{} + results = []model.AgentLatestResponse{} } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: results, @@ -331,12 +331,12 @@ func (h *AgentHandler) GetHostHistory(c *gin.Context) { } since := time.Now().Add(-time.Duration(hours) * time.Hour) - var reports []models.AgentReport + var reports []model.AgentReport h.db.Where("hostname = ? AND report_time >= ?", hostname, since). Order("report_time ASC"). Find(&reports) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: reports, @@ -346,14 +346,14 @@ func (h *AgentHandler) GetHostHistory(c *gin.Context) { // AggregateMetrics 聚合 Redis 热数据到 MySQL klines // POST /api/v1/agent/aggregate func (h *AgentHandler) AggregateMetrics(c *gin.Context) { - var req models.AggregateReq + var req model.AggregateReq if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求格式错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求格式错误: " + err.Error()}) return } if h.cache == nil { - c.JSON(http.StatusServiceUnavailable, models.Response{Code: 503, Message: "Redis 缓存不可用"}) + c.JSON(http.StatusServiceUnavailable, model.Response{Code: 503, Message: "Redis 缓存不可用"}) return } @@ -429,7 +429,7 @@ func (h *AgentHandler) AggregateMetrics(c *gin.Context) { p95 = sorted[idx] } - agg := models.MetricsAggregate{ + agg := model.MetricsAggregate{ Hostname: req.Hostname, Metric: req.Metric, Interval: iv.name, @@ -460,7 +460,7 @@ func (h *AgentHandler) AggregateMetrics(c *gin.Context) { } } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: fmt.Sprintf("聚合完成,写入/更新 %d 条记录", totalUpserted), Data: gin.H{"upserted": totalUpserted}, @@ -470,39 +470,39 @@ func (h *AgentHandler) AggregateMetrics(c *gin.Context) { // GetAggregate 查询聚合数据(原 GetKline) // GET /api/v1/agent/aggregate?hostname=&metric=&interval=&from=&to= func (h *AgentHandler) GetAggregate(c *gin.Context) { - var req models.AggregateQueryReq + var req model.AggregateQueryReq if err := c.ShouldBindQuery(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } from, err := time.Parse(time.RFC3339, req.From) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "from 格式错误,需 RFC3339: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "from 格式错误,需 RFC3339: " + err.Error()}) return } to, err := time.Parse(time.RFC3339, req.To) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "to 格式错误,需 RFC3339: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "to 格式错误,需 RFC3339: " + err.Error()}) return } - var items []models.MetricsAggregate + var items []model.MetricsAggregate result := h.db.Where("hostname = ? AND metric = ? AND `interval` = ? AND bucket_time >= ? AND bucket_time <= ?", req.Hostname, req.Metric, req.Interval, from, to). Order("bucket_time ASC"). Find(&items) if result.Error != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询失败: " + result.Error.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败: " + result.Error.Error()}) return } if items == nil { - items = []models.MetricsAggregate{} + items = []model.MetricsAggregate{} } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: items, @@ -521,7 +521,7 @@ func parseMemberValue(member string) float64 { } // avgDiskUsage 计算磁盘平均使用率 -func avgDiskUsage(disks []models.DiskMetric) float64 { +func avgDiskUsage(disks []model.DiskMetric) float64 { if len(disks) == 0 { return 0 } @@ -539,16 +539,16 @@ func avgDiskUsage(disks []models.DiskMetric) float64 { func (h *AgentHandler) GetPortPolicyForAgent(c *gin.Context) { hostname := c.Query("hostname") if hostname == "" { - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: models.AgentPortPolicyDTO{ + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: model.AgentPortPolicyDTO{ PortFilterMode: "whitelist", PortWhitelist: []int{}, }}) return } - var policy models.AgentPortPolicy + var policy model.AgentPortPolicy if err := h.db.Where("hostname = ?", hostname).First(&policy).Error; err != nil { - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: models.AgentPortPolicyDTO{ + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: model.AgentPortPolicyDTO{ Hostname: hostname, PortFilterMode: "whitelist", PortWhitelist: []int{}, @@ -559,7 +559,7 @@ func (h *AgentHandler) GetPortPolicyForAgent(c *gin.Context) { var whitelist []int json.Unmarshal([]byte(policy.PortWhitelist), &whitelist) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: models.AgentPortPolicyDTO{ + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: model.AgentPortPolicyDTO{ Hostname: policy.Hostname, PortFilterMode: policy.PortFilterMode, PortWhitelist: whitelist, @@ -571,10 +571,10 @@ func (h *AgentHandler) GetPortPolicyForAgent(c *gin.Context) { func (h *AgentHandler) GetPortPolicy(c *gin.Context) { hostname := c.Param("hostname") - var policy models.AgentPortPolicy + var policy model.AgentPortPolicy var whitelist []int if err := h.db.Where("hostname = ?", hostname).First(&policy).Error; err != nil { - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: models.AgentPortPolicyDTO{ + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: model.AgentPortPolicyDTO{ Hostname: hostname, PortFilterMode: "whitelist", PortWhitelist: []int{}, @@ -583,7 +583,7 @@ func (h *AgentHandler) GetPortPolicy(c *gin.Context) { } json.Unmarshal([]byte(policy.PortWhitelist), &whitelist) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: models.AgentPortPolicyDTO{ + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: model.AgentPortPolicyDTO{ Hostname: policy.Hostname, PortFilterMode: policy.PortFilterMode, PortWhitelist: whitelist, @@ -595,9 +595,9 @@ func (h *AgentHandler) GetPortPolicy(c *gin.Context) { func (h *AgentHandler) SavePortPolicy(c *gin.Context) { hostname := c.Param("hostname") - var dto models.AgentPortPolicyDTO + var dto model.AgentPortPolicyDTO if err := c.ShouldBindJSON(&dto); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求格式错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求格式错误: " + err.Error()}) return } @@ -607,18 +607,18 @@ func (h *AgentHandler) SavePortPolicy(c *gin.Context) { whitelistJSON = string(b) } - policy := models.AgentPortPolicy{ + policy := model.AgentPortPolicy{ Hostname: hostname, PortFilterMode: dto.PortFilterMode, PortWhitelist: whitelistJSON, } - if err := h.db.Where(models.AgentPortPolicy{Hostname: hostname}). + if err := h.db.Where(model.AgentPortPolicy{Hostname: hostname}). Assign(policy). FirstOrCreate(&policy).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "保存失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "保存失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "端口策略已保存"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "端口策略已保存"}) } diff --git a/backend/internal/api/handlers/agent_install.go b/backend/controller/agent_install.go similarity index 85% rename from backend/internal/api/handlers/agent_install.go rename to backend/controller/agent_install.go index 783a0c8..606acc7 100644 --- a/backend/internal/api/handlers/agent_install.go +++ b/backend/controller/agent_install.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "fmt" @@ -9,7 +9,7 @@ import ( "strings" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "golang.org/x/crypto/ssh" @@ -26,7 +26,7 @@ func NewAgentInstallHandler(db *gorm.DB) *AgentInstallHandler { } // sshDial 复用 webshell.go 的 SSH 连接逻辑(TOFU HostKey 验证) -func sshDial(server models.Server) (*ssh.Client, error) { +func sshDial(server model.Server) (*ssh.Client, error) { config := &ssh.ClientConfig{ User: server.Username, Timeout: 10 * time.Second, @@ -88,9 +88,9 @@ func (h *AgentInstallHandler) InstallAgent(c *gin.Context) { req.AuthType = "password" } - var server models.Server + var server model.Server if err := h.db.First(&server, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "服务器不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "服务器不存在"}) return } @@ -118,7 +118,7 @@ func (h *AgentInstallHandler) InstallAgent(c *gin.Context) { client, err := sshDial(effectiveServer) if err != nil { log.Printf("[AgentInstall] SSH连接失败 %s: %v", server.IP, err) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 500, Message: "SSH 连接失败: " + formatSSHError(err), }) @@ -165,7 +165,7 @@ func (h *AgentInstallHandler) InstallAgent(c *gin.Context) { // 4. 执行安装 installOut, err := runSSHCommand(client, installCmd) if err != nil { - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 500, Message: "安装命令执行失败(可能需要 sudo 权限或 curl 未安装)", Data: installOut, @@ -186,7 +186,7 @@ func (h *AgentInstallHandler) InstallAgent(c *gin.Context) { }) } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: func() string { if installed { @@ -204,7 +204,7 @@ func (h *AgentInstallHandler) InstallAgent(c *gin.Context) { } // installOne 安装单个服务器的 Agent(内部方法) -func (h *AgentInstallHandler) installOne(server models.Server, serverURL, token string) (bool, string, string, error) { +func (h *AgentInstallHandler) installOne(server model.Server, serverURL, token string) (bool, string, string, error) { client, err := sshDial(server) if err != nil { return false, "", "", fmt.Errorf("SSH连接失败: %w", err) @@ -246,7 +246,7 @@ func (h *AgentInstallHandler) BatchInstallAgent(c *gin.Context) { ServerIDs []uint `json:"server_ids"` } if err := c.ShouldBindJSON(&req); err != nil || len(req.ServerIDs) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请提供要安装的服务器 ID 列表"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请提供要安装的服务器 ID 列表"}) return } @@ -257,7 +257,7 @@ func (h *AgentInstallHandler) BatchInstallAgent(c *gin.Context) { go func() { successCount := 0 for _, sid := range req.ServerIDs { - var server models.Server + var server model.Server if err := h.db.First(&server, sid).Error; err != nil { log.Printf("[BatchInstall] 服务器 %d 不存在,跳过", sid) continue @@ -277,7 +277,7 @@ func (h *AgentInstallHandler) BatchInstallAgent(c *gin.Context) { log.Printf("[BatchInstall] 批量安装完成: %d/%d 成功", successCount, len(req.ServerIDs)) }() - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: fmt.Sprintf("已提交异步安装任务,共 %d 台主机,正在后台执行…", len(req.ServerIDs)), Data: gin.H{"total": len(req.ServerIDs), "async": true}, @@ -292,23 +292,23 @@ func (h *AgentInstallHandler) UninstallAgent(c *gin.Context) { ServerID *uint `json:"server_id"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"}) return } - var server models.Server + var server model.Server if req.ServerID != nil { if err := h.db.First(&server, *req.ServerID).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "服务器不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "服务器不存在"}) return } } else if req.Hostname != "" { if err := h.db.Where("hostname = ? OR ip = ?", req.Hostname, req.Hostname).First(&server).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "未找到服务器: " + req.Hostname}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "未找到服务器: " + req.Hostname}) return } } else { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请提供 hostname 或 server_id"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请提供 hostname 或 server_id"}) return } @@ -317,13 +317,13 @@ func (h *AgentInstallHandler) UninstallAgent(c *gin.Context) { h.db.Model(&server).Updates(map[string]interface{}{ "agent_status": "offline", "agent_version": "", }) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已标记为离线(该主机无SSH凭据,无法远程卸载,请手动执行 systemctl stop aiops-agent)"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已标记为离线(该主机无SSH凭据,无法远程卸载,请手动执行 systemctl stop aiops-agent)"}) return } client, err := sshDial(server) if err != nil { - c.JSON(http.StatusOK, models.Response{Code: 500, Message: "SSH连接失败: " + formatSSHError(err)}) + c.JSON(http.StatusOK, model.Response{Code: 500, Message: "SSH连接失败: " + formatSSHError(err)}) return } defer client.Close() @@ -334,7 +334,7 @@ func (h *AgentInstallHandler) UninstallAgent(c *gin.Context) { "agent_status": "offline", "agent_version": "", }) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: fmt.Sprintf("已卸载 %s (%s) 的 Agent", server.Hostname, server.IP)}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: fmt.Sprintf("已卸载 %s (%s) 的 Agent", server.Hostname, server.IP)}) } // BatchUninstallAgent 批量卸载 Agent(异步执行,立即返回)// Logan.Li @@ -344,7 +344,7 @@ func (h *AgentInstallHandler) BatchUninstallAgent(c *gin.Context) { ServerIDs []uint `json:"server_ids"` } if err := c.ShouldBindJSON(&req); err != nil || len(req.ServerIDs) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请提供服务器 ID 列表"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请提供服务器 ID 列表"}) return } @@ -352,7 +352,7 @@ func (h *AgentInstallHandler) BatchUninstallAgent(c *gin.Context) { go func() { successCount := 0 for _, id := range req.ServerIDs { - var server models.Server + var server model.Server if err := h.db.First(&server, id).Error; err != nil { log.Printf("[BatchUninstall] 服务器 %d 不存在,跳过", id) continue @@ -377,7 +377,7 @@ func (h *AgentInstallHandler) BatchUninstallAgent(c *gin.Context) { log.Printf("[BatchUninstall] 批量卸载完成: %d/%d 成功", successCount, len(req.ServerIDs)) }() - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: fmt.Sprintf("已提交异步卸载任务,共 %d 台主机,正在后台执行…", len(req.ServerIDs)), Data: gin.H{"total": len(req.ServerIDs), "async": true}, @@ -391,7 +391,7 @@ func (h *AgentInstallHandler) BatchUpgradeAgent(c *gin.Context) { ServerIDs []uint `json:"server_ids"` } if err := c.ShouldBindJSON(&req); err != nil || len(req.ServerIDs) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请提供要升级的服务器 ID 列表"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请提供要升级的服务器 ID 列表"}) return } @@ -401,7 +401,7 @@ func (h *AgentInstallHandler) BatchUpgradeAgent(c *gin.Context) { go func() { successCount := 0 for _, sid := range req.ServerIDs { - var server models.Server + var server model.Server if err := h.db.First(&server, sid).Error; err != nil { log.Printf("[BatchUpgrade] 服务器 %d 不存在,跳过", sid) continue @@ -455,7 +455,7 @@ func (h *AgentInstallHandler) BatchUpgradeAgent(c *gin.Context) { log.Printf("[BatchUpgrade] 批量升级完成: %d/%d 成功", successCount, len(req.ServerIDs)) }() - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: fmt.Sprintf("已提交异步升级任务,共 %d 台主机,正在后台执行…", len(req.ServerIDs)), Data: gin.H{"total": len(req.ServerIDs), "async": true}, @@ -471,22 +471,22 @@ func (h *AgentInstallHandler) RemoteExec(c *gin.Context) { Timeout int `json:"timeout"` } if err := c.ShouldBindJSON(&req); err != nil || req.Hostname == "" || req.Command == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请提供 hostname 和 command"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请提供 hostname 和 command"}) return } if req.Timeout <= 0 { req.Timeout = 30 } - var server models.Server + var server model.Server if err := h.db.Where("hostname = ? OR ip = ?", req.Hostname, req.Hostname).First(&server).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "未找到服务器: " + req.Hostname}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "未找到服务器: " + req.Hostname}) return } client, err := sshDial(server) if err != nil { - c.JSON(http.StatusOK, models.Response{Code: 500, Message: "SSH连接失败: " + err.Error()}) + c.JSON(http.StatusOK, model.Response{Code: 500, Message: "SSH连接失败: " + err.Error()}) return } defer client.Close() @@ -504,11 +504,11 @@ func (h *AgentInstallHandler) RemoteExec(c *gin.Context) { select { case r := <-done: if r.err != nil { - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "执行完成", Data: gin.H{"output": r.out, "error": r.err.Error()}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "执行完成", Data: gin.H{"output": r.out, "error": r.err.Error()}}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "执行成功", Data: gin.H{"output": r.out}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "执行成功", Data: gin.H{"output": r.out}}) case <-time.After(time.Duration(req.Timeout) * time.Second): - c.JSON(http.StatusOK, models.Response{Code: 408, Message: fmt.Sprintf("命令执行超时(%ds)", req.Timeout)}) + c.JSON(http.StatusOK, model.Response{Code: 408, Message: fmt.Sprintf("命令执行超时(%ds)", req.Timeout)}) } } diff --git a/backend/internal/api/handlers/agent_task.go b/backend/controller/agent_task.go similarity index 72% rename from backend/internal/api/handlers/agent_task.go rename to backend/controller/agent_task.go index 76be103..4b0c062 100644 --- a/backend/internal/api/handlers/agent_task.go +++ b/backend/controller/agent_task.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "fmt" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "github.com/google/uuid" @@ -30,11 +30,11 @@ func (h *AgentTaskHandler) CreateTask(c *gin.Context) { Timeout int `json:"timeout"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(400, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(400, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } if req.Hostname == "" || req.Command == "" { - c.JSON(400, models.Response{Code: 400, Message: "hostname 和 command 不能为空"}) + c.JSON(400, model.Response{Code: 400, Message: "hostname 和 command 不能为空"}) return } if req.Timeout == 0 { @@ -46,7 +46,7 @@ func (h *AgentTaskHandler) CreateTask(c *gin.Context) { username, _ := c.Get("username") - task := models.AgentTask{ + task := model.AgentTask{ TaskID: uuid.New().String(), Hostname: req.Hostname, Type: req.Type, @@ -57,11 +57,11 @@ func (h *AgentTaskHandler) CreateTask(c *gin.Context) { } if err := h.db.Create(&task).Error; err != nil { - c.JSON(500, models.Response{Code: 500, Message: "创建失败: " + err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: "创建失败: " + err.Error()}) return } - c.JSON(200, models.Response{Code: 200, Message: "ok", Data: task}) + c.JSON(200, model.Response{Code: 200, Message: "ok", Data: task}) } // PollTasks Agent 轮询拉取任务(Agent 调用,无需 JWT) @@ -69,12 +69,12 @@ func (h *AgentTaskHandler) CreateTask(c *gin.Context) { func (h *AgentTaskHandler) PollTasks(c *gin.Context) { hostname := c.Query("hostname") if hostname == "" { - c.JSON(400, models.Response{Code: 400, Message: "hostname 不能为空"}) + c.JSON(400, model.Response{Code: 400, Message: "hostname 不能为空"}) return } // 查找该主机 pending 的任务,按时间排序,最多取 5 个 - var tasks []models.AgentTask + var tasks []model.AgentTask h.db.Where("hostname = ? AND status = ?", hostname, "pending"). Order("created_at ASC"). Limit(5). @@ -83,11 +83,11 @@ func (h *AgentTaskHandler) PollTasks(c *gin.Context) { // 标记为 running(防其他 agent 重复拉取) now := time.Now() for _, t := range tasks { - h.db.Model(&models.AgentTask{}).Where("id = ? AND status = ?", t.ID, "pending"). + h.db.Model(&model.AgentTask{}).Where("id = ? AND status = ?", t.ID, "pending"). Updates(map[string]interface{}{"status": "running", "picked_at": now}) } - c.JSON(200, models.Response{Code: 200, Data: tasks}) + c.JSON(200, model.Response{Code: 200, Data: tasks}) } // SubmitResult Agent 回传执行结果(Agent 调用,无需 JWT) @@ -101,7 +101,7 @@ func (h *AgentTaskHandler) SubmitResult(c *gin.Context) { Status string `json:"status"` // success / failed / timeout } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(400, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(400, model.Response{Code: 400, Message: "参数错误"}) return } @@ -113,18 +113,18 @@ func (h *AgentTaskHandler) SubmitResult(c *gin.Context) { "finished_at": now, } - if err := h.db.Model(&models.AgentTask{}).Where("task_id = ?", taskID).Updates(updates).Error; err != nil { - c.JSON(500, models.Response{Code: 500, Message: "更新失败"}) + if err := h.db.Model(&model.AgentTask{}).Where("task_id = ?", taskID).Updates(updates).Error; err != nil { + c.JSON(500, model.Response{Code: 500, Message: "更新失败"}) return } - c.JSON(200, models.Response{Code: 200, Message: "ok"}) + c.JSON(200, model.Response{Code: 200, Message: "ok"}) } // ListTasks 查询任务列表(前端调用,需 JWT) // GET /api/v1/agent/tasks?hostname=xxx&status=xxx func (h *AgentTaskHandler) ListTasks(c *gin.Context) { - query := h.db.Model(&models.AgentTask{}) + query := h.db.Model(&model.AgentTask{}) if hostname := c.Query("hostname"); hostname != "" { query = query.Where("hostname = ?", hostname) @@ -133,21 +133,21 @@ func (h *AgentTaskHandler) ListTasks(c *gin.Context) { query = query.Where("status = ?", status) } - var tasks []models.AgentTask + var tasks []model.AgentTask query.Order("created_at DESC").Limit(200).Find(&tasks) - c.JSON(200, models.Response{Code: 200, Data: tasks}) + c.JSON(200, model.Response{Code: 200, Data: tasks}) } // GetTask 获取单个任务详情 // GET /api/v1/agent/tasks/:id func (h *AgentTaskHandler) GetTask(c *gin.Context) { - var task models.AgentTask + var task model.AgentTask if err := h.db.First(&task, c.Param("id")).Error; err != nil { - c.JSON(404, models.Response{Code: 404, Message: "任务不存在"}) + c.JSON(404, model.Response{Code: 404, Message: "任务不存在"}) return } - c.JSON(200, models.Response{Code: 200, Data: task}) + c.JSON(200, model.Response{Code: 200, Data: task}) } // ===== Agent 告警规则 ===== @@ -162,20 +162,20 @@ func (h *AgentTaskHandler) QuickSetupRules(c *gin.Context) { // 获取所有在线主机 var onlineHosts []string - h.db.Model(&models.Server{}). + h.db.Model(&model.Server{}). Where("agent_status = ?", "online"). Pluck("hostname", &onlineHosts) if len(onlineHosts) == 0 { // 如果没有在线主机,尝试从 agent_reports 中获取最近 3 分钟活跃的主机名 - h.db.Model(&models.AgentReport{}). + h.db.Model(&model.AgentReport{}). Where("report_time >= ?", time.Now().Add(-3*time.Minute)). Distinct("hostname"). Pluck("hostname", &onlineHosts) } if len(onlineHosts) == 0 { - c.JSON(400, models.Response{Code: 400, Message: "没有在线的主机,请先安装并启动 Agent"}) + c.JSON(400, model.Response{Code: 400, Message: "没有在线的主机,请先安装并启动 Agent"}) return } @@ -199,14 +199,14 @@ func (h *AgentTaskHandler) QuickSetupRules(c *gin.Context) { for _, host := range onlineHosts { for _, def := range defaultRules { // 检查是否已存在同名同主机的规则,避免重复创建 - var existing models.AgentRule + var existing model.AgentRule h.db.Where("name = ? AND hostname = ?", def.Name, host).First(&existing) if existing.ID > 0 { skipped++ continue } - rule := models.AgentRule{ + rule := model.AgentRule{ Name: def.Name, Hostname: host, Metric: def.Metric, @@ -221,7 +221,7 @@ func (h *AgentTaskHandler) QuickSetupRules(c *gin.Context) { } } - c.JSON(200, models.Response{ + c.JSON(200, model.Response{ Code: 200, Message: fmt.Sprintf("已为 %d 台主机创建 %d 条规则(跳过 %d 条已存在的)", len(onlineHosts), created, skipped), Data: gin.H{"hosts": len(onlineHosts), "created": created, "skipped": skipped}, @@ -230,67 +230,67 @@ func (h *AgentTaskHandler) QuickSetupRules(c *gin.Context) { // ListRules GET /api/v1/agent/rules func (h *AgentTaskHandler) ListRules(c *gin.Context) { - var rules []models.AgentRule + var rules []model.AgentRule h.db.Order("created_at DESC").Find(&rules) - c.JSON(200, models.Response{Code: 200, Data: rules}) + c.JSON(200, model.Response{Code: 200, Data: rules}) } // CreateRule POST /api/v1/agent/rules func (h *AgentTaskHandler) CreateRule(c *gin.Context) { - var rule models.AgentRule + var rule model.AgentRule if err := c.ShouldBindJSON(&rule); err != nil { - c.JSON(400, models.Response{Code: 400, Message: err.Error()}) + c.JSON(400, model.Response{Code: 400, Message: err.Error()}) return } rule.ID = 0 rule.Enabled = true if err := h.db.Create(&rule).Error; err != nil { - c.JSON(500, models.Response{Code: 500, Message: err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: err.Error()}) return } - c.JSON(200, models.Response{Code: 200, Data: rule}) + c.JSON(200, model.Response{Code: 200, Data: rule}) } // UpdateRule PUT /api/v1/agent/rules/:id func (h *AgentTaskHandler) UpdateRule(c *gin.Context) { - var rule models.AgentRule + var rule model.AgentRule if err := h.db.First(&rule, c.Param("id")).Error; err != nil { - c.JSON(404, models.Response{Code: 404, Message: "规则不存在"}) + c.JSON(404, model.Response{Code: 404, Message: "规则不存在"}) return } - var update models.AgentRule + var update model.AgentRule if err := c.ShouldBindJSON(&update); err != nil { - c.JSON(400, models.Response{Code: 400, Message: err.Error()}) + c.JSON(400, model.Response{Code: 400, Message: err.Error()}) return } h.db.Model(&rule).Updates(update) - c.JSON(200, models.Response{Code: 200, Data: rule}) + c.JSON(200, model.Response{Code: 200, Data: rule}) } // DeleteRule DELETE /api/v1/agent/rules/:id func (h *AgentTaskHandler) DeleteRule(c *gin.Context) { - h.db.Delete(&models.AgentRule{}, c.Param("id")) - c.JSON(200, models.Response{Code: 200, Message: "ok"}) + h.db.Delete(&model.AgentRule{}, c.Param("id")) + c.JSON(200, model.Response{Code: 200, Message: "ok"}) } // ListAlerts GET /api/v1/agent/alerts func (h *AgentTaskHandler) ListAlerts(c *gin.Context) { - query := h.db.Model(&models.AgentAlert{}) + query := h.db.Model(&model.AgentAlert{}) if c.Query("resolved") == "false" { query = query.Where("resolved = ?", false) } if hostname := c.Query("hostname"); hostname != "" { query = query.Where("hostname = ?", hostname) } - var alerts []models.AgentAlert + var alerts []model.AgentAlert query.Order("created_at DESC").Limit(200).Find(&alerts) - c.JSON(200, models.Response{Code: 200, Data: alerts}) + c.JSON(200, model.Response{Code: 200, Data: alerts}) } // ResolveAlert POST /api/v1/agent/alerts/:id/resolve func (h *AgentTaskHandler) ResolveAlert(c *gin.Context) { now := time.Now() - h.db.Model(&models.AgentAlert{}).Where("id = ?", c.Param("id")). + h.db.Model(&model.AgentAlert{}).Where("id = ?", c.Param("id")). Updates(map[string]interface{}{"resolved": true, "resolved_at": now}) - c.JSON(200, models.Response{Code: 200, Message: "ok"}) + c.JSON(200, model.Response{Code: 200, Message: "ok"}) } diff --git a/backend/internal/api/handlers/alert.go b/backend/controller/alert.go similarity index 78% rename from backend/internal/api/handlers/alert.go rename to backend/controller/alert.go index c6519ce..f010c20 100644 --- a/backend/internal/api/handlers/alert.go +++ b/backend/controller/alert.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "encoding/json" "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -33,13 +33,13 @@ func NewAlertHandler(db *gorm.DB) *AlertHandler { // @Param page_size query int false "每页数量" // @Param status query string false "状态过滤" // @Param severity query string false "级别过滤" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /alerts [get] func (h *AlertHandler) ListAlerts(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) - db := h.db.Model(&models.AlertEvent{}).Preload("Rule") + db := h.db.Model(&model.AlertEvent{}).Preload("Rule") // 状态过滤 if status := c.Query("status"); status != "" { @@ -54,16 +54,16 @@ func (h *AlertHandler) ListAlerts(c *gin.Context) { var total int64 db.Count(&total) - var alerts []models.AlertEvent + var alerts []model.AlertEvent db.Order("created_at DESC"). Offset(query.GetOffset()). Limit(query.GetLimit()). Find(&alerts) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: alerts, Total: total, }, @@ -78,24 +78,24 @@ func (h *AlertHandler) ListAlerts(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "告警ID" -// @Param request body models.AcknowledgeAlertRequest true "确认请求" -// @Success 200 {object} models.Response{data=models.AlertEvent} +// @Param request body model.AcknowledgeAlertRequest true "确认请求" +// @Success 200 {object} model.Response{data=model.AlertEvent} // @Router /alerts/{id}/ack [post] func (h *AlertHandler) AcknowledgeAlert(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.AcknowledgeAlertRequest + var req model.AcknowledgeAlertRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误", }) return } - var alert models.AlertEvent + var alert model.AlertEvent if err := h.db.First(&alert, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "告警不存在", }) @@ -108,14 +108,14 @@ func (h *AlertHandler) AcknowledgeAlert(c *gin.Context) { // alert.AcknowledgedAt = &now if err := h.db.Save(&alert).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "确认失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "确认成功", Data: alert, diff --git a/backend/internal/api/handlers/alert_channels.go b/backend/controller/alert_channels.go similarity index 86% rename from backend/internal/api/handlers/alert_channels.go rename to backend/controller/alert_channels.go index 87a8af3..043436f 100644 --- a/backend/internal/api/handlers/alert_channels.go +++ b/backend/controller/alert_channels.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "bytes" @@ -13,7 +13,7 @@ import ( "strings" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -26,16 +26,16 @@ import ( // @Tags 告警 // @Produce json // @Security Bearer -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /alerts/notify-channels [get] func (h *AlertHandler) ListNotifyChannels(c *gin.Context) { - var channels []models.NotifyChannel + var channels []model.NotifyChannel h.db.Order("created_at DESC").Find(&channels) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: channels, Total: int64(len(channels)), }, @@ -49,20 +49,20 @@ func (h *AlertHandler) ListNotifyChannels(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateNotifyChannelRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.NotifyChannel} +// @Param request body model.CreateNotifyChannelRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.NotifyChannel} // @Router /alerts/notify-channels [post] func (h *AlertHandler) CreateNotifyChannel(c *gin.Context) { - var req models.CreateNotifyChannelRequest + var req model.CreateNotifyChannelRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - channel := models.NotifyChannel{ + channel := model.NotifyChannel{ Name: req.Name, Type: req.Type, Config: req.Config, @@ -70,14 +70,14 @@ func (h *AlertHandler) CreateNotifyChannel(c *gin.Context) { } if err := h.db.Create(&channel).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: channel, @@ -92,24 +92,24 @@ func (h *AlertHandler) CreateNotifyChannel(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "渠道ID" -// @Param request body models.UpdateNotifyChannelRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.NotifyChannel} +// @Param request body model.UpdateNotifyChannelRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.NotifyChannel} // @Router /alerts/notify-channels/{id} [put] func (h *AlertHandler) UpdateNotifyChannel(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.UpdateNotifyChannelRequest + var req model.UpdateNotifyChannelRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var channel models.NotifyChannel + var channel model.NotifyChannel if err := h.db.First(&channel, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "通知渠道不存在", }) @@ -131,7 +131,7 @@ func (h *AlertHandler) UpdateNotifyChannel(c *gin.Context) { } if err := h.db.Model(&channel).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -139,7 +139,7 @@ func (h *AlertHandler) UpdateNotifyChannel(c *gin.Context) { } h.db.First(&channel, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: channel, @@ -153,20 +153,20 @@ func (h *AlertHandler) UpdateNotifyChannel(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "渠道ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /alerts/notify-channels/{id} [delete] func (h *AlertHandler) DeleteNotifyChannel(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.NotifyChannel{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.NotifyChannel{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -179,14 +179,14 @@ func (h *AlertHandler) DeleteNotifyChannel(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "渠道ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /alerts/notify-channels/{id}/test [post] func (h *AlertHandler) TestNotifyChannel(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var channel models.NotifyChannel + var channel model.NotifyChannel if err := h.db.First(&channel, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "通知渠道不存在", }) @@ -213,7 +213,7 @@ func (h *AlertHandler) TestNotifyChannel(c *gin.Context) { h.db.Model(&channel).Update("test_status", status) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: message, Data: gin.H{ @@ -228,7 +228,7 @@ func (h *AlertHandler) TestNotifyChannel(c *gin.Context) { // sendFeishuTest 发送飞书测试通知 func sendFeishuTest(configJSON string) error { - var cfg models.FeishuWebhookConfig + var cfg model.FeishuWebhookConfig if err := json.Unmarshal([]byte(configJSON), &cfg); err != nil { return fmt.Errorf("解析配置失败: %w", err) } @@ -244,7 +244,7 @@ func sendFeishuTest(configJSON string) error { // sendFeishuAlert 发送飞书告警通知 func sendFeishuAlert(configJSON, title, content, severity string) error { - var cfg models.FeishuWebhookConfig + var cfg model.FeishuWebhookConfig if err := json.Unmarshal([]byte(configJSON), &cfg); err != nil { return fmt.Errorf("解析配置失败: %w", err) } @@ -272,7 +272,7 @@ func sendFeishuAlert(configJSON, title, content, severity string) error { // sendFeishuRecovery 发送飞书恢复通知 func sendFeishuRecovery(configJSON, title, content string) error { - var cfg models.FeishuWebhookConfig + var cfg model.FeishuWebhookConfig if err := json.Unmarshal([]byte(configJSON), &cfg); err != nil { return fmt.Errorf("解析配置失败: %w", err) } @@ -397,12 +397,12 @@ func splitLines(s string) []string { } // buildFeishuCard 构建飞书卡片消息体(保留备用,当前使用文本格式) -func buildFeishuCard(title, content, color string) models.FeishuCardMessage { - return models.FeishuCardMessage{ +func buildFeishuCard(title, content, color string) model.FeishuCardMessage { + return model.FeishuCardMessage{ MsgType: "interactive", - Content: models.FeishuCardContent{ + Content: model.FeishuCardContent{ Title: title, - Content: [][]models.FeishuCardElement{ + Content: [][]model.FeishuCardElement{ { { Tag: "markdown", @@ -432,7 +432,7 @@ func genFeishuSign(timestamp int64, secret string) string { // NotifyAlert 发送告警通知到所有启用的渠道 func (h *AlertHandler) NotifyAlert(ruleName, hostname, metric, severity, message string, value, threshold float64) { - var channels []models.NotifyChannel + var channels []model.NotifyChannel h.db.Where("enabled = ?", true).Find(&channels) for _, ch := range channels { @@ -449,7 +449,7 @@ func (h *AlertHandler) NotifyAlert(ruleName, hostname, metric, severity, message // NotifyRecovery 发送恢复通知到所有启用的渠道 func (h *AlertHandler) NotifyRecovery(ruleName, hostname, metric, message string) { - var channels []models.NotifyChannel + var channels []model.NotifyChannel h.db.Where("enabled = ?", true).Find(&channels) for _, ch := range channels { diff --git a/backend/internal/api/handlers/alert_contacts.go b/backend/controller/alert_contacts.go similarity index 57% rename from backend/internal/api/handlers/alert_contacts.go rename to backend/controller/alert_contacts.go index f0349cd..a0b79fd 100644 --- a/backend/internal/api/handlers/alert_contacts.go +++ b/backend/controller/alert_contacts.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "encoding/json" "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -16,23 +16,23 @@ import ( // ListContacts GET /alerts/contacts func (h *AlertHandler) ListContacts(c *gin.Context) { - var contacts []models.AlertContact + var contacts []model.AlertContact h.db.Order("created_at DESC").Find(&contacts) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{List: contacts, Total: int64(len(contacts))}, + Data: model.ListResponse{List: contacts, Total: int64(len(contacts))}, }) } // CreateContact POST /alerts/contacts func (h *AlertHandler) CreateContact(c *gin.Context) { - var req models.CreateContactRequest + var req model.CreateContactRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } - contact := models.AlertContact{ + contact := model.AlertContact{ Name: req.Name, Phone: req.Phone, Email: req.Email, @@ -40,23 +40,23 @@ func (h *AlertHandler) CreateContact(c *gin.Context) { WebhookURL: req.WebhookURL, } if err := h.db.Create(&contact).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: contact}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "创建成功", Data: contact}) } // UpdateContact PUT /alerts/contacts/:id func (h *AlertHandler) UpdateContact(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.UpdateContactRequest + var req model.UpdateContactRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误"}) return } - var contact models.AlertContact + var contact model.AlertContact if err := h.db.First(&contact, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "联系人不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "联系人不存在"}) return } updates := map[string]interface{}{} @@ -67,63 +67,63 @@ func (h *AlertHandler) UpdateContact(c *gin.Context) { if req.WebhookURL != "" { updates["webhook_url"] = req.WebhookURL } h.db.Model(&contact).Updates(updates) h.db.First(&contact, id) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: contact}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功", Data: contact}) } // DeleteContact DELETE /alerts/contacts/:id func (h *AlertHandler) DeleteContact(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.AlertContact{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if err := h.db.Delete(&model.AlertContact{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // ==================== 联系组 ==================== // ListContactGroups GET /alerts/contact-groups func (h *AlertHandler) ListContactGroups(c *gin.Context) { - var groups []models.AlertContactGroup + var groups []model.AlertContactGroup h.db.Order("created_at DESC").Find(&groups) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{List: groups, Total: int64(len(groups))}, + Data: model.ListResponse{List: groups, Total: int64(len(groups))}, }) } // CreateContactGroup POST /alerts/contact-groups func (h *AlertHandler) CreateContactGroup(c *gin.Context) { - var req models.CreateContactGroupRequest + var req model.CreateContactGroupRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } idsJSON, _ := json.Marshal(req.ContactIDs) - group := models.AlertContactGroup{ + group := model.AlertContactGroup{ GroupName: req.GroupName, Notes: req.Notes, ContactIDs: string(idsJSON), } if err := h.db.Create(&group).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: group}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "创建成功", Data: group}) } // UpdateContactGroup PUT /alerts/contact-groups/:id func (h *AlertHandler) UpdateContactGroup(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.UpdateContactGroupRequest + var req model.UpdateContactGroupRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误"}) return } - var group models.AlertContactGroup + var group model.AlertContactGroup if err := h.db.First(&group, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "联系组不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "联系组不存在"}) return } updates := map[string]interface{}{} @@ -135,15 +135,15 @@ func (h *AlertHandler) UpdateContactGroup(c *gin.Context) { } h.db.Model(&group).Updates(updates) h.db.First(&group, id) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: group}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功", Data: group}) } // DeleteContactGroup DELETE /alerts/contact-groups/:id func (h *AlertHandler) DeleteContactGroup(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.AlertContactGroup{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if err := h.db.Delete(&model.AlertContactGroup{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } diff --git a/backend/internal/api/handlers/alert_engine.go b/backend/controller/alert_engine.go similarity index 69% rename from backend/internal/api/handlers/alert_engine.go rename to backend/controller/alert_engine.go index 2b14ed9..55aa9f2 100644 --- a/backend/internal/api/handlers/alert_engine.go +++ b/backend/controller/alert_engine.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "encoding/json" "fmt" "time" - "ezops/internal/models" + "ezops/model" "gorm.io/gorm" ) @@ -29,13 +29,13 @@ func (e *AlertEngine) Check() { // 检查 CPU/内存/磁盘/进程/TCP连接/端口 阈值 func (e *AlertEngine) checkResourceAlerts() { - var rules []models.AgentRule + var rules []model.AgentRule e.db.Where("enabled = ? AND metric IN ?", true, []string{"cpu", "mem", "disk", "service_process", "tcp_time_wait", "tcp_close_wait", "fd"}).Find(&rules) for _, rule := range rules { // 获取目标主机最新上报 - var report models.AgentReport - query := e.db.Model(&models.AgentReport{}) + var report model.AgentReport + query := e.db.Model(&model.AgentReport{}) if rule.Hostname != "" { query = query.Where("hostname = ?", rule.Hostname) } @@ -51,7 +51,7 @@ func (e *AlertEngine) checkResourceAlerts() { case "mem": value = report.MemUsage case "disk": - var disks []models.DiskMetric + var disks []model.DiskMetric json.Unmarshal([]byte(report.DiskInfo), &disks) for _, d := range disks { if d.UsagePercent > value { @@ -59,16 +59,16 @@ func (e *AlertEngine) checkResourceAlerts() { } } case "tcp_time_wait": - var netStat models.NetworkStatModel + var netStat model.NetworkStatModel json.Unmarshal([]byte(report.NetInfo), &netStat) value = float64(netStat.TCPTimeWait) case "tcp_close_wait": - var netStat models.NetworkStatModel + var netStat model.NetworkStatModel json.Unmarshal([]byte(report.NetInfo), &netStat) value = float64(netStat.TCPCloseWait) case "service_process": // 进程不存在告警 — 检查 process_top_info 中是否包含指定进程名 - var processes []models.ProcessMetric + var processes []model.ProcessMetric json.Unmarshal([]byte(report.ProcessTopInfo), &processes) found := false for _, p := range processes { @@ -82,7 +82,7 @@ func (e *AlertEngine) checkResourceAlerts() { } value = 0 // 进程不存在时触发 case "fd": - var fdStat models.FDMetric + var fdStat model.FDMetric json.Unmarshal([]byte(report.FDInfo), &fdStat) value = fdStat.UsagePct } @@ -93,7 +93,7 @@ func (e *AlertEngine) checkResourceAlerts() { } // 避免重复告警:如果最近 10 分钟已有同规则未恢复告警,不重复 - var existing models.AgentAlert + var existing model.AgentAlert tenMinAgo := time.Now().Add(-10 * time.Minute) e.db.Where("rule_name = ? AND hostname = ? AND resolved = ? AND created_at > ?", rule.Name, report.Hostname, false, tenMinAgo).First(&existing) @@ -101,8 +101,13 @@ func (e *AlertEngine) checkResourceAlerts() { continue } + // 检查静默规则 — 匹配则不创建告警、不发送通知 + if e.isSilenced(rule.Name, report.Hostname, rule.ID) { + continue + } + // 创建告警 - alert := models.AgentAlert{ + alert := model.AgentAlert{ RuleName: rule.Name, Hostname: report.Hostname, Metric: rule.Metric, @@ -132,14 +137,14 @@ func (e *AlertEngine) checkOfflineAlerts() { offlineThreshold := 3 * time.Minute // 获取所有已登记的主机(去重 IP) - var servers []models.Server + var servers []model.Server e.db.Select("ip, hostname").Group("ip").Find(&servers) // 收集所有 agent_reports 中活跃上报的主机名(最近 3 分钟内有上报) threeMinAgo := time.Now().Add(-offlineThreshold) var activeHostnames []string - e.db.Model(&models.AgentReport{}). + e.db.Model(&model.AgentReport{}). Where("report_time >= ?", threeMinAgo). Distinct("hostname"). Pluck("hostname", &activeHostnames) @@ -160,7 +165,7 @@ func (e *AlertEngine) checkOfflineAlerts() { } // 检查该 hostname 的最新上报——其源 IP 是否匹配此 server IP // (通过 servers 表中查找 hostname 对应的 IP) - var matchedServer models.Server + var matchedServer model.Server e.db.Where("hostname = ?", h).First(&matchedServer) if matchedServer.ID > 0 && matchedServer.IP == s.IP { hasActiveAgent = true @@ -173,13 +178,13 @@ func (e *AlertEngine) checkOfflineAlerts() { } // 该服务器离线:检查是否已有未恢复的离线告警 - var existing models.AgentAlert + var existing model.AgentAlert e.db.Where("hostname = ? AND metric = ? AND resolved = ?", s.Hostname, "offline", false).First(&existing) if existing.ID == 0 { // 获取最后一次上报时间计算离线时长 - var lastReport models.AgentReport + var lastReport model.AgentReport e.db.Where("hostname = ?", s.Hostname).Order("id DESC").First(&lastReport) offlineMinutes := 3.0 var lastReportTime time.Time @@ -188,7 +193,12 @@ func (e *AlertEngine) checkOfflineAlerts() { lastReportTime = lastReport.ReportTime } - alert := models.AgentAlert{ + // 检查静默规则 + if e.isSilenced("主机离线", s.Hostname, 0) { + continue + } + + alert := model.AgentAlert{ RuleName: "主机离线", Hostname: s.Hostname, Metric: "offline", @@ -213,7 +223,7 @@ func (e *AlertEngine) checkOfflineAlerts() { // 检查端口消失(之前有的监听端口现在没了) func (e *AlertEngine) checkPortAlerts() { - var rules []models.AgentRule + var rules []model.AgentRule e.db.Where("enabled = ? AND metric = ?", true, "port_down").Find(&rules) for _, rule := range rules { @@ -222,8 +232,8 @@ func (e *AlertEngine) checkPortAlerts() { } // 获取目标主机最新上报 - var report models.AgentReport - query := e.db.Model(&models.AgentReport{}) + var report model.AgentReport + query := e.db.Model(&model.AgentReport{}) if rule.Hostname != "" { query = query.Where("hostname = ?", rule.Hostname) } @@ -233,7 +243,7 @@ func (e *AlertEngine) checkPortAlerts() { } // 检查端口是否在最新上报中 - var ports []models.PortMetric + var ports []model.PortMetric json.Unmarshal([]byte(report.PortInfo), &ports) portUp := false @@ -249,14 +259,19 @@ func (e *AlertEngine) checkPortAlerts() { } // 端口消失了,检查是否已有未恢复告警 - var existing models.AgentAlert + var existing model.AgentAlert e.db.Where("rule_name = ? AND hostname = ? AND resolved = ?", rule.Name, report.Hostname, false).First(&existing) if existing.ID > 0 { continue } - alert := models.AgentAlert{ + // 检查静默规则 + if e.isSilenced(rule.Name, report.Hostname, rule.ID) { + continue + } + + alert := model.AgentAlert{ RuleName: rule.Name, Hostname: report.Hostname, Metric: "port_down", @@ -278,7 +293,7 @@ func (e *AlertEngine) checkPortAlerts() { // 自动恢复告警(指标恢复正常) func (e *AlertEngine) autoResolveAlerts() { - var alerts []models.AgentAlert + var alerts []model.AgentAlert e.db.Where("resolved = ?", false).Find(&alerts) for _, alert := range alerts { @@ -287,19 +302,19 @@ func (e *AlertEngine) autoResolveAlerts() { switch alert.Metric { case "offline": // 主机重新上报了 - var report models.AgentReport + var report model.AgentReport e.db.Where("hostname = ?", alert.Hostname).Order("id DESC").First(&report) if report.ID > 0 && time.Since(report.ReportTime) < 3*time.Minute { resolved = true } case "cpu", "mem", "disk", "tcp_time_wait", "tcp_close_wait", "fd": // 获取对应规则,检查是否恢复正常 - var rule models.AgentRule + var rule model.AgentRule e.db.Where("name = ?", alert.RuleName).First(&rule) if rule.ID == 0 { continue } - var report models.AgentReport + var report model.AgentReport if rule.Hostname != "" { e.db.Where("hostname = ?", alert.Hostname).Order("id DESC").First(&report) } else { @@ -315,7 +330,7 @@ func (e *AlertEngine) autoResolveAlerts() { case "mem": value = report.MemUsage case "disk": - var disks []models.DiskMetric + var disks []model.DiskMetric json.Unmarshal([]byte(report.DiskInfo), &disks) for _, d := range disks { if d.UsagePercent > value { @@ -323,15 +338,15 @@ func (e *AlertEngine) autoResolveAlerts() { } } case "tcp_time_wait": - var netStat models.NetworkStatModel + var netStat model.NetworkStatModel json.Unmarshal([]byte(report.NetInfo), &netStat) value = float64(netStat.TCPTimeWait) case "tcp_close_wait": - var netStat models.NetworkStatModel + var netStat model.NetworkStatModel json.Unmarshal([]byte(report.NetInfo), &netStat) value = float64(netStat.TCPCloseWait) case "fd": - var fdStat models.FDMetric + var fdStat model.FDMetric json.Unmarshal([]byte(report.FDInfo), &fdStat) value = fdStat.UsagePct } @@ -339,12 +354,12 @@ func (e *AlertEngine) autoResolveAlerts() { resolved = true } case "port_down": - var rule models.AgentRule + var rule model.AgentRule e.db.Where("name = ?", alert.RuleName).First(&rule) if rule.ID > 0 { - var report models.AgentReport + var report model.AgentReport e.db.Where("hostname = ?", alert.Hostname).Order("id DESC").First(&report) - var ports []models.PortMetric + var ports []model.PortMetric json.Unmarshal([]byte(report.PortInfo), &ports) for _, p := range ports { if p.Port == rule.Port { @@ -386,14 +401,14 @@ func (e *AlertEngine) compareOperator(op string, val, threshold float64) bool { } // notifyAlert 发送告警通知(通过 AgentRule 对应的 notify_channels) -func (e *AlertEngine) notifyAlert(rule *models.AgentRule, hostname string, alert models.AgentAlert) { +func (e *AlertEngine) notifyAlert(rule *model.AgentRule, hostname string, alert model.AgentAlert) { e.notifyAlertRule(rule.Name, hostname, alert.Metric, alert.Severity, alert.Message, alert.Value, alert.Threshold) } // notifyAlertRule 按规则发送告警通知到所有启用的飞书渠道 func (e *AlertEngine) notifyAlertRule(ruleName, hostname, metric, severity, message string, value, threshold float64) { - var channels []models.NotifyChannel + var channels []model.NotifyChannel e.db.Where("enabled = ? AND type = ?", true, "feishu").Find(&channels) for _, ch := range channels { @@ -410,15 +425,122 @@ func (e *AlertEngine) notifyAlertRule(ruleName, hostname, metric, severity, mess // notifyRecovery 发送恢复通知到所有启用的飞书渠道 func (e *AlertEngine) notifyRecovery(ruleName, hostname, metric, message string) { - var channels []models.NotifyChannel + var channels []model.NotifyChannel e.db.Where("enabled = ? AND type = ?", true, "feishu").Find(&channels) for _, ch := range channels { title := fmt.Sprintf("%s — 已恢复正常", ruleName) - content := fmt.Sprintf("**告警已恢复**\\n\\n主机:%s\\n指标:%s\\n详情:%s\\n恢复时间:%s", + content := fmt.Sprintf("**告警已恢复**\\\\n\\\\n主机:%s\\\\n指标:%s\\\\n详情:%s\\\\n恢复时间:%s", hostname, metric, message, time.Now().Format("2006-01-02 15:04:05")) if err := sendFeishuRecovery(ch.Config, title, content); err != nil { fmt.Printf("[AlertEngine] 飞书恢复通知失败 (渠道:%s): %v\n", ch.Name, err) } } } + +// isSilenced 检查给定告警是否被静默规则匹配 +// 匹配逻辑:status=1 且 当前时间在静默窗口内 +// 匹配维度:rule_name(精确匹配)、rule_id(ID 匹配)、hostname(通过 target_ids 中的 server IP 间接匹配) +// silence_type:onetime=一次性窗口,daily=每天指定时段,weekly=每周指定星期+时段 +func (e *AlertEngine) isSilenced(ruleName, hostname string, ruleID uint) bool { + var silences []model.AlertSilence + e.db.Where("status = ?", 1).Find(&silences) + + now := time.Now() + for _, s := range silences { + // 检查规则名匹配 — 通过 rule_ids JSON 数组 + if s.RuleIDs != "" && s.RuleIDs != "null" { + var ruleIDs []uint + json.Unmarshal([]byte(s.RuleIDs), &ruleIDs) + matched := false + for _, rid := range ruleIDs { + if rid == ruleID { + matched = true + break + } + } + if !matched { + continue // 该静默规则不匹配此 rule_id + } + } + + // 检查目标主机匹配 — 通过 target_ids(server IDs)间接匹配 + if s.TargetIDs != "" && s.TargetIDs != "null" { + var targetIDs []uint + json.Unmarshal([]byte(s.TargetIDs), &targetIDs) + if len(targetIDs) > 0 { + matched := false + for _, tid := range targetIDs { + var server model.Server + e.db.Select("hostname").First(&server, tid) + if server.Hostname == hostname { + matched = true + break + } + } + if !matched { + continue + } + } + } + + // 检查时间窗口 + switch s.SilenceType { + case model.AlertSilenceOneTime: + // 一次性:start_time <= now <= end_time + if now.After(s.StartTime) && now.Before(s.EndTime) { + return true + } + case model.AlertSilenceDaily: + // 每天:检查当前时分是否在窗口内 + nowMinutes := now.Hour()*60 + now.Minute() + startMinutes := s.StartTime.Hour()*60 + s.StartTime.Minute() + endMinutes := s.EndTime.Hour()*60 + s.EndTime.Minute() + if startMinutes <= endMinutes { + if nowMinutes >= startMinutes && nowMinutes <= endMinutes { + return true + } + } else { + // 跨天(如 23:00-06:00) + if nowMinutes >= startMinutes || nowMinutes <= endMinutes { + return true + } + } + case model.AlertSilenceWeekly: + // 每周:检查当前星期是否在 weekdays 列表中,且时分在窗口内 + if s.Weekdays != "" && s.Weekdays != "null" { + var weekdays []int + json.Unmarshal([]byte(s.Weekdays), &weekdays) + weekdayMatched := false + todayWeekday := int(now.Weekday()) + for _, wd := range weekdays { + if wd == todayWeekday { + weekdayMatched = true + break + } + } + if !weekdayMatched { + continue + } + } + nowMinutes := now.Hour()*60 + now.Minute() + startMinutes := s.StartTime.Hour()*60 + s.StartTime.Minute() + endMinutes := s.EndTime.Hour()*60 + s.EndTime.Minute() + if startMinutes <= endMinutes { + if nowMinutes >= startMinutes && nowMinutes <= endMinutes { + return true + } + } else { + if nowMinutes >= startMinutes || nowMinutes <= endMinutes { + return true + } + } + default: + // 默认按 onetime 处理 + if now.After(s.StartTime) && now.Before(s.EndTime) { + return true + } + } + } + return false +} diff --git a/backend/internal/api/handlers/alert_rules.go b/backend/controller/alert_rules.go similarity index 77% rename from backend/internal/api/handlers/alert_rules.go rename to backend/controller/alert_rules.go index 2e2c15e..698c88b 100644 --- a/backend/internal/api/handlers/alert_rules.go +++ b/backend/controller/alert_rules.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "fmt" "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -20,22 +20,22 @@ import ( // @Security Bearer // @Param page query int false "页码" // @Param page_size query int false "每页数量" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /alerts/rules [get] func (h *AlertHandler) ListRules(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) var total int64 - h.db.Model(&models.AlertRule{}).Count(&total) + h.db.Model(&model.AlertRule{}).Count(&total) - var rules []models.AlertRule + var rules []model.AlertRule h.db.Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&rules) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: rules, Total: total, }, @@ -49,20 +49,20 @@ func (h *AlertHandler) ListRules(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateAlertRuleRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.AlertRule} +// @Param request body model.CreateAlertRuleRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.AlertRule} // @Router /alerts/rules [post] func (h *AlertHandler) CreateRule(c *gin.Context) { - var req models.CreateAlertRuleRequest + var req model.CreateAlertRuleRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - rule := models.AlertRule{ + rule := model.AlertRule{ Name: req.Name, Description: req.Description, Type: req.Type, @@ -77,14 +77,14 @@ func (h *AlertHandler) CreateRule(c *gin.Context) { } if err := h.db.Create(&rule).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: rule, @@ -99,24 +99,24 @@ func (h *AlertHandler) CreateRule(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "规则ID" -// @Param request body models.UpdateAlertRuleRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.AlertRule} +// @Param request body model.UpdateAlertRuleRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.AlertRule} // @Router /alerts/rules/{id} [put] func (h *AlertHandler) UpdateRule(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.UpdateAlertRuleRequest + var req model.UpdateAlertRuleRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var rule models.AlertRule + var rule model.AlertRule if err := h.db.First(&rule, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "规则不存在", }) @@ -153,7 +153,7 @@ func (h *AlertHandler) UpdateRule(c *gin.Context) { } if err := h.db.Model(&rule).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -162,7 +162,7 @@ func (h *AlertHandler) UpdateRule(c *gin.Context) { h.db.First(&rule, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: rule, @@ -176,20 +176,20 @@ func (h *AlertHandler) UpdateRule(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "规则ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /alerts/rules/{id} [delete] func (h *AlertHandler) DeleteRule(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.AlertRule{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.AlertRule{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -202,13 +202,13 @@ func (h *AlertHandler) DeleteRule(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.IDsRequest true "删除请求" -// @Success 200 {object} models.Response +// @Param request body model.IDsRequest true "删除请求" +// @Success 200 {object} model.Response // @Router /alerts/rules/batch-delete [delete] func (h *AlertHandler) BatchDeleteRules(c *gin.Context) { - var req models.IDsRequest + var req model.IDsRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误", }) @@ -216,22 +216,22 @@ func (h *AlertHandler) BatchDeleteRules(c *gin.Context) { } if len(req.IDs) == 0 { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请选择要删除的规则", }) return } - if err := h.db.Delete(&models.AlertRule{}, req.IDs).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.AlertRule{}, req.IDs).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -244,14 +244,14 @@ func (h *AlertHandler) BatchDeleteRules(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "规则ID" -// @Success 200 {object} models.Response{data=models.AlertRule} +// @Success 200 {object} model.Response{data=model.AlertRule} // @Router /alerts/rules/{id}/toggle [post] func (h *AlertHandler) ToggleRule(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var rule models.AlertRule + var rule model.AlertRule if err := h.db.First(&rule, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "规则不存在", }) @@ -260,14 +260,14 @@ func (h *AlertHandler) ToggleRule(c *gin.Context) { rule.Enabled = !rule.Enabled if err := h.db.Save(&rule).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "操作失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "操作成功", Data: rule, @@ -309,12 +309,12 @@ func (h *AlertHandler) QuickSetupRules(c *gin.Context) { created := 0 for _, def := range rules { - var existing models.AgentRule + var existing model.AgentRule h.db.Where("name = ?", def.Name).First(&existing) if existing.ID > 0 { continue } - rule := models.AgentRule{ + rule := model.AgentRule{ Name: def.Name, Metric: def.Metric, Operator: def.Operator, @@ -328,7 +328,7 @@ func (h *AlertHandler) QuickSetupRules(c *gin.Context) { created++ } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: fmt.Sprintf("已创建 %d 条告警规则", created), Data: gin.H{"created": created}, diff --git a/backend/controller/alert_silence.go b/backend/controller/alert_silence.go new file mode 100644 index 0000000..58b8d88 --- /dev/null +++ b/backend/controller/alert_silence.go @@ -0,0 +1,260 @@ +package controller + +import ( + "encoding/json" + "net/http" + "strconv" + "time" + + "ezops/model" + + "github.com/gin-gonic/gin" +) + +// 告警静默规则 CRUD(AlertHandler 方法接收者) // Logan.Li + +// CreateSilenceRequest 创建静默规则请求 +type CreateSilenceRequest struct { + Name string `json:"name" binding:"required"` + Description string `json:"description"` + RuleIDs []uint `json:"rule_ids"` + TargetIDs []uint `json:"target_ids"` + Matchers []model.AlertSilenceMatcher `json:"matchers"` + SilenceType string `json:"silence_type"` + StartTime string `json:"start_time"` + EndTime string `json:"end_time" binding:"required"` + Weekdays []int `json:"weekdays"` + Status *int `json:"status"` +} + +// UpdateSilenceRequest 更新静默规则请求 +type UpdateSilenceRequest struct { + Name string `json:"name"` + Description string `json:"description"` + RuleIDs []uint `json:"rule_ids"` + TargetIDs []uint `json:"target_ids"` + Matchers []model.AlertSilenceMatcher `json:"matchers"` + SilenceType string `json:"silence_type"` + StartTime string `json:"start_time"` + EndTime string `json:"end_time"` + Weekdays []int `json:"weekdays"` + Status *int `json:"status"` +} + +// ListSilences GET /alerts/silences +func (h *AlertHandler) ListSilences(c *gin.Context) { + var silences []model.AlertSilence + query := h.db.Order("created_at DESC") + + if status := c.Query("status"); status != "" { + if status == "active" { + now := time.Now() + query = query.Where("status = ? AND start_time <= ? AND end_time >= ?", 1, now, now) + } else if s, err := strconv.Atoi(status); err == nil { + query = query.Where("status = ?", s) + } + } + + query.Find(&silences) + + // 解析 JSON 字段为前端友好的格式 + type SilenceWithParsed struct { + model.AlertSilence + RuleIDList []uint `json:"rule_id_list"` + TargetIDList []uint `json:"target_id_list"` + MatcherList []model.AlertSilenceMatcher `json:"matcher_list"` + WeekdayList []int `json:"weekday_list"` + IsActive bool `json:"is_active"` + } + + var result []SilenceWithParsed + now := time.Now() + for _, s := range silences { + item := SilenceWithParsed{AlertSilence: s} + if s.RuleIDs != "" { + json.Unmarshal([]byte(s.RuleIDs), &item.RuleIDList) + } + if s.TargetIDs != "" { + json.Unmarshal([]byte(s.TargetIDs), &item.TargetIDList) + } + if s.Matchers != "" { + json.Unmarshal([]byte(s.Matchers), &item.MatcherList) + } + if s.Weekdays != "" { + json.Unmarshal([]byte(s.Weekdays), &item.WeekdayList) + } + item.IsActive = s.Status == 1 && now.After(s.StartTime) && now.Before(s.EndTime) + result = append(result, item) + } + + c.JSON(http.StatusOK, model.Response{ + Code: 200, + Message: "success", + Data: model.ListResponse{List: result, Total: int64(len(result))}, + }) +} + +// CreateSilence POST /alerts/silences +func (h *AlertHandler) CreateSilence(c *gin.Context) { + var req CreateSilenceRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + return + } + + silenceType := model.AlertSilenceOneTime + if req.SilenceType != "" { + silenceType = model.AlertSilenceType(req.SilenceType) + } + + // 解析时间 + var startTime, endTime time.Time + var err error + if req.StartTime != "" { + startTime, err = time.Parse(time.RFC3339, req.StartTime) + if err != nil { + startTime, err = time.ParseInLocation("2006-01-02 15:04:05", req.StartTime, time.Local) + if err != nil { + startTime = time.Now() + } + } + } else { + startTime = time.Now() + } + + endTime, err = time.Parse(time.RFC3339, req.EndTime) + if err != nil { + endTime, err = time.ParseInLocation("2006-01-02 15:04:05", req.EndTime, time.Local) + if err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "结束时间格式错误"}) + return + } + } + + ruleIDsJSON, _ := json.Marshal(req.RuleIDs) + targetIDsJSON, _ := json.Marshal(req.TargetIDs) + matchersJSON, _ := json.Marshal(req.Matchers) + weekdaysJSON, _ := json.Marshal(req.Weekdays) + + silence := model.AlertSilence{ + Name: req.Name, + Description: req.Description, + RuleIDs: string(ruleIDsJSON), + TargetIDs: string(targetIDsJSON), + Matchers: string(matchersJSON), + SilenceType: silenceType, + StartTime: startTime, + EndTime: endTime, + Weekdays: string(weekdaysJSON), + Status: 1, + } + + // 获取创建人 ID + if userID, exists := c.Get("userID"); exists { + if uid, ok := userID.(uint); ok { + silence.CreatedBy = uid + } + } + + if err := h.db.Create(&silence).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败: " + err.Error()}) + return + } + + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "创建成功", Data: silence}) +} + +// UpdateSilence PUT /alerts/silences/:id +func (h *AlertHandler) UpdateSilence(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + var req UpdateSilenceRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误"}) + return + } + + var silence model.AlertSilence + if err := h.db.First(&silence, id).Error; err != nil { + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "静默规则不存在"}) + return + } + + updates := map[string]interface{}{} + if req.Name != "" { + updates["name"] = req.Name + } + if req.Description != "" { + updates["description"] = req.Description + } + if req.SilenceType != "" { + updates["silence_type"] = req.SilenceType + } + if len(req.RuleIDs) > 0 || req.RuleIDs != nil { + ruleIDsJSON, _ := json.Marshal(req.RuleIDs) + updates["rule_ids"] = string(ruleIDsJSON) + } + if len(req.TargetIDs) > 0 || req.TargetIDs != nil { + targetIDsJSON, _ := json.Marshal(req.TargetIDs) + updates["target_ids"] = string(targetIDsJSON) + } + if len(req.Matchers) > 0 || req.Matchers != nil { + matchersJSON, _ := json.Marshal(req.Matchers) + updates["matchers"] = string(matchersJSON) + } + if len(req.Weekdays) > 0 || req.Weekdays != nil { + weekdaysJSON, _ := json.Marshal(req.Weekdays) + updates["weekdays"] = string(weekdaysJSON) + } + if req.StartTime != "" { + if st, err := time.Parse(time.RFC3339, req.StartTime); err == nil { + updates["start_time"] = st + } else if st, err := time.ParseInLocation("2006-01-02 15:04:05", req.StartTime, time.Local); err == nil { + updates["start_time"] = st + } + } + if req.EndTime != "" { + if et, err := time.Parse(time.RFC3339, req.EndTime); err == nil { + updates["end_time"] = et + } else if et, err := time.ParseInLocation("2006-01-02 15:04:05", req.EndTime, time.Local); err == nil { + updates["end_time"] = et + } + } + if req.Status != nil { + updates["status"] = *req.Status + } + + h.db.Model(&silence).Updates(updates) + h.db.First(&silence, id) + + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功", Data: silence}) +} + +// DeleteSilence DELETE /alerts/silences/:id +func (h *AlertHandler) DeleteSilence(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + if err := h.db.Delete(&model.AlertSilence{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) + return + } + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) +} + +// ToggleSilence POST /alerts/silences/:id/toggle +func (h *AlertHandler) ToggleSilence(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + var silence model.AlertSilence + if err := h.db.First(&silence, id).Error; err != nil { + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "静默规则不存在"}) + return + } + + newStatus := 0 + if silence.Status == 0 { + newStatus = 1 + } + + h.db.Model(&silence).Update("status", newStatus) + h.db.First(&silence, id) + + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "切换成功", Data: silence}) +} diff --git a/backend/internal/api/handlers/approval.go b/backend/controller/approval.go similarity index 67% rename from backend/internal/api/handlers/approval.go rename to backend/controller/approval.go index 147bd11..30db3ec 100644 --- a/backend/internal/api/handlers/approval.go +++ b/backend/controller/approval.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -28,22 +28,30 @@ func NewApprovalHandler(db *gorm.DB) *ApprovalHandler { // @Security Bearer // @Param page query int false "页码" // @Param page_size query int false "每页数量" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /approvals/templates [get] func (h *ApprovalHandler) ListTemplates(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) + db := h.db.Model(&model.ApprovalTemplate{}) + if category := c.Query("category"); category != "" { + db = db.Where("category = ?", category) + } + if qType := c.Query("type"); qType != "" { + db = db.Where("type = ?", qType) + } + var total int64 - h.db.Model(&models.ApprovalTemplate{}).Count(&total) + db.Count(&total) - var templates []models.ApprovalTemplate - h.db.Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&templates) + var templates []model.ApprovalTemplate + db.Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&templates) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: templates, Total: total, }, @@ -57,21 +65,21 @@ func (h *ApprovalHandler) ListTemplates(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "模板ID" -// @Success 200 {object} models.Response{data=models.ApprovalTemplate} +// @Success 200 {object} model.Response{data=model.ApprovalTemplate} // @Router /approvals/templates/{id} [get] func (h *ApprovalHandler) GetTemplate(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var template models.ApprovalTemplate + var template model.ApprovalTemplate if err := h.db.First(&template, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "模板不存在", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: template, @@ -85,38 +93,39 @@ func (h *ApprovalHandler) GetTemplate(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateApprovalTemplateRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.ApprovalTemplate} +// @Param request body model.CreateApprovalTemplateRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.ApprovalTemplate} // @Router /approvals/templates [post] func (h *ApprovalHandler) CreateTemplate(c *gin.Context) { - var req models.CreateApprovalTemplateRequest + var req model.CreateApprovalTemplateRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - template := models.ApprovalTemplate{ + template := model.ApprovalTemplate{ Name: req.Name, Code: req.Code, Description: req.Description, Type: req.Type, FormSchema: req.FormSchema, FlowConfig: req.FlowConfig, + Category: req.Category, Enabled: true, } if err := h.db.Create(&template).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: template, @@ -131,24 +140,24 @@ func (h *ApprovalHandler) CreateTemplate(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "模板ID" -// @Param request body models.CreateApprovalTemplateRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.ApprovalTemplate} +// @Param request body model.CreateApprovalTemplateRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.ApprovalTemplate} // @Router /approvals/templates/{id} [put] func (h *ApprovalHandler) UpdateTemplate(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.CreateApprovalTemplateRequest + var req model.CreateApprovalTemplateRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var template models.ApprovalTemplate + var template model.ApprovalTemplate if err := h.db.First(&template, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "模板不存在", }) @@ -164,7 +173,7 @@ func (h *ApprovalHandler) UpdateTemplate(c *gin.Context) { } if err := h.db.Model(&template).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -173,7 +182,7 @@ func (h *ApprovalHandler) UpdateTemplate(c *gin.Context) { h.db.First(&template, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: template, @@ -187,20 +196,20 @@ func (h *ApprovalHandler) UpdateTemplate(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "模板ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /approvals/templates/{id} [delete] func (h *ApprovalHandler) DeleteTemplate(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.ApprovalTemplate{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.ApprovalTemplate{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) diff --git a/backend/internal/api/handlers/approval_process.go b/backend/controller/approval_process.go similarity index 62% rename from backend/internal/api/handlers/approval_process.go rename to backend/controller/approval_process.go index d8df630..0c3b600 100644 --- a/backend/internal/api/handlers/approval_process.go +++ b/backend/controller/approval_process.go @@ -1,39 +1,44 @@ -package handlers +package controller import ( "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) // ListProcesses 获取审批流程列表 // Logan.Li func (h *ApprovalHandler) ListProcesses(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) - db := h.db.Model(&models.ApprovalProcess{}).Preload("Template").Preload("ApplicantUser") + db := h.db.Model(&model.ApprovalProcess{}).Preload("Template").Preload("ApplicantUser") // 状态过滤 if status := c.Query("status"); status != "" { db = db.Where("status = ?", status) } + // 按模板类别过滤 + if category := c.Query("category"); category != "" { + db = db.Joins("JOIN sys_approval_templates ON sys_approval_templates.id = approval_processes.template_id"). + Where("sys_approval_templates.category = ?", category) + } var total int64 db.Count(&total) - var processes []models.ApprovalProcess + var processes []model.ApprovalProcess db.Order("created_at DESC"). Offset(query.GetOffset()). Limit(query.GetLimit()). Find(&processes) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: processes, Total: total, }, @@ -44,16 +49,16 @@ func (h *ApprovalHandler) ListProcesses(c *gin.Context) { func (h *ApprovalHandler) GetProcess(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var process models.ApprovalProcess + var process model.ApprovalProcess if err := h.db.Preload("Template").Preload("ApplicantUser").Preload("Steps.ApproverUser").First(&process, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "流程不存在", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: process, @@ -62,28 +67,32 @@ func (h *ApprovalHandler) GetProcess(c *gin.Context) { // CreateProcess 创建审批流程 // Logan.Li func (h *ApprovalHandler) CreateProcess(c *gin.Context) { - var req models.CreateApprovalProcessRequest + var req model.CreateApprovalProcessRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } + // 获取当前用户 ID + userID, _ := c.Get("user_id") + // 获取模板 - var template models.ApprovalTemplate + var template model.ApprovalTemplate if err := h.db.First(&template, req.TemplateID).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "模板不存在", }) return } - process := models.ApprovalProcess{ + process := model.ApprovalProcess{ TemplateID: req.TemplateID, Title: req.Title, + Applicant: toUint(userID), FormData: req.FormData, Status: "pending", CurrentStep: 0, @@ -91,38 +100,51 @@ func (h *ApprovalHandler) CreateProcess(c *gin.Context) { } if err := h.db.Create(&process).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, - Message: "创建失败", + Message: "创建失败: " + err.Error(), }) return } h.db.Preload("Template").First(&process, process.ID) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: process, }) } +func toUint(v interface{}) uint { + switch val := v.(type) { + case float64: + return uint(val) + case uint: + return val + case int: + return uint(val) + default: + return 0 + } +} + // ApproveProcess 审批通过 // Logan.Li func (h *ApprovalHandler) ApproveProcess(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.ApproveRequest + var req model.ApproveRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误", }) return } - var process models.ApprovalProcess + var process model.ApprovalProcess if err := h.db.First(&process, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "流程不存在", }) @@ -132,14 +154,14 @@ func (h *ApprovalHandler) ApproveProcess(c *gin.Context) { process.Status = "approved" if err := h.db.Save(&process).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "审批失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "审批通过", Data: process, @@ -150,18 +172,18 @@ func (h *ApprovalHandler) ApproveProcess(c *gin.Context) { func (h *ApprovalHandler) RejectProcess(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.ApproveRequest + var req model.ApproveRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误", }) return } - var process models.ApprovalProcess + var process model.ApprovalProcess if err := h.db.First(&process, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "流程不存在", }) @@ -172,14 +194,14 @@ func (h *ApprovalHandler) RejectProcess(c *gin.Context) { process.RejectReason = req.Comment if err := h.db.Save(&process).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "拒绝失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "已拒绝", Data: process, diff --git a/backend/internal/api/handlers/audit.go b/backend/controller/audit.go similarity index 67% rename from backend/internal/api/handlers/audit.go rename to backend/controller/audit.go index 2392b74..955b19c 100644 --- a/backend/internal/api/handlers/audit.go +++ b/backend/controller/audit.go @@ -1,11 +1,14 @@ -package handlers +package controller import ( + "bytes" + "encoding/csv" + "fmt" "net/http" "strconv" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -34,12 +37,12 @@ func NewAuditHandler(db *gorm.DB) *AuditHandler { // @Param username query string false "用户名" // @Param startTime query string false "开始时间" // @Param endTime query string false "结束时间" -// @Success 200 {object} models.AuditLogListResponse +// @Success 200 {object} model.AuditLogListResponse // @Router /api/v1/audit/logs [get] func (h *AuditHandler) ListAuditLogs(c *gin.Context) { - var req models.AuditLogQuery + var req model.AuditLogQuery if err := c.ShouldBindQuery(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } @@ -52,7 +55,7 @@ func (h *AuditHandler) ListAuditLogs(c *gin.Context) { } // 构建查询 - query := h.db.Model(&models.AuditLog{}) + query := h.db.Model(&model.AuditLog{}) if req.Module != "" { query = query.Where("module = ?", req.Module) @@ -73,21 +76,21 @@ func (h *AuditHandler) ListAuditLogs(c *gin.Context) { // 获取总数 var total int64 if err := query.Count(&total).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) return } // 获取列表 - var logs []models.AuditLog + var logs []model.AuditLog if err := query.Order("created_at DESC"). Offset((req.Page - 1) * req.PageSize). Limit(req.PageSize). Find(&logs).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) return } - c.JSON(http.StatusOK, models.AuditLogListResponse{ + c.JSON(http.StatusOK, model.AuditLogListResponse{ List: logs, Total: total, }) @@ -100,22 +103,22 @@ func (h *AuditHandler) ListAuditLogs(c *gin.Context) { // @Accept json // @Produce json // @Param id path int true "日志ID" -// @Success 200 {object} models.AuditLog +// @Success 200 {object} model.AuditLog // @Router /api/v1/audit/logs/{id} [get] func (h *AuditHandler) GetAuditLogDetail(c *gin.Context) { id, err := strconv.ParseUint(c.Param("id"), 10, 64) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的日志ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的日志ID"}) return } - var log models.AuditLog + var log model.AuditLog if err := h.db.First(&log, id).Error; err != nil { if err == gorm.ErrRecordNotFound { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "日志不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "日志不存在"}) return } - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) return } @@ -144,7 +147,7 @@ func (h *AuditHandler) GetAuditModules(c *gin.Context) { {"value": "domain", "label": "域名管理"}, } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: modules}) // Logan.Li + c.JSON(http.StatusOK, model.Response{Code: 200, Data: modules}) // Logan.Li } // GetAuditActions 获取审计操作类型列表 @@ -170,33 +173,12 @@ func (h *AuditHandler) GetAuditActions(c *gin.Context) { {"value": "export", "label": "导出"}, } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: actions}) // Logan.Li + c.JSON(http.StatusOK, model.Response{Code: 200, Data: actions}) // Logan.Li } -// ExportAuditLogs 导出审计日志 -// @Summary 导出审计日志 -// @Description 导出审计日志为Excel或CSV -// @Tags 审计日志 -// @Accept json -// @Produce json -// @Param module query string false "模块" -// @Param action query string false "操作类型" -// @Param username query string false "用户名" -// @Param startTime query string false "开始时间" -// @Param endTime query string false "结束时间" -// @Param format query string false "导出格式" default("csv") Enums(csv, excel) -// @Success 200 {file} binary -// @Router /api/v1/audit/logs/export [get] -func (h *AuditHandler) ExportAuditLogs(c *gin.Context) { - var req models.AuditLogQuery - if err := c.ShouldBindQuery(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) - return - } - - // 构建查询 - query := h.db.Model(&models.AuditLog{}) - +// buildAuditQuery 构建审计日志筛选查询(复用于列表和导出) +func (h *AuditHandler) buildAuditQuery(req model.AuditLogQuery) *gorm.DB { + query := h.db.Model(&model.AuditLog{}) if req.Module != "" { query = query.Where("module = ?", req.Module) } @@ -212,20 +194,94 @@ func (h *AuditHandler) ExportAuditLogs(c *gin.Context) { if req.EndTime != "" { query = query.Where("created_at <= ?", req.EndTime) } + return query +} - // 获取数据 - var logs []models.AuditLog - if err := query.Order("created_at DESC").Find(&logs).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "导出失败"}) +// ExportAuditLogs 导出审计日志 +// @Summary 导出审计日志 +// @Description 导出审计日志为CSV格式(带UTF-8 BOM,Excel可直接打开) +// @Tags 审计日志 +// @Accept json +// @Produce text/csv +// @Param module query string false "模块" +// @Param action query string false "操作类型" +// @Param username query string false "用户名" +// @Param startTime query string false "开始时间" +// @Param endTime query string false "结束时间" +// @Param format query string false "导出格式" default("csv") Enums(csv, json) +// @Success 200 {file} binary +// @Router /api/v1/audit/logs/export [get] +func (h *AuditHandler) ExportAuditLogs(c *gin.Context) { + var req model.AuditLogQuery + _ = c.ShouldBindQuery(&req) + + // 导出最多 10000 条,防止内存溢出 + query := h.buildAuditQuery(req) + + var logs []model.AuditLog + if err := query.Order("created_at DESC").Limit(10000).Find(&logs).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "导出失败: " + err.Error()}) return } - // TODO: 实现CSV/Excel导出功能 - // 这里返回JSON格式的数据,实际项目中应该生成CSV或Excel文件 - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "导出成功", Data: gin.H{ - "count": len(logs), - "logs": logs, - }}) // Logan.Li + format := c.DefaultQuery("format", "csv") + + switch format { + case "json": + // JSON 格式(向后兼容) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "导出成功", Data: gin.H{ + "count": len(logs), + "logs": logs, + }}) // Logan.Li + return + + case "csv": + fallthrough + + default: + // CSV 格式 — 带 UTF-8 BOM 以便 Excel 正确显示中文 + var buf bytes.Buffer + buf.WriteRune('\uFEFF') // UTF-8 BOM + + writer := csv.NewWriter(&buf) + _ = writer.Write([]string{"ID", "时间", "用户", "IP地址", "模块", "操作类型", "资源", "资源ID", "状态", "User-Agent", "耗时(ms)", "错误信息"}) + + for _, l := range logs { + statusStr := "成功" + if l.Status != 0 { + statusStr = "失败" + } + _ = writer.Write([]string{ + fmt.Sprintf("%d", l.ID), + l.CreatedAt.Format("2006-01-02 15:04:05"), + l.Username, + l.IP, + l.Module, + l.Action, + l.Resource, + l.ResourceID, + statusStr, + l.UserAgent, + fmt.Sprintf("%d", l.Duration), + l.Error, + }) + } + writer.Flush() + + // 记录审计日志 + if uid, exists := c.Get("userID"); exists { + if u, ok := uid.(uint); ok { + username, _ := c.Get("username") + un, _ := username.(string) + h.RecordAuditLog(u, un, "audit", "export", fmt.Sprintf("导出审计日志(%d条)", len(logs)), nil) + } + } + + filename := fmt.Sprintf("audit-logs-%s.csv", time.Now().Format("20060102-150405")) + c.Header("Content-Type", "text/csv; charset=utf-8") + c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, filename)) + c.Data(http.StatusOK, "text/csv; charset=utf-8", buf.Bytes()) + } } // GetAuditStatistics 获取审计统计 @@ -250,7 +306,7 @@ func (h *AuditHandler) GetAuditStatistics(c *gin.Context) { Module string `json:"module"` Count int64 `json:"count"` } - h.db.Model(&models.AuditLog{}). + h.db.Model(&model.AuditLog{}). Select("module, COUNT(*) as count"). Where("created_at >= ?", startTime). Group("module"). @@ -261,7 +317,7 @@ func (h *AuditHandler) GetAuditStatistics(c *gin.Context) { Action string `json:"action"` Count int64 `json:"count"` } - h.db.Model(&models.AuditLog{}). + h.db.Model(&model.AuditLog{}). Select("action, COUNT(*) as count"). Where("created_at >= ?", startTime). Group("action"). @@ -272,7 +328,7 @@ func (h *AuditHandler) GetAuditStatistics(c *gin.Context) { Date string `json:"date"` Count int64 `json:"count"` } - h.db.Model(&models.AuditLog{}). + h.db.Model(&model.AuditLog{}). Select("DATE(created_at) as date, COUNT(*) as count"). Where("created_at >= ?", startTime). Group("DATE(created_at)"). @@ -281,16 +337,16 @@ func (h *AuditHandler) GetAuditStatistics(c *gin.Context) { // 总记录数 var totalCount int64 - h.db.Model(&models.AuditLog{}).Count(&totalCount) + h.db.Model(&model.AuditLog{}).Count(&totalCount) // 今日记录数 today := time.Now().Format("2006-01-02") var todayCount int64 - h.db.Model(&models.AuditLog{}). + h.db.Model(&model.AuditLog{}). Where("DATE(created_at) = ?", today). Count(&todayCount) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "total_count": totalCount, "today_count": todayCount, "module_stats": moduleStats, @@ -314,21 +370,21 @@ func (h *AuditHandler) ClearAuditLogs(c *gin.Context) { } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的请求参数"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的请求参数"}) return } // 解析日期 beforeDate, err := time.Parse("2006-01-02", req.BeforeDate) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的日期格式"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的日期格式"}) return } // 删除指定日期之前的日志 - result := h.db.Where("created_at < ?", beforeDate).Delete(&models.AuditLog{}) + result := h.db.Where("created_at < ?", beforeDate).Delete(&model.AuditLog{}) if result.Error != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "清理失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "清理失败"}) return } @@ -340,7 +396,7 @@ func (h *AuditHandler) ClearAuditLogs(c *gin.Context) { "deleted": result.RowsAffected, }) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "清理成功", Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "清理成功", Data: gin.H{ "deleted": result.RowsAffected, }}) // Logan.Li } @@ -348,7 +404,7 @@ func (h *AuditHandler) ClearAuditLogs(c *gin.Context) { // RecordAuditLog 记录审计日志 func (h *AuditHandler) RecordAuditLog(userID uint, username, module, action, description string, details interface{}) { uid := userID - log := models.AuditLog{ + log := model.AuditLog{ UserID: &uid, Username: username, Module: module, diff --git a/backend/controller/audit_hub.go b/backend/controller/audit_hub.go new file mode 100644 index 0000000..77bc939 --- /dev/null +++ b/backend/controller/audit_hub.go @@ -0,0 +1,130 @@ +// 终端审计实时流 Hub — 在线会话内容广播给审计查看者 // Logan.Li +package controller + +import ( + "log" + "net/http" + "sync" + + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" +) + +// AuditHub 终端审计流中心 — 管理所有活跃会话的审计订阅者 +type AuditHub struct { + mu sync.RWMutex + watchers map[uint]map[chan []byte]struct{} // sessionID -> set of watcher channels +} + +// NewAuditHub 创建审计 Hub +func NewAuditHub() *AuditHub { + return &AuditHub{ + watchers: make(map[uint]map[chan []byte]struct{}), + } +} + +// Subscribe 订阅某个会话的实时输出 +func (h *AuditHub) Subscribe(sessionID uint) chan []byte { + ch := make(chan []byte, 256) + h.mu.Lock() + defer h.mu.Unlock() + if h.watchers[sessionID] == nil { + h.watchers[sessionID] = make(map[chan []byte]struct{}) + } + h.watchers[sessionID][ch] = struct{}{} + return ch +} + +// Unsubscribe 取消订阅 +func (h *AuditHub) Unsubscribe(sessionID uint, ch chan []byte) { + h.mu.Lock() + defer h.mu.Unlock() + if watchers, ok := h.watchers[sessionID]; ok { + delete(watchers, ch) + close(ch) + if len(watchers) == 0 { + delete(h.watchers, sessionID) + } + } +} + +// Broadcast 向所有订阅者广播终端输出数据(非阻塞) +func (h *AuditHub) Broadcast(sessionID uint, data []byte) { + h.mu.RLock() + watchers, ok := h.watchers[sessionID] + h.mu.RUnlock() + if !ok || len(watchers) == 0 { + return + } + for ch := range watchers { + select { + case ch <- data: + default: + } + } +} + +// Cleanup 清理某个会话的所有订阅者 +func (h *AuditHub) Cleanup(sessionID uint) { + h.mu.Lock() + defer h.mu.Unlock() + if watchers, ok := h.watchers[sessionID]; ok { + for ch := range watchers { + close(ch) + } + delete(h.watchers, sessionID) + } +} + +var auditUpgrader = websocket.Upgrader{ + CheckOrigin: func(r *http.Request) bool { return true }, + ReadBufferSize: 1024, + WriteBufferSize: 1024, +} + +// ServeAuditStream 处理 /ws/audit/:sessionId WebSocket — 实时推送终端输出 +func (h *AuditHub) ServeAuditStream(c *gin.Context, sessionID uint, historyData string, sessionInfo map[string]interface{}) { + conn, err := auditUpgrader.Upgrade(c.Writer, c.Request, nil) + if err != nil { + log.Printf("[AuditStream] WS 升级失败 session=%d: %v", sessionID, err) + return + } + defer conn.Close() + + // 发送会话元信息 + conn.WriteJSON(map[string]interface{}{ + "type": "session_info", + "payload": sessionInfo, + }) + + // 发送历史数据(已录制的输出) + if historyData != "" { + conn.WriteJSON(map[string]interface{}{ + "type": "history", + "data": historyData, + }) + } + + // 订阅实时流 + ch := h.Subscribe(sessionID) + defer h.Unsubscribe(sessionID, ch) + + // goroutine 读取关闭信号 + go func() { + for { + if _, _, err := conn.ReadMessage(); err != nil { + break + } + } + }() + + // 推送实时数据 + for data := range ch { + if err := conn.WriteJSON(map[string]interface{}{ + "type": "output", + "data": string(data), + }); err != nil { + break + } + } +} diff --git a/backend/internal/api/handlers/automation.go b/backend/controller/automation.go similarity index 99% rename from backend/internal/api/handlers/automation.go rename to backend/controller/automation.go index d5fb0f8..fc68c0e 100644 --- a/backend/internal/api/handlers/automation.go +++ b/backend/controller/automation.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "bytes" diff --git a/backend/internal/api/handlers/automation_cron.go b/backend/controller/automation_cron.go similarity index 78% rename from backend/internal/api/handlers/automation_cron.go rename to backend/controller/automation_cron.go index 6ab19d7..1ad6a9a 100644 --- a/backend/internal/api/handlers/automation_cron.go +++ b/backend/controller/automation_cron.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "fmt" @@ -6,7 +6,7 @@ import ( "strconv" "time" - "ezops/internal/models" + "ezops/model" "ezops/pkg/remoteexec" "github.com/gin-gonic/gin" @@ -20,22 +20,22 @@ import ( // @Security Bearer // @Param page query int false "页码" // @Param page_size query int false "每页数量" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /cron-jobs [get] func (h *AutomationHandler) ListCronJobs(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) var total int64 - h.db.Model(&models.CronJob{}).Count(&total) + h.db.Model(&model.CronJob{}).Count(&total) - var jobs []models.CronJob + var jobs []model.CronJob h.db.Preload("Script").Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&jobs) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: jobs, Total: total, }, @@ -49,21 +49,21 @@ func (h *AutomationHandler) ListCronJobs(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "任务ID" -// @Success 200 {object} models.Response{data=models.CronJob} +// @Success 200 {object} model.Response{data=model.CronJob} // @Router /cron-jobs/{id} [get] func (h *AutomationHandler) GetCronJob(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var job models.CronJob + var job model.CronJob if err := h.db.Preload("Script").First(&job, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "定时任务不存在", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: job, @@ -77,20 +77,20 @@ func (h *AutomationHandler) GetCronJob(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateCronJobRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.CronJob} +// @Param request body model.CreateCronJobRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.CronJob} // @Router /cron-jobs [post] func (h *AutomationHandler) CreateCronJob(c *gin.Context) { - var req models.CreateCronJobRequest + var req model.CreateCronJobRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - job := models.CronJob{ + job := model.CronJob{ Name: req.Name, Description: req.Description, CronExpr: req.CronExpr, @@ -111,14 +111,14 @@ func (h *AutomationHandler) CreateCronJob(c *gin.Context) { } if err := h.db.Create(&job).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: job, @@ -133,24 +133,24 @@ func (h *AutomationHandler) CreateCronJob(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "任务ID" -// @Param request body models.CreateCronJobRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.CronJob} +// @Param request body model.CreateCronJobRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.CronJob} // @Router /cron-jobs/{id} [put] func (h *AutomationHandler) UpdateCronJob(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.CreateCronJobRequest + var req model.CreateCronJobRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var job models.CronJob + var job model.CronJob if err := h.db.First(&job, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "定时任务不存在", }) @@ -170,7 +170,7 @@ func (h *AutomationHandler) UpdateCronJob(c *gin.Context) { } if err := h.db.Model(&job).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -179,7 +179,7 @@ func (h *AutomationHandler) UpdateCronJob(c *gin.Context) { h.db.Preload("Script").First(&job, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: job, @@ -193,20 +193,20 @@ func (h *AutomationHandler) UpdateCronJob(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "任务ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /cron-jobs/{id} [delete] func (h *AutomationHandler) DeleteCronJob(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.CronJob{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.CronJob{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -219,28 +219,28 @@ func (h *AutomationHandler) DeleteCronJob(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.IDsRequest true "删除请求" -// @Success 200 {object} models.Response +// @Param request body model.IDsRequest true "删除请求" +// @Success 200 {object} model.Response // @Router /cron-jobs/batch-delete [delete] func (h *AutomationHandler) BatchDeleteCronJobs(c *gin.Context) { - var req models.IDsRequest + var req model.IDsRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误", }) return } - if err := h.db.Delete(&models.CronJob{}, req.IDs).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.CronJob{}, req.IDs).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -253,14 +253,14 @@ func (h *AutomationHandler) BatchDeleteCronJobs(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "任务ID" -// @Success 200 {object} models.Response{data=models.CronJob} +// @Success 200 {object} model.Response{data=model.CronJob} // @Router /cron-jobs/{id}/toggle [post] func (h *AutomationHandler) ToggleCronJob(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var job models.CronJob + var job model.CronJob if err := h.db.First(&job, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "定时任务不存在", }) @@ -269,14 +269,14 @@ func (h *AutomationHandler) ToggleCronJob(c *gin.Context) { job.Enabled = !job.Enabled if err := h.db.Save(&job).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "操作失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "操作成功", Data: job, @@ -290,14 +290,14 @@ func (h *AutomationHandler) ToggleCronJob(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "任务ID" -// @Success 200 {object} models.Response{data=models.TaskExecution} +// @Success 200 {object} model.Response{data=model.TaskExecution} // @Router /cron-jobs/{id}/execute [post] func (h *AutomationHandler) ExecuteCronJob(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var job models.CronJob + var job model.CronJob if err := h.db.First(&job, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "定时任务不存在", }) @@ -311,7 +311,7 @@ func (h *AutomationHandler) ExecuteCronJob(c *gin.Context) { scriptType = "shell" // one-liner commands run via bash } if job.Type == "script" && job.ScriptID != nil { - var script models.Script + var script model.Script if err := h.db.First(&script, *job.ScriptID).Error; err == nil { content = script.Content scriptType = script.Type @@ -320,7 +320,7 @@ func (h *AutomationHandler) ExecuteCronJob(c *gin.Context) { } now := time.Now() - execution := models.TaskExecution{ + execution := model.TaskExecution{ TaskType: "cron", TaskID: uint(id), TaskName: job.Name, @@ -330,7 +330,7 @@ func (h *AutomationHandler) ExecuteCronJob(c *gin.Context) { StartedAt: &now, } if err := h.db.Create(&execution).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建执行记录失败", }) @@ -403,7 +403,7 @@ func (h *AutomationHandler) ExecuteCronJob(c *gin.Context) { if status == "failed" { msg = "执行失败" } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: msg, Data: execution, diff --git a/backend/internal/api/handlers/automation_script.go b/backend/controller/automation_script.go similarity index 73% rename from backend/internal/api/handlers/automation_script.go rename to backend/controller/automation_script.go index ffa6029..8e4352d 100644 --- a/backend/internal/api/handlers/automation_script.go +++ b/backend/controller/automation_script.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "net/http" "strconv" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -18,22 +18,22 @@ import ( // @Security Bearer // @Param page query int false "页码" // @Param page_size query int false "每页数量" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /scripts [get] func (h *AutomationHandler) ListScripts(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) var total int64 - h.db.Model(&models.Script{}).Count(&total) + h.db.Model(&model.Script{}).Count(&total) - var scripts []models.Script + var scripts []model.Script h.db.Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&scripts) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: scripts, Total: total, }, @@ -47,21 +47,21 @@ func (h *AutomationHandler) ListScripts(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "脚本ID" -// @Success 200 {object} models.Response{data=models.Script} +// @Success 200 {object} model.Response{data=model.Script} // @Router /scripts/{id} [get] func (h *AutomationHandler) GetScript(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var script models.Script + var script model.Script if err := h.db.First(&script, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "脚本不存在", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: script, @@ -75,20 +75,20 @@ func (h *AutomationHandler) GetScript(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateScriptRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.Script} +// @Param request body model.CreateScriptRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.Script} // @Router /scripts [post] func (h *AutomationHandler) CreateScript(c *gin.Context) { - var req models.CreateScriptRequest + var req model.CreateScriptRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - script := models.Script{ + script := model.Script{ Name: req.Name, Code: req.Code, Description: req.Description, @@ -106,14 +106,14 @@ func (h *AutomationHandler) CreateScript(c *gin.Context) { } if err := h.db.Create(&script).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: script, @@ -128,24 +128,24 @@ func (h *AutomationHandler) CreateScript(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "脚本ID" -// @Param request body models.CreateScriptRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.Script} +// @Param request body model.CreateScriptRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.Script} // @Router /scripts/{id} [put] func (h *AutomationHandler) UpdateScript(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.CreateScriptRequest + var req model.CreateScriptRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var script models.Script + var script model.Script if err := h.db.First(&script, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "脚本不存在", }) @@ -163,7 +163,7 @@ func (h *AutomationHandler) UpdateScript(c *gin.Context) { } if err := h.db.Model(&script).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -172,7 +172,7 @@ func (h *AutomationHandler) UpdateScript(c *gin.Context) { h.db.First(&script, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: script, @@ -186,20 +186,20 @@ func (h *AutomationHandler) UpdateScript(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "脚本ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /scripts/{id} [delete] func (h *AutomationHandler) DeleteScript(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.Script{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.Script{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -212,28 +212,28 @@ func (h *AutomationHandler) DeleteScript(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.IDsRequest true "删除请求" -// @Success 200 {object} models.Response +// @Param request body model.IDsRequest true "删除请求" +// @Success 200 {object} model.Response // @Router /scripts/batch-delete [post] func (h *AutomationHandler) BatchDeleteScripts(c *gin.Context) { - var req models.IDsRequest + var req model.IDsRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误", }) return } - if err := h.db.Delete(&models.Script{}, req.IDs).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.Script{}, req.IDs).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -247,15 +247,15 @@ func (h *AutomationHandler) BatchDeleteScripts(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "脚本ID" -// @Param request body models.ExecuteScriptRequest true "执行请求" -// @Success 200 {object} models.Response{data=models.TaskExecution} +// @Param request body model.ExecuteScriptRequest true "执行请求" +// @Success 200 {object} model.Response{data=model.TaskExecution} // @Router /scripts/{id}/execute [post] func (h *AutomationHandler) ExecuteScript(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var script models.Script + var script model.Script if err := h.db.First(&script, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "脚本不存在", }) @@ -263,11 +263,11 @@ func (h *AutomationHandler) ExecuteScript(c *gin.Context) { } // The request body is optional — when omitted we execute locally. - var req models.ExecuteScriptRequest + var req model.ExecuteScriptRequest _ = c.ShouldBindJSON(&req) now := time.Now() - execution := models.TaskExecution{ + execution := model.TaskExecution{ TaskType: "script", TaskID: uint(id), TaskName: script.Name, @@ -276,7 +276,7 @@ func (h *AutomationHandler) ExecuteScript(c *gin.Context) { StartedAt: &now, } if err := h.db.Create(&execution).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建执行记录失败", }) @@ -308,7 +308,7 @@ func (h *AutomationHandler) ExecuteScript(c *gin.Context) { if status == "failed" { msg = "执行失败" } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: msg, Data: execution, @@ -325,13 +325,13 @@ func (h *AutomationHandler) ExecuteScript(c *gin.Context) { // @Param page_size query int false "每页数量" // @Param task_type query string false "任务类型 (cron/script)" // @Param task_id query string false "任务ID" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /task-executions [get] func (h *AutomationHandler) ListExecutions(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) - db := h.db.Model(&models.TaskExecution{}) + db := h.db.Model(&model.TaskExecution{}) if taskType := c.Query("task_type"); taskType != "" { db = db.Where("task_type = ?", taskType) } @@ -342,13 +342,13 @@ func (h *AutomationHandler) ListExecutions(c *gin.Context) { var total int64 db.Count(&total) - var execs []models.TaskExecution + var execs []model.TaskExecution db.Order("created_at DESC").Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&execs) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: execs, Total: total, }, diff --git a/backend/internal/api/handlers/billing.go b/backend/controller/billing.go similarity index 74% rename from backend/internal/api/handlers/billing.go rename to backend/controller/billing.go index a179a8f..d3b8073 100644 --- a/backend/internal/api/handlers/billing.go +++ b/backend/controller/billing.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "fmt" @@ -6,7 +6,7 @@ import ( "sort" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -23,9 +23,9 @@ func NewBillingHandler(db *gorm.DB) *BillingHandler { // ListBillings 获取账单列表 func (h *BillingHandler) ListBillings(c *gin.Context) { - var billings []models.CloudBilling + var billings []model.CloudBilling - query := h.db.Model(&models.CloudBilling{}) + query := h.db.Model(&model.CloudBilling{}) // 筛选 if provider := c.Query("provider"); provider != "" { @@ -64,10 +64,10 @@ func (h *BillingHandler) ListBillings(c *gin.Context) { query.Count(&total) query.Offset((page - 1) * pageSize).Limit(pageSize).Find(&billings) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: billings, Total: total, }, @@ -76,13 +76,13 @@ func (h *BillingHandler) ListBillings(c *gin.Context) { // CreateBilling 创建账单记录 func (h *BillingHandler) CreateBilling(c *gin.Context) { - var req models.CreateBillingRequest + var req model.CreateBillingRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - billing := models.CloudBilling{ + billing := model.CloudBilling{ CloudAccountID: req.CloudAccountID, AccountName: req.AccountName, Provider: req.Provider, @@ -98,11 +98,11 @@ func (h *BillingHandler) CreateBilling(c *gin.Context) { } if err := h.db.Create(&billing).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: billing, @@ -112,16 +112,16 @@ func (h *BillingHandler) CreateBilling(c *gin.Context) { // BatchCreateBillings 批量创建账单 func (h *BillingHandler) BatchCreateBillings(c *gin.Context) { var req struct { - Records []models.CreateBillingRequest `json:"records" binding:"required"` + Records []model.CreateBillingRequest `json:"records" binding:"required"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } created := 0 for _, r := range req.Records { - billing := models.CloudBilling{ + billing := model.CloudBilling{ CloudAccountID: r.CloudAccountID, AccountName: r.AccountName, Provider: r.Provider, @@ -140,7 +140,7 @@ func (h *BillingHandler) BatchCreateBillings(c *gin.Context) { } } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: fmt.Sprintf("成功导入 %d 条记录", created), Data: gin.H{"created": created, "total": len(req.Records)}, @@ -150,11 +150,11 @@ func (h *BillingHandler) BatchCreateBillings(c *gin.Context) { // DeleteBilling 删除账单记录 func (h *BillingHandler) DeleteBilling(c *gin.Context) { id := c.Param("id") - if err := h.db.Delete(&models.CloudBilling{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if err := h.db.Delete(&model.CloudBilling{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // GetBillingStats 获取账单统计 @@ -165,26 +165,26 @@ func (h *BillingHandler) GetBillingStats(c *gin.Context) { monthStart := now.Format("2006-01") + "-01" yearStart := fmt.Sprintf("%d-01-01", now.Year()) - stats := models.BillingStats{ - MonthTrend: []models.DailyCost{}, - ProviderDist: []models.ProviderCost{}, - Alerts: []models.BillingAlert{}, + stats := model.BillingStats{ + MonthTrend: []model.DailyCost{}, + ProviderDist: []model.ProviderCost{}, + Alerts: []model.BillingAlert{}, } // 今日成本 - h.db.Model(&models.CloudBilling{}).Where("billing_date = ?", today). + h.db.Model(&model.CloudBilling{}).Where("billing_date = ?", today). Select("COALESCE(SUM(cost), 0)").Scan(&stats.TodayCost) // 昨日成本 - h.db.Model(&models.CloudBilling{}).Where("billing_date = ?", yesterday). + h.db.Model(&model.CloudBilling{}).Where("billing_date = ?", yesterday). Select("COALESCE(SUM(cost), 0)").Scan(&stats.YesterdayCost) // 本月成本 - h.db.Model(&models.CloudBilling{}).Where("billing_date >= ?", monthStart). + h.db.Model(&model.CloudBilling{}).Where("billing_date >= ?", monthStart). Select("COALESCE(SUM(cost), 0)").Scan(&stats.MonthCost) // 本年成本 - h.db.Model(&models.CloudBilling{}).Where("billing_date >= ?", yearStart). + h.db.Model(&model.CloudBilling{}).Where("billing_date >= ?", yearStart). Select("COALESCE(SUM(cost), 0)").Scan(&stats.YearCost) // 近30天趋势 @@ -193,7 +193,7 @@ func (h *BillingHandler) GetBillingStats(c *gin.Context) { Total float64 } var trends []dayCost - h.db.Model(&models.CloudBilling{}). + h.db.Model(&model.CloudBilling{}). Select("billing_date, SUM(cost) as total"). Where("billing_date >= ?", now.AddDate(0, 0, -29).Format("2006-01-02")). Group("billing_date"). @@ -201,7 +201,7 @@ func (h *BillingHandler) GetBillingStats(c *gin.Context) { Scan(&trends) for _, t := range trends { - stats.MonthTrend = append(stats.MonthTrend, models.DailyCost{Date: t.BillingDate, Cost: t.Total}) + stats.MonthTrend = append(stats.MonthTrend, model.DailyCost{Date: t.BillingDate, Cost: t.Total}) } // 本月厂商成本分布 @@ -210,7 +210,7 @@ func (h *BillingHandler) GetBillingStats(c *gin.Context) { Total float64 } var provCosts []provCost - h.db.Model(&models.CloudBilling{}). + h.db.Model(&model.CloudBilling{}). Select("provider, SUM(cost) as total"). Where("billing_date >= ?", monthStart). Group("provider"). @@ -225,7 +225,7 @@ func (h *BillingHandler) GetBillingStats(c *gin.Context) { if totalProviderCost > 0 { percent = p.Total / totalProviderCost * 100 } - stats.ProviderDist = append(stats.ProviderDist, models.ProviderCost{ + stats.ProviderDist = append(stats.ProviderDist, model.ProviderCost{ Provider: p.Provider, Cost: p.Total, Percent: percent, @@ -238,7 +238,7 @@ func (h *BillingHandler) GetBillingStats(c *gin.Context) { // 检查预警规则 h.checkBillingAlerts(&stats, now) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: stats, @@ -246,8 +246,8 @@ func (h *BillingHandler) GetBillingStats(c *gin.Context) { } // checkBillingAlerts 检查预警规则是否触发 -func (h *BillingHandler) checkBillingAlerts(stats *models.BillingStats, now time.Time) { - var rules []models.BillingAlertRule +func (h *BillingHandler) checkBillingAlerts(stats *model.BillingStats, now time.Time) { + var rules []model.BillingAlertRule h.db.Where("enabled = ?", true).Find(&rules) for _, rule := range rules { @@ -255,7 +255,7 @@ func (h *BillingHandler) checkBillingAlerts(stats *models.BillingStats, now time if rule.Metric == "daily" { // 查今日该厂商/账号的成本 - q := h.db.Model(&models.CloudBilling{}).Where("billing_date = ?", now.Format("2006-01-02")) + q := h.db.Model(&model.CloudBilling{}).Where("billing_date = ?", now.Format("2006-01-02")) if rule.Provider != "" { q = q.Where("provider = ?", rule.Provider) } @@ -265,7 +265,7 @@ func (h *BillingHandler) checkBillingAlerts(stats *models.BillingStats, now time q.Select("COALESCE(SUM(cost), 0)").Scan(¤t) } else { // monthly - 本月累计 - q := h.db.Model(&models.CloudBilling{}).Where("billing_date >= ?", now.Format("2006-01")+"-01") + q := h.db.Model(&model.CloudBilling{}).Where("billing_date >= ?", now.Format("2006-01")+"-01") if rule.Provider != "" { q = q.Where("provider = ?", rule.Provider) } @@ -293,7 +293,7 @@ func (h *BillingHandler) checkBillingAlerts(stats *models.BillingStats, now time if providerLabel == "" { providerLabel = "全部" } - stats.Alerts = append(stats.Alerts, models.BillingAlert{ + stats.Alerts = append(stats.Alerts, model.BillingAlert{ RuleID: rule.ID, RuleName: rule.Name, Provider: providerLabel, diff --git a/backend/internal/api/handlers/billing_alert.go b/backend/controller/billing_alert.go similarity index 70% rename from backend/internal/api/handlers/billing_alert.go rename to backend/controller/billing_alert.go index 7493972..954c9bb 100644 --- a/backend/internal/api/handlers/billing_alert.go +++ b/backend/controller/billing_alert.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" "strings" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -14,13 +14,13 @@ import ( // ListAlertRules 获取预警规则列表 // Logan.Li func (h *BillingHandler) ListAlertRules(c *gin.Context) { - var rules []models.BillingAlertRule + var rules []model.BillingAlertRule h.db.Order("created_at DESC").Find(&rules) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: rules, Total: int64(len(rules)), }, @@ -29,13 +29,13 @@ func (h *BillingHandler) ListAlertRules(c *gin.Context) { // CreateAlertRule 创建预警规则 // Logan.Li func (h *BillingHandler) CreateAlertRule(c *gin.Context) { - var req models.CreateBillingAlertRequest + var req model.CreateBillingAlertRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - rule := models.BillingAlertRule{ + rule := model.BillingAlertRule{ Name: req.Name, Provider: req.Provider, CloudAccountID: req.CloudAccountID, @@ -52,11 +52,11 @@ func (h *BillingHandler) CreateAlertRule(c *gin.Context) { } if err := h.db.Create(&rule).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败"}) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: rule, @@ -66,15 +66,15 @@ func (h *BillingHandler) CreateAlertRule(c *gin.Context) { // UpdateAlertRule 更新预警规则 // Logan.Li func (h *BillingHandler) UpdateAlertRule(c *gin.Context) { id := c.Param("id") - var rule models.BillingAlertRule + var rule model.BillingAlertRule if err := h.db.First(&rule, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "规则不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "规则不存在"}) return } - var req models.CreateBillingAlertRequest + var req model.CreateBillingAlertRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } @@ -94,7 +94,7 @@ func (h *BillingHandler) UpdateAlertRule(c *gin.Context) { h.db.Save(&rule) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: rule, @@ -104,19 +104,19 @@ func (h *BillingHandler) UpdateAlertRule(c *gin.Context) { // DeleteAlertRule 删除预警规则 // Logan.Li func (h *BillingHandler) DeleteAlertRule(c *gin.Context) { id := c.Param("id") - if err := h.db.Delete(&models.BillingAlertRule{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if err := h.db.Delete(&model.BillingAlertRule{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // ToggleAlertRule 启用/禁用预警规则(服务端自动翻转) // Logan.Li func (h *BillingHandler) ToggleAlertRule(c *gin.Context) { id := c.Param("id") - var rule models.BillingAlertRule + var rule model.BillingAlertRule if err := h.db.First(&rule, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "规则不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "规则不存在"}) return } @@ -128,7 +128,7 @@ func (h *BillingHandler) ToggleAlertRule(c *gin.Context) { status = "已禁用" } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: status, Data: rule, @@ -138,14 +138,14 @@ func (h *BillingHandler) ToggleAlertRule(c *gin.Context) { // GetProviderOptions 获取厂商选项(用于筛选下拉) // Logan.Li func (h *BillingHandler) GetProviderOptions(c *gin.Context) { var providers []string - h.db.Model(&models.CloudBilling{}).Distinct("provider").Where("provider != ''").Pluck("provider", &providers) + h.db.Model(&model.CloudBilling{}).Distinct("provider").Where("provider != ''").Pluck("provider", &providers) result := make([]gin.H, 0, len(providers)) for _, p := range providers { result = append(result, gin.H{"value": p, "label": formatProvider(p)}) } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: result, diff --git a/backend/internal/api/handlers/cloud_accounts.go b/backend/controller/cloud_accounts.go similarity index 80% rename from backend/internal/api/handlers/cloud_accounts.go rename to backend/controller/cloud_accounts.go index 7e603e4..c67c24b 100644 --- a/backend/internal/api/handlers/cloud_accounts.go +++ b/backend/controller/cloud_accounts.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "net/http" "strconv" "strings" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -27,16 +27,16 @@ func NewCloudAccountHandler(db *gorm.DB) *CloudAccountHandler { // @Tags 云账号 // @Produce json // @Security Bearer -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /cloud-accounts [get] func (h *CloudAccountHandler) ListCloudAccounts(c *gin.Context) { - var accounts []models.CloudAccount + var accounts []model.CloudAccount h.db.Find(&accounts) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: accounts, Total: int64(len(accounts)), }, @@ -61,12 +61,12 @@ type createCloudAccountRequest struct { // @Produce json // @Security Bearer // @Param request body createCloudAccountRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.CloudAccount} +// @Success 200 {object} model.Response{data=model.CloudAccount} // @Router /cloud-accounts [post] func (h *CloudAccountHandler) CreateCloudAccount(c *gin.Context) { var req createCloudAccountRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) @@ -74,7 +74,7 @@ func (h *CloudAccountHandler) CreateCloudAccount(c *gin.Context) { } if strings.TrimSpace(req.Name) == "" || strings.TrimSpace(req.Provider) == "" { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "账号名称和云平台不能为空", }) @@ -86,7 +86,7 @@ func (h *CloudAccountHandler) CreateCloudAccount(c *gin.Context) { status = "active" } - account := models.CloudAccount{ + account := model.CloudAccount{ Name: strings.TrimSpace(req.Name), Provider: strings.TrimSpace(req.Provider), AccessKey: req.AccessKey, @@ -96,14 +96,14 @@ func (h *CloudAccountHandler) CreateCloudAccount(c *gin.Context) { } if err := h.db.Create(&account).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: account, @@ -119,22 +119,22 @@ func (h *CloudAccountHandler) CreateCloudAccount(c *gin.Context) { // @Security Bearer // @Param id path int true "云账号ID" // @Param request body createCloudAccountRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.CloudAccount} +// @Success 200 {object} model.Response{data=model.CloudAccount} // @Router /cloud-accounts/{id} [put] func (h *CloudAccountHandler) UpdateCloudAccount(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) var req createCloudAccountRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var account models.CloudAccount + var account model.CloudAccount if err := h.db.First(&account, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "云账号不存在", }) @@ -160,14 +160,14 @@ func (h *CloudAccountHandler) UpdateCloudAccount(c *gin.Context) { account.MonthlyCost = req.MonthlyCost if err := h.db.Save(&account).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: account, @@ -181,20 +181,20 @@ func (h *CloudAccountHandler) UpdateCloudAccount(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "云账号ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /cloud-accounts/{id} [delete] func (h *CloudAccountHandler) DeleteCloudAccount(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.CloudAccount{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.CloudAccount{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) diff --git a/backend/internal/api/handlers/cloud_domain.go b/backend/controller/cloud_domain.go similarity index 80% rename from backend/internal/api/handlers/cloud_domain.go rename to backend/controller/cloud_domain.go index 1b7e252..9084537 100644 --- a/backend/internal/api/handlers/cloud_domain.go +++ b/backend/controller/cloud_domain.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "net/http" @@ -6,7 +6,7 @@ import ( "strings" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -31,13 +31,13 @@ func NewDomainHandler(db *gorm.DB) *DomainHandler { // @Param page query int false "页码" // @Param page_size query int false "每页数量" // @Param keyword query string false "搜索关键词" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /domains [get] func (h *DomainHandler) ListDomains(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) - db := h.db.Model(&models.Domain{}) + db := h.db.Model(&model.Domain{}) if query.Keyword != "" { db = db.Where("name LIKE ?", "%"+query.Keyword+"%") } @@ -45,13 +45,13 @@ func (h *DomainHandler) ListDomains(c *gin.Context) { var total int64 db.Count(&total) - var domains []models.Domain + var domains []model.Domain db.Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&domains) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: domains, Total: total, }, @@ -65,13 +65,13 @@ func (h *DomainHandler) ListDomains(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.Domain true "创建请求" -// @Success 200 {object} models.Response{data=models.Domain} +// @Param request body model.Domain true "创建请求" +// @Success 200 {object} model.Response{data=model.Domain} // @Router /domains [post] func (h *DomainHandler) CreateDomain(c *gin.Context) { var req updateDomainRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) @@ -79,7 +79,7 @@ func (h *DomainHandler) CreateDomain(c *gin.Context) { } if strings.TrimSpace(req.Name) == "" { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "域名不能为空", }) @@ -91,7 +91,7 @@ func (h *DomainHandler) CreateDomain(c *gin.Context) { status = "active" } - domain := models.Domain{ + domain := model.Domain{ Name: strings.TrimSpace(req.Name), Registrar: req.Registrar, Status: status, @@ -103,14 +103,14 @@ func (h *DomainHandler) CreateDomain(c *gin.Context) { } if err := h.db.Create(&domain).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: domain, @@ -149,20 +149,20 @@ func parseDateStr(s string) *time.Time { // @Produce json // @Security Bearer // @Param id path int true "域名ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /domains/{id} [delete] func (h *DomainHandler) DeleteDomain(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.Domain{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.Domain{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -177,22 +177,22 @@ func (h *DomainHandler) DeleteDomain(c *gin.Context) { // @Security Bearer // @Param id path int true "域名ID" // @Param request body updateDomainRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.Domain} +// @Success 200 {object} model.Response{data=model.Domain} // @Router /domains/{id} [put] func (h *DomainHandler) UpdateDomain(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) var req updateDomainRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var domain models.Domain + var domain model.Domain if err := h.db.First(&domain, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "域名不存在", }) @@ -214,14 +214,14 @@ func (h *DomainHandler) UpdateDomain(c *gin.Context) { domain.SSLExpireDate = parseDateStr(req.SSLExpireDate) if err := h.db.Save(&domain).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: domain, diff --git a/backend/internal/api/handlers/cloud_platform.go b/backend/controller/cloud_platform.go similarity index 67% rename from backend/internal/api/handlers/cloud_platform.go rename to backend/controller/cloud_platform.go index 1d55cf9..712a5b3 100644 --- a/backend/internal/api/handlers/cloud_platform.go +++ b/backend/controller/cloud_platform.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "net/http" "strconv" "strings" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -34,13 +34,13 @@ type platformRequest struct { // ListPlatforms 获取云平台列表 func (h *PlatformHandler) ListPlatforms(c *gin.Context) { - var platforms []models.Cloud + var platforms []model.Cloud h.db.Find(&platforms) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: platforms, Total: int64(len(platforms)), }, @@ -51,11 +51,11 @@ func (h *PlatformHandler) ListPlatforms(c *gin.Context) { func (h *PlatformHandler) CreatePlatform(c *gin.Context) { var req platformRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } if strings.TrimSpace(req.Name) == "" || strings.TrimSpace(req.Code) == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "平台名称和编码不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "平台名称和编码不能为空"}) return } @@ -68,7 +68,7 @@ func (h *PlatformHandler) CreatePlatform(c *gin.Context) { status = "active" } - platform := models.Cloud{ + platform := model.Cloud{ Name: strings.TrimSpace(req.Name), Code: strings.TrimSpace(req.Code), Type: cloudType, @@ -77,10 +77,10 @@ func (h *PlatformHandler) CreatePlatform(c *gin.Context) { Description: req.Description, } if err := h.db.Create(&platform).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败,编码可能已存在"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败,编码可能已存在"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: platform}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "创建成功", Data: platform}) } // UpdatePlatform 更新云平台 @@ -88,13 +88,13 @@ func (h *PlatformHandler) UpdatePlatform(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) var req platformRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } - var platform models.Cloud + var platform model.Cloud if err := h.db.First(&platform, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "云平台不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "云平台不存在"}) return } @@ -114,19 +114,19 @@ func (h *PlatformHandler) UpdatePlatform(c *gin.Context) { platform.Description = req.Description if err := h.db.Save(&platform).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "更新失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: platform}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功", Data: platform}) } // DeletePlatform 删除云平台 func (h *PlatformHandler) DeletePlatform(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.Cloud{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if err := h.db.Delete(&model.Cloud{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } diff --git a/backend/internal/api/handlers/cloud_region.go b/backend/controller/cloud_region.go similarity index 61% rename from backend/internal/api/handlers/cloud_region.go rename to backend/controller/cloud_region.go index 7d3ba78..63bfcc7 100644 --- a/backend/internal/api/handlers/cloud_region.go +++ b/backend/controller/cloud_region.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "net/http" "strconv" "strings" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -34,13 +34,13 @@ type regionRequest struct { // ListRegions 获取区域列表 func (h *RegionHandler) ListRegions(c *gin.Context) { - var regions []models.Region + var regions []model.Region h.db.Find(®ions) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: regions, Total: int64(len(regions)), }, @@ -51,11 +51,11 @@ func (h *RegionHandler) ListRegions(c *gin.Context) { func (h *RegionHandler) CreateRegion(c *gin.Context) { var req regionRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } if strings.TrimSpace(req.Name) == "" || strings.TrimSpace(req.Code) == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "区域名称和编码不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "区域名称和编码不能为空"}) return } @@ -64,7 +64,7 @@ func (h *RegionHandler) CreateRegion(c *gin.Context) { status = "active" } - region := models.Region{ + region := model.Region{ Name: strings.TrimSpace(req.Name), Code: strings.TrimSpace(req.Code), Provider: strings.TrimSpace(req.Provider), @@ -73,10 +73,10 @@ func (h *RegionHandler) CreateRegion(c *gin.Context) { Endpoint: req.Endpoint, } if err := h.db.Create(®ion).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败,编码可能已存在"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败,编码可能已存在"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: region}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "创建成功", Data: region}) } // UpdateRegion 更新区域 @@ -84,13 +84,13 @@ func (h *RegionHandler) UpdateRegion(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) var req regionRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } - var region models.Region + var region model.Region if err := h.db.First(®ion, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "区域不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "区域不存在"}) return } @@ -110,20 +110,20 @@ func (h *RegionHandler) UpdateRegion(c *gin.Context) { region.Endpoint = req.Endpoint if err := h.db.Save(®ion).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "更新失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: region}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功", Data: region}) } // DeleteRegion 删除区域 func (h *RegionHandler) DeleteRegion(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.Region{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if err := h.db.Delete(&model.Region{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // BatchDeleteRegions 批量删除区域 // Logan.Li @@ -133,19 +133,19 @@ func (h *RegionHandler) DeleteRegion(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.IDsRequest true "删除请求" -// @Success 200 {object} models.Response +// @Param request body model.IDsRequest true "删除请求" +// @Success 200 {object} model.Response // @Router /regions/batch-delete [delete] func (h *RegionHandler) BatchDeleteRegions(c *gin.Context) { - var req models.IDsRequest + var req model.IDsRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误"}) return } - if err := h.db.Delete(&models.Region{}, req.IDs).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if err := h.db.Delete(&model.Region{}, req.IDs).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } diff --git a/backend/internal/api/handlers/cloud_sync.go b/backend/controller/cloud_sync.go similarity index 76% rename from backend/internal/api/handlers/cloud_sync.go rename to backend/controller/cloud_sync.go index c488522..823cfcc 100644 --- a/backend/internal/api/handlers/cloud_sync.go +++ b/backend/controller/cloud_sync.go @@ -1,12 +1,12 @@ -package handlers +package controller import ( "net/http" "strconv" "time" - "ezops/internal/cloud" - "ezops/internal/models" + "ezops/cloud" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -26,36 +26,36 @@ func NewCloudSyncHandler(db *gorm.DB) *CloudSyncHandler { func (h *CloudSyncHandler) SyncRegions(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var account models.CloudAccount + var account model.CloudAccount if err := h.db.First(&account, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "云账号不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "云账号不存在"}) return } if account.Status != "active" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "云账号未激活,无法同步"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "云账号未激活,无法同步"}) return } provider := cloud.NewProvider(account.Provider, account.AccessKey, account.SecretKey) if provider == nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "暂不支持的云平台: " + account.Provider}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "暂不支持的云平台: " + account.Provider}) return } cloudRegions, err := provider.ListRegions() if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "同步区域失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "同步区域失败: " + err.Error()}) return } // Upsert: 不存在则创建,存在则更新 synced := 0 for _, cr := range cloudRegions { - var region models.Region + var region model.Region result := h.db.Where("code = ? AND provider = ?", cr.RegionID, account.Provider).First(®ion) if result.Error == gorm.ErrRecordNotFound { // 新区域 → 创建 - h.db.Create(&models.Region{ + h.db.Create(&model.Region{ Name: cr.LocalName, Code: cr.RegionID, Provider: account.Provider, @@ -77,7 +77,7 @@ func (h *CloudSyncHandler) SyncRegions(c *gin.Context) { "last_sync_at": time.Now(), }) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "同步成功", Data: gin.H{ @@ -92,19 +92,19 @@ func (h *CloudSyncHandler) SyncRegions(c *gin.Context) { func (h *CloudSyncHandler) GetAccountRegions(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var account models.CloudAccount + var account model.CloudAccount if err := h.db.First(&account, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "云账号不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "云账号不存在"}) return } - var regions []models.Region + var regions []model.Region h.db.Where("provider = ?", account.Provider).Order("name ASC").Find(®ions) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: regions, Total: int64(len(regions)), }, @@ -121,25 +121,25 @@ type discoverRequest struct { func (h *CloudSyncHandler) DiscoverInstances(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var account models.CloudAccount + var account model.CloudAccount if err := h.db.First(&account, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "云账号不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "云账号不存在"}) return } var req discoverRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误"}) return } if len(req.Regions) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请至少选择一个区域"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请至少选择一个区域"}) return } provider := cloud.NewProvider(account.Provider, account.AccessKey, account.SecretKey) if provider == nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "暂不支持的云平台"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "暂不支持的云平台"}) return } @@ -155,7 +155,7 @@ func (h *CloudSyncHandler) DiscoverInstances(c *gin.Context) { allInstances = append(allInstances, instances...) } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: gin.H{ @@ -176,15 +176,15 @@ type importRequest struct { func (h *CloudSyncHandler) ImportInstances(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var account models.CloudAccount + var account model.CloudAccount if err := h.db.First(&account, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "云账号不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "云账号不存在"}) return } var req importRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误"}) return } @@ -203,14 +203,14 @@ func (h *CloudSyncHandler) ImportInstances(c *gin.Context) { // 检查是否已存在(按 IP 或 hostname) var count int64 - h.db.Model(&models.Server{}).Where("ip = ? OR hostname = ?", ip, inst.Hostname).Count(&count) + h.db.Model(&model.Server{}).Where("ip = ? OR hostname = ?", ip, inst.Hostname).Count(&count) if count > 0 { skipped++ continue } // 查找 Region 关联 - var region models.Region + var region model.Region var regionID *uint if h.db.Where("code = ? AND provider = ?", inst.RegionID, account.Provider).First(®ion).Error == nil { regionID = ®ion.ID @@ -241,7 +241,7 @@ func (h *CloudSyncHandler) ImportInstances(c *gin.Context) { // 注意:servers 表的 cloud_id 外键引用的是 clouds 表(非 cloud_accounts), // region_id 外键引用 regions 表。未找到关联时设为 NULL 避免外键约束失败。 - server := models.Server{ + server := model.Server{ Hostname: hostname, IP: ipAddr, PublicIP: inst.PublicIP, @@ -266,7 +266,7 @@ func (h *CloudSyncHandler) ImportInstances(c *gin.Context) { // 更新账号的 server_count h.db.Model(&account).UpdateColumn("server_count", imported) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "导入完成", Data: gin.H{ diff --git a/backend/internal/api/handlers/credential.go b/backend/controller/credential.go similarity index 82% rename from backend/internal/api/handlers/credential.go rename to backend/controller/credential.go index b1e13cf..21a28d3 100644 --- a/backend/internal/api/handlers/credential.go +++ b/backend/controller/credential.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "crypto/rand" @@ -9,7 +9,7 @@ import ( "strconv" "strings" - "ezops/internal/models" + "ezops/model" "ezops/pkg/crypto" "github.com/gin-gonic/gin" @@ -34,7 +34,7 @@ func genEnvPrefix() string { return hex.EncodeToString(b)[:8] } -func buildContent(req models.CreateSecretRequest) (string, string, error) { +func buildContent(req model.CreateSecretRequest) (string, string, error) { switch req.SecretType { case "ssh": data := map[string]interface{}{ @@ -93,10 +93,10 @@ func buildContent(req models.CreateSecretRequest) (string, string, error) { // ────── List ────── func (h *CredentialHandler) ListCredentials(c *gin.Context) { - var query models.SecretListQuery + var query model.SecretListQuery c.ShouldBindQuery(&query) - db := h.db.Model(&models.Credential{}) + db := h.db.Model(&model.Credential{}) if query.SecretType != "" { db = db.Where("secret_type = ?", query.SecretType) } @@ -121,16 +121,16 @@ func (h *CredentialHandler) ListCredentials(c *gin.Context) { pageSize := query.PageSize if pageSize < 1 || pageSize > 100 { pageSize = 20 } - var creds []models.Credential + var creds []model.Credential db.Order("updated_at DESC").Offset((page - 1) * pageSize).Limit(pageSize).Find(&creds) - items := make([]models.SecretListResponse, 0, len(creds)) + items := make([]model.SecretListResponse, 0, len(creds)) for _, cred := range creds { tags := []string{} if cred.Tags != "" { json.Unmarshal([]byte(cred.Tags), &tags) } - items = append(items, models.SecretListResponse{ + items = append(items, model.SecretListResponse{ ID: cred.ID, Name: cred.Name, VariableName: cred.VariableName, @@ -146,7 +146,7 @@ func (h *CredentialHandler) ListCredentials(c *gin.Context) { }) } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{ List: items, Total: total, }}) } @@ -154,21 +154,21 @@ func (h *CredentialHandler) ListCredentials(c *gin.Context) { // ────── Create ────── func (h *CredentialHandler) CreateCredential(c *gin.Context) { - var req models.CreateSecretRequest + var req model.CreateSecretRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } plainContent, summary, err := buildContent(req) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } encrypted, err := h.crypt.Encrypt(plainContent) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "加密失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "加密失败"}) return } @@ -177,7 +177,7 @@ func (h *CredentialHandler) CreateCredential(c *gin.Context) { isActive := true if req.IsActive != nil { isActive = *req.IsActive } - cred := models.Credential{ + cred := model.Credential{ Name: req.Name, VariableName: req.VariableName, SecretType: req.SecretType, @@ -191,27 +191,27 @@ func (h *CredentialHandler) CreateCredential(c *gin.Context) { } if err := h.db.Create(&cred).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: cred.ID}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "创建成功", Data: cred.ID}) } // ────── Get Detail ────── func (h *CredentialHandler) GetCredential(c *gin.Context) { id, _ := strconv.ParseUint(c.Param("id"), 10, 32) - var cred models.Credential + var cred model.Credential if h.db.First(&cred, id).Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "凭据不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "凭据不存在"}) return } // Decrypt content plain, err := h.crypt.Decrypt(cred.Content) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "解密失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "解密失败"}) return } @@ -221,7 +221,7 @@ func (h *CredentialHandler) GetCredential(c *gin.Context) { tags := []string{} if cred.Tags != "" { json.Unmarshal([]byte(cred.Tags), &tags) } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "id": cred.ID, "name": cred.Name, "variable_name": cred.VariableName, @@ -241,15 +241,15 @@ func (h *CredentialHandler) GetCredential(c *gin.Context) { func (h *CredentialHandler) UpdateCredential(c *gin.Context) { id, _ := strconv.ParseUint(c.Param("id"), 10, 32) - var cred models.Credential + var cred model.Credential if h.db.First(&cred, id).Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "凭据不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "凭据不存在"}) return } - var req models.UpdateSecretRequest + var req model.UpdateSecretRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"}) return } @@ -279,7 +279,7 @@ func (h *CredentialHandler) UpdateCredential(c *gin.Context) { newPlain, _ := json.Marshal(old) enc, err := h.crypt.Encrypt(string(newPlain)) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "加密失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "加密失败"}) return } updates["content"] = enc @@ -292,10 +292,10 @@ func (h *CredentialHandler) UpdateCredential(c *gin.Context) { h.db.Model(&cred).Updates(updates) } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功"}) } -func hasTypeFieldUpdate(req models.UpdateSecretRequest) bool { +func hasTypeFieldUpdate(req model.UpdateSecretRequest) bool { return req.SSHPrivateKey != nil || req.SSHPublicKey != nil || req.SSHUser != nil || req.SSHPort != nil || req.SSHPassword != nil || req.DockerServer != nil || req.DockerUsername != nil || req.DockerPassword != nil || req.TLSCert != nil || req.TLSKey != nil || req.TLSCA != nil || @@ -305,7 +305,7 @@ func hasTypeFieldUpdate(req models.UpdateSecretRequest) bool { req.GenericKey != nil || req.GenericValue != nil } -func mergeUpdate(req models.UpdateSecretRequest, old map[string]interface{}) { +func mergeUpdate(req model.UpdateSecretRequest, old map[string]interface{}) { if req.SSHPrivateKey != nil { old["private_key"] = *req.SSHPrivateKey } if req.SSHPublicKey != nil { old["public_key"] = *req.SSHPublicKey } if req.SSHUser != nil { old["ssh_user"] = *req.SSHUser } @@ -365,27 +365,27 @@ func (h *CredentialHandler) PatchCredential(c *gin.Context) { updates["is_active"] = v } if len(updates) > 0 { - h.db.Model(&models.Credential{}).Where("id = ?", id).Updates(updates) + h.db.Model(&model.Credential{}).Where("id = ?", id).Updates(updates) } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "ok"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "ok"}) } // ────── Delete ────── func (h *CredentialHandler) DeleteCredential(c *gin.Context) { id, _ := strconv.ParseUint(c.Param("id"), 10, 32) - if h.db.Delete(&models.Credential{}, id).Error != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if h.db.Delete(&model.Credential{}, id).Error != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // ────── Tags ────── func (h *CredentialHandler) GetTags(c *gin.Context) { var rows []string - h.db.Model(&models.Credential{}).Where("tags != ''").Pluck("tags", &rows) + h.db.Model(&model.Credential{}).Where("tags != ''").Pluck("tags", &rows) tagSet := map[string]bool{} for _, r := range rows { @@ -396,5 +396,5 @@ func (h *CredentialHandler) GetTags(c *gin.Context) { } tags := make([]string, 0, len(tagSet)) for t := range tagSet { tags = append(tags, t) } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: tags}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: tags}) } diff --git a/backend/internal/api/handlers/credential_assign.go b/backend/controller/credential_assign.go similarity index 56% rename from backend/internal/api/handlers/credential_assign.go rename to backend/controller/credential_assign.go index d5a6f95..81432c8 100644 --- a/backend/internal/api/handlers/credential_assign.go +++ b/backend/controller/credential_assign.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -13,7 +13,7 @@ import ( func (h *CredentialHandler) AssignCredential(c *gin.Context) { serverID, err := strconv.ParseUint(c.Param("id"), 10, 32) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的服务器ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的服务器ID"}) return } @@ -21,25 +21,25 @@ func (h *CredentialHandler) AssignCredential(c *gin.Context) { CredentialID uint `json:"credential_id"` } if err := c.ShouldBindJSON(&req); err != nil || req.CredentialID == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请选择凭据"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请选择凭据"}) return } - var cred models.Credential + var cred model.Credential if err := h.db.First(&cred, req.CredentialID).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "凭据不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "凭据不存在"}) return } plain, err := h.crypt.Decrypt(cred.Content) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "凭据解密失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "凭据解密失败"}) return } - var server models.Server + var server model.Server if err := h.db.First(&server, serverID).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "服务器不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "服务器不存在"}) return } @@ -54,9 +54,9 @@ func (h *CredentialHandler) AssignCredential(c *gin.Context) { } if err := h.db.Save(&server).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "分配失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "分配失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "凭据已关联"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "凭据已关联"}) } diff --git a/backend/internal/api/handlers/dashboard.go b/backend/controller/dashboard.go similarity index 63% rename from backend/internal/api/handlers/dashboard.go rename to backend/controller/dashboard.go index 9743c93..2c1bd93 100644 --- a/backend/internal/api/handlers/dashboard.go +++ b/backend/controller/dashboard.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "context" @@ -9,7 +9,7 @@ import ( "strconv" "time" - "ezops/internal/models" + "ezops/model" ezredis "ezops/pkg/redis" "github.com/gin-gonic/gin" @@ -33,7 +33,7 @@ func NewDashboardHandler(db *gorm.DB, cache ezredis.Cache) *DashboardHandler { // @Tags 仪表盘 // @Produce json // @Security Bearer -// @Success 200 {object} models.Response{data=models.DashboardStats} +// @Success 200 {object} model.Response{data=model.DashboardStats} // @Router /dashboard/stats [get] func (h *DashboardHandler) GetStats(c *gin.Context) { const cacheKey = "dashboard:stats" @@ -41,9 +41,9 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { // 尝试从 Redis 缓存读取 if cached, err := h.cache.Get(c.Request.Context(), cacheKey); err == nil && cached != "" { - var stats models.DashboardStats + var stats model.DashboardStats if json.Unmarshal([]byte(cached), &stats) == nil { - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: stats, @@ -52,20 +52,20 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { } } - var stats models.DashboardStats + var stats model.DashboardStats // 服务器统计 - var serverStats models.ServerStats - h.db.Model(&models.Server{}).Count(&serverStats.Total) - h.db.Model(&models.Server{}).Where("status = ?", "running").Count(&serverStats.Running) - h.db.Model(&models.Server{}).Where("status = ?", "stopped").Count(&serverStats.Stopped) - h.db.Model(&models.Server{}).Where("status = ?", "maintenance").Count(&serverStats.Maintenance) - h.db.Model(&models.Server{}).Where("status = ?", "error").Count(&serverStats.Error) + var serverStats model.ServerStats + h.db.Model(&model.Server{}).Count(&serverStats.Total) + h.db.Model(&model.Server{}).Where("status = ?", "running").Count(&serverStats.Running) + h.db.Model(&model.Server{}).Where("status = ?", "stopped").Count(&serverStats.Stopped) + h.db.Model(&model.Server{}).Where("status = ?", "maintenance").Count(&serverStats.Maintenance) + h.db.Model(&model.Server{}).Where("status = ?", "error").Count(&serverStats.Error) var avgCPU, avgMemory, avgDisk float64 - h.db.Model(&models.Server{}).Select("AVG(cpu_usage)").Scan(&avgCPU) - h.db.Model(&models.Server{}).Select("AVG(memory_usage)").Scan(&avgMemory) - h.db.Model(&models.Server{}).Select("AVG(disk_usage)").Scan(&avgDisk) + h.db.Model(&model.Server{}).Select("AVG(cpu_usage)").Scan(&avgCPU) + h.db.Model(&model.Server{}).Select("AVG(memory_usage)").Scan(&avgMemory) + h.db.Model(&model.Server{}).Select("AVG(disk_usage)").Scan(&avgDisk) serverStats.AvgCPU = math.Round(avgCPU*100) / 100 serverStats.AvgMemory = math.Round(avgMemory*100) / 100 serverStats.AvgDisk = math.Round(avgDisk*100) / 100 @@ -73,16 +73,16 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { stats.ServerStats = serverStats // K8s集群统计 - var k8sStats models.KubernetesClusterStats - h.db.Model(&models.KubernetesCluster{}).Count(&k8sStats.Total) - h.db.Model(&models.KubernetesCluster{}).Where("status = ?", "healthy").Count(&k8sStats.Healthy) - h.db.Model(&models.KubernetesCluster{}).Where("status = ?", "warning").Count(&k8sStats.Warning) - h.db.Model(&models.KubernetesCluster{}).Where("status = ?", "error").Count(&k8sStats.Error) + var k8sStats model.KubernetesClusterStats + h.db.Model(&model.KubernetesCluster{}).Count(&k8sStats.Total) + h.db.Model(&model.KubernetesCluster{}).Where("status = ?", "healthy").Count(&k8sStats.Healthy) + h.db.Model(&model.KubernetesCluster{}).Where("status = ?", "warning").Count(&k8sStats.Warning) + h.db.Model(&model.KubernetesCluster{}).Where("status = ?", "error").Count(&k8sStats.Error) var totalNodes, totalPods, totalServices int64 - h.db.Model(&models.KubernetesNode{}).Count(&totalNodes) - h.db.Model(&models.KubernetesPod{}).Count(&totalPods) - h.db.Model(&models.KubernetesService{}).Count(&totalServices) + h.db.Model(&model.KubernetesNode{}).Count(&totalNodes) + h.db.Model(&model.KubernetesPod{}).Count(&totalPods) + h.db.Model(&model.KubernetesService{}).Count(&totalServices) k8sStats.TotalNodes = totalNodes k8sStats.TotalPods = totalPods k8sStats.TotalServices = totalServices @@ -90,31 +90,31 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { stats.K8sStats = k8sStats // 告警统计 - var alertStats models.AlertStats - h.db.Model(&models.AlertEvent{}).Count(&alertStats.Total) - h.db.Model(&models.AlertEvent{}).Where("status = ?", "firing").Count(&alertStats.Firing) - h.db.Model(&models.AlertEvent{}).Where("status = ?", "resolved").Count(&alertStats.Resolved) - h.db.Model(&models.AlertEvent{}).Where("severity = ?", "critical").Count(&alertStats.Critical) - h.db.Model(&models.AlertEvent{}).Where("severity = ?", "warning").Count(&alertStats.Warning) - h.db.Model(&models.AlertEvent{}).Where("severity = ?", "info").Count(&alertStats.Info) + var alertStats model.AlertStats + h.db.Model(&model.AlertEvent{}).Count(&alertStats.Total) + h.db.Model(&model.AlertEvent{}).Where("status = ?", "firing").Count(&alertStats.Firing) + h.db.Model(&model.AlertEvent{}).Where("status = ?", "resolved").Count(&alertStats.Resolved) + h.db.Model(&model.AlertEvent{}).Where("severity = ?", "critical").Count(&alertStats.Critical) + h.db.Model(&model.AlertEvent{}).Where("severity = ?", "warning").Count(&alertStats.Warning) + h.db.Model(&model.AlertEvent{}).Where("severity = ?", "info").Count(&alertStats.Info) // 今日告警 today := time.Now().Format("2006-01-02") - h.db.Model(&models.AlertEvent{}).Where("DATE(created_at) = ?", today).Count(&alertStats.TodayCount) + h.db.Model(&model.AlertEvent{}).Where("DATE(created_at) = ?", today).Count(&alertStats.TodayCount) // 本周告警 weekAgo := time.Now().AddDate(0, 0, -7).Format("2006-01-02") - h.db.Model(&models.AlertEvent{}).Where("created_at >= ?", weekAgo).Count(&alertStats.WeekCount) + h.db.Model(&model.AlertEvent{}).Where("created_at >= ?", weekAgo).Count(&alertStats.WeekCount) stats.AlertStats = alertStats // 流水线统计 - var pipelineStats models.PipelineStats - h.db.Model(&models.PipelineRun{}).Count(&pipelineStats.Total) - h.db.Model(&models.PipelineRun{}).Where("status = ?", "success").Count(&pipelineStats.Success) - h.db.Model(&models.PipelineRun{}).Where("status = ?", "failed").Count(&pipelineStats.Failed) - h.db.Model(&models.PipelineRun{}).Where("status = ?", "running").Count(&pipelineStats.Running) - h.db.Model(&models.PipelineRun{}).Where("DATE(created_at) = ?", today).Count(&pipelineStats.TodayCount) + var pipelineStats model.PipelineStats + h.db.Model(&model.PipelineRun{}).Count(&pipelineStats.Total) + h.db.Model(&model.PipelineRun{}).Where("status = ?", "success").Count(&pipelineStats.Success) + h.db.Model(&model.PipelineRun{}).Where("status = ?", "failed").Count(&pipelineStats.Failed) + h.db.Model(&model.PipelineRun{}).Where("status = ?", "running").Count(&pipelineStats.Running) + h.db.Model(&model.PipelineRun{}).Where("DATE(created_at) = ?", today).Count(&pipelineStats.TodayCount) if pipelineStats.Total > 0 { pipelineStats.SuccessRate = math.Round(float64(pipelineStats.Success)/float64(pipelineStats.Total)*10000) / 100 @@ -123,7 +123,7 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { stats.PipelineStats = pipelineStats // 成本统计 — 基于云账号月费用(monthly_cost)计算,不再硬编码 - var cloudAccounts []models.CloudAccount + var cloudAccounts []model.CloudAccount h.db.Find(&cloudAccounts) providerCost := make(map[string]float64) @@ -145,21 +145,21 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { "huawei": "华为云", "azure": "Azure", } - var cloudCosts []models.CloudCost + var cloudCosts []model.CloudCost for _, p := range providerOrder { name := providerName[p] if name == "" { name = p } - cloudCosts = append(cloudCosts, models.CloudCost{Cloud: name, Cost: math.Round(providerCost[p]*100) / 100}) + cloudCosts = append(cloudCosts, model.CloudCost{Cloud: name, Cost: math.Round(providerCost[p]*100) / 100}) } // 月度趋势:以本月实际费用为锚,向前回推 5 个月(轻微增长趋势),合计即为 total_cost - var monthTrend []models.MonthTrend + var monthTrend []model.MonthTrend trendScales := []float64{0.85, 0.88, 0.91, 0.94, 0.97, 1.0} for i := 0; i < 6; i++ { t := time.Now().AddDate(0, -(5 - i), 0) - monthTrend = append(monthTrend, models.MonthTrend{ + monthTrend = append(monthTrend, model.MonthTrend{ Month: fmt.Sprintf("%d月", int(t.Month())), Cost: math.Round(monthCostTotal*trendScales[i]*100) / 100, }) @@ -170,7 +170,7 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { totalCost += m.Cost } - stats.CostStats = models.CostStats{ + stats.CostStats = model.CostStats{ TotalCost: math.Round(totalCost*100) / 100, MonthCost: math.Round(monthCostTotal*100) / 100, CloudCosts: cloudCosts, @@ -178,14 +178,14 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { } // Top资源使用 - var topCPU, topMemory, topDisk []models.Server + var topCPU, topMemory, topDisk []model.Server h.db.Order("cpu_usage DESC").Limit(5).Find(&topCPU) h.db.Order("memory_usage DESC").Limit(5).Find(&topMemory) h.db.Order("disk_usage DESC").Limit(5).Find(&topDisk) - var topResourceUsage models.TopResourceUsage + var topResourceUsage model.TopResourceUsage for _, s := range topCPU { - topResourceUsage.CPU = append(topResourceUsage.CPU, models.ServerResource{ + topResourceUsage.CPU = append(topResourceUsage.CPU, model.ServerResource{ ID: s.ID, Hostname: s.Hostname, IP: s.IP, @@ -193,7 +193,7 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { }) } for _, s := range topMemory { - topResourceUsage.Memory = append(topResourceUsage.Memory, models.ServerResource{ + topResourceUsage.Memory = append(topResourceUsage.Memory, model.ServerResource{ ID: s.ID, Hostname: s.Hostname, IP: s.IP, @@ -201,7 +201,7 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { }) } for _, s := range topDisk { - topResourceUsage.Disk = append(topResourceUsage.Disk, models.ServerResource{ + topResourceUsage.Disk = append(topResourceUsage.Disk, model.ServerResource{ ID: s.ID, Hostname: s.Hostname, IP: s.IP, @@ -211,16 +211,16 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { stats.TopResourceUsage = topResourceUsage // 即将过期的证书 - var domains []models.Domain + var domains []model.Domain h.db.Where("ssl_enabled = ?", true).Find(&domains) - var expiringCerts []models.DomainCert + var expiringCerts []model.DomainCert now := time.Now() for _, d := range domains { if d.SSLExpireDate != nil { days := int(d.SSLExpireDate.Sub(now).Hours() / 24) if days < 90 { - expiringCerts = append(expiringCerts, models.DomainCert{ + expiringCerts = append(expiringCerts, model.DomainCert{ ID: d.ID, Name: d.Name, ExpireDate: d.SSLExpireDate.Format("2006-01-02"), @@ -236,7 +236,7 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { _ = h.cache.Set(context.Background(), cacheKey, string(data), cacheTTL) } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: stats, @@ -250,7 +250,7 @@ func (h *DashboardHandler) GetStats(c *gin.Context) { // @Produce json // @Security Bearer // @Param limit query int false "数量限制" -// @Success 200 {object} models.Response{data=[]models.AlertEvent} +// @Success 200 {object} model.Response{data=[]model.AlertEvent} // @Router /dashboard/recent-alerts [get] func (h *DashboardHandler) GetRecentAlerts(c *gin.Context) { limit := 10 @@ -260,13 +260,13 @@ func (h *DashboardHandler) GetRecentAlerts(c *gin.Context) { } } - var alerts []models.AlertEvent + var alerts []model.AlertEvent h.db.Preload("Rule").Where("status = ?", "firing"). Order("created_at DESC"). Limit(limit). Find(&alerts) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: alerts, @@ -280,7 +280,7 @@ func (h *DashboardHandler) GetRecentAlerts(c *gin.Context) { // @Produce json // @Security Bearer // @Param limit query int false "数量限制" -// @Success 200 {object} models.Response{data=[]models.AppRelease} +// @Success 200 {object} model.Response{data=[]model.AppRelease} // @Router /dashboard/recent-releases [get] func (h *DashboardHandler) GetRecentReleases(c *gin.Context) { limit := 5 @@ -290,12 +290,12 @@ func (h *DashboardHandler) GetRecentReleases(c *gin.Context) { } } - var releases []models.AppRelease + var releases []model.AppRelease h.db.Order("created_at DESC"). Limit(limit). Find(&releases) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: releases, @@ -309,7 +309,7 @@ func (h *DashboardHandler) GetRecentReleases(c *gin.Context) { // @Produce json // @Security Bearer // @Param hours query int false "小时数" -// @Success 200 {object} models.Response{data=[]models.MetricData} +// @Success 200 {object} model.Response{data=[]model.MetricData} // @Router /dashboard/metrics [get] func (h *DashboardHandler) GetMetrics(c *gin.Context) { hours := 6 // 默认6小时,减少扫描行数 @@ -327,28 +327,28 @@ func (h *DashboardHandler) GetMetrics(c *gin.Context) { AvgMem float64 } var rows []avgPoint - h.db.Model(&models.AgentReport{}). + h.db.Model(&model.AgentReport{}). Select("UNIX_TIMESTAMP(report_time) DIV 3600 as bucket_ts, ROUND(AVG(cpu_usage),2) as avg_cpu, ROUND(AVG(mem_usage),2) as avg_mem"). Where("report_time >= ?", since). Group("bucket_ts"). Order("bucket_ts ASC"). Scan(&rows) - var metrics []models.MetricData + var metrics []model.MetricData for _, r := range rows { ts := time.Unix(r.BucketTS*3600, 0) metrics = append(metrics, - models.MetricData{Name: "cpu", Value: r.AvgCPU, Timestamp: ts}, - models.MetricData{Name: "memory", Value: r.AvgMem, Timestamp: ts}, + model.MetricData{Name: "cpu", Value: r.AvgCPU, Timestamp: ts}, + model.MetricData{Name: "memory", Value: r.AvgMem, Timestamp: ts}, ) } // 如果没有真实数据,返回空数组(不造假数据) if metrics == nil { - metrics = []models.MetricData{} + metrics = []model.MetricData{} } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: metrics, diff --git a/backend/internal/api/handlers/deploy.go b/backend/controller/deploy.go similarity index 67% rename from backend/internal/api/handlers/deploy.go rename to backend/controller/deploy.go index de77f4f..6ccbe3b 100644 --- a/backend/internal/api/handlers/deploy.go +++ b/backend/controller/deploy.go @@ -1,9 +1,9 @@ -package handlers +package controller import ( "net/http" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -21,18 +21,18 @@ func NewDeployHandler(db *gorm.DB) *DeployHandler { // ==================== Git 仓库认证 ==================== func (h *DeployHandler) ListRepos(c *gin.Context) { - var items []models.PipelineRepo + var items []model.PipelineRepo h.db.Order("updated_at DESC").Find(&items) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{List: items, Total: int64(len(items))}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: items, Total: int64(len(items))}}) } func (h *DeployHandler) GetRepo(c *gin.Context) { - var item models.PipelineRepo + var item model.PipelineRepo if err := h.db.First(&item, c.Param("id")); err.Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "不存在"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: item}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: item}) } func (h *DeployHandler) CreateRepo(c *gin.Context) { @@ -40,34 +40,34 @@ func (h *DeployHandler) CreateRepo(c *gin.Context) { Name string `json:"name" binding:"required"` Description string `json:"description"` URL string `json:"url" binding:"required"` - AuthType models.RepoAuthType `json:"auth_type"` + AuthType model.RepoAuthType `json:"auth_type"` CredentialID *uint `json:"credential_id"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - if req.AuthType == "" { req.AuthType = models.RepoAuthToken } - item := models.PipelineRepo{ + if req.AuthType == "" { req.AuthType = model.RepoAuthToken } + item := model.PipelineRepo{ Name: req.Name, Description: req.Description, URL: req.URL, AuthType: req.AuthType, CredentialID: req.CredentialID, CreatedBy: c.GetString("username"), } h.db.Create(&item) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: item}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: item}) } func (h *DeployHandler) UpdateRepo(c *gin.Context) { - var item models.PipelineRepo + var item model.PipelineRepo if err := h.db.First(&item, c.Param("id")); err.Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "不存在"}) return } var req struct { Name *string `json:"name"` Description *string `json:"description"` URL *string `json:"url"` - AuthType *models.RepoAuthType `json:"auth_type"` + AuthType *model.RepoAuthType `json:"auth_type"` CredentialID *uint `json:"credential_id"` Enabled *bool `json:"enabled"` } @@ -81,29 +81,29 @@ func (h *DeployHandler) UpdateRepo(c *gin.Context) { if req.CredentialID != nil { updates["credential_id"] = req.CredentialID } h.db.Model(&item).Updates(updates) h.db.First(&item, item.ID) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: item}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: item}) } func (h *DeployHandler) DeleteRepo(c *gin.Context) { - h.db.Delete(&models.PipelineRepo{}, c.Param("id")) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已删除"}) + h.db.Delete(&model.PipelineRepo{}, c.Param("id")) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已删除"}) } // ==================== 镜像仓库认证 ==================== func (h *DeployHandler) ListRegistries(c *gin.Context) { - var items []models.PipelineRegistry + var items []model.PipelineRegistry h.db.Order("updated_at DESC").Find(&items) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{List: items, Total: int64(len(items))}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: items, Total: int64(len(items))}}) } func (h *DeployHandler) GetRegistry(c *gin.Context) { - var item models.PipelineRegistry + var item model.PipelineRegistry if err := h.db.First(&item, c.Param("id")); err.Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "不存在"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: item}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: item}) } func (h *DeployHandler) CreateRegistry(c *gin.Context) { @@ -112,27 +112,27 @@ func (h *DeployHandler) CreateRegistry(c *gin.Context) { Description string `json:"description"` RegistryURL string `json:"registry_url" binding:"required"` Namespace string `json:"namespace"` - AuthType models.RegistryAuthType `json:"auth_type"` + AuthType model.RegistryAuthType `json:"auth_type"` CredentialID *uint `json:"credential_id"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - if req.AuthType == "" { req.AuthType = models.RegistryAuthPassword } - item := models.PipelineRegistry{ + if req.AuthType == "" { req.AuthType = model.RegistryAuthPassword } + item := model.PipelineRegistry{ Name: req.Name, Description: req.Description, RegistryURL: req.RegistryURL, Namespace: req.Namespace, AuthType: req.AuthType, CredentialID: req.CredentialID, CreatedBy: c.GetString("username"), } h.db.Create(&item) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: item}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: item}) } func (h *DeployHandler) UpdateRegistry(c *gin.Context) { - var item models.PipelineRegistry + var item model.PipelineRegistry if err := h.db.First(&item, c.Param("id")); err.Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "不存在"}) return } var req struct { @@ -140,7 +140,7 @@ func (h *DeployHandler) UpdateRegistry(c *gin.Context) { Description *string `json:"description"` RegistryURL *string `json:"registry_url"` Namespace *string `json:"namespace"` - AuthType *models.RegistryAuthType `json:"auth_type"` + AuthType *model.RegistryAuthType `json:"auth_type"` CredentialID *uint `json:"credential_id"` Enabled *bool `json:"enabled"` } @@ -155,10 +155,10 @@ func (h *DeployHandler) UpdateRegistry(c *gin.Context) { if req.CredentialID != nil { updates["credential_id"] = req.CredentialID } h.db.Model(&item).Updates(updates) h.db.First(&item, item.ID) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: item}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: item}) } func (h *DeployHandler) DeleteRegistry(c *gin.Context) { - h.db.Delete(&models.PipelineRegistry{}, c.Param("id")) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已删除"}) + h.db.Delete(&model.PipelineRegistry{}, c.Param("id")) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已删除"}) } diff --git a/backend/internal/api/handlers/deploy_environments.go b/backend/controller/deploy_environments.go similarity index 69% rename from backend/internal/api/handlers/deploy_environments.go rename to backend/controller/deploy_environments.go index 5ea2df9..207fdb1 100644 --- a/backend/internal/api/handlers/deploy_environments.go +++ b/backend/controller/deploy_environments.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" @@ -7,7 +7,7 @@ import ( "strconv" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -16,9 +16,9 @@ import ( // ListEnvironments 环境列表 func (h *PipelineHandler) ListEnvironments(c *gin.Context) { - var items []models.DeployEnvironment + var items []model.DeployEnvironment h.db.Order("sort_order ASC, id ASC").Find(&items) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{List: items, Total: int64(len(items))}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: items, Total: int64(len(items))}}) } // CreateEnvironment 创建环境 @@ -32,28 +32,28 @@ func (h *PipelineHandler) CreateEnvironment(c *gin.Context) { Description string `json:"description"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } if req.Color == "" { req.Color = typeDefaultColor(req.Type) } - item := models.DeployEnvironment{ + item := model.DeployEnvironment{ Name: req.Name, DisplayName: req.DisplayName, - Type: models.EnvironmentType(req.Type), Color: req.Color, + Type: model.EnvironmentType(req.Type), Color: req.Color, SortOrder: req.SortOrder, Description: req.Description, } if err := h.db.Create(&item).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: item}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: item}) } // UpdateEnvironment 更新环境 func (h *PipelineHandler) UpdateEnvironment(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var item models.DeployEnvironment + var item model.DeployEnvironment if err := h.db.First(&item, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "不存在"}) return } var req struct { @@ -76,13 +76,13 @@ func (h *PipelineHandler) UpdateEnvironment(c *gin.Context) { if req.Enabled != nil { updates["enabled"] = *req.Enabled } h.db.Model(&item).Updates(updates) h.db.First(&item, id) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: item}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: item}) } // DeleteEnvironment 删除环境 func (h *PipelineHandler) DeleteEnvironment(c *gin.Context) { - h.db.Delete(&models.DeployEnvironment{}, c.Param("id")) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已删除"}) + h.db.Delete(&model.DeployEnvironment{}, c.Param("id")) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已删除"}) } func typeDefaultColor(t string) string { @@ -99,9 +99,9 @@ func typeDefaultColor(t string) string { // ListPipelineMembers 成员列表 func (h *PipelineHandler) ListPipelineMembers(c *gin.Context) { pipelineID := getPipelineID(c) - var members []models.DeployPipelineMember + var members []model.DeployPipelineMember h.db.Where("pipeline_id = ?", pipelineID).Order("created_at ASC").Find(&members) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: members}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: members}) } // AddPipelineMember 添加成员 @@ -112,38 +112,38 @@ func (h *PipelineHandler) AddPipelineMember(c *gin.Context) { Role string `json:"role" binding:"required,oneof=owner editor viewer"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - var pipeline models.Pipeline + var pipeline model.Pipeline if err := h.db.First(&pipeline, pipelineID).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "流水线不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "流水线不存在"}) return } - member := models.DeployPipelineMember{ + member := model.DeployPipelineMember{ PipelineID: uint(pipelineID), Username: &req.Username, - Role: models.MemberRole(req.Role), + Role: model.MemberRole(req.Role), } if err := h.db.Create(&member).Error; err != nil { - c.JSON(http.StatusConflict, models.Response{Code: 409, Message: "该用户已是成员"}) + c.JSON(http.StatusConflict, model.Response{Code: 409, Message: "该用户已是成员"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: member}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: member}) } // RemovePipelineMember 移除成员 func (h *PipelineHandler) RemovePipelineMember(c *gin.Context) { pipelineID := getPipelineID(c) memberID, _ := strconv.Atoi(c.Param("memberId")) - result := h.db.Where("id = ? AND pipeline_id = ?", memberID, pipelineID).Delete(&models.DeployPipelineMember{}) + result := h.db.Where("id = ? AND pipeline_id = ?", memberID, pipelineID).Delete(&model.DeployPipelineMember{}) if result.RowsAffected == 0 { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "成员不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "成员不存在"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已移除"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已移除"}) } // ==================== 流水线运行控制 ==================== @@ -153,13 +153,13 @@ func (h *PipelineHandler) StopPipelineRun(c *gin.Context) { pipelineID := getPipelineID(c) runID, _ := strconv.Atoi(c.Param("runId")) - var run models.PipelineRun + var run model.PipelineRun if err := h.db.Where("id = ? AND pipeline_id = ?", runID, pipelineID).First(&run).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "运行记录不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "运行记录不存在"}) return } if run.Status != "running" && run.Status != "pending" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "仅运行中或等待中的任务可停止, 当前状态: " + run.Status}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "仅运行中或等待中的任务可停止, 当前状态: " + run.Status}) return } @@ -192,7 +192,7 @@ func (h *PipelineHandler) StopPipelineRun(c *gin.Context) { h.db.Model(&run).Update("logs", string(newLogs)) h.db.First(&run, runID) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: run, Message: "已停止"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: run, Message: "已停止"}) } // GetRunLog 获取运行日志 @@ -200,9 +200,9 @@ func (h *PipelineHandler) GetRunLog(c *gin.Context) { pipelineID := getPipelineID(c) runID, _ := strconv.Atoi(c.Param("runId")) - var run models.PipelineRun + var run model.PipelineRun if err := h.db.Where("id = ? AND pipeline_id = ?", runID, pipelineID).First(&run).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "运行记录不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "运行记录不存在"}) return } @@ -211,7 +211,7 @@ func (h *PipelineHandler) GetRunLog(c *gin.Context) { json.Unmarshal([]byte(run.Logs), &logs) } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "run": run, "logs": logs, }}) @@ -225,10 +225,10 @@ func (h *PipelineHandler) BatchDeleteRuns(c *gin.Context) { IDs []uint `json:"ids" binding:"required"` } if err := c.ShouldBindJSON(&req); err != nil || len(req.IDs) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请选择要删除的记录"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请选择要删除的记录"}) return } - result := h.db.Where("pipeline_id = ? AND id IN ?", pipelineID, req.IDs).Delete(&models.PipelineRun{}) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: fmt.Sprintf("已删除 %d 条记录", result.RowsAffected)}) + result := h.db.Where("pipeline_id = ? AND id IN ?", pipelineID, req.IDs).Delete(&model.PipelineRun{}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: fmt.Sprintf("已删除 %d 条记录", result.RowsAffected)}) } diff --git a/backend/internal/api/handlers/deploy_groups.go b/backend/controller/deploy_groups.go similarity index 58% rename from backend/internal/api/handlers/deploy_groups.go rename to backend/controller/deploy_groups.go index d7135df..f4260d9 100644 --- a/backend/internal/api/handlers/deploy_groups.go +++ b/backend/controller/deploy_groups.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -13,9 +13,9 @@ import ( // ListGroups 用户组列表 func (h *PipelineHandler) ListGroups(c *gin.Context) { - var groups []models.DeployUserGroup + var groups []model.DeployUserGroup h.db.Preload("Members").Order("created_at DESC").Find(&groups) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{List: groups, Total: int64(len(groups))}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: groups, Total: int64(len(groups))}}) } // CreateGroup 创建用户组 @@ -25,26 +25,26 @@ func (h *PipelineHandler) CreateGroup(c *gin.Context) { Description string `json:"description"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - group := models.DeployUserGroup{ + group := model.DeployUserGroup{ Name: req.Name, Description: req.Description, CreatedBy: c.GetString("username"), } if err := h.db.Create(&group).Error; err != nil { - c.JSON(http.StatusConflict, models.Response{Code: 409, Message: "组名已存在: " + err.Error()}) + c.JSON(http.StatusConflict, model.Response{Code: 409, Message: "组名已存在: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: group}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: group}) } // UpdateGroup 更新用户组 func (h *PipelineHandler) UpdateGroup(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var group models.DeployUserGroup + var group model.DeployUserGroup if err := h.db.First(&group, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "不存在"}) return } var req struct { @@ -57,17 +57,17 @@ func (h *PipelineHandler) UpdateGroup(c *gin.Context) { if req.Description != nil { updates["description"] = *req.Description } h.db.Model(&group).Updates(updates) h.db.First(&group, id) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: group}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: group}) } // DeleteGroup 删除用户组 func (h *PipelineHandler) DeleteGroup(c *gin.Context) { id := c.Param("id") // 先删组成员和流水线授权 - h.db.Where("group_id = ?", id).Delete(&models.DeployUserGroupMember{}) - h.db.Where("group_id = ?", id).Delete(&models.DeployPipelineMember{}) - h.db.Delete(&models.DeployUserGroup{}, id) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已删除"}) + h.db.Where("group_id = ?", id).Delete(&model.DeployUserGroupMember{}) + h.db.Where("group_id = ?", id).Delete(&model.DeployPipelineMember{}) + h.db.Delete(&model.DeployUserGroup{}, id) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已删除"}) } // ==================== 用户组成员管理 ==================== @@ -75,9 +75,9 @@ func (h *PipelineHandler) DeleteGroup(c *gin.Context) { // ListGroupMembers 组成员列表 func (h *PipelineHandler) ListGroupMembers(c *gin.Context) { groupID, _ := strconv.Atoi(c.Param("id")) - var members []models.DeployUserGroupMember + var members []model.DeployUserGroupMember h.db.Where("group_id = ?", groupID).Find(&members) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: members}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: members}) } // AddGroupMember 添加组成员 @@ -87,27 +87,27 @@ func (h *PipelineHandler) AddGroupMember(c *gin.Context) { Username string `json:"username" binding:"required"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - member := models.DeployUserGroupMember{GroupID: uint(groupID), Username: req.Username} + member := model.DeployUserGroupMember{GroupID: uint(groupID), Username: req.Username} if err := h.db.Create(&member).Error; err != nil { - c.JSON(http.StatusConflict, models.Response{Code: 409, Message: "该用户已在组内"}) + c.JSON(http.StatusConflict, model.Response{Code: 409, Message: "该用户已在组内"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: member}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: member}) } // RemoveGroupMember 移除组成员 func (h *PipelineHandler) RemoveGroupMember(c *gin.Context) { groupID, _ := strconv.Atoi(c.Param("id")) memberID, _ := strconv.Atoi(c.Param("memberId")) - result := h.db.Where("id = ? AND group_id = ?", memberID, groupID).Delete(&models.DeployUserGroupMember{}) + result := h.db.Where("id = ? AND group_id = ?", memberID, groupID).Delete(&model.DeployUserGroupMember{}) if result.RowsAffected == 0 { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "成员不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "成员不存在"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已移除"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已移除"}) } // ==================== 组授权给流水线 ==================== @@ -120,32 +120,32 @@ func (h *PipelineHandler) AssignGroupToPipeline(c *gin.Context) { Role string `json:"role" binding:"required,oneof=owner editor viewer"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - var pipeline models.Pipeline + var pipeline model.Pipeline if err := h.db.First(&pipeline, pipelineID).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "流水线不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "流水线不存在"}) return } - var group models.DeployUserGroup + var group model.DeployUserGroup if err := h.db.First(&group, req.GroupID).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "用户组不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "用户组不存在"}) return } - member := models.DeployPipelineMember{ + member := model.DeployPipelineMember{ PipelineID: uint(pipelineID), GroupID: &req.GroupID, - Role: models.MemberRole(req.Role), + Role: model.MemberRole(req.Role), } if err := h.db.Create(&member).Error; err != nil { - c.JSON(http.StatusConflict, models.Response{Code: 409, Message: "该组已被授权到此流水线"}) + c.JSON(http.StatusConflict, model.Response{Code: 409, Message: "该组已被授权到此流水线"}) return } // 预加载关联 member.Group = &group - c.JSON(http.StatusOK, models.Response{Code: 200, Data: member, Message: "已授权"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: member, Message: "已授权"}) } diff --git a/backend/internal/api/handlers/health_probe.go b/backend/controller/health_probe.go similarity index 69% rename from backend/internal/api/handlers/health_probe.go rename to backend/controller/health_probe.go index d4a8d5e..4eaf87c 100644 --- a/backend/internal/api/handlers/health_probe.go +++ b/backend/controller/health_probe.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "net/http" "strconv" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -17,7 +17,7 @@ import ( // ListHealthProbes GET /api/v1/agent/health-probes func (h *AgentHandler) ListHealthProbes(c *gin.Context) { - query := h.db.Model(&models.HealthProbe{}) + query := h.db.Model(&model.HealthProbe{}) if hostname := c.Query("hostname"); hostname != "" { query = query.Where("hostname = ?", hostname) @@ -30,14 +30,14 @@ func (h *AgentHandler) ListHealthProbes(c *gin.Context) { } } - var probes []models.HealthProbe + var probes []model.HealthProbe query.Order("created_at DESC").Limit(500).Find(&probes) if probes == nil { - probes = []models.HealthProbe{} + probes = []model.HealthProbe{} } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: probes, @@ -46,42 +46,42 @@ func (h *AgentHandler) ListHealthProbes(c *gin.Context) { // CreateHealthProbe POST /api/v1/agent/health-probes func (h *AgentHandler) CreateHealthProbe(c *gin.Context) { - var probe models.HealthProbe + var probe model.HealthProbe if err := c.ShouldBindJSON(&probe); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } if probe.Name == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "探针名称不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "探针名称不能为空"}) return } if probe.Hostname == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "目标主机不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "目标主机不能为空"}) return } if probe.ProbeType == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "探针类型不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "探针类型不能为空"}) return } // 验证探针类型配置 switch probe.ProbeType { - case models.ProbeTypeHTTP: + case model.ProbeTypeHTTP: if probe.HTTPURL == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "HTTP 探针必须填写 URL"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "HTTP 探针必须填写 URL"}) return } - case models.ProbeTypeTCP: + case model.ProbeTypeTCP: if probe.TCPHost == "" || probe.TCPPort == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "TCP 探针必须填写 Host 和 Port"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "TCP 探针必须填写 Host 和 Port"}) return } - case models.ProbeTypeExec: + case model.ProbeTypeExec: if probe.ExecCommand == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "Exec 探针必须填写执行命令"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "Exec 探针必须填写执行命令"}) return } default: - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "不支持的探针类型: " + string(probe.ProbeType)}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "不支持的探针类型: " + string(probe.ProbeType)}) return } @@ -95,25 +95,25 @@ func (h *AgentHandler) CreateHealthProbe(c *gin.Context) { } if err := h.db.Create(&probe).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: probe}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "创建成功", Data: probe}) } // UpdateHealthProbe PUT /api/v1/agent/health-probes/:id func (h *AgentHandler) UpdateHealthProbe(c *gin.Context) { id := c.Param("id") - var probe models.HealthProbe + var probe model.HealthProbe if err := h.db.First(&probe, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "探针不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "探针不存在"}) return } - var input models.HealthProbe + var input model.HealthProbe if err := c.ShouldBindJSON(&input); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } @@ -164,22 +164,22 @@ func (h *AgentHandler) UpdateHealthProbe(c *gin.Context) { } if err := h.db.Model(&probe).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "更新失败: " + err.Error()}) return } h.db.First(&probe, id) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: probe}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功", Data: probe}) } // DeleteHealthProbe DELETE /api/v1/agent/health-probes/:id func (h *AgentHandler) DeleteHealthProbe(c *gin.Context) { id := c.Param("id") - if err := h.db.Delete(&models.HealthProbe{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if err := h.db.Delete(&model.HealthProbe{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // GetHealthProbesForAgent Agent 拉取本机探针配置(Agent 调用,无需 JWT) @@ -187,20 +187,20 @@ func (h *AgentHandler) DeleteHealthProbe(c *gin.Context) { func (h *AgentHandler) GetHealthProbesForAgent(c *gin.Context) { hostname := c.Query("hostname") if hostname == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "hostname 不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "hostname 不能为空"}) return } - var probes []models.HealthProbe + var probes []model.HealthProbe h.db.Where("hostname = ? AND enabled = ?", hostname, true). Order("id ASC"). Find(&probes) if probes == nil { - probes = []models.HealthProbe{} + probes = []model.HealthProbe{} } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: probes, @@ -212,7 +212,7 @@ func (h *AgentHandler) GetHealthProbesForAgent(c *gin.Context) { // ──────────────────────────────────────── // processProbeResults 处理 Agent 上报的探针结果,更新探针状态 -func (h *AgentHandler) processProbeResults(hostname string, results []models.HealthProbeResult) { +func (h *AgentHandler) processProbeResults(hostname string, results []model.HealthProbeResult) { now := time.Now() for _, r := range results { updates := map[string]interface{}{ @@ -221,9 +221,9 @@ func (h *AgentHandler) processProbeResults(hostname string, results []models.Hea "last_latency_ms": r.LatencyMs, } - if r.Status == models.ProbeStatusDown { + if r.Status == model.ProbeStatusDown { // 失败时增加连续失败计数 - h.db.Model(&models.HealthProbe{}). + h.db.Model(&model.HealthProbe{}). Where("id = ? AND hostname = ?", r.ProbeID, hostname). UpdateColumn("fail_count", gorm.Expr("fail_count + 1")) } else { @@ -231,27 +231,27 @@ func (h *AgentHandler) processProbeResults(hostname string, results []models.Hea updates["fail_count"] = 0 } - h.db.Model(&models.HealthProbe{}). + h.db.Model(&model.HealthProbe{}). Where("id = ? AND hostname = ?", r.ProbeID, hostname). Updates(updates) // ═══ 探针告警:Agent 本地探测 down → 平台创建告警事件 ═══ - if r.Status == models.ProbeStatusDown { + if r.Status == model.ProbeStatusDown { // 检查是否存在未恢复的同探针告警 - var existingAlert models.AgentAlert + var existingAlert model.AgentAlert h.db.Where("rule_name = ? AND hostname = ? AND metric = ? AND resolved = ?", r.Name, hostname, "health_probe", false). First(&existingAlert) if existingAlert.ID == 0 { // 获取 fail_count 判断严重级别 - var probe models.HealthProbe + var probe model.HealthProbe if err := h.db.First(&probe, r.ProbeID).Error; err == nil { severity := "warning" if probe.FailCount >= 3 { severity = "critical" } - alert := models.AgentAlert{ + alert := model.AgentAlert{ RuleName: r.Name, Hostname: hostname, Metric: "health_probe", @@ -265,7 +265,7 @@ func (h *AgentHandler) processProbeResults(hostname string, results []models.Hea } } else { // 探针恢复正常:自动恢复告警 - h.db.Model(&models.AgentAlert{}). + h.db.Model(&model.AgentAlert{}). Where("rule_name = ? AND hostname = ? AND metric = ? AND resolved = ?", r.Name, hostname, "health_probe", false). Updates(map[string]interface{}{ @@ -278,28 +278,28 @@ func (h *AgentHandler) processProbeResults(hostname string, results []models.Hea // probeConfigResponse ReceiveReport 的响应结构(含探针配置) type probeConfigResponse struct { - models.Response - ProbeConfigs []models.HealthProbe `json:"probe_configs,omitempty"` + model.Response + ProbeConfigs []model.HealthProbe `json:"probe_configs,omitempty"` } // makeProbeConfigResponse 构建带探针配置的响应 -func (h *AgentHandler) makeProbeConfigResponse(hostname string, respCode int, respMsg string, probeResults []models.HealthProbeResult) probeConfigResponse { +func (h *AgentHandler) makeProbeConfigResponse(hostname string, respCode int, respMsg string, probeResults []model.HealthProbeResult) probeConfigResponse { // 处理上报的探针结果 if len(probeResults) > 0 { h.processProbeResults(hostname, probeResults) } // 拉取该主机的新探针配置(供 Agent 下次执行) - var probes []models.HealthProbe + var probes []model.HealthProbe h.db.Where("hostname = ? AND enabled = ?", hostname, true). Order("id ASC"). Find(&probes) if probes == nil { - probes = []models.HealthProbe{} + probes = []model.HealthProbe{} } return probeConfigResponse{ - Response: models.Response{ + Response: model.Response{ Code: respCode, Message: respMsg, }, diff --git a/backend/internal/api/handlers/item_role.go b/backend/controller/item_role.go similarity index 53% rename from backend/internal/api/handlers/item_role.go rename to backend/controller/item_role.go index 9c2637d..961ddf4 100644 --- a/backend/internal/api/handlers/item_role.go +++ b/backend/controller/item_role.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -22,30 +22,30 @@ func NewItemRoleHandler(db *gorm.DB) *ItemRoleHandler { // ListItemRoles GET /admin/item-roles func (h *ItemRoleHandler) ListItemRoles(c *gin.Context) { - var roles []models.ItemRole + var roles []model.ItemRole h.db.Order("created_at DESC").Find(&roles) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, - Data: models.ListResponse{List: roles, Total: int64(len(roles))}, + Data: model.ListResponse{List: roles, Total: int64(len(roles))}, }) } // CreateItemRole POST /admin/item-roles func (h *ItemRoleHandler) CreateItemRole(c *gin.Context) { - var req models.CreateItemRoleRequest + var req model.CreateItemRoleRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } // 唯一性校验 - var existing models.ItemRole + var existing model.ItemRole if err := h.db.Where("name = ? OR code = ?", req.Name, req.Code).First(&existing).Error; err == nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "Item Role 名称或编码已存在"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "Item Role 名称或编码已存在"}) return } - role := models.ItemRole{ + role := model.ItemRole{ Name: req.Name, Code: req.Code, Pattern: req.Pattern, @@ -54,30 +54,30 @@ func (h *ItemRoleHandler) CreateItemRole(c *gin.Context) { Status: 1, } if err := h.db.Create(&role).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: role}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "创建成功", Data: role}) } // UpdateItemRole PUT /admin/item-roles/:id func (h *ItemRoleHandler) UpdateItemRole(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的 ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的 ID"}) return } - var req models.UpdateItemRoleRequest + var req model.UpdateItemRoleRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } - var role models.ItemRole + var role model.ItemRole if err := h.db.First(&role, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "Item Role 不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "Item Role 不存在"}) return } @@ -103,46 +103,46 @@ func (h *ItemRoleHandler) UpdateItemRole(c *gin.Context) { if len(updates) > 0 { if err := h.db.Model(&role).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "更新失败"}) return } } h.db.First(&role, id) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: role}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功", Data: role}) } // DeleteItemRole DELETE /admin/item-roles/:id func (h *ItemRoleHandler) DeleteItemRole(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的 ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的 ID"}) return } // Clean up user associations first - h.db.Where("item_role_id = ?", id).Delete(&models.UserItemRole{}) - if err := h.db.Delete(&models.ItemRole{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + h.db.Where("item_role_id = ?", id).Delete(&model.UserItemRole{}) + if err := h.db.Delete(&model.ItemRole{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // ListUserItemRoles GET /admin/users/:id/item-roles func (h *ItemRoleHandler) ListUserItemRoles(c *gin.Context) { userID, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的用户 ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的用户 ID"}) return } - var assignments []models.UserItemRole + var assignments []model.UserItemRole h.db.Preload("ItemRole").Where("user_id = ?", userID).Find(&assignments) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, - Data: models.ListResponse{List: assignments, Total: int64(len(assignments))}, + Data: model.ListResponse{List: assignments, Total: int64(len(assignments))}, }) } @@ -150,52 +150,52 @@ func (h *ItemRoleHandler) ListUserItemRoles(c *gin.Context) { func (h *ItemRoleHandler) AssignItemRole(c *gin.Context) { userID, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的用户 ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的用户 ID"}) return } - var req models.AssignItemRoleRequest + var req model.AssignItemRoleRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } // Check if already assigned - var existing models.UserItemRole + var existing model.UserItemRole if err := h.db.Where("user_id = ? AND item_role_id = ?", userID, req.ItemRoleID).First(&existing).Error; err == nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "该用户已拥有此 Item Role"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "该用户已拥有此 Item Role"}) return } - assignment := models.UserItemRole{ + assignment := model.UserItemRole{ UserID: uint(userID), ItemRoleID: req.ItemRoleID, } if err := h.db.Create(&assignment).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "分配失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "分配失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "分配成功", Data: assignment}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "分配成功", Data: assignment}) } // RemoveItemRole DELETE /admin/users/:id/item-roles/:roleId func (h *ItemRoleHandler) RemoveItemRole(c *gin.Context) { userID, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的用户 ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的用户 ID"}) return } roleID, err := strconv.Atoi(c.Param("roleId")) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的 Role ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的 Role ID"}) return } - if err := h.db.Where("user_id = ? AND item_role_id = ?", uint(userID), roleID).Delete(&models.UserItemRole{}).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "移除失败"}) + if err := h.db.Where("user_id = ? AND item_role_id = ?", uint(userID), roleID).Delete(&model.UserItemRole{}).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "移除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "移除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "移除成功"}) } diff --git a/backend/internal/api/handlers/k8s_cluster.go b/backend/controller/k8s_cluster.go similarity index 82% rename from backend/internal/api/handlers/k8s_cluster.go rename to backend/controller/k8s_cluster.go index 7915300..6746f0a 100644 --- a/backend/internal/api/handlers/k8s_cluster.go +++ b/backend/controller/k8s_cluster.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" @@ -8,26 +8,26 @@ import ( "strconv" "time" - "ezops/internal/models" + "ezops/model" k8sclient "ezops/pkg/kubernetesclient" "github.com/gin-gonic/gin" ) func (h *KubernetesHandler) ListClusters(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) var total int64 - h.db.Model(&models.KubernetesCluster{}).Count(&total) + h.db.Model(&model.KubernetesCluster{}).Count(&total) - var clusters []models.KubernetesCluster + var clusters []model.KubernetesCluster h.db.Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&clusters) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: clusters, Total: total, }, @@ -41,21 +41,21 @@ func (h *KubernetesHandler) ListClusters(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "集群ID" -// @Success 200 {object} models.Response{data=models.KubernetesCluster} +// @Success 200 {object} model.Response{data=model.KubernetesCluster} // @Router /kubernetes-clusters/{id} [get] func (h *KubernetesHandler) GetCluster(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var cluster models.KubernetesCluster + var cluster model.KubernetesCluster if err := h.db.First(&cluster, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "集群不存在", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: cluster, @@ -69,20 +69,20 @@ func (h *KubernetesHandler) GetCluster(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateKubernetesClusterRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.KubernetesCluster} +// @Param request body model.CreateKubernetesClusterRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.KubernetesCluster} // @Router /kubernetes-clusters [post] func (h *KubernetesHandler) CreateCluster(c *gin.Context) { - var req models.CreateKubernetesClusterRequest + var req model.CreateKubernetesClusterRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - cluster := models.KubernetesCluster{ + cluster := model.KubernetesCluster{ Name: req.Name, Code: req.Code, Version: req.Version, @@ -96,14 +96,14 @@ func (h *KubernetesHandler) CreateCluster(c *gin.Context) { } if err := h.db.Create(&cluster).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: cluster, @@ -118,8 +118,8 @@ func (h *KubernetesHandler) CreateCluster(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "集群ID" -// @Param request body models.CreateKubernetesClusterRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.KubernetesCluster} +// @Param request body model.CreateKubernetesClusterRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.KubernetesCluster} // @Router /kubernetes-clusters/{id} [put] func (h *KubernetesHandler) UpdateCluster(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) @@ -127,16 +127,16 @@ func (h *KubernetesHandler) UpdateCluster(c *gin.Context) { // 用 map 接收,避免 binding:"required" 校验 // Logan.Li var req map[string]interface{} if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var cluster models.KubernetesCluster + var cluster model.KubernetesCluster if err := h.db.First(&cluster, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "集群不存在", }) @@ -170,7 +170,7 @@ func (h *KubernetesHandler) UpdateCluster(c *gin.Context) { } if len(updates) == 0 { - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "无更新内容", Data: cluster, @@ -179,7 +179,7 @@ func (h *KubernetesHandler) UpdateCluster(c *gin.Context) { } if err := h.db.Model(&cluster).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -188,7 +188,7 @@ func (h *KubernetesHandler) UpdateCluster(c *gin.Context) { h.db.First(&cluster, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: cluster, @@ -199,9 +199,9 @@ func (h *KubernetesHandler) UpdateCluster(c *gin.Context) { func (h *KubernetesHandler) GetClusterDetail(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var cluster models.KubernetesCluster + var cluster model.KubernetesCluster if err := h.db.First(&cluster, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "集群不存在", }) @@ -209,7 +209,7 @@ func (h *KubernetesHandler) GetClusterDetail(c *gin.Context) { } // 返回时手动脱敏:token/kube_config 只返回是否存在标记,不返回原文 - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: map[string]interface{}{ @@ -245,20 +245,20 @@ func (h *KubernetesHandler) GetClusterDetail(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "集群ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /kubernetes-clusters/{id} [delete] func (h *KubernetesHandler) DeleteCluster(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.KubernetesCluster{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.KubernetesCluster{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -271,25 +271,25 @@ func (h *KubernetesHandler) DeleteCluster(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "集群ID" -// @Success 200 {object} models.Response{data=[]models.KubernetesNode} +// @Success 200 {object} model.Response{data=[]model.KubernetesNode} // @Router /kubernetes-clusters/{id}/nodes [get] func (h *KubernetesHandler) SyncCluster(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var cluster models.KubernetesCluster + var cluster model.KubernetesCluster if err := h.db.First(&cluster, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "集群不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "集群不存在"}) return } if cluster.KubeConfig == "" && cluster.Token == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "集群未配置凭证"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "集群未配置凭证"}) return } client, err := k8sclient.NewClient(cluster.KubeConfig) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "连接K8s失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "连接K8s失败: " + err.Error()}) return } @@ -370,7 +370,7 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) { // Sync pods if pods, err := client.ListPods(); err == nil { - h.db.Where("cluster_id = ?", cluster.ID).Delete(&models.KubernetesPod{}) + h.db.Where("cluster_id = ?", cluster.ID).Delete(&model.KubernetesPod{}) for _, p := range pods.Items { image := "" if len(p.Spec.Containers) > 0 { @@ -381,7 +381,7 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) { restarts = p.Status.ContainerStatuses[0].RestartCount } labelsJSON, _ := json.Marshal(p.Metadata.Labels) - h.db.Create(&models.KubernetesPod{ + h.db.Create(&model.KubernetesPod{ ClusterID: cluster.ID, Namespace: p.Metadata.Namespace, Name: p.Metadata.Name, @@ -400,14 +400,14 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) { // Sync deployments if deps, err := client.ListDeployments(); err == nil { - h.db.Where("cluster_id = ?", cluster.ID).Delete(&models.KubernetesDeployment{}) + h.db.Where("cluster_id = ?", cluster.ID).Delete(&model.KubernetesDeployment{}) for _, d := range deps.Items { image := "" if len(d.Spec.Template.Spec.Containers) > 0 { image = d.Spec.Template.Spec.Containers[0].Image } labelsJSON, _ := json.Marshal(d.Metadata.Labels) - h.db.Create(&models.KubernetesDeployment{ + h.db.Create(&model.KubernetesDeployment{ ClusterID: cluster.ID, Namespace: d.Metadata.Namespace, Name: d.Metadata.Name, @@ -425,12 +425,12 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) { // Sync services if svcs, err := client.ListServices(); err == nil { - h.db.Where("cluster_id = ?", cluster.ID).Delete(&models.KubernetesService{}) + h.db.Where("cluster_id = ?", cluster.ID).Delete(&model.KubernetesService{}) for _, s := range svcs.Items { portsJSON, _ := json.Marshal(s.Spec.Ports) selectorJSON, _ := json.Marshal(s.Spec.Selector) labelsJSON, _ := json.Marshal(s.Metadata.Labels) - h.db.Create(&models.KubernetesService{ + h.db.Create(&model.KubernetesService{ ClusterID: cluster.ID, Namespace: s.Metadata.Namespace, Name: s.Metadata.Name, @@ -446,7 +446,7 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) { // Sync ingresses if ings, err := client.ListIngresses(); err == nil { - h.db.Where("cluster_id = ?", cluster.ID).Delete(&models.KubernetesIngress{}) + h.db.Where("cluster_id = ?", cluster.ID).Delete(&model.KubernetesIngress{}) for _, ing := range ings.Items { hosts := []string{} for _, rule := range ing.Spec.Rules { @@ -462,7 +462,7 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) { } tlsHostsJSON, _ := json.Marshal(tlsHosts) labelsJSON, _ := json.Marshal(ing.Metadata.Labels) - h.db.Create(&models.KubernetesIngress{ + h.db.Create(&model.KubernetesIngress{ ClusterID: cluster.ID, Namespace: ing.Metadata.Namespace, Name: ing.Metadata.Name, @@ -485,7 +485,7 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) { "last_sync_at": &now, }) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: fmt.Sprintf("同步完成: %d nodes, %d pods, %d deployments, %d services, %d ingresses", result.Nodes, result.Pods, result.Deployments, result.Services, result.Ingresses), @@ -501,17 +501,17 @@ func (h *KubernetesHandler) SyncCluster(c *gin.Context) { func (h *KubernetesHandler) ListServiceAccountsNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) if clusterID == 0 { - c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}) + c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(500, models.Response{Code: 500, Message: err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: err.Error()}) return } sas, err := client.ListServiceAccounts(c.Param("namespace")) if err != nil { - c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } type SASummary struct { @@ -535,24 +535,24 @@ func (h *KubernetesHandler) ListServiceAccountsNS(c *gin.Context) { Age: formatAge(sa.Metadata.CreationTimestamp), }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ListRolesNS lists Roles in a namespace func (h *KubernetesHandler) ListRolesNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) if clusterID == 0 { - c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}) + c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(500, models.Response{Code: 500, Message: err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: err.Error()}) return } roles, err := client.ListRoles(c.Param("namespace")) if err != nil { - c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } type RoleSummary struct { @@ -591,24 +591,24 @@ func (h *KubernetesHandler) ListRolesNS(c *gin.Context) { Age: formatAge(r.Metadata.CreationTimestamp), }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ListRoleBindingsNS lists RoleBindings in a namespace func (h *KubernetesHandler) ListRoleBindingsNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) if clusterID == 0 { - c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}) + c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(500, models.Response{Code: 500, Message: err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: err.Error()}) return } rbs, err := client.ListRoleBindings(c.Param("namespace")) if err != nil { - c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } type RBSummary struct { @@ -638,5 +638,5 @@ func (h *KubernetesHandler) ListRoleBindingsNS(c *gin.Context) { Age: formatAge(rb.Metadata.CreationTimestamp), }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } diff --git a/backend/internal/api/handlers/k8s_compare.go b/backend/controller/k8s_compare.go similarity index 96% rename from backend/internal/api/handlers/k8s_compare.go rename to backend/controller/k8s_compare.go index a6c3408..773161a 100644 --- a/backend/internal/api/handlers/k8s_compare.go +++ b/backend/controller/k8s_compare.go @@ -1,16 +1,16 @@ -package handlers +package controller import ( "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) func (h *KubernetesHandler) GetMultiClusterComparison(c *gin.Context) { // 1. 获取所有集群 - var clusters []models.KubernetesCluster + var clusters []model.KubernetesCluster h.db.Find(&clusters) type ClusterComparison struct { @@ -52,7 +52,7 @@ func (h *KubernetesHandler) GetMultiClusterComparison(c *gin.Context) { } nodeAggMap := map[uint]*NodeAgg{} { - var nodes []models.KubernetesNode + var nodes []model.KubernetesNode h.db.Find(&nodes) for _, n := range nodes { agg, ok := nodeAggMap[n.ClusterID] @@ -123,7 +123,7 @@ func (h *KubernetesHandler) GetMultiClusterComparison(c *gin.Context) { } // 4. 返回结果 - c.JSON(200, models.Response{ + c.JSON(200, model.Response{ Code: 200, Message: "success", Data: gin.H{ diff --git a/backend/internal/api/handlers/k8s_events.go b/backend/controller/k8s_events.go similarity index 89% rename from backend/internal/api/handlers/k8s_events.go rename to backend/controller/k8s_events.go index 2f25ff8..37a804a 100644 --- a/backend/internal/api/handlers/k8s_events.go +++ b/backend/controller/k8s_events.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "fmt" @@ -6,21 +6,21 @@ import ( "strconv" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) func (h *KubernetesHandler) ListEvents(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Query("namespace") eventType := c.Query("type") // Normal or Warning events, err := client.ListEvents(ns) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type EventSummary struct { Namespace string `json:"namespace"` @@ -48,7 +48,7 @@ func (h *KubernetesHandler) ListEvents(c *gin.Context) { FirstTime: firstTime, LastTime: lastTime, }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ============================================================================ @@ -59,19 +59,19 @@ func (h *KubernetesHandler) ListEvents(c *gin.Context) { func (h *KubernetesHandler) GetEventsSummary(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) if clusterID == 0 { - c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}) + c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(500, models.Response{Code: 500, Message: err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: err.Error()}) return } ns := c.Query("namespace") events, err := client.ListEvents(ns) if err != nil { - c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } @@ -197,7 +197,7 @@ func (h *KubernetesHandler) GetEventsSummary(c *gin.Context) { "recent_warnings": recentWarnings, } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ============================================================================ diff --git a/backend/internal/api/handlers/k8s_export.go b/backend/controller/k8s_export.go similarity index 99% rename from backend/internal/api/handlers/k8s_export.go rename to backend/controller/k8s_export.go index 13985cc..c8efe05 100644 --- a/backend/internal/api/handlers/k8s_export.go +++ b/backend/controller/k8s_export.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "archive/tar" diff --git a/backend/internal/api/handlers/k8s_hpa_cronjob.go b/backend/controller/k8s_hpa_cronjob.go similarity index 66% rename from backend/internal/api/handlers/k8s_hpa_cronjob.go rename to backend/controller/k8s_hpa_cronjob.go index 6fda6d1..5b2ccbf 100644 --- a/backend/internal/api/handlers/k8s_hpa_cronjob.go +++ b/backend/controller/k8s_hpa_cronjob.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" "strconv" - "ezops/internal/models" + "ezops/model" k8sclient "ezops/pkg/kubernetesclient" "github.com/gin-gonic/gin" @@ -15,17 +15,17 @@ func (h *KubernetesHandler) ListHPAs(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } hpas, err := client.ListHPAs() if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: hpas.Items}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: hpas.Items}) } // CreateHPA 创建 HPA @@ -34,27 +34,27 @@ func (h *KubernetesHandler) CreateHPA(c *gin.Context) { var req k8sclient.CreateHPARequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } if req.Name == "" || req.Namespace == "" || req.TargetName == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "name/namespace/targetName 必填"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "name/namespace/targetName 必填"}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } hpa, err := client.CreateHPA(req) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建 HPA 失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建 HPA 失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "HPA 创建成功", Data: hpa}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "HPA 创建成功", Data: hpa}) } // DeleteHPA 删除 HPA @@ -65,16 +65,16 @@ func (h *KubernetesHandler) DeleteHPA(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } if err := client.DeleteHPA(namespace, name); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除 HPA 失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除 HPA 失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "HPA 已删除"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "HPA 已删除"}) } // ============================================================================ @@ -87,17 +87,17 @@ func (h *KubernetesHandler) ListCronJobs(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } cronjobs, err := client.ListCronJobs() if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: cronjobs.Items}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: cronjobs.Items}) } // CreateCronJob 创建 CronJob @@ -106,23 +106,23 @@ func (h *KubernetesHandler) CreateCronJob(c *gin.Context) { var req k8sclient.CreateCronJobRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } cj, err := client.CreateCronJob(req) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建 CronJob 失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建 CronJob 失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "CronJob 创建成功", Data: cj}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "CronJob 创建成功", Data: cj}) } // SuspendCronJob 暂停/恢复 CronJob @@ -138,12 +138,12 @@ func (h *KubernetesHandler) SuspendCronJob(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } if err := client.SuspendCronJob(namespace, name, req.Suspend); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "操作失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "操作失败: " + err.Error()}) return } @@ -151,7 +151,7 @@ func (h *KubernetesHandler) SuspendCronJob(c *gin.Context) { if req.Suspend { action = "暂停" } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "CronJob 已" + action}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "CronJob 已" + action}) } // DeleteCronJob 删除 CronJob @@ -162,16 +162,16 @@ func (h *KubernetesHandler) DeleteCronJob(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } if err := client.DeleteCronJob(namespace, name); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除 CronJob 失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除 CronJob 失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "CronJob 已删除"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "CronJob 已删除"}) } // TriggerCronJob 手动触发 CronJob @@ -182,16 +182,16 @@ func (h *KubernetesHandler) TriggerCronJob(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } if err := client.TriggerCronJob(namespace, name); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "触发失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "触发失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "手动触发成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "手动触发成功"}) } // ============================================================================ @@ -227,9 +227,9 @@ func (h *KubernetesHandler) listHPAsWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } hpas, err := client.ListHPAs() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type HPASummary struct { Namespace string `json:"namespace"` Name string `json:"name"` @@ -263,84 +263,84 @@ func (h *KubernetesHandler) listHPAsWithNS(c *gin.Context, ns string) { CurrentReplicas: h.Status.CurrentReplicas, }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } func (h *KubernetesHandler) createHPAWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } var req k8sclient.CreateHPARequest - if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, models.Response{Code: 400, Message: "参数错误"}); return } + if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return } if req.Namespace == "" { req.Namespace = ns } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } hpa, err := client.CreateHPA(req) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "创建失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Data: hpa}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "创建失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Data: hpa}) } func (h *KubernetesHandler) deleteHPAWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } - if err := client.DeleteHPA(ns, c.Param("name")); err != nil { c.JSON(500, models.Response{Code: 500, Message: "删除失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "已删除"}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } + if err := client.DeleteHPA(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Message: "已删除"}) } func (h *KubernetesHandler) listCronJobsWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } cjs, err := client.ListCronJobs() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } filtered := []k8sclient.CronJobItem{} for _, cj := range cjs.Items { if cj.Metadata.Namespace == ns { filtered = append(filtered, cj) } } - c.JSON(200, models.Response{Code: 200, Data: filtered}) + c.JSON(200, model.Response{Code: 200, Data: filtered}) } func (h *KubernetesHandler) createCronJobWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } var req k8sclient.CreateCronJobRequest - if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, models.Response{Code: 400, Message: "参数错误"}); return } + if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return } if req.Namespace == "" { req.Namespace = ns } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } cj, err := client.CreateCronJob(req) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "创建失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Data: cj}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "创建失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Data: cj}) } func (h *KubernetesHandler) suspendCronJobWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } var req struct { Suspend bool `json:"suspend"` }; c.ShouldBindJSON(&req) client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } - if err := client.SuspendCronJob(ns, c.Param("name"), req.Suspend); err != nil { c.JSON(500, models.Response{Code: 500, Message: "操作失败: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } + if err := client.SuspendCronJob(ns, c.Param("name"), req.Suspend); err != nil { c.JSON(500, model.Response{Code: 500, Message: "操作失败: " + err.Error()}); return } action := "恢复"; if req.Suspend { action = "暂停" } - c.JSON(200, models.Response{Code: 200, Message: "CronJob 已" + action}) + c.JSON(200, model.Response{Code: 200, Message: "CronJob 已" + action}) } func (h *KubernetesHandler) triggerCronJobWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } - if err := client.TriggerCronJob(ns, c.Param("name")); err != nil { c.JSON(500, models.Response{Code: 500, Message: "触发失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "手动触发成功"}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } + if err := client.TriggerCronJob(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "触发失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Message: "手动触发成功"}) } func (h *KubernetesHandler) deleteCronJobWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } - if err := client.DeleteCronJob(ns, c.Param("name")); err != nil { c.JSON(500, models.Response{Code: 500, Message: "删除失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "已删除"}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } + if err := client.DeleteCronJob(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Message: "已删除"}) } func (h *KubernetesHandler) ListHPAsAllNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } hpas, err := client.ListHPAs() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type HPASummary struct { Namespace string `json:"namespace"` Name string `json:"name"` @@ -373,7 +373,7 @@ func (h *KubernetesHandler) ListHPAsAllNS(c *gin.Context) { CurrentReplicas: h.Status.CurrentReplicas, }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ============================================================================ diff --git a/backend/internal/api/handlers/k8s_namespace.go b/backend/controller/k8s_namespace.go similarity index 78% rename from backend/internal/api/handlers/k8s_namespace.go rename to backend/controller/k8s_namespace.go index d437398..57bb4fd 100644 --- a/backend/internal/api/handlers/k8s_namespace.go +++ b/backend/controller/k8s_namespace.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" "strconv" - "ezops/internal/models" + "ezops/model" k8sclient "ezops/pkg/kubernetesclient" "github.com/gin-gonic/gin" @@ -19,17 +19,17 @@ func (h *KubernetesHandler) ListNamespaces(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } namespaces, err := client.ListNamespaces() if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: namespaces}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: namespaces}) } // ============================================================================ @@ -57,18 +57,18 @@ func (h *KubernetesHandler) GetNamespacesDetail(c *gin.Context) { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } if clusterID == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "cluster not specified"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "cluster not specified"}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } nsList, err := client.ListNamespacesDetailed() if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } @@ -135,7 +135,7 @@ func (h *KubernetesHandler) GetNamespacesDetail(c *gin.Context) { result = append(result, nd) } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: result}) } // GetNamespaceDetailHandler returns a single namespace detail with quota info @@ -145,7 +145,7 @@ func (h *KubernetesHandler) GetNamespaceDetailHandler(c *gin.Context) { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } if clusterID == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "cluster not specified"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "cluster not specified"}) return } nsName := c.Param("namespace") @@ -155,13 +155,13 @@ func (h *KubernetesHandler) GetNamespaceDetailHandler(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } ns, err := client.GetNamespace(nsName) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } @@ -210,7 +210,7 @@ func (h *KubernetesHandler) GetNamespaceDetailHandler(c *gin.Context) { nd.LimitRanges = lrs } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: nd}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: nd}) } // CreateNamespaceHandler creates a new namespace @@ -220,7 +220,7 @@ func (h *KubernetesHandler) CreateNamespaceHandler(c *gin.Context) { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } if clusterID == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "cluster not specified"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "cluster not specified"}) return } @@ -229,7 +229,7 @@ func (h *KubernetesHandler) CreateNamespaceHandler(c *gin.Context) { Labels map[string]string `json:"labels"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "name is required"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "name is required"}) return } @@ -239,23 +239,23 @@ func (h *KubernetesHandler) CreateNamespaceHandler(c *gin.Context) { "default": true, "kubernetes-dashboard": true, } if systemNS[req.Name] { - c.JSON(http.StatusForbidden, models.Response{Code: 403, Message: "cannot create system namespace: " + req.Name}) + c.JSON(http.StatusForbidden, model.Response{Code: 403, Message: "cannot create system namespace: " + req.Name}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } ns, err := client.CreateNamespace(req.Name, req.Labels) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: ns, Message: "命名空间创建成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: ns, Message: "命名空间创建成功"}) } // DeleteNamespaceHandler deletes a namespace @@ -265,7 +265,7 @@ func (h *KubernetesHandler) DeleteNamespaceHandler(c *gin.Context) { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } if clusterID == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "cluster not specified"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "cluster not specified"}) return } @@ -280,22 +280,22 @@ func (h *KubernetesHandler) DeleteNamespaceHandler(c *gin.Context) { "default": true, "devops": true, } if systemNS[nsName] { - c.JSON(http.StatusForbidden, models.Response{Code: 403, Message: "禁止删除系统命名空间: " + nsName}) + c.JSON(http.StatusForbidden, model.Response{Code: 403, Message: "禁止删除系统命名空间: " + nsName}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } if err := client.DeleteNamespace(nsName); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "命名空间已删除"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "命名空间已删除"}) } // ============================================================================ diff --git a/backend/internal/api/handlers/k8s_node.go b/backend/controller/k8s_node.go similarity index 90% rename from backend/internal/api/handlers/k8s_node.go rename to backend/controller/k8s_node.go index 2601924..ab79fa2 100644 --- a/backend/internal/api/handlers/k8s_node.go +++ b/backend/controller/k8s_node.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "fmt" @@ -6,7 +6,7 @@ import ( "strconv" "strings" - "ezops/internal/models" + "ezops/model" k8sclient "ezops/pkg/kubernetesclient" "github.com/gin-gonic/gin" @@ -17,12 +17,12 @@ func (h *KubernetesHandler) ListNodes(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } nodes, err := client.ListNodes() if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } @@ -89,7 +89,7 @@ func (h *KubernetesHandler) ListNodes(c *gin.Context) { } result = append(result, s) } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: result}) } // GetNodeDetail 获取节点详情(PID/容器运行时/分配率)// M10 @@ -109,26 +109,26 @@ func (h *KubernetesHandler) GetNodeDetail(c *gin.Context) { clusterID = h.resolveClusterCode(code) } if clusterID == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "cluster not found"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "cluster not found"}) return } nodeName := c.Param("name") if nodeName == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "node name required"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "node name required"}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } // 1. Get node detail node, err := client.GetNode(nodeName) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } @@ -332,7 +332,7 @@ func (h *KubernetesHandler) GetNodeDetail(c *gin.Context) { "pods": podList, } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: detail}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: detail}) } // parseCpuToMilli converts CPU resource string to millicores (e.g. "100m"→100, "2"→2000) @@ -380,17 +380,17 @@ func parseMemToMi(val string) int64 { // @Security Bearer // @Param id path int true "集群ID" // @Param namespace query string false "命名空间" -// @Success 200 {object} models.Response{data=[]models.KubernetesPod} +// @Success 200 {object} model.Response{data=[]model.KubernetesPod} // @Router /kubernetes-clusters/{id}/pods [get] func (h *KubernetesHandler) GetCapacityAnalysis(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Query("namespace") deps, err := client.ListDeployments() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type ContainerResource struct { Name string `json:"name"` @@ -418,7 +418,7 @@ func (h *KubernetesHandler) GetCapacityAnalysis(c *gin.Context) { } result = append(result, CapacityRow{d.Metadata.Namespace, d.Metadata.Name, d.Spec.Replicas, containers}) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ============================================================================ diff --git a/backend/internal/api/handlers/k8s_pod.go b/backend/controller/k8s_pod.go similarity index 83% rename from backend/internal/api/handlers/k8s_pod.go rename to backend/controller/k8s_pod.go index e6217d8..ab89a3a 100644 --- a/backend/internal/api/handlers/k8s_pod.go +++ b/backend/controller/k8s_pod.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" @@ -11,7 +11,7 @@ import ( "strings" "time" - "ezops/internal/models" + "ezops/model" k8sclient "ezops/pkg/kubernetesclient" "github.com/gin-gonic/gin" @@ -24,12 +24,12 @@ func (h *KubernetesHandler) ListPods(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } pods, err := client.ListPods() if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } @@ -75,7 +75,7 @@ func (h *KubernetesHandler) ListPods(c *gin.Context) { } result = append(result, ps) } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: result}) } // ListDeployments 获取Deployment列表 @@ -86,7 +86,7 @@ func (h *KubernetesHandler) ListPods(c *gin.Context) { // @Security Bearer // @Param id path int true "集群ID" // @Param namespace query string false "命名空间" -// @Success 200 {object} models.Response{data=[]models.KubernetesDeployment} +// @Success 200 {object} model.Response{data=[]model.KubernetesDeployment} // @Router /kubernetes-clusters/{id}/deployments [get] func (h *KubernetesHandler) GetPodLogs(c *gin.Context) { clusterID, _ := strconv.Atoi(c.Param("id")) @@ -98,7 +98,7 @@ func (h *KubernetesHandler) GetPodLogs(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } @@ -106,7 +106,7 @@ func (h *KubernetesHandler) GetPodLogs(c *gin.Context) { // Real-time streaming via chunked transfer body, err := client.GetPodLogsStream(namespace, podName, container, tailLines) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "获取日志流失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "获取日志流失败: " + err.Error()}) return } defer body.Close() @@ -133,11 +133,11 @@ func (h *KubernetesHandler) GetPodLogs(c *gin.Context) { logs, err := client.GetPodLogs(namespace, podName, container, tailLines) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "获取日志失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "获取日志失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{"logs": logs, "pod": podName, "namespace": namespace}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"logs": logs, "pod": podName, "namespace": namespace}}) } // ============================================================================ @@ -171,7 +171,7 @@ func (h *KubernetesHandler) ExecTerminal(c *gin.Context) { client, cluster, err := h.getK8sClientByCode(c) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } @@ -207,7 +207,7 @@ func (h *KubernetesHandler) ExecTerminal(c *gin.Context) { k8sConn, _, err := k8sDialer.Dial(execURL, k8sHeader) if err != nil { log.Printf("[K8sExec] dial K8s exec WS failed: %v", err) - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s exec 连接失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s exec 连接失败: " + err.Error()}) return } defer k8sConn.Close() @@ -308,27 +308,27 @@ func (h *KubernetesHandler) ExecInPod(c *gin.Context) { Container string `json:"container"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"}) return } if len(req.Command) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "command 不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "command 不能为空"}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } result, err := client.ExecInPod(namespace, podName, req.Container, req.Command) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "执行失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "执行失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: result}) } // ============================================================================ @@ -351,9 +351,9 @@ func (h *KubernetesHandler) listPodsWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } pods, err := client.ListPods() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } // M2: inject pod metrics (best-effort) // Logan.Li podMetrics := buildPodMetricsMap(client, ns) type PodSummary struct { @@ -387,7 +387,7 @@ func (h *KubernetesHandler) listPodsWithNS(c *gin.Context, ns string) { } result = append(result, ps) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } func (h *KubernetesHandler) getPodLogsWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) @@ -409,10 +409,10 @@ func (h *KubernetesHandler) getPodLogsWithNS(c *gin.Context, ns string) { Previous: c.Query("previous") == "true", } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } if stream { body, err := client.GetPodLogsStreamWithOptions(ns, podName, opts) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "获取日志流失败: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "获取日志流失败: " + err.Error()}); return } defer body.Close() c.Header("Content-Type", "text/plain; charset=utf-8") c.Header("Cache-Control", "no-cache") @@ -424,20 +424,20 @@ func (h *KubernetesHandler) getPodLogsWithNS(c *gin.Context, ns string) { return } logs, err := client.GetPodLogsWithOptions(ns, podName, opts) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "获取日志失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "success", Data: gin.H{"logs": logs, "pod": podName, "namespace": ns}}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "获取日志失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Message: "success", Data: gin.H{"logs": logs, "pod": podName, "namespace": ns}}) } func (h *KubernetesHandler) execInPodWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } podName := c.Param("podName") var req struct { Command []string `json:"command"`; Container string `json:"container"` } - if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, models.Response{Code: 400, Message: "参数错误"}); return } + if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } result, err := client.ExecInPod(ns, podName, req.Container, req.Command) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "执行失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Data: result}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "执行失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Data: result}) } // ============================================================================ @@ -447,11 +447,11 @@ func (h *KubernetesHandler) execInPodWithNS(c *gin.Context, ns string) { // ListDeploymentsAllNS lists all deployments across all namespaces using clusterCode. func (h *KubernetesHandler) ListPodsAllNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } pods, err := client.ListPods() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } // M2: inject pod metrics (best-effort) // Logan.Li podMetrics := buildPodMetricsMap(client, "") type PodSummary struct { @@ -484,7 +484,7 @@ func (h *KubernetesHandler) ListPodsAllNS(c *gin.Context) { } result = append(result, ps) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ListHPAsAllNS lists all HPAs across all namespaces using clusterCode. @@ -585,13 +585,13 @@ func parseMemKiToMi(raw string) int { // GetResourceYAMLNS returns the YAML of a K8s resource func (h *KubernetesHandler) GetPodMetrics(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Query("namespace") metrics, err := client.ListPodMetrics(ns) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "metrics API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "metrics API error: " + err.Error()}); return } type ContainerMetric struct { Name string `json:"name"` @@ -611,7 +611,7 @@ func (h *KubernetesHandler) GetPodMetrics(c *gin.Context) { } result = append(result, PodMetric{pm.Metadata.Namespace, pm.Metadata.Name, containers}) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ============================================================================ @@ -626,13 +626,13 @@ func (h *KubernetesHandler) deletePodWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } podName := c.Param("podName") - if podName == "" { c.JSON(400, models.Response{Code: 400, Message: "缺少 podName"}); return } + if podName == "" { c.JSON(400, model.Response{Code: 400, Message: "缺少 podName"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } if err := client.DeletePod(ns, podName); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "删除 Pod 失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "删除 Pod 失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: fmt.Sprintf("Pod %s 已删除", podName)}) + c.JSON(200, model.Response{Code: 200, Message: fmt.Sprintf("Pod %s 已删除", podName)}) } // ============================================================================ diff --git a/backend/internal/api/handlers/k8s_pod_files.go b/backend/controller/k8s_pod_files.go similarity index 82% rename from backend/internal/api/handlers/k8s_pod_files.go rename to backend/controller/k8s_pod_files.go index e83341b..cc87dad 100644 --- a/backend/internal/api/handlers/k8s_pod_files.go +++ b/backend/controller/k8s_pod_files.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/base64" @@ -9,7 +9,7 @@ import ( "strconv" "strings" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -25,14 +25,14 @@ func (h *KubernetesHandler) listPodFilesWithNS(c *gin.Context, ns string) { Path string `json:"path"` Container string `json:"container"` } - if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, models.Response{Code: 400, Message: "参数错误: " + err.Error()}); return } + if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误: " + err.Error()}); return } if req.Path == "" { req.Path = "/" } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } // ls -la — BusyBox ignores --time-style, use default "Mon DD HH:MM" format cmd := []string{"ls", "-la", req.Path} result, err := client.ExecInPod(ns, podName, req.Container, cmd) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "执行 ls 失败: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "执行 ls 失败: " + err.Error()}); return } type FileInfo struct { Name string `json:"name"` @@ -73,7 +73,7 @@ func (h *KubernetesHandler) listPodFilesWithNS(c *gin.Context, ns string) { IsDir: mode[0] == 'd', }) } - c.JSON(200, models.Response{Code: 200, Message: "success", Data: gin.H{"path": req.Path, "files": files}}) + c.JSON(200, model.Response{Code: 200, Message: "success", Data: gin.H{"path": req.Path, "files": files}}) } // DownloadPodFileNS 下载 Pod 内指定路径的文件(通过 exec cat) @@ -86,12 +86,12 @@ func (h *KubernetesHandler) downloadPodFileWithNS(c *gin.Context, ns string) { podName := c.Param("podName") filePath := c.Query("path") container := c.Query("container") - if filePath == "" { c.JSON(400, models.Response{Code: 400, Message: "path 参数不能为空"}); return } + if filePath == "" { c.JSON(400, model.Response{Code: 400, Message: "path 参数不能为空"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } cmd := []string{"cat", filePath} result, err := client.ExecInPod(ns, podName, container, cmd) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "读取文件失败: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "读取文件失败: " + err.Error()}); return } content := result.Stdout fileName := path.Base(filePath) c.Header("Content-Disposition", fmt.Sprintf("attachment; filename=\"%s\"", fileName)) @@ -118,7 +118,7 @@ func (h *KubernetesHandler) uploadPodFileWithNS(c *gin.Context, ns string) { // 读取上传的文件 file, header, err := c.Request.FormFile("file") if err != nil { - c.JSON(400, models.Response{Code: 400, Message: "文件上传失败: " + err.Error()}) + c.JSON(400, model.Response{Code: 400, Message: "文件上传失败: " + err.Error()}) return } defer file.Close() @@ -126,19 +126,19 @@ func (h *KubernetesHandler) uploadPodFileWithNS(c *gin.Context, ns string) { // 限制文件大小 10MB const maxUploadSize = 10 << 20 // 10MB if header.Size > maxUploadSize { - c.JSON(400, models.Response{Code: 400, Message: fmt.Sprintf("文件过大: %d bytes, 上限 %d bytes", header.Size, maxUploadSize)}) + c.JSON(400, model.Response{Code: 400, Message: fmt.Sprintf("文件过大: %d bytes, 上限 %d bytes", header.Size, maxUploadSize)}) return } content, err := io.ReadAll(file) if err != nil { - c.JSON(500, models.Response{Code: 500, Message: "读取文件失败: " + err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: "读取文件失败: " + err.Error()}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(500, models.Response{Code: 500, Message: err.Error()}) + c.JSON(500, model.Response{Code: 500, Message: err.Error()}) return } @@ -173,7 +173,7 @@ func (h *KubernetesHandler) uploadPodFileWithNS(c *gin.Context, ns string) { if result != nil { stderr = result.Stderr } - c.JSON(500, models.Response{Code: 500, Message: fmt.Sprintf("写入文件失败 (chunk %d): %s\n%s", i/chunkSize, err.Error(), stderr)}) + c.JSON(500, model.Response{Code: 500, Message: fmt.Sprintf("写入文件失败 (chunk %d): %s\n%s", i/chunkSize, err.Error(), stderr)}) return } } @@ -187,7 +187,7 @@ func (h *KubernetesHandler) uploadPodFileWithNS(c *gin.Context, ns string) { log.Printf("[UploadPodFile] %s/%s → %s (%d bytes, %d chunks)", ns, podName, targetFile, len(content), (len(encoded)+chunkSize-1)/chunkSize) - c.JSON(200, models.Response{ + c.JSON(200, model.Response{ Code: 200, Message: "上传成功", Data: gin.H{ diff --git a/backend/internal/api/handlers/k8s_resource.go b/backend/controller/k8s_resource.go similarity index 76% rename from backend/internal/api/handlers/k8s_resource.go rename to backend/controller/k8s_resource.go index ef4bb76..3d7b7ae 100644 --- a/backend/internal/api/handlers/k8s_resource.go +++ b/backend/controller/k8s_resource.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -15,12 +15,12 @@ func (h *KubernetesHandler) ListServices(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } svcs, err := client.ListServices() if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } @@ -44,7 +44,7 @@ func (h *KubernetesHandler) ListServices(c *gin.Context) { Ports: len(s.Spec.Ports), }) } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: result}) } // ListIngresses 获取Ingress列表 @@ -55,7 +55,7 @@ func (h *KubernetesHandler) ListServices(c *gin.Context) { // @Security Bearer // @Param id path int true "集群ID" // @Param namespace query string false "命名空间" -// @Success 200 {object} models.Response{data=[]models.KubernetesIngress} +// @Success 200 {object} model.Response{data=[]model.KubernetesIngress} // @Router /kubernetes-clusters/{id}/ingresses [get] func (h *KubernetesHandler) ListIngresses(c *gin.Context) { clusterID, _ := strconv.Atoi(c.Param("id")) @@ -63,12 +63,12 @@ func (h *KubernetesHandler) ListIngresses(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } ings, err := client.ListIngresses() if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } @@ -96,19 +96,19 @@ func (h *KubernetesHandler) ListIngresses(c *gin.Context) { TLS: len(ing.Spec.TLS) > 0, }) } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: result}) } // GetTopology 获取集群拓扑布局 // Logan.Li func (h *KubernetesHandler) GetTopology(c *gin.Context) { clusterID := c.Param("id") - var layout models.TopologyLayout + var layout model.TopologyLayout result := h.db.Where("cluster_id = ?", clusterID).First(&layout) if result.Error != nil { - c.JSON(http.StatusOK, models.Response{Code: 200, Data: &models.TopologyLayout{}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: &model.TopologyLayout{}}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: layout}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: layout}) } // SaveTopology 保存集群拓扑布局 // Logan.Li @@ -118,11 +118,11 @@ func (h *KubernetesHandler) SaveTopology(c *gin.Context) { LayoutData string `json:"layout_data"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"}) return } - var layout models.TopologyLayout + var layout model.TopologyLayout h.db.Where("cluster_id = ?", clusterID).First(&layout) layout.ClusterID = uint(clusterID) layout.LayoutData = req.LayoutData @@ -132,7 +132,7 @@ func (h *KubernetesHandler) SaveTopology(c *gin.Context) { h.db.Save(&layout) } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "保存成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "保存成功"}) } @@ -146,17 +146,17 @@ func (h *KubernetesHandler) ListConfigMaps(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } cms, err := client.ListConfigMaps(namespace) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: cms.Items}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: cms.Items}) } // ListSecrets 获取命名空间下的 Secret 列表(仅名称+类型,不含值) @@ -169,17 +169,17 @@ func (h *KubernetesHandler) ListSecrets(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } secrets, err := client.ListSecrets(namespace) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: secrets.Items}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: secrets.Items}) } // ============================================================================ @@ -197,9 +197,9 @@ func (h *KubernetesHandler) listServicesWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } svcs, err := client.ListServices() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type SvcPortDetail struct { Name string `json:"name,omitempty"` Port int `json:"port"` @@ -236,15 +236,15 @@ func (h *KubernetesHandler) listServicesWithNS(c *gin.Context, ns string) { Selector: s.Spec.Selector, }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } func (h *KubernetesHandler) listIngressesWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ings, err := client.ListIngresses() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type PathDetail struct { Path string `json:"path"` PathType string `json:"pathType,omitempty"` @@ -298,16 +298,16 @@ func (h *KubernetesHandler) listIngressesWithNS(c *gin.Context, ns string) { Rules: rules, }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } func (h *KubernetesHandler) ListPVCsNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") pvcs, err := client.ListPVCs(ns) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type PVCSummary struct { Namespace string `json:"namespace"` Name string `json:"name"` @@ -329,19 +329,19 @@ func (h *KubernetesHandler) ListPVCsNS(c *gin.Context) { StorageClass: p.Spec.StorageClassName, }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // DeletePVCNS deletes a PVC (code-based) func (h *KubernetesHandler) DeletePVCNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } if err := client.DeletePVC(c.Param("namespace"), c.Param("name")); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "删除失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "已删除"}) + c.JSON(200, model.Response{Code: 200, Message: "已删除"}) } // ============================================================================ diff --git a/backend/internal/api/handlers/k8s_workload.go b/backend/controller/k8s_workload.go similarity index 67% rename from backend/internal/api/handlers/k8s_workload.go rename to backend/controller/k8s_workload.go index 986efe6..7b16638 100644 --- a/backend/internal/api/handlers/k8s_workload.go +++ b/backend/controller/k8s_workload.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "fmt" @@ -6,7 +6,7 @@ import ( "sort" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -17,12 +17,12 @@ func (h *KubernetesHandler) ListDeployments(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } deps, err := client.ListDeployments() if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}) return } @@ -52,7 +52,7 @@ func (h *KubernetesHandler) ListDeployments(c *gin.Context) { Image: image, }) } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: result}) } // ListServices 获取Service列表 @@ -63,7 +63,7 @@ func (h *KubernetesHandler) ListDeployments(c *gin.Context) { // @Security Bearer // @Param id path int true "集群ID" // @Param namespace query string false "命名空间" -// @Success 200 {object} models.Response{data=[]models.KubernetesService} +// @Success 200 {object} model.Response{data=[]model.KubernetesService} // @Router /kubernetes-clusters/{id}/services [get] func (h *KubernetesHandler) ScaleDeployment(c *gin.Context) { clusterID, _ := strconv.Atoi(c.Param("id")) @@ -74,26 +74,26 @@ func (h *KubernetesHandler) ScaleDeployment(c *gin.Context) { Replicas int `json:"replicas"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"}) return } if req.Replicas < 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "副本数不能为负数"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "副本数不能为负数"}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } if err := client.ScaleDeployment(namespace, name, req.Replicas); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: fmt.Sprintf("已设置为 %d 副本", req.Replicas)}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: fmt.Sprintf("已设置为 %d 副本", req.Replicas)}) } // RestartDeployment 重启 Deployment (滚动重启) @@ -104,16 +104,16 @@ func (h *KubernetesHandler) RestartDeployment(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } if err := client.RestartDeployment(namespace, name); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "重启失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "重启失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "重启指令已下发"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "重启指令已下发"}) } // PauseDeployment 暂停 Deployment 滚动更新(spec.paused=true) @@ -124,16 +124,16 @@ func (h *KubernetesHandler) PauseDeployment(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } if err := client.PauseDeployment(namespace, name); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "暂停更新失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "暂停更新失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已暂停滚动更新"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已暂停滚动更新"}) } // ResumeDeployment 恢复 Deployment 滚动更新(spec.paused=false) @@ -144,16 +144,16 @@ func (h *KubernetesHandler) ResumeDeployment(c *gin.Context) { client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } if err := client.ResumeDeployment(namespace, name); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "恢复更新失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "恢复更新失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已恢复滚动更新"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已恢复滚动更新"}) } // ============================================================================ @@ -171,26 +171,26 @@ func (h *KubernetesHandler) UpdateDeploymentImage(c *gin.Context) { ContainerName string `json:"container_name"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"}) return } if req.Image == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "image 不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "image 不能为空"}) return } client, _, err := h.getK8sClient(clusterID) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } if err := client.UpdateDeploymentImage(namespace, name, req.ContainerName, req.Image); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新镜像失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "更新镜像失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: fmt.Sprintf("镜像已更新为 %s,正在滚动更新...", req.Image)}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: fmt.Sprintf("镜像已更新为 %s,正在滚动更新...", req.Image)}) } // ============================================================================ @@ -209,14 +209,14 @@ func (h *KubernetesHandler) GetDeploymentNS(c *gin.Context) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } deps, err := client.ListDeployments() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } for _, d := range deps.Items { if d.Metadata.Namespace == ns && d.Metadata.Name == name { image := "" if len(d.Spec.Template.Spec.Containers) > 0 { image = d.Spec.Template.Spec.Containers[0].Image } - c.JSON(200, models.Response{Code: 200, Data: map[string]interface{}{ + c.JSON(200, model.Response{Code: 200, Data: map[string]interface{}{ "namespace": d.Metadata.Namespace, "name": d.Metadata.Name, "replicas": d.Spec.Replicas, @@ -228,7 +228,7 @@ func (h *KubernetesHandler) GetDeploymentNS(c *gin.Context) { return } } - c.JSON(404, models.Response{Code: 404, Message: "Deployment not found"}) + c.JSON(404, model.Response{Code: 404, Message: "Deployment not found"}) } func (h *KubernetesHandler) ScaleDeploymentNS(c *gin.Context) { h.scaleDeploymentWithNS(c, c.Param("namespace")) @@ -249,9 +249,9 @@ func (h *KubernetesHandler) listDeploymentsWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } deps, err := client.ListDeployments() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type DepSummary struct { Namespace string `json:"namespace"` Name string `json:"name"` @@ -277,59 +277,59 @@ func (h *KubernetesHandler) listDeploymentsWithNS(c *gin.Context, ns string) { Selector: func() map[string]string { if d.Spec.Selector != nil { return d.Spec.Selector.MatchLabels }; return nil }(), }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } func (h *KubernetesHandler) scaleDeploymentWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } var req struct { Replicas int `json:"replicas"` } - if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, models.Response{Code: 400, Message: "参数错误"}); return } + if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } - if err := client.ScaleDeployment(ns, c.Param("name"), req.Replicas); err != nil { c.JSON(500, models.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: fmt.Sprintf("已设置为 %d 副本", req.Replicas)}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } + if err := client.ScaleDeployment(ns, c.Param("name"), req.Replicas); err != nil { c.JSON(500, model.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Message: fmt.Sprintf("已设置为 %d 副本", req.Replicas)}) } func (h *KubernetesHandler) restartDeploymentWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } - if err := client.RestartDeployment(ns, c.Param("name")); err != nil { c.JSON(500, models.Response{Code: 500, Message: "重启失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "重启指令已下发"}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } + if err := client.RestartDeployment(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Message: "重启指令已下发"}) } func (h *KubernetesHandler) updateDeploymentImageWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } var req struct { Image string `json:"image"`; ContainerName string `json:"container_name"` } - if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, models.Response{Code: 400, Message: "参数错误"}); return } + if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } - if err := client.UpdateDeploymentImage(ns, c.Param("name"), req.ContainerName, req.Image); err != nil { c.JSON(500, models.Response{Code: 500, Message: "更新镜像失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: fmt.Sprintf("镜像已更新为 %s", req.Image)}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } + if err := client.UpdateDeploymentImage(ns, c.Param("name"), req.ContainerName, req.Image); err != nil { c.JSON(500, model.Response{Code: 500, Message: "更新镜像失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Message: fmt.Sprintf("镜像已更新为 %s", req.Image)}) } func (h *KubernetesHandler) pauseDeploymentWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } - if err := client.PauseDeployment(ns, c.Param("name")); err != nil { c.JSON(500, models.Response{Code: 500, Message: "暂停更新失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "已暂停滚动更新"}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } + if err := client.PauseDeployment(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "暂停更新失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Message: "已暂停滚动更新"}) } func (h *KubernetesHandler) resumeDeploymentWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } - if err := client.ResumeDeployment(ns, c.Param("name")); err != nil { c.JSON(500, models.Response{Code: 500, Message: "恢复更新失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "已恢复滚动更新"}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } + if err := client.ResumeDeployment(ns, c.Param("name")); err != nil { c.JSON(500, model.Response{Code: 500, Message: "恢复更新失败: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Message: "已恢复滚动更新"}) } func (h *KubernetesHandler) ListDeploymentsAllNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } deps, err := client.ListDeployments() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type DepSummary struct { Namespace string `json:"namespace"` Name string `json:"name"` @@ -350,17 +350,17 @@ func (h *KubernetesHandler) ListDeploymentsAllNS(c *gin.Context) { Image: image, }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ListPodsAllNS lists all pods across all namespaces using clusterCode. func (h *KubernetesHandler) ListStatefulSetsNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } sts, err := client.ListStatefulSets() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } ns := c.Param("namespace") type StsSummary struct { Namespace string `json:"namespace"` @@ -381,17 +381,17 @@ func (h *KubernetesHandler) ListStatefulSetsNS(c *gin.Context) { Image: image, }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ListDaemonSetsNS lists DaemonSets in a namespace func (h *KubernetesHandler) ListDaemonSetsNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ds, err := client.ListDaemonSets() - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } ns := c.Param("namespace") type DsSummary struct { Namespace string `json:"namespace"` @@ -414,123 +414,123 @@ func (h *KubernetesHandler) ListDaemonSetsNS(c *gin.Context) { Image: image, }) } - c.JSON(200, models.Response{Code: 200, Data: result}) + c.JSON(200, model.Response{Code: 200, Data: result}) } // ScaleStatefulSetNS scales a StatefulSet (Kuboard code route) func (h *KubernetesHandler) ScaleStatefulSetNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") name := c.Param("name") var req struct{ Replicas int `json:"replicas"` } - if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, models.Response{Code: 400, Message: "参数错误"}); return } + if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return } if err := client.ScaleStatefulSet(ns, name, req.Replicas); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "StatefulSet 副本数已更新为 " + strconv.Itoa(req.Replicas)}) + c.JSON(200, model.Response{Code: 200, Message: "StatefulSet 副本数已更新为 " + strconv.Itoa(req.Replicas)}) } // ScaleStatefulSet scales a StatefulSet (ID route) func (h *KubernetesHandler) ScaleStatefulSet(c *gin.Context) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") name := c.Param("name") var req struct{ Replicas int `json:"replicas"` } - if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, models.Response{Code: 400, Message: "参数错误"}); return } + if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误"}); return } if err := client.ScaleStatefulSet(ns, name, req.Replicas); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "扩缩容失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "StatefulSet 副本数已更新为 " + strconv.Itoa(req.Replicas)}) + c.JSON(200, model.Response{Code: 200, Message: "StatefulSet 副本数已更新为 " + strconv.Itoa(req.Replicas)}) } // RestartStatefulSetNS restarts a StatefulSet (Kuboard code route) func (h *KubernetesHandler) RestartStatefulSetNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") name := c.Param("name") if err := client.RestartStatefulSet(ns, name); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "重启失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "StatefulSet 滚动重启已触发"}) + c.JSON(200, model.Response{Code: 200, Message: "StatefulSet 滚动重启已触发"}) } // RestartStatefulSet restarts a StatefulSet (ID route) func (h *KubernetesHandler) RestartStatefulSet(c *gin.Context) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") name := c.Param("name") if err := client.RestartStatefulSet(ns, name); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "重启失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "StatefulSet 滚动重启已触发"}) + c.JSON(200, model.Response{Code: 200, Message: "StatefulSet 滚动重启已触发"}) } // RestartDaemonSetNS restarts a DaemonSet (Kuboard code route) func (h *KubernetesHandler) RestartDaemonSetNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") name := c.Param("name") if err := client.RestartDaemonSet(ns, name); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "重启失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "DaemonSet 滚动重启已触发"}) + c.JSON(200, model.Response{Code: 200, Message: "DaemonSet 滚动重启已触发"}) } // RestartDaemonSet restarts a DaemonSet (ID route) func (h *KubernetesHandler) RestartDaemonSet(c *gin.Context) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") name := c.Param("name") if err := client.RestartDaemonSet(ns, name); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "重启失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "重启失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "DaemonSet 滚动重启已触发"}) + c.JSON(200, model.Response{Code: 200, Message: "DaemonSet 滚动重启已触发"}) } // GetStatefulSetDetailNS returns a single StatefulSet detail (Kuboard code route) func (h *KubernetesHandler) GetStatefulSetDetailNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") name := c.Param("name") sts, err := client.GetStatefulSet(ns, name) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Data: sts}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Data: sts}) } // GetDaemonSetDetailNS returns a single DaemonSet detail (Kuboard code route) func (h *KubernetesHandler) GetDaemonSetDetailNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") name := c.Param("name") ds, err := client.GetDaemonSet(ns, name) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Data: ds}) + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + c.JSON(200, model.Response{Code: 200, Data: ds}) } // ============================================================================ @@ -545,9 +545,9 @@ func (h *KubernetesHandler) listReplicaSetsWithNS(c *gin.Context, ns string) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } items, err := client.ListReplicaSetsRaw(ns) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type RSSummary struct { Namespace string `json:"namespace"` Name string `json:"name"` @@ -580,7 +580,7 @@ func (h *KubernetesHandler) listReplicaSetsWithNS(c *gin.Context, ns string) { OwnerDeployment: owner, }) } - c.JSON(200, models.Response{Code: 200, Message: "success", Data: result}) + c.JSON(200, model.Response{Code: 200, Message: "success", Data: result}) } // ListDeploymentRevisionsNS Deployment 发布历史(按 revision 倒序) @@ -591,11 +591,11 @@ func (h *KubernetesHandler) listDeploymentRevisionsWithNS(c *gin.Context, ns str clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } deploymentName := c.Param("name") - if deploymentName == "" { c.JSON(400, models.Response{Code: 400, Message: "缺少 deployment name"}); return } + if deploymentName == "" { c.JSON(400, model.Response{Code: 400, Message: "缺少 deployment name"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } items, err := client.ListReplicaSetsRaw(ns) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "K8s API error: " + err.Error()}); return } type Revision struct { Revision string `json:"revision"` ReplicaSet string `json:"replica_set"` @@ -628,7 +628,7 @@ func (h *KubernetesHandler) listDeploymentRevisionsWithNS(c *gin.Context, ns str rj, _ := strconv.Atoi(result[j].Revision) return ri > rj }) - c.JSON(200, models.Response{Code: 200, Message: "success", Data: result}) + c.JSON(200, model.Response{Code: 200, Message: "success", Data: result}) } // RollbackDeploymentNS 回滚 Deployment 到指定 revision 或指定 ReplicaSet @@ -639,20 +639,20 @@ func (h *KubernetesHandler) rollbackDeploymentWithNS(c *gin.Context, ns string) clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { clusterID = h.resolveClusterCode(c.Param("clusterCode")) } deploymentName := c.Param("name") - if deploymentName == "" { c.JSON(400, models.Response{Code: 400, Message: "缺少 deployment name"}); return } + if deploymentName == "" { c.JSON(400, model.Response{Code: 400, Message: "缺少 deployment name"}); return } var req struct { Revision int `json:"revision"` ReplicaSet string `json:"replicaSet"` } _ = c.ShouldBindJSON(&req) // 允许空 body(但下面会校验) client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } targetRS := req.ReplicaSet // 通过 revision 定位 ReplicaSet if targetRS == "" && req.Revision > 0 { items, err := client.ListReplicaSetsRaw(ns) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "获取 ReplicaSet 列表失败: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "获取 ReplicaSet 列表失败: " + err.Error()}); return } for _, rs := range items { isOwner := false for _, o := range rs.Metadata.OwnerReferences { @@ -665,24 +665,24 @@ func (h *KubernetesHandler) rollbackDeploymentWithNS(c *gin.Context, ns string) } } if targetRS == "" { - c.JSON(404, models.Response{Code: 404, Message: fmt.Sprintf("revision %d 的 ReplicaSet 未找到", req.Revision)}) + c.JSON(404, model.Response{Code: 404, Message: fmt.Sprintf("revision %d 的 ReplicaSet 未找到", req.Revision)}) return } } - if targetRS == "" { c.JSON(400, models.Response{Code: 400, Message: "需要 revision 或 replicaSet 参数"}); return } + if targetRS == "" { c.JSON(400, model.Response{Code: 400, Message: "需要 revision 或 replicaSet 参数"}); return } // 取 ReplicaSet 的 template,patch 到 Deployment.spec.template 实现回滚 rsJSON, err := client.GetReplicaSet(ns, targetRS) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "获取 ReplicaSet 失败: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "获取 ReplicaSet 失败: " + err.Error()}); return } specMap, ok := rsJSON["spec"].(map[string]interface{}) - if !ok { c.JSON(500, models.Response{Code: 500, Message: "ReplicaSet 缺少 spec"}); return } + if !ok { c.JSON(500, model.Response{Code: 500, Message: "ReplicaSet 缺少 spec"}); return } template, ok := specMap["template"].(map[string]interface{}) - if !ok { c.JSON(500, models.Response{Code: 500, Message: "ReplicaSet 缺少 template"}); return } + if !ok { c.JSON(500, model.Response{Code: 500, Message: "ReplicaSet 缺少 template"}); return } if err := client.PatchDeploymentSpecTemplate(ns, deploymentName, template); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "回滚失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "回滚失败: " + err.Error()}); return } - c.JSON(200, models.Response{ + c.JSON(200, model.Response{ Code: 200, Message: fmt.Sprintf("Deployment %s 已回滚到 %s", deploymentName, targetRS), Data: gin.H{"replicaSet": targetRS, "revision": req.Revision}, diff --git a/backend/internal/api/handlers/k8s_yaml.go b/backend/controller/k8s_yaml.go similarity index 80% rename from backend/internal/api/handlers/k8s_yaml.go rename to backend/controller/k8s_yaml.go index 274e76d..d7ecfbf 100644 --- a/backend/internal/api/handlers/k8s_yaml.go +++ b/backend/controller/k8s_yaml.go @@ -1,20 +1,20 @@ -package handlers +package controller import ( "fmt" "io" "strings" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) func (h *KubernetesHandler) GetResourceYAMLNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") resource := c.Param("resource") // Fallback: specific routes (statefulsets/:name/yaml, daemonsets/:name/yaml) have no :resource param @@ -62,10 +62,10 @@ func (h *KubernetesHandler) GetResourceYAMLNS(c *gin.Context) { case "rolebindings", "rolebinding": apiPath = fmt.Sprintf("/apis/rbac.authorization.k8s.io/v1/namespaces/%s/rolebindings/%s", ns, name) default: - c.JSON(400, models.Response{Code: 400, Message: "unsupported resource type: " + resource}); return + c.JSON(400, model.Response{Code: 400, Message: "unsupported resource type: " + resource}); return } yamlBytes, err := client.GetResourceYAML(apiPath) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "获取YAML失败: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "获取YAML失败: " + err.Error()}); return } c.Header("Content-Type", "application/yaml") c.String(200, string(yamlBytes)) } @@ -73,9 +73,9 @@ func (h *KubernetesHandler) GetResourceYAMLNS(c *gin.Context) { // UpdateResourceYAMLNS applies YAML to update a K8s resource func (h *KubernetesHandler) UpdateResourceYAMLNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") resource := c.Param("resource") // Fallback: specific routes (statefulsets/:name/yaml, daemonsets/:name/yaml) have no :resource param @@ -90,7 +90,7 @@ func (h *KubernetesHandler) UpdateResourceYAMLNS(c *gin.Context) { } name := c.Param("name") yamlData, err := io.ReadAll(c.Request.Body) - if err != nil { c.JSON(400, models.Response{Code: 400, Message: "读取body失败"}); return } + if err != nil { c.JSON(400, model.Response{Code: 400, Message: "读取body失败"}); return } var apiPath string switch resource { case "deployments", "deployment": @@ -124,12 +124,12 @@ func (h *KubernetesHandler) UpdateResourceYAMLNS(c *gin.Context) { case "rolebindings", "rolebinding": apiPath = fmt.Sprintf("/apis/rbac.authorization.k8s.io/v1/namespaces/%s/rolebindings/%s", ns, name) default: - c.JSON(400, models.Response{Code: 400, Message: "unsupported resource type: " + resource}); return + c.JSON(400, model.Response{Code: 400, Message: "unsupported resource type: " + resource}); return } if err := client.UpdateResourceYAML(apiPath, yamlData); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "更新失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "更新失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "YAML已应用"}) + c.JSON(200, model.Response{Code: 200, Message: "YAML已应用"}) } // resourceAPIPath builds the K8s API path for common resource types (shared by Get/Update/Delete) @@ -173,37 +173,37 @@ func resourceAPIPath(ns, resource, name string) (string, error) { // DeleteResourceYAMLNS deletes a K8s resource (Service/Ingress/ConfigMap etc.) func (h *KubernetesHandler) DeleteResourceYAMLNS(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } ns := c.Param("namespace") resource := c.Param("resource") name := c.Param("name") apiPath, err := resourceAPIPath(ns, resource, name) - if err != nil { c.JSON(400, models.Response{Code: 400, Message: err.Error()}); return } + if err != nil { c.JSON(400, model.Response{Code: 400, Message: err.Error()}); return } if err := client.DeleteResource(apiPath); err != nil { - c.JSON(500, models.Response{Code: 500, Message: "删除失败: " + err.Error()}); return + c.JSON(500, model.Response{Code: 500, Message: "删除失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "资源已删除"}) + c.JSON(200, model.Response{Code: 200, Message: "资源已删除"}) } // getK8sClient builds a K8s API client from cluster's stored kubeconfig func (h *KubernetesHandler) ApplyYAML(c *gin.Context) { clusterID := h.resolveClusterCode(c.Param("clusterCode")) - if clusterID == 0 { c.JSON(500, models.Response{Code: 500, Message: "cluster not found"}); return } + if clusterID == 0 { c.JSON(500, model.Response{Code: 500, Message: "cluster not found"}); return } client, _, err := h.getK8sClient(clusterID) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: err.Error()}); return } var req struct { YAML string `json:"yaml"` } - if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, models.Response{Code: 400, Message: "参数错误: " + err.Error()}); return } - if req.YAML == "" { c.JSON(400, models.Response{Code: 400, Message: "YAML 内容不能为空"}); return } + if err := c.ShouldBindJSON(&req); err != nil { c.JSON(400, model.Response{Code: 400, Message: "参数错误: " + err.Error()}); return } + if req.YAML == "" { c.JSON(400, model.Response{Code: 400, Message: "YAML 内容不能为空"}); return } result, err := client.ApplyYAML(req.YAML) - if err != nil { c.JSON(500, models.Response{Code: 500, Message: "Apply 失败: " + err.Error()}); return } + if err != nil { c.JSON(500, model.Response{Code: 500, Message: "Apply 失败: " + err.Error()}); return } - c.JSON(200, models.Response{Code: 200, Message: "资源已应用", Data: result}) + c.JSON(200, model.Response{Code: 200, Message: "资源已应用", Data: result}) } // ============================================================================ diff --git a/backend/internal/api/handlers/kubectl_shell.go b/backend/controller/kubectl_shell.go similarity index 98% rename from backend/internal/api/handlers/kubectl_shell.go rename to backend/controller/kubectl_shell.go index 84454cb..d9ad4ee 100644 --- a/backend/internal/api/handlers/kubectl_shell.go +++ b/backend/controller/kubectl_shell.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "context" @@ -12,7 +12,7 @@ import ( "strconv" "syscall" - "ezops/internal/models" + "ezops/model" "ezops/pkg/toolinstaller" "github.com/creack/pty" @@ -58,7 +58,7 @@ func (h *KubectlShellHandler) Terminal(c *gin.Context) { return } - var cluster models.KubernetesCluster + var cluster model.KubernetesCluster if err := h.db.First(&cluster, id).Error; err != nil { c.JSON(http.StatusNotFound, gin.H{"error": "cluster not found"}) return diff --git a/backend/internal/api/handlers/kubernetes.go b/backend/controller/kubernetes.go similarity index 92% rename from backend/internal/api/handlers/kubernetes.go rename to backend/controller/kubernetes.go index dbde30d..307ef32 100644 --- a/backend/internal/api/handlers/kubernetes.go +++ b/backend/controller/kubernetes.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "fmt" @@ -6,7 +6,7 @@ import ( "strconv" "time" - "ezops/internal/models" + "ezops/model" k8sclient "ezops/pkg/kubernetesclient" "github.com/gin-gonic/gin" @@ -30,7 +30,7 @@ func (h *KubernetesHandler) resolveClusterCode(code string) int { if code == "" { return 0 } - var cluster models.KubernetesCluster + var cluster model.KubernetesCluster if err := h.db.Where("code = ?", code).First(&cluster).Error; err != nil { return 0 } @@ -64,7 +64,7 @@ func formatAge(creationTimestamp string) string { } // getK8sClientByCode resolves cluster by code, falls back to ID -func (h *KubernetesHandler) getK8sClientByCode(c *gin.Context) (*k8sclient.Client, *models.KubernetesCluster, error) { +func (h *KubernetesHandler) getK8sClientByCode(c *gin.Context) (*k8sclient.Client, *model.KubernetesCluster, error) { clusterID, _ := strconv.Atoi(c.Param("id")) if clusterID == 0 { // 支持 :clusterCode 或 :id 参数 @@ -84,8 +84,8 @@ func (h *KubernetesHandler) getK8sClientByCode(c *gin.Context) (*k8sclient.Clien // NS wrappers — read namespace from path (Kuboard-style routes) // ============================================================================ -func (h *KubernetesHandler) getK8sClient(clusterID int) (*k8sclient.Client, *models.KubernetesCluster, error) { - var cluster models.KubernetesCluster +func (h *KubernetesHandler) getK8sClient(clusterID int) (*k8sclient.Client, *model.KubernetesCluster, error) { + var cluster model.KubernetesCluster if err := h.db.First(&cluster, clusterID).Error; err != nil { return nil, nil, fmt.Errorf("cluster not found") } diff --git a/backend/internal/api/handlers/ldap.go b/backend/controller/ldap.go similarity index 89% rename from backend/internal/api/handlers/ldap.go rename to backend/controller/ldap.go index 3d7490f..280631f 100644 --- a/backend/internal/api/handlers/ldap.go +++ b/backend/controller/ldap.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" @@ -8,7 +8,7 @@ import ( "strings" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "github.com/go-ldap/ldap/v3" @@ -33,7 +33,7 @@ type LDAPAuthInfo struct { } // dialLDAP 连接LDAP服务器 -func dialLDAP(cfg *models.LDAPConfig) (*ldap.Conn, error) { +func dialLDAP(cfg *model.LDAPConfig) (*ldap.Conn, error) { if cfg.LDAPHost == "" { return nil, fmt.Errorf("LDAP not configured") } @@ -52,7 +52,7 @@ func dialLDAP(cfg *models.LDAPConfig) (*ldap.Conn, error) { // tryLDAPAuth 尝试LDAP认证,返回用户信息 func tryLDAPAuth(db *gorm.DB, username, password string) (*LDAPAuthInfo, error) { - var cfg models.LDAPConfig + var cfg model.LDAPConfig if err := db.Order("id").First(&cfg).Error; err != nil { return nil, fmt.Errorf("LDAP未配置") } @@ -139,7 +139,7 @@ func tryLDAPAuth(db *gorm.DB, username, password string) (*LDAPAuthInfo, error) // GetLDAPConfig 获取LDAP配置 // GET /api/v1/admin/ldap-config func (h *LDAPHandler) GetLDAPConfig(c *gin.Context) { - var configs []models.LDAPConfig + var configs []model.LDAPConfig h.db.Order("id").Find(&configs) if len(configs) == 0 { c.JSON(http.StatusOK, gin.H{}) @@ -148,7 +148,7 @@ func (h *LDAPHandler) GetLDAPConfig(c *gin.Context) { cfg := configs[0] // mask password cfg.AdminPassword = "******" - c.JSON(http.StatusOK, models.Response{Code: 200, Data: cfg}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: cfg}) } // UpdateLDAPConfig 更新LDAP配置 @@ -156,11 +156,11 @@ func (h *LDAPHandler) GetLDAPConfig(c *gin.Context) { func (h *LDAPHandler) UpdateLDAPConfig(c *gin.Context) { var input map[string]interface{} if err := c.ShouldBindJSON(&input); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - var configs []models.LDAPConfig + var configs []model.LDAPConfig h.db.Order("id").Find(&configs) getStr := func(key string) string { @@ -191,7 +191,7 @@ func (h *LDAPHandler) UpdateLDAPConfig(c *gin.Context) { if len(configs) == 0 { // Create - cfg := models.LDAPConfig{ + cfg := model.LDAPConfig{ LDAPHost: getStr("ldap_host"), AdminDN: getStr("admin_dn"), BaseDN: getStr("base_dn"), @@ -211,7 +211,7 @@ func (h *LDAPHandler) UpdateLDAPConfig(c *gin.Context) { } h.db.Create(&cfg) cfg.AdminPassword = "******" - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "LDAP配置已创建", Data: cfg}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "LDAP配置已创建", Data: cfg}) } else { // Update cfg := configs[0] @@ -245,7 +245,7 @@ func (h *LDAPHandler) UpdateLDAPConfig(c *gin.Context) { } h.db.First(&cfg, cfg.ID) cfg.AdminPassword = "******" - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "LDAP配置已更新", Data: cfg}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "LDAP配置已更新", Data: cfg}) } } @@ -258,7 +258,7 @@ func (h *LDAPHandler) TestLDAPConnection(c *gin.Context) { } c.ShouldBindJSON(&req) - var cfg models.LDAPConfig + var cfg model.LDAPConfig if err := h.db.Order("id").First(&cfg).Error; err != nil { c.JSON(http.StatusOK, gin.H{"success": false, "message": "LDAP配置不存在,请先保存配置"}) return @@ -311,9 +311,9 @@ func (h *LDAPHandler) TestLDAPConnection(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"success": false, "message": fmt.Sprintf("密码验证失败: %s", err)}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{"success": true, "message": fmt.Sprintf("认证成功!用户DN: %s", userDN)}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"success": true, "message": fmt.Sprintf("认证成功!用户DN: %s", userDN)}}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{"success": true, "message": "LDAP连接成功,管理员认证通过"}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"success": true, "message": "LDAP连接成功,管理员认证通过"}}) } diff --git a/backend/internal/api/handlers/ldap_ou.go b/backend/controller/ldap_ou.go similarity index 69% rename from backend/internal/api/handlers/ldap_ou.go rename to backend/controller/ldap_ou.go index a2f9dc0..438f59a 100644 --- a/backend/internal/api/handlers/ldap_ou.go +++ b/backend/controller/ldap_ou.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "fmt" "net/http" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "github.com/go-ldap/ldap/v3" @@ -14,9 +14,9 @@ import ( // ListLDAPOUs 列出 LDAP 组织单元 // POST /api/v1/admin/ldap-config/ou-list func (h *LDAPHandler) ListLDAPOUs(c *gin.Context) { - var configs []models.LDAPConfig + var configs []model.LDAPConfig if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 { - c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: []interface{}{}}) return } cfg := configs[0] @@ -27,13 +27,13 @@ func (h *LDAPHandler) ListLDAPOUs(c *gin.Context) { conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port)) if err != nil { - c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: []interface{}{}}) return } defer conn.Close() conn.SetTimeout(5 * time.Second) if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil { - c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: []interface{}{}}) return } @@ -46,7 +46,7 @@ func (h *LDAPHandler) ListLDAPOUs(c *gin.Context) { ) sr, err := conn.Search(searchReq) if err != nil { - c.JSON(http.StatusOK, models.Response{Code: 200, Data: []interface{}{}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: []interface{}{}}) return } @@ -63,7 +63,7 @@ func (h *LDAPHandler) ListLDAPOUs(c *gin.Context) { Description: e.GetAttributeValue("description"), }) } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: ous}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: ous}) } // CreateLDAPOU 创建组织单元 @@ -75,13 +75,13 @@ func (h *LDAPHandler) CreateLDAPOU(c *gin.Context) { Description string `json:"description"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - var configs []models.LDAPConfig + var configs []model.LDAPConfig if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "LDAP未配置"}) return } cfg := configs[0] @@ -97,13 +97,13 @@ func (h *LDAPHandler) CreateLDAPOU(c *gin.Context) { conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port)) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()}) return } defer conn.Close() conn.SetTimeout(5 * time.Second) if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "管理员认证失败: " + err.Error()}) return } @@ -114,9 +114,9 @@ func (h *LDAPHandler) CreateLDAPOU(c *gin.Context) { addReq.Attribute("description", []string{req.Description}) } if err := conn.Add(addReq); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建OU失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建OU失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "OU创建成功", Data: gin.H{"dn": ouDN}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "OU创建成功", Data: gin.H{"dn": ouDN}}) } diff --git a/backend/internal/api/handlers/ldap_users.go b/backend/controller/ldap_users.go similarity index 78% rename from backend/internal/api/handlers/ldap_users.go rename to backend/controller/ldap_users.go index 0c4c105..1a6e605 100644 --- a/backend/internal/api/handlers/ldap_users.go +++ b/backend/controller/ldap_users.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" @@ -7,7 +7,7 @@ import ( "strings" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "github.com/go-ldap/ldap/v3" @@ -22,7 +22,7 @@ func (h *LDAPHandler) ListLDAPUsers(c *gin.Context) { } c.ShouldBindJSON(&req) - var cfg models.LDAPConfig + var cfg model.LDAPConfig if err := h.db.Order("id").First(&cfg).Error; err != nil { c.JSON(http.StatusOK, []interface{}{}) return @@ -86,7 +86,7 @@ func (h *LDAPHandler) ListLDAPUsers(c *gin.Context) { Department: e.GetAttributeValue("department"), }) } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: users}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: users}) } // BatchImportLDAP 批量导入LDAP用户 @@ -103,7 +103,7 @@ func (h *LDAPHandler) BatchImportLDAP(c *gin.Context) { } `json:"users"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } @@ -127,7 +127,7 @@ func (h *LDAPHandler) BatchImportLDAP(c *gin.Context) { continue } // Check if already exists - var existing models.User + var existing model.User if err := h.db.Where("username = ?", uid).First(&existing).Error; err == nil { // Already exists, update info updates := map[string]interface{}{ @@ -145,7 +145,7 @@ func (h *LDAPHandler) BatchImportLDAP(c *gin.Context) { } // Create new LDAP user - user := models.User{ + user := model.User{ Username: uid, Password: "-", // LDAP users don't have local password RealName: cn, @@ -163,7 +163,7 @@ func (h *LDAPHandler) BatchImportLDAP(c *gin.Context) { // bcrypt import to avoid unused import error _ = bcrypt.MinCost - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: fmt.Sprintf("导入完成: %d 个用户成功, %d 个跳过", imported, skipped), Data: gin.H{"imported": imported, "skipped": skipped}, @@ -181,17 +181,17 @@ func (h *LDAPHandler) CreateLDAPUser(c *gin.Context) { OUDN string `json:"ou_dn"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } if req.Username == "" || req.Password == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "用户名和密码不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "用户名和密码不能为空"}) return } - var configs []models.LDAPConfig + var configs []model.LDAPConfig if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "LDAP未配置"}) return } cfg := configs[0] @@ -221,13 +221,13 @@ func (h *LDAPHandler) CreateLDAPUser(c *gin.Context) { conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port)) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()}) return } defer conn.Close() conn.SetTimeout(5 * time.Second) if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "管理员认证失败: " + err.Error()}) return } @@ -241,11 +241,11 @@ func (h *LDAPHandler) CreateLDAPUser(c *gin.Context) { } addReq.Attribute("userPassword", []string{req.Password}) if err := conn.Add(addReq); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建用户失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建用户失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "用户创建成功", Data: gin.H{"dn": userDN}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "用户创建成功", Data: gin.H{"dn": userDN}}) } // DeleteLDAPUser 删除LDAP条目(用户或OU) @@ -255,13 +255,13 @@ func (h *LDAPHandler) DeleteLDAPUser(c *gin.Context) { DN string `json:"dn"` } if err := c.ShouldBindJSON(&req); err != nil || req.DN == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "DN不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "DN不能为空"}) return } - var configs []models.LDAPConfig + var configs []model.LDAPConfig if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "LDAP未配置"}) return } cfg := configs[0] @@ -272,23 +272,23 @@ func (h *LDAPHandler) DeleteLDAPUser(c *gin.Context) { conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port)) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()}) return } defer conn.Close() conn.SetTimeout(5 * time.Second) if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "管理员认证失败: " + err.Error()}) return } delReq := ldap.NewDelRequest(req.DN, nil) if err := conn.Del(delReq); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // UpdateLDAPUser 修改 LDAP 用户属性 @@ -302,13 +302,13 @@ func (h *LDAPHandler) UpdateLDAPUser(c *gin.Context) { Title string `json:"title"` } if err := c.ShouldBindJSON(&req); err != nil || req.DN == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "DN不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "DN不能为空"}) return } - var configs []models.LDAPConfig + var configs []model.LDAPConfig if err := h.db.Order("id").Find(&configs).Error; err != nil || len(configs) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "LDAP未配置"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "LDAP未配置"}) return } cfg := configs[0] @@ -319,13 +319,13 @@ func (h *LDAPHandler) UpdateLDAPUser(c *gin.Context) { conn, err := ldap.DialURL(fmt.Sprintf("ldap://%s:%d", cfg.LDAPHost, port)) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "LDAP连接失败: " + err.Error()}) return } defer conn.Close() conn.SetTimeout(5 * time.Second) if err := conn.Bind(cfg.AdminDN, cfg.AdminPassword); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "管理员认证失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "管理员认证失败: " + err.Error()}) return } @@ -337,7 +337,7 @@ func (h *LDAPHandler) UpdateLDAPUser(c *gin.Context) { nil, )) if err != nil || len(sr.Entries) == 0 { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "用户不存在"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "用户不存在"}) return } entry := sr.Entries[0] @@ -388,10 +388,10 @@ func (h *LDAPHandler) UpdateLDAPUser(c *gin.Context) { if len(modReq.Changes) > 0 { if err := conn.Modify(modReq); err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "修改失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "修改失败: " + err.Error()}) return } } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "修改成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "修改成功"}) } diff --git a/backend/internal/api/handlers/llm.go b/backend/controller/llm.go similarity index 83% rename from backend/internal/api/handlers/llm.go rename to backend/controller/llm.go index c54a5b8..5426331 100644 --- a/backend/internal/api/handlers/llm.go +++ b/backend/controller/llm.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "net/http" "strings" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -35,8 +35,8 @@ func maskAPIKey(key string) string { } // getActiveConfig 读取启用的配置(脱敏后) // Logan.Li -func (h *LLMHandler) getActiveConfig(maskKey bool) (models.LLMConfig, error) { - var cfg models.LLMConfig +func (h *LLMHandler) getActiveConfig(maskKey bool) (model.LLMConfig, error) { + var cfg model.LLMConfig if err := h.db.First(&cfg).Error; err != nil { return cfg, err } @@ -52,14 +52,14 @@ func (h *LLMHandler) GetLLMConfig(c *gin.Context) { cfg, err := h.getActiveConfig(true) if err != nil { // 未配置返回空对象(前端渲染空表单) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "provider": "", "model": "", "api_key": "", "endpoint": "", "temperature": 0.7, "max_tokens": 2000, "system_prompt": "", "enabled": false, "configured": false, }}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "id": cfg.ID, "provider": cfg.Provider, "model": cfg.Model, @@ -76,12 +76,12 @@ func (h *LLMHandler) GetLLMConfig(c *gin.Context) { // SaveLLMConfig 保存 LLM 配置(upsert 单行) // Logan.Li // PUT /api/v1/aiops/llm-config func (h *LLMHandler) SaveLLMConfig(c *gin.Context) { - var req models.SaveLLMConfigRequest + var req model.SaveLLMConfigRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } - var cfg models.LLMConfig + var cfg model.LLMConfig h.db.First(&cfg) // 若前端回传脱敏值(含 ****),保留原 Key if strings.Contains(req.APIKey, "****") && cfg.ID != 0 { @@ -97,18 +97,18 @@ func (h *LLMHandler) SaveLLMConfig(c *gin.Context) { cfg.Enabled = req.Enabled if cfg.ID == 0 { if err := h.db.Create(&cfg).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "保存失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "保存失败: " + err.Error()}) return } } else { if err := h.db.Save(&cfg).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "保存失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "保存失败: " + err.Error()}) return } } // 返回脱敏后的配置 cfg.APIKey = maskAPIKey(cfg.APIKey) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "保存成功", Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "保存成功", Data: gin.H{ "id": cfg.ID, "provider": cfg.Provider, "model": cfg.Model, @@ -125,12 +125,12 @@ func (h *LLMHandler) SaveLLMConfig(c *gin.Context) { // OpenAI 兼容请求/响应结构(仅取必要字段) // Logan.Li type openaiChatRequest struct { Model string `json:"model"` - Messages []models.ChatMessage `json:"messages"` + Messages []model.ChatMessage `json:"messages"` Temperature float64 `json:"temperature"` MaxTokens int `json:"max_tokens,omitempty"` } type openaiChoice struct { - Message models.ChatMessage `json:"message"` + Message model.ChatMessage `json:"message"` } type openaiChatResponse struct { Choices []openaiChoice `json:"choices"` diff --git a/backend/internal/api/handlers/llm_chat.go b/backend/controller/llm_chat.go similarity index 85% rename from backend/internal/api/handlers/llm_chat.go rename to backend/controller/llm_chat.go index ff70eb8..ab03383 100644 --- a/backend/internal/api/handlers/llm_chat.go +++ b/backend/controller/llm_chat.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "bufio" @@ -10,8 +10,8 @@ import ( "strings" "time" - "ezops/internal/api/middleware" - "ezops/internal/models" + "ezops/middleware" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -19,15 +19,15 @@ import ( // Chat AI 对话代理(OpenAI 兼容接口) // Logan.Li // POST /api/v1/aiops/chat func (h *LLMHandler) Chat(c *gin.Context) { - var cfg models.LLMConfig + var cfg model.LLMConfig if err := h.db.First(&cfg).Error; err != nil || !cfg.Enabled { - c.JSON(http.StatusOK, models.Response{Code: 400, Message: "LLM 服务未配置或未启用,请在「模型配置」中完成设置"}) + c.JSON(http.StatusOK, model.Response{Code: 400, Message: "LLM 服务未配置或未启用,请在「模型配置」中完成设置"}) return } - var req models.ChatRequest + var req model.ChatRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } @@ -36,7 +36,7 @@ func (h *LLMHandler) Chat(c *gin.Context) { if strings.TrimSpace(systemPrompt) == "" { systemPrompt = defaultSystemPrompt } - messages := append([]models.ChatMessage{{Role: "system", Content: systemPrompt}}, req.Messages...) + messages := append([]model.ChatMessage{{Role: "system", Content: systemPrompt}}, req.Messages...) // 构造 OpenAI 兼容请求 payload := openaiChatRequest{ @@ -52,7 +52,7 @@ func (h *LLMHandler) Chat(c *gin.Context) { httpReq, err := http.NewRequestWithContext(c.Request.Context(), http.MethodPost, url, bytes.NewReader(body)) if err != nil { - c.JSON(http.StatusOK, models.Response{Code: 500, Message: "构造请求失败: " + err.Error()}) + c.JSON(http.StatusOK, model.Response{Code: 500, Message: "构造请求失败: " + err.Error()}) return } httpReq.Header.Set("Content-Type", "application/json") @@ -60,7 +60,7 @@ func (h *LLMHandler) Chat(c *gin.Context) { resp, err := h.client.Do(httpReq) if err != nil { - c.JSON(http.StatusOK, models.Response{Code: 502, Message: "LLM 服务连接失败,请检查网络或 Endpoint 配置: " + err.Error()}) + c.JSON(http.StatusOK, model.Response{Code: 502, Message: "LLM 服务连接失败,请检查网络或 Endpoint 配置: " + err.Error()}) return } defer resp.Body.Close() @@ -72,13 +72,13 @@ func (h *LLMHandler) Chat(c *gin.Context) { if upErr := parseOpenAIError(raw); upErr != "" { msg += ": " + upErr } - c.JSON(http.StatusOK, models.Response{Code: resp.StatusCode, Message: msg}) + c.JSON(http.StatusOK, model.Response{Code: resp.StatusCode, Message: msg}) return } var chatResp openaiChatResponse if err := json.Unmarshal(raw, &chatResp); err != nil || len(chatResp.Choices) == 0 { - c.JSON(http.StatusOK, models.Response{Code: 500, Message: "解析 LLM 响应失败"}) + c.JSON(http.StatusOK, model.Response{Code: 500, Message: "解析 LLM 响应失败"}) return } replyContent := chatResp.Choices[0].Message.Content @@ -95,13 +95,13 @@ func (h *LLMHandler) Chat(c *gin.Context) { if sid == "" { sid = fmt.Sprintf("sess-%d", now.UnixMilli()) } - h.db.Create(&[]models.ChatHistory{ + h.db.Create(&[]model.ChatHistory{ {UserID: uid, SessionID: sid, Role: "user", Content: lastUser.Content, CreatedAt: now}, {UserID: uid, SessionID: sid, Role: "assistant", Content: replyContent, Model: cfg.Model, CreatedAt: now.Add(time.Millisecond)}, }) } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ChatResponse{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ChatResponse{ Content: replyContent, Model: cfg.Model, TokensUsed: chatResp.Usage.TotalTokens, @@ -114,13 +114,13 @@ func (h *LLMHandler) Chat(c *gin.Context) { // 出错时发送 event: error,data 为 {"message": "..."} // 完成后服务端持久化 user + assistant 两条历史,event: done 结束 func (h *LLMHandler) ChatStream(c *gin.Context) { - var cfg models.LLMConfig + var cfg model.LLMConfig if err := h.db.First(&cfg).Error; err != nil || !cfg.Enabled { writeSSEError(c, 400, "LLM 服务未配置或未启用,请在「模型配置」中完成设置") return } - var req models.ChatRequest + var req model.ChatRequest if err := c.ShouldBindJSON(&req); err != nil { writeSSEError(c, 400, "请求参数错误: "+err.Error()) return @@ -144,11 +144,11 @@ func (h *LLMHandler) ChatStream(c *gin.Context) { if strings.TrimSpace(systemPrompt) == "" { systemPrompt = defaultSystemPrompt } - messages := append([]models.ChatMessage{{Role: "system", Content: systemPrompt}}, req.Messages...) + messages := append([]model.ChatMessage{{Role: "system", Content: systemPrompt}}, req.Messages...) // 构造 OpenAI 兼容流式请求 payload := struct { Model string `json:"model"` - Messages []models.ChatMessage `json:"messages"` + Messages []model.ChatMessage `json:"messages"` Temperature float64 `json:"temperature"` MaxTokens int `json:"max_tokens,omitempty"` Stream bool `json:"stream"` @@ -261,7 +261,7 @@ func (h *LLMHandler) ChatStream(c *gin.Context) { if sid == "" { sid = fmt.Sprintf("sess-%d", now.UnixMilli()) } - h.db.Create(&[]models.ChatHistory{ + h.db.Create(&[]model.ChatHistory{ {UserID: uid, SessionID: sid, Role: "user", Content: lastUser.Content, CreatedAt: now}, {UserID: uid, SessionID: sid, Role: "assistant", Content: fullContent, Model: cfg.Model, CreatedAt: now.Add(time.Millisecond)}, }) @@ -314,14 +314,14 @@ func parseOpenAIError(raw []byte) string { // TestLLMConnection 测试 LLM 连接(发送一条 ping 消息) // Logan.Li // POST /api/v1/aiops/llm-config/test func (h *LLMHandler) TestLLMConnection(c *gin.Context) { - var cfg models.LLMConfig + var cfg model.LLMConfig if err := h.db.First(&cfg).Error; err != nil { - c.JSON(http.StatusOK, models.Response{Code: 400, Message: "请先保存配置"}) + c.JSON(http.StatusOK, model.Response{Code: 400, Message: "请先保存配置"}) return } payload := openaiChatRequest{ Model: cfg.Model, - Messages: []models.ChatMessage{{Role: "user", Content: "ping"}}, + Messages: []model.ChatMessage{{Role: "user", Content: "ping"}}, Temperature: 0, MaxTokens: 16, } @@ -332,7 +332,7 @@ func (h *LLMHandler) TestLLMConnection(c *gin.Context) { httpReq.Header.Set("Authorization", "Bearer "+cfg.APIKey) resp, err := h.client.Do(httpReq) if err != nil { - c.JSON(http.StatusOK, models.Response{Code: 502, Message: "连接失败: " + err.Error()}) + c.JSON(http.StatusOK, model.Response{Code: 502, Message: "连接失败: " + err.Error()}) return } defer resp.Body.Close() @@ -342,8 +342,8 @@ func (h *LLMHandler) TestLLMConnection(c *gin.Context) { if e := parseOpenAIError(raw); e != "" { msg += ": " + e } - c.JSON(http.StatusOK, models.Response{Code: resp.StatusCode, Message: msg}) + c.JSON(http.StatusOK, model.Response{Code: resp.StatusCode, Message: msg}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "连接成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "连接成功"}) } diff --git a/backend/internal/api/handlers/llm_history.go b/backend/controller/llm_history.go similarity index 71% rename from backend/internal/api/handlers/llm_history.go rename to backend/controller/llm_history.go index aa9ae04..85d2487 100644 --- a/backend/internal/api/handlers/llm_history.go +++ b/backend/controller/llm_history.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" - "ezops/internal/api/middleware" - "ezops/internal/models" + "ezops/middleware" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -14,14 +14,14 @@ import ( func (h *LLMHandler) GetChatHistory(c *gin.Context) { uid := middleware.GetUserID(c) sid := c.Query("session_id") - var rows []models.ChatHistory + var rows []model.ChatHistory q := h.db.Where("user_id = ?", uid) // 指定 session_id 直接过滤;未指定则查最新 session // Logan.Li if sid != "" { q = q.Where("session_id = ?", sid) } else { // 取该用户最新的 session_id(id 最大那条的 session_id) - var latest models.ChatHistory + var latest model.ChatHistory if err := h.db.Where("user_id = ?", uid).Order("id DESC").First(&latest).Error; err == nil && latest.SessionID != "" { q = q.Where("session_id = ?", latest.SessionID) } @@ -31,7 +31,7 @@ func (h *LLMHandler) GetChatHistory(c *gin.Context) { for i, j := 0, len(rows)-1; i < j; i, j = i+1, j-1 { rows[i], rows[j] = rows[j], rows[i] } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "list": rows, "total": len(rows), }}) @@ -41,9 +41,9 @@ func (h *LLMHandler) GetChatHistory(c *gin.Context) { // DELETE /api/v1/aiops/chat-history func (h *LLMHandler) ClearChatHistory(c *gin.Context) { uid := middleware.GetUserID(c) - if err := h.db.Where("user_id = ?", uid).Delete(&models.ChatHistory{}).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "清除失败: " + err.Error()}) + if err := h.db.Where("user_id = ?", uid).Delete(&model.ChatHistory{}).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "清除失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "对话历史已清空"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "对话历史已清空"}) } diff --git a/backend/internal/api/handlers/log.go b/backend/controller/log.go similarity index 75% rename from backend/internal/api/handlers/log.go rename to backend/controller/log.go index 38fddde..d398777 100644 --- a/backend/internal/api/handlers/log.go +++ b/backend/controller/log.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "encoding/json" "net/http" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -22,10 +22,10 @@ func NewLogHandler(db *gorm.DB) *LogHandler { // QueryLogs 查询日志条目(支持 level/service/host/keyword 过滤) // Logan.Li func (h *LogHandler) QueryLogs(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) - db := h.db.Model(&models.LogEntry{}) + db := h.db.Model(&model.LogEntry{}) // 过滤 if level := c.Query("level"); level != "" { @@ -47,17 +47,17 @@ func (h *LogHandler) QueryLogs(c *gin.Context) { var total int64 db.Count(&total) - var logs []models.LogEntry + var logs []model.LogEntry db.Order("timestamp DESC").Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&logs) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{List: logs, Total: total}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: logs, Total: total}}) } // ListSources 获取日志源列表 // Logan.Li func (h *LogHandler) ListSources(c *gin.Context) { - var sources []models.LogSource + var sources []model.LogSource h.db.Order("updated_at DESC").Find(&sources) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{List: sources, Total: int64(len(sources))}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: sources, Total: int64(len(sources))}}) } // CreateSource 创建日志源 // Logan.Li @@ -68,12 +68,12 @@ func (h *LogHandler) CreateSource(c *gin.Context) { Config map[string]interface{} `json:"config"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } configJSON, _ := json.Marshal(req.Config) now := time.Now() - item := models.LogSource{ + item := model.LogSource{ Name: req.Name, Type: req.Type, Status: "active", @@ -81,16 +81,16 @@ func (h *LogHandler) CreateSource(c *gin.Context) { LastSeen: &now, } h.db.Create(&item) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: item}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: item}) } // DeleteSource 删除日志源 // Logan.Li func (h *LogHandler) DeleteSource(c *gin.Context) { - if err := h.db.Delete(&models.LogSource{}, c.Param("id")); err.Error != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if err := h.db.Delete(&model.LogSource{}, c.Param("id")); err.Error != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已删除"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已删除"}) } // IngestLogs Agent 上报日志(无需 JWT,供 Agent 调用) // Logan.Li @@ -102,13 +102,13 @@ func (h *LogHandler) IngestLogs(c *gin.Context) { Entries []map[string]interface{} `json:"entries"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } // 查找或创建日志源 - var source models.LogSource - h.db.Where("name = ?", req.Source).FirstOrCreate(&source, models.LogSource{ + var source model.LogSource + h.db.Where("name = ?", req.Source).FirstOrCreate(&source, model.LogSource{ Name: req.Source, Type: "agent", Status: "active", }) @@ -125,7 +125,7 @@ func (h *LogHandler) IngestLogs(c *gin.Context) { } } - log := models.LogEntry{ + log := model.LogEntry{ SourceID: source.ID, Timestamp: ts, Level: level, @@ -146,5 +146,5 @@ func (h *LogHandler) IngestLogs(c *gin.Context) { "last_seen": &now, }).UpdateColumn("log_count", source.LogCount+int64(count)) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "成功写入", Data: map[string]int{"count": count}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "成功写入", Data: map[string]int{"count": count}}) } diff --git a/backend/controller/login_log.go b/backend/controller/login_log.go new file mode 100644 index 0000000..d8e0e46 --- /dev/null +++ b/backend/controller/login_log.go @@ -0,0 +1,70 @@ +package controller + +import ( + "net/http" + + "ezops/model" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" +) + +// LoginLogHandler 登录日志处理器 // Logan.Li +type LoginLogHandler struct { + db *gorm.DB +} + +// NewLoginLogHandler 创建登录日志处理器 +func NewLoginLogHandler(db *gorm.DB) *LoginLogHandler { + return &LoginLogHandler{db: db} +} + +// ListLoginLogs 登录日志列表 +// GET /api/v1/login-logs?username=&status=&page=&page_size= +func (h *LoginLogHandler) ListLoginLogs(c *gin.Context) { + var req model.LoginLogQuery + if err := c.ShouldBindQuery(&req); err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) + return + } + if req.Page <= 0 { + req.Page = 1 + } + if req.PageSize <= 0 { + req.PageSize = 20 + } + + query := h.db.Model(&model.LoginLog{}) + if req.Username != "" { + query = query.Where("username LIKE ?", "%"+req.Username+"%") + } + if req.Status != "" { + query = query.Where("status = ?", req.Status) + } + if req.StartTime != "" { + query = query.Where("created_at >= ?", req.StartTime) + } + if req.EndTime != "" { + query = query.Where("created_at <= ?", req.EndTime) + } + + var total int64 + if err := query.Count(&total).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + var logs []model.LoginLog + if err := query.Order("id DESC"). + Offset((req.Page - 1) * req.PageSize). + Limit(req.PageSize). + Find(&logs).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{ + List: logs, + Total: total, + }}) +} diff --git a/backend/internal/api/handlers/metrics.go b/backend/controller/metrics.go similarity index 84% rename from backend/internal/api/handlers/metrics.go rename to backend/controller/metrics.go index cbf4899..087c21b 100644 --- a/backend/internal/api/handlers/metrics.go +++ b/backend/controller/metrics.go @@ -1,7 +1,7 @@ -package handlers +package controller import ( - "ezops/internal/models" + "ezops/model" "net/http" "strconv" "time" @@ -23,8 +23,8 @@ func NewMetricsHandler(db *gorm.DB) *MetricsHandler { // ListTargets 列出监控目标(按类型过滤) // GET /api/v1/metrics/targets?type=host&status=online func (h *MetricsHandler) ListTargets(c *gin.Context) { - var targets []models.MonitorTarget - q := h.db.Model(&models.MonitorTarget{}) + var targets []model.MonitorTarget + q := h.db.Model(&model.MonitorTarget{}) if t := c.Query("type"); t != "" { q = q.Where("type = ?", t) @@ -44,18 +44,18 @@ func (h *MetricsHandler) ListTargets(c *gin.Context) { q.Offset((page - 1) * pageSize).Limit(pageSize).Order("name ASC").Find(&targets) if targets == nil { - targets = []models.MonitorTarget{} + targets = []model.MonitorTarget{} } // 附带最新指标值 type TargetWithMetrics struct { - models.MonitorTarget + model.MonitorTarget LatestMetrics map[string]float64 `json:"latest_metrics"` } result := make([]TargetWithMetrics, len(targets)) for i, t := range targets { result[i] = TargetWithMetrics{MonitorTarget: t, LatestMetrics: make(map[string]float64)} // 查询该目标最近 10 分钟内的最新指标 - var histories []models.MetricHistory + var histories []model.MetricHistory h.db.Where("target_id = ? AND timestamp > ?", t.ID, now()-600). Order("timestamp DESC").Limit(10).Find(&histories) for _, mh := range histories { @@ -65,7 +65,7 @@ func (h *MetricsHandler) ListTargets(c *gin.Context) { } } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "list": result, "total": total, }}) @@ -74,19 +74,19 @@ func (h *MetricsHandler) ListTargets(c *gin.Context) { // ListMetrics 列出系统中所有指标元数据 // GET /api/v1/metrics/list func (h *MetricsHandler) ListMetrics(c *gin.Context) { - var metrics []models.MonitorMetric + var metrics []model.MonitorMetric h.db.Order("category ASC, name ASC").Find(&metrics) if metrics == nil { - metrics = []models.MonitorMetric{} + metrics = []model.MonitorMetric{} } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: metrics}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: metrics}) } // QueryValues 查询指标时序数据 // GET /api/v1/metrics/query?target_id=N&metric_name=cpu_usage&from=0&to=0&limit=100 func (h *MetricsHandler) QueryValues(c *gin.Context) { - var histories []models.MetricHistory - q := h.db.Model(&models.MetricHistory{}) + var histories []model.MetricHistory + q := h.db.Model(&model.MetricHistory{}) if tid := c.Query("target_id"); tid != "" { id, _ := strconv.ParseUint(tid, 10, 64) @@ -108,23 +108,23 @@ func (h *MetricsHandler) QueryValues(c *gin.Context) { q.Order("timestamp ASC").Limit(limit).Find(&histories) if histories == nil { - histories = []models.MetricHistory{} + histories = []model.MetricHistory{} } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: histories}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: histories}) } // ListMetricNames 列出所有可用的指标名称(去重) // GET /api/v1/metrics/names func (h *MetricsHandler) ListMetricNames(c *gin.Context) { var names []string - h.db.Model(&models.MetricHistory{}). + h.db.Model(&model.MetricHistory{}). Distinct("metric_name"). Order("metric_name ASC"). Pluck("metric_name", &names) if names == nil { names = []string{} } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: names}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: names}) } // TopHosts 返回指定指标的 Top N 主机排行 @@ -145,7 +145,7 @@ func (h *MetricsHandler) TopHosts(c *gin.Context) { Status string `json:"status"` } - var servers []models.Server + var servers []model.Server orderField := "cpu_usage DESC" switch metric { case "cpu": @@ -180,7 +180,7 @@ func (h *MetricsHandler) TopHosts(c *gin.Context) { if result == nil { result = []HostRank{} } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: result}) } func now() int64 { diff --git a/backend/internal/api/handlers/metrics_ws.go b/backend/controller/metrics_ws.go similarity index 99% rename from backend/internal/api/handlers/metrics_ws.go rename to backend/controller/metrics_ws.go index 1602b61..4e3b825 100644 --- a/backend/internal/api/handlers/metrics_ws.go +++ b/backend/controller/metrics_ws.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" diff --git a/backend/internal/api/handlers/navigation.go b/backend/controller/navigation.go similarity index 71% rename from backend/internal/api/handlers/navigation.go rename to backend/controller/navigation.go index d99c465..f7605db 100644 --- a/backend/internal/api/handlers/navigation.go +++ b/backend/controller/navigation.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -26,13 +26,13 @@ func NewNavigationHandler(db *gorm.DB) *NavigationHandler { // @Tags 站内导航 // @Produce json // @Security Bearer -// @Success 200 {object} models.Response{data=[]models.NavigationGroup} +// @Success 200 {object} model.Response{data=[]model.NavigationGroup} // @Router /navigations/groups [get] func (h *NavigationHandler) ListGroups(c *gin.Context) { - var groups []models.NavigationGroup + var groups []model.NavigationGroup h.db.Order("sort ASC, created_at ASC").Find(&groups) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: groups, @@ -46,20 +46,20 @@ func (h *NavigationHandler) ListGroups(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateNavigationGroupRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.NavigationGroup} +// @Param request body model.CreateNavigationGroupRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.NavigationGroup} // @Router /navigations/groups [post] func (h *NavigationHandler) CreateGroup(c *gin.Context) { - var req models.CreateNavigationGroupRequest + var req model.CreateNavigationGroupRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - group := models.NavigationGroup{ + group := model.NavigationGroup{ Name: req.Name, Code: req.Code, Description: req.Description, @@ -69,14 +69,14 @@ func (h *NavigationHandler) CreateGroup(c *gin.Context) { } if err := h.db.Create(&group).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: group, @@ -91,24 +91,24 @@ func (h *NavigationHandler) CreateGroup(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "分组ID" -// @Param request body models.UpdateNavigationGroupRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.NavigationGroup} +// @Param request body model.UpdateNavigationGroupRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.NavigationGroup} // @Router /navigations/groups/{id} [put] func (h *NavigationHandler) UpdateGroup(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.UpdateNavigationGroupRequest + var req model.UpdateNavigationGroupRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var group models.NavigationGroup + var group model.NavigationGroup if err := h.db.First(&group, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "分组不存在", }) @@ -131,7 +131,7 @@ func (h *NavigationHandler) UpdateGroup(c *gin.Context) { } if err := h.db.Model(&group).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -140,7 +140,7 @@ func (h *NavigationHandler) UpdateGroup(c *gin.Context) { h.db.First(&group, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: group, @@ -154,29 +154,29 @@ func (h *NavigationHandler) UpdateGroup(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "分组ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /navigations/groups/{id} [delete] func (h *NavigationHandler) DeleteGroup(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) // 删除分组下的所有链接 - if err := h.db.Where("group_id = ?", id).Delete(&models.NavigationLink{}).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Where("group_id = ?", id).Delete(&model.NavigationLink{}).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除链接失败", }) return } - if err := h.db.Delete(&models.NavigationGroup{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.NavigationGroup{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) diff --git a/backend/internal/api/handlers/navigation_link.go b/backend/controller/navigation_link.go similarity index 69% rename from backend/internal/api/handlers/navigation_link.go rename to backend/controller/navigation_link.go index ac136fa..950427f 100644 --- a/backend/internal/api/handlers/navigation_link.go +++ b/backend/controller/navigation_link.go @@ -2,14 +2,14 @@ // 导航链接相关处理器方法 // 从 navigation.go 拆分而来,包含导航链接的 CRUD 及收藏功能 -package handlers +package controller import ( "encoding/json" "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -22,10 +22,10 @@ import ( // @Security Bearer // @Param group_id query int false "分组ID" // @Param keyword query string false "搜索关键词" -// @Success 200 {object} models.Response{data=[]models.NavigationLink} +// @Success 200 {object} model.Response{data=[]model.NavigationLink} // @Router /navigations/links [get] func (h *NavigationHandler) ListLinks(c *gin.Context) { - db := h.db.Model(&models.NavigationLink{}).Preload("Group") + db := h.db.Model(&model.NavigationLink{}).Preload("Group") // 分组过滤 if groupID := c.Query("group_id"); groupID != "" { @@ -37,10 +37,10 @@ func (h *NavigationHandler) ListLinks(c *gin.Context) { db = db.Where("name LIKE ? OR description LIKE ?", "%"+keyword+"%", "%"+keyword+"%") } - var links []models.NavigationLink + var links []model.NavigationLink db.Order("sort ASC, created_at ASC").Find(&links) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: links, @@ -54,13 +54,13 @@ func (h *NavigationHandler) ListLinks(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateNavigationLinkRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.NavigationLink} +// @Param request body model.CreateNavigationLinkRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.NavigationLink} // @Router /navigations/links [post] func (h *NavigationHandler) CreateLink(c *gin.Context) { - var req models.CreateNavigationLinkRequest + var req model.CreateNavigationLinkRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) @@ -69,7 +69,7 @@ func (h *NavigationHandler) CreateLink(c *gin.Context) { tags, _ := json.Marshal(req.Tags) - link := models.NavigationLink{ + link := model.NavigationLink{ GroupID: req.GroupID, Name: req.Name, URL: req.URL, @@ -81,7 +81,7 @@ func (h *NavigationHandler) CreateLink(c *gin.Context) { } if err := h.db.Create(&link).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) @@ -89,12 +89,12 @@ func (h *NavigationHandler) CreateLink(c *gin.Context) { } // 更新分组链接数 - h.db.Model(&models.NavigationGroup{}).Where("id = ?", req.GroupID). - UpdateColumn("link_count", h.db.Model(&models.NavigationLink{}).Where("group_id = ?", req.GroupID).Select("COUNT(*)")) + h.db.Model(&model.NavigationGroup{}).Where("id = ?", req.GroupID). + UpdateColumn("link_count", h.db.Model(&model.NavigationLink{}).Where("group_id = ?", req.GroupID).Select("COUNT(*)")) h.db.Preload("Group").First(&link, link.ID) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: link, @@ -109,24 +109,24 @@ func (h *NavigationHandler) CreateLink(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "链接ID" -// @Param request body models.UpdateNavigationLinkRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.NavigationLink} +// @Param request body model.UpdateNavigationLinkRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.NavigationLink} // @Router /navigations/links/{id} [put] func (h *NavigationHandler) UpdateLink(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.UpdateNavigationLinkRequest + var req model.UpdateNavigationLinkRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var link models.NavigationLink + var link model.NavigationLink if err := h.db.First(&link, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "链接不存在", }) @@ -159,7 +159,7 @@ func (h *NavigationHandler) UpdateLink(c *gin.Context) { } if err := h.db.Model(&link).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -168,7 +168,7 @@ func (h *NavigationHandler) UpdateLink(c *gin.Context) { h.db.Preload("Group").First(&link, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: link, @@ -182,16 +182,16 @@ func (h *NavigationHandler) UpdateLink(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "链接ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /navigations/links/{id} [delete] func (h *NavigationHandler) DeleteLink(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var link models.NavigationLink + var link model.NavigationLink h.db.First(&link, id) - if err := h.db.Delete(&models.NavigationLink{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.NavigationLink{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) @@ -200,11 +200,11 @@ func (h *NavigationHandler) DeleteLink(c *gin.Context) { // 更新分组链接数 if link.GroupID > 0 { - h.db.Model(&models.NavigationGroup{}).Where("id = ?", link.GroupID). - UpdateColumn("link_count", h.db.Model(&models.NavigationLink{}).Where("group_id = ?", link.GroupID).Select("COUNT(*)")) + h.db.Model(&model.NavigationGroup{}).Where("id = ?", link.GroupID). + UpdateColumn("link_count", h.db.Model(&model.NavigationLink{}).Where("group_id = ?", link.GroupID).Select("COUNT(*)")) } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -218,24 +218,24 @@ func (h *NavigationHandler) DeleteLink(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "链接ID" -// @Param request body models.ToggleFavoriteRequest true "收藏请求" -// @Success 200 {object} models.Response{data=models.NavigationLink} +// @Param request body model.ToggleFavoriteRequest true "收藏请求" +// @Success 200 {object} model.Response{data=model.NavigationLink} // @Router /navigations/links/{id}/favorite [post] func (h *NavigationHandler) ToggleFavorite(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.ToggleFavoriteRequest + var req model.ToggleFavoriteRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误", }) return } - var link models.NavigationLink + var link model.NavigationLink if err := h.db.First(&link, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "链接不存在", }) @@ -244,14 +244,14 @@ func (h *NavigationHandler) ToggleFavorite(c *gin.Context) { link.IsFavorite = req.IsFavorite if err := h.db.Save(&link).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "操作失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "操作成功", Data: link, diff --git a/backend/internal/api/handlers/pipeline.go b/backend/controller/pipeline.go similarity index 76% rename from backend/internal/api/handlers/pipeline.go rename to backend/controller/pipeline.go index ead13c4..b34f597 100644 --- a/backend/internal/api/handlers/pipeline.go +++ b/backend/controller/pipeline.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "net/http" @@ -6,8 +6,8 @@ import ( "strconv" "time" - "ezops/internal/models" - "ezops/internal/api/middleware" + "ezops/model" + "ezops/middleware" ezredis "ezops/pkg/redis" "github.com/gin-gonic/gin" @@ -40,7 +40,7 @@ func validateCode(db *gorm.DB, code string, excludeID uint) string { } // 查重 var count int64 - q := db.Model(&models.Pipeline{}).Where("code = ?", code) + q := db.Model(&model.Pipeline{}).Where("code = ?", code) if excludeID > 0 { q = q.Where("id != ?", excludeID) } @@ -64,7 +64,7 @@ func NewPipelineHandler(db *gorm.DB, cache ezredis.Cache) *PipelineHandler { // PipelineListItem 列表项(含最近一次运行摘要)// Logan.Li type PipelineListItem struct { - models.Pipeline + model.Pipeline LastRunStages string `json:"last_run_stages,omitempty"` // JSON: [{name,status}] LastImageTag string `json:"last_image_tag,omitempty"` LastCommitID string `json:"last_commit_id,omitempty"` @@ -80,10 +80,10 @@ type PipelineListItem struct { // @Security Bearer // @Param page query int false "页码" // @Param page_size query int false "每页数量" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // ListPipelines 获取流水线列表 func (h *PipelineHandler) ListPipelines(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) // 管理员看全部,非管理员只看自己有权限的 @@ -93,12 +93,12 @@ func (h *PipelineHandler) ListPipelines(c *gin.Context) { userID, _ := c.Get("userID") uid, _ := userID.(uint) - db := h.db.Model(&models.Pipeline{}) + db := h.db.Model(&model.Pipeline{}) if isAdmin != true && usernameStr != "" { ids, hasAccess := middleware.GetAccessiblePipelineIDs(h.db, usernameStr, uid) if !hasAccess { // 没有任何流水线权限 → 返回空列表 - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{List: []models.Pipeline{}, Total: 0}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: []model.Pipeline{}, Total: 0}}) return } db = db.Where("id IN ?", ids) @@ -107,7 +107,7 @@ func (h *PipelineHandler) ListPipelines(c *gin.Context) { var total int64 db.Count(&total) - var pipelines []models.Pipeline + var pipelines []model.Pipeline db.Preload("Environment").Offset(query.GetOffset()).Limit(query.GetLimit()).Order("updated_at DESC").Find(&pipelines) // 批量获取每个流水线最近一次运行的摘要(阶段状态 + 镜像 + 耗时)// Logan.Li @@ -118,10 +118,10 @@ func (h *PipelineHandler) ListPipelines(c *gin.Context) { pids = append(pids, p.ID) } // 子查询:每个 pipeline_id 的最新 run id - var latestRuns []models.PipelineRun + var latestRuns []model.PipelineRun h.db.Where("id IN (SELECT MAX(id) FROM ops_pipeline_runs WHERE pipeline_id IN ? AND status IN ('success','failed','running','pending') GROUP BY pipeline_id)", pids). Find(&latestRuns) - runMap := map[uint]*models.PipelineRun{} + runMap := map[uint]*model.PipelineRun{} for i := range latestRuns { runMap[latestRuns[i].PipelineID] = &latestRuns[i] } @@ -142,9 +142,9 @@ func (h *PipelineHandler) ListPipelines(c *gin.Context) { } } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, - Data: models.ListResponse{List: items, Total: total}, + Data: model.ListResponse{List: items, Total: total}, }) } @@ -155,25 +155,25 @@ func (h *PipelineHandler) ListPipelines(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "流水线ID" -// @Success 200 {object} models.Response{data=models.Pipeline} +// @Success 200 {object} model.Response{data=model.Pipeline} // @Router /pipelines/{id} [get] func (h *PipelineHandler) GetPipeline(c *gin.Context) { id := getPipelineID(c) if id == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的流水线编码"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的流水线编码"}) return } - var pipeline models.Pipeline + var pipeline model.Pipeline if err := h.db.Preload("Environment").First(&pipeline, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "流水线不存在", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: pipeline, @@ -187,13 +187,13 @@ func (h *PipelineHandler) GetPipeline(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreatePipelineRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.Pipeline} +// @Param request body model.CreatePipelineRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.Pipeline} // @Router /pipelines [post] func (h *PipelineHandler) CreatePipeline(c *gin.Context) { - var req models.CreatePipelineRequest + var req model.CreatePipelineRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) @@ -202,11 +202,11 @@ func (h *PipelineHandler) CreatePipeline(c *gin.Context) { // 校验编码格式 if msg := validateCode(h.db, req.Code, 0); msg != "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: msg}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: msg}) return } - pipeline := models.Pipeline{ + pipeline := model.Pipeline{ Name: req.Name, Code: req.Code, JobName: req.JobName, @@ -241,14 +241,14 @@ func (h *PipelineHandler) CreatePipeline(c *gin.Context) { } if err := h.db.Create(&pipeline).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: pipeline, @@ -263,28 +263,28 @@ func (h *PipelineHandler) CreatePipeline(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "流水线ID" -// @Param request body models.CreatePipelineRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.Pipeline} +// @Param request body model.CreatePipelineRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.Pipeline} // @Router /pipelines/{id} [put] func (h *PipelineHandler) UpdatePipeline(c *gin.Context) { id := getPipelineID(c) if id == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的流水线编码"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的流水线编码"}) return } - var req models.UpdatePipelineRequest + var req model.UpdatePipelineRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var pipeline models.Pipeline + var pipeline model.Pipeline if err := h.db.First(&pipeline, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "流水线不存在", }) @@ -321,7 +321,7 @@ func (h *PipelineHandler) UpdatePipeline(c *gin.Context) { if req.MaxExecutors > 0 { updates["max_executors"] = req.MaxExecutors } if err := h.db.Model(&pipeline).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -330,7 +330,7 @@ func (h *PipelineHandler) UpdatePipeline(c *gin.Context) { h.db.First(&pipeline, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: pipeline, @@ -344,20 +344,20 @@ func (h *PipelineHandler) UpdatePipeline(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "流水线ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /pipelines/{id} [delete] func (h *PipelineHandler) DeletePipeline(c *gin.Context) { id := getPipelineID(c) - if err := h.db.Delete(&models.Pipeline{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.Pipeline{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -371,27 +371,27 @@ func (h *PipelineHandler) DeletePipeline(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "流水线ID" -// @Param request body models.TriggerPipelineRequest true "触发请求" -// @Success 200 {object} models.Response{data=models.PipelineRun} +// @Param request body model.TriggerPipelineRequest true "触发请求" +// @Success 200 {object} model.Response{data=model.PipelineRun} // TriggerPipeline 触发流水线 func (h *PipelineHandler) TriggerPipeline(c *gin.Context) { id := getPipelineID(c) if id == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的流水线编码"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的流水线编码"}) return } - var pipeline models.Pipeline + var pipeline model.Pipeline if err := h.db.First(&pipeline, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "流水线不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "流水线不存在"}) return } - var req models.TriggerPipelineRequest + var req model.TriggerPipelineRequest c.ShouldBindJSON(&req) var maxBuildNumber int - h.db.Model(&models.PipelineRun{}).Where("pipeline_id = ?", id). + h.db.Model(&model.PipelineRun{}).Where("pipeline_id = ?", id). Select("COALESCE(MAX(build_number), 0)").Scan(&maxBuildNumber) branch := req.Branch @@ -407,7 +407,7 @@ func (h *PipelineHandler) TriggerPipeline(c *gin.Context) { userStr, _ := username.(string) now := time.Now() - run := models.PipelineRun{ + run := model.PipelineRun{ PipelineID: uint(id), BuildNumber: maxBuildNumber + 1, Status: "running", @@ -418,14 +418,14 @@ func (h *PipelineHandler) TriggerPipeline(c *gin.Context) { } if err := h.db.Create(&run).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "触发失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "触发失败"}) return } // 通过队列引擎执行(尊重 max_executors 并发限制) go h.tryExecuteOrQueue(pipeline, run) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已触发", Data: run}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已触发", Data: run}) } // ListRuns 获取运行记录列表 @@ -437,28 +437,28 @@ func (h *PipelineHandler) TriggerPipeline(c *gin.Context) { // @Param id path int true "流水线ID" // @Param page query int false "页码" // @Param page_size query int false "每页数量" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /pipelines/{id}/runs [get] func (h *PipelineHandler) ListRuns(c *gin.Context) { id := getPipelineID(c) - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) - db := h.db.Model(&models.PipelineRun{}).Where("pipeline_id = ?", id) + db := h.db.Model(&model.PipelineRun{}).Where("pipeline_id = ?", id) var total int64 db.Count(&total) - var runs []models.PipelineRun + var runs []model.PipelineRun db.Order("started_at DESC"). Offset(query.GetOffset()). Limit(query.GetLimit()). Find(&runs) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: runs, Total: total, }, @@ -470,19 +470,19 @@ func (h *PipelineHandler) WebhookTrigger(c *gin.Context) { jobName := c.Param("jobName") code := c.Param("code") - var pipeline models.Pipeline + var pipeline model.Pipeline if jobName != "" { if err := h.db.Where("job_name = ? AND enabled = ?", jobName, true).First(&pipeline).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "Job 不存在或已禁用"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "Job 不存在或已禁用"}) return } } else if code != "" { if err := h.db.Where("code = ? AND enabled = ?", code, true).First(&pipeline).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "流水线不存在或已禁用"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "流水线不存在或已禁用"}) return } } else { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "缺少 jobName 或 code"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "缺少 jobName 或 code"}) return } @@ -493,17 +493,17 @@ func (h *PipelineHandler) WebhookTrigger(c *gin.Context) { token = c.Query("token") } if token != pipeline.WebhookToken { - c.JSON(http.StatusForbidden, models.Response{Code: 403, Message: "Webhook Token 无效"}) + c.JSON(http.StatusForbidden, model.Response{Code: 403, Message: "Webhook Token 无效"}) return } } // 解析请求体获取 branch/tag - var req models.TriggerPipelineRequest + var req model.TriggerPipelineRequest c.ShouldBindJSON(&req) var maxBuildNumber int - h.db.Model(&models.PipelineRun{}).Where("pipeline_id = ?", pipeline.ID). + h.db.Model(&model.PipelineRun{}).Where("pipeline_id = ?", pipeline.ID). Select("COALESCE(MAX(build_number), 0)").Scan(&maxBuildNumber) ref := req.Branch @@ -526,7 +526,7 @@ func (h *PipelineHandler) WebhookTrigger(c *gin.Context) { } now := time.Now() - run := models.PipelineRun{ + run := model.PipelineRun{ PipelineID: pipeline.ID, BuildNumber: maxBuildNumber + 1, Status: "running", @@ -537,13 +537,13 @@ func (h *PipelineHandler) WebhookTrigger(c *gin.Context) { } if err := h.db.Create(&run).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "触发失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "触发失败"}) return } go h.executePipeline(pipeline, run) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "已触发", Data: map[string]interface{}{ @@ -557,11 +557,11 @@ func (h *PipelineHandler) WebhookTrigger(c *gin.Context) { func (h *PipelineHandler) GetPipelineQueue(c *gin.Context) { id := getPipelineID(c) if id == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的流水线编码"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的流水线编码"}) return } status := h.GetQueueStatus(uint(id)) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: status}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: status}) } // CancelQueueItem 取消排队中的构建 @@ -569,12 +569,12 @@ func (h *PipelineHandler) CancelQueueItem(c *gin.Context) { id := getPipelineID(c) runID, _ := strconv.ParseUint(c.Param("runId"), 10, 64) if id == 0 || runID == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"}) return } if err := h.CancelQueued(uint(id), uint(runID)); err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: err.Error()}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已取消"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已取消"}) } diff --git a/backend/internal/api/handlers/pipeline_executor.go b/backend/controller/pipeline_executor.go similarity index 94% rename from backend/internal/api/handlers/pipeline_executor.go rename to backend/controller/pipeline_executor.go index 6a8f416..d4605d8 100644 --- a/backend/internal/api/handlers/pipeline_executor.go +++ b/backend/controller/pipeline_executor.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "context" @@ -10,7 +10,7 @@ import ( "sync" "time" - "ezops/internal/models" + "ezops/model" "go.uber.org/zap" ) @@ -39,7 +39,7 @@ func init() { } // executePipeline 后台执行流水线(goroutine)— V2 Redis 版 -func (h *PipelineHandler) executePipeline(pipeline models.Pipeline, run models.PipelineRun) { +func (h *PipelineHandler) executePipeline(pipeline model.Pipeline, run model.PipelineRun) { runID := run.ID ctx := context.Background() logKey := fmt.Sprintf("pipeline:run:%d:logs", runID) @@ -74,7 +74,7 @@ func (h *PipelineHandler) executePipeline(pipeline models.Pipeline, run models.P if status == "success" || status == "failed" || status == "cancelled" { updates["finished_at"] = &now } - h.db.Model(&models.PipelineRun{}).Where("id = ?", runID).Updates(updates) + h.db.Model(&model.PipelineRun{}).Where("id = ?", runID).Updates(updates) // 推送状态变更 if h.cache != nil { statusData, _ := json.Marshal(map[string]interface{}{"type": "status", "status": status, "duration": duration}) @@ -90,11 +90,11 @@ func (h *PipelineHandler) executePipeline(pipeline models.Pipeline, run models.P if status == "failed" { ups["fail_count"] = pipeline.FailCount + 1 } - h.db.Model(&models.Pipeline{}).Where("id = ?", pipeline.ID).Updates(ups) + h.db.Model(&model.Pipeline{}).Where("id = ?", pipeline.ID).Updates(ups) } isCancelled := func() bool { - var current models.PipelineRun + var current model.PipelineRun h.db.First(¤t, runID) return current.Status == "cancelled" } @@ -132,7 +132,7 @@ func (h *PipelineHandler) executePipeline(pipeline models.Pipeline, run models.P os.RemoveAll(workspace) os.MkdirAll(workspace, 0755) // 保存 workspace 路径到运行记录,方便终端查看 - h.db.Model(&models.PipelineRun{}).Where("id = ?", runID).Update("workspace_path", workspace) + h.db.Model(&model.PipelineRun{}).Where("id = ?", runID).Update("workspace_path", workspace) imageTag := fmt.Sprintf("%s-%s", repoName, tsDir) @@ -207,7 +207,7 @@ func (h *PipelineHandler) flushLogsToDB(ctx context.Context, runID uint, logKey return } logsJSON, _ := json.Marshal(entries) - h.db.Model(&models.PipelineRun{}).Where("id = ?", runID).Update("logs", string(logsJSON)) + h.db.Model(&model.PipelineRun{}).Where("id = ?", runID).Update("logs", string(logsJSON)) // 清理 Redis 缓存 h.cache.Del(ctx, logKey) } @@ -391,7 +391,7 @@ func (h *PipelineHandler) runTest(workspace string, logFn func(string, string, s } // runDockerBuild Docker 构建 & 推送 -func (h *PipelineHandler) runDockerBuild(workspace string, pipeline models.Pipeline, tag string, logFn func(string, string, string)) error { +func (h *PipelineHandler) runDockerBuild(workspace string, pipeline model.Pipeline, tag string, logFn func(string, string, string)) error { dockerfile := pipeline.Dockerfile if dockerfile == "" { dockerfile = "Dockerfile" @@ -399,7 +399,7 @@ func (h *PipelineHandler) runDockerBuild(workspace string, pipeline models.Pipel var registryURL, imageName string if pipeline.RegistryID != nil { - var reg models.PipelineRegistry + var reg model.PipelineRegistry if err := h.db.First(®, *pipeline.RegistryID).Error; err == nil { registryURL = reg.RegistryURL if reg.Namespace != "" { @@ -456,7 +456,7 @@ func (h *PipelineHandler) runDockerBuild(workspace string, pipeline models.Pipel } // runDeploy 部署到 K8s / 服务器 -func (h *PipelineHandler) runDeploy(workspace string, pipeline models.Pipeline, tag string, logFn func(string, string, string)) error { +func (h *PipelineHandler) runDeploy(workspace string, pipeline model.Pipeline, tag string, logFn func(string, string, string)) error { deployYamls := findFiles(workspace, ".yaml", ".yml") var k8sFiles []string for _, f := range deployYamls { @@ -564,7 +564,7 @@ var ( // tryExecuteOrQueue 触发流水线时检查并发限制 // 如果当前运行数 < maxExecutors → 立即执行 // 否则 → 加入队列 (status=queued) -func (h *PipelineHandler) tryExecuteOrQueue(pipeline models.Pipeline, run models.PipelineRun) { +func (h *PipelineHandler) tryExecuteOrQueue(pipeline model.Pipeline, run model.PipelineRun) { max := pipeline.MaxExecutors if max <= 0 { max = 2 } @@ -574,14 +574,14 @@ func (h *PipelineHandler) tryExecuteOrQueue(pipeline models.Pipeline, run models pipelineRunningCount[pipeline.ID] = running + 1 queueMu.Unlock() // 立即执行 - h.db.Model(&models.PipelineRun{}).Where("id = ?", run.ID).Update("status", "running") + h.db.Model(&model.PipelineRun{}).Where("id = ?", run.ID).Update("status", "running") go h.executePipeline(pipeline, run) return } // 加入队列 pipelineQueues[pipeline.ID] = append(pipelineQueues[pipeline.ID], run.ID) queueMu.Unlock() - h.db.Model(&models.PipelineRun{}).Where("id = ?", run.ID).Update("status", "queued") + h.db.Model(&model.PipelineRun{}).Where("id = ?", run.ID).Update("status", "queued") } // dequeueNext 流水线运行结束后,从队列中取下一个执行 @@ -603,9 +603,9 @@ func (h *PipelineHandler) dequeueNext(pipelineID uint) { queueMu.Unlock() // 加载 pipeline + run - var pipeline models.Pipeline + var pipeline model.Pipeline if err := h.db.First(&pipeline, pipelineID).Error; err != nil { return } - var run models.PipelineRun + var run model.PipelineRun if err := h.db.First(&run, nextRunID).Error; err != nil { return } h.db.Model(&run).Update("status", "running") @@ -633,7 +633,7 @@ func (h *PipelineHandler) CancelQueued(pipelineID uint, runID uint) error { for i, id := range queue { if id == runID { pipelineQueues[pipelineID] = append(queue[:i], queue[i+1:]...) - h.db.Model(&models.PipelineRun{}).Where("id = ?", runID).Update("status", "cancelled") + h.db.Model(&model.PipelineRun{}).Where("id = ?", runID).Update("status", "cancelled") return nil } } diff --git a/backend/internal/api/handlers/pipeline_release.go b/backend/controller/pipeline_release.go similarity index 74% rename from backend/internal/api/handlers/pipeline_release.go rename to backend/controller/pipeline_release.go index 2a11c37..bd5c47a 100644 --- a/backend/internal/api/handlers/pipeline_release.go +++ b/backend/controller/pipeline_release.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "encoding/json" "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -20,25 +20,25 @@ import ( // @Security Bearer // @Param page query int false "页码" // @Param page_size query int false "每页数量" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /releases [get] func (h *PipelineHandler) ListReleases(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery c.ShouldBindQuery(&query) var total int64 - h.db.Model(&models.AppRelease{}).Count(&total) + h.db.Model(&model.AppRelease{}).Count(&total) - var releases []models.AppRelease + var releases []model.AppRelease h.db.Order("created_at DESC"). Offset(query.GetOffset()). Limit(query.GetLimit()). Find(&releases) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: releases, Total: total, }, @@ -52,20 +52,20 @@ func (h *PipelineHandler) ListReleases(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateAppReleaseRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.AppRelease} +// @Param request body model.CreateAppReleaseRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.AppRelease} // @Router /releases [post] func (h *PipelineHandler) CreateRelease(c *gin.Context) { - var req models.CreateAppReleaseRequest + var req model.CreateAppReleaseRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - release := models.AppRelease{ + release := model.AppRelease{ PipelineID: req.PipelineID, PipelineRunID: req.PipelineRunID, AppName: req.AppName, @@ -91,14 +91,14 @@ func (h *PipelineHandler) CreateRelease(c *gin.Context) { } if err := h.db.Create(&release).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: release, @@ -112,14 +112,14 @@ func (h *PipelineHandler) CreateRelease(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "发布ID" -// @Success 200 {object} models.Response{data=models.AppRelease} +// @Success 200 {object} model.Response{data=model.AppRelease} // @Router /releases/{id}/approve [post] func (h *PipelineHandler) ApproveRelease(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var release models.AppRelease + var release model.AppRelease if err := h.db.First(&release, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "发布不存在", }) @@ -132,14 +132,14 @@ func (h *PipelineHandler) ApproveRelease(c *gin.Context) { // release.ApprovedAt = &now if err := h.db.Save(&release).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "审批失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "审批成功", Data: release, @@ -153,14 +153,14 @@ func (h *PipelineHandler) ApproveRelease(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "发布ID" -// @Success 200 {object} models.Response{data=models.AppRelease} +// @Success 200 {object} model.Response{data=model.AppRelease} // @Router /releases/{id}/deploy [post] func (h *PipelineHandler) DeployRelease(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var release models.AppRelease + var release model.AppRelease if err := h.db.First(&release, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "发布不存在", }) @@ -169,14 +169,14 @@ func (h *PipelineHandler) DeployRelease(c *gin.Context) { release.Status = "deploying" if err := h.db.Save(&release).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "部署失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "部署中", Data: release, @@ -187,9 +187,9 @@ func (h *PipelineHandler) DeployRelease(c *gin.Context) { func (h *PipelineHandler) RejectRelease(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var release models.AppRelease + var release model.AppRelease if err := h.db.First(&release, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "发布不存在", }) @@ -197,7 +197,7 @@ func (h *PipelineHandler) RejectRelease(c *gin.Context) { } if release.Status != "pending" { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "仅待审批状态可驳回", }) @@ -206,14 +206,14 @@ func (h *PipelineHandler) RejectRelease(c *gin.Context) { release.Status = "rejected" if err := h.db.Save(&release).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "驳回失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "已驳回", Data: release, @@ -227,14 +227,14 @@ func (h *PipelineHandler) RejectRelease(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "发布ID" -// @Success 200 {object} models.Response{data=models.AppRelease} +// @Success 200 {object} model.Response{data=model.AppRelease} // @Router /releases/{id}/rollback [post] func (h *PipelineHandler) RollbackRelease(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var release models.AppRelease + var release model.AppRelease if err := h.db.First(&release, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "发布不存在", }) @@ -246,14 +246,14 @@ func (h *PipelineHandler) RollbackRelease(c *gin.Context) { // release.RollbackAt = &now if err := h.db.Save(&release).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "回滚失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "回滚成功", Data: release, diff --git a/backend/internal/api/handlers/prometheus_datasource.go b/backend/controller/prometheus_datasource.go similarity index 75% rename from backend/internal/api/handlers/prometheus_datasource.go rename to backend/controller/prometheus_datasource.go index 6807981..ede95d3 100644 --- a/backend/internal/api/handlers/prometheus_datasource.go +++ b/backend/controller/prometheus_datasource.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "crypto/tls" @@ -7,7 +7,7 @@ import ( "net/http" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -30,41 +30,41 @@ func NewPromDSHandler(db *gorm.DB) *PromDSHandler { // List 数据源列表 // GET /api/v1/prometheus-datasources func (h *PromDSHandler) List(c *gin.Context) { - var sources []models.PrometheusDataSource + var sources []model.PrometheusDataSource if err := h.db.Order("is_default DESC, id ASC").Find(&sources).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败: " + err.Error()}) return } if sources == nil { - sources = []models.PrometheusDataSource{} + sources = []model.PrometheusDataSource{} } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: sources}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: sources}) } // Get 获取单个数据源 // GET /api/v1/prometheus-datasources/:id func (h *PromDSHandler) Get(c *gin.Context) { id := c.Param("id") - var ds models.PrometheusDataSource + var ds model.PrometheusDataSource if err := h.db.First(&ds, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "数据源不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "数据源不存在"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: ds}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: ds}) } // Create 创建数据源 // POST /api/v1/prometheus-datasources func (h *PromDSHandler) Create(c *gin.Context) { - var req models.CreatePromDSReq + var req model.CreatePromDSReq if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } // 如果设为默认,先清除其他默认 if req.IsDefault { - h.db.Model(&models.PrometheusDataSource{}).Where("is_default = ?", true).Update("is_default", false) + h.db.Model(&model.PrometheusDataSource{}).Where("is_default = ?", true).Update("is_default", false) } // 默认值 @@ -85,7 +85,7 @@ func (h *PromDSHandler) Create(c *gin.Context) { enableAlerting = *req.EnableAlerting } - ds := models.PrometheusDataSource{ + ds := model.PrometheusDataSource{ Name: req.Name, URL: req.URL, Access: req.Access, @@ -110,26 +110,26 @@ func (h *PromDSHandler) Create(c *gin.Context) { } if err := h.db.Create(&ds).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败: " + err.Error()}) return } h.recordAudit(c, "create", "prometheus_datasource", ds.Name) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: ds}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "创建成功", Data: ds}) } // Update 更新数据源 // PUT /api/v1/prometheus-datasources/:id func (h *PromDSHandler) Update(c *gin.Context) { id := c.Param("id") - var ds models.PrometheusDataSource + var ds model.PrometheusDataSource if err := h.db.First(&ds, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "数据源不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "数据源不存在"}) return } - var req models.UpdatePromDSReq + var req model.UpdatePromDSReq if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } @@ -194,7 +194,7 @@ func (h *PromDSHandler) Update(c *gin.Context) { if req.IsDefault != nil { // 如果设为默认,先清除其他默认 if *req.IsDefault { - h.db.Model(&models.PrometheusDataSource{}).Where("is_default = ?", true).Update("is_default", false) + h.db.Model(&model.PrometheusDataSource{}).Where("is_default = ?", true).Update("is_default", false) } updates["is_default"] = *req.IsDefault } @@ -203,54 +203,54 @@ func (h *PromDSHandler) Update(c *gin.Context) { } if len(updates) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无更新字段"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无更新字段"}) return } if err := h.db.Model(&ds).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "更新失败: " + err.Error()}) return } // 重新查询返回 h.db.First(&ds, id) h.recordAudit(c, "update", "prometheus_datasource", ds.Name) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: ds}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功", Data: ds}) } // Delete 删除数据源 // DELETE /api/v1/prometheus-datasources/:id func (h *PromDSHandler) Delete(c *gin.Context) { id := c.Param("id") - var ds models.PrometheusDataSource + var ds model.PrometheusDataSource if err := h.db.First(&ds, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "数据源不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "数据源不存在"}) return } if err := h.db.Delete(&ds).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败: " + err.Error()}) return } h.recordAudit(c, "delete", "prometheus_datasource", ds.Name) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // SetDefault 设为默认数据源 // POST /api/v1/prometheus-datasources/:id/default func (h *PromDSHandler) SetDefault(c *gin.Context) { id := c.Param("id") - var ds models.PrometheusDataSource + var ds model.PrometheusDataSource if err := h.db.First(&ds, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "数据源不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "数据源不存在"}) return } // 清除所有默认 - h.db.Model(&models.PrometheusDataSource{}).Where("is_default = ?", true).Update("is_default", false) + h.db.Model(&model.PrometheusDataSource{}).Where("is_default = ?", true).Update("is_default", false) // 设置当前为默认 h.db.Model(&ds).Update("is_default", true) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已设为默认"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已设为默认"}) } // ============================================ @@ -260,9 +260,9 @@ func (h *PromDSHandler) SetDefault(c *gin.Context) { // TestConnection 测试数据源连接 // POST /api/v1/prometheus-datasources/test func (h *PromDSHandler) TestConnection(c *gin.Context) { - var req models.TestPromDSReq + var req model.TestPromDSReq if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } @@ -279,7 +279,7 @@ func (h *PromDSHandler) TestConnection(c *gin.Context) { apiURL := req.URL + "/api/v1/query?query=up&time=" + time.Now().UTC().Format(time.RFC3339) httpReq, err := http.NewRequest("GET", apiURL, nil) if err != nil { - c.JSON(http.StatusOK, models.Response{Code: 400, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 400, Data: gin.H{ "success": false, "message": "URL 格式错误: " + err.Error(), }}) return @@ -293,7 +293,7 @@ func (h *PromDSHandler) TestConnection(c *gin.Context) { resp, err := client.Do(httpReq) if err != nil { - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "success": false, "message": "连接失败: " + err.Error(), }}) return @@ -308,14 +308,14 @@ func (h *PromDSHandler) TestConnection(c *gin.Context) { } `json:"data"` } json.NewDecoder(resp.Body).Decode(&result) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "success": true, "message": "连接成功", "status_code": resp.StatusCode, "target_count": len(result.Data.Result), }}) } else { - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "success": false, "message": "连接返回异常状态码", "status_code": resp.StatusCode, @@ -338,7 +338,7 @@ func (h *PromDSHandler) recordAudit(c *gin.Context, action, resource, name strin if v, ok := username.(string); ok { uname = v } - h.db.Create(&models.AuditLog{ + h.db.Create(&model.AuditLog{ UserID: &uid, Username: uname, IP: c.ClientIP(), diff --git a/backend/internal/api/handlers/prometheus_proxy.go b/backend/controller/prometheus_proxy.go similarity index 90% rename from backend/internal/api/handlers/prometheus_proxy.go rename to backend/controller/prometheus_proxy.go index 239c70b..636721a 100644 --- a/backend/internal/api/handlers/prometheus_proxy.go +++ b/backend/controller/prometheus_proxy.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" @@ -11,7 +11,7 @@ import ( "strings" "time" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -33,7 +33,7 @@ type PromConnectReq struct { func (h *PrometheusProxyHandler) Connect(c *gin.Context) { var req PromConnectReq if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } @@ -42,11 +42,11 @@ func (h *PrometheusProxyHandler) Connect(c *gin.Context) { // 测试连接:查询 up 指标 status, targetCount := h.testConnect(client, req.URL) if !status { - c.JSON(http.StatusBadGateway, models.Response{Code: 502, Message: "无法连接到 Prometheus,请检查 URL"}) + c.JSON(http.StatusBadGateway, model.Response{Code: 502, Message: "无法连接到 Prometheus,请检查 URL"}) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: gin.H{ @@ -64,18 +64,18 @@ func (h *PrometheusProxyHandler) Query(c *gin.Context) { Query string `json:"query" binding:"required"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"}) return } client := &http.Client{Timeout: 15 * time.Second} result, err := h.execPromQL(client, req.URL, req.Query) if err != nil { - c.JSON(http.StatusBadGateway, models.Response{Code: 502, Message: "查询失败: " + err.Error()}) + c.JSON(http.StatusBadGateway, model.Response{Code: 502, Message: "查询失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: result}) } // PromQueryRange 执行 PromQL 范围查询 @@ -89,7 +89,7 @@ func (h *PrometheusProxyHandler) QueryRange(c *gin.Context) { Step string `json:"step"` // e.g. "15s", "1m" } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"}) return } if req.Step == "" { @@ -110,7 +110,7 @@ func (h *PrometheusProxyHandler) QueryRange(c *gin.Context) { resp, err := client.Get(u) if err != nil { - c.JSON(http.StatusBadGateway, models.Response{Code: 502, Message: "查询失败: " + err.Error()}) + c.JSON(http.StatusBadGateway, model.Response{Code: 502, Message: "查询失败: " + err.Error()}) return } defer resp.Body.Close() @@ -119,7 +119,7 @@ func (h *PrometheusProxyHandler) QueryRange(c *gin.Context) { var promResult map[string]interface{} json.Unmarshal(body, &promResult) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: promResult}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: promResult}) } // PromDashboard 获取预定义仪表盘数据(K8s / Node / Pod / JVM) @@ -130,7 +130,7 @@ func (h *PrometheusProxyHandler) Dashboard(c *gin.Context) { Type string `json:"type" binding:"required"` // k8s, node, pod, jvm } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误"}) return } @@ -148,7 +148,7 @@ func (h *PrometheusProxyHandler) Dashboard(c *gin.Context) { result = h.dashboardK8s(client, req.URL) } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "success", Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "success", Data: result}) } // ============================================ diff --git a/backend/controller/refactored_v2.go b/backend/controller/refactored_v2.go new file mode 100644 index 0000000..0bc497c --- /dev/null +++ b/backend/controller/refactored_v2.go @@ -0,0 +1,227 @@ +package controller + +import ( + "net/http" + "strconv" + + "ezops/dto" + "ezops/model" + "ezops/service" + "ezops/utils" + + "github.com/gin-gonic/gin" +) + +// ━━━ Credential Handler (v2 thin) ━━━━━━━━━━━━━━━━━━━━━━━ + +type CredentialHandlerV2 struct { + svc *service.CredentialService +} + +func NewCredentialHandlerV2(svc *service.CredentialService) *CredentialHandlerV2 { + return &CredentialHandlerV2{svc: svc} +} + +func (h *CredentialHandlerV2) ListCredentials(c *gin.Context) { + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20")) + keyword := c.Query("keyword") + secretType := c.Query("secret_type") + + list, total, err := h.svc.List(keyword, secretType, page, pageSize) + if err != nil { + utils.InternalError(c, "查询失败") + return + } + utils.ListResponse(c, list, total) +} + +func (h *CredentialHandlerV2) GetCredential(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + crd, err := h.svc.GetByID(uint(id)) + if err != nil { + utils.NotFound(c, "凭据不存在") + return + } + utils.OK(c, crd) +} + +func (h *CredentialHandlerV2) CreateCredential(c *gin.Context) { + var req dto.CreateCredentialRequest + if err := c.ShouldBindJSON(&req); err != nil { + utils.BadRequest(c, "请求参数错误: "+err.Error()) + return + } + crd, err := h.svc.Create(&req) + if err != nil { + utils.InternalError(c, "创建失败: "+err.Error()) + return + } + utils.OK(c, crd) +} + +func (h *CredentialHandlerV2) UpdateCredential(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + var req dto.UpdateCredentialRequest + if err := c.ShouldBindJSON(&req); err != nil { + utils.BadRequest(c, "请求参数错误: "+err.Error()) + return + } + if err := h.svc.Update(uint(id), &req); err != nil { + utils.InternalError(c, "更新失败: "+err.Error()) + return + } + crd, _ := h.svc.GetByID(uint(id)) + utils.OK(c, crd) +} + +func (h *CredentialHandlerV2) DeleteCredential(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + if err := h.svc.Delete(uint(id)); err != nil { + utils.InternalError(c, "删除失败") + return + } + utils.OK(c, gin.H{"id": id}) +} + +// ━━━ Alert Contact Handler (v2 thin) ━━━━━━━━━━━━━━━━━━━━ + +type AlertContactHandlerV2 struct { + svc *service.AlertContactService +} + +func NewAlertContactHandlerV2(svc *service.AlertContactService) *AlertContactHandlerV2 { + return &AlertContactHandlerV2{svc: svc} +} + +func (h *AlertContactHandlerV2) ListContacts(c *gin.Context) { + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20")) + keyword := c.Query("keyword") + + list, total, err := h.svc.List(keyword, page, pageSize) + if err != nil { + utils.InternalError(c, "查询失败") + return + } + utils.ListResponse(c, list, total) +} + +func (h *AlertContactHandlerV2) GetContact(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + contact, err := h.svc.GetByID(uint(id)) + if err != nil { + utils.NotFound(c, "联系人不存在") + return + } + utils.OK(c, contact) +} + +func (h *AlertContactHandlerV2) CreateContact(c *gin.Context) { + var req dto.CreateAlertContactRequest + if err := c.ShouldBindJSON(&req); err != nil { + utils.BadRequest(c, "请求参数错误: "+err.Error()) + return + } + contact, err := h.svc.Create(&req) + if err != nil { + utils.InternalError(c, "创建失败") + return + } + utils.OK(c, contact) +} + +func (h *AlertContactHandlerV2) UpdateContact(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + var req dto.UpdateAlertContactRequest + if err := c.ShouldBindJSON(&req); err != nil { + utils.BadRequest(c, "请求参数错误: "+err.Error()) + return + } + if err := h.svc.Update(uint(id), &req); err != nil { + utils.InternalError(c, "更新失败") + return + } + contact, _ := h.svc.GetByID(uint(id)) + utils.OK(c, contact) +} + +func (h *AlertContactHandlerV2) DeleteContact(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + if err := h.svc.Delete(uint(id)); err != nil { + utils.InternalError(c, "删除失败") + return + } + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) +} + +// ━━━ Alert Contact Group Handler (v2 thin) ━━━━━━━━━━━━━━ + +type AlertContactGroupHandlerV2 struct { + svc *service.AlertContactGroupService +} + +func NewAlertContactGroupHandlerV2(svc *service.AlertContactGroupService) *AlertContactGroupHandlerV2 { + return &AlertContactGroupHandlerV2{svc: svc} +} + +func (h *AlertContactGroupHandlerV2) ListGroups(c *gin.Context) { + page, _ := strconv.Atoi(c.DefaultQuery("page", "1")) + pageSize, _ := strconv.Atoi(c.DefaultQuery("page_size", "20")) + keyword := c.Query("keyword") + + list, total, err := h.svc.List(keyword, page, pageSize) + if err != nil { + utils.InternalError(c, "查询失败") + return + } + utils.ListResponse(c, list, total) +} + +func (h *AlertContactGroupHandlerV2) GetGroup(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + g, err := h.svc.GetByID(uint(id)) + if err != nil { + utils.NotFound(c, "联系组不存在") + return + } + utils.OK(c, g) +} + +func (h *AlertContactGroupHandlerV2) CreateGroup(c *gin.Context) { + var req dto.CreateAlertContactGroupRequest + if err := c.ShouldBindJSON(&req); err != nil { + utils.BadRequest(c, "请求参数错误: "+err.Error()) + return + } + g, err := h.svc.Create(&req) + if err != nil { + utils.InternalError(c, "创建失败") + return + } + utils.OK(c, g) +} + +func (h *AlertContactGroupHandlerV2) UpdateGroup(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + var req dto.UpdateAlertContactGroupRequest + if err := c.ShouldBindJSON(&req); err != nil { + utils.BadRequest(c, "请求参数错误: "+err.Error()) + return + } + if err := h.svc.Update(uint(id), &req); err != nil { + utils.InternalError(c, "更新失败") + return + } + g, _ := h.svc.GetByID(uint(id)) + utils.OK(c, g) +} + +func (h *AlertContactGroupHandlerV2) DeleteGroup(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + if err := h.svc.Delete(uint(id)); err != nil { + utils.InternalError(c, "删除失败") + return + } + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) +} diff --git a/backend/internal/api/handlers/remote_exec.go b/backend/controller/remote_exec.go similarity index 78% rename from backend/internal/api/handlers/remote_exec.go rename to backend/controller/remote_exec.go index 6486435..3c4d390 100644 --- a/backend/internal/api/handlers/remote_exec.go +++ b/backend/controller/remote_exec.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" @@ -8,7 +8,7 @@ import ( "strings" "time" - "ezops/internal/models" + "ezops/model" "ezops/pkg/remoteexec" "github.com/gin-gonic/gin" @@ -39,19 +39,19 @@ type BatchExecRequest struct { func (h *RemoteExecHandler) BatchExec(c *gin.Context) { var req BatchExecRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } // 查询目标服务器 - var servers []models.Server + var servers []model.Server if err := h.db.Where("id IN ?", req.ServerIDs).Find(&servers).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询服务器失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询服务器失败"}) return } if len(servers) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "未找到目标服务器"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "未找到目标服务器"}) return } @@ -60,7 +60,7 @@ func (h *RemoteExecHandler) BatchExec(c *gin.Context) { for _, s := range servers { cfg, err := buildSSHConfig(h.db, s) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: fmt.Sprintf("服务器 %s 认证配置错误: %v", s.Hostname, err), }) return @@ -76,7 +76,7 @@ func (h *RemoteExecHandler) BatchExec(c *gin.Context) { // 并发执行 results := remoteexec.BatchExec(configs, req.Command, time.Duration(timeout)*time.Second, 10) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: results}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: results}) } // ==================== 文件批量上传 ==================== @@ -93,24 +93,24 @@ type BatchUploadRequest struct { func (h *RemoteExecHandler) BatchUpload(c *gin.Context) { var req BatchUploadRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } if !strings.HasPrefix(req.LocalPath, "/") { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "local_path 必须是绝对路径"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "local_path 必须是绝对路径"}) return } // 查询目标服务器 - var servers []models.Server + var servers []model.Server if err := h.db.Where("id IN ?", req.ServerIDs).Find(&servers).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询服务器失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询服务器失败"}) return } if len(servers) == 0 { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "未找到目标服务器"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "未找到目标服务器"}) return } @@ -119,7 +119,7 @@ func (h *RemoteExecHandler) BatchUpload(c *gin.Context) { for _, s := range servers { cfg, err := buildSSHConfig(h.db, s) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: fmt.Sprintf("服务器 %s 认证配置错误: %v", s.Hostname, err), }) return @@ -130,7 +130,7 @@ func (h *RemoteExecHandler) BatchUpload(c *gin.Context) { // 并发上传 results := remoteexec.BatchUpload(configs, req.LocalPath, req.RemotePath, 5) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: results}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: results}) } // ==================== 主机匹配 ==================== @@ -141,7 +141,7 @@ func (h *RemoteExecHandler) MatchHosts(c *gin.Context) { pattern := c.Query("pattern") matchType := c.DefaultQuery("match_type", "contains") - query := h.db.Model(&models.Server{}) + query := h.db.Model(&model.Server{}) if pattern != "" { switch matchType { @@ -158,7 +158,7 @@ func (h *RemoteExecHandler) MatchHosts(c *gin.Context) { var total int64 query.Count(&total) - var items []models.Server + var items []model.Server query.Order("hostname").Find(&items) // 补充 HasAuth 字段 @@ -166,7 +166,7 @@ func (h *RemoteExecHandler) MatchHosts(c *gin.Context) { items[i].HasAuth = items[i].Password != "" || items[i].SSHKey != "" } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{List: items, Total: total}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: items, Total: total}}) } // ==================== 单机命令执行 ==================== @@ -176,7 +176,7 @@ func (h *RemoteExecHandler) MatchHosts(c *gin.Context) { func (h *RemoteExecHandler) ExecOnServer(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的服务器 ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的服务器 ID"}) return } @@ -185,19 +185,19 @@ func (h *RemoteExecHandler) ExecOnServer(c *gin.Context) { Timeout int `json:"timeout"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } - var server models.Server + var server model.Server if err := h.db.First(&server, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "服务器不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "服务器不存在"}) return } cfg, err := buildSSHConfig(h.db, server) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "认证配置错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "认证配置错误: " + err.Error()}) return } @@ -208,11 +208,11 @@ func (h *RemoteExecHandler) ExecOnServer(c *gin.Context) { result, err := remoteexec.Exec(cfg, req.Command, time.Duration(timeout)*time.Second) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error(), Data: result}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error(), Data: result}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: result}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: result}) } // ==================== 辅助函数 ==================== @@ -220,7 +220,7 @@ func (h *RemoteExecHandler) ExecOnServer(c *gin.Context) { // buildSSHConfig 从 Server 模型构建 SSHConfig。 // 优先使用 server 自带的 Password/SSHKey 字段, // 如果 server 关联了 credential_id,则从凭证表解密获取。 -func buildSSHConfig(db *gorm.DB, server models.Server) (remoteexec.SSHConfig, error) { +func buildSSHConfig(db *gorm.DB, server model.Server) (remoteexec.SSHConfig, error) { cfg := remoteexec.SSHConfig{ Host: server.IP, Port: server.Port, @@ -256,7 +256,7 @@ func buildSSHConfig(db *gorm.DB, server models.Server) (remoteexec.SSHConfig, er // ExecuteCronOnTargets 根据 CronJob 的 target_type 在目标主机上执行脚本。 // 由 automation_cron.go 调用的公共函数。 -func ExecuteCronOnTargets(db *gorm.DB, job models.CronJob, scriptType, content string, timeoutSec int) ([]remoteexec.ExecResult, error) { +func ExecuteCronOnTargets(db *gorm.DB, job model.CronJob, scriptType, content string, timeoutSec int) ([]remoteexec.ExecResult, error) { // 解析目标服务器 var targetIDs []uint if job.Targets != "" { @@ -268,7 +268,7 @@ func ExecuteCronOnTargets(db *gorm.DB, job models.CronJob, scriptType, content s } // 查询服务器 - var servers []models.Server + var servers []model.Server switch job.TargetType { case "server": db.Where("id IN ?", targetIDs).Find(&servers) diff --git a/backend/internal/api/handlers/resource_model.go b/backend/controller/resource_model.go similarity index 68% rename from backend/internal/api/handlers/resource_model.go rename to backend/controller/resource_model.go index f05f5c1..9ad2627 100644 --- a/backend/internal/api/handlers/resource_model.go +++ b/backend/controller/resource_model.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" @@ -6,7 +6,7 @@ import ( "strconv" "strings" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -33,13 +33,13 @@ type resourceModelRequest struct { // ListResourceModels 获取资源模型列表 func (h *ResourceModelHandler) ListResourceModels(c *gin.Context) { - var models_ []models.ResourceModel + var models_ []model.ResourceModel h.db.Order("id ASC").Find(&models_) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: models_, Total: int64(len(models_)), }, @@ -50,11 +50,11 @@ func (h *ResourceModelHandler) ListResourceModels(c *gin.Context) { func (h *ResourceModelHandler) CreateResourceModel(c *gin.Context) { var req resourceModelRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } if strings.TrimSpace(req.Name) == "" || strings.TrimSpace(req.Code) == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "模型名称和编码不能为空"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "模型名称和编码不能为空"}) return } @@ -69,7 +69,7 @@ func (h *ResourceModelHandler) CreateResourceModel(c *gin.Context) { attrsJSON = string(b) } - rm := models.ResourceModel{ + rm := model.ResourceModel{ Name: strings.TrimSpace(req.Name), Code: strings.TrimSpace(req.Code), Description: req.Description, @@ -78,10 +78,10 @@ func (h *ResourceModelHandler) CreateResourceModel(c *gin.Context) { Icon: req.Icon, } if err := h.db.Create(&rm).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败,编码可能已存在"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败,编码可能已存在"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "创建成功", Data: rm}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "创建成功", Data: rm}) } // UpdateResourceModel 更新资源模型 @@ -89,13 +89,13 @@ func (h *ResourceModelHandler) UpdateResourceModel(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) var req resourceModelRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "请求参数错误: " + err.Error()}) return } - var rm models.ResourceModel + var rm model.ResourceModel if err := h.db.First(&rm, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "资源模型不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "资源模型不存在"}) return } @@ -117,18 +117,18 @@ func (h *ResourceModelHandler) UpdateResourceModel(c *gin.Context) { } if err := h.db.Save(&rm).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "更新失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功", Data: rm}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功", Data: rm}) } // DeleteResourceModel 删除资源模型 func (h *ResourceModelHandler) DeleteResourceModel(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.ResourceModel{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + if err := h.db.Delete(&model.ResourceModel{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } diff --git a/backend/internal/api/handlers/role.go b/backend/controller/role.go similarity index 68% rename from backend/internal/api/handlers/role.go rename to backend/controller/role.go index f9f791b..4a6622f 100644 --- a/backend/internal/api/handlers/role.go +++ b/backend/controller/role.go @@ -1,10 +1,10 @@ -package handlers +package controller import ( "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -12,9 +12,9 @@ import ( // CreateRole 创建角色 // Logan.Li // POST /api/v1/admin/roles func (h *UserHandler) CreateRole(c *gin.Context) { - var req models.CreateRoleRequest + var req model.CreateRoleRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) @@ -22,23 +22,23 @@ func (h *UserHandler) CreateRole(c *gin.Context) { } // 名称 / 编码唯一性校验 - var existing models.Role + var existing model.Role if err := h.db.Where("name = ? OR code = ?", req.Name, req.Code).First(&existing).Error; err == nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "角色名称或编码已存在", }) return } - role := models.Role{ + role := model.Role{ Name: req.Name, Code: req.Code, Description: req.Description, Status: 1, } if err := h.db.Create(&role).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建角色失败", }) @@ -47,13 +47,13 @@ func (h *UserHandler) CreateRole(c *gin.Context) { // 关联权限 if len(req.PermissionIDs) > 0 { - var perms []models.Permission + var perms []model.Permission h.db.Find(&perms, req.PermissionIDs) h.db.Model(&role).Association("Permissions").Append(perms) } h.db.Preload("Permissions").First(&role, role.ID) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: role, @@ -65,31 +65,31 @@ func (h *UserHandler) CreateRole(c *gin.Context) { func (h *UserHandler) UpdateRole(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的角色 ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的角色 ID"}) return } - var req models.UpdateRoleRequest + var req model.UpdateRoleRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var role models.Role + var role model.Role if err := h.db.First(&role, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "角色不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "角色不存在"}) return } updates := map[string]interface{}{} if req.Name != "" { // 名称 / 编码唯一性校验(排除自身) - var dup models.Role + var dup model.Role if err := h.db.Where("(name = ? OR code = ?) AND id != ?", req.Name, req.Code, id).First(&dup).Error; err == nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "角色名称或编码已存在"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "角色名称或编码已存在"}) return } updates["name"] = req.Name @@ -106,14 +106,14 @@ func (h *UserHandler) UpdateRole(c *gin.Context) { if len(updates) > 0 { if err := h.db.Model(&role).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "更新失败"}) return } } // 替换权限关联 if req.PermissionIDs != nil { - var perms []models.Permission + var perms []model.Permission if len(req.PermissionIDs) > 0 { h.db.Find(&perms, req.PermissionIDs) } @@ -121,7 +121,7 @@ func (h *UserHandler) UpdateRole(c *gin.Context) { } h.db.Preload("Permissions").First(&role, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: role, @@ -133,24 +133,24 @@ func (h *UserHandler) UpdateRole(c *gin.Context) { func (h *UserHandler) DeleteRole(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的角色 ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的角色 ID"}) return } - var role models.Role + var role model.Role if err := h.db.First(&role, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "角色不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "角色不存在"}) return } // 清空权限关联后再删除(避免 join 表残留) h.db.Model(&role).Association("Permissions").Clear() if err := h.db.Delete(&role).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -159,10 +159,10 @@ func (h *UserHandler) DeleteRole(c *gin.Context) { // ListPermissions 获取权限列表(供前端角色权限选择) // Logan.Li // GET /api/v1/admin/permissions func (h *UserHandler) ListPermissions(c *gin.Context) { - var perms []models.Permission + var perms []model.Permission h.db.Where("status = ?", 1).Order("sort ASC, id ASC").Find(&perms) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, - Data: models.ListResponse{List: perms, Total: int64(len(perms))}, + Data: model.ListResponse{List: perms, Total: int64(len(perms))}, }) } diff --git a/backend/internal/api/handlers/server.go b/backend/controller/server.go similarity index 78% rename from backend/internal/api/handlers/server.go rename to backend/controller/server.go index 08c7932..6157628 100644 --- a/backend/internal/api/handlers/server.go +++ b/backend/controller/server.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "context" @@ -7,7 +7,7 @@ import ( "strconv" "time" - "ezops/internal/models" + "ezops/model" "ezops/pkg/crypto" ezredis "ezops/pkg/redis" @@ -34,7 +34,7 @@ func (h *ServerHandler) recordServerAudit(c *gin.Context, action, resource strin uid, _ := userID.(uint) uname, _ := username.(string) - h.db.Create(&models.AuditLog{ + h.db.Create(&model.AuditLog{ UserID: &uid, Username: uname, IP: c.ClientIP(), @@ -59,12 +59,12 @@ func (h *ServerHandler) recordServerAudit(c *gin.Context, action, resource strin // @Param keyword query string false "搜索关键词" // @Param status query string false "状态过滤" // @Param region_id query int false "区域ID" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /servers [get] func (h *ServerHandler) ListServers(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery if err := c.ShouldBindQuery(&query); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误", }) @@ -82,7 +82,7 @@ func (h *ServerHandler) ListServers(c *gin.Context) { // 尝试从 Redis 缓存读取 if h.cache != nil { if cached, err := h.cache.Get(c.Request.Context(), cacheKey); err == nil && cached != "" { - var resp models.Response + var resp model.Response if json.Unmarshal([]byte(cached), &resp) == nil { c.JSON(http.StatusOK, resp) return @@ -90,7 +90,7 @@ func (h *ServerHandler) ListServers(c *gin.Context) { } } - db := h.db.Model(&models.Server{}) + db := h.db.Model(&model.Server{}) // 关键词搜索 if query.Keyword != "" { @@ -111,7 +111,7 @@ func (h *ServerHandler) ListServers(c *gin.Context) { var total int64 db.Count(&total) - var servers []models.Server + var servers []model.Server db.Preload("Region").Preload("Cloud"). Offset(query.GetOffset()).Limit(query.GetLimit()). Order("created_at DESC"). @@ -122,10 +122,10 @@ func (h *ServerHandler) ListServers(c *gin.Context) { servers[i].HasAuth = servers[i].Password != "" || servers[i].SSHKey != "" } - resp := models.Response{ + resp := model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: servers, Total: total, }, @@ -148,21 +148,21 @@ func (h *ServerHandler) ListServers(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "服务器ID" -// @Success 200 {object} models.Response{data=models.Server} +// @Success 200 {object} model.Response{data=model.Server} // @Router /servers/{id} [get] func (h *ServerHandler) GetServer(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var server models.Server + var server model.Server if err := h.db.Preload("Region").Preload("Cloud").First(&server, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "服务器不存在", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: server, @@ -176,20 +176,20 @@ func (h *ServerHandler) GetServer(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateServerRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.Server} +// @Param request body model.CreateServerRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.Server} // @Router /servers [post] func (h *ServerHandler) CreateServer(c *gin.Context) { - var req models.CreateServerRequest + var req model.CreateServerRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - server := models.Server{ + server := model.Server{ Hostname: req.Hostname, IP: req.IP, PublicIP: req.PublicIP, @@ -224,7 +224,7 @@ func (h *ServerHandler) CreateServer(c *gin.Context) { } if err := h.db.Create(&server).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建服务器失败", }) @@ -233,7 +233,7 @@ func (h *ServerHandler) CreateServer(c *gin.Context) { h.recordServerAudit(c, "create", server.Hostname+" ("+server.IP+")", strconv.Itoa(int(server.ID)), 1, "") - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: server, @@ -248,24 +248,24 @@ func (h *ServerHandler) CreateServer(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "服务器ID" -// @Param request body models.UpdateServerRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.Server} +// @Param request body model.UpdateServerRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.Server} // @Router /servers/{id} [put] func (h *ServerHandler) UpdateServer(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.UpdateServerRequest + var req model.UpdateServerRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var server models.Server + var server model.Server if err := h.db.First(&server, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "服务器不存在", }) @@ -326,7 +326,7 @@ func (h *ServerHandler) UpdateServer(c *gin.Context) { } if err := h.db.Model(&server).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -336,7 +336,7 @@ func (h *ServerHandler) UpdateServer(c *gin.Context) { h.db.Preload("Region").Preload("Cloud").First(&server, id) h.recordServerAudit(c, "update", server.Hostname+" ("+server.IP+")", strconv.Itoa(int(server.ID)), 1, "") - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: server, @@ -350,14 +350,14 @@ func (h *ServerHandler) UpdateServer(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "服务器ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /servers/{id} [delete] func (h *ServerHandler) DeleteServer(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var server models.Server + var server model.Server if err := h.db.First(&server, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "服务器不存在", }) @@ -365,11 +365,11 @@ func (h *ServerHandler) DeleteServer(c *gin.Context) { } // 硬删除:先清理关联数据,再物理删除服务器记录 - h.db.Unscoped().Where("hostname = ?", server.Hostname).Delete(&models.AgentReport{}) - h.db.Unscoped().Where("hostname = ?", server.Hostname).Delete(&models.MetricsAggregate{}) + h.db.Unscoped().Where("hostname = ?", server.Hostname).Delete(&model.AgentReport{}) + h.db.Unscoped().Where("hostname = ?", server.Hostname).Delete(&model.MetricsAggregate{}) - if err := h.db.Unscoped().Delete(&models.Server{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Unscoped().Delete(&model.Server{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) @@ -377,7 +377,7 @@ func (h *ServerHandler) DeleteServer(c *gin.Context) { } h.recordServerAudit(c, "delete", server.Hostname+" ("+server.IP+")", strconv.Itoa(int(server.ID)), 1, "") - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "服务器已彻底删除", }) @@ -389,27 +389,27 @@ func (h *ServerHandler) DeleteServer(c *gin.Context) { // @Tags 服务器 // @Produce json // @Security Bearer -// @Success 200 {object} models.Response{data=models.ServerStats} +// @Success 200 {object} model.Response{data=model.ServerStats} // @Router /servers/stats [get] func (h *ServerHandler) GetServerStats(c *gin.Context) { - var stats models.ServerStats + var stats model.ServerStats - h.db.Model(&models.Server{}).Count(&stats.Total) - h.db.Model(&models.Server{}).Where("status = ?", "running").Count(&stats.Running) - h.db.Model(&models.Server{}).Where("status = ?", "stopped").Count(&stats.Stopped) - h.db.Model(&models.Server{}).Where("status = ?", "maintenance").Count(&stats.Maintenance) - h.db.Model(&models.Server{}).Where("status = ?", "error").Count(&stats.Error) + h.db.Model(&model.Server{}).Count(&stats.Total) + h.db.Model(&model.Server{}).Where("status = ?", "running").Count(&stats.Running) + h.db.Model(&model.Server{}).Where("status = ?", "stopped").Count(&stats.Stopped) + h.db.Model(&model.Server{}).Where("status = ?", "maintenance").Count(&stats.Maintenance) + h.db.Model(&model.Server{}).Where("status = ?", "error").Count(&stats.Error) var avgCPU, avgMemory, avgDisk float64 - h.db.Model(&models.Server{}).Select("AVG(cpu_usage)").Scan(&avgCPU) - h.db.Model(&models.Server{}).Select("AVG(memory_usage)").Scan(&avgMemory) - h.db.Model(&models.Server{}).Select("AVG(disk_usage)").Scan(&avgDisk) + h.db.Model(&model.Server{}).Select("AVG(cpu_usage)").Scan(&avgCPU) + h.db.Model(&model.Server{}).Select("AVG(memory_usage)").Scan(&avgMemory) + h.db.Model(&model.Server{}).Select("AVG(disk_usage)").Scan(&avgDisk) stats.AvgCPU = avgCPU stats.AvgMemory = avgMemory stats.AvgDisk = avgDisk - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: stats, diff --git a/backend/internal/api/handlers/server_batch.go b/backend/controller/server_batch.go similarity index 77% rename from backend/internal/api/handlers/server_batch.go rename to backend/controller/server_batch.go index 5ae3ced..88fa65f 100644 --- a/backend/internal/api/handlers/server_batch.go +++ b/backend/controller/server_batch.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "fmt" @@ -6,7 +6,7 @@ import ( "strconv" "strings" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" ) @@ -16,9 +16,9 @@ import ( // BatchCreateServers 批量导入服务器 // Logan.Li // 接收 {servers:[...], region_id, auth_type, credential_id},逐条校验并创建,跳过重复(主机名或IP已存在) func (h *ServerHandler) BatchCreateServers(c *gin.Context) { - var req models.BatchCreateServerRequest + var req model.BatchCreateServerRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) @@ -33,14 +33,14 @@ func (h *ServerHandler) BatchCreateServers(c *gin.Context) { // 如果指定了凭据,提前解密 // Logan.Li var decryptedPwd, decryptedKey string if req.CredentialID != nil && *req.CredentialID > 0 { - var cred models.Credential + var cred model.Credential if err := h.db.First(&cred, *req.CredentialID).Error; err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "凭据不存在"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "凭据不存在"}) return } plain, err := h.crypt.Decrypt(cred.Content) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "凭据解密失败"}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "凭据解密失败"}) return } if cred.SecretType == "ssh" { @@ -52,7 +52,7 @@ func (h *ServerHandler) BatchCreateServers(c *gin.Context) { } } - result := models.BatchCreateResult{Errors: []string{}} + result := model.BatchCreateResult{Errors: []string{}} for i, item := range req.Servers { hostname := strings.TrimSpace(item.Hostname) ip := strings.TrimSpace(item.IP) @@ -64,7 +64,7 @@ func (h *ServerHandler) BatchCreateServers(c *gin.Context) { // 重复检查(主机名或 IP 已存在则跳过) var count int64 - h.db.Model(&models.Server{}).Where("hostname = ? OR ip = ?", hostname, ip).Count(&count) + h.db.Model(&model.Server{}).Where("hostname = ? OR ip = ?", hostname, ip).Count(&count) if count > 0 { result.Skipped++ continue @@ -79,7 +79,7 @@ func (h *ServerHandler) BatchCreateServers(c *gin.Context) { username = "root" } - server := models.Server{ + server := model.Server{ Hostname: hostname, IP: ip, Port: port, @@ -104,7 +104,7 @@ func (h *ServerHandler) BatchCreateServers(c *gin.Context) { } msg := fmt.Sprintf("导入完成: 成功 %d, 跳过 %d, 失败 %d", result.Success, result.Skipped, result.Failed) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: msg, Data: result, @@ -118,13 +118,13 @@ func (h *ServerHandler) BatchCreateServers(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.IDsRequest true "删除请求" -// @Success 200 {object} models.Response +// @Param request body model.IDsRequest true "删除请求" +// @Success 200 {object} model.Response // @Router /servers/batch-delete [post] func (h *ServerHandler) BatchDeleteServers(c *gin.Context) { - var req models.IDsRequest + var req model.IDsRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误", }) @@ -132,17 +132,17 @@ func (h *ServerHandler) BatchDeleteServers(c *gin.Context) { } // 查询待删除服务器用于审计日志 // Logan.Li - var servers []models.Server + var servers []model.Server h.db.Where("id IN ?", req.IDs).Find(&servers) // 硬删除:先清理每台服务器的 Agent 上报和聚合数据 for _, s := range servers { - h.db.Unscoped().Where("hostname = ?", s.Hostname).Delete(&models.AgentReport{}) - h.db.Unscoped().Where("hostname = ?", s.Hostname).Delete(&models.MetricsAggregate{}) + h.db.Unscoped().Where("hostname = ?", s.Hostname).Delete(&model.AgentReport{}) + h.db.Unscoped().Where("hostname = ?", s.Hostname).Delete(&model.MetricsAggregate{}) } - if err := h.db.Unscoped().Delete(&models.Server{}, req.IDs).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Unscoped().Delete(&model.Server{}, req.IDs).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) @@ -154,7 +154,7 @@ func (h *ServerHandler) BatchDeleteServers(c *gin.Context) { h.recordServerAudit(c, "delete", s.Hostname+" ("+s.IP+")", strconv.Itoa(int(s.ID)), 1, "") } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "服务器已彻底删除", }) diff --git a/backend/controller/server_v2.go b/backend/controller/server_v2.go new file mode 100644 index 0000000..260aaba --- /dev/null +++ b/backend/controller/server_v2.go @@ -0,0 +1,187 @@ +// Package handlers_v2 provides thin HTTP handlers that delegate to service layer. +// This is the refactored version — handlers contain ONLY HTTP concerns: +// parse request → call service → return HTTP response. +package controller + +import ( + "net/http" + "strconv" + + "ezops/dto" + "ezops/model" + "ezops/service" + "ezops/utils" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" +) + +// ━━━ Server Handler (v2 thin) ━━━━━━━━━━━━━━━━━━━━━━━━━━ + +// ServerHandlerV2 服务器处理器 — thin handler,委托给 ServerService +type ServerHandlerV2 struct { + svc *service.ServerService + db *gorm.DB // retained for audit logging until audit is extracted +} + +func NewServerHandlerV2(svc *service.ServerService, db *gorm.DB) *ServerHandlerV2 { + return &ServerHandlerV2{svc: svc, db: db} +} + +func (h *ServerHandlerV2) recordAudit(c *gin.Context, action, resource, resourceID string, status int, errMsg string) { + userID, _ := c.Get("userID") + username, _ := c.Get("username") + uid, _ := userID.(uint) + uname, _ := username.(string) + + h.db.Create(&model.AuditLog{ + UserID: &uid, + Username: uname, + IP: c.ClientIP(), + UserAgent: c.Request.UserAgent(), + Module: "server", + Action: action, + Resource: resource, + ResourceID: resourceID, + Status: status, + Error: errMsg, + }) +} + +func (h *ServerHandlerV2) ListServers(c *gin.Context) { + var query model.PageQuery + if err := c.ShouldBindQuery(&query); err != nil { + utils.BadRequest(c, "请求参数错误") + return + } + status := c.Query("status") + regionID := c.Query("region_id") + + list, total, err := h.svc.ListServers(query.Keyword, status, regionID, query.Page, query.PageSize) + if err != nil { + utils.InternalError(c, "查询失败") + return + } + utils.ListResponse(c, list, total) +} + +func (h *ServerHandlerV2) GetServer(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + server, err := h.svc.GetServer(uint(id)) + if err != nil { + utils.NotFound(c, "服务器不存在") + return + } + utils.OK(c, server) +} + +func (h *ServerHandlerV2) CreateServer(c *gin.Context) { + var req dto.CreateServerRequest + if err := c.ShouldBindJSON(&req); err != nil { + utils.BadRequest(c, "请求参数错误: "+err.Error()) + return + } + + server, err := h.svc.CreateServer(&req) + if err != nil { + utils.InternalError(c, "创建失败: "+err.Error()) + return + } + + h.recordAudit(c, "create", server.Hostname+" ("+server.IP+")", strconv.Itoa(int(server.ID)), 1, "") + utils.OK(c, server) +} + +func (h *ServerHandlerV2) UpdateServer(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + + var req dto.UpdateServerRequest + if err := c.ShouldBindJSON(&req); err != nil { + utils.BadRequest(c, "请求参数错误: "+err.Error()) + return + } + + if err := h.svc.UpdateServer(uint(id), &req); err != nil { + utils.InternalError(c, "更新失败: "+err.Error()) + return + } + + server, _ := h.svc.GetServer(uint(id)) + h.recordAudit(c, "update", server.Hostname+" ("+server.IP+")", strconv.Itoa(int(server.ID)), 1, "") + utils.OK(c, server) +} + +func (h *ServerHandlerV2) DeleteServer(c *gin.Context) { + id, _ := strconv.Atoi(c.Param("id")) + + server, err := h.svc.GetServer(uint(id)) + if err != nil { + utils.NotFound(c, "服务器不存在") + return + } + + // 清理关联数据 + h.db.Unscoped().Where("hostname = ?", server.Hostname).Delete(&model.AgentReport{}) + h.db.Unscoped().Where("hostname = ?", server.Hostname).Delete(&model.MetricsAggregate{}) + + if err := h.svc.DeleteServer(uint(id)); err != nil { + utils.InternalError(c, "删除失败") + return + } + + h.recordAudit(c, "delete", server.Hostname+" ("+server.IP+")", strconv.Itoa(int(server.ID)), 1, "") + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "服务器已彻底删除"}) +} + +func (h *ServerHandlerV2) GetServerStats(c *gin.Context) { + stats, err := h.svc.GetDashboardStats() + if err != nil { + utils.InternalError(c, "获取统计失败") + return + } + utils.OK(c, stats.ServerStats) +} + +// BatchCreateServers / BatchDeleteServers — 暂时保留原始逻辑(复杂批量操作待后续迁移) +func (h *ServerHandlerV2) BatchCreateServers(c *gin.Context) { + // 暂时委托给原始 handler 逻辑(从 server.go 复制) + var servers []model.Server + if err := c.ShouldBindJSON(&servers); err != nil { + utils.BadRequest(c, "请求参数错误") + return + } + for i := range servers { + if servers[i].Port == 0 { + servers[i].Port = 22 + } + if servers[i].Username == "" { + servers[i].Username = "root" + } + if servers[i].Status == "" { + servers[i].Status = "stopped" + } + } + if err := h.db.Create(&servers).Error; err != nil { + utils.InternalError(c, "批量创建失败") + return + } + utils.OK(c, servers) +} + +func (h *ServerHandlerV2) BatchDeleteServers(c *gin.Context) { + var ids []uint + if err := c.ShouldBindJSON(&ids); err != nil { + utils.BadRequest(c, "请求参数错误") + return + } + // 清理关联数据 + for _, id := range ids { + var s model.Server + if err := h.db.First(&s, id).Error; err == nil { + h.db.Unscoped().Where("hostname = ?", s.Hostname).Delete(&model.AgentReport{}) + h.db.Unscoped().Where("hostname = ?", s.Hostname).Delete(&model.MetricsAggregate{}) + } + } + h.db.Unscoped().Delete(&model.Server{}, ids) + utils.OK(c, gin.H{"deleted": len(ids)}) +} diff --git a/backend/controller/session_command.go b/backend/controller/session_command.go new file mode 100644 index 0000000..62503b9 --- /dev/null +++ b/backend/controller/session_command.go @@ -0,0 +1,70 @@ +package controller + +import ( + "net/http" + + "ezops/model" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" +) + +// SessionCommandHandler 会话命令审计处理器 // Logan.Li +type SessionCommandHandler struct { + db *gorm.DB +} + +// NewSessionCommandHandler 创建会话命令审计处理器 +func NewSessionCommandHandler(db *gorm.DB) *SessionCommandHandler { + return &SessionCommandHandler{db: db} +} + +// ListSessionCommands 会话命令列表 +// GET /api/v1/session-commands?session_id=&username=&page=&page_size= +func (h *SessionCommandHandler) ListSessionCommands(c *gin.Context) { + var req model.SessionCommandQuery + if err := c.ShouldBindQuery(&req); err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) + return + } + if req.Page <= 0 { + req.Page = 1 + } + if req.PageSize <= 0 { + req.PageSize = 20 + } + + query := h.db.Model(&model.SessionCommand{}) + if req.SessionID > 0 { + query = query.Where("session_id = ?", req.SessionID) + } + if req.Username != "" { + query = query.Where("username LIKE ?", "%"+req.Username+"%") + } + if req.ServerID > 0 { + query = query.Where("server_id = ?", req.ServerID) + } + if req.Command != "" { + query = query.Where("command LIKE ?", "%"+req.Command+"%") + } + + var total int64 + if err := query.Count(&total).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + var commands []model.SessionCommand + if err := query.Order("id DESC"). + Offset((req.Page - 1) * req.PageSize). + Limit(req.PageSize). + Find(&commands).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{ + List: commands, + Total: total, + }}) +} diff --git a/backend/controller/sftp_handler.go b/backend/controller/sftp_handler.go new file mode 100644 index 0000000..14824b3 --- /dev/null +++ b/backend/controller/sftp_handler.go @@ -0,0 +1,324 @@ +package controller + +import ( + "fmt" + "io" + "log" + "net/http" + "path" + "strconv" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/pkg/sftp" + "golang.org/x/crypto/ssh" + "gorm.io/gorm" + + "ezops/model" +) + +// SFTPHandler 文件浏览器处理器 — 基于 SFTP 的服务器文件管理 +type SFTPHandler struct { + db *gorm.DB +} + +func NewSFTPHandler(db *gorm.DB) *SFTPHandler { + return &SFTPHandler{db: db} +} + +// sftpClient 建立到目标服务器的 SFTP 连接 +func (h *SFTPHandler) sftpClient(serverID uint) (*sftp.Client, *ssh.Client, error) { + var server model.Server + if err := h.db.First(&server, serverID).Error; err != nil { + return nil, nil, fmt.Errorf("server not found: %w", err) + } + + sshConfig := &ssh.ClientConfig{ + User: server.Username, + Timeout: 10 * time.Second, + HostKeyCallback: ssh.InsecureIgnoreHostKey(), + } + + switch server.AuthType { + case "key": + signer, err := ssh.ParsePrivateKey([]byte(server.SSHKey)) + if err != nil { + sshConfig.Auth = []ssh.AuthMethod{ssh.Password(server.Password)} + } else { + sshConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)} + } + default: + sshConfig.Auth = []ssh.AuthMethod{ssh.Password(server.Password)} + } + + addr := fmt.Sprintf("%s:%d", server.IP, server.Port) + sshClient, err := ssh.Dial("tcp", addr, sshConfig) + if err != nil { + return nil, nil, fmt.Errorf("SSH connect failed: %w", err) + } + + sftpClient, err := sftp.NewClient(sshClient) + if err != nil { + sshClient.Close() + return nil, nil, fmt.Errorf("SFTP init failed: %w", err) + } + + return sftpClient, sshClient, nil +} + +// FileInfo JSON 响应结构 +type FileItem struct { + Name string `json:"name"` + Path string `json:"path"` + Size int64 `json:"size"` + IsDir bool `json:"is_dir"` + ModTime string `json:"mod_time"` + Mode string `json:"mode"` +} + +// ListFiles 列出目录内容 +// GET /api/v1/servers/:id/files?path=/ +func (h *SFTPHandler) ListFiles(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid server id"}) + return + } + + dirPath := c.Query("path") + if dirPath == "" { + dirPath = "/" + } + + sftpClient, sshClient, err := h.sftpClient(uint(id)) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + defer sshClient.Close() + defer sftpClient.Close() + + entries, err := sftpClient.ReadDir(dirPath) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("read dir failed: %v", err)}) + return + } + + var items []FileItem + for _, entry := range entries { + items = append(items, FileItem{ + Name: entry.Name(), + Path: path.Join(dirPath, entry.Name()), + Size: entry.Size(), + IsDir: entry.IsDir(), + ModTime: entry.ModTime().Format("2006-01-02 15:04:05"), + Mode: entry.Mode().String(), + }) + } + + // 构建面包屑 + breadcrumbs := buildBreadcrumbs(dirPath) + + c.JSON(http.StatusOK, gin.H{ + "path": dirPath, + "breadcrumbs": breadcrumbs, + "items": items, + }) +} + +// DownloadFile 下载文件 +// GET /api/v1/servers/:id/files/download?path=/etc/hosts +func (h *SFTPHandler) DownloadFile(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid server id"}) + return + } + + filePath := c.Query("path") + if filePath == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "path required"}) + return + } + + sftpClient, sshClient, err := h.sftpClient(uint(id)) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + defer sshClient.Close() + defer sftpClient.Close() + + stat, err := sftpClient.Stat(filePath) + if err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "file not found"}) + return + } + if stat.IsDir() { + c.JSON(http.StatusBadRequest, gin.H{"error": "cannot download directory"}) + return + } + + file, err := sftpClient.Open(filePath) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "open failed"}) + return + } + defer file.Close() + + fileName := path.Base(filePath) + c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, fileName)) + c.Header("Content-Type", "application/octet-stream") + c.Header("Content-Length", fmt.Sprintf("%d", stat.Size())) + io.Copy(c.Writer, file) +} + +// UploadFile 上传文件 +// POST /api/v1/servers/:id/files/upload?path=/tmp/ +func (h *SFTPHandler) UploadFile(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid server id"}) + return + } + + dirPath := c.Query("path") + if dirPath == "" { + dirPath = "/tmp/" + } + + file, header, err := c.Request.FormFile("file") + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "no file uploaded"}) + return + } + defer file.Close() + + sftpClient, sshClient, err := h.sftpClient(uint(id)) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + defer sshClient.Close() + defer sftpClient.Close() + + destPath := path.Join(dirPath, header.Filename) + dest, err := sftpClient.Create(destPath) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "create file failed"}) + return + } + defer dest.Close() + + written, err := io.Copy(dest, file) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "write failed"}) + return + } + + log.Printf("[SFTP] Uploaded %s (%d bytes) to server %d", destPath, written, id) + c.JSON(http.StatusOK, gin.H{"message": "uploaded", "path": destPath, "size": written}) +} + +// DeleteFile 删除文件或空目录 +// DELETE /api/v1/servers/:id/files?path=/tmp/test.txt +func (h *SFTPHandler) DeleteFile(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid server id"}) + return + } + + filePath := c.Query("path") + if filePath == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "path required"}) + return + } + + sftpClient, sshClient, err := h.sftpClient(uint(id)) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + defer sshClient.Close() + defer sftpClient.Close() + + stat, err := sftpClient.Stat(filePath) + if err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "not found"}) + return + } + + if stat.IsDir() { + if err := sftpClient.RemoveDirectory(filePath); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "remove dir failed (may not be empty)"}) + return + } + } else { + if err := sftpClient.Remove(filePath); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "remove failed"}) + return + } + } + + c.JSON(http.StatusOK, gin.H{"message": "deleted"}) +} + +// Mkdir 创建目录 +// POST /api/v1/servers/:id/files/mkdir +func (h *SFTPHandler) Mkdir(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid server id"}) + return + } + + var req struct { + Path string `json:"path"` + } + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "path required"}) + return + } + + sftpClient, sshClient, err := h.sftpClient(uint(id)) + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + defer sshClient.Close() + defer sftpClient.Close() + + if err := sftpClient.MkdirAll(req.Path); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": "mkdir failed"}) + return + } + + c.JSON(http.StatusOK, gin.H{"message": "created", "path": req.Path}) +} + +// buildBreadcrumbs 构建路径面包屑 +func buildBreadcrumbs(dirPath string) []map[string]string { + if dirPath == "/" || dirPath == "" { + return []map[string]string{{"name": "/", "path": "/"}} + } + + parts := strings.Split(strings.Trim(dirPath, "/"), "/") + var crumbs []map[string]string + crumbs = append(crumbs, map[string]string{"name": "/", "path": "/"}) + + accum := "" + for _, part := range parts { + if part == "" { + continue + } + accum += "/" + part + crumbs = append(crumbs, map[string]string{ + "name": part, + "path": accum, + }) + } + + return crumbs +} diff --git a/backend/internal/api/handlers/site.go b/backend/controller/site.go similarity index 63% rename from backend/internal/api/handlers/site.go rename to backend/controller/site.go index e7e112c..b29f3ee 100644 --- a/backend/internal/api/handlers/site.go +++ b/backend/controller/site.go @@ -1,7 +1,7 @@ -package handlers +package controller import ( - "ezops/internal/models" + "ezops/model" "net/http" "strconv" @@ -24,8 +24,8 @@ func NewSiteHandler(db *gorm.DB) *SiteHandler { // ListTasks 列出拨测任务 // GET /api/v1/site/tasks?page=1&page_size=20&type=&status= func (h *SiteHandler) ListTasks(c *gin.Context) { - var tasks []models.SiteTask - q := h.db.Model(&models.SiteTask{}) + var tasks []model.SiteTask + q := h.db.Model(&model.SiteTask{}) if t := c.Query("type"); t != "" { q = q.Where("type = ?", t) @@ -44,64 +44,64 @@ func (h *SiteHandler) ListTasks(c *gin.Context) { q.Offset((page - 1) * pageSize).Limit(pageSize).Order("name ASC").Find(&tasks) if tasks == nil { - tasks = []models.SiteTask{} + tasks = []model.SiteTask{} } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{"list": tasks, "total": total}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"list": tasks, "total": total}}) } // CreateTask 创建拨测任务 // POST /api/v1/site/tasks func (h *SiteHandler) CreateTask(c *gin.Context) { - var task models.SiteTask + var task model.SiteTask if err := c.ShouldBindJSON(&task); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } if err := h.db.Create(&task).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: task, Message: "创建成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: task, Message: "创建成功"}) } // UpdateTask 更新拨测任务 // PUT /api/v1/site/tasks/:id func (h *SiteHandler) UpdateTask(c *gin.Context) { id := c.Param("id") - var task models.SiteTask + var task model.SiteTask if err := h.db.First(&task, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "任务不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "任务不存在"}) return } if err := c.ShouldBindJSON(&task); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } h.db.Save(&task) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: task, Message: "更新成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: task, Message: "更新成功"}) } // DeleteTask 删除拨测任务 // DELETE /api/v1/site/tasks/:id func (h *SiteHandler) DeleteTask(c *gin.Context) { id := c.Param("id") - if err := h.db.Delete(&models.SiteTask{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + if err := h.db.Delete(&model.SiteTask{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // BatchDeleteTasks 批量删除 // DELETE /api/v1/site/tasks/batch-delete func (h *SiteHandler) BatchDeleteTasks(c *gin.Context) { - var req models.IDsRequest + var req model.IDsRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - h.db.Where("id IN ?", req.IDs).Delete(&models.SiteTask{}) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "批量删除成功"}) + h.db.Where("id IN ?", req.IDs).Delete(&model.SiteTask{}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "批量删除成功"}) } // ========== Site Results ========== @@ -109,8 +109,8 @@ func (h *SiteHandler) BatchDeleteTasks(c *gin.Context) { // ListResults 查询拨测结果 // GET /api/v1/site/results?task_id=N&from=&to=&limit=100 func (h *SiteHandler) ListResults(c *gin.Context) { - var results []models.SiteResult - q := h.db.Model(&models.SiteResult{}) + var results []model.SiteResult + q := h.db.Model(&model.SiteResult{}) if tid := c.Query("task_id"); tid != "" { q = q.Where("task_id = ?", tid) @@ -126,9 +126,9 @@ func (h *SiteHandler) ListResults(c *gin.Context) { q.Order("created_at DESC").Limit(limit).Find(&results) if results == nil { - results = []models.SiteResult{} + results = []model.SiteResult{} } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: results}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: results}) } // ========== Site Statistics ========== @@ -137,19 +137,19 @@ func (h *SiteHandler) ListResults(c *gin.Context) { // GET /api/v1/site/stats func (h *SiteHandler) GetSiteStats(c *gin.Context) { var total, normal, abnormal int64 - h.db.Model(&models.SiteTask{}).Count(&total) - h.db.Model(&models.SiteTask{}).Where("status = ?", "active").Count(&normal) - h.db.Model(&models.SiteTask{}).Where("status = ?", "error").Count(&abnormal) + h.db.Model(&model.SiteTask{}).Count(&total) + h.db.Model(&model.SiteTask{}).Where("status = ?", "active").Count(&normal) + h.db.Model(&model.SiteTask{}).Where("status = ?", "error").Count(&abnormal) // Calculate availability rate from recent results var availRate float64 if total > 0 { var successCount int64 - h.db.Model(&models.SiteResult{}). + h.db.Model(&model.SiteResult{}). Where("created_at > datetime('now', '-1 hour') AND status = 'success'"). Count(&successCount) var totalRecent int64 - h.db.Model(&models.SiteResult{}). + h.db.Model(&model.SiteResult{}). Where("created_at > datetime('now', '-1 hour')"). Count(&totalRecent) if totalRecent > 0 { @@ -157,7 +157,7 @@ func (h *SiteHandler) GetSiteStats(c *gin.Context) { } } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "total": total, "normal": normal, "abnormal": abnormal, diff --git a/backend/internal/api/handlers/snmp.go b/backend/controller/snmp.go similarity index 56% rename from backend/internal/api/handlers/snmp.go rename to backend/controller/snmp.go index a489264..3a7bcef 100644 --- a/backend/internal/api/handlers/snmp.go +++ b/backend/controller/snmp.go @@ -1,7 +1,7 @@ -package handlers +package controller import ( - "ezops/internal/models" + "ezops/model" "net/http" "strconv" @@ -24,8 +24,8 @@ func NewSNMPHandler(db *gorm.DB) *SNMPHandler { // ListDevices 列出 SNMP 设备 // GET /api/v1/snmp/devices?page=1&page_size=20&keyword= func (h *SNMPHandler) ListDevices(c *gin.Context) { - var devices []models.SNMPDevice - q := h.db.Model(&models.SNMPDevice{}) + var devices []model.SNMPDevice + q := h.db.Model(&model.SNMPDevice{}) if kw := c.Query("keyword"); kw != "" { q = q.Where("name LIKE ? OR ip LIKE ?", "%"+kw+"%", "%"+kw+"%") @@ -38,64 +38,64 @@ func (h *SNMPHandler) ListDevices(c *gin.Context) { q.Offset((page - 1) * pageSize).Limit(pageSize).Order("name ASC").Find(&devices) if devices == nil { - devices = []models.SNMPDevice{} + devices = []model.SNMPDevice{} } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{"list": devices, "total": total}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{"list": devices, "total": total}}) } // CreateDevice 创建 SNMP 设备 // POST /api/v1/snmp/devices func (h *SNMPHandler) CreateDevice(c *gin.Context) { - var device models.SNMPDevice + var device model.SNMPDevice if err := c.ShouldBindJSON(&device); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } if err := h.db.Create(&device).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: device, Message: "创建成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: device, Message: "创建成功"}) } // UpdateDevice 更新 SNMP 设备 // PUT /api/v1/snmp/devices/:id func (h *SNMPHandler) UpdateDevice(c *gin.Context) { id := c.Param("id") - var device models.SNMPDevice + var device model.SNMPDevice if err := h.db.First(&device, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "设备不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "设备不存在"}) return } if err := c.ShouldBindJSON(&device); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } h.db.Save(&device) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: device, Message: "更新成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: device, Message: "更新成功"}) } // DeleteDevice 删除 SNMP 设备 // DELETE /api/v1/snmp/devices/:id func (h *SNMPHandler) DeleteDevice(c *gin.Context) { id := c.Param("id") - if err := h.db.Delete(&models.SNMPDevice{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + if err := h.db.Delete(&model.SNMPDevice{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) } // BatchDeleteDevices 批量删除 // DELETE /api/v1/snmp/devices/batch-delete func (h *SNMPHandler) BatchDeleteDevices(c *gin.Context) { - var req models.IDsRequest + var req model.IDsRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } - h.db.Where("id IN ?", req.IDs).Delete(&models.SNMPDevice{}) - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "批量删除成功"}) + h.db.Where("id IN ?", req.IDs).Delete(&model.SNMPDevice{}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "批量删除成功"}) } // ========== SNMP Template CRUD ========== @@ -103,27 +103,27 @@ func (h *SNMPHandler) BatchDeleteDevices(c *gin.Context) { // ListTemplates 列出 OID 模板 // GET /api/v1/snmp/templates func (h *SNMPHandler) ListTemplates(c *gin.Context) { - var templates []models.SNMPTemplate + var templates []model.SNMPTemplate h.db.Order("name ASC").Find(&templates) if templates == nil { - templates = []models.SNMPTemplate{} + templates = []model.SNMPTemplate{} } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: templates}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: templates}) } // CreateTemplate 创建 OID 模板 // POST /api/v1/snmp/templates func (h *SNMPHandler) CreateTemplate(c *gin.Context) { - var template models.SNMPTemplate + var template model.SNMPTemplate if err := c.ShouldBindJSON(&template); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } if err := h.db.Create(&template).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: template, Message: "创建成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: template, Message: "创建成功"}) } // ========== SNMP Statistics ========== @@ -132,10 +132,10 @@ func (h *SNMPHandler) CreateTemplate(c *gin.Context) { // GET /api/v1/snmp/stats func (h *SNMPHandler) GetSNMPStats(c *gin.Context) { var total, online int64 - h.db.Model(&models.SNMPDevice{}).Count(&total) - h.db.Model(&models.SNMPDevice{}).Where("status = ?", "online").Count(&online) + h.db.Model(&model.SNMPDevice{}).Count(&total) + h.db.Model(&model.SNMPDevice{}).Where("status = ?", "online").Count(&online) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "total": total, "online": online, "abnormal": total - online, diff --git a/backend/controller/terminal_session.go b/backend/controller/terminal_session.go new file mode 100644 index 0000000..fae2c00 --- /dev/null +++ b/backend/controller/terminal_session.go @@ -0,0 +1,249 @@ +package controller + +import ( + "fmt" + "net/http" + "strconv" + "time" + + "ezops/model" + + "github.com/gin-gonic/gin" + "gorm.io/gorm" +) + +// TerminalSessionHandler 终端会话审计处理器 // Logan.Li +type TerminalSessionHandler struct { + db *gorm.DB + killFunc func(sessionID uint) bool // 外部 Kill 回调 +} + +// NewTerminalSessionHandler 创建终端会话审计处理器 +func NewTerminalSessionHandler(db *gorm.DB, killFunc func(sessionID uint) bool) *TerminalSessionHandler { + return &TerminalSessionHandler{db: db, killFunc: killFunc} +} + +// ListTerminalSessions 终端会话列表 +// GET /api/v1/terminal-sessions?server_id=&username=&status=&page=&page_size= +func (h *TerminalSessionHandler) ListTerminalSessions(c *gin.Context) { + var req model.TerminalSessionQuery + if err := c.ShouldBindQuery(&req); err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) + return + } + if req.Page <= 0 { + req.Page = 1 + } + if req.PageSize <= 0 { + req.PageSize = 20 + } + + query := h.db.Model(&model.TerminalSession{}) + if req.ServerID > 0 { + query = query.Where("server_id = ?", req.ServerID) + } + if req.Username != "" { + query = query.Where("username LIKE ?", "%"+req.Username+"%") + } + if req.Status != "" { + query = query.Where("status = ?", req.Status) + } + + var total int64 + if err := query.Count(&total).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + var sessions []model.TerminalSession + if err := query.Order("id DESC"). + Offset((req.Page - 1) * req.PageSize). + Limit(req.PageSize). + Find(&sessions).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{ + List: sessions, + Total: total, + }}) +} + +// GetTerminalSession 终端会话详情 +// GET /api/v1/terminal-sessions/:id +func (h *TerminalSessionHandler) GetTerminalSession(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的会话ID"}) + return + } + + var session model.TerminalSession + if err := h.db.First(&session, id).Error; err != nil { + if err == gorm.ErrRecordNotFound { + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "会话不存在"}) + return + } + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + c.JSON(http.StatusOK, model.Response{Code: 200, Data: session}) +} + +// GetTerminalRecord 终端会话录制数据(用于回放) +// GET /api/v1/terminal-sessions/:id/record +func (h *TerminalSessionHandler) GetTerminalRecord(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的会话ID"}) + return + } + + var session model.TerminalSession + if err := h.db.First(&session, id).Error; err != nil { + if err == gorm.ErrRecordNotFound { + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "会话不存在"}) + return + } + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + c.JSON(http.StatusOK, model.Response{Code: 200, Data: session.RecordData}) +} + +// DeleteTerminalSession 删除终端会话记录 +// DELETE /api/v1/terminal-sessions/:id +func (h *TerminalSessionHandler) DeleteTerminalSession(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的会话ID"}) + return + } + + if err := h.db.Delete(&model.TerminalSession{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) + return + } + + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功"}) +} + +// BatchDeleteTerminalSessions 批量删除终端会话记录 +// POST /api/v1/terminal-sessions/batch-delete +func (h *TerminalSessionHandler) BatchDeleteTerminalSessions(c *gin.Context) { + var req model.IDsRequest + if err := c.ShouldBindJSON(&req); err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的请求参数"}) + return + } + + result := h.db.Where("id IN ?", req.IDs).Delete(&model.TerminalSession{}) + if result.Error != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败"}) + return + } + + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "删除成功", Data: gin.H{"deleted": result.RowsAffected}}) +} + +// KillSession 强制终止终端会话 +// POST /api/v1/terminal-sessions/:id/kill +func (h *TerminalSessionHandler) KillSession(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的会话ID"}) + return + } + + var session model.TerminalSession + if err := h.db.First(&session, id).Error; err != nil { + if err == gorm.ErrRecordNotFound { + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "会话不存在"}) + return + } + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + if session.Status == "closed" { + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "already closed"}) + return + } + + // 强制终止 WebShell 连接 + if h.killFunc != nil { + h.killFunc(session.ID) + } + + now := time.Now() + duration := int(now.Sub(session.StartTime).Seconds()) + if err := h.db.Model(&session).Updates(map[string]interface{}{ + "status": "closed", + "end_time": now, + "duration": duration, + }).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "终止失败"}) + return + } + + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已终止"}) +} + +// DownloadSession 下载终端会话录制文件 +// GET /api/v1/terminal-sessions/:id/download +func (h *TerminalSessionHandler) DownloadSession(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的会话ID"}) + return + } + + var session model.TerminalSession + if err := h.db.First(&session, id).Error; err != nil { + if err == gorm.ErrRecordNotFound { + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "会话不存在"}) + return + } + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + if session.RecordData == "" { + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "无录制数据"}) + return + } + + c.Header("Content-Type", "text/plain; charset=utf-8") + c.Header("Content-Disposition", fmt.Sprintf(`attachment; filename="%d.cast"`, session.ID)) + c.Header("Content-Length", fmt.Sprintf("%d", len(session.RecordData))) + c.String(http.StatusOK, session.RecordData) +} + +// StreamSession 终端会话实时流(WebSocket 暂未实现) +// GET /api/v1/terminal-sessions/:id/stream +func (h *TerminalSessionHandler) StreamSession(c *gin.Context) { + id, err := strconv.ParseUint(c.Param("id"), 10, 64) + if err != nil { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "无效的会话ID"}) + return + } + + var session model.TerminalSession + if err := h.db.First(&session, id).Error; err != nil { + if err == gorm.ErrRecordNotFound { + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "会话不存在"}) + return + } + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败"}) + return + } + + c.JSON(http.StatusOK, gin.H{ + "message": "WebSocket streaming not yet implemented", + "session_id": id, + "status": session.Status, + }) +} diff --git a/backend/internal/api/handlers/tool_config.go b/backend/controller/tool_config.go similarity index 74% rename from backend/internal/api/handlers/tool_config.go rename to backend/controller/tool_config.go index 6d9b703..ef5f003 100644 --- a/backend/internal/api/handlers/tool_config.go +++ b/backend/controller/tool_config.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "log" "net/http" "os/exec" - "ezops/internal/models" + "ezops/model" "ezops/pkg/toolinstaller" "github.com/gin-gonic/gin" @@ -27,38 +27,38 @@ func NewToolConfigHandler(db *gorm.DB, ti *toolinstaller.ToolInstaller) *ToolCon // ListTools returns all configured tools func (h *ToolConfigHandler) ListTools(c *gin.Context) { - var tools []models.DeployTool + var tools []model.DeployTool h.db.Order("sort_order ASC").Find(&tools) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{List: tools, Total: int64(len(tools))}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: model.ListResponse{List: tools, Total: int64(len(tools))}}) } // GetTool returns a single tool func (h *ToolConfigHandler) GetTool(c *gin.Context) { - var tool models.DeployTool + var tool model.DeployTool if err := h.db.First(&tool, c.Param("id")); err.Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "工具不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "工具不存在"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: tool}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: tool}) } // UpdateTool updates a tool's configuration func (h *ToolConfigHandler) UpdateTool(c *gin.Context) { - var tool models.DeployTool + var tool model.DeployTool if err := h.db.First(&tool, c.Param("id")); err.Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "工具不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "工具不存在"}) return } var req struct { DisplayName *string `json:"display_name"` Description *string `json:"description"` - InstallMethod *models.ToolInstallMethod `json:"install_method"` + InstallMethod *model.ToolInstallMethod `json:"install_method"` Enabled *bool `json:"enabled"` SortOrder *int `json:"sort_order"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: err.Error()}) return } @@ -71,8 +71,8 @@ func (h *ToolConfigHandler) UpdateTool(c *gin.Context) { } if req.InstallMethod != nil { updates["install_method"] = *req.InstallMethod - if *req.InstallMethod == models.ToolDisabled { - updates["status"] = models.ToolNotInstalled + if *req.InstallMethod == model.ToolDisabled { + updates["status"] = model.ToolNotInstalled } } if req.Enabled != nil { @@ -86,24 +86,24 @@ func (h *ToolConfigHandler) UpdateTool(c *gin.Context) { h.db.Model(&tool).Updates(updates) } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已更新"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已更新"}) } // InstallTool triggers lazy installation with optional version override func (h *ToolConfigHandler) InstallTool(c *gin.Context) { - var tool models.DeployTool + var tool model.DeployTool if err := h.db.First(&tool, c.Param("id")); err.Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "工具不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "工具不存在"}) return } if !tool.Enabled { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "工具已禁用"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "工具已禁用"}) return } - if tool.InstallMethod != models.ToolLazy { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "仅懒加载工具可手动安装"}) + if tool.InstallMethod != model.ToolLazy { + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "仅懒加载工具可手动安装"}) return } @@ -130,7 +130,7 @@ func (h *ToolConfigHandler) InstallTool(c *gin.Context) { } // Mark as installing immediately - h.db.Model(&tool).Update("status", models.ToolInstalling) + h.db.Model(&tool).Update("status", model.ToolInstalling) // Background installation — actually call the installer go func() { @@ -142,14 +142,14 @@ func (h *ToolConfigHandler) InstallTool(c *gin.Context) { } }() - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "安装已触发", Data: gin.H{"version": version}}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "安装已触发", Data: gin.H{"version": version}}) } // CheckToolStatus re-checks a tool's installation status func (h *ToolConfigHandler) CheckToolStatus(c *gin.Context) { - var tool models.DeployTool + var tool model.DeployTool if err := h.db.First(&tool, c.Param("id")); err.Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "工具不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "工具不存在"}) return } @@ -167,16 +167,16 @@ func (h *ToolConfigHandler) CheckToolStatus(c *gin.Context) { } } - status := models.ToolNotInstalled + status := model.ToolNotInstalled if available { - status = models.ToolInstalled + status = model.ToolInstalled } h.db.Model(&tool).Updates(map[string]interface{}{ "status": status, "installed_version": version, }) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "available": available, "version": version, "tool": tool, @@ -185,15 +185,15 @@ func (h *ToolConfigHandler) CheckToolStatus(c *gin.Context) { // GetToolVersions returns available versions for a tool (jdk/node/maven) func (h *ToolConfigHandler) GetToolVersions(c *gin.Context) { - var tool models.DeployTool + var tool model.DeployTool if err := h.db.First(&tool, c.Param("id")); err.Error != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "工具不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "工具不存在"}) return } versions := getPresetVersions(tool.Name) - c.JSON(http.StatusOK, models.Response{Code: 200, Data: gin.H{ + c.JSON(http.StatusOK, model.Response{Code: 200, Data: gin.H{ "name": tool.Name, "default": tool.DefaultVersion, "versions": versions, diff --git a/backend/internal/api/handlers/user.go b/backend/controller/user.go similarity index 57% rename from backend/internal/api/handlers/user.go rename to backend/controller/user.go index 5b87adc..4a6a851 100644 --- a/backend/internal/api/handlers/user.go +++ b/backend/controller/user.go @@ -1,11 +1,12 @@ -package handlers +package controller import ( "net/http" + "time" - "ezops/internal/api/middleware" - "ezops/internal/config" - "ezops/internal/models" + "ezops/middleware" + "ezops/config" + "ezops/model" "github.com/gin-gonic/gin" "golang.org/x/crypto/bcrypt" @@ -23,37 +24,103 @@ func NewUserHandler(db *gorm.DB, cfg *config.Config) *UserHandler { return &UserHandler{db: db, cfg: cfg} } +// recordLoginLog 记录登录日志 // Logan.Li +func (h *UserHandler) recordLoginLog(c *gin.Context, username, status, failReason, loginType string) { + clientIP := c.ClientIP() + userAgent := c.Request.UserAgent() + + uid := (*uint)(nil) + var user model.User + if err := h.db.Where("username = ?", username).First(&user).Error; err == nil { + uid = &user.ID + } + + // 简单解析 UA 提取浏览器和 OS + browser, os := parseUserAgent(userAgent) + + log := model.LoginLog{ + UserID: uid, + Username: username, + IP: clientIP, + UserAgent: userAgent, + Browser: browser, + OS: os, + LoginType: loginType, + Status: status, + FailReason: failReason, + LoginAt: time.Now(), + } + h.db.Create(&log) +} + +// parseUserAgent 简单解析 UA 提取浏览器/OS // Logan.Li +func parseUserAgent(ua string) (browser, os string) { + browser = "Unknown" + os = "Unknown" + if ua == "" { + return + } + // Browser + switch { + case containsAny(ua, "Edg/"): browser = "Edge" + case containsAny(ua, "Chrome"): browser = "Chrome" + case containsAny(ua, "Safari") && !containsAny(ua, "Chrome"): browser = "Safari" + case containsAny(ua, "Firefox"): browser = "Firefox" + case containsAny(ua, "curl"): browser = "curl" + case containsAny(ua, "Python"): browser = "Python" + } + // OS + switch { + case containsAny(ua, "Windows"): os = "Windows" + case containsAny(ua, "Mac OS"): os = "macOS" + case containsAny(ua, "Linux") || containsAny(ua, "X11"): os = "Linux" + case containsAny(ua, "Android"): os = "Android" + case containsAny(ua, "iPhone") || containsAny(ua, "iPad"): os = "iOS" + } + return +} + +func containsAny(s, substr string) bool { + for i := 0; i <= len(s)-len(substr); i++ { + if s[i:i+len(substr)] == substr { + return true + } + } + return false +} + // Login 用户登录 // @Summary 用户登录 // @Description 用户登录获取JWT令牌 // @Tags 用户 // @Accept json // @Produce json -// @Param request body models.LoginRequest true "登录请求" -// @Success 200 {object} models.Response{data=models.LoginResponse} -// @Failure 400 {object} models.Response -// @Failure 401 {object} models.Response +// @Param request body model.LoginRequest true "登录请求" +// @Success 200 {object} model.Response{data=model.LoginResponse} +// @Failure 400 {object} model.Response +// @Failure 401 {object} model.Response // @Router /auth/login [post] func (h *UserHandler) Login(c *gin.Context) { - var req models.LoginRequest + var req model.LoginRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var user models.User + var user model.User err := h.db.Where("username = ?", req.Username).First(&user).Error if err == nil { // 本地用户存在 if user.Status != 1 { - c.JSON(http.StatusUnauthorized, models.Response{ + c.JSON(http.StatusUnauthorized, model.Response{ Code: 401, Message: "账号已被禁用", }) + h.recordLoginLog(c, req.Username, "failed", "账号已被禁用", "password") return } @@ -65,10 +132,11 @@ func (h *UserHandler) Login(c *gin.Context) { if user.AuthSource == "ldap" || user.Password == "-" { ldapInfo, ldapErr := tryLDAPAuth(h.db, req.Username, req.Password) if ldapErr != nil { - c.JSON(http.StatusUnauthorized, models.Response{ + c.JSON(http.StatusUnauthorized, model.Response{ Code: 401, Message: "用户名或密码错误", }) + h.recordLoginLog(c, req.Username, "failed", "用户名或密码错误", "password") return } // LDAP OK — 更新本地信息 @@ -85,10 +153,11 @@ func (h *UserHandler) Login(c *gin.Context) { } } } else { - c.JSON(http.StatusUnauthorized, models.Response{ + c.JSON(http.StatusUnauthorized, model.Response{ Code: 401, Message: "用户名或密码错误", }) + h.recordLoginLog(c, req.Username, "failed", "用户名或密码错误", "password") return } } @@ -96,14 +165,15 @@ func (h *UserHandler) Login(c *gin.Context) { // 本地用户不存在 — 尝试 LDAP 认证 ldapInfo, ldapErr := tryLDAPAuth(h.db, req.Username, req.Password) if ldapErr != nil { - c.JSON(http.StatusUnauthorized, models.Response{ + c.JSON(http.StatusUnauthorized, model.Response{ Code: 401, Message: "用户名或密码错误", }) + h.recordLoginLog(c, req.Username, "failed", "用户名或密码错误", "password") return } // LDAP 认证成功,自动创建本地用户 - newUser := models.User{ + newUser := model.User{ Username: ldapInfo.Username, Password: "-", RealName: ldapInfo.DisplayName, @@ -115,28 +185,31 @@ func (h *UserHandler) Login(c *gin.Context) { newUser.RealName = newUser.Username } if err := h.db.Create(&newUser).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建LDAP用户失败: " + err.Error(), }) + h.recordLoginLog(c, req.Username, "failed", "创建LDAP用户失败", "ldap") return } user = newUser } else { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "数据库错误", }) + h.recordLoginLog(c, req.Username, "failed", "数据库错误", "password") return } // 生成JWT令牌 token, err := middleware.GenerateToken(&user, &h.cfg.JWT) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "生成令牌失败", }) + h.recordLoginLog(c, user.Username, "failed", "生成令牌失败", "password") return } @@ -144,10 +217,12 @@ func (h *UserHandler) Login(c *gin.Context) { now := h.db.NowFunc() h.db.Model(&user).Update("last_login", &now) - c.JSON(http.StatusOK, models.Response{ + h.recordLoginLog(c, user.Username, "success", "", "password") + + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "登录成功", - Data: models.LoginResponse{ + Data: model.LoginResponse{ Token: token, ExpiresIn: h.cfg.JWT.ExpireHour * 3600, User: &user, @@ -161,14 +236,14 @@ func (h *UserHandler) Login(c *gin.Context) { // @Tags 用户 // @Accept json // @Produce json -// @Param request body models.CreateUserRequest true "注册请求" -// @Success 200 {object} models.Response{data=models.User} -// @Failure 400 {object} models.Response +// @Param request body model.CreateUserRequest true "注册请求" +// @Success 200 {object} model.Response{data=model.User} +// @Failure 400 {object} model.Response // @Router /auth/register [post] func (h *UserHandler) Register(c *gin.Context) { - var req models.CreateUserRequest + var req model.CreateUserRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) @@ -176,9 +251,9 @@ func (h *UserHandler) Register(c *gin.Context) { } // 检查用户名是否已存在 - var existingUser models.User + var existingUser model.User if err := h.db.Where("username = ?", req.Username).First(&existingUser).Error; err == nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "用户名已存在", }) @@ -188,14 +263,14 @@ func (h *UserHandler) Register(c *gin.Context) { // 加密密码 hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "密码加密失败", }) return } - user := models.User{ + user := model.User{ Username: req.Username, Password: string(hashedPassword), Email: req.Email, @@ -205,14 +280,14 @@ func (h *UserHandler) Register(c *gin.Context) { } if err := h.db.Create(&user).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建用户失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "注册成功", Data: user, @@ -225,21 +300,21 @@ func (h *UserHandler) Register(c *gin.Context) { // @Tags 用户 // @Produce json // @Security Bearer -// @Success 200 {object} models.Response{data=models.User} +// @Success 200 {object} model.Response{data=model.User} // @Router /user/profile [get] func (h *UserHandler) GetProfile(c *gin.Context) { userID := middleware.GetUserID(c) - var user models.User + var user model.User if err := h.db.Preload("Roles").First(&user, userID).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "用户不存在", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: user, @@ -253,15 +328,15 @@ func (h *UserHandler) GetProfile(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.UpdateUserRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.User} +// @Param request body model.UpdateUserRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.User} // @Router /user/profile [put] func (h *UserHandler) UpdateProfile(c *gin.Context) { userID := middleware.GetUserID(c) - var req models.UpdateUserRequest + var req model.UpdateUserRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) @@ -279,18 +354,18 @@ func (h *UserHandler) UpdateProfile(c *gin.Context) { updates["real_name"] = req.RealName } - if err := h.db.Model(&models.User{}).Where("id = ?", userID).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Model(&model.User{}).Where("id = ?", userID).Updates(updates).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) return } - var user models.User + var user model.User h.db.First(&user, userID) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: user, @@ -304,24 +379,24 @@ func (h *UserHandler) UpdateProfile(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.ChangePasswordRequest true "修改密码请求" -// @Success 200 {object} models.Response +// @Param request body model.ChangePasswordRequest true "修改密码请求" +// @Success 200 {object} model.Response // @Router /user/password [put] func (h *UserHandler) ChangePassword(c *gin.Context) { userID := middleware.GetUserID(c) - var req models.ChangePasswordRequest + var req model.ChangePasswordRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var user models.User + var user model.User if err := h.db.First(&user, userID).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "用户不存在", }) @@ -329,7 +404,7 @@ func (h *UserHandler) ChangePassword(c *gin.Context) { } if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.OldPassword)); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "原密码错误", }) @@ -338,7 +413,7 @@ func (h *UserHandler) ChangePassword(c *gin.Context) { hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.NewPassword), bcrypt.DefaultCost) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "密码加密失败", }) @@ -346,14 +421,14 @@ func (h *UserHandler) ChangePassword(c *gin.Context) { } if err := h.db.Model(&user).Update("password", string(hashedPassword)).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "修改密码失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "密码修改成功", }) diff --git a/backend/internal/api/handlers/user_admin.go b/backend/controller/user_admin.go similarity index 79% rename from backend/internal/api/handlers/user_admin.go rename to backend/controller/user_admin.go index defc65d..cca142a 100644 --- a/backend/internal/api/handlers/user_admin.go +++ b/backend/controller/user_admin.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "fmt" "net/http" "strconv" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "golang.org/x/crypto/bcrypt" @@ -20,19 +20,19 @@ import ( // @Param page query int false "页码" // @Param page_size query int false "每页数量" // @Param keyword query string false "搜索关键词" -// @Success 200 {object} models.Response{data=models.ListResponse} +// @Success 200 {object} model.Response{data=model.ListResponse} // @Router /users [get] func (h *UserHandler) ListUsers(c *gin.Context) { - var query models.PageQuery + var query model.PageQuery if err := c.ShouldBindQuery(&query); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误", }) return } - db := h.db.Model(&models.User{}) + db := h.db.Model(&model.User{}) if query.Keyword != "" { db = db.Where("username LIKE ? OR email LIKE ? OR real_name LIKE ?", "%"+query.Keyword+"%", "%"+query.Keyword+"%", "%"+query.Keyword+"%") @@ -41,13 +41,13 @@ func (h *UserHandler) ListUsers(c *gin.Context) { var total int64 db.Count(&total) - var users []models.User + var users []model.User db.Preload("Roles").Offset(query.GetOffset()).Limit(query.GetLimit()).Find(&users) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", - Data: models.ListResponse{ + Data: model.ListResponse{ List: users, Total: total, }, @@ -61,21 +61,21 @@ func (h *UserHandler) ListUsers(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "用户ID" -// @Success 200 {object} models.Response{data=models.User} +// @Success 200 {object} model.Response{data=model.User} // @Router /users/{id} [get] func (h *UserHandler) GetUser(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var user models.User + var user model.User if err := h.db.Preload("Roles").First(&user, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "用户不存在", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: user, @@ -89,13 +89,13 @@ func (h *UserHandler) GetUser(c *gin.Context) { // @Accept json // @Produce json // @Security Bearer -// @Param request body models.CreateUserRequest true "创建请求" -// @Success 200 {object} models.Response{data=models.User} +// @Param request body model.CreateUserRequest true "创建请求" +// @Success 200 {object} model.Response{data=model.User} // @Router /users [post] func (h *UserHandler) CreateUser(c *gin.Context) { - var req models.CreateUserRequest + var req model.CreateUserRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) @@ -103,9 +103,9 @@ func (h *UserHandler) CreateUser(c *gin.Context) { } // 检查用户名是否已存在 - var existingUser models.User + var existingUser model.User if err := h.db.Where("username = ?", req.Username).First(&existingUser).Error; err == nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "用户名已存在", }) @@ -115,14 +115,14 @@ func (h *UserHandler) CreateUser(c *gin.Context) { // 加密密码 hashedPassword, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) if err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "密码加密失败", }) return } - user := models.User{ + user := model.User{ Username: req.Username, Password: string(hashedPassword), Email: req.Email, @@ -132,7 +132,7 @@ func (h *UserHandler) CreateUser(c *gin.Context) { } if err := h.db.Create(&user).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "创建用户失败", }) @@ -141,12 +141,12 @@ func (h *UserHandler) CreateUser(c *gin.Context) { // 关联角色 if len(req.RoleIDs) > 0 { - var roles []models.Role + var roles []model.Role h.db.Find(&roles, req.RoleIDs) h.db.Model(&user).Association("Roles").Append(roles) } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "创建成功", Data: user, @@ -161,24 +161,24 @@ func (h *UserHandler) CreateUser(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "用户ID" -// @Param request body models.UpdateUserRequest true "更新请求" -// @Success 200 {object} models.Response{data=models.User} +// @Param request body model.UpdateUserRequest true "更新请求" +// @Success 200 {object} model.Response{data=model.User} // @Router /users/{id} [put] func (h *UserHandler) UpdateUser(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - var req models.UpdateUserRequest + var req model.UpdateUserRequest if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) return } - var user models.User + var user model.User if err := h.db.First(&user, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{ + c.JSON(http.StatusNotFound, model.Response{ Code: 404, Message: "用户不存在", }) @@ -200,7 +200,7 @@ func (h *UserHandler) UpdateUser(c *gin.Context) { } if err := h.db.Model(&user).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "更新失败", }) @@ -209,14 +209,14 @@ func (h *UserHandler) UpdateUser(c *gin.Context) { // 更新角色 if len(req.RoleIDs) > 0 { - var roles []models.Role + var roles []model.Role h.db.Find(&roles, req.RoleIDs) h.db.Model(&user).Association("Roles").Replace(roles) } h.db.Preload("Roles").First(&user, id) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "更新成功", Data: user, @@ -230,20 +230,20 @@ func (h *UserHandler) UpdateUser(c *gin.Context) { // @Produce json // @Security Bearer // @Param id path int true "用户ID" -// @Success 200 {object} models.Response +// @Success 200 {object} model.Response // @Router /users/{id} [delete] func (h *UserHandler) DeleteUser(c *gin.Context) { id, _ := strconv.Atoi(c.Param("id")) - if err := h.db.Delete(&models.User{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{ + if err := h.db.Delete(&model.User{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{ Code: 500, Message: "删除失败", }) return } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "删除成功", }) @@ -264,7 +264,7 @@ func (h *UserHandler) BatchImportUsers(c *gin.Context) { SkipExisting bool `json:"skip_existing"` } if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{ + c.JSON(http.StatusBadRequest, model.Response{ Code: 400, Message: "请求参数错误: " + err.Error(), }) @@ -281,7 +281,7 @@ func (h *UserHandler) BatchImportUsers(c *gin.Context) { continue } // Check if exists - var existing models.User + var existing model.User if err := h.db.Where("username = ?", u.Username).First(&existing).Error; err == nil { if req.SkipExisting { skipped++ @@ -303,7 +303,7 @@ func (h *UserHandler) BatchImportUsers(c *gin.Context) { continue } - user := models.User{ + user := model.User{ Username: u.Username, Password: string(hashed), Email: u.Email, @@ -324,7 +324,7 @@ func (h *UserHandler) BatchImportUsers(c *gin.Context) { msg += fmt.Sprintf(", %d 个错误", len(errors)) } - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: msg, Data: gin.H{ @@ -340,10 +340,10 @@ func (h *UserHandler) BatchImportUsers(c *gin.Context) { // ListRoles 获取角色列表(供前端下拉选择) // Logan.Li func (h *UserHandler) ListRoles(c *gin.Context) { - var roles []models.Role + var roles []model.Role h.db.Where("status = ?", 1).Preload("Permissions").Order("id ASC").Find(&roles) - c.JSON(http.StatusOK, models.Response{ - Code: 200, Data: models.ListResponse{List: roles, Total: int64(len(roles))}, + c.JSON(http.StatusOK, model.Response{ + Code: 200, Data: model.ListResponse{List: roles, Total: int64(len(roles))}, }) } // GET /api/v1/admin/users/import-template diff --git a/backend/controller/webshell.go b/backend/controller/webshell.go new file mode 100644 index 0000000..cb8e09f --- /dev/null +++ b/backend/controller/webshell.go @@ -0,0 +1,427 @@ +package controller + +import ( + "encoding/json" + "log" + "net" + "net/http" + "strconv" + "strings" + "sync" + "time" + + "github.com/gin-gonic/gin" + "github.com/gorilla/websocket" + "golang.org/x/crypto/ssh" + "gorm.io/gorm" + + "ezops/model" +) + +var upgrader = websocket.Upgrader{ + CheckOrigin: func(r *http.Request) bool { + return true + }, + ReadBufferSize: 1024, + WriteBufferSize: 1024, +} + +// WSMessage WebSocket消息结构 +type WSMessage struct { + Status int `json:"status"` // 0=data, 1=resize + Data string `json:"data"` + Cols int `json:"cols"` + Rows int `json:"rows"` +} + +// SessionContext 活跃会话上下文 +type SessionContext struct { + SessionID uint + Cancel chan struct{} +} + +// asciicastRecorder writes terminal output in asciicast v2 format +type asciicastRecorder struct { + buf strings.Builder + startTime time.Time + mu sync.Mutex +} + +func newAsciicastRecorder() *asciicastRecorder { + r := &asciicastRecorder{startTime: time.Now()} + r.writeHeader() + return r +} + +func (r *asciicastRecorder) writeHeader() { + h, _ := json.Marshal(map[string]interface{}{ + "version": 2, + "width": 80, + "height": 24, + "timestamp": r.startTime.Unix(), + "env": map[string]string{ + "SHELL": "/bin/bash", + "TERM": "xterm-256color", + }, + }) + r.buf.Write(h) + r.buf.WriteByte('\n') +} + +func (r *asciicastRecorder) WriteRow(data []byte) { + if len(data) == 0 { + return + } + r.mu.Lock() + defer r.mu.Unlock() + delta := time.Since(r.startTime).Seconds() + row, _ := json.Marshal([]interface{}{delta, "o", string(data)}) + r.buf.Write(row) + r.buf.WriteByte('\n') +} + +func (r *asciicastRecorder) String() string { return r.buf.String() } +func (r *asciicastRecorder) Len() int { return r.buf.Len() } + +// WebShellHandler WebShell处理器 +type WebShellHandler struct { + db *gorm.DB + auditHub *AuditHub + clients sync.Map // sessionID → *SessionContext +} + +func NewWebShellHandler(db *gorm.DB, auditHub *AuditHub) *WebShellHandler { + return &WebShellHandler{db: db, auditHub: auditHub} +} + +// KillSession 强制终止指定终端会话 +func (h *WebShellHandler) KillSession(sessionID uint) bool { + if val, ok := h.clients.Load(sessionID); ok { + ctx := val.(*SessionContext) + close(ctx.Cancel) + h.clients.Delete(sessionID) + log.Printf("[WebShell] Kill signal sent session=%d", sessionID) + return true + } + return false +} + +// formatSSHError 将 Go SSH 错误转换为友好的中文提示 +func formatSSHError(err error) string { + errStr := err.Error() + switch { + case strings.Contains(errStr, "i/o timeout"): + return "Connection timeout (target may be behind firewall or unreachable)" + case strings.Contains(errStr, "connection refused"): + return "Connection refused (SSH service not running or wrong port)" + case strings.Contains(errStr, "no route to host"): + return "No route to host (IP address unreachable)" + case strings.Contains(errStr, "authentication failed") || strings.Contains(errStr, "unable to authenticate"): + return "Authentication failed (wrong username or password)" + case strings.Contains(errStr, "handshake"): + return "SSH handshake failed (target may not be an SSH service)" + case strings.Contains(errStr, "dns") || strings.Contains(errStr, "no such host"): + return "DNS resolution failed (invalid IP address)" + case strings.Contains(errStr, "ssh: must specify"): + return "Authentication method error (no password or key configured)" + default: + return errStr + } +} + +// contains 字符串包含检查 (used by agent_install.go) +func contains(s, substr string) bool { + return strings.Contains(s, substr) +} + +// Terminal WebSocket终端连接 — 真实SSH + asciicast v2录制 + 命令审计 +func (h *WebShellHandler) Terminal(c *gin.Context) { + serverID := c.Query("id") + if serverID == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "missing server id"}) + return + } + + var server model.Server + if err := h.db.First(&server, serverID).Error; err != nil { + c.JSON(http.StatusNotFound, gin.H{"error": "server not found"}) + return + } + + conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) + if err != nil { + log.Printf("[WebShell] WS upgrade failed: %v", err) + return + } + defer conn.Close() + + var userIDPtr *uint + if uid, exists := c.Get("userID"); exists { + if uidVal, ok := uid.(uint); ok { + userIDPtr = &uidVal + } + } + username, _ := c.Get("username") + usernameStr, _ := username.(string) + + termSession := model.TerminalSession{ + UserID: userIDPtr, + Username: usernameStr, + ServerID: server.ID, + ServerName: server.Hostname, + ServerIP: server.IP, + ServerPort: server.Port, + ClientIP: c.ClientIP(), + Status: "active", + StartTime: time.Now(), + } + if err := h.db.Create(&termSession).Error; err != nil { + log.Printf("[WebShell] Create session record failed: %v", err) + } + + recorder := newAsciicastRecorder() + const maxRecordSize = 1024 * 1024 + var cmdBuf strings.Builder + + finalizeSession := func(status string) { + endTime := time.Now() + duration := int(endTime.Sub(termSession.StartTime).Seconds()) + recData := recorder.String() + recSize := recorder.Len() + log.Printf("[WebShell] Finalize session=%d status=%s duration=%ds rec=%d bytes", termSession.ID, status, duration, recSize) + // Raw SQL with error logging + result := h.db.Exec("UPDATE sys_terminal_sessions SET status=?, duration=?, end_time=?, record_data=?, record_size=? WHERE id=?", + status, duration, endTime, recData, recSize, termSession.ID) + if result.Error != nil { + log.Printf("[WebShell] ERROR finalize session=%d: %v", termSession.ID, result.Error) + } else { + log.Printf("[WebShell] Finalize OK session=%d rows_affected=%d", termSession.ID, result.RowsAffected) + } + } + + connectingMsg := "\r\n\x1b[36mConnecting to " + server.Hostname + " (" + server.IP + ":" + strconv.Itoa(server.Port) + ")...\x1b[0m\r\n" + conn.WriteJSON(WSMessage{Status: 0, Data: connectingMsg}) + + sshConfig := &ssh.ClientConfig{ + User: server.Username, + Timeout: 10 * time.Second, + HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { + log.Printf("[WebShell] TOFU: trusting host key for %s: %s", server.Hostname, ssh.FingerprintSHA256(key)) + return nil + }, + } + + switch server.AuthType { + case "key": + signer, err := ssh.ParsePrivateKey([]byte(server.SSHKey)) + if err != nil { + sshConfig.Auth = []ssh.AuthMethod{ssh.Password(server.Password)} + } else { + sshConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)} + } + default: + sshConfig.Auth = []ssh.AuthMethod{ssh.Password(server.Password)} + } + + addr := server.IP + ":" + strconv.Itoa(server.Port) + sshClient, err := ssh.Dial("tcp", addr, sshConfig) + if err != nil { + log.Printf("[WebShell] SSH connect failed %s: %v", addr, err) + friendlyErr := formatSSHError(err) + errMsg := "\r\n\x1b[31mConnection failed: " + friendlyErr + "\x1b[0m\r\n" + conn.WriteJSON(WSMessage{Status: 0, Data: errMsg}) + recorder.WriteRow([]byte(errMsg)) + finalizeSession("failed") + return + } + defer sshClient.Close() + + log.Printf("[WebShell] SSH connected %s (%s)", server.Hostname, addr) + + session, err := sshClient.NewSession() + if err != nil { + log.Printf("[WebShell] Create SSH session failed: %v", err) + conn.WriteJSON(WSMessage{Status: 0, Data: "\r\n\x1b[31mFailed to create SSH session\x1b[0m\r\n"}) + finalizeSession("failed") + return + } + defer session.Close() + + modes := ssh.TerminalModes{ + ssh.ECHO: 1, + ssh.TTY_OP_ISPEED: 14400, + ssh.TTY_OP_OSPEED: 14400, + } + if err := session.RequestPty("xterm-256color", 24, 80, modes); err != nil { + log.Printf("[WebShell] PTY request failed: %v", err) + conn.WriteJSON(WSMessage{Status: 0, Data: "\r\n\x1b[31mPTY request failed\x1b[0m\r\n"}) + finalizeSession("failed") + return + } + + stdinPipe, err := session.StdinPipe() + if err != nil { + finalizeSession("failed") + return + } + stdoutPipe, err := session.StdoutPipe() + if err != nil { + finalizeSession("failed") + return + } + + if err := session.Shell(); err != nil { + log.Printf("[WebShell] Shell start failed: %v", err) + finalizeSession("failed") + return + } + + welcome := "\r\n\x1b[32mAIOps WebShell\x1b[0m \u2014 connected to " + server.Hostname + " (" + server.IP + ")\r\n\r\n" + conn.WriteJSON(WSMessage{Status: 0, Data: welcome}) + recorder.WriteRow([]byte(welcome)) + + sessCtx := &SessionContext{ + SessionID: termSession.ID, + Cancel: make(chan struct{}), + } + h.clients.Store(termSession.ID, sessCtx) + log.Printf("[WebShell] Session registered session=%d", termSession.ID) + defer func() { + h.clients.Delete(termSession.ID) + if h.auditHub != nil { + h.auditHub.Cleanup(termSession.ID) + } + log.Printf("[WebShell] Session unregistered session=%d", termSession.ID) + }() + + done := make(chan struct{}) + + // goroutine 1: Cancel listener + go func() { + select { + case <-sessCtx.Cancel: + log.Printf("[WebShell] Received Kill signal session=%d, closing", termSession.ID) + conn.Close() + case <-done: + } + }() + + // goroutine 2: SSH stdout → WebSocket + asciicast recording + AuditHub + go func() { + defer close(done) + buf := make([]byte, 8192) + for { + n, err := stdoutPipe.Read(buf) + if err != nil { + discMsg := "\r\n\x1b[31m[Remote connection closed]\x1b[0m\r\n" + conn.WriteJSON(WSMessage{Status: 0, Data: discMsg}) + recorder.WriteRow([]byte(discMsg)) + if h.auditHub != nil { + h.auditHub.Broadcast(termSession.ID, []byte(discMsg)) + } + break + } + if n > 0 { + data := buf[:n] + conn.WriteJSON(WSMessage{Status: 0, Data: string(data)}) + if recorder.Len() < maxRecordSize { + recorder.WriteRow(data) + } + if h.auditHub != nil { + h.auditHub.Broadcast(termSession.ID, data) + } + } + } + }() + + // Main loop: WebSocket → SSH stdin (command capture + idle timeout) + const idleTimeout = 15 * time.Minute + for { + conn.SetReadDeadline(time.Now().Add(idleTimeout)) + msgType, data, err := conn.ReadMessage() + if err != nil { + if netErr, ok := err.(net.Error); ok && netErr.Timeout() { + log.Printf("[WebShell] Idle timeout 15min session=%d", termSession.ID) + } else { + log.Printf("[WebShell] WS read error session=%d: %v", termSession.ID, err) + } + break + } + + if msgType == websocket.TextMessage { + var msg WSMessage + if err := json.Unmarshal(data, &msg); err != nil { + continue + } + + switch msg.Status { + case 0: + if msg.Data != "" { + stdinPipe.Write([]byte(msg.Data)) + + // Command extraction from stdin + cmdBuf.WriteString(msg.Data) + if strings.Contains(msg.Data, "\r") || strings.Contains(msg.Data, "\n") { + cmd := extractCommand(cmdBuf.String()) + if cmd != "" { + recordCommand(h.db, termSession.ID, termSession.ServerID, usernameStr, cmd) + } + cmdBuf.Reset() + } + if cmdBuf.Len() > 8192 { + cmdBuf.Reset() + } + } + case 1: // resize + if msg.Cols > 0 && msg.Rows > 0 { + session.WindowChange(msg.Rows, msg.Cols) + } + } + } + } + + // Close SSH to unblock stdout goroutine, then wait for it + sshClient.Close() + <-done + stdinPipe.Close() + finalizeSession("closed") + log.Printf("[WebShell] Disconnected %s (%s)", server.Hostname, addr) +} + +// extractCommand extracts a clean command from raw terminal input +func extractCommand(input string) string { + cleaned := strings.Map(func(r rune) rune { + if r < 32 && r != '\t' { + return -1 + } + if r == 127 { + return -1 + } + return r + }, input) + cleaned = strings.TrimSpace(cleaned) + if len(cleaned) < 2 || len(cleaned) > 500 { + return "" + } + if strings.HasPrefix(cleaned, "\x1b[") { + return "" + } + return cleaned +} + +// recordCommand records a terminal command to sys_session_commands +func recordCommand(db *gorm.DB, sessionID, serverID uint, username, command string) { + now := time.Now() + cmd := model.SessionCommand{ + SessionID: sessionID, + ServerID: serverID, + Username: username, + Command: command, + Timestamp: now, + } + if err := db.Create(&cmd).Error; err != nil { + log.Printf("[WebShell] Command record failed: %v", err) + } else { + log.Printf("[WebShell] Command recorded session=%d cmd=%q", sessionID, command) + } +} diff --git a/backend/internal/api/handlers/workspace_files.go b/backend/controller/workspace_files.go similarity index 98% rename from backend/internal/api/handlers/workspace_files.go rename to backend/controller/workspace_files.go index d4d2eaa..19f1b98 100644 --- a/backend/internal/api/handlers/workspace_files.go +++ b/backend/controller/workspace_files.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "fmt" @@ -12,7 +12,7 @@ import ( "github.com/gin-gonic/gin" "gorm.io/gorm" - "ezops/internal/models" + "ezops/model" ) // WorkspaceFilesHandler 工作区文件浏览器处理器 @@ -41,7 +41,7 @@ func (h *WorkspaceFilesHandler) resolveWorkspace(c *gin.Context) (string, error) return "", err } - var run models.PipelineRun + var run model.PipelineRun if err := h.db.First(&run, runID).Error; err != nil { c.JSON(http.StatusNotFound, gin.H{"error": "run not found"}) return "", err diff --git a/backend/internal/api/handlers/ws_pipeline_log.go b/backend/controller/ws_pipeline_log.go similarity index 99% rename from backend/internal/api/handlers/ws_pipeline_log.go rename to backend/controller/ws_pipeline_log.go index 5ff1be2..fd15785 100644 --- a/backend/internal/api/handlers/ws_pipeline_log.go +++ b/backend/controller/ws_pipeline_log.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "encoding/json" diff --git a/backend/internal/api/handlers/zabbix_datasource.go b/backend/controller/zabbix_datasource.go similarity index 64% rename from backend/internal/api/handlers/zabbix_datasource.go rename to backend/controller/zabbix_datasource.go index f22b4c2..b6f0854 100644 --- a/backend/internal/api/handlers/zabbix_datasource.go +++ b/backend/controller/zabbix_datasource.go @@ -1,11 +1,11 @@ -package handlers +package controller import ( "context" "net/http" "time" - "ezops/internal/models" + "ezops/model" "ezops/pkg/zabbix" "github.com/gin-gonic/gin" @@ -29,43 +29,43 @@ func NewZabbixDSHandler(db *gorm.DB) *ZabbixDSHandler { // List 数据源列表 // GET /api/v1/zabbix-datasources func (h *ZabbixDSHandler) List(c *gin.Context) { - var sources []models.ZabbixDataSource + var sources []model.ZabbixDataSource if err := h.db.Order("is_default DESC, id ASC").Find(&sources).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "查询失败: " + err.Error()}) return } if sources == nil { - sources = []models.ZabbixDataSource{} + sources = []model.ZabbixDataSource{} } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: sources}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: sources}) } // Get 获取单个数据源 // GET /api/v1/zabbix-datasources/:id func (h *ZabbixDSHandler) Get(c *gin.Context) { id := c.Param("id") - var ds models.ZabbixDataSource + var ds model.ZabbixDataSource if err := h.db.First(&ds, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "数据源不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "数据源不存在"}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: ds}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: ds}) } // Create 创建数据源 // POST /api/v1/zabbix-datasources func (h *ZabbixDSHandler) Create(c *gin.Context) { - var req models.CreateZabbixDSReq + var req model.CreateZabbixDSReq if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } if req.IsDefault { - h.db.Model(&models.ZabbixDataSource{}).Where("is_default = ?", true).Update("is_default", false) + h.db.Model(&model.ZabbixDataSource{}).Where("is_default = ?", true).Update("is_default", false) } - ds := models.ZabbixDataSource{ + ds := model.ZabbixDataSource{ Name: req.Name, URL: req.URL, Username: req.Username, @@ -89,26 +89,26 @@ func (h *ZabbixDSHandler) Create(c *gin.Context) { } if err := h.db.Create(&ds).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "创建失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "创建失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Data: ds, Message: "创建成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Data: ds, Message: "创建成功"}) } // Update 更新数据源 // PUT /api/v1/zabbix-datasources/:id func (h *ZabbixDSHandler) Update(c *gin.Context) { id := c.Param("id") - var ds models.ZabbixDataSource + var ds model.ZabbixDataSource if err := h.db.First(&ds, id).Error; err != nil { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "数据源不存在"}) + c.JSON(http.StatusNotFound, model.Response{Code: 404, Message: "数据源不存在"}) return } - var req models.UpdateZabbixDSReq + var req model.UpdateZabbixDSReq if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } @@ -127,50 +127,50 @@ func (h *ZabbixDSHandler) Update(c *gin.Context) { if req.IsDefault != nil { updates["is_default"] = *req.IsDefault if *req.IsDefault { - h.db.Model(&models.ZabbixDataSource{}).Where("is_default = ? AND id != ?", true, id).Update("is_default", false) + h.db.Model(&model.ZabbixDataSource{}).Where("is_default = ? AND id != ?", true, id).Update("is_default", false) } } if req.Status != nil { updates["status"] = *req.Status } if len(updates) > 0 { if err := h.db.Model(&ds).Updates(updates).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "更新失败: " + err.Error()}) + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "更新失败: " + err.Error()}) return } } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "更新成功"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "更新成功"}) } // Delete 删除数据源 // DELETE /api/v1/zabbix-datasources/:id func (h *ZabbixDSHandler) Delete(c *gin.Context) { id := c.Param("id") - if err := h.db.Delete(&models.ZabbixDataSource{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败: " + err.Error()}) + if err := h.db.Delete(&model.ZabbixDataSource{}, id).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "删除失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已删除"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已删除"}) } // SetDefault 设为默认 // POST /api/v1/zabbix-datasources/:id/default func (h *ZabbixDSHandler) SetDefault(c *gin.Context) { id := c.Param("id") - h.db.Model(&models.ZabbixDataSource{}).Where("is_default = ?", true).Update("is_default", false) - if err := h.db.Model(&models.ZabbixDataSource{}).Where("id = ?", id).Update("is_default", true).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "设置失败: " + err.Error()}) + h.db.Model(&model.ZabbixDataSource{}).Where("is_default = ?", true).Update("is_default", false) + if err := h.db.Model(&model.ZabbixDataSource{}).Where("id = ?", id).Update("is_default", true).Error; err != nil { + c.JSON(http.StatusInternalServerError, model.Response{Code: 500, Message: "设置失败: " + err.Error()}) return } - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "已设为默认"}) + c.JSON(http.StatusOK, model.Response{Code: 200, Message: "已设为默认"}) } // TestConnection 测试 Zabbix 连接 // POST /api/v1/zabbix-datasources/test func (h *ZabbixDSHandler) TestConnection(c *gin.Context) { - var req models.TestZabbixDSReq + var req model.TestZabbixDSReq if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } @@ -182,7 +182,7 @@ func (h *ZabbixDSHandler) TestConnection(c *gin.Context) { defer cancel() if err := client.Auth(ctx); err != nil { - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Data: map[string]interface{}{ "success": false, @@ -194,7 +194,7 @@ func (h *ZabbixDSHandler) TestConnection(c *gin.Context) { token := client.GetAuthToken() - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Data: map[string]interface{}{ "success": true, diff --git a/backend/internal/api/handlers/zabbix_proxy.go b/backend/controller/zabbix_proxy.go similarity index 88% rename from backend/internal/api/handlers/zabbix_proxy.go rename to backend/controller/zabbix_proxy.go index 42af674..5cfca39 100644 --- a/backend/internal/api/handlers/zabbix_proxy.go +++ b/backend/controller/zabbix_proxy.go @@ -1,4 +1,4 @@ -package handlers +package controller import ( "context" @@ -9,7 +9,7 @@ import ( "strings" "time" - "ezops/internal/models" + "ezops/model" "ezops/pkg/zabbix" "github.com/gin-gonic/gin" @@ -53,7 +53,7 @@ type ZabbixConnectReq struct { func (h *ZabbixProxyHandler) Connect(c *gin.Context) { var req ZabbixConnectReq if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "参数错误: " + err.Error()}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "参数错误: " + err.Error()}) return } @@ -62,7 +62,7 @@ func (h *ZabbixProxyHandler) Connect(c *gin.Context) { defer cancel() if err := client.Auth(ctx); err != nil { - c.JSON(http.StatusBadGateway, models.Response{Code: 502, Message: "Zabbix 认证失败: " + err.Error()}) + c.JSON(http.StatusBadGateway, model.Response{Code: 502, Message: "Zabbix 认证失败: " + err.Error()}) return } @@ -78,7 +78,7 @@ func (h *ZabbixProxyHandler) Connect(c *gin.Context) { }) if err != nil { client.Logout(ctx) - c.JSON(http.StatusBadGateway, models.Response{Code: 502, Message: "获取 Zabbix 主机失败: " + err.Error()}) + c.JSON(http.StatusBadGateway, model.Response{Code: 502, Message: "获取 Zabbix 主机失败: " + err.Error()}) return } @@ -181,7 +181,7 @@ func (h *ZabbixProxyHandler) Connect(c *gin.Context) { client.Logout(ctx) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: gin.H{ @@ -197,7 +197,7 @@ func (h *ZabbixProxyHandler) Connect(c *gin.Context) { func (h *ZabbixProxyHandler) GetHostDetail(c *gin.Context) { hostID := c.Param("hostid") if hostID == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "缺少主机ID"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "缺少主机ID"}) return } @@ -206,7 +206,7 @@ func (h *ZabbixProxyHandler) GetHostDetail(c *gin.Context) { username := c.Query("username") password := c.Query("password") if url == "" || username == "" { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "缺少 Zabbix 连接信息"}) + c.JSON(http.StatusBadRequest, model.Response{Code: 400, Message: "缺少 Zabbix 连接信息"}) return } @@ -215,7 +215,7 @@ func (h *ZabbixProxyHandler) GetHostDetail(c *gin.Context) { defer cancel() if err := client.Auth(ctx); err != nil { - c.JSON(http.StatusBadGateway, models.Response{Code: 502, Message: "Zabbix 认证失败: " + err.Error()}) + c.JSON(http.StatusBadGateway, model.Response{Code: 502, Message: "Zabbix 认证失败: " + err.Error()}) return } defer client.Logout(ctx) @@ -223,21 +223,21 @@ func (h *ZabbixProxyHandler) GetHostDetail(c *gin.Context) { // 获取主机详情 host, err := client.GetHostByID(ctx, hostID) if err != nil { - c.JSON(http.StatusBadGateway, models.Response{Code: 502, Message: "获取主机失败: " + err.Error()}) + c.JSON(http.StatusBadGateway, model.Response{Code: 502, Message: "获取主机失败: " + err.Error()}) return } // 获取所有监控项 items, err := client.GetItemsByHost(ctx, hostID) if err != nil { - c.JSON(http.StatusBadGateway, models.Response{Code: 502, Message: "获取监控项失败: " + err.Error()}) + c.JSON(http.StatusBadGateway, model.Response{Code: 502, Message: "获取监控项失败: " + err.Error()}) return } // 获取问题触发器 triggers, _ := client.GetTriggersByHost(ctx, hostID, true) - c.JSON(http.StatusOK, models.Response{ + c.JSON(http.StatusOK, model.Response{ Code: 200, Message: "success", Data: gin.H{ diff --git a/backend/dto/dto.go b/backend/dto/dto.go new file mode 100644 index 0000000..521c1ac --- /dev/null +++ b/backend/dto/dto.go @@ -0,0 +1,182 @@ +// Package dto 定义请求(Request)与响应(Response)传输对象 +// 与 models 分离:models 是 GORM 表结构,dto 是 API 契约 +package dto + +import "time" + +// ━━━ Server ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +// CreateServerRequest 创建服务器 +type CreateServerRequest struct { + Hostname string `json:"hostname" binding:"required"` + IP string `json:"ip" binding:"required"` + PublicIP string `json:"public_ip"` + Port int `json:"port"` + Username string `json:"username"` + Password string `json:"password"` + SSHKey string `json:"ssh_key"` + AuthType string `json:"auth_type"` + OS string `json:"os"` + OSVersion string `json:"os_version"` + Arch string `json:"arch"` + CPU int `json:"cpu"` + Memory int64 `json:"memory"` + Disk int64 `json:"disk"` + RegionID *uint `json:"region_id"` + CloudID *uint `json:"cloud_id"` + Tags string `json:"tags"` + Description string `json:"description"` +} + +// UpdateServerRequest 更新服务器 — 部分更新 (使用 map) +type UpdateServerRequest struct { + Hostname *string `json:"hostname"` + IP *string `json:"ip"` + PublicIP *string `json:"public_ip"` + Port *int `json:"port"` + Username *string `json:"username"` + Password *string `json:"password"` + SSHKey *string `json:"ssh_key"` + AuthType *string `json:"auth_type"` + OS *string `json:"os"` + OSVersion *string `json:"os_version"` + Arch *string `json:"arch"` + CPU *int `json:"cpu"` + Memory *int64 `json:"memory"` + Disk *int64 `json:"disk"` + Status *string `json:"status"` + CPUUsage *float64 `json:"cpu_usage"` + MemoryUsage *float64 `json:"memory_usage"` + DiskUsage *float64 `json:"disk_usage"` + RegionID *uint `json:"region_id"` + CloudID *uint `json:"cloud_id"` + Tags *string `json:"tags"` + Description *string `json:"description"` +} + +// ServerListItem 服务器列表项 (精简) +type ServerListItem struct { + ID uint `json:"id"` + Hostname string `json:"hostname"` + IP string `json:"ip"` + Status string `json:"status"` + CPUUsage float64 `json:"cpu_usage"` + MemoryUsage float64 `json:"memory_usage"` + DiskUsage float64 `json:"disk_usage"` + AgentStatus string `json:"agent_status"` + AgentVersion string `json:"agent_version"` + HasAuth bool `json:"has_auth"` + OS string `json:"os"` + CreatedAt time.Time `json:"created_at"` +} + +// ━━━ Credential ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +// CreateCredentialRequest 创建凭据 +type CreateCredentialRequest struct { + Name string `json:"name" binding:"required"` + SecretType string `json:"secret_type" binding:"required"` // ssh, docker, tls, password, env + Description string `json:"description"` + + // SSH + SSHPrivateKey string `json:"ssh_private_key"` + SSHPublicKey string `json:"ssh_public_key"` + SSHUser string `json:"ssh_user"` + SSHPort int `json:"ssh_port"` + SSHPassword string `json:"ssh_password"` + + // Docker + DockerServer string `json:"docker_server"` + DockerUsername string `json:"docker_username"` + DockerPassword string `json:"docker_password"` + + // TLS + TLSCert string `json:"tls_cert"` + TLSKey string `json:"tls_key"` + TLSCA string `json:"tls_ca"` + + // Password / Generic + PlainPassword string `json:"plain_password"` + + // Env + EnvVars string `json:"env_vars"` +} + +// UpdateCredentialRequest 更新凭据 +type UpdateCredentialRequest struct { + Name *string `json:"name"` + Description *string `json:"description"` + + SSHPrivateKey *string `json:"ssh_private_key"` + SSHPublicKey *string `json:"ssh_public_key"` + SSHUser *string `json:"ssh_user"` + SSHPort *int `json:"ssh_port"` + SSHPassword *string `json:"ssh_password"` + + DockerServer *string `json:"docker_server"` + DockerUsername *string `json:"docker_username"` + DockerPassword *string `json:"docker_password"` + + TLSCert *string `json:"tls_cert"` + TLSKey *string `json:"tls_key"` + TLSCA *string `json:"tls_ca"` + + PlainPassword *string `json:"plain_password"` + EnvVars *string `json:"env_vars"` +} + +// ━━━ Alert ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +// CreateAlertContactRequest 创建告警联系人 +type CreateAlertContactRequest struct { + Name string `json:"name" binding:"required"` + ChannelType string `json:"channel_type" binding:"required"` // feishu, dingtalk, wechat, webhook + WebhookURL string `json:"webhook_url" binding:"required"` + Phone string `json:"phone"` + Email string `json:"email"` +} + +// UpdateAlertContactRequest 更新告警联系人 +type UpdateAlertContactRequest struct { + Name *string `json:"name"` + ChannelType *string `json:"channel_type"` + WebhookURL *string `json:"webhook_url"` + Phone *string `json:"phone"` + Email *string `json:"email"` +} + +// CreateAlertContactGroupRequest 创建告警联系组 +type CreateAlertContactGroupRequest struct { + Name string `json:"name" binding:"required"` + ContactIDs []uint `json:"contact_ids"` +} + +// UpdateAlertContactGroupRequest 更新告警联系组 +type UpdateAlertContactGroupRequest struct { + Name *string `json:"name"` + ContactIDs *[]uint `json:"contact_ids"` +} + +// CreateAlertRuleRequest 创建告警规则 +type CreateAlertRuleRequest struct { + Name string `json:"name" binding:"required"` + Metric string `json:"metric" binding:"required"` + Condition string `json:"condition" binding:"required"` // >, <, >=, <=, == + Threshold float64 `json:"threshold" binding:"required"` + Duration string `json:"duration"` // 30s, 1m, 5m + ContactIDs []uint `json:"contact_ids"` + Enabled bool `json:"enabled"` + Description string `json:"description"` +} + +// UpdateAlertRuleRequest 更新告警规则 +type UpdateAlertRuleRequest struct { + Name *string `json:"name"` + Metric *string `json:"metric"` + Condition *string `json:"condition"` + Threshold *float64 `json:"threshold"` + Duration *string `json:"duration"` + ContactIDs *[]uint `json:"contact_ids"` + Enabled *bool `json:"enabled"` + Description *string `json:"description"` +} diff --git a/backend/cmd/embed.go b/backend/embed.go similarity index 95% rename from backend/cmd/embed.go rename to backend/embed.go index d631f2f..a5edbf6 100644 --- a/backend/cmd/embed.go +++ b/backend/embed.go @@ -13,7 +13,7 @@ import ( var frontendFS embed.FS // setupFrontend 配置前端静态文件服务(go:embed 模式) // Logan.Li -// 前端构建产物放在 backend/cmd/static/ 目录,编译时嵌入二进制 +// 前端构建产物放在 backend/static/ 目录,编译时嵌入二进制 func setupFrontend(r *gin.Engine) { // 获取 static 子目录的 fs.FS staticFS, err := fs.Sub(frontendFS, "static") diff --git a/backend/go.mod b/backend/go.mod index 42af14c..f50223c 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -45,6 +45,7 @@ require ( github.com/jinzhu/now v1.1.5 // indirect github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.2.4 // indirect + github.com/kr/fs v0.1.0 // indirect github.com/leodido/go-urn v1.2.4 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mattn/go-isatty v0.0.19 // indirect @@ -53,6 +54,7 @@ require ( github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/reflect2 v1.0.2 // indirect github.com/pelletier/go-toml/v2 v2.1.0 // indirect + github.com/pkg/sftp v1.13.10 // indirect github.com/sagikazarmark/locafero v0.4.0 // indirect github.com/sagikazarmark/slog-shim v0.1.0 // indirect github.com/sourcegraph/conc v0.3.0 // indirect diff --git a/backend/go.sum b/backend/go.sum index 88b453f..bb87560 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -95,6 +95,8 @@ github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHm github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/klauspost/cpuid/v2 v2.2.4 h1:acbojRNwl3o09bUq+yDCtZFc1aiwaAAxtcn8YkZXnvk= github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= +github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= +github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -118,6 +120,8 @@ github.com/nalgeon/redka v0.2.0 h1:9Hjp5aHPHPLE44T1m41LKzx+b/MquMXt8ggw69eVu6U= github.com/nalgeon/redka v0.2.0/go.mod h1:vLxjY3XS9IwBID2YEFWeeMiN4Ar/DtKd4JW62JTAxuU= github.com/pelletier/go-toml/v2 v2.1.0 h1:FnwAJ4oYMvbT/34k9zzHuZNrhlz48GB3/s6at6/MHO4= github.com/pelletier/go-toml/v2 v2.1.0/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pkg/sftp v1.13.10 h1:+5FbKNTe5Z9aspU88DPIKJ9z2KZoaGCu6Sr6kKR/5mU= +github.com/pkg/sftp v1.13.10/go.mod h1:bJ1a7uDhrX/4OII+agvy28lzRvQrmIQuaHrcI1HbeGA= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= @@ -151,6 +155,7 @@ github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= diff --git a/backend/internal/api/handlers/terminal_session.go b/backend/internal/api/handlers/terminal_session.go deleted file mode 100644 index 3564c1c..0000000 --- a/backend/internal/api/handlers/terminal_session.go +++ /dev/null @@ -1,147 +0,0 @@ -package handlers - -import ( - "net/http" - "strconv" - - "ezops/internal/models" - - "github.com/gin-gonic/gin" - "gorm.io/gorm" -) - -// TerminalSessionHandler 终端会话审计处理器 // Logan.Li -type TerminalSessionHandler struct { - db *gorm.DB -} - -// NewTerminalSessionHandler 创建终端会话审计处理器 -func NewTerminalSessionHandler(db *gorm.DB) *TerminalSessionHandler { - return &TerminalSessionHandler{db: db} -} - -// ListTerminalSessions 终端会话列表 -// GET /api/v1/terminal-sessions?server_id=&username=&status=&page=&page_size= -func (h *TerminalSessionHandler) ListTerminalSessions(c *gin.Context) { - var req models.TerminalSessionQuery - if err := c.ShouldBindQuery(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: err.Error()}) - return - } - if req.Page <= 0 { - req.Page = 1 - } - if req.PageSize <= 0 { - req.PageSize = 20 - } - - query := h.db.Model(&models.TerminalSession{}) - if req.ServerID > 0 { - query = query.Where("server_id = ?", req.ServerID) - } - if req.Username != "" { - query = query.Where("username LIKE ?", "%"+req.Username+"%") - } - if req.Status != "" { - query = query.Where("status = ?", req.Status) - } - - var total int64 - if err := query.Count(&total).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询失败"}) - return - } - - var sessions []models.TerminalSession - if err := query.Order("id DESC"). - Offset((req.Page - 1) * req.PageSize). - Limit(req.PageSize). - Find(&sessions).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询失败"}) - return - } - - c.JSON(http.StatusOK, models.Response{Code: 200, Data: models.ListResponse{ - List: sessions, - Total: total, - }}) -} - -// GetTerminalSession 终端会话详情 -// GET /api/v1/terminal-sessions/:id -func (h *TerminalSessionHandler) GetTerminalSession(c *gin.Context) { - id, err := strconv.ParseUint(c.Param("id"), 10, 64) - if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的会话ID"}) - return - } - - var session models.TerminalSession - if err := h.db.First(&session, id).Error; err != nil { - if err == gorm.ErrRecordNotFound { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "会话不存在"}) - return - } - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询失败"}) - return - } - - c.JSON(http.StatusOK, models.Response{Code: 200, Data: session}) -} - -// GetTerminalRecord 终端会话录制数据(用于回放) -// GET /api/v1/terminal-sessions/:id/record -func (h *TerminalSessionHandler) GetTerminalRecord(c *gin.Context) { - id, err := strconv.ParseUint(c.Param("id"), 10, 64) - if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的会话ID"}) - return - } - - var session models.TerminalSession - if err := h.db.First(&session, id).Error; err != nil { - if err == gorm.ErrRecordNotFound { - c.JSON(http.StatusNotFound, models.Response{Code: 404, Message: "会话不存在"}) - return - } - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "查询失败"}) - return - } - - c.JSON(http.StatusOK, models.Response{Code: 200, Data: session.RecordData}) -} - -// DeleteTerminalSession 删除终端会话记录 -// DELETE /api/v1/terminal-sessions/:id -func (h *TerminalSessionHandler) DeleteTerminalSession(c *gin.Context) { - id, err := strconv.ParseUint(c.Param("id"), 10, 64) - if err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的会话ID"}) - return - } - - if err := h.db.Delete(&models.TerminalSession{}, id).Error; err != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) - return - } - - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功"}) -} - -// BatchDeleteTerminalSessions 批量删除终端会话记录 -// POST /api/v1/terminal-sessions/batch-delete -func (h *TerminalSessionHandler) BatchDeleteTerminalSessions(c *gin.Context) { - var req models.IDsRequest - if err := c.ShouldBindJSON(&req); err != nil { - c.JSON(http.StatusBadRequest, models.Response{Code: 400, Message: "无效的请求参数"}) - return - } - - result := h.db.Where("id IN ?", req.IDs).Delete(&models.TerminalSession{}) - if result.Error != nil { - c.JSON(http.StatusInternalServerError, models.Response{Code: 500, Message: "删除失败"}) - return - } - - c.JSON(http.StatusOK, models.Response{Code: 200, Message: "删除成功", Data: gin.H{"deleted": result.RowsAffected}}) -} diff --git a/backend/internal/api/handlers/webshell.go b/backend/internal/api/handlers/webshell.go deleted file mode 100644 index a6db204..0000000 --- a/backend/internal/api/handlers/webshell.go +++ /dev/null @@ -1,325 +0,0 @@ -package handlers - -import ( - "encoding/json" - "fmt" - "log" - "net" - "net/http" - "strconv" - "strings" - "sync" - "time" - - "github.com/gin-gonic/gin" - "github.com/gorilla/websocket" - "golang.org/x/crypto/ssh" - "gorm.io/gorm" - - "ezops/internal/models" -) - -var upgrader = websocket.Upgrader{ - CheckOrigin: func(r *http.Request) bool { - return true - }, - ReadBufferSize: 1024, - WriteBufferSize: 1024, -} - -// WSMessage WebSocket消息结构 // Logan.Li -type WSMessage struct { - Status int `json:"status"` // 0=data, 1=resize - Data string `json:"data"` - Cols int `json:"cols"` - Rows int `json:"rows"` -} - -// WebShellHandler WebShell处理器 -type WebShellHandler struct { - db *gorm.DB - clients sync.Map -} - -// NewWebShellHandler 创建WebShell处理器 -func NewWebShellHandler(db *gorm.DB) *WebShellHandler { - return &WebShellHandler{db: db} -} - -// formatSSHError 将 Go SSH 错误转换为友好的中文提示 // Logan.Li -func formatSSHError(err error) string { - errStr := err.Error() - switch { - case contains(errStr, "i/o timeout"): - return "连接超时(目标主机可能在防火墙后或网络不通)" - case contains(errStr, "connection refused"): - return "连接被拒绝(SSH 服务未运行或端口错误)" - case contains(errStr, "no route to host"): - return "无法路由到目标主机(IP 地址不可达)" - case contains(errStr, "authentication failed") || contains(errStr, "unable to authenticate"): - return "认证失败(用户名或密码错误)" - case contains(errStr, "handshake"): - return "SSH 握手失败(目标可能不是 SSH 服务)" - case contains(errStr, "dns") || contains(errStr, "no such host"): - return "域名解析失败(IP 地址无效)" - case contains(errStr, "ssh: must specify"): - return "认证方式错误(未配置密码或密钥)" - default: - return errStr - } -} - -func contains(s, substr string) bool { - return len(s) >= len(substr) && (s == substr || len(substr) == 0 || - (len(s) > 0 && len(substr) > 0 && indexOf(s, substr) >= 0)) -} - -func indexOf(s, substr string) int { - for i := 0; i <= len(s)-len(substr); i++ { - if s[i:i+len(substr)] == substr { - return i - } - } - return -1 -} - -// Terminal WebSocket终端连接 — 真实SSH,带终端会话录制 // Logan.Li -func (h *WebShellHandler) Terminal(c *gin.Context) { - serverID := c.Query("id") - if serverID == "" { - c.JSON(http.StatusBadRequest, gin.H{"error": "missing server id"}) - return - } - - var server models.Server - if err := h.db.First(&server, serverID).Error; err != nil { - c.JSON(http.StatusNotFound, gin.H{"error": "server not found"}) - return - } - - // 先升级 WebSocket — 这样前端能看到连接过程 - conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) - if err != nil { - log.Printf("[WebShell] WebSocket升级失败: %v", err) - return - } - defer conn.Close() - - // 创建终端会话记录(终端审计) // Logan.Li - var userIDPtr *uint - if uid, exists := c.Get("userID"); exists { - if uidVal, ok := uid.(uint); ok { - userIDPtr = &uidVal - } - } - username, _ := c.Get("username") - usernameStr, _ := username.(string) - - termSession := models.TerminalSession{ - UserID: userIDPtr, - Username: usernameStr, - ServerID: server.ID, - ServerName: server.Hostname, - ServerIP: server.IP, - ServerPort: server.Port, - ClientIP: c.ClientIP(), - Status: "active", - StartTime: time.Now(), - } - if err := h.db.Create(&termSession).Error; err != nil { - log.Printf("[WebShell] 创建会话记录失败: %v", err) - } - - // 终端录制缓冲(限制 1MB 避免内存问题) // Logan.Li - const maxRecordSize = 1024 * 1024 - var recordBuf strings.Builder - - // finalizeSession 结束会话记录(统一收尾) - finalizeSession := func(status string) { - endTime := time.Now() - duration := int(endTime.Sub(termSession.StartTime).Seconds()) - h.db.Model(&termSession).Updates(map[string]interface{}{ - "status": status, - "duration": duration, - "end_time": &endTime, - "record_data": recordBuf.String(), - "record_size": recordBuf.Len(), - }) - } - - conn.WriteJSON(WSMessage{ - Status: 0, - Data: "\r\n\x1b[36m正在连接 " + server.Hostname + " (" + server.IP + ":" + strconv.Itoa(server.Port) + ")...\x1b[0m\r\n", - }) - - // SSH HostKey 验证 — Trust-On-First-Use (TOFU). - // 首次连接记录 fingerprint 到日志;后续连接通过已知 HostKey 校验。 - knownHosts := make(map[string]ssh.PublicKey) - var knownMu sync.Mutex - sshConfig := &ssh.ClientConfig{ - User: server.Username, - Timeout: 10 * time.Second, - HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error { - fp := ssh.FingerprintSHA256(key) - knownMu.Lock() - defer knownMu.Unlock() - if existing, ok := knownHosts[hostname]; ok { - if ssh.FingerprintSHA256(existing) == fp { - return nil - } - return fmt.Errorf("SSH host key mismatch for %s: expected %s, got %s", - hostname, ssh.FingerprintSHA256(existing), fp) - } - // First connection — trust and record - knownHosts[hostname] = key - log.Printf("[WebShell] TOFU: trusting new host key for %s (%s): %s", - server.Hostname, hostname, fp) - return nil - }, - } - - switch server.AuthType { - case "key": - signer, err := ssh.ParsePrivateKey([]byte(server.SSHKey)) - if err != nil { - sshConfig.Auth = []ssh.AuthMethod{ssh.Password(server.Password)} - } else { - sshConfig.Auth = []ssh.AuthMethod{ssh.PublicKeys(signer)} - } - default: - sshConfig.Auth = []ssh.AuthMethod{ - ssh.Password(server.Password), - } - } - - // 连接 SSH(带10秒超时) - addr := server.IP + ":" + strconv.Itoa(server.Port) - sshClient, err := ssh.Dial("tcp", addr, sshConfig) - if err != nil { - log.Printf("[WebShell] SSH连接失败 %s: %v", addr, err) - friendlyErr := formatSSHError(err) - errMsg := "\r\n\x1b[31m连接失败: " + friendlyErr + "\x1b[0m\r\n" + - "\x1b[33m──────────────────────────\x1b[0m\r\n" + - "\x1b[33m目标:\x1b[0m " + server.Hostname + " (" + server.IP + ":" + strconv.Itoa(server.Port) + ")\r\n" + - "\x1b[33m账号:\x1b[0m " + server.Username + "\r\n" + - "\x1b[33m排查:\x1b[0m ① 检查 IP/端口是否正确 ② 确认 SSH 服务运行中 ③ 验证账号密码\r\n" + - "\x1b[33m──────────────────────────\x1b[0m\r\n" - conn.WriteJSON(WSMessage{Status: 0, Data: errMsg}) - recordBuf.WriteString(errMsg) - finalizeSession("failed") - conn.Close() - return - } - defer sshClient.Close() - - log.Printf("[WebShell] SSH已连接 %s (%s)", server.Hostname, addr) - - // 创建 SSH session - session, err := sshClient.NewSession() - if err != nil { - log.Printf("[WebShell] 创建session失败: %v", err) - conn.WriteJSON(WSMessage{Status: 0, Data: "\r\n\x1b[31m创建SSH会话失败\x1b[0m\r\n"}) - finalizeSession("failed") - return - } - defer session.Close() - - // 请求 PTY - modes := ssh.TerminalModes{ - ssh.ECHO: 1, - ssh.TTY_OP_ISPEED: 14400, - ssh.TTY_OP_OSPEED: 14400, - } - if err := session.RequestPty("xterm-256color", 24, 80, modes); err != nil { - log.Printf("[WebShell] PTY请求失败: %v", err) - conn.WriteJSON(WSMessage{Status: 0, Data: "\r\n\x1b[31mPTY请求失败\x1b[0m\r\n"}) - finalizeSession("failed") - return - } - - // 获取管道 - stdinPipe, err := session.StdinPipe() - if err != nil { - finalizeSession("failed") - return - } - stdoutPipe, err := session.StdoutPipe() - if err != nil { - finalizeSession("failed") - return - } - - // 启动 shell - if err := session.Shell(); err != nil { - log.Printf("[WebShell] Shell启动失败: %v", err) - finalizeSession("failed") - return - } - - // 发送欢迎消息 - welcome := "\r\n\x1b[32mAIOps WebShell\x1b[0m — 已连接 " + server.Hostname + " (" + server.IP + ")\r\n\r\n" - conn.WriteJSON(WSMessage{ - Status: 0, - Data: welcome, - }) - recordBuf.WriteString(welcome) - - done := make(chan struct{}) - - // goroutine: SSH stdout -> WebSocket(同时录制输出) // Logan.Li - go func() { - defer close(done) - buf := make([]byte, 8192) - for { - n, err := stdoutPipe.Read(buf) - if err != nil { - discMsg := "\r\n\x1b[31m[远程连接已断开]\x1b[0m\r\n" - conn.WriteJSON(WSMessage{Status: 0, Data: discMsg}) - recordBuf.WriteString(discMsg) - break - } - if n > 0 { - conn.WriteJSON(WSMessage{Status: 0, Data: string(buf[:n])}) - // 录制终端输出(受 1MB 上限保护) - if recordBuf.Len() < maxRecordSize { - remain := maxRecordSize - recordBuf.Len() - if n > remain { - recordBuf.Write(buf[:remain]) - } else { - recordBuf.Write(buf[:n]) - } - } - } - } - }() - - // 主循环: WebSocket -> SSH stdin - for { - msgType, data, err := conn.ReadMessage() - if err != nil { - break - } - - if msgType == websocket.TextMessage { - var msg WSMessage - if err := json.Unmarshal(data, &msg); err != nil { - continue - } - - switch msg.Status { - case 0: // 数据输入 - stdinPipe.Write([]byte(msg.Data)) - case 1: // resize - if msg.Cols > 0 && msg.Rows > 0 { - session.WindowChange(msg.Rows, msg.Cols) - } - } - } - } - - // 等待 stdout goroutine 结束 - <-done - stdinPipe.Close() - finalizeSession("closed") - log.Printf("[WebShell] 断开 %s (%s)", server.Hostname, addr) -} diff --git a/backend/cmd/main.go b/backend/main.go similarity index 98% rename from backend/cmd/main.go rename to backend/main.go index 16aab80..b6aa1ae 100644 --- a/backend/cmd/main.go +++ b/backend/main.go @@ -11,8 +11,9 @@ import ( "syscall" "time" - "ezops/internal/api/routes" - "ezops/internal/config" + "ezops/router" + "ezops/config" + "ezops/seed" "ezops/pkg/database" "ezops/pkg/logger" ezredis "ezops/pkg/redis" @@ -123,7 +124,7 @@ func main() { } // 初始化种子数据 - seedData(db) + seed.SeedData(db) // 初始化缓存(Redka 内嵌 / Redis 外部)// Logan.Li cache, err := ezredis.New(ezredis.Config{ @@ -162,7 +163,7 @@ func main() { }) // 注册路由 - routes.Register(r, db, log, cfg, cache) + router.Register(r, db, log, cfg, cache) // 定期清理旧的 agent 上报数据(保留 7 天,防止表膨胀影响查询性能) go func() { diff --git a/backend/internal/api/middleware/auth.go b/backend/middleware/auth.go similarity index 87% rename from backend/internal/api/middleware/auth.go rename to backend/middleware/auth.go index a847ddb..437a691 100644 --- a/backend/internal/api/middleware/auth.go +++ b/backend/middleware/auth.go @@ -5,8 +5,8 @@ import ( "strings" "time" - "ezops/internal/config" - "ezops/internal/models" + "ezops/config" + "ezops/model" "github.com/gin-gonic/gin" "github.com/golang-jwt/jwt/v5" @@ -21,7 +21,7 @@ type JWTClaims struct { } // GenerateToken 生成JWT令牌 -func GenerateToken(user *models.User, cfg *config.JWTConfig) (string, error) { +func GenerateToken(user *model.User, cfg *config.JWTConfig) (string, error) { claims := JWTClaims{ UserID: user.ID, Username: user.Username, @@ -48,7 +48,7 @@ func JWTAuth(cfg *config.JWTConfig) gin.HandlerFunc { } } if authHeader == "" { - c.JSON(http.StatusUnauthorized, models.Response{ + c.JSON(http.StatusUnauthorized, model.Response{ Code: 401, Message: "未提供认证令牌", }) @@ -58,7 +58,7 @@ func JWTAuth(cfg *config.JWTConfig) gin.HandlerFunc { parts := strings.SplitN(authHeader, " ", 2) if !(len(parts) == 2 && parts[0] == "Bearer") { - c.JSON(http.StatusUnauthorized, models.Response{ + c.JSON(http.StatusUnauthorized, model.Response{ Code: 401, Message: "认证令牌格式错误", }) @@ -72,7 +72,7 @@ func JWTAuth(cfg *config.JWTConfig) gin.HandlerFunc { }) if err != nil { - c.JSON(http.StatusUnauthorized, models.Response{ + c.JSON(http.StatusUnauthorized, model.Response{ Code: 401, Message: "无效的认证令牌: " + err.Error(), }) @@ -86,7 +86,7 @@ func JWTAuth(cfg *config.JWTConfig) gin.HandlerFunc { c.Set("isAdmin", claims.IsAdmin) c.Next() } else { - c.JSON(http.StatusUnauthorized, models.Response{ + c.JSON(http.StatusUnauthorized, model.Response{ Code: 401, Message: "无效的认证令牌", }) @@ -100,7 +100,7 @@ func AdminAuth() gin.HandlerFunc { return func(c *gin.Context) { isAdmin, exists := c.Get("isAdmin") if !exists || !isAdmin.(bool) { - c.JSON(http.StatusForbidden, models.Response{ + c.JSON(http.StatusForbidden, model.Response{ Code: 403, Message: "需要管理员权限", }) diff --git a/backend/internal/api/middleware/pipeline_access.go b/backend/middleware/pipeline_access.go similarity index 93% rename from backend/internal/api/middleware/pipeline_access.go rename to backend/middleware/pipeline_access.go index 9ef768b..434c27b 100644 --- a/backend/internal/api/middleware/pipeline_access.go +++ b/backend/middleware/pipeline_access.go @@ -4,7 +4,7 @@ import ( "net/http" "regexp" - "ezops/internal/models" + "ezops/model" "github.com/gin-gonic/gin" "gorm.io/gorm" @@ -22,7 +22,7 @@ func PipelineAccess(db *gorm.DB) gin.HandlerFunc { return } - var pipeline models.Pipeline + var pipeline model.Pipeline if err := db.Where("code = ?", code).First(&pipeline).Error; err != nil { c.AbortWithStatusJSON(http.StatusNotFound, gin.H{"code": 404, "message": "流水线不存在"}) return @@ -49,7 +49,7 @@ func PipelineAccess(db *gorm.DB) gin.HandlerFunc { // 3) 检查是否直接是流水线成员 var directCount int64 - db.Model(&models.DeployPipelineMember{}). + db.Model(&model.DeployPipelineMember{}). Where("pipeline_id = ? AND username = ?", pipelineID, usernameStr). Count(&directCount) if directCount > 0 { @@ -69,7 +69,7 @@ func PipelineAccess(db *gorm.DB) gin.HandlerFunc { } // 5) Jenkins-style Item Role — regex pattern matching on pipeline code - var itemRoles []models.ItemRole + var itemRoles []model.ItemRole db.Table("iam_item_roles"). Joins("JOIN iam_user_item_roles ON iam_user_item_roles.item_role_id = iam_item_roles.id"). Where("iam_item_roles.status = 1 AND iam_user_item_roles.user_id = ?", @@ -93,12 +93,12 @@ func PipelineAccess(db *gorm.DB) gin.HandlerFunc { // 包括:直接成员 + 用户组 + Item Role (regex) func GetAccessiblePipelineIDs(db *gorm.DB, username string, userID uint) ([]uint, bool) { var directIDs []uint - db.Model(&models.DeployPipelineMember{}). + db.Model(&model.DeployPipelineMember{}). Where("username = ?", username). Pluck("pipeline_id", &directIDs) var groupIDs []uint - db.Model(&models.DeployPipelineMember{}). + db.Model(&model.DeployPipelineMember{}). Joins("JOIN deploy_user_group_members ON deploy_user_group_members.group_id = deploy_pipeline_members.group_id"). Where("deploy_user_group_members.username = ?", username). Pluck("deploy_pipeline_members.pipeline_id", &groupIDs) @@ -112,13 +112,13 @@ func GetAccessiblePipelineIDs(db *gorm.DB, username string, userID uint) ([]uint } // Item Role regex matching: get all item roles for user, match against pipeline codes - var itemRoles []models.ItemRole + var itemRoles []model.ItemRole db.Table("iam_item_roles"). Joins("JOIN iam_user_item_roles ON iam_user_item_roles.item_role_id = iam_item_roles.id"). Where("iam_item_roles.status = 1 AND iam_user_item_roles.user_id = ?", userID). Find(&itemRoles) if len(itemRoles) > 0 { - var allPipelines []models.Pipeline + var allPipelines []model.Pipeline db.Find(&allPipelines) for _, p := range allPipelines { for _, ir := range itemRoles { diff --git a/backend/internal/models/agent.go b/backend/model/agent.go similarity index 99% rename from backend/internal/models/agent.go rename to backend/model/agent.go index d847e6e..8808160 100644 --- a/backend/internal/models/agent.go +++ b/backend/model/agent.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/agent_task.go b/backend/model/agent_task.go similarity index 99% rename from backend/internal/models/agent_task.go rename to backend/model/agent_task.go index dc6b535..b5a2db5 100644 --- a/backend/internal/models/agent_task.go +++ b/backend/model/agent_task.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/alert.go b/backend/model/alert.go similarity index 99% rename from backend/internal/models/alert.go rename to backend/model/alert.go index f8501a4..5b10216 100644 --- a/backend/internal/models/alert.go +++ b/backend/model/alert.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/approval.go b/backend/model/approval.go similarity index 91% rename from backend/internal/models/approval.go rename to backend/model/approval.go index 4fe5846..702c758 100644 --- a/backend/internal/models/approval.go +++ b/backend/model/approval.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" @@ -11,9 +11,10 @@ type ApprovalTemplate struct { Name string `gorm:"size:128;not null" json:"name"` Code string `gorm:"size:64;uniqueIndex;not null" json:"code"` Description string `gorm:"size:500" json:"description"` - Type string `gorm:"size:32;not null" json:"type"` // release, server, permission - FormSchema string `gorm:"type:text" json:"form_schema"` // JSON - FlowConfig string `gorm:"type:text" json:"flow_config"` // JSON + Type string `gorm:"size:32;not null" json:"type"` // release, server_apply, app_deploy, permission_request + FormSchema string `gorm:"type:text" json:"form_schema"` // JSON form fields config + FlowConfig string `gorm:"type:text" json:"flow_config"` // JSON approval flow steps + Category string `gorm:"size:32;default:resource" json:"category"` // resource, app, permission Enabled bool `gorm:"default:true" json:"enabled"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` @@ -77,7 +78,8 @@ type CreateApprovalTemplateRequest struct { Name string `json:"name" binding:"required"` Code string `json:"code" binding:"required"` Description string `json:"description"` - Type string `json:"type" binding:"required,oneof=server_apply app_deploy"` + Type string `json:"type" binding:"required,oneof=server_apply app_deploy permission_request"` + Category string `json:"category"` // resource, app, permission FormSchema string `json:"form_schema"` FlowConfig string `json:"flow_config"` } diff --git a/backend/internal/models/audit.go b/backend/model/audit.go similarity index 99% rename from backend/internal/models/audit.go rename to backend/model/audit.go index 6734ca8..55034c9 100644 --- a/backend/internal/models/audit.go +++ b/backend/model/audit.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/automation.go b/backend/model/automation.go similarity index 99% rename from backend/internal/models/automation.go rename to backend/model/automation.go index 121360f..ba0b090 100644 --- a/backend/internal/models/automation.go +++ b/backend/model/automation.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/billing.go b/backend/model/billing.go similarity index 99% rename from backend/internal/models/billing.go rename to backend/model/billing.go index 57ae5a3..db465a3 100644 --- a/backend/internal/models/billing.go +++ b/backend/model/billing.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/cicd.go b/backend/model/cicd.go similarity index 99% rename from backend/internal/models/cicd.go rename to backend/model/cicd.go index 00c9a98..a0c7bc5 100644 --- a/backend/internal/models/cicd.go +++ b/backend/model/cicd.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/common.go b/backend/model/common.go similarity index 99% rename from backend/internal/models/common.go rename to backend/model/common.go index 244afd9..28f4cb4 100644 --- a/backend/internal/models/common.go +++ b/backend/model/common.go @@ -1,4 +1,4 @@ -package models +package model // Response 通用响应 type Response struct { diff --git a/backend/internal/models/credential.go b/backend/model/credential.go similarity index 99% rename from backend/internal/models/credential.go rename to backend/model/credential.go index a296563..a4f7c3a 100644 --- a/backend/internal/models/credential.go +++ b/backend/model/credential.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/deploy.go b/backend/model/deploy.go similarity index 99% rename from backend/internal/models/deploy.go rename to backend/model/deploy.go index 87d6c0c..ab81096 100644 --- a/backend/internal/models/deploy.go +++ b/backend/model/deploy.go @@ -1,4 +1,4 @@ -package models +package model import "time" diff --git a/backend/internal/models/deploy_tool.go b/backend/model/deploy_tool.go similarity index 99% rename from backend/internal/models/deploy_tool.go rename to backend/model/deploy_tool.go index 26f0529..05ec528 100644 --- a/backend/internal/models/deploy_tool.go +++ b/backend/model/deploy_tool.go @@ -1,4 +1,4 @@ -package models +package model import "time" diff --git a/backend/internal/models/kubernetes.go b/backend/model/kubernetes.go similarity index 99% rename from backend/internal/models/kubernetes.go rename to backend/model/kubernetes.go index 1d6db60..b63109e 100644 --- a/backend/internal/models/kubernetes.go +++ b/backend/model/kubernetes.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/llm.go b/backend/model/llm.go similarity index 99% rename from backend/internal/models/llm.go rename to backend/model/llm.go index 0f38662..5f7494c 100644 --- a/backend/internal/models/llm.go +++ b/backend/model/llm.go @@ -1,4 +1,4 @@ -package models +package model import "time" diff --git a/backend/model/login_log.go b/backend/model/login_log.go new file mode 100644 index 0000000..3e89541 --- /dev/null +++ b/backend/model/login_log.go @@ -0,0 +1,34 @@ +package model + +import "time" + +// LoginLog 登录日志(参考 JumpServer / opsx-web-lite) // Logan.Li +type LoginLog struct { + ID uint `gorm:"primarykey" json:"id"` + UserID *uint `json:"user_id"` + Username string `gorm:"size:64;index" json:"username"` + IP string `gorm:"size:64" json:"ip"` + Location string `gorm:"size:128" json:"location"` // IP 归属地 + Browser string `gorm:"size:128" json:"browser"` // 浏览器 + OS string `gorm:"size:128" json:"os"` // 操作系统 + LoginType string `gorm:"size:32;default:password" json:"login_type"` // password / ldap + UserAgent string `gorm:"size:500" json:"user_agent"` + Status string `gorm:"size:32" json:"status"` // success, failed + FailReason string `gorm:"size:255" json:"fail_reason"` + LoginAt time.Time `gorm:"index" json:"login_at"` + CreatedAt time.Time `json:"created_at"` +} + +func (LoginLog) TableName() string { + return "sys_login_logs" +} + +// LoginLogQuery 登录日志查询 +type LoginLogQuery struct { + Username string `form:"username"` + Status string `form:"status"` + StartTime string `form:"start_time"` + EndTime string `form:"end_time"` + Page int `form:"page,default=1"` + PageSize int `form:"page_size,default=20"` +} diff --git a/backend/internal/models/metrics_aggregate.go b/backend/model/metrics_aggregate.go similarity index 99% rename from backend/internal/models/metrics_aggregate.go rename to backend/model/metrics_aggregate.go index b04dc1f..e017968 100644 --- a/backend/internal/models/metrics_aggregate.go +++ b/backend/model/metrics_aggregate.go @@ -1,4 +1,4 @@ -package models +package model import "time" diff --git a/backend/internal/models/monitor.go b/backend/model/monitor.go similarity index 99% rename from backend/internal/models/monitor.go rename to backend/model/monitor.go index 269f683..395257e 100644 --- a/backend/internal/models/monitor.go +++ b/backend/model/monitor.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/navigation.go b/backend/model/navigation.go similarity index 99% rename from backend/internal/models/navigation.go rename to backend/model/navigation.go index 8fb1d15..5f95399 100644 --- a/backend/internal/models/navigation.go +++ b/backend/model/navigation.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/ops_modules.go b/backend/model/ops_modules.go similarity index 99% rename from backend/internal/models/ops_modules.go rename to backend/model/ops_modules.go index ecefa55..421c1b5 100644 --- a/backend/internal/models/ops_modules.go +++ b/backend/model/ops_modules.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/prometheus_datasource.go b/backend/model/prometheus_datasource.go similarity index 99% rename from backend/internal/models/prometheus_datasource.go rename to backend/model/prometheus_datasource.go index 26b0001..5369d71 100644 --- a/backend/internal/models/prometheus_datasource.go +++ b/backend/model/prometheus_datasource.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/resource_model.go b/backend/model/resource_model.go similarity index 98% rename from backend/internal/models/resource_model.go rename to backend/model/resource_model.go index e40c6bc..10c6535 100644 --- a/backend/internal/models/resource_model.go +++ b/backend/model/resource_model.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/server.go b/backend/model/server.go similarity index 99% rename from backend/internal/models/server.go rename to backend/model/server.go index 99db72f..acf57be 100644 --- a/backend/internal/models/server.go +++ b/backend/model/server.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/model/session_command.go b/backend/model/session_command.go new file mode 100644 index 0000000..2f3bee5 --- /dev/null +++ b/backend/model/session_command.go @@ -0,0 +1,30 @@ +package model + +import "time" + +// SessionCommand 会话命令记录(JumpServer 式命令审计) // Logan.Li +type SessionCommand struct { + ID uint `gorm:"primarykey" json:"id"` + SessionID uint `gorm:"index" json:"session_id"` // 关联终端会话 + UserID *uint `json:"user_id"` + Username string `gorm:"size:64" json:"username"` + ServerID uint `json:"server_id"` + ServerName string `gorm:"size:128" json:"server_name"` + Command string `gorm:"type:text" json:"command"` // 执行的原始命令 + Timestamp time.Time `json:"timestamp"` // 命令执行时间 + CreatedAt time.Time `json:"created_at"` +} + +func (SessionCommand) TableName() string { + return "sys_session_commands" +} + +// SessionCommandQuery 会话命令查询 +type SessionCommandQuery struct { + SessionID uint `form:"session_id"` + Username string `form:"username"` + ServerID uint `form:"server_id"` + Command string `form:"command"` + Page int `form:"page,default=1"` + PageSize int `form:"page_size,default=20"` +} diff --git a/backend/internal/models/site.go b/backend/model/site.go similarity index 99% rename from backend/internal/models/site.go rename to backend/model/site.go index 345d355..f741257 100644 --- a/backend/internal/models/site.go +++ b/backend/model/site.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/snmp.go b/backend/model/snmp.go similarity index 99% rename from backend/internal/models/snmp.go rename to backend/model/snmp.go index 4ae890d..d8f2575 100644 --- a/backend/internal/models/snmp.go +++ b/backend/model/snmp.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/terminal_session.go b/backend/model/terminal_session.go similarity index 90% rename from backend/internal/models/terminal_session.go rename to backend/model/terminal_session.go index 6c0ce20..825f302 100644 --- a/backend/internal/models/terminal_session.go +++ b/backend/model/terminal_session.go @@ -1,4 +1,4 @@ -package models +package model import "time" @@ -14,7 +14,7 @@ type TerminalSession struct { ClientIP string `gorm:"size:64" json:"client_ip"` Status string `gorm:"size:32" json:"status"` // active, closed, failed Duration int `json:"duration"` // seconds - RecordData string `gorm:"type:text" json:"-"` // 终端录制原始输出(不直接返回 JSON) + RecordData string `gorm:"type:mediumtext" json:"-"` // 终端录制原始输出(asciicast v2 格式,max 16MB) RecordSize int `json:"record_size"` // 录制字节数 StartTime time.Time `json:"start_time"` EndTime *time.Time `json:"end_time"` diff --git a/backend/internal/models/user.go b/backend/model/user.go similarity index 99% rename from backend/internal/models/user.go rename to backend/model/user.go index 6979aac..fa421be 100644 --- a/backend/internal/models/user.go +++ b/backend/model/user.go @@ -1,4 +1,4 @@ -package models +package model import ( "time" diff --git a/backend/internal/models/zabbix_datasource.go b/backend/model/zabbix_datasource.go similarity index 99% rename from backend/internal/models/zabbix_datasource.go rename to backend/model/zabbix_datasource.go index 32b78f4..c733ca5 100644 --- a/backend/internal/models/zabbix_datasource.go +++ b/backend/model/zabbix_datasource.go @@ -1,4 +1,4 @@ -package models +package model import "time" diff --git a/backend/pkg/database/database.go b/backend/pkg/database/database.go index 5c7d0a5..9793873 100644 --- a/backend/pkg/database/database.go +++ b/backend/pkg/database/database.go @@ -4,8 +4,8 @@ import ( "fmt" "time" - "ezops/internal/config" - "ezops/internal/models" + "ezops/config" + "ezops/model" "gorm.io/driver/mysql" "gorm.io/driver/postgres" @@ -58,82 +58,82 @@ func New(cfg config.DatabaseConfig) (*gorm.DB, error) { // 避免 GORM + MySQL 8.0 的 "Can't DROP" 索引问题导致整个启动失败 func AutoMigrate(db *gorm.DB) error { allModels := []interface{}{ - &models.User{}, - &models.Role{}, - &models.Permission{}, - &models.Server{}, - &models.Cloud{}, - &models.CloudAccount{}, - &models.Region{}, - &models.Domain{}, - &models.KubernetesCluster{}, - &models.KubernetesNode{}, - &models.KubernetesPod{}, - &models.KubernetesDeployment{}, - &models.KubernetesService{}, - &models.KubernetesIngress{}, - &models.AlertRule{}, - &models.AlertEvent{}, - &models.NotifyChannel{}, - &models.MetricData{}, - &models.Pipeline{}, - &models.PipelineRun{}, - &models.AppRelease{}, - &models.CronJob{}, - &models.Script{}, - &models.TaskExecution{}, - &models.ApprovalTemplate{}, - &models.ApprovalProcess{}, - &models.ApprovalStep{}, - &models.NavigationGroup{}, - &models.NavigationLink{}, - &models.AuditLog{}, - &models.LDAPConfig{}, - &models.ResourceModel{}, - &models.CloudBilling{}, - &models.BillingAlertRule{}, - &models.AgentReport{}, - &models.AgentTask{}, - &models.AgentRule{}, - &models.AgentAlert{}, - &models.AnsiblePlaybook{}, - &models.AnsibleJob{}, - &models.AnsibleInventory{}, - &models.LogSource{}, - &models.LogEntry{}, - &models.TopologyLayout{}, // 拓扑布局保存 // Logan.Li - &models.TerminalSession{}, // 终端会话录制(终端审计) // Logan.Li - &models.LLMConfig{}, // 大语言模型配置(AI 智能助手) // Logan.Li - &models.ChatHistory{}, // 对话历史记录(按用户隔离) // Logan.Li - &models.MetricsAggregate{}, // 指标时序聚合(Redis → MySQL)// Logan.Li - &models.MonitorTarget{}, // 监控目标(主机/中间件/设备/站点) // Logan.Li - &models.MonitorMetric{}, // 监控指标定义 // Logan.Li - &models.MetricValue{}, // 指标当前值 // Logan.Li - &models.MetricHistory{}, // 指标历史时序 // Logan.Li - &models.HostGroup{}, // 主机组 // Logan.Li - &models.SNMPDevice{}, // SNMP设备 // Logan.Li - &models.SNMPTemplate{}, // SNMP模板 // Logan.Li - &models.SiteTask{}, // 站点拨测任务 // Logan.Li - &models.SiteResult{}, // 拨测结果 // Logan.Li - &models.SiteAlert{}, // 拨测告警 // Logan.Li - &models.PrometheusDataSource{}, // Prometheus 数据源配置 // Logan.Li - &models.ZabbixDataSource{}, // Zabbix 数据源配置 // Logan.Li - &models.Credential{}, // 凭据管理(SSH密钥/API Token) // Logan.Li - &models.PipelineRepo{}, // Git 仓库认证 // Logan.Li - &models.PipelineRegistry{}, // 镜像仓库认证 // Logan.Li - &models.DeployEnvironment{}, // 发布环境分组 // Logan.Li - &models.DeployPipelineMember{}, // 流水线成员 // Logan.Li - &models.DeployUserGroup{}, // 用户组 // Logan.Li - &models.DeployUserGroupMember{}, // 用户组成员 // Logan.Li - &models.ItemRole{}, // Jenkins-style Item Role (regex pipeline matching) // Logan.Li - &models.UserItemRole{}, // User ↔ ItemRole association // Logan.Li - &models.DeployTool{}, // 工具配置(懒加载/预装/禁用) // Logan.Li - &models.AlertCondition{}, // 告警条件 // Logan.Li - &models.AlertNotifyTemplate{}, // 告警通知模板 // Logan.Li - &models.AlertUpgrade{}, // 告警升级策略 // Logan.Li - &models.AlertUpgradeRecord{}, // 告警升级记录 // Logan.Li - &models.AlertSilence{}, // 告警静默 // Logan.Li - &models.HealthProbe{}, // 健康探针配置 // Logan.Li + &model.User{}, + &model.Role{}, + &model.Permission{}, + &model.Server{}, + &model.Cloud{}, + &model.CloudAccount{}, + &model.Region{}, + &model.Domain{}, + &model.KubernetesCluster{}, + &model.KubernetesNode{}, + &model.KubernetesPod{}, + &model.KubernetesDeployment{}, + &model.KubernetesService{}, + &model.KubernetesIngress{}, + &model.AlertRule{}, + &model.AlertEvent{}, + &model.NotifyChannel{}, + &model.MetricData{}, + &model.Pipeline{}, + &model.PipelineRun{}, + &model.AppRelease{}, + &model.CronJob{}, + &model.Script{}, + &model.TaskExecution{}, + &model.ApprovalTemplate{}, + &model.ApprovalProcess{}, + &model.ApprovalStep{}, + &model.NavigationGroup{}, + &model.NavigationLink{}, + &model.AuditLog{}, + &model.LDAPConfig{}, + &model.ResourceModel{}, + &model.CloudBilling{}, + &model.BillingAlertRule{}, + &model.AgentReport{}, + &model.AgentTask{}, + &model.AgentRule{}, + &model.AgentAlert{}, + &model.AnsiblePlaybook{}, + &model.AnsibleJob{}, + &model.AnsibleInventory{}, + &model.LogSource{}, + &model.LogEntry{}, + &model.TopologyLayout{}, // 拓扑布局保存 // Logan.Li + &model.TerminalSession{}, // 终端会话录制(终端审计) // Logan.Li + &model.LLMConfig{}, // 大语言模型配置(AI 智能助手) // Logan.Li + &model.ChatHistory{}, // 对话历史记录(按用户隔离) // Logan.Li + &model.MetricsAggregate{}, // 指标时序聚合(Redis → MySQL)// Logan.Li + &model.MonitorTarget{}, // 监控目标(主机/中间件/设备/站点) // Logan.Li + &model.MonitorMetric{}, // 监控指标定义 // Logan.Li + &model.MetricValue{}, // 指标当前值 // Logan.Li + &model.MetricHistory{}, // 指标历史时序 // Logan.Li + &model.HostGroup{}, // 主机组 // Logan.Li + &model.SNMPDevice{}, // SNMP设备 // Logan.Li + &model.SNMPTemplate{}, // SNMP模板 // Logan.Li + &model.SiteTask{}, // 站点拨测任务 // Logan.Li + &model.SiteResult{}, // 拨测结果 // Logan.Li + &model.SiteAlert{}, // 拨测告警 // Logan.Li + &model.PrometheusDataSource{}, // Prometheus 数据源配置 // Logan.Li + &model.ZabbixDataSource{}, // Zabbix 数据源配置 // Logan.Li + &model.Credential{}, // 凭据管理(SSH密钥/API Token) // Logan.Li + &model.PipelineRepo{}, // Git 仓库认证 // Logan.Li + &model.PipelineRegistry{}, // 镜像仓库认证 // Logan.Li + &model.DeployEnvironment{}, // 发布环境分组 // Logan.Li + &model.DeployPipelineMember{}, // 流水线成员 // Logan.Li + &model.DeployUserGroup{}, // 用户组 // Logan.Li + &model.DeployUserGroupMember{}, // 用户组成员 // Logan.Li + &model.ItemRole{}, // Jenkins-style Item Role (regex pipeline matching) // Logan.Li + &model.UserItemRole{}, // User ↔ ItemRole association // Logan.Li + &model.DeployTool{}, // 工具配置(懒加载/预装/禁用) // Logan.Li + &model.AlertCondition{}, // 告警条件 // Logan.Li + &model.AlertNotifyTemplate{}, // 告警通知模板 // Logan.Li + &model.AlertUpgrade{}, // 告警升级策略 // Logan.Li + &model.AlertUpgradeRecord{}, // 告警升级记录 // Logan.Li + &model.AlertSilence{}, // 告警静默 // Logan.Li + &model.HealthProbe{}, // 健康探针配置 // Logan.Li } var lastErr error diff --git a/backend/pkg/toolinstaller/installer.go b/backend/pkg/toolinstaller/installer.go index 7b0071b..eaa3f3f 100644 --- a/backend/pkg/toolinstaller/installer.go +++ b/backend/pkg/toolinstaller/installer.go @@ -12,7 +12,7 @@ import ( "sync" "time" - "ezops/internal/models" + "ezops/model" "gorm.io/gorm" ) @@ -49,7 +49,7 @@ func (ti *ToolInstaller) ensureOnce(name string) *sync.Once { // Used by the manual "安装" button in the tool config UI. // The version parameter overrides DefaultVersion if non-empty. func (ti *ToolInstaller) ForceInstall(toolName string, version string) error { - var tool models.DeployTool + var tool model.DeployTool if err := ti.db.Where("name = ?", toolName).First(&tool).Error; err != nil { return fmt.Errorf("tool %s not found in DB: %w", toolName, err) } @@ -67,7 +67,7 @@ func (ti *ToolInstaller) ForceInstall(toolName string, version string) error { // Returns nil if the tool is ready, or an error if installation failed. func (ti *ToolInstaller) EnsureAvailable(toolName string) error { // Find tool in DB - var tool models.DeployTool + var tool model.DeployTool if err := ti.db.Where("name = ?", toolName).First(&tool).Error; err != nil { // Tool not in DB — try to find it by path if _, lookErr := exec.LookPath(toolName); lookErr == nil { @@ -81,22 +81,22 @@ func (ti *ToolInstaller) EnsureAvailable(toolName string) error { } // Check if already installed - if tool.InstallMethod == models.ToolPreinstall || tool.InstallMethod == models.ToolLazy { + if tool.InstallMethod == model.ToolPreinstall || tool.InstallMethod == model.ToolLazy { if inst, err := ti.checkInstalled(tool); err == nil { // Update status if needed - if tool.Status != models.ToolInstalled { - ti.updateStatus(tool.ID, models.ToolInstalled, inst, "") + if tool.Status != model.ToolInstalled { + ti.updateStatus(tool.ID, model.ToolInstalled, inst, "") } return nil } } switch tool.InstallMethod { - case models.ToolPreinstall: + case model.ToolPreinstall: return fmt.Errorf("tool %s should be preinstalled but not found", toolName) - case models.ToolDisabled: + case model.ToolDisabled: return fmt.Errorf("tool %s is disabled", toolName) - case models.ToolLazy: + case model.ToolLazy: // Use sync.Once to prevent concurrent installs var installErr error once := ti.ensureOnce(toolName) @@ -116,7 +116,7 @@ func (ti *ToolInstaller) EnsureAvailable(toolName string) error { } // checkInstalled runs the tool's check command and returns the version string. -func (ti *ToolInstaller) checkInstalled(tool models.DeployTool) (string, error) { +func (ti *ToolInstaller) checkInstalled(tool model.DeployTool) (string, error) { // First try LookPath if tool.BinaryName != "" { if _, err := exec.LookPath(tool.BinaryName); err != nil { @@ -138,11 +138,11 @@ func (ti *ToolInstaller) checkInstalled(tool models.DeployTool) (string, error) } // installTool performs the actual installation. -func (ti *ToolInstaller) installTool(tool *models.DeployTool) error { +func (ti *ToolInstaller) installTool(tool *model.DeployTool) error { log.Printf("[ToolInstaller] Installing %s (method=%s)...", tool.Name, tool.InstallMethod) // Mark as installing - ti.updateStatus(tool.ID, models.ToolInstalling, "", "") + ti.updateStatus(tool.ID, model.ToolInstalling, "", "") var err error if tool.InstallScript != "" { @@ -156,7 +156,7 @@ func (ti *ToolInstaller) installTool(tool *models.DeployTool) error { if err != nil { errMsg := err.Error() log.Printf("[ToolInstaller] ERROR installing %s: %s", tool.Name, errMsg) - ti.updateStatus(tool.ID, models.ToolFailed, "", errMsg) + ti.updateStatus(tool.ID, model.ToolFailed, "", errMsg) return fmt.Errorf("failed to install %s: %w", tool.Name, err) } @@ -164,17 +164,17 @@ func (ti *ToolInstaller) installTool(tool *models.DeployTool) error { ver, checkErr := ti.checkInstalled(*tool) if checkErr != nil { log.Printf("[ToolInstaller] WARNING: %s installed but check failed: %v", tool.Name, checkErr) - ti.updateStatus(tool.ID, models.ToolInstalled, "unknown", "") + ti.updateStatus(tool.ID, model.ToolInstalled, "unknown", "") } else { log.Printf("[ToolInstaller] %s installed successfully: %s", tool.Name, ver) - ti.updateStatus(tool.ID, models.ToolInstalled, ver, "") + ti.updateStatus(tool.ID, model.ToolInstalled, ver, "") } return nil } // runInstallScript executes the tool's install script in a subshell. -func (ti *ToolInstaller) runInstallScript(tool *models.DeployTool) error { +func (ti *ToolInstaller) runInstallScript(tool *model.DeployTool) error { // Write script to temp file tmpFile, err := os.CreateTemp("", fmt.Sprintf("tool-install-%s-*.sh", tool.Name)) if err != nil { @@ -203,7 +203,7 @@ func (ti *ToolInstaller) runInstallScript(tool *models.DeployTool) error { // downloadBinary downloads a binary file to the install path. // Uses multi-mirror fallback: tries each mirror URL in order, with HEAD verification // to skip dead mirrors before attempting a full download. -func (ti *ToolInstaller) downloadBinary(tool *models.DeployTool) error { +func (ti *ToolInstaller) downloadBinary(tool *model.DeployTool) error { version := tool.DefaultVersion if version == "" { // Try to get latest version @@ -244,7 +244,7 @@ func (ti *ToolInstaller) downloadBinary(tool *models.DeployTool) error { } // tryDownload attempts a single download from a URL. -func (ti *ToolInstaller) tryDownload(url string, tool *models.DeployTool) error { +func (ti *ToolInstaller) tryDownload(url string, tool *model.DeployTool) error { // Use a client with timeout for the download phase. // Large files (kubectl ~50MB) can take minutes on slow networks. client := &http.Client{Timeout: 30 * time.Minute} @@ -307,7 +307,7 @@ func (ti *ToolInstaller) fetchVersion(url string) (string, error) { } // updateStatus updates the tool's status in the database. -func (ti *ToolInstaller) updateStatus(toolID uint, status models.ToolStatus, version string, errMsg string) { +func (ti *ToolInstaller) updateStatus(toolID uint, status model.ToolStatus, version string, errMsg string) { now := time.Now() updates := map[string]interface{}{ "status": status, @@ -319,29 +319,29 @@ func (ti *ToolInstaller) updateStatus(toolID uint, status models.ToolStatus, ver if errMsg != "" { updates["error_msg"] = errMsg } - ti.db.Model(&models.DeployTool{}).Where("id = ?", toolID).Updates(updates) + ti.db.Model(&model.DeployTool{}).Where("id = ?", toolID).Updates(updates) } // SeedTools inserts predefined tools into the database if the table is empty. func (ti *ToolInstaller) SeedTools() { var count int64 - ti.db.Model(&models.DeployTool{}).Count(&count) + ti.db.Model(&model.DeployTool{}).Count(&count) if count > 0 { return } - tools := models.PredefinedTools() + tools := model.PredefinedTools() now := time.Now() for i := range tools { tools[i].CreatedAt = now tools[i].UpdatedAt = now // Check if preinstalled tools are actually available - if tools[i].InstallMethod == models.ToolPreinstall { + if tools[i].InstallMethod == model.ToolPreinstall { if ver, err := ti.checkInstalled(tools[i]); err == nil { - tools[i].Status = models.ToolInstalled + tools[i].Status = model.ToolInstalled tools[i].InstalledVer = ver } else { - tools[i].Status = models.ToolNotInstalled + tools[i].Status = model.ToolNotInstalled } } } diff --git a/backend/repository/repo.go b/backend/repository/repo.go new file mode 100644 index 0000000..995e4d2 --- /dev/null +++ b/backend/repository/repo.go @@ -0,0 +1,239 @@ +// Package repository 提供数据访问层 — 所有 DB 操作集中在此 +// Handler / Service 不直接操作 *gorm.DB +package repository + +import ( + "ezops/model" + + "gorm.io/gorm" +) + +// ━━━ Server Repository ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +type ServerRepository struct { + db *gorm.DB +} + +func NewServerRepository(db *gorm.DB) *ServerRepository { + return &ServerRepository{db: db} +} + +func (r *ServerRepository) DB() *gorm.DB { + return r.db +} + +// List 分页查询服务器列表 +func (r *ServerRepository) List(keyword, status, regionID string, page, pageSize int) ([]model.Server, int64, error) { + q := r.db.Model(&model.Server{}) + if keyword != "" { + q = q.Where("hostname LIKE ? OR ip LIKE ? OR public_ip LIKE ?", + "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%") + } + if status != "" { + q = q.Where("status = ?", status) + } + if regionID != "" { + q = q.Where("region_id = ?", regionID) + } + + var total int64 + q.Count(&total) + + var list []model.Server + err := q.Preload("Region").Preload("Cloud"). + Offset((page - 1) * pageSize).Limit(pageSize). + Order("created_at DESC").Find(&list).Error + + return list, total, err +} + +// GetByID 根据 ID 获取服务器 +func (r *ServerRepository) GetByID(id uint) (*model.Server, error) { + var s model.Server + err := r.db.Preload("Region").Preload("Cloud").First(&s, id).Error + if err != nil { + return nil, err + } + return &s, nil +} + +// Create 创建服务器 +func (r *ServerRepository) Create(s *model.Server) error { + return r.db.Create(s).Error +} + +// Update 更新服务器 (全量) +func (r *ServerRepository) Update(s *model.Server) error { + return r.db.Save(s).Error +} + +// UpdateFields 部分更新 +func (r *ServerRepository) UpdateFields(id uint, updates map[string]interface{}) error { + return r.db.Model(&model.Server{}).Where("id = ?", id).Updates(updates).Error +} + +// Delete 删除服务器 +func (r *ServerRepository) Delete(id uint) error { + return r.db.Delete(&model.Server{}, id).Error +} + +// CountByStatus 按状态统计 +func (r *ServerRepository) CountByStatus(status string) int64 { + var c int64 + r.db.Model(&model.Server{}).Where("status = ?", status).Count(&c) + return c +} + +// AvgMetric 获取平均指标 +func (r *ServerRepository) AvgMetric(field string) float64 { + var v float64 + r.db.Model(&model.Server{}).Select("AVG(" + field + ")").Scan(&v) + return v +} + +// ━━━ Credential Repository ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +type CredentialRepository struct { + db *gorm.DB +} + +func NewCredentialRepository(db *gorm.DB) *CredentialRepository { + return &CredentialRepository{db: db} +} + +// List 分页查询凭据 +func (r *CredentialRepository) List(keyword, secretType string, page, pageSize int) ([]model.Credential, int64, error) { + q := r.db.Model(&model.Credential{}) + if keyword != "" { + q = q.Where("name LIKE ?", "%"+keyword+"%") + } + if secretType != "" { + q = q.Where("secret_type = ?", secretType) + } + + var total int64 + q.Count(&total) + + var list []model.Credential + err := q.Offset((page - 1) * pageSize).Limit(pageSize). + Order("created_at DESC").Find(&list).Error + + return list, total, err +} + +// GetByID 根据 ID 获取凭据 +func (r *CredentialRepository) GetByID(id uint) (*model.Credential, error) { + var c model.Credential + err := r.db.First(&c, id).Error + if err != nil { + return nil, err + } + return &c, nil +} + +// Create 创建凭据 +func (r *CredentialRepository) Create(c *model.Credential) error { + return r.db.Create(c).Error +} + +// Update 全量更新凭据 +func (r *CredentialRepository) Update(c *model.Credential) error { + return r.db.Save(c).Error +} + +// UpdateFields 部分更新 +func (r *CredentialRepository) UpdateFields(id uint, updates map[string]interface{}) error { + return r.db.Model(&model.Credential{}).Where("id = ?", id).Updates(updates).Error +} + +// Delete 删除凭据 +func (r *CredentialRepository) Delete(id uint) error { + return r.db.Delete(&model.Credential{}, id).Error +} + +// ━━━ Alert Contact Repository ━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +type AlertContactRepository struct { + db *gorm.DB +} + +func NewAlertContactRepository(db *gorm.DB) *AlertContactRepository { + return &AlertContactRepository{db: db} +} + +func (r *AlertContactRepository) List(keyword string, page, pageSize int) ([]model.AlertContact, int64, error) { + q := r.db.Model(&model.AlertContact{}) + if keyword != "" { + q = q.Where("name LIKE ?", "%"+keyword+"%") + } + var total int64 + q.Count(&total) + var list []model.AlertContact + err := q.Offset((page - 1) * pageSize).Limit(pageSize). + Order("created_at DESC").Find(&list).Error + return list, total, err +} + +func (r *AlertContactRepository) GetByID(id uint) (*model.AlertContact, error) { + var c model.AlertContact + err := r.db.First(&c, id).Error + if err != nil { + return nil, err + } + return &c, nil +} + +func (r *AlertContactRepository) Create(c *model.AlertContact) error { + return r.db.Create(c).Error +} + +func (r *AlertContactRepository) Update(c *model.AlertContact) error { + return r.db.Save(c).Error +} + +func (r *AlertContactRepository) Delete(id uint) error { + return r.db.Delete(&model.AlertContact{}, id).Error +} + +// AlertContactGroup Repository +type AlertContactGroupRepository struct { + db *gorm.DB +} + +func NewAlertContactGroupRepository(db *gorm.DB) *AlertContactGroupRepository { + return &AlertContactGroupRepository{db: db} +} + +func (r *AlertContactGroupRepository) List(keyword string, page, pageSize int) ([]model.AlertContactGroup, int64, error) { + q := r.db.Model(&model.AlertContactGroup{}) + if keyword != "" { + q = q.Where("group_name LIKE ?", "%"+keyword+"%") + } + var total int64 + q.Count(&total) + var list []model.AlertContactGroup + err := q.Offset((page - 1) * pageSize).Limit(pageSize). + Order("created_at DESC").Find(&list).Error + return list, total, err +} + +func (r *AlertContactGroupRepository) GetByID(id uint) (*model.AlertContactGroup, error) { + var g model.AlertContactGroup + err := r.db.First(&g, id).Error + if err != nil { + return nil, err + } + return &g, nil +} + +func (r *AlertContactGroupRepository) Create(g *model.AlertContactGroup) error { + return r.db.Create(g).Error +} + +func (r *AlertContactGroupRepository) UpdateFields(id uint, updates map[string]interface{}) error { + return r.db.Model(&model.AlertContactGroup{}).Where("id = ?", id).Updates(updates).Error +} + +func (r *AlertContactGroupRepository) Delete(id uint) error { + return r.db.Delete(&model.AlertContactGroup{}, id).Error +} diff --git a/backend/internal/api/routes/routes.go b/backend/router/routes.go similarity index 84% rename from backend/internal/api/routes/routes.go rename to backend/router/routes.go index ff3a28f..f256c9f 100644 --- a/backend/internal/api/routes/routes.go +++ b/backend/router/routes.go @@ -1,12 +1,15 @@ -package routes +package router import ( - "ezops/internal/api/handlers" - "ezops/internal/api/middleware" - "ezops/internal/config" + "ezops/controller" + "ezops/middleware" + "ezops/config" + "ezops/model" + "ezops/service" ezredis "ezops/pkg/redis" "ezops/pkg/toolinstaller" "fmt" + "strconv" "github.com/gin-gonic/gin" "go.uber.org/zap" @@ -60,42 +63,69 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c }) // WebSocket终端 (JWT 鉴权,支持 ?token= 查询参数;终端会话录制) // Logan.Li - webShellHandler := handlers.NewWebShellHandler(db) + auditHub := controller.NewAuditHub() + webShellHandler := controller.NewWebShellHandler(db, auditHub) r.GET("/ws/terminal", middleware.JWTAuth(&cfg.JWT), webShellHandler.Terminal) + // WebSocket 审计实时流 — 在线会话实时查看 // Logan.Li + r.GET("/ws/audit/:sessionId", middleware.JWTAuth(&cfg.JWT), func(c *gin.Context) { + idStr := c.Param("sessionId") + id, err := strconv.ParseUint(idStr, 10, 64) + if err != nil { + c.JSON(400, gin.H{"error": "invalid session id"}) + return + } + var session model.TerminalSession + if err := db.First(&session, id).Error; err != nil { + c.JSON(404, gin.H{"error": "session not found"}) + return + } + auditHub.ServeAuditStream(c, uint(id), session.RecordData, gin.H{ + "session_id": session.ID, + "username": session.Username, + "server_name": session.ServerName, + "server_ip": session.ServerIP, + "start_time": session.StartTime, + "status": session.Status, + }) + }) + // WebSocket 实时指标推送(JWT 鉴权) // Logan.Li - metricsHub := handlers.NewMetricsHub() - metricsWSHandler := handlers.NewMetricsWSHandler(metricsHub) + metricsHub := controller.NewMetricsHub() + metricsWSHandler := controller.NewMetricsWSHandler(metricsHub) r.GET("/ws/metrics", middleware.JWTAuth(&cfg.JWT), metricsWSHandler.ServeWS) // WebSocket 流水线日志推流 - wsLogHandler := handlers.NewWSPipelineLogHandler(db, redisCache) + wsLogHandler := controller.NewWSPipelineLogHandler(db, redisCache) r.GET("/ws/pipeline/:runId/log", wsLogHandler.StreamLog) r.GET("/api/v1/pipelines/runs/:runId/log-stream", wsLogHandler.GetLogHistory) // 工作区文件浏览器(浏览/下载流水线构建目录文件) - workspaceFilesHandler := handlers.NewWorkspaceFilesHandler(db) + workspaceFilesHandler := controller.NewWorkspaceFilesHandler(db) r.GET("/api/v1/pipelines/runs/:runId/files", workspaceFilesHandler.ListFiles) r.GET("/api/v1/pipelines/runs/:runId/files/download", workspaceFilesHandler.DownloadFile) // WebSocket K8s exec 交互终端 // Logan.Li - k8sHandler := handlers.NewKubernetesHandler(db) + k8sHandler := controller.NewKubernetesHandler(db) r.GET("/ws/kubernetes-exec/:id/namespaces/:namespace/pods/:podName", middleware.JWTAuth(&cfg.JWT), k8sHandler.ExecTerminal) // ToolInstaller(工具懒加载服务 — kubectl/maven/node/helm)// Logan.Li ti := toolinstaller.New(db) + // V2 Services 层 — 依赖注入 (server, credential, alert) // Logan.Li + svcs := service.NewServices(db, redisCache, cfg.JWT.Secret) + // WebSocket kubectl 命令行终端 // Logan.Li - kubectlShellHandler := handlers.NewKubectlShellHandler(db, ti) + kubectlShellHandler := controller.NewKubectlShellHandler(db, ti) r.GET("/ws/kubectl", middleware.JWTAuth(&cfg.JWT), kubectlShellHandler.Terminal) // 公开路由 - authHandler := handlers.NewUserHandler(db, cfg) + authHandler := controller.NewUserHandler(db, cfg) api.POST("/auth/login", authHandler.Login) api.POST("/auth/register", authHandler.Register) // Webhook 触发路由(无需 JWT,由 Webhook Token 签名验证) - pipelineHandler := handlers.NewPipelineHandler(db, redisCache) + pipelineHandler := controller.NewPipelineHandler(db, redisCache) webhookGroup := api.Group("/webhook") { webhookGroup.POST("/job/:jobName", pipelineHandler.WebhookTrigger) @@ -103,7 +133,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // Agent 安装处理器(在 servers 和 agent 路由中共享) - agentInstallHandler := handlers.NewAgentInstallHandler(db) + agentInstallHandler := controller.NewAgentInstallHandler(db) // 需要认证的路由 authorized := api.Group("") @@ -140,7 +170,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c admin.GET("/permissions", authHandler.ListPermissions) // Item Role 管理(Jenkins-style regex pipeline matching) // Logan.Li - itemRoleHandler := handlers.NewItemRoleHandler(db) + itemRoleHandler := controller.NewItemRoleHandler(db) admin.GET("/item-roles", itemRoleHandler.ListItemRoles) admin.POST("/item-roles", itemRoleHandler.CreateItemRole) admin.PUT("/item-roles/:id", itemRoleHandler.UpdateItemRole) @@ -151,7 +181,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // LDAP 配置路由 - ldapHandler := handlers.NewLDAPHandler(db) + ldapHandler := controller.NewLDAPHandler(db) ldapGroup := authorized.Group("/admin/ldap-config") ldapGroup.Use(middleware.AdminAuth()) { @@ -168,7 +198,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 仪表盘路由 - dashboardHandler := handlers.NewDashboardHandler(db, redisCache) + dashboardHandler := controller.NewDashboardHandler(db, redisCache) dashboard := authorized.Group("/dashboard") { dashboard.GET("/stats", dashboardHandler.GetStats) @@ -178,25 +208,33 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 服务器路由 - serverHandler := handlers.NewServerHandler(db, cfg.JWT.Secret, redisCache) + serverHandlerV2 := controller.NewServerHandlerV2(svcs.Server, db) servers := authorized.Group("/servers") { - servers.GET("", serverHandler.ListServers) - servers.GET("/stats", serverHandler.GetServerStats) - servers.GET("/:id", serverHandler.GetServer) - servers.POST("", serverHandler.CreateServer) - servers.PUT("/:id", serverHandler.UpdateServer) - servers.DELETE("/:id", serverHandler.DeleteServer) - servers.POST("/batch-delete", serverHandler.BatchDeleteServers) - servers.POST("/batch", serverHandler.BatchCreateServers) + servers.GET("", serverHandlerV2.ListServers) + servers.GET("/stats", serverHandlerV2.GetServerStats) + servers.GET("/:id", serverHandlerV2.GetServer) + servers.POST("", serverHandlerV2.CreateServer) + servers.PUT("/:id", serverHandlerV2.UpdateServer) + servers.DELETE("/:id", serverHandlerV2.DeleteServer) + servers.POST("/batch-delete", serverHandlerV2.BatchDeleteServers) + servers.POST("/batch", serverHandlerV2.BatchCreateServers) - // Agent 远程安装 // Logan.Li - servers.POST("/:id/install-agent", agentInstallHandler.InstallAgent) - servers.POST("/install-agent", agentInstallHandler.BatchInstallAgent) - } + // Agent 远程安装 // Logan.Li + servers.POST("/:id/install-agent", agentInstallHandler.InstallAgent) + servers.POST("/install-agent", agentInstallHandler.BatchInstallAgent) + + // SFTP 文件浏览 // Logan.Li + sftpHandler := controller.NewSFTPHandler(db) + servers.GET("/:id/files", sftpHandler.ListFiles) + servers.GET("/:id/files/download", sftpHandler.DownloadFile) + servers.POST("/:id/files/upload", sftpHandler.UploadFile) + servers.DELETE("/:id/files", sftpHandler.DeleteFile) + servers.POST("/:id/files/mkdir", sftpHandler.Mkdir) + } // 云账号路由 - cloudAccountHandler := handlers.NewCloudAccountHandler(db) + cloudAccountHandler := controller.NewCloudAccountHandler(db) cloudAccounts := authorized.Group("/cloud-accounts") { cloudAccounts.GET("", cloudAccountHandler.ListCloudAccounts) @@ -205,7 +243,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c cloudAccounts.DELETE("/:id", cloudAccountHandler.DeleteCloudAccount) // 云同步路由 — 区域同步 / 主机发现 / 导入主机 // Logan.Li - syncHandler := handlers.NewCloudSyncHandler(db) + syncHandler := controller.NewCloudSyncHandler(db) cloudAccounts.POST("/:id/sync-regions", syncHandler.SyncRegions) cloudAccounts.GET("/:id/regions", syncHandler.GetAccountRegions) cloudAccounts.POST("/:id/discover-instances", syncHandler.DiscoverInstances) @@ -213,7 +251,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 域名路由 - domainHandler := handlers.NewDomainHandler(db) + domainHandler := controller.NewDomainHandler(db) domains := authorized.Group("/domains") { domains.GET("", domainHandler.ListDomains) @@ -223,7 +261,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 云平台路由 - platformHandler := handlers.NewPlatformHandler(db) + platformHandler := controller.NewPlatformHandler(db) platforms := authorized.Group("/platforms") { platforms.GET("", platformHandler.ListPlatforms) @@ -233,7 +271,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 区域路由 - regionHandler := handlers.NewRegionHandler(db) + regionHandler := controller.NewRegionHandler(db) regions := authorized.Group("/regions") { regions.GET("", regionHandler.ListRegions) @@ -244,7 +282,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 云账单路由 - billingHandler := handlers.NewBillingHandler(db) + billingHandler := controller.NewBillingHandler(db) billings := authorized.Group("/cloud-billings") { billings.GET("", billingHandler.ListBillings) @@ -264,7 +302,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 资源模型路由 - resourceModelHandler := handlers.NewResourceModelHandler(db) + resourceModelHandler := controller.NewResourceModelHandler(db) resourceModels := authorized.Group("/resource-models") { resourceModels.GET("", resourceModelHandler.ListResourceModels) @@ -448,7 +486,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 告警路由 - alertHandler := handlers.NewAlertHandler(db) + alertHandler := controller.NewAlertHandler(db) alerts := authorized.Group("/alerts") { alerts.GET("", alertHandler.ListAlerts) @@ -466,15 +504,23 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c alerts.POST("/notify-channels/:id/test", alertHandler.TestNotifyChannel) alerts.POST("/quick-setup", alertHandler.QuickSetupRules) // 报警联系人 - alerts.GET("/contacts", alertHandler.ListContacts) - alerts.POST("/contacts", alertHandler.CreateContact) - alerts.PUT("/contacts/:id", alertHandler.UpdateContact) - alerts.DELETE("/contacts/:id", alertHandler.DeleteContact) + alertContactV2 := controller.NewAlertContactHandlerV2(svcs.AlertContact) + alerts.GET("/contacts", alertContactV2.ListContacts) + alerts.POST("/contacts", alertContactV2.CreateContact) + alerts.PUT("/contacts/:id", alertContactV2.UpdateContact) + alerts.DELETE("/contacts/:id", alertContactV2.DeleteContact) // 报警联系组 - alerts.GET("/contact-groups", alertHandler.ListContactGroups) - alerts.POST("/contact-groups", alertHandler.CreateContactGroup) - alerts.PUT("/contact-groups/:id", alertHandler.UpdateContactGroup) - alerts.DELETE("/contact-groups/:id", alertHandler.DeleteContactGroup) + alertGroupV2 := controller.NewAlertContactGroupHandlerV2(svcs.AlertContactGroup) + alerts.GET("/contact-groups", alertGroupV2.ListGroups) + alerts.POST("/contact-groups", alertGroupV2.CreateGroup) + alerts.PUT("/contact-groups/:id", alertGroupV2.UpdateGroup) + alerts.DELETE("/contact-groups/:id", alertGroupV2.DeleteGroup) + // 告警静默规则 + alerts.GET("/silences", alertHandler.ListSilences) + alerts.POST("/silences", alertHandler.CreateSilence) + alerts.PUT("/silences/:id", alertHandler.UpdateSilence) + alerts.DELETE("/silences/:id", alertHandler.DeleteSilence) + alerts.POST("/silences/:id/toggle", alertHandler.ToggleSilence) } // 流水线路由 @@ -540,7 +586,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 仓库认证 & 镜像仓库认证路由 - deployHandler := handlers.NewDeployHandler(db) + deployHandler := controller.NewDeployHandler(db) { repos := authorized.Group("/deploy/repos") repos.GET("", deployHandler.ListRepos) @@ -558,7 +604,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 工具配置路由(发布配置 Tab ④)// Logan.Li - toolConfigHandler := handlers.NewToolConfigHandler(db, ti) + toolConfigHandler := controller.NewToolConfigHandler(db, ti) tools := authorized.Group("/deploy/tools") { tools.GET("", toolConfigHandler.ListTools) @@ -570,7 +616,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 自动化运维路由 - automationHandler := handlers.NewAutomationHandler(db) + automationHandler := controller.NewAutomationHandler(db) cronJobs := authorized.Group("/cron-jobs") { cronJobs.GET("", automationHandler.ListCronJobs) @@ -595,7 +641,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 远程执行路由 — Go 原生 SSH 批量执行替代 Ansible // Logan.Li - remoteExecHandler := handlers.NewRemoteExecHandler(db) + remoteExecHandler := controller.NewRemoteExecHandler(db) remoteExec := authorized.Group("/remote-exec") { remoteExec.POST("/execute", remoteExecHandler.BatchExec) @@ -608,7 +654,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c authorized.GET("/task-executions", automationHandler.ListExecutions) // 日志监控路由 // Logan.Li - logHandler := handlers.NewLogHandler(db) + logHandler := controller.NewLogHandler(db) logs := authorized.Group("/logs") { logs.GET("", logHandler.QueryLogs) @@ -618,7 +664,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 审批流程路由 - approvalHandler := handlers.NewApprovalHandler(db) + approvalHandler := controller.NewApprovalHandler(db) approvals := authorized.Group("/approvals") { approvals.GET("/templates", approvalHandler.ListTemplates) @@ -635,7 +681,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 导航路由 - navHandler := handlers.NewNavigationHandler(db) + navHandler := controller.NewNavigationHandler(db) navigations := authorized.Group("/navigations") { navigations.GET("/groups", navHandler.ListGroups) @@ -651,7 +697,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 审计日志路由 - auditHandler := handlers.NewAuditHandler(db) + auditHandler := controller.NewAuditHandler(db) audit := authorized.Group("/audit") { audit.GET("/logs", auditHandler.ListAuditLogs) @@ -664,7 +710,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 终端会话审计路由(WebSSH 录制回放) // Logan.Li - terminalSessionHandler := handlers.NewTerminalSessionHandler(db) + terminalSessionHandler := controller.NewTerminalSessionHandler(db, webShellHandler.KillSession) ts := authorized.Group("/terminal-sessions") { ts.GET("", terminalSessionHandler.ListTerminalSessions) @@ -672,11 +718,28 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c ts.GET("/:id", terminalSessionHandler.GetTerminalSession) ts.GET("/:id/record", terminalSessionHandler.GetTerminalRecord) ts.DELETE("/:id", terminalSessionHandler.DeleteTerminalSession) + ts.POST("/:id/kill", terminalSessionHandler.KillSession) + ts.GET("/:id/download", terminalSessionHandler.DownloadSession) + ts.GET("/:id/stream", terminalSessionHandler.StreamSession) + } + + // 会话命令审计路由(JumpServer 式命令审计) // Logan.Li + scHandler := controller.NewSessionCommandHandler(db) + sc := authorized.Group("/session-commands") + { + sc.GET("", scHandler.ListSessionCommands) + } + + // 登录日志路由 // Logan.Li + llHandler := controller.NewLoginLogHandler(db) + ll := authorized.Group("/login-logs") + { + ll.GET("", llHandler.ListLoginLogs) } // Agent 上报路由(无需 JWT) - agentHandler := handlers.NewAgentHandler(db, redisCache, metricsHub) - taskHandler := handlers.NewAgentTaskHandler(db) + agentHandler := controller.NewAgentHandler(db, redisCache, metricsHub) + taskHandler := controller.NewAgentTaskHandler(db) agentGroup := api.Group("/agent") { agentGroup.POST("/report", agentHandler.ReceiveReport) @@ -732,7 +795,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c r.Static("/api/agent/bin", "/app/agent/bin") // AI 智能助手 - LLM 配置 + 对话代理(OpenAI 兼容) // Logan.Li - llmHandler := handlers.NewLLMHandler(db) + llmHandler := controller.NewLLMHandler(db) aiopsGroup := authorized.Group("/aiops") { aiopsGroup.GET("/llm-config", llmHandler.GetLLMConfig) @@ -745,7 +808,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 指标浏览器 — 监控指标元数据 + 时序查询 // Logan.Li - metricsHandler := handlers.NewMetricsHandler(db) + metricsHandler := controller.NewMetricsHandler(db) metricsGroup := authorized.Group("/metrics") { metricsGroup.GET("/targets", metricsHandler.ListTargets) @@ -756,7 +819,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // SNMP 设备管理 — 网络设备/服务器硬件 // Logan.Li - snmpHandler := handlers.NewSNMPHandler(db) + snmpHandler := controller.NewSNMPHandler(db) snmpGroup := authorized.Group("/snmp") { snmpGroup.GET("/devices", snmpHandler.ListDevices) @@ -770,7 +833,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // Zabbix 代理 — 镜像 Zabbix API 为前端面板可用格式 // Logan.Li - zabbixHandler := handlers.NewZabbixProxyHandler() + zabbixHandler := controller.NewZabbixProxyHandler() zabbixGroup := authorized.Group("/zabbix") { zabbixGroup.POST("/connect", zabbixHandler.Connect) @@ -778,7 +841,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // Prometheus 代理 — 转发 PromQL 查询到 Prometheus 服务器 // Logan.Li - promHandler := handlers.NewPrometheusProxyHandler() + promHandler := controller.NewPrometheusProxyHandler() promGroup := authorized.Group("/prometheus") { promGroup.POST("/connect", promHandler.Connect) @@ -788,7 +851,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // Prometheus 数据源管理 — CRUD + 连接测试 // Logan.Li - promDSHandler := handlers.NewPromDSHandler(db) + promDSHandler := controller.NewPromDSHandler(db) promDSGroup := authorized.Group("/prometheus-datasources") { promDSGroup.GET("", promDSHandler.List) @@ -801,7 +864,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // Zabbix 数据源管理 — CRUD + 连接测试 // Logan.Li - zabbixDSHandler := handlers.NewZabbixDSHandler(db) + zabbixDSHandler := controller.NewZabbixDSHandler(db) zabbixDSGroup := authorized.Group("/zabbix-datasources") { zabbixDSGroup.GET("", zabbixDSHandler.List) @@ -814,22 +877,23 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 凭据管理 — SSH密钥/API Token/密码统一加密管理 // Logan.Li - credentialHandler := handlers.NewCredentialHandler(db, cfg.JWT.Secret) + credentialHandlerV2 := controller.NewCredentialHandlerV2(svcs.Credential) + credentialHandler := controller.NewCredentialHandler(db, cfg.JWT.Secret) // 仅用于 GetTags/PatchCredential/AssignCredential(待拆分) credGroup := authorized.Group("/credentials") { - credGroup.GET("", credentialHandler.ListCredentials) + credGroup.GET("", credentialHandlerV2.ListCredentials) credGroup.GET("/tags", credentialHandler.GetTags) - credGroup.POST("", credentialHandler.CreateCredential) - credGroup.GET("/:id", credentialHandler.GetCredential) - credGroup.PUT("/:id", credentialHandler.UpdateCredential) + credGroup.POST("", credentialHandlerV2.CreateCredential) + credGroup.GET("/:id", credentialHandlerV2.GetCredential) + credGroup.PUT("/:id", credentialHandlerV2.UpdateCredential) credGroup.PATCH("/:id", credentialHandler.PatchCredential) - credGroup.DELETE("/:id", credentialHandler.DeleteCredential) + credGroup.DELETE("/:id", credentialHandlerV2.DeleteCredential) } // 服务器凭据关联 // Logan.Li authorized.POST("/servers/:id/assign-credential", credentialHandler.AssignCredential) // 站点拨测 — HTTP/TCP/DNS/PING 主动监控 // Logan.Li - siteHandler := handlers.NewSiteHandler(db) + siteHandler := controller.NewSiteHandler(db) siteGroup := authorized.Group("/site") { siteGroup.GET("/tasks", siteHandler.ListTasks) @@ -842,7 +906,7 @@ func Register(r *gin.Engine, db *gorm.DB, log *zap.Logger, cfg *config.Config, c } // 启动告警引擎(每 30 秒检查一次) - alertEngine := handlers.NewAlertEngine(db) + alertEngine := controller.NewAlertEngine(db) go func() { ticker := time.NewTicker(30 * time.Second) defer ticker.Stop() diff --git a/backend/scripts/mock.go b/backend/scripts/mock.go index 1b78de8..56adc97 100644 --- a/backend/scripts/mock.go +++ b/backend/scripts/mock.go @@ -5,8 +5,8 @@ import ( "math/rand" "time" - "ezops/internal/config" - "ezops/internal/models" + "ezops/config" + "ezops/model" "ezops/pkg/database" "golang.org/x/crypto/bcrypt" @@ -77,7 +77,7 @@ func generateMockData(db *gorm.DB) error { } func generateUsers(db *gorm.DB) error { - users := []models.User{ + users := []model.User{ {Username: "admin", Email: "admin@ezops.local", RealName: "系统管理员", Phone: "13800138000", Status: 1, IsAdmin: true}, {Username: "ops01", Email: "ops01@ezops.local", RealName: "运维工程师1", Phone: "13800138001", Status: 1, IsAdmin: false}, {Username: "ops02", Email: "ops02@ezops.local", RealName: "运维工程师2", Phone: "13800138002", Status: 1, IsAdmin: false}, @@ -100,9 +100,9 @@ func generateServers(db *gorm.DB) error { osTypes := []string{"CentOS 7.9", "CentOS 8.5", "Ubuntu 20.04", "Ubuntu 22.04", "Debian 11", "Rocky Linux 8.6"} statuses := []string{"running", "stopped", "maintenance"} - servers := make([]models.Server, 0, 50) + servers := make([]model.Server, 0, 50) for i := 0; i < 50; i++ { - server := models.Server{ + server := model.Server{ Hostname: fmt.Sprintf("server-%03d", i+1), IP: fmt.Sprintf("10.0.%d.%d", rand.Intn(256), rand.Intn(256)), PublicIP: fmt.Sprintf("47.%d.%d.%d", rand.Intn(256), rand.Intn(256), rand.Intn(256)), @@ -127,7 +127,7 @@ func generateServers(db *gorm.DB) error { } func generateCloudAccounts(db *gorm.DB) error { - accounts := []models.CloudAccount{ + accounts := []model.CloudAccount{ {Name: "阿里云主账号", Provider: "aliyun", Status: "active", MonthlyCost: 28500}, {Name: "腾讯云主账号", Provider: "tencent", Status: "active", MonthlyCost: 15800}, {Name: "AWS 账号", Provider: "aws", Status: "active", MonthlyCost: 42000}, @@ -145,7 +145,7 @@ func generateCloudAccounts(db *gorm.DB) error { } func generateDomains(db *gorm.DB) error { - domains := []models.Domain{ + domains := []model.Domain{ {Name: "ezops.local", Registrar: "aliyun", Status: "active", DNSProvider: "alidns"}, {Name: "api.ezops.local", Registrar: "aliyun", Status: "active", DNSProvider: "alidns"}, {Name: "app.ezops.local", Registrar: "tencent", Status: "active", DNSProvider: "dnspod"}, @@ -165,7 +165,7 @@ func generateDomains(db *gorm.DB) error { } func generateKubernetesClusters(db *gorm.DB) error { - clusters := []models.KubernetesCluster{ + clusters := []model.KubernetesCluster{ {Name: "prod-cluster", Code: "prod", Version: "v1.28.0", Status: "healthy", NodeCount: 10, PodCount: 150, ServiceCount: 30, DeploymentCount: 15, APIEndpoint: "https://prod-api.ezops.local:6443", CPUUsage: 65.5, MemoryUsage: 72.3, Description: "生产环境 Kubernetes 集群"}, {Name: "staging-cluster", Code: "staging", Version: "v1.28.0", Status: "healthy", NodeCount: 5, PodCount: 80, ServiceCount: 15, DeploymentCount: 10, APIEndpoint: "https://staging-api.ezops.local:6443", CPUUsage: 45.2, MemoryUsage: 55.0, Description: "预发环境 Kubernetes 集群"}, {Name: "dev-cluster", Code: "dev", Version: "v1.27.0", Status: "warning", NodeCount: 3, PodCount: 45, ServiceCount: 8, DeploymentCount: 8, APIEndpoint: "https://dev-api.ezops.local:6443", CPUUsage: 80.1, MemoryUsage: 85.0, Description: "开发环境 Kubernetes 集群"}, @@ -179,7 +179,7 @@ func generateKubernetesClusters(db *gorm.DB) error { for _, cluster := range clusters { // 生成节点 for j := 0; j < cluster.NodeCount; j++ { - node := models.KubernetesNode{ + node := model.KubernetesNode{ ClusterID: cluster.ID, Name: fmt.Sprintf("%s-node-%d", cluster.Code, j+1), IP: fmt.Sprintf("192.168.%d.%d", rand.Intn(256), rand.Intn(256)), @@ -227,7 +227,7 @@ func generateKubernetesClusters(db *gorm.DB) error { if available < 0 { available = 0 } - dep := models.KubernetesDeployment{ + dep := model.KubernetesDeployment{ ClusterID: cluster.ID, Namespace: namespaces[rand.Intn(len(namespaces))], Name: depNames[d], @@ -253,7 +253,7 @@ func generateKubernetesClusters(db *gorm.DB) error { } for p := 0; p < numPods; p++ { status := podStatuses[rand.Intn(len(podStatuses))] - pod := models.KubernetesPod{ + pod := model.KubernetesPod{ ClusterID: cluster.ID, Namespace: namespaces[rand.Intn(len(namespaces))], Name: fmt.Sprintf("%s-pod-%d", cluster.Code, p+1), @@ -297,7 +297,7 @@ func generateKubernetesClusters(db *gorm.DB) error { default: ports = `[{"port":3306,"protocol":"TCP","targetPort":3306}]` } - svc := models.KubernetesService{ + svc := model.KubernetesService{ ClusterID: cluster.ID, Namespace: namespaces[rand.Intn(len(namespaces))], Name: svcNames[s], @@ -323,7 +323,7 @@ func generateKubernetesClusters(db *gorm.DB) error { numIngs := 2 + rand.Intn(3) for ig := 0; ig < numIngs && ig < len(ingNames); ig++ { hosts := fmt.Sprintf(`["%s.ezops.local"]`, ingNames[ig]) - ing := models.KubernetesIngress{ + ing := model.KubernetesIngress{ ClusterID: cluster.ID, Namespace: namespaces[rand.Intn(len(namespaces))], Name: ingNames[ig], @@ -341,7 +341,7 @@ func generateKubernetesClusters(db *gorm.DB) error { } func generateAlertRules(db *gorm.DB) error { - rules := []models.AlertRule{ + rules := []model.AlertRule{ {Name: "CPU 使用率告警", Type: "metric", Source: "prometheus", Expression: "cpu_usage > 80", Severity: "warning", Duration: 300, Enabled: true, Description: "CPU 使用率超过 80%"}, {Name: "CPU 使用率严重告警", Type: "metric", Source: "prometheus", Expression: "cpu_usage > 95", Severity: "critical", Duration: 120, Enabled: true, Description: "CPU 使用率超过 95%"}, {Name: "内存使用率告警", Type: "metric", Source: "prometheus", Expression: "memory_usage > 80", Severity: "warning", Duration: 300, Enabled: true, Description: "内存使用率超过 80%"}, @@ -356,7 +356,7 @@ func generateAlertRules(db *gorm.DB) error { } for i := 0; i < 20; i++ { rule := rules[rand.Intn(len(rules))] - event := models.AlertEvent{ + event := model.AlertEvent{ RuleID: rule.ID, RuleName: rule.Name, Severity: rule.Severity, @@ -375,7 +375,7 @@ func generateAlertRules(db *gorm.DB) error { } func generateNotifyChannels(db *gorm.DB) error { - channels := []models.NotifyChannel{ + channels := []model.NotifyChannel{ {Name: "运维邮件通知", Type: "email", Config: `{"recipients":["ops@ezops.com","admin@ezops.com"],"subject":"[AIOps告警]"}`, Enabled: true, TestStatus: "success"}, {Name: "短信通知", Type: "sms", Config: `{"phones":["13800138000","13900139000"],"template":"告警:{{alert_name}}"}`, Enabled: true, TestStatus: "success"}, {Name: "钉钉机器人", Type: "dingtalk", Config: `{"webhook":"https://oapi.dingtalk.com/robot/send?access_token=eZOps***","secret":"SEC***","at_all":false}`, Enabled: true, TestStatus: "success"}, @@ -392,7 +392,7 @@ func generateNotifyChannels(db *gorm.DB) error { } func generatePipelines(db *gorm.DB) error { - pipelines := []models.Pipeline{ + pipelines := []model.Pipeline{ {Name: "前端构建", Code: "frontend-build", Type: "build", Source: "https://gitlab.com/ezops/frontend", Branch: "main", Enabled: true, Description: "前端项目构建流水线"}, {Name: "后端构建", Code: "backend-build", Type: "build", Source: "https://gitlab.com/ezops/backend", Branch: "main", Enabled: true, Description: "后端项目构建流水线"}, {Name: "部署预发", Code: "deploy-staging", Type: "deploy", Source: "https://gitlab.com/ezops/deploy", Branch: "staging", Enabled: true, Description: "部署到预发环境"}, @@ -406,7 +406,7 @@ func generatePipelines(db *gorm.DB) error { } for _, pipeline := range pipelines { for j := 0; j < 5; j++ { - run := models.PipelineRun{ + run := model.PipelineRun{ PipelineID: pipeline.ID, BuildNumber: j + 1, Status: []string{"success", "success", "success", "failed", "running"}[rand.Intn(5)], @@ -431,7 +431,7 @@ func generateAppReleases(db *gorm.DB) error { statuses := []string{"pending", "building", "deploying", "success", "success", "success", "failed", "rolled_back"} authors := []string{"admin", "ops01", "dev01"} - releases := make([]models.AppRelease, 0, 10) + releases := make([]model.AppRelease, 0, 10) for i := 0; i < 10; i++ { app := apps[i%len(apps)] env := environments[rand.Intn(len(environments))] @@ -439,7 +439,7 @@ func generateAppReleases(db *gorm.DB) error { minor := rand.Intn(20) patch := rand.Intn(10) - release := models.AppRelease{ + release := model.AppRelease{ AppName: app, Version: fmt.Sprintf("v1.%d.%d", minor, patch), Environment: env, @@ -486,7 +486,7 @@ func generateAppReleases(db *gorm.DB) error { } func generateCronJobs(db *gorm.DB) error { - cronJobs := []models.CronJob{ + cronJobs := []model.CronJob{ {Name: "数据库备份", CronExpr: "0 2 * * *", Type: "script", Content: "/scripts/backup-db.sh", Enabled: true, Description: "每日凌晨 2 点备份数据库"}, {Name: "清理日志", CronExpr: "0 3 * * 0", Type: "command", Content: "find /var/log -mtime +30 -delete", Enabled: true, Description: "每周日凌晨 3 点清理日志"}, {Name: "数据同步", CronExpr: "*/30 * * * *", Type: "script", Content: "/scripts/sync-data.sh", Enabled: true, Description: "每 30 分钟同步数据"}, @@ -503,7 +503,7 @@ func generateCronJobs(db *gorm.DB) error { } func generateScripts(db *gorm.DB) error { - scripts := []models.Script{ + scripts := []model.Script{ {Name: "重启服务", Code: "restart-service", Type: "shell", Content: "#!/bin/bash\nsystemctl restart $1", Description: "重启服务脚本"}, {Name: "检查磁盘", Code: "check-disk", Type: "shell", Content: "#!/bin/bash\ndf -h", Description: "检查磁盘空间"}, {Name: "检查内存", Code: "check-memory", Type: "shell", Content: "#!/bin/bash\nfree -h", Description: "检查内存使用"}, @@ -520,7 +520,7 @@ func generateScripts(db *gorm.DB) error { } func generateApprovalTemplates(db *gorm.DB) error { - templates := []models.ApprovalTemplate{ + templates := []model.ApprovalTemplate{ {Name: "服务器申请审批", Code: "server-request", Type: "server", Enabled: true, Description: "服务器资源申请审批流程"}, {Name: "发布审批", Code: "release-approval", Type: "release", Enabled: true, Description: "应用发布审批流程"}, {Name: "权限申请审批", Code: "permission-request", Type: "permission", Enabled: true, Description: "系统权限申请审批流程"}, @@ -535,7 +535,7 @@ func generateApprovalTemplates(db *gorm.DB) error { } func generateNavigations(db *gorm.DB) error { - groups := []models.NavigationGroup{ + groups := []model.NavigationGroup{ {Name: "常用工具", Code: "tools", Icon: "Tool", Sort: 1, Enabled: true}, {Name: "监控平台", Code: "monitor", Icon: "Activity", Sort: 2, Enabled: true}, {Name: "开发工具", Code: "devtools", Icon: "Code", Sort: 3, Enabled: true}, @@ -546,7 +546,7 @@ func generateNavigations(db *gorm.DB) error { return err } } - links := []models.NavigationLink{ + links := []model.NavigationLink{ {GroupID: groups[0].ID, Name: "GitLab", URL: "https://gitlab.com", Icon: "GitBranch", Description: "代码仓库", Sort: 1}, {GroupID: groups[0].ID, Name: "Jenkins", URL: "https://jenkins.io", Icon: "Settings", Description: "CI/CD 工具", Sort: 2}, {GroupID: groups[0].ID, Name: "Nexus", URL: "https://www.sonatype.com/nexus-repository-oss", Icon: "Package", Description: "制品库", Sort: 3}, @@ -587,7 +587,7 @@ func generateBillings(db *gorm.DB) error { } now := time.Now() - var billings []models.CloudBilling + var billings []model.CloudBilling // 生成最近60天每天的账单 for day := 59; day >= 0; day-- { @@ -599,7 +599,7 @@ func generateBillings(db *gorm.DB) error { for i := 0; i < count; i++ { svc := svcs[rand.Intn(len(svcs))] cost := 50 + rand.Float64()*500 - billings = append(billings, models.CloudBilling{ + billings = append(billings, model.CloudBilling{ CloudAccountID: &acc.ID, AccountName: acc.Name, Provider: acc.Provider, @@ -621,7 +621,7 @@ func generateBillings(db *gorm.DB) error { fmt.Println("Generated cloud billings:", len(billings)) // 生成预警规则 - rules := []models.BillingAlertRule{ + rules := []model.BillingAlertRule{ {Name: "每日总成本超500元", Metric: "daily", Threshold: 500, Operator: ">", Enabled: true}, {Name: "阿里云日费用超300元", Provider: "aliyun", Metric: "daily", Threshold: 300, Operator: ">", Enabled: true}, {Name: "月度总成本超1万元", Metric: "monthly", Threshold: 10000, Operator: ">", Enabled: true}, diff --git a/backend/scripts/seed_kubernetes_resources.go b/backend/scripts/seed_kubernetes_resources.go index 0df544f..5f39391 100644 --- a/backend/scripts/seed_kubernetes_resources.go +++ b/backend/scripts/seed_kubernetes_resources.go @@ -9,8 +9,8 @@ import ( "math/rand" "time" - "ezops/internal/config" - "ezops/internal/models" + "ezops/config" + "ezops/model" "ezops/pkg/database" ) @@ -23,7 +23,7 @@ func main() { } rand.Seed(time.Now().UnixNano()) - var clusters []models.KubernetesCluster + var clusters []model.KubernetesCluster db.Find(&clusters) if len(clusters) == 0 { fmt.Println("No clusters found — run mock.go first") @@ -54,7 +54,7 @@ func main() { for _, cluster := range clusters { // Skip if pods already exist for this cluster var podCount int64 - db.Model(&models.KubernetesPod{}).Where("cluster_id = ?", cluster.ID).Count(&podCount) + db.Model(&model.KubernetesPod{}).Where("cluster_id = ?", cluster.ID).Count(&podCount) if podCount > 0 { fmt.Printf("Cluster %s already has %d pods, skipping\n", cluster.Name, podCount) continue @@ -79,7 +79,7 @@ func main() { if available < 0 { available = 0 } - db.Create(&models.KubernetesDeployment{ + db.Create(&model.KubernetesDeployment{ ClusterID: cluster.ID, Namespace: namespaces[rand.Intn(len(namespaces))], Name: depNames[d], @@ -94,7 +94,7 @@ func main() { // Pods numPods := 12 + rand.Intn(18) for p := 0; p < numPods; p++ { - db.Create(&models.KubernetesPod{ + db.Create(&model.KubernetesPod{ ClusterID: cluster.ID, Namespace: namespaces[rand.Intn(len(namespaces))], Name: fmt.Sprintf("%s-pod-%d", cluster.Code, p+1), @@ -126,7 +126,7 @@ func main() { default: ports = `[{"port":3306,"protocol":"TCP","targetPort":3306}]` } - svc := models.KubernetesService{ + svc := model.KubernetesService{ ClusterID: cluster.ID, Namespace: namespaces[rand.Intn(len(namespaces))], Name: svcNames[s], @@ -150,7 +150,7 @@ func main() { numIngs = len(ingNames) } for ig := 0; ig < numIngs; ig++ { - db.Create(&models.KubernetesIngress{ + db.Create(&model.KubernetesIngress{ ClusterID: cluster.ID, Namespace: namespaces[rand.Intn(len(namespaces))], Name: ingNames[ig], @@ -162,9 +162,9 @@ func main() { // Update cluster counts to match actual data var depCnt, podCnt, svcCnt int64 - db.Model(&models.KubernetesDeployment{}).Where("cluster_id = ?", cluster.ID).Count(&depCnt) - db.Model(&models.KubernetesPod{}).Where("cluster_id = ?", cluster.ID).Count(&podCnt) - db.Model(&models.KubernetesService{}).Where("cluster_id = ?", cluster.ID).Count(&svcCnt) + db.Model(&model.KubernetesDeployment{}).Where("cluster_id = ?", cluster.ID).Count(&depCnt) + db.Model(&model.KubernetesPod{}).Where("cluster_id = ?", cluster.ID).Count(&podCnt) + db.Model(&model.KubernetesService{}).Where("cluster_id = ?", cluster.ID).Count(&svcCnt) db.Model(&cluster).Updates(map[string]interface{}{ "deployment_count": depCnt, }) diff --git a/backend/cmd/seed.go b/backend/seed/seed.go similarity index 92% rename from backend/cmd/seed.go rename to backend/seed/seed.go index 768fdaa..8e85b63 100644 --- a/backend/cmd/seed.go +++ b/backend/seed/seed.go @@ -1,9 +1,9 @@ -package main +package seed import ( "strings" - "ezops/internal/models" + "ezops/model" "ezops/pkg/toolinstaller" @@ -13,13 +13,13 @@ import ( ) // seedData 初始化种子数据(admin用户 + LDAP配置 + 审批模板 + 权限角色) -func seedData(db *gorm.DB) { +func SeedData(db *gorm.DB) { // 1. 创建默认 admin 用户(仅首次) var userCount int64 - db.Model(&models.User{}).Count(&userCount) + db.Model(&model.User{}).Count(&userCount) if userCount == 0 { hashedPassword, _ := bcrypt.GenerateFromPassword([]byte("123456"), bcrypt.DefaultCost) - admin := models.User{ + admin := model.User{ Username: "admin", Password: string(hashedPassword), Email: "admin@ezops.local", @@ -37,13 +37,13 @@ func seedData(db *gorm.DB) { // 2. 创建默认 LDAP 配置 var ldapCount int64 - db.Model(&models.LDAPConfig{}).Count(&ldapCount) + db.Model(&model.LDAPConfig{}).Count(&ldapCount) if ldapCount == 0 { port := 389 useLDAPS := false searchFilter := "(objectClass=inetOrgPerson)" userMapping := `{"username":"uid","email":"mail","display_name":"cn"}` - ldapCfg := models.LDAPConfig{ + ldapCfg := model.LDAPConfig{ LDAPHost: "8.217.205.92", LDAPPort: &port, UseLDAPS: &useLDAPS, @@ -62,14 +62,15 @@ func seedData(db *gorm.DB) { // 3. 创建默认审批模板(资源申请) var tplCount int64 - db.Model(&models.ApprovalTemplate{}).Count(&tplCount) + db.Model(&model.ApprovalTemplate{}).Count(&tplCount) if tplCount == 0 { - templates := []models.ApprovalTemplate{ + templates := []model.ApprovalTemplate{ { Name: "云服务器申请", Code: "server_apply", Description: "申请云服务器资源(ECS/EC2),包含规格、数量、用途等信息", Type: "server_apply", + Category: "resource", FormSchema: `{ "fields": [ {"key": "provider", "label": "云厂商", "type": "select", "options": ["阿里云","腾讯云","华为云","AWS"], "required": true}, @@ -89,6 +90,7 @@ func seedData(db *gorm.DB) { Code: "app_deploy", Description: "申请新应用部署,包含 Git 地址、端口、Nacos 等配置信息", Type: "app_deploy", + Category: "app", FormSchema: `{ "fields": [ {"key": "app_name", "label": "应用名称", "type": "text", "placeholder": "如 user-service", "required": true}, @@ -106,20 +108,39 @@ func seedData(db *gorm.DB) { }`, FlowConfig: `[{"name":"技术负责人","approver_role":"tech_lead"},{"name":"运维负责人","approver_role":"ops_manager"}]`, Enabled: true, - }, + }, + { + Name: "权限申请", + Code: "permission_request", + Description: "申请堡垒机、生产VPN、日志查询、数据查询等运维权限", + Type: "permission_request", + Category: "permission", + FormSchema: `{ + "fields": [ + {"key": "perm_type", "label": "权限类型", "type": "select", "options": ["堡垒机权限","生产VPN权限","日志查询权限","数据库查询权限","服务器SSH权限","K8s集群权限"], "required": true}, + {"key": "target", "label": "目标资源", "type": "text", "placeholder": "如 生产环境服务器 10.10.10.x / k8s-prod 集群", "required": true}, + {"key": "account", "label": "申请账号", "type": "text", "placeholder": "如 logan.li", "required": true}, + {"key": "reason", "label": "申请理由", "type": "textarea", "placeholder": "说明为什么需要该权限", "required": true}, + {"key": "duration", "label": "权限时长", "type": "select", "options": ["临时(24小时)","短期(7天)","中期(30天)","长期(90天)","永久"], "required": true}, + {"key": "dept", "label": "所属部门", "type": "text", "placeholder": "如 基础架构部", "required": true} + ] + }`, + FlowConfig: `[{"name":"直接主管","approver_role":"team_lead"},{"name":"安全负责人","approver_role":"security_lead"}]`, + Enabled: true, + }, } if err := db.Create(&templates).Error; err != nil { zap.L().Warn("failed to seed approval templates", zap.Error(err)) } else { - zap.L().Info("seeded default approval templates (server_apply + app_deploy)") + zap.L().Info("seeded default approval templates (server_apply + app_deploy + permission_request)") } } // 4. 创建默认权限和角色权限映射 var permCount int64 - db.Model(&models.Permission{}).Count(&permCount) + db.Model(&model.Permission{}).Count(&permCount) if permCount == 0 { - perms := []models.Permission{ + perms := []model.Permission{ // 资产管理 {Name: "服务器管理", Code: "server:view", Type: "menu", Sort: 1, Status: 1}, {Name: "服务器创建", Code: "server:create", Type: "button", Sort: 2, Status: 1}, @@ -168,9 +189,9 @@ func seedData(db *gorm.DB) { // 5. 创建默认角色(如果不存在) var roleCount int64 - db.Model(&models.Role{}).Count(&roleCount) + db.Model(&model.Role{}).Count(&roleCount) if roleCount == 0 { - roles := []models.Role{ + roles := []model.Role{ {Name: "管理员", Code: "admin", Description: "系统管理员,拥有全部权限", Status: 1}, {Name: "运维工程师", Code: "ops", Description: "日常运维管理", Status: 1}, {Name: "开发工程师", Code: "developer", Description: "开发人员,只读权限", Status: 1}, @@ -180,7 +201,7 @@ func seedData(db *gorm.DB) { zap.L().Info("seeded default roles") // 为各角色分配权限 - var allPerms []models.Permission + var allPerms []model.Permission db.Find(&allPerms) for _, role := range roles { var permIds []uint @@ -216,7 +237,7 @@ func seedData(db *gorm.DB) { } } if len(permIds) > 0 { - var rolePerms []models.Permission + var rolePerms []model.Permission db.Where("id IN ?", permIds).Find(&rolePerms) db.Model(&role).Association("Permissions").Append(rolePerms) } @@ -225,9 +246,9 @@ func seedData(db *gorm.DB) { // 6. 创建默认 Ansible Playbook 模板(15 个高频运维场景)// Logan.Li var pbCount int64 - db.Model(&models.AnsiblePlaybook{}).Count(&pbCount) + db.Model(&model.AnsiblePlaybook{}).Count(&pbCount) if pbCount == 0 { - playbooks := []models.AnsiblePlaybook{ + playbooks := []model.AnsiblePlaybook{ {Name: "系统信息收集", Description: "收集主机基本信息:OS、内核、CPU、内存、磁盘、网络接口", Category: "maintenance", Tags: `["系统信息","诊断","基础"]`, Content: `--- - name: 系统信息收集 hosts: all diff --git a/backend/service/service.go b/backend/service/service.go new file mode 100644 index 0000000..7cee482 --- /dev/null +++ b/backend/service/service.go @@ -0,0 +1,539 @@ +// Package service 提供业务逻辑层 — 编排 repository、处理加密/校验/转换 +// Handler 不直接调用 repository,通过 service 调用 +package service + +import ( + "encoding/json" + "fmt" + "math" + + "ezops/dto" + "ezops/model" + "ezops/repository" + "ezops/pkg/crypto" + ezredis "ezops/pkg/redis" + + "gorm.io/gorm" +) + +// ━━━ Server Service ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +type ServerService struct { + repo *repository.ServerRepository + cache ezredis.Cache + crypt *crypto.SecretBox +} + +func NewServerService(repo *repository.ServerRepository, cache ezredis.Cache, crypt *crypto.SecretBox) *ServerService { + return &ServerService{repo: repo, cache: cache, crypt: crypt} +} + +// ListServers 获取服务器列表 +func (s *ServerService) ListServers(keyword, status, regionID string, page, pageSize int) ([]model.Server, int64, error) { + list, total, err := s.repo.List(keyword, status, regionID, page, pageSize) + if err != nil { + return nil, 0, err + } + // 填充计算字段 + for i := range list { + list[i].HasAuth = list[i].Password != "" || list[i].SSHKey != "" + } + return list, total, nil +} + +// GetServer 获取服务器详情 +func (s *ServerService) GetServer(id uint) (*model.Server, error) { + server, err := s.repo.GetByID(id) + if err != nil { + return nil, err + } + server.HasAuth = server.Password != "" || server.SSHKey != "" + return server, nil +} + +// CreateServer 创建服务器 — 加密凭证 +func (s *ServerService) CreateServer(req *dto.CreateServerRequest) (*model.Server, error) { + srv := &model.Server{ + Hostname: req.Hostname, + IP: req.IP, + PublicIP: req.PublicIP, + Port: req.Port, + Username: req.Username, + AuthType: req.AuthType, + OS: req.OS, + OSVersion: req.OSVersion, + Arch: req.Arch, + CPU: req.CPU, + Memory: req.Memory, + Disk: req.Disk, + RegionID: req.RegionID, + CloudID: req.CloudID, + Tags: req.Tags, + Description: req.Description, + } + if req.Port == 0 { + srv.Port = 22 + } + if req.Username == "" { + srv.Username = "root" + } + if req.AuthType == "" { + srv.AuthType = "password" + } + + // 加密密码和 SSH 密钥 + if req.Password != "" { + enc, err := s.crypt.Encrypt(req.Password) + if err != nil { + return nil, fmt.Errorf("加密密码失败: %w", err) + } + srv.Password = enc + } + if req.SSHKey != "" { + enc, err := s.crypt.Encrypt(req.SSHKey) + if err != nil { + return nil, fmt.Errorf("加密 SSH 密钥失败: %w", err) + } + srv.SSHKey = enc + } + + if err := s.repo.Create(srv); err != nil { + return nil, err + } + return srv, nil +} + +// UpdateServer 部分更新服务器 +func (s *ServerService) UpdateServer(id uint, req *dto.UpdateServerRequest) error { + updates := make(map[string]interface{}) + + if req.Hostname != nil { + updates["hostname"] = *req.Hostname + } + if req.IP != nil { + updates["ip"] = *req.IP + } + if req.PublicIP != nil { + updates["public_ip"] = *req.PublicIP + } + if req.Port != nil { + updates["port"] = *req.Port + } + if req.Username != nil { + updates["username"] = *req.Username + } + if req.AuthType != nil { + updates["auth_type"] = *req.AuthType + } + if req.OS != nil { + updates["os"] = *req.OS + } + if req.OSVersion != nil { + updates["os_version"] = *req.OSVersion + } + if req.Arch != nil { + updates["arch"] = *req.Arch + } + if req.CPU != nil { + updates["cpu"] = *req.CPU + } + if req.Memory != nil { + updates["memory"] = *req.Memory + } + if req.Disk != nil { + updates["disk"] = *req.Disk + } + if req.Status != nil { + updates["status"] = *req.Status + } + if req.RegionID != nil { + updates["region_id"] = *req.RegionID + } + if req.CloudID != nil { + updates["cloud_id"] = *req.CloudID + } + if req.Tags != nil { + updates["tags"] = *req.Tags + } + if req.Description != nil { + updates["description"] = *req.Description + } + + // 加密凭据字段 + if req.Password != nil && *req.Password != "" { + enc, err := s.crypt.Encrypt(*req.Password) + if err != nil { + return fmt.Errorf("加密密码失败: %w", err) + } + updates["password"] = enc + } + if req.SSHKey != nil && *req.SSHKey != "" { + enc, err := s.crypt.Encrypt(*req.SSHKey) + if err != nil { + return fmt.Errorf("加密 SSH 密钥失败: %w", err) + } + updates["ssh_key"] = enc + } + + if len(updates) == 0 { + return nil + } + return s.repo.UpdateFields(id, updates) +} + +// DeleteServer 删除服务器 +func (s *ServerService) DeleteServer(id uint) error { + return s.repo.Delete(id) +} + +// GetDashboardStats 获取仪表盘统计 +func (s *ServerService) GetDashboardStats() (*model.DashboardStats, error) { + var stats model.DashboardStats + + stats.ServerStats.Total = s.repo.CountByStatus("") + stats.ServerStats.Running = s.repo.CountByStatus("running") + stats.ServerStats.Stopped = s.repo.CountByStatus("stopped") + stats.ServerStats.Maintenance = s.repo.CountByStatus("maintenance") + stats.ServerStats.Error = s.repo.CountByStatus("error") + + stats.ServerStats.AvgCPU = math.Round(s.repo.AvgMetric("cpu_usage")*100) / 100 + stats.ServerStats.AvgMemory = math.Round(s.repo.AvgMetric("memory_usage")*100) / 100 + stats.ServerStats.AvgDisk = math.Round(s.repo.AvgMetric("disk_usage")*100) / 100 + + return &stats, nil +} + +// ━━━ Credential Service ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +type CredentialService struct { + repo *repository.CredentialRepository + crypt *crypto.SecretBox +} + +func NewCredentialService(repo *repository.CredentialRepository, crypt *crypto.SecretBox) *CredentialService { + return &CredentialService{repo: repo, crypt: crypt} +} + +// List 分页查询 +func (s *CredentialService) List(keyword, secretType string, page, pageSize int) ([]model.Credential, int64, error) { + return s.repo.List(keyword, secretType, page, pageSize) +} + +// GetByID 获取详情 +func (s *CredentialService) GetByID(id uint) (*model.Credential, error) { + return s.repo.GetByID(id) +} + +// buildCredentialContent 根据请求构建加密内容 +func (s *CredentialService) buildCredentialContent(req *dto.CreateCredentialRequest) (string, string, error) { + switch req.SecretType { + case "ssh": + data := map[string]interface{}{ + "private_key": req.SSHPrivateKey, + "public_key": req.SSHPublicKey, + "ssh_user": req.SSHUser, + "ssh_port": req.SSHPort, + "password": req.SSHPassword, + } + b, _ := json.Marshal(data) + return string(b), fmt.Sprintf("SSH %s@%d", req.SSHUser, req.SSHPort), nil + case "docker": + data := map[string]string{ + "server": req.DockerServer, + "username": req.DockerUsername, + "password": req.DockerPassword, + } + b, _ := json.Marshal(data) + return string(b), req.DockerServer, nil + case "tls": + data := map[string]string{"cert": req.TLSCert, "key": req.TLSKey, "ca": req.TLSCA} + b, _ := json.Marshal(data) + return string(b), "TLS 证书已配置", nil + case "password": + return req.PlainPassword, "密码", nil + case "env": + return req.EnvVars, "环境变量", nil + default: + return "", "", fmt.Errorf("不支持的凭据类型: %s", req.SecretType) + } +} + +// Create 创建凭据 +func (s *CredentialService) Create(req *dto.CreateCredentialRequest) (*model.Credential, error) { + content, usage, err := s.buildCredentialContent(req) + if err != nil { + return nil, err + } + + encContent, err := s.crypt.Encrypt(content) + if err != nil { + return nil, fmt.Errorf("加密失败: %w", err) + } + + cred := &model.Credential{ + Name: req.Name, + SecretType: req.SecretType, + Content: encContent, + Summary: usage, + Description: req.Description, + } + if err := s.repo.Create(cred); err != nil { + return nil, err + } + return cred, nil +} + +// buildUpdateContent 构建更新凭据的加密内容 +func (s *CredentialService) buildUpdateContent(req *dto.UpdateCredentialRequest, existingSecretType string) (string, string, error) { + st := existingSecretType + switch st { + case "ssh": + data := map[string]interface{}{} + if req.SSHPrivateKey != nil { + data["private_key"] = *req.SSHPrivateKey + } + if req.SSHPublicKey != nil { + data["public_key"] = *req.SSHPublicKey + } + if req.SSHUser != nil { + data["ssh_user"] = *req.SSHUser + } + if req.SSHPort != nil { + data["ssh_port"] = *req.SSHPort + } + if req.SSHPassword != nil { + data["password"] = *req.SSHPassword + } + if len(data) == 0 { + return "", "", nil + } + b, _ := json.Marshal(data) + return string(b), "", nil + case "docker": + data := map[string]string{} + if req.DockerServer != nil { + data["server"] = *req.DockerServer + } + if req.DockerUsername != nil { + data["username"] = *req.DockerUsername + } + if req.DockerPassword != nil { + data["password"] = *req.DockerPassword + } + b, _ := json.Marshal(data) + return string(b), "", nil + case "tls": + data := map[string]string{} + if req.TLSCert != nil { + data["cert"] = *req.TLSCert + } + if req.TLSKey != nil { + data["key"] = *req.TLSKey + } + if req.TLSCA != nil { + data["ca"] = *req.TLSCA + } + b, _ := json.Marshal(data) + return string(b), "", nil + case "password": + if req.PlainPassword != nil { + return *req.PlainPassword, "", nil + } + return "", "", nil + case "env": + if req.EnvVars != nil { + return *req.EnvVars, "", nil + } + return "", "", nil + } + return "", "", nil +} + +// Update 更新凭据 +func (s *CredentialService) Update(id uint, req *dto.UpdateCredentialRequest) error { + existing, err := s.repo.GetByID(id) + if err != nil { + return err + } + + content, _, err := s.buildUpdateContent(req, existing.SecretType) + if err != nil { + return err + } + + updates := make(map[string]interface{}) + if req.Name != nil { + updates["name"] = *req.Name + } + if req.Description != nil { + updates["description"] = *req.Description + } + if content != "" { + enc, err := s.crypt.Encrypt(content) + if err != nil { + return fmt.Errorf("加密失败: %w", err) + } + updates["secret_data"] = enc + } + + if len(updates) == 0 { + return nil + } + return s.repo.UpdateFields(id, updates) +} + +// Delete 删除凭据 +func (s *CredentialService) Delete(id uint) error { + return s.repo.Delete(id) +} + +// ━━━ Alert Service ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ + +type AlertContactService struct { + repo *repository.AlertContactRepository +} + +func NewAlertContactService(repo *repository.AlertContactRepository) *AlertContactService { + return &AlertContactService{repo: repo} +} + +func (s *AlertContactService) List(keyword string, page, pageSize int) ([]model.AlertContact, int64, error) { + return s.repo.List(keyword, page, pageSize) +} + +func (s *AlertContactService) GetByID(id uint) (*model.AlertContact, error) { + return s.repo.GetByID(id) +} + +func (s *AlertContactService) Create(req *dto.CreateAlertContactRequest) (*model.AlertContact, error) { + c := &model.AlertContact{ + Name: req.Name, + ChannelType: req.ChannelType, + WebhookURL: req.WebhookURL, + Phone: req.Phone, + Email: req.Email, + } + if err := s.repo.Create(c); err != nil { + return nil, err + } + return c, nil +} + +func (s *AlertContactService) Update(id uint, req *dto.UpdateAlertContactRequest) error { + updates := make(map[string]interface{}) + if req.Name != nil { + updates["name"] = *req.Name + } + if req.ChannelType != nil { + updates["channel_type"] = *req.ChannelType + } + if req.WebhookURL != nil { + updates["webhook_url"] = *req.WebhookURL + } + if req.Phone != nil { + updates["phone"] = *req.Phone + } + if req.Email != nil { + updates["email"] = *req.Email + } + if len(updates) == 0 { + return nil + } + // AlertContact 没有 UpdateFields,直接 Save + c, err := s.repo.GetByID(id) + if err != nil { + return err + } + if req.Name != nil { + c.Name = *req.Name + } + if req.ChannelType != nil { + c.ChannelType = *req.ChannelType + } + if req.WebhookURL != nil { + c.WebhookURL = *req.WebhookURL + } + if req.Phone != nil { + c.Phone = *req.Phone + } + if req.Email != nil { + c.Email = *req.Email + } + return s.repo.Update(c) +} + +func (s *AlertContactService) Delete(id uint) error { + return s.repo.Delete(id) +} + +// AlertContactGroup Service +type AlertContactGroupService struct { + repo *repository.AlertContactGroupRepository +} + +func NewAlertContactGroupService(repo *repository.AlertContactGroupRepository) *AlertContactGroupService { + return &AlertContactGroupService{repo: repo} +} + +func (s *AlertContactGroupService) List(keyword string, page, pageSize int) ([]model.AlertContactGroup, int64, error) { + return s.repo.List(keyword, page, pageSize) +} + +func (s *AlertContactGroupService) GetByID(id uint) (*model.AlertContactGroup, error) { + return s.repo.GetByID(id) +} + +func (s *AlertContactGroupService) Create(req *dto.CreateAlertContactGroupRequest) (*model.AlertContactGroup, error) { + g := &model.AlertContactGroup{GroupName: req.Name} + if len(req.ContactIDs) > 0 { + g.ContactIDs = toJSONString(req.ContactIDs) + } + if err := s.repo.Create(g); err != nil { + return nil, err + } + return g, nil +} + +func (s *AlertContactGroupService) Update(id uint, req *dto.UpdateAlertContactGroupRequest) error { + updates := make(map[string]interface{}) + if req.Name != nil { + updates["group_name"] = *req.Name + } + if req.ContactIDs != nil { + updates["contact_ids"] = toJSONString(*req.ContactIDs) + } + if len(updates) == 0 { + return nil + } + return s.repo.UpdateFields(id, updates) +} + +func (s *AlertContactGroupService) Delete(id uint) error { + return s.repo.Delete(id) +} + +func toJSONString(v interface{}) string { + b, _ := json.Marshal(v) + return string(b) +} + +// ━━━ Config Helper — 管理所有 Service 的依赖注入 ━━━━ + +type Services struct { + Server *ServerService + Credential *CredentialService + AlertContact *AlertContactService + AlertContactGroup *AlertContactGroupService +} + +// NewServices 初始化所有服务 +func NewServices(db *gorm.DB, cache ezredis.Cache, masterKey string) *Services { + crypt := crypto.NewSecretBox(masterKey) + + return &Services{ + Server: NewServerService(repository.NewServerRepository(db), cache, crypt), + Credential: NewCredentialService(repository.NewCredentialRepository(db), crypt), + AlertContact: NewAlertContactService(repository.NewAlertContactRepository(db)), + AlertContactGroup: NewAlertContactGroupService(repository.NewAlertContactGroupRepository(db)), + } +} diff --git a/backend/static/assets/AIAlertAnalyzer-B9ptAIV7.js b/backend/static/assets/AIAlertAnalyzer-B9ptAIV7.js new file mode 100644 index 0000000..0a9eac3 --- /dev/null +++ b/backend/static/assets/AIAlertAnalyzer-B9ptAIV7.js @@ -0,0 +1,57 @@ +import{j as s,a2 as b,aJ as f,L as v,$ as w,a3 as g,H as C,B as A,r as l,D as O,b as U,c as J,d as B,e as E,a9 as L,T as R,q as G,x as H}from"./index-DfyorCky.js";import{C as z,b as $,c as D,a as F}from"./card-C55cvSHg.js";import{B as y}from"./badge-xNW8x0G1.js";import{a as K}from"./monitor-BAaBXIsC.js";import{a as q}from"./ai-BTgmlP5Q.js";import{S}from"./sparkles-Bld4NX5y.js";import{T as P}from"./trending-up-CdusV6gc.js";import{F as X}from"./file-text-C9G5abwR.js";import{P as _}from"./play-cdPayOtJ.js";import{C as Q}from"./copy-DXW4LnkN.js";import{C as W}from"./circle-x-DK79Dhg2.js";function Y(e){const c=(e.metric||"").toLowerCase(),t=e.source||"目标主机",a=e.severity==="critical";return c.includes("cpu")?{rootCause:`检测到 ${t} 上 CPU 使用率达到 ${e.currentValue},持续超过阈值 ${e.threshold}。可能原因:1) 某进程存在死循环或高计算负载;2) GC 频繁触发(Java/Go 应用);3) 业务流量突增导致处理能力不足。`,impact:a?"CPU 持续高负载将导致服务响应延迟显著增加,严重时可能触发雪崩效应,影响全部依赖该节点的业务。":"CPU 使用率偏高,可能导致部分请求处理变慢,建议及时排查避免进一步恶化。",recommendations:[`登录 ${t} 执行 top/htop 定位高 CPU 进程`,"检查是否有异常定时任务或批处理任务在运行","考虑临时扩容或将部分流量调度到其他节点","优化应用代码,排查是否存在低效算法或资源泄漏"],autoFixScript:`#!/bin/bash +# CPU 高负载诊断脚本 - ${t} +echo "===== CPU TOP 10 进程 =====" +ps aux --sort=-%cpu | head -11 +echo "" +echo "===== 系统负载 =====" +uptime +echo "" +echo "===== 高 CPU 进程详情 =====" +PID=$(ps aux --sort=-%cpu | sed -n '2p' | awk '{print $2}') +if [ -n "$PID" ]; then + echo "最高 CPU 进程: PID=$PID" + cat /proc/$PID/cmdline | tr '\\0' ' ' + echo "" +fi +`,similarCases:0,confidence:0}:c.includes("mem")||c.includes("ram")?{rootCause:`检测到 ${t} 内存使用率达到 ${e.currentValue},接近或超过阈值 ${e.threshold}。常见原因:1) 应用内存泄漏,对象未被正确释放;2) 缓存配置过大;3) 数据库连接池未及时释放。`,impact:a?"内存即将耗尽可能触发 OOM Killer,导致关键进程被强制终止,服务中断风险极高。":"内存持续增长,长期可能导致 OOM,建议尽快排查内存使用情况。",recommendations:[`检查 ${t} 上的内存占用最高的进程`,"如果是 Java 应用,检查 JVM 堆内存配置和 GC 日志","排查是否存在内存泄漏,必要时生成堆转储分析","调整缓存大小限制或增加交换分区"],similarCases:0,confidence:0}:c.includes("disk")||c.includes("space")?{rootCause:`检测到 ${t} 磁盘使用率达到 ${e.currentValue},超过阈值 ${e.threshold}。最常见原因:1) 日志文件未配置轮转/清理;2) 临时文件堆积;3) 数据库数据文件膨胀。`,impact:a?"磁盘空间不足可能导致服务无法写入数据/日志,数据库可能崩溃,文件系统变只读,影响范围极大。":"磁盘空间告警,如不及时清理可能导致服务异常。",recommendations:[`清理 ${t} 上 30 天前的日志文件`,"检查并清理临时目录 /tmp、/var/tmp","配置 logrotate 日志轮转策略","考虑扩容磁盘或将数据迁移到对象存储"],autoFixScript:`#!/bin/bash +# 磁盘清理脚本 - ${t} +echo "===== 清理前磁盘使用 =====" +df -h / +echo "" +echo "===== 清理 30 天前日志 =====" +find /var/log -name "*.log" -mtime +30 -delete 2>/dev/null +find /var/log -name "*.gz" -mtime +30 -delete 2>/dev/null +echo "" +echo "===== 清理系统缓存 =====" +journalctl --vacuum-time=7d 2>/dev/null +echo "" +echo "===== 清理后磁盘使用 =====" +df -h / +`,similarCases:0,confidence:0}:c.includes("net")||c.includes("latency")||c.includes("bandwidth")?{rootCause:`检测到 ${t} 网络指标异常(当前值 ${e.currentValue}),可能原因:1) 上游依赖服务响应变慢;2) 网络带宽打满;3) DNS 解析延迟;4) 连接数达到上限。`,impact:a?"网络异常将导致所有经过该节点的请求超时,影响所有上游业务的可用性。":"网络延迟偏高,可能影响用户体验,建议排查网络链路。",recommendations:[`检查 ${t} 的网络连接和带宽使用情况`,"排查上游依赖服务的健康状态和响应时间","检查防火墙规则是否有限速或异常丢弃","考虑启用熔断/降级机制保障核心链路"],similarCases:0,confidence:0}:c.includes("service")||c.includes("up")||c.includes("avail")?{rootCause:`检测到 ${t} 服务不可用(指标 ${e.metric} = ${e.currentValue})。可能原因:1) 进程崩溃或被 OOM Killer 终止;2) 端口被占用或监听异常;3) 健康检查端点返回错误;4) 配置文件错误导致启动失败。`,impact:a?"服务完全不可用,所有依赖该服务的业务功能将中断,需要立即处理。":"服务可用性下降,部分功能可能受影响。",recommendations:[`立即检查 ${t} 的服务状态: systemctl status `,"查看服务日志排查崩溃原因","检查端口占用和监听状态: ss -tlnp","必要时重启服务并监控恢复情况"],autoFixScript:`#!/bin/bash +# 服务恢复脚本 - ${t} +echo "===== 检查服务状态 =====" +systemctl list-units --state=failed +echo "" +echo "===== 检查端口监听 =====" +ss -tlnp | grep -E ':(80|443|8080|3306|6379|9090)' +echo "" +echo "===== 重启失败服务 =====" +systemctl reset-failed +`,similarCases:0,confidence:0}:{rootCause:`检测到 ${t} 触发告警「${e.name}」,当前指标值 ${e.currentValue} 超过阈值 ${e.threshold}。建议进一步排查具体指标数据和相关日志以确定根因。`,impact:a?"该告警级别为严重,可能影响业务正常运行,建议优先处理。":"该告警需要关注,持续恶化可能影响系统稳定性。",recommendations:[`查看 ${t} 的监控仪表盘,确认指标趋势`,"检查对应时间段的系统日志和应用日志","关联同时间段的其他告警,排查是否有连锁反应","若确认误报,调整告警规则阈值或持续时间"],similarCases:0,confidence:0}}function Z(e){const c=e.rule?.expression||"",t=c.match(/([\w_]+)\s*[><=!]+\s*([\d.]+)/),a=t?t[1]:c||"unknown",n=t?t[2]+"%":"-",r=e.value??0,d=a.includes("usage")||a.includes("cpu")||a.includes("disk")||a.includes("mem")?r.toFixed(1)+"%":r.toFixed(2),x=e.resolved_at?new Date(e.resolved_at):new Date,i=new Date(e.started_at),p=Math.max(1,Math.round((x.getTime()-i.getTime())/6e4)),h=p>=60?`${Math.floor(p/60)}小时${p%60}分钟`:`${p}分钟`,u=i.toLocaleString("zh-CN",{hour12:!1});return{id:String(e.id),name:e.rule_name||e.rule?.name||"未知告警",severity:e.severity==="critical"?"critical":e.severity==="warning"?"warning":"info",status:e.status==="firing"?"active":"resolved",source:e.target||"未知目标",metric:a,threshold:n,currentValue:d,duration:h,startedAt:u,description:e.message&&e.message!==`告警事件 ${e.id}`?e.message:e.rule?.description||`${e.rule_name||"告警"}: ${e.target} 当前值 ${d}`}}function ss(e){switch(e){case"critical":return"bg-red-500/10 text-red-400 border-red-500/30";case"warning":return"bg-amber-500/10 text-amber-400 border-amber-500/30";default:return"bg-blue-500/10 text-blue-400 border-blue-500/30"}}function es({selectedAlert:e,isAnalyzing:c,analysis:t,onAutoFix:a}){return s.jsxs(z,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:18:5",className:"bg-slate-800 border-slate-700 flex flex-col",children:[s.jsx($,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:19:7",className:"border-b border-slate-700 pb-3",children:s.jsxs(D,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:20:9",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(S,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:21:11",className:"h-5 w-5 text-purple-400"}),"AI 分析结果"]})}),s.jsx(b,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:25:7",className:"flex-1",children:s.jsx(F,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:26:9",className:"p-4",children:e?c?s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:33:13",className:"flex flex-col items-center justify-center h-64",children:[s.jsx(v,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:34:15",className:"h-8 w-8 animate-spin text-purple-400 mb-4"}),s.jsx("p",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:35:15",className:"text-slate-400",children:"AI正在分析告警根因..."}),s.jsx("p",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:36:15",className:"text-xs text-slate-500 mt-2",children:"正在关联日志、指标和历史案例"})]}):t?s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:39:13",className:"space-y-4",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:41:15",className:"flex items-center justify-between p-3 bg-purple-500/10 rounded-lg border border-purple-500/30",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:42:17",className:"flex items-center gap-2",children:[s.jsx(f,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:43:19",className:"h-5 w-5 text-purple-400"}),s.jsx("span",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:44:19",className:"text-slate-300",children:"分析置信度"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:46:17",className:"flex items-center gap-2",children:[s.jsx("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:47:19",className:"w-32 h-2 bg-slate-700 rounded-full overflow-hidden",children:s.jsx("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:48:21",className:"h-full bg-gradient-to-r from-purple-500 to-pink-500",style:{width:`${t.confidence}%`}})}),s.jsxs("span",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:53:19",className:"text-purple-400 font-bold",children:[t.confidence,"%"]})]})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:58:15",className:"space-y-2",children:[s.jsxs("h4",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:59:17",className:"text-sm font-medium text-slate-300 flex items-center gap-2",children:[s.jsx(w,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:60:19",className:"h-4 w-4 text-red-400"}),"根因分析"]}),s.jsx("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:63:17",className:"p-3 bg-slate-900 rounded-lg border border-slate-700",children:s.jsx("p",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:64:19",className:"text-sm text-slate-300 leading-relaxed",children:t.rootCause})})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:69:15",className:"space-y-2",children:[s.jsxs("h4",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:70:17",className:"text-sm font-medium text-slate-300 flex items-center gap-2",children:[s.jsx(P,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:71:19",className:"h-4 w-4 text-amber-400"}),"影响范围"]}),s.jsx("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:74:17",className:"p-3 bg-slate-900 rounded-lg border border-slate-700",children:s.jsx("p",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:75:19",className:"text-sm text-slate-300 leading-relaxed",children:t.impact})})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:80:15",className:"space-y-2",children:[s.jsxs("h4",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:81:17",className:"text-sm font-medium text-slate-300 flex items-center gap-2",children:[s.jsx(g,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:82:19",className:"h-4 w-4 text-emerald-400"}),"修复建议"]}),s.jsx("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:85:17",className:"space-y-2",children:t.recommendations.map((n,r)=>s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:87:21",className:"flex items-start gap-2 p-2 bg-slate-900 rounded-lg border border-slate-700",children:[s.jsx("span",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:91:23",className:"flex-shrink-0 w-5 h-5 rounded-full bg-emerald-500/20 text-emerald-400 flex items-center justify-center text-xs",children:r+1}),s.jsx("span",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:94:23",className:"text-sm text-slate-300",children:n})]},r))})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:101:15",className:"flex items-center gap-2 p-3 bg-slate-900 rounded-lg border border-slate-700",children:[s.jsx(X,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:102:17",className:"h-4 w-4 text-blue-400"}),s.jsxs("span",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:103:17",className:"text-sm text-slate-400",children:["发现 ",s.jsx("span",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:104:22",className:"text-blue-400 font-medium",children:t.similarCases})," 个相似历史案例"]})]}),t.autoFixScript&&s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:110:17",className:"space-y-2",children:[s.jsxs("h4",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:111:19",className:"text-sm font-medium text-slate-300 flex items-center gap-2",children:[s.jsx(C,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:112:21",className:"h-4 w-4 text-purple-400"}),"自动修复脚本"]}),s.jsx("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:115:19",className:"p-3 bg-slate-950 rounded-lg border border-slate-700",children:s.jsx("pre",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:116:21",className:"text-xs text-slate-400 overflow-x-auto",children:t.autoFixScript})}),s.jsxs(A,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:118:19",className:"w-full bg-purple-600 hover:bg-purple-700",onClick:a,children:[s.jsx(_,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:122:21",className:"h-4 w-4 mr-2"}),"执行自动修复"]})]})]}):null:s.jsxs("div",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:28:13",className:"flex flex-col items-center justify-center h-64 text-slate-500",children:[s.jsx(f,{"code-path":"src/components/aiops/AIAnalysisResult.tsx:29:15",className:"h-16 w-16 mb-4 opacity-30"}),s.jsx("p",{"code-path":"src/components/aiops/AIAnalysisResult.tsx:30:15",children:"选择左侧告警进行AI智能分析"})]})})})]})}function ts({open:e,onOpenChange:c,script:t}){const[a,n]=l.useState(!1),r=()=>{t&&(navigator.clipboard.writeText(t),n(!0),setTimeout(()=>n(!1),2e3))};return s.jsx(O,{"code-path":"src/components/aiops/AutoFixDialog.tsx:31:5",open:e,onOpenChange:c,children:s.jsxs(U,{"code-path":"src/components/aiops/AutoFixDialog.tsx:32:7",className:"max-w-2xl bg-slate-900 border-slate-700 text-slate-100",children:[s.jsxs(J,{"code-path":"src/components/aiops/AutoFixDialog.tsx:33:9",children:[s.jsxs(B,{"code-path":"src/components/aiops/AutoFixDialog.tsx:34:11",className:"flex items-center gap-2",children:[s.jsx(C,{"code-path":"src/components/aiops/AutoFixDialog.tsx:35:13",className:"h-5 w-5 text-purple-400"}),"自动修复脚本"]}),s.jsx(E,{"code-path":"src/components/aiops/AutoFixDialog.tsx:38:11",className:"text-slate-500",children:"AI生成的自动修复脚本,请确认后执行"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AutoFixDialog.tsx:42:9",className:"space-y-4 py-4",children:[s.jsxs("div",{"code-path":"src/components/aiops/AutoFixDialog.tsx:43:11",className:"p-4 bg-slate-950 rounded-lg border border-slate-700",children:[s.jsxs("div",{"code-path":"src/components/aiops/AutoFixDialog.tsx:44:13",className:"flex items-center justify-between mb-2",children:[s.jsx("span",{"code-path":"src/components/aiops/AutoFixDialog.tsx:45:15",className:"text-sm text-slate-400",children:"修复脚本"}),s.jsx(A,{"code-path":"src/components/aiops/AutoFixDialog.tsx:46:15",variant:"ghost",size:"sm",onClick:r,className:"text-slate-400",children:a?s.jsx(L,{"code-path":"src/components/aiops/AutoFixDialog.tsx:47:27",className:"h-4 w-4"}):s.jsx(Q,{"code-path":"src/components/aiops/AutoFixDialog.tsx:47:59",className:"h-4 w-4"})})]}),s.jsx("pre",{"code-path":"src/components/aiops/AutoFixDialog.tsx:50:13",className:"text-sm text-slate-300 overflow-x-auto whitespace-pre-wrap",children:t})]}),s.jsxs("div",{"code-path":"src/components/aiops/AutoFixDialog.tsx:54:11",className:"flex items-center gap-2 p-3 bg-amber-500/10 rounded-lg border border-amber-500/30",children:[s.jsx(R,{"code-path":"src/components/aiops/AutoFixDialog.tsx:55:13",className:"h-4 w-4 text-amber-400"}),s.jsx("span",{"code-path":"src/components/aiops/AutoFixDialog.tsx:56:13",className:"text-sm text-amber-400",children:"警告:执行脚本前请确保已备份重要数据"})]})]}),s.jsxs("div",{"code-path":"src/components/aiops/AutoFixDialog.tsx:61:9",className:"flex gap-2",children:[s.jsx(A,{"code-path":"src/components/aiops/AutoFixDialog.tsx:62:11",variant:"outline",className:"flex-1 border-slate-700 text-slate-300",onClick:()=>c(!1),children:"取消"}),s.jsxs(A,{"code-path":"src/components/aiops/AutoFixDialog.tsx:65:11",className:"flex-1 bg-purple-600 hover:bg-purple-700",onClick:()=>c(!1),children:[s.jsx(_,{"code-path":"src/components/aiops/AutoFixDialog.tsx:66:13",className:"h-4 w-4 mr-2"}),"确认执行"]})]})]})})}function as(e,c){try{let t=e.replace(/```(?:json)?\s*\n?/g,"").replace(/```$/,"").trim();const a=JSON.parse(t);return{rootCause:a.root_cause||a.rootCause||c.rootCause,impact:a.impact||c.impact,recommendations:Array.isArray(a.recommendations)?a.recommendations:c.recommendations,autoFixScript:a.auto_fix_script||a.autoFixScript||c.autoFixScript,similarCases:typeof a.similar_cases=="number"?a.similar_cases:a.similarCases??c.similarCases,confidence:typeof a.confidence=="number"?a.confidence:c.confidence}}catch{return{...c,rootCause:e}}}function As(){const[e,c]=l.useState([]),[t,a]=l.useState(!0),[n,r]=l.useState(null),[j,d]=l.useState(!1),[x,i]=l.useState(null),[p,h]=l.useState(!1);l.useEffect(()=>{u()},[]);const u=async()=>{a(!0);try{const o=await K.getAlerts({page:1,page_size:50}),m=o?.list||o||[];c(m.map(Z))}catch(o){console.error("加载告警失败:",o),c([])}finally{a(!1)}},T=async o=>{r(o),d(!0),i(null);const m=Y(o);try{const M=`你是运维专家。请分析以下告警并以 JSON 格式回复(不要 markdown 代码块)。 + +告警名称:${o.name} +严重程度:${o.severity} +目标:${o.source} +指标:${o.metric} = ${o.currentValue}(阈值 ${o.threshold}) +持续:${o.duration} +描述:${o.description} + +返回 JSON 格式(字段名用 snake_case): +{ + "root_cause": "根因分析(2-3句)", + "impact": "影响评估(1-2句)", + "recommendations": ["建议1", "建议2", "建议3"], + "auto_fix_script": "#!/bin/bash\\n...\\n(可选的自动修复脚本,无则 null)", + "similar_cases": 数字(类似案例数预估), + "confidence": 数字(0-100 置信度) +}`,N=await q.chat([{role:"user",content:M}]),I=N?.content||N?.message?.content||"";i(I?as(I,m):m)}catch{i(m)}finally{d(!1)}},k=()=>{h(!0)},V=o=>{switch(o){case"critical":return s.jsx(W,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:127:16",className:"h-4 w-4 text-red-400"});case"warning":return s.jsx(w,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:129:16",className:"h-4 w-4 text-amber-400"});default:return s.jsx(g,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:131:16",className:"h-4 w-4 text-blue-400"})}};return s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:136:5",className:"space-y-6",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:138:7",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:139:9",className:"flex items-center gap-3",children:[s.jsx("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:140:11",className:"w-10 h-10 rounded-lg bg-gradient-to-br from-amber-500 to-orange-500 flex items-center justify-center",children:s.jsx(f,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:141:13",className:"h-5 w-5 text-white"})}),s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:143:11",children:[s.jsx("h1",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:144:13",className:"text-2xl font-bold text-slate-100",children:"AI 告警智能分析"}),s.jsx("p",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:145:13",className:"text-sm text-slate-500",children:"基于大模型的告警根因分析和自动修复建议"})]})]}),s.jsx("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:148:9",className:"flex items-center gap-2",children:s.jsxs(y,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:149:11",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:[s.jsx(S,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:150:13",className:"h-3 w-3 mr-1"}),"AI 引擎运行中"]})})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:156:7",className:"grid grid-cols-2 gap-6 h-[calc(100vh-200px)]",children:[s.jsxs(z,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:158:9",className:"bg-slate-800 border-slate-700 flex flex-col",children:[s.jsx($,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:159:11",className:"border-b border-slate-700 pb-3",children:s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:160:13",className:"flex items-center justify-between",children:[s.jsxs(D,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:161:15",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(R,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:162:17",className:"h-5 w-5 text-amber-400"}),"活跃告警"]}),s.jsxs(y,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:165:15",className:"bg-red-500/10 text-red-400 border-red-500/30",children:[e.filter(o=>o.status==="active").length," 个活跃"]})]})}),s.jsx(b,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:170:11",className:"flex-1",children:s.jsx(F,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:171:13",className:"p-4 space-y-3",children:t?s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:173:17",className:"flex flex-col items-center justify-center h-32",children:[s.jsx(v,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:174:19",className:"h-6 w-6 animate-spin text-slate-500 mb-2"}),s.jsx("p",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:175:19",className:"text-sm text-slate-500",children:"加载告警数据..."})]}):e.length===0?s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:178:17",className:"flex flex-col items-center justify-center h-32 text-slate-500",children:[s.jsx(g,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:179:19",className:"h-8 w-8 mb-2 opacity-50"}),s.jsx("p",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:180:19",className:"text-sm",children:"暂无告警事件"})]}):e.map(o=>s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:184:17",className:`p-4 rounded-lg border cursor-pointer transition-all ${n?.id===o.id?"border-purple-500 bg-purple-500/10":"border-slate-700 bg-slate-800/50 hover:border-slate-600"}`,onClick:()=>T(o),children:[s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:193:19",className:"flex items-start justify-between mb-2",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:194:21",className:"flex items-center gap-2",children:[V(o.severity),s.jsx("span",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:196:23",className:"font-medium text-slate-100",children:o.name})]}),s.jsx(y,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:198:21",variant:"outline",className:ss(o.severity),children:o.severity==="critical"?"严重":o.severity==="warning"?"警告":"提示"})]}),s.jsx("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:202:19",className:"text-sm text-slate-400 mb-2",children:o.description}),s.jsxs("div",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:203:19",className:"flex items-center gap-4 text-xs text-slate-500",children:[s.jsxs("span",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:204:21",className:"flex items-center gap-1",children:[s.jsx(G,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:205:23",className:"h-3 w-3"}),o.source]}),s.jsxs("span",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:208:21",className:"flex items-center gap-1",children:[s.jsx(H,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:209:23",className:"h-3 w-3"}),o.duration]}),s.jsxs("span",{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:212:21",className:"flex items-center gap-1",children:[s.jsx(P,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:213:23",className:"h-3 w-3"}),o.currentValue]})]})]},o.id))})})]}),s.jsx(es,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:225:9",selectedAlert:n,isAnalyzing:j,analysis:x,onAutoFix:k})]}),s.jsx(ts,{"code-path":"src/components/aiops/AIAlertAnalyzer.tsx:234:7",open:p,onOpenChange:h,script:x?.autoFixScript})]})}export{As as AIAlertAnalyzer}; diff --git a/backend/static/assets/AIOpsAssistant-DFQDT-tz.js b/backend/static/assets/AIOpsAssistant-DFQDT-tz.js new file mode 100644 index 0000000..296ac85 --- /dev/null +++ b/backend/static/assets/AIOpsAssistant-DFQDT-tz.js @@ -0,0 +1,19 @@ +import{g as _s,r as x,j as s,ao as ks,aR as Es,aA as Ls,aw as H,X as ds,aJ as Rs,B as N,E as Z,T as ms,A as xs,L as k,H as Ms,aS as ss,a2 as Ps,a8 as Ds,I as w,D as Ts,b as qs,c as Us,d as Bs,e as zs,f as Fs}from"./index-DfyorCky.js";import{C as D,b as T,c as ts,a as q}from"./card-C55cvSHg.js";import{B as E}from"./badge-xNW8x0G1.js";import{L as y}from"./label-BK0h2apY.js";import{S as es,a as as,b as ns,c as os,d as cs}from"./select-D5qUzdAs.js";import{S as Hs}from"./switch-CGiGgOnh.js";import{t as C}from"./index-a3ybMjbR.js";import{d as U}from"./dashboard-BjQPIG2G.js";import{a as Vs}from"./monitor-BAaBXIsC.js";import{a as Ks}from"./agent-DqqIRCQX.js";import{a as $}from"./ai-BTgmlP5Q.js";import{C as Gs}from"./circle-check-DWcXrx2k.js";import{F as hs}from"./file-text-C9G5abwR.js";import{T as Ws}from"./trending-up-CdusV6gc.js";import{R as Js}from"./rotate-cw-5qcj_h_q.js";import{M as Qs}from"./message-square-DyxabBvb.js";import{S as Xs}from"./square-9TIYDO_t.js";import{W as Ys}from"./wifi-FqsslTyA.js";import"./index-CWVNW_qu.js";const Zs=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]],st=_s("send",Zs);function tt(e,n=[]){let i=[];function r(a,d){const m=x.createContext(d);m.displayName=a+"Context";const l=i.length;i=[...i,d];const g=h=>{const{scope:u,children:c,...p}=h,A=u?.[e]?.[l]||m,j=x.useMemo(()=>p,Object.values(p));return s.jsx(A.Provider,{value:j,children:c})};g.displayName=a+"Provider";function v(h,u){const c=u?.[e]?.[l]||m,p=x.useContext(c);if(p)return p;if(d!==void 0)return d;throw new Error(`\`${h}\` must be used within \`${a}\``)}return[g,v]}const o=()=>{const a=i.map(d=>x.createContext(d));return function(m){const l=m?.[e]||a;return x.useMemo(()=>({[`__scope${e}`]:{...m,[e]:l}}),[m,l])}};return o.scopeName=e,[r,et(o,...n)]}function et(...e){const n=e[0];if(e.length===1)return n;const i=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(a){const d=r.reduce((m,{useScope:l,scopeName:g})=>{const h=l(a)[`__scope${g}`];return{...m,...h}},{});return x.useMemo(()=>({[`__scope${n.scopeName}`]:d}),[d])}};return i.scopeName=n.scopeName,i}var at=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],V=at.reduce((e,n)=>{const i=ks(`Primitive.${n}`),r=x.forwardRef((o,a)=>{const{asChild:d,...m}=o,l=d?i:n;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),s.jsx(l,{...m,ref:a})});return r.displayName=`Primitive.${n}`,{...e,[n]:r}},{}),B={exports:{}},z={};var rs;function nt(){if(rs)return z;rs=1;var e=Es();function n(h,u){return h===u&&(h!==0||1/h===1/u)||h!==h&&u!==u}var i=typeof Object.is=="function"?Object.is:n,r=e.useState,o=e.useEffect,a=e.useLayoutEffect,d=e.useDebugValue;function m(h,u){var c=u(),p=r({inst:{value:c,getSnapshot:u}}),A=p[0].inst,j=p[1];return a(function(){A.value=c,A.getSnapshot=u,l(A)&&j({inst:A})},[h,c,u]),o(function(){return l(A)&&j({inst:A}),h(function(){l(A)&&j({inst:A})})},[h]),d(c),c}function l(h){var u=h.getSnapshot;h=h.value;try{var c=u();return!i(h,c)}catch{return!0}}function g(h,u){return u()}var v=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?g:m;return z.useSyncExternalStore=e.useSyncExternalStore!==void 0?e.useSyncExternalStore:v,z}var is;function ot(){return is||(is=1,B.exports=nt()),B.exports}var ct=ot();function rt(){return ct.useSyncExternalStore(it,()=>!0,()=>!1)}function it(){return()=>{}}var K="Avatar",[pt]=tt(K),[lt,us]=pt(K),As=x.forwardRef((e,n)=>{const{__scopeAvatar:i,...r}=e,[o,a]=x.useState("idle");return s.jsx(lt,{scope:i,imageLoadingStatus:o,onImageLoadingStatusChange:a,children:s.jsx(V.span,{...r,ref:n})})});As.displayName=K;var fs="AvatarImage",dt=x.forwardRef((e,n)=>{const{__scopeAvatar:i,src:r,onLoadingStatusChange:o=()=>{},...a}=e,d=us(fs,i),m=mt(r,a),l=Ls(g=>{o(g),d.onImageLoadingStatusChange(g)});return H(()=>{m!=="idle"&&l(m)},[m,l]),m==="loaded"?s.jsx(V.img,{...a,ref:n,src:r}):null});dt.displayName=fs;var gs="AvatarFallback",Is=x.forwardRef((e,n)=>{const{__scopeAvatar:i,delayMs:r,...o}=e,a=us(gs,i),[d,m]=x.useState(r===void 0);return x.useEffect(()=>{if(r!==void 0){const l=window.setTimeout(()=>m(!0),r);return()=>window.clearTimeout(l)}},[r]),d&&a.imageLoadingStatus!=="loaded"?s.jsx(V.span,{...o,ref:n}):null});Is.displayName=gs;function ps(e,n){return e?n?(e.src!==n&&(e.src=n),e.complete&&e.naturalWidth>0?"loaded":"loading"):"error":"idle"}function mt(e,{referrerPolicy:n,crossOrigin:i}){const r=rt(),o=x.useRef(null),a=r?(o.current||(o.current=new window.Image),o.current):null,[d,m]=x.useState(()=>ps(a,e));return H(()=>{m(ps(a,e))},[a,e]),H(()=>{const l=h=>()=>{m(h)};if(!a)return;const g=l("loaded"),v=l("error");return a.addEventListener("load",g),a.addEventListener("error",v),n&&(a.referrerPolicy=n),typeof i=="string"&&(a.crossOrigin=i),()=>{a.removeEventListener("load",g),a.removeEventListener("error",v)}},[a,i,n]),d}var xt=As,ht=Is;function ut({className:e,...n}){return s.jsx(xt,{"code-path":"src/components/ui/avatar.tsx:11:5","data-slot":"avatar",className:ds("relative flex size-8 shrink-0 overflow-hidden rounded-full",e),...n})}function At({className:e,...n}){return s.jsx(ht,{"code-path":"src/components/ui/avatar.tsx:40:5","data-slot":"avatar-fallback",className:ds("bg-muted flex size-full items-center justify-center rounded-full",e),...n})}const F=[{id:"openai",name:"OpenAI",defaultEndpoint:"https://api.openai.com/v1",models:["gpt-4o-mini","gpt-4o","gpt-4-turbo"]},{id:"deepseek",name:"DeepSeek",defaultEndpoint:"https://api.deepseek.com/v1",models:["deepseek-chat","deepseek-reasoner"]},{id:"qwen",name:"通义千问 (DashScope)",defaultEndpoint:"https://dashscope.aliyuncs.com/compatible-mode/v1",models:["qwen-plus","qwen-turbo","qwen-max"]},{id:"moonshot",name:"Moonshot 月之暗面",defaultEndpoint:"https://api.moonshot.cn/v1",models:["moonshot-v1-8k","moonshot-v1-32k"]},{id:"ollama",name:"Ollama 本地",defaultEndpoint:"http://localhost:11434/v1",models:["qwen2.5:7b","llama3.2","deepseek-r1:7b"]},{id:"custom",name:"自定义 (OpenAI 兼容)",defaultEndpoint:"",models:[]}],ft={provider:"openai",model:"gpt-4o-mini",api_key:"",endpoint:"https://api.openai.com/v1",temperature:.7,max_tokens:2e3,system_prompt:"",enabled:!1};async function gt(){const n=(await Vs.getAlerts({page:1,page_size:20}))?.list||[];if(!n.length)return"(当前无告警事件)";const i=n.slice(0,15).map((o,a)=>`${a+1}. [${o.severity||"未知"}|${o.status||"-"}] ${o.rule_name||"告警"} → 目标:${o.target||"-"} 值:${o.value??"-"} 时间:${(o.started_at||"").slice(0,16)}`),r=n.filter(o=>o.status==="firing").length;return`共 ${n.length} 条告警(firing ${r} 条),前 ${Math.min(15,n.length)} 条: +${i.join(` +`)}`}async function ls(){const e=await Ks.getLatest(),n=Array.isArray(e)?e:e?.list||[];if(!n.length)return"(当前无 Agent 上报数据,可能未部署监控 Agent)";const i=n.slice(0,20).map((a,d)=>{const m=a.cpu_usage??"-",l=a.mem_usage??"-";return`${d+1}. ${a.hostname||"-"} | CPU:${m}% | 内存:${l}% (${a.mem_used??"-"}/${a.mem_total??"-"}GB) | 核数:${a.cpu_cores??"-"} | 上报:${(a.report_time||"").slice(0,16)}`}),r=n.filter(a=>(a.cpu_usage??0)>=80||(a.mem_usage??0)>=80),o=r.length?` +⚠️ 高负载主机 ${r.length} 台:${r.map(a=>`${a.hostname}(CPU${a.cpu_usage}%/MEM${a.mem_usage}%)`).join("、")}`:"";return`Agent 监控的 ${n.length} 台主机实时指标: +${i.join(` +`)}${o}`}async function It(){const[e,n,i]=await Promise.all([U.getStats().catch(()=>null),U.getAlerts(10).catch(()=>null),U.getReleases(10).catch(()=>null)]),r=e||{},o=r.server_stats||{},a=r.kubernetes_stats||{},d=r.alert_stats||{},m=r.pipeline_stats||{},l=r.cost_stats||{},g=`服务器:${o.total??0}(运行${o.running??0}) | Kubernetes集群:${a.total??0} 节点:${a.total_nodes??0} Pod:${a.total_pods??0} | 告警:${d.total??0}(firing ${d.firing??0}) | 流水线:${m.total??0}(成功率${m.success_rate??0}%) | 本月成本:¥${l.month_cost??0}`,v=Array.isArray(n)?n:n?.list||[],h=Array.isArray(i)?i:i?.list||[],u=v.slice(0,10).map((p,A)=>`${A+1}.[${p.severity||"?"}|${p.status||"?"}] ${p.rule_name||"-"} → ${p.target||"-"}`),c=h.slice(0,10).map((p,A)=>`${A+1}.${p.app_name||"-"} ${p.version||""} [${p.environment||"-"}/${p.status||"-"}] by ${p.author||"-"}`);return`平台概览:${g} + +最近告警: +${u.join(` +`)||"(无)"} + +最近发布: +${c.join(` +`)||"(无)"}`}const vt=[{id:"alerts",name:"分析今日告警",icon:ms,prompt:"帮我分析以下最近的告警事件,给出根因分析和处置建议(按严重程度排序,给出具体处置步骤)",contextLoader:gt},{id:"performance",name:"性能瓶颈分析",icon:xs,prompt:"分析以下主机实时指标,找出 CPU/内存使用率最高的主机并给出性能优化建议",contextLoader:ls},{id:"report",name:"生成运维报告",icon:hs,prompt:"基于以下平台实时数据,生成一份简洁的今日运维报告,包括资源概览、告警情况和发布状态,用 Markdown 格式输出",contextLoader:It},{id:"optimize",name:"资源优化建议",icon:Ws,prompt:"根据以下主机资源使用数据,提供成本优化和容量规划建议(识别闲置/过载主机,给出缩容/扩容建议)",contextLoader:ls}];function jt(e){return new Date(e).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})}function Bt(){const[e,n]=x.useState([]),[i,r]=x.useState(""),[o,a]=x.useState(!1),d=x.useRef(null);x.useEffect(()=>()=>d.current?.abort(),[]);const[m,l]=x.useState(!1),[g,v]=x.useState(!1),[h,u]=x.useState(!1),[c,p]=x.useState(ft),[A,j]=x.useState(!1),[L,G]=x.useState(null),W=()=>{try{return crypto.randomUUID()}catch{}return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,t=>{const I=Math.random()*16|0;return(t==="x"?I:I&3|8).toString(16)})},[J,vs]=x.useState(()=>W()),Q=x.useRef(null),js=()=>Q.current?.scrollIntoView({behavior:"smooth"});x.useEffect(()=>{js()},[e]);const Os=async()=>{try{const t=await $.getConfig();p(t),j(!!(t.enabled&&t.configured))}catch{j(!1)}},bs=async()=>{try{const I=(await $.getHistory(J))?.list||[];n(I.map(f=>({id:String(f.id),role:f.role,content:f.content,timestamp:f.created_at})))}catch{}};x.useEffect(()=>{Os(),bs()},[]);const Ns=t=>{const I=F.find(f=>f.id===t);p(f=>({...f,provider:t,endpoint:I?.defaultEndpoint||f.endpoint,model:I?.models[0]||f.model}))},Ss=async()=>{if(c.enabled&&!c.api_key&&c.provider!=="ollama"){C.error("请填写 API Key");return}v(!0);try{const t=await $.saveConfig(c);p(t),j(!!(t.enabled&&t.configured)),C.success("配置已保存"),l(!1)}catch(t){C.error(t instanceof Error?t.message:"保存失败")}finally{v(!1)}},ys=async()=>{u(!0);try{await $.testConnection(),C.success("LLM 服务连接成功")}catch(t){C.error(t instanceof Error?t.message:"连接失败")}finally{u(!1)}},X=async t=>{const I={id:Date.now().toString(),role:"user",content:t,timestamp:new Date().toISOString()},f=(Date.now()+1).toString(),$s=[...e,I,{id:f,role:"assistant",content:"",timestamp:new Date().toISOString()}];n($s),a(!0);const M=new AbortController;d.current=M;let P=!1;try{const _=[...e,I].slice(-10).map(O=>({role:O.role,content:O.content}));await $.chatStream(_,O=>{P=!0,n(S=>S.map(b=>b.id===f?{...b,content:b.content+O}:b))},M.signal,J)}catch(_){if(M.signal.aborted)n(O=>O.map(S=>S.id===f?{...S,content:S.content||"(已停止生成)",isStopped:!0}:S));else{const O=_ instanceof Error?_.message:"对话失败";n(S=>S.map(b=>b.id===f?{...b,content:P?b.content+` + +⚠️ ${O}`:`⚠️ ${O}`,isError:!P}:b))}}finally{a(!1),d.current=null}},Y=async()=>{const t=i.trim();!t||o||(r(""),await X(t))},ws=async t=>{if(o||L)return;if(!A||!t.contextLoader){r(t.prompt);return}G(t.id);let I="";try{I=await t.contextLoader()}catch{I="(平台数据加载失败,请稍后重试或检查后端服务)"}finally{G(null)}const f=`${t.prompt} + +【平台实时数据】 +${I}`;await X(f)},Cs=async()=>{try{await $.clearHistory()}catch{}const t=W();vs(t),n([]),r(""),C.success("已开始新对话")},R=F.find(t=>t.id===c.provider);return s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:370:5",className:"space-y-6",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:372:7",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:373:9",className:"flex items-center gap-3",children:[s.jsx("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:374:11",className:"w-10 h-10 rounded-lg bg-gradient-to-br from-purple-500 to-pink-500 flex items-center justify-center",children:s.jsx(Rs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:375:13",className:"h-5 w-5 text-white"})}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:377:11",children:[s.jsx("h1",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:378:13",className:"text-2xl font-bold text-slate-100",children:"AIOps 智能助手"}),s.jsx("p",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:379:13",className:"text-sm text-slate-500",children:"AI 驱动的智能运维助手"})]})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:382:9",className:"flex items-center gap-3",children:[A?s.jsxs(E,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:384:13",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:[s.jsx(Gs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:385:15",className:"h-3 w-3 mr-1"}),c.model]}):s.jsx(E,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:389:13",variant:"outline",className:"border-amber-500/30 text-amber-400 bg-amber-500/10",children:"未配置"}),s.jsxs(N,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:393:11",variant:"outline",className:"border-slate-700 text-slate-300",onClick:()=>l(!0),children:[s.jsx(Z,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:394:13",className:"h-4 w-4 mr-2"}),"模型配置"]})]})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:400:7",className:"grid grid-cols-4 gap-6 h-[calc(100vh-200px)]",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:402:9",className:"col-span-1 space-y-4",children:[s.jsxs(D,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:403:11",className:"bg-slate-800 border-slate-700",children:[s.jsx(T,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:404:13",className:"pb-3",children:s.jsx(ts,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:405:15",className:"text-sm text-slate-300",children:"快速操作"})}),s.jsx(q,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:407:13",className:"space-y-2",children:vt.map(t=>s.jsxs(N,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:409:17",variant:"ghost",className:"w-full justify-start text-slate-300 hover:text-slate-100 hover:bg-slate-700",disabled:o||L!==null,onClick:()=>ws(t),children:[L===t.id?s.jsx(k,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:417:21",className:"h-4 w-4 mr-2 shrink-0 animate-spin"}):s.jsx(t.icon,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:419:21",className:"h-4 w-4 mr-2 shrink-0"}),s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:421:19",className:"text-sm",children:t.name}),A&&t.contextLoader&&s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:423:21",className:"ml-auto text-[10px] text-emerald-400/60 shrink-0",children:"实时"})]},t.id))})]}),s.jsxs(D,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:430:11",className:"bg-slate-800 border-slate-700",children:[s.jsx(T,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:431:13",className:"pb-3",children:s.jsx(ts,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:432:15",className:"text-sm text-slate-300",children:"能力展示"})}),s.jsxs(q,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:434:13",className:"space-y-3",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:435:15",className:"flex items-center gap-2 text-sm text-slate-400",children:[s.jsx(ms,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:436:17",className:"h-4 w-4 text-amber-400"}),s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:437:17",children:"智能告警分析"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:439:15",className:"flex items-center gap-2 text-sm text-slate-400",children:[s.jsx(xs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:440:17",className:"h-4 w-4 text-blue-400"}),s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:441:17",children:"性能瓶颈识别"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:443:15",className:"flex items-center gap-2 text-sm text-slate-400",children:[s.jsx(hs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:444:17",className:"h-4 w-4 text-emerald-400"}),s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:445:17",children:"自动报告生成"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:447:15",className:"flex items-center gap-2 text-sm text-slate-400",children:[s.jsx(Ms,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:448:17",className:"h-4 w-4 text-purple-400"}),s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:449:17",children:"脚本自动生成"})]})]})]})]}),s.jsxs(D,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:456:9",className:"col-span-3 bg-slate-800 border-slate-700 flex flex-col",children:[s.jsx(T,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:457:11",className:"border-b border-slate-700 pb-3",children:s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:458:13",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:459:15",className:"flex items-center gap-2",children:[s.jsx(ss,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:460:17",className:"h-5 w-5 text-purple-400"}),s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:461:17",className:"font-medium text-slate-100",children:"AI 助手"}),A?s.jsxs(E,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:463:19",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10 text-xs",children:[s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:464:21",className:"w-2 h-2 rounded-full bg-emerald-400 mr-1 animate-pulse"}),"在线"]}):s.jsx(E,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:468:19",variant:"outline",className:"border-slate-600 text-slate-400 text-xs",children:"离线"})]}),s.jsxs(N,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:471:15",variant:"ghost",size:"sm",className:"text-slate-400",onClick:Cs,disabled:e.length===0,children:[s.jsx(Js,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:472:17",className:"h-4 w-4 mr-1"}),"新对话"]})]})}),s.jsx(Ps,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:478:11",className:"flex-1 p-4",children:s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:479:13",className:"space-y-4",children:[e.length===0&&!o&&s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:481:17",className:"flex flex-col items-center justify-center py-16 text-slate-500",children:[s.jsx(Qs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:482:19",className:"h-10 w-10 mb-3 opacity-30"}),s.jsx("p",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:483:19",children:A?"暂无对话记录,输入问题开始与 AI 助手对话":"AI 助手尚未配置大模型"}),!A&&s.jsxs(N,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:485:21",variant:"outline",size:"sm",className:"mt-4 border-slate-600 text-slate-300",onClick:()=>l(!0),children:[s.jsx(Z,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:486:23",className:"h-4 w-4 mr-1"}),"前往配置"]})]}),e.map(t=>{const I=o&&t.role==="assistant"&&t.content==="";return s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:496:17",className:`flex gap-3 ${t.role==="user"?"flex-row-reverse":""}`,children:[s.jsx(ut,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:497:19",className:t.role==="assistant"?"bg-purple-500":"bg-blue-500",children:s.jsx(At,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:498:21",children:t.role==="assistant"?s.jsx(ss,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:499:55",className:"h-4 w-4"}):s.jsx(Ds,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:499:85",className:"h-4 w-4"})})}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:502:19",className:`max-w-[80%] ${t.role==="user"?"text-right":""}`,children:[s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:503:21",className:`inline-block rounded-lg p-3 text-left whitespace-pre-wrap break-words ${t.isError?"bg-red-900/30 border border-red-500/30 text-red-300":t.role==="assistant"?"bg-slate-700 text-slate-100":"bg-blue-600 text-white"}`,children:[I?s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:513:25",className:"flex items-center gap-2 text-slate-400",children:[s.jsx(k,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:514:27",className:"h-4 w-4 animate-spin"}),s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:515:27",className:"text-sm",children:"思考中..."})]}):t.content,o&&t.role==="assistant"&&!I&&t.content&&s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:522:25",className:"inline-block w-2 h-4 ml-0.5 bg-purple-400 animate-pulse align-middle"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:525:21",className:"text-xs text-slate-500 mt-1",children:[jt(t.timestamp),t.isStopped&&s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:527:45",className:"ml-2 text-slate-600",children:"(已停止)"})]})]})]},t.id)}),s.jsx("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:534:15",ref:Q})]})}),s.jsx(q,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:538:11",className:"border-t border-slate-700 pt-4",children:s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:539:13",className:"flex gap-2",children:[s.jsx(w,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:540:15",value:i,onChange:t=>r(t.target.value),onKeyDown:t=>t.key==="Enter"&&Y(),placeholder:A?"输入运维问题,或选择左侧快速操作...":"请先配置大模型...",className:"flex-1 bg-slate-900 border-slate-700 text-slate-100",disabled:o}),s.jsx(N,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:548:15",className:"bg-purple-600 hover:bg-purple-700",onClick:Y,disabled:o||!i.trim(),children:s.jsx(st,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:549:17",className:"h-4 w-4"})}),o&&s.jsx(N,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:553:17",variant:"outline",className:"border-red-500/40 text-red-400 hover:bg-red-500/10",onClick:()=>d.current?.abort(),title:"停止生成",children:s.jsx(Xs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:559:19",className:"h-4 w-4"})})]})})]})]}),s.jsx(Ts,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:568:7",open:m,onOpenChange:l,children:s.jsxs(qs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:569:9",className:"max-w-2xl bg-slate-900 border-slate-700 text-slate-100",children:[s.jsxs(Us,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:570:11",children:[s.jsx(Bs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:571:13",children:"大模型配置"}),s.jsx(zs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:572:13",className:"text-slate-500",children:"配置 AI 助手使用的大语言模型(支持 OpenAI 兼容接口)"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:576:11",className:"space-y-4 py-4 max-h-[60vh] overflow-y-auto pr-1",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:578:13",className:"flex items-center justify-between rounded-lg border border-slate-700 p-3",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:579:15",children:[s.jsx("p",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:580:17",className:"text-sm font-medium text-slate-200",children:"启用 AI 助手"}),s.jsx("p",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:581:17",className:"text-xs text-slate-500",children:"关闭后将无法进行对话"})]}),s.jsx(Hs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:583:15",checked:c.enabled,onCheckedChange:t=>p({...c,enabled:t})})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:586:13",className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:587:15",children:[s.jsx(y,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:588:17",className:"text-slate-300",children:"提供商"}),s.jsxs(es,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:589:17",value:c.provider,onValueChange:Ns,children:[s.jsx(as,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:590:19",className:"bg-slate-800 border-slate-700 text-slate-100 mt-1",children:s.jsx(ns,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:591:21"})}),s.jsx(os,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:593:19",className:"bg-slate-800 border-slate-700",children:F.map(t=>s.jsx(cs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:595:23",value:t.id,className:"text-slate-100",children:t.name},t.id))})]})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:600:15",children:[s.jsx(y,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:601:17",className:"text-slate-300",children:"模型"}),R&&R.models.length>0?s.jsxs(es,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:603:19",value:c.model,onValueChange:t=>p({...c,model:t}),children:[s.jsx(as,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:604:21",className:"bg-slate-800 border-slate-700 text-slate-100 mt-1",children:s.jsx(ns,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:605:23"})}),s.jsx(os,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:607:21",className:"bg-slate-800 border-slate-700",children:R.models.map(t=>s.jsx(cs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:609:25",value:t,className:"text-slate-100",children:t},t))})]}):s.jsx(w,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:614:19",value:c.model,onChange:t=>p({...c,model:t.target.value}),placeholder:"输入模型名称",className:"bg-slate-800 border-slate-700 text-slate-100 mt-1"})]})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:623:13",children:[s.jsxs(y,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:624:15",className:"text-slate-300",children:["API Key ",c.provider==="ollama"&&s.jsx("span",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:624:90",className:"text-xs text-slate-500",children:"(本地 Ollama 通常无需)"})]}),s.jsx(w,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:625:15",type:"password",value:c.api_key,onChange:t=>p({...c,api_key:t.target.value}),placeholder:"sk-...",className:"bg-slate-800 border-slate-700 text-slate-100 mt-1"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:633:13",children:[s.jsx(y,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:634:15",className:"text-slate-300",children:"API Endpoint"}),s.jsx(w,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:635:15",value:c.endpoint,onChange:t=>p({...c,endpoint:t.target.value}),placeholder:"https://api.openai.com/v1",className:"bg-slate-800 border-slate-700 text-slate-100 mt-1 font-mono text-sm"}),s.jsx("p",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:641:15",className:"text-xs text-slate-500 mt-1",children:"基础地址(不含 /chat/completions),OpenAI 兼容格式"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:643:13",children:[s.jsx(y,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:644:15",className:"text-slate-300",children:"系统提示词(可选)"}),s.jsx("textarea",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:645:15",value:c.system_prompt,onChange:t=>p({...c,system_prompt:t.target.value}),placeholder:"留空则使用内置 AIOps 运维助手角色提示词",className:"w-full bg-slate-800 border border-slate-700 text-slate-100 mt-1 rounded-md p-2 text-sm min-h-[70px] resize-y"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:652:13",className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:653:15",children:[s.jsx(y,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:654:17",className:"text-slate-300",children:"Temperature"}),s.jsx(w,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:655:17",type:"number",min:0,max:2,step:.1,value:Math.round(c.temperature*10)/10,onChange:t=>p({...c,temperature:parseFloat(t.target.value)||0}),className:"bg-slate-800 border-slate-700 text-slate-100 mt-1"}),s.jsx("p",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:664:17",className:"text-xs text-slate-500 mt-1",children:"值越高回答越创造性"})]}),s.jsxs("div",{"code-path":"src/components/aiops/AIOpsAssistant.tsx:666:15",children:[s.jsx(y,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:667:17",className:"text-slate-300",children:"Max Tokens"}),s.jsx(w,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:668:17",type:"number",value:c.max_tokens,onChange:t=>p({...c,max_tokens:parseInt(t.target.value)||2e3}),className:"bg-slate-800 border-slate-700 text-slate-100 mt-1"})]})]})]}),s.jsxs(Fs,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:677:11",className:"gap-2",children:[s.jsxs(N,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:678:13",variant:"outline",onClick:ys,disabled:h,className:"border-slate-700 text-slate-300",children:[h?s.jsx(k,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:679:26",className:"h-4 w-4 mr-2 animate-spin"}):s.jsx(Ys,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:679:78",className:"h-4 w-4 mr-2"}),"测试连接"]}),s.jsx(N,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:682:13",variant:"outline",onClick:()=>l(!1),className:"border-slate-700 text-slate-300",children:"取消"}),s.jsxs(N,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:685:13",className:"bg-purple-600 hover:bg-purple-700",onClick:Ss,disabled:g,children:[g?s.jsx(k,{"code-path":"src/components/aiops/AIOpsAssistant.tsx:686:25",className:"h-4 w-4 mr-2 animate-spin"}):null,"保存配置"]})]})]})})]})}export{Bt as AIOpsAssistant}; diff --git a/backend/static/assets/AIPredictiveAnalytics-Dr8sfqna.js b/backend/static/assets/AIPredictiveAnalytics-Dr8sfqna.js new file mode 100644 index 0000000..bea5f35 --- /dev/null +++ b/backend/static/assets/AIPredictiveAnalytics-Dr8sfqna.js @@ -0,0 +1 @@ +import{g as J,j as e,L as D,G as q,r as g,aJ as Q,B as ee,A as se,a3 as te,T as _,K as ce,o as ae,N as ie}from"./index-DfyorCky.js";import{C as w,b as K,c as H,a as C}from"./card-C55cvSHg.js";import{B as X}from"./badge-xNW8x0G1.js";import{T as ne,a as oe,b as F,c as B}from"./tabs-CIh_yD4s.js";import{S as re,a as le,b as de,c as pe,d as U}from"./select-D5qUzdAs.js";import{d as me}from"./dashboard-BjQPIG2G.js";import{s as xe}from"./server-CjDPBaTN.js";import{a as W}from"./monitor-BAaBXIsC.js";import{H as z}from"./hard-drive-BbPmnARR.js";import{Z as Y}from"./zap-D2uWSK32.js";import{S as G}from"./sparkles-Bld4NX5y.js";import{T as O}from"./trending-up-CdusV6gc.js";import{M as he}from"./memory-stick-QMV-0CnU.js";import{M as Ae}from"./minus-UVrx3jLc.js";import{T as ye}from"./trending-down-BGTWG_dA.js";import"./index-CWVNW_qu.js";const ve=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]],ue=J("calendar",ve);const je=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]],be=J("chart-line",je);function Pe({forecasts:a,loading:i}){return e.jsxs(w,{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:14:5",className:"bg-slate-800 border-slate-700",children:[e.jsx(K,{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:15:7",className:"pb-3",children:e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:16:9",className:"flex items-center justify-between",children:[e.jsxs(H,{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:17:11",className:"text-slate-100 flex items-center gap-2",children:[e.jsx(z,{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:18:13",className:"h-5 w-5 text-amber-400"}),"容量规划预警"]}),e.jsx("span",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:21:11",className:"text-xs text-slate-500",children:"基于日均增长率推算阈值触及时间"})]})}),e.jsx(C,{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:24:7",children:i?e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:26:11",className:"flex items-center justify-center py-12 text-slate-500",children:[e.jsx(D,{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:27:13",className:"h-5 w-5 animate-spin mr-2"})," 加载容量数据..."]}):a.length===0?e.jsx("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:30:11",className:"text-center py-12 text-slate-500",children:"暂无容量数据"}):e.jsx("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:32:11",className:"space-y-4",children:a.map((c,p)=>e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:34:15",className:"p-4 rounded-lg border border-slate-700 bg-slate-800/50",children:[e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:35:17",className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:36:19",className:"flex items-center gap-2",children:[e.jsx(q,{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:37:21",className:"h-5 w-5 text-blue-400"}),e.jsx("span",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:38:21",className:"font-medium text-slate-200",children:c.resource})]}),e.jsx(X,{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:40:19",variant:"outline",className:c.daysUntilThreshold<=7?"border-red-500/30 text-red-400 bg-red-500/10":c.daysUntilThreshold<=14?"border-amber-500/30 text-amber-400 bg-amber-500/10":"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:c.daysUntilThreshold<=7?"紧急":c.daysUntilThreshold<=14?"警告":"正常"})]}),e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:58:17",className:"mb-4",children:[e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:59:19",className:"flex items-center justify-between text-sm mb-1",children:[e.jsx("span",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:60:21",className:"text-slate-400",children:"7天使用率预测"}),e.jsx("span",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:61:21",className:"text-slate-400",children:c.daysUntilThreshold>=999?"增长平缓,暂无触顶风险":e.jsxs(e.Fragment,{children:["预计"," ",e.jsxs("span",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:67:27",className:"text-amber-400 font-medium",children:[c.daysUntilThreshold,"天"]})," ","后达到阈值"]})})]}),e.jsx("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:73:19",className:"h-3 bg-slate-700 rounded-full overflow-hidden",children:e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:74:21",className:"flex h-full",children:[e.jsx("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:75:23",className:"bg-blue-500",style:{width:`${c.currentUsage}%`}}),e.jsx("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:76:23",className:"bg-gradient-to-r from-blue-500/50 to-amber-500",style:{width:`${Math.max(0,c.predictedUsage-c.currentUsage)}%`}})]})}),e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:84:19",className:"flex items-center justify-between text-xs mt-1",children:[e.jsxs("span",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:85:21",className:"text-slate-500",children:["当前 ",c.currentUsage,"%"]}),e.jsxs("span",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:86:21",className:"text-amber-400",children:["预测 ",c.predictedUsage,"%"]}),e.jsxs("span",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:87:21",className:"text-red-400",children:["阈值 ",c.threshold,"%"]})]})]}),e.jsx("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:91:17",className:"p-3 bg-slate-900 rounded-lg border border-slate-700",children:e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:92:19",className:"flex items-start gap-2",children:[e.jsx(Y,{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:93:21",className:"h-4 w-4 text-emerald-400 mt-0.5"}),e.jsxs("div",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:94:21",children:[e.jsx("span",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:95:23",className:"text-sm text-slate-400",children:"AI建议:"}),e.jsx("p",{"code-path":"src/components/aiops/PredictiveCapacityTab.tsx:96:23",className:"text-sm text-slate-300 mt-1",children:c.recommendation})]})]})})]},p))})})]})}const M=[{key:"cpu",label:"CPU使用率",exprKey:"cpu_usage",threshold:85},{key:"memory",label:"内存使用率",exprKey:"memory_usage",threshold:85},{key:"disk",label:"磁盘使用率",exprKey:"disk_usage",threshold:90}],Ne={"1h":"1小时后","24h":"24小时后","7d":"7天后","30d":"30天后"},ge={"1h":1,"24h":24,"7d":168,"30d":720};function E(a){const i=a.length;if(i<2)return{slope:0,r2:0};const c=a.map((o,h)=>h),p=c.reduce((o,h)=>o+h,0)/i,A=a.reduce((o,h)=>o+h,0)/i;let j=0,b=0,I=0,T=0;for(let o=0;oc.name===i).sort((c,p)=>new Date(c.timestamp).getTime()-new Date(p.timestamp).getTime()).map(c=>Number(c.value)||0)}function Ie(a){const i=a.match(/[><=]\s*([\d.]+)/);return i?parseFloat(i[1]):null}function fe(a,i){const c=i<=7?"urgent":i<=14?"warning":"normal";return{urgent:{cpu:"CPU增长趋势明显,建议尽快扩容计算资源或优化高负载进程",memory:"内存增长趋势明显,建议增加内存或排查内存泄漏",disk:"磁盘空间即将耗尽,建议立即扩容或清理历史数据与日志"},warning:{cpu:"CPU使用率呈上升趋势,建议持续监控并准备扩容计划",memory:"内存使用率呈上升趋势,建议优化应用内存使用",disk:"磁盘使用率持续增长,建议规划数据归档和清理策略"},normal:{cpu:"CPU使用正常,建议持续监控",memory:"内存使用正常,建议持续监控",disk:"磁盘空间充足,建议持续监控"}}[c]?.[a]||"建议持续监控资源使用趋势"}function V(a){return{cpu:"检查高负载进程,优化CPU密集型任务,考虑横向扩容",memory:"排查内存泄漏,优化进程内存配置,考虑增加节点",disk:"清理历史数据和日志,实施数据归档策略,扩容磁盘",service:"检查服务健康状态与依赖组件,查看服务日志",pod:"检查Pod重启原因,查看容器日志,排查OOM或健康检查失败"}[a]||"建议检查相关服务状态并持续监控"}function we(a){const{rawMetrics:i,serverStats:c,alertEvents:p,alertRules:A,selectedTimeRange:j}=a,b=ge[j]||24,I=Ne[j]||"24小时后",T=M.map(t=>{const n=$(i,t.key),{slope:m,r2:x}=E(n),r=t.key==="cpu"?c.avg_cpu:t.key==="memory"?c.avg_memory:c.avg_disk,l=n.length>0?n[n.length-1]:r||0;let v=l+m*b;v=Math.max(0,Math.min(100,v));const s=m>.05?"up":m<-.05?"down":"stable",d=Math.round(60+x*35);return{name:t.label,current:Math.round(l),predicted:Math.round(v),unit:"%",trend:s,confidence:d,timeRange:I}}),P=M.map(t=>{const n=$(i,t.key),{slope:m}=E(n),x=t.key==="cpu"?c.avg_cpu:t.key==="memory"?c.avg_memory:c.avg_disk,r=Math.round(n.length>0?n[n.length-1]:x||0),l=m*24,v=Math.round(Math.min(100,r+l*7)),s=t.threshold;let d=999;return l>.01&&(d=Math.round((s-r)/l),d=d<1?1:d),{resource:{cpu:"服务器CPU算力",memory:"服务器内存",disk:"存储磁盘空间"}[t.key]||t.label,metricKey:t.key,currentUsage:r,predictedUsage:v,threshold:s,daysUntilThreshold:d,recommendation:fe(t.key,d)}}).filter(t=>t.currentUsage>0),f=[];for(const t of A){if(!t.enabled)continue;const n=Ie(t.expression||""),m=(t.expression||"").toLowerCase(),x=M.find(r=>m.includes(r.exprKey));if(x&&n){const r=$(i,x.key),{slope:l}=E(r),v=x.key==="cpu"?c.avg_cpu:x.key==="memory"?c.avg_memory:c.avg_disk,s=r.length>0?r[r.length-1]:v||0,d=n>0?s/n:0;let u=Math.round(d*55);l>.05&&(u+=15);const R=p.filter(y=>y.rule_id===t.id||y.rule_name===t.name).length;u+=Math.min(20,R*3),u=Math.max(5,Math.min(90,u));let N="未来24小时";if(l>.01&&n>s){const y=(n-s)/l;y<4?N="未来4小时":y<12?N="未来12小时":y<24?N="未来24小时":N=`未来${Math.ceil(y/24)}天`}f.push({metric:t.name,predictedAnomaly:t.description||`${t.name}可能触发`,probability:u,timeframe:N,suggestedAction:V(x.key)})}else{const r=p.filter(l=>l.rule_id===t.id||l.rule_name===t.name).length;if(r>0){const l=m.includes("service")?"service":m.includes("pod")?"pod":"service";f.push({metric:t.name,predictedAnomaly:t.description||`${t.name}可能再次发生`,probability:Math.min(60,20+r*5),timeframe:"未来24小时",suggestedAction:V(l)})}}}const k=f.sort((t,n)=>n.probability-t.probability).filter((t,n,m)=>m.findIndex(x=>x.metric===t.metric)===n),o=M.length>0?M.reduce((t,n)=>t+E($(i,n.key)).r2,0)/M.length:0,h=Math.round(78+o*17),S=k.filter(t=>t.probability>=50).length,L=P.filter(t=>t.daysUntilThreshold<=14).length;return{predictions:T,capacityForecasts:P,dedupedAnomalies:k,accuracy:h,predictedAlertCount:S,capacityWarningCount:L}}function Z(a){switch(a){case"up":return"text-red-400";case"down":return"text-emerald-400";default:return"text-slate-400"}}function ze(){const[a,i]=g.useState("24h"),[c,p]=g.useState(!1),[A,j]=g.useState(!0),[b,I]=g.useState([]),[T,P]=g.useState({}),[f,k]=g.useState([]),[o,h]=g.useState([]);g.useEffect(()=>{S()},[]);const S=async()=>{j(!0);try{const[s,d,u,R]=await Promise.all([me.getMetrics(72),xe.getServerStats(),W.getAlerts({page:1,page_size:100}),W.getRules()]);I(Array.isArray(s)?s:[]),P(d||{});const N=u?.list||u||[];k(Array.isArray(N)?N:[]);const y=R?.list||R||[];h(Array.isArray(y)?y:[])}catch{}finally{j(!1)}},L=async()=>{p(!0),await S(),p(!1)},{predictions:t,capacityForecasts:n,dedupedAnomalies:m,accuracy:x,predictedAlertCount:r,capacityWarningCount:l}=we({rawMetrics:b,serverStats:T,alertEvents:f,alertRules:o,selectedTimeRange:a}),v=s=>{switch(s){case"up":return e.jsx(O,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:99:16",className:"h-4 w-4 text-red-400"});case"down":return e.jsx(ye,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:101:16",className:"h-4 w-4 text-emerald-400"});default:return e.jsx(Ae,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:103:16",className:"h-4 w-4 text-slate-400"})}};return e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:108:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:110:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:111:9",className:"flex items-center gap-3",children:[e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:112:11",className:"w-10 h-10 rounded-lg bg-gradient-to-br from-indigo-500 to-purple-500 flex items-center justify-center",children:e.jsx(Q,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:113:13",className:"h-5 w-5 text-white"})}),e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:115:11",children:[e.jsx("h1",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:116:13",className:"text-2xl font-bold text-slate-100",children:"AI 预测分析"}),e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:117:13",className:"text-sm text-slate-500",children:"基于实时指标时序数据的线性回归预测与容量规划"})]})]}),e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:120:9",className:"flex items-center gap-2",children:[e.jsxs(re,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:121:11",value:a,onValueChange:i,children:[e.jsxs(le,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:122:13",className:"w-32 bg-slate-800 border-slate-700 text-slate-100",children:[e.jsx(ue,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:123:15",className:"h-4 w-4 mr-2"}),e.jsx(de,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:124:15"})]}),e.jsxs(pe,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:126:13",className:"bg-slate-800 border-slate-700",children:[e.jsx(U,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:127:15",value:"1h",children:"1小时"}),e.jsx(U,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:128:15",value:"24h",children:"24小时"}),e.jsx(U,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:129:15",value:"7d",children:"7天"}),e.jsx(U,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:130:15",value:"30d",children:"30天"})]})]}),e.jsx(ee,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:133:11",variant:"outline",className:"border-slate-700 text-slate-300",onClick:L,children:c||A?e.jsx(D,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:134:39",className:"h-4 w-4 animate-spin"}):e.jsx(se,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:134:86",className:"h-4 w-4"})})]})]}),e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:140:7",className:"grid grid-cols-4 gap-4",children:[e.jsx(w,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:141:9",className:"bg-slate-800 border-slate-700",children:e.jsxs(C,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:142:11",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:143:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:144:15",children:[e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:145:17",className:"text-sm text-slate-400",children:"预测置信度"}),e.jsxs("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:146:17",className:"text-2xl font-bold text-slate-100",children:[x,"%"]})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:148:15",className:"w-10 h-10 rounded-lg bg-emerald-500/20 flex items-center justify-center",children:e.jsx(te,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:149:17",className:"h-5 w-5 text-emerald-400"})})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:152:13",className:"flex items-center gap-1 mt-2 text-xs text-slate-500",children:e.jsxs("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:153:15",children:["基于 ",b.length," 个时序数据点回归拟合 R²"]})})]})}),e.jsx(w,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:158:9",className:"bg-slate-800 border-slate-700",children:e.jsxs(C,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:159:11",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:160:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:161:15",children:[e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:162:17",className:"text-sm text-slate-400",children:"高风险预测"}),e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:163:17",className:"text-2xl font-bold text-slate-100",children:r})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:165:15",className:"w-10 h-10 rounded-lg bg-amber-500/20 flex items-center justify-center",children:e.jsx(_,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:166:17",className:"h-5 w-5 text-amber-400"})})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:169:13",className:"flex items-center gap-1 mt-2 text-xs text-amber-400",children:e.jsx("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:170:15",children:"概率 ≥50% 的异常预测"})})]})}),e.jsx(w,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:175:9",className:"bg-slate-800 border-slate-700",children:e.jsxs(C,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:176:11",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:177:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:178:15",children:[e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:179:17",className:"text-sm text-slate-400",children:"容量预警"}),e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:180:17",className:"text-2xl font-bold text-slate-100",children:l})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:182:15",className:"w-10 h-10 rounded-lg bg-red-500/20 flex items-center justify-center",children:e.jsx(z,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:183:17",className:"h-5 w-5 text-red-400"})})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:186:13",className:"flex items-center gap-1 mt-2 text-xs text-slate-500",children:e.jsx("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:187:15",children:"14天内触及阈值"})})]})}),e.jsx(w,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:192:9",className:"bg-slate-800 border-slate-700",children:e.jsxs(C,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:193:11",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:194:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:195:15",children:[e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:196:17",className:"text-sm text-slate-400",children:"监控指标数"}),e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:197:17",className:"text-2xl font-bold text-slate-100",children:t.length})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:199:15",className:"w-10 h-10 rounded-lg bg-purple-500/20 flex items-center justify-center",children:e.jsx(G,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:200:17",className:"h-5 w-5 text-purple-400"})})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:203:13",className:"flex items-center gap-1 mt-2 text-xs text-slate-500",children:e.jsx("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:204:15",children:"CPU / 内存 / 磁盘"})})]})})]}),e.jsxs(ne,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:210:7",defaultValue:"metrics",className:"space-y-4",children:[e.jsxs(oe,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:211:9",className:"bg-slate-800 border border-slate-700",children:[e.jsxs(F,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:212:11",value:"metrics",className:"data-[state=active]:bg-slate-700",children:[e.jsx(be,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:213:13",className:"h-4 w-4 mr-2"}),"指标预测"]}),e.jsxs(F,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:216:11",value:"capacity",className:"data-[state=active]:bg-slate-700",children:[e.jsx(ce,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:217:13",className:"h-4 w-4 mr-2"}),"容量规划"]}),e.jsxs(F,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:220:11",value:"anomaly",className:"data-[state=active]:bg-slate-700",children:[e.jsx(_,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:221:13",className:"h-4 w-4 mr-2"}),"异常预测"]})]}),e.jsx(B,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:226:9",value:"metrics",className:"space-y-4",children:e.jsxs(w,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:227:11",className:"bg-slate-800 border-slate-700",children:[e.jsx(K,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:228:13",className:"pb-3",children:e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:229:15",className:"flex items-center justify-between",children:[e.jsxs(H,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:230:17",className:"text-slate-100 flex items-center gap-2",children:[e.jsx(O,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:231:19",className:"h-5 w-5 text-blue-400"}),"关键指标预测"]}),e.jsxs(X,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:234:17",variant:"outline",className:"border-purple-500/30 text-purple-400 bg-purple-500/10",children:[e.jsx(G,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:235:19",className:"h-3 w-3 mr-1"}),"线性回归预测"]})]})}),e.jsx(C,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:240:13",children:A?e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:242:17",className:"flex items-center justify-center py-12 text-slate-500",children:[e.jsx(D,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:243:19",className:"h-5 w-5 animate-spin mr-2"})," 加载指标数据..."]}):t.length===0?e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:246:17",className:"text-center py-12 text-slate-500",children:"暂无指标数据"}):e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:248:17",className:"grid grid-cols-2 gap-4",children:t.map((s,d)=>e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:250:21",className:"p-4 rounded-lg border border-slate-700 bg-slate-800/50",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:251:23",className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:252:25",className:"flex items-center gap-2",children:[s.name.includes("CPU")&&e.jsx(ae,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:253:63",className:"h-4 w-4 text-blue-400"}),s.name.includes("内存")&&e.jsx(he,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:254:62",className:"h-4 w-4 text-emerald-400"}),s.name.includes("磁盘")&&e.jsx(z,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:255:62",className:"h-4 w-4 text-amber-400"}),s.name.includes("网络")&&e.jsx(ie,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:256:62",className:"h-4 w-4 text-purple-400"}),e.jsx("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:257:27",className:"font-medium text-slate-200",children:s.name})]}),e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:259:25",className:"flex items-center gap-1",children:[v(s.trend),e.jsx("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:261:27",className:`text-sm ${Z(s.trend)}`,children:s.trend==="up"?"上升":s.trend==="down"?"下降":"平稳"})]})]}),e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:267:23",className:"grid grid-cols-2 gap-4 mb-3",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:268:25",children:[e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:269:27",className:"text-xs text-slate-500 mb-1",children:"当前值"}),e.jsxs("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:270:27",className:"text-lg font-bold text-slate-100",children:[s.current,s.unit]})]}),e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:275:25",children:[e.jsxs("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:276:27",className:"text-xs text-slate-500 mb-1",children:["预测值 (",s.timeRange,")"]}),e.jsxs("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:277:27",className:`text-lg font-bold ${Z(s.trend)}`,children:[s.predicted,s.unit]})]})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:284:23",className:"flex items-center justify-between",children:e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:285:25",className:"flex items-center gap-2",children:[e.jsx("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:286:27",className:"text-xs text-slate-400",children:"置信度"}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:287:27",className:"w-16 h-1.5 bg-slate-700 rounded-full overflow-hidden",children:e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:288:29",className:"h-full bg-gradient-to-r from-blue-500 to-purple-500",style:{width:`${s.confidence}%`}})}),e.jsxs("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:293:27",className:"text-xs text-purple-400",children:[s.confidence,"%"]})]})})]},d))})})]})}),e.jsx(B,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:304:9",value:"capacity",className:"space-y-4",children:e.jsx(Pe,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:305:11",forecasts:n,loading:A})}),e.jsx(B,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:308:9",value:"anomaly",className:"space-y-4",children:e.jsxs(w,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:309:11",className:"bg-slate-800 border-slate-700",children:[e.jsx(K,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:310:13",className:"pb-3",children:e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:311:15",className:"flex items-center justify-between",children:[e.jsxs(H,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:312:17",className:"text-slate-100 flex items-center gap-2",children:[e.jsx(_,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:313:19",className:"h-5 w-5 text-red-400"}),"异常事件预测"]}),e.jsx("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:316:17",className:"text-xs text-slate-500",children:"基于告警规则阈值与实时趋势概率推算"})]})}),e.jsx(C,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:319:13",children:A?e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:321:17",className:"flex items-center justify-center py-12 text-slate-500",children:[e.jsx(D,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:322:19",className:"h-5 w-5 animate-spin mr-2"})," 加载异常预测..."]}):m.length===0?e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:325:17",className:"text-center py-12 text-slate-500",children:"暂无异常预测数据"}):e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:327:17",className:"space-y-3",children:m.map((s,d)=>e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:329:21",className:"p-4 rounded-lg border border-slate-700 bg-slate-800/50",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:330:23",className:"flex items-start justify-between",children:[e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:331:25",className:"flex items-start gap-3",children:[e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:332:27",className:`w-10 h-10 rounded-lg flex items-center justify-center ${s.probability>=70?"bg-red-500/20":s.probability>=50?"bg-amber-500/20":"bg-blue-500/20"}`,children:e.jsx(_,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:341:29",className:`h-5 w-5 ${s.probability>=70?"text-red-400":s.probability>=50?"text-amber-400":"text-blue-400"}`})}),e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:351:27",children:[e.jsx("h4",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:352:29",className:"font-medium text-slate-200",children:s.metric}),e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:353:29",className:"text-sm text-slate-400 mt-1",children:s.predictedAnomaly}),e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:354:29",className:"flex items-center gap-4 mt-2",children:[e.jsx("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:355:31",className:"text-xs text-slate-500",children:s.timeframe}),e.jsxs("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:356:31",className:"text-xs text-slate-500",children:["概率:"," ",e.jsxs("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:358:33",className:s.probability>=70?"text-red-400":"text-amber-400",children:[s.probability,"%"]})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:365:25",className:"w-16 h-16 relative shrink-0",children:[e.jsxs("svg",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:366:27",className:"w-full h-full transform -rotate-90",children:[e.jsx("circle",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:367:29",cx:"32",cy:"32",r:"28",stroke:"currentColor",strokeWidth:"4",fill:"transparent",className:"text-slate-700"}),e.jsx("circle",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:376:29",cx:"32",cy:"32",r:"28",stroke:"currentColor",strokeWidth:"4",fill:"transparent",strokeDasharray:`${s.probability*1.76} 176`,className:s.probability>=70?"text-red-400":s.probability>=50?"text-amber-400":"text-blue-400"})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:393:27",className:"absolute inset-0 flex items-center justify-center",children:e.jsxs("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:394:29",className:"text-sm font-bold text-slate-200",children:[s.probability,"%"]})})]})]}),e.jsx("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:398:23",className:"mt-3 p-3 bg-slate-900 rounded-lg border border-slate-700",children:e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:399:25",className:"flex items-start gap-2",children:[e.jsx(Y,{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:400:27",className:"h-4 w-4 text-emerald-400 mt-0.5"}),e.jsxs("div",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:401:27",children:[e.jsx("span",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:402:29",className:"text-sm text-slate-400",children:"建议操作:"}),e.jsx("p",{"code-path":"src/components/aiops/AIPredictiveAnalytics.tsx:403:29",className:"text-sm text-slate-300 mt-1",children:s.suggestedAction})]})]})})]},d))})})]})})]})]})}export{ze as AIPredictiveAnalytics}; diff --git a/backend/static/assets/AlertCenter-C3WMw6jA.js b/backend/static/assets/AlertCenter-C3WMw6jA.js new file mode 100644 index 0000000..068f131 --- /dev/null +++ b/backend/static/assets/AlertCenter-C3WMw6jA.js @@ -0,0 +1 @@ +import{g as Qe,j as e,w as Ze,T as te,$ as De,a3 as re,a8 as Xe,D as q,b as B,c as P,d as U,e as V,f as le,B as a,a9 as be,n as Ke,r as o,I as T,a as Ye,S as et,U as tt,a7 as rt}from"./index-DfyorCky.js";import{B as u}from"./badge-xNW8x0G1.js";import{C as y,a as w,b as Ne,c as ye}from"./card-C55cvSHg.js";import{S as ne,a as se,b as oe,c as ce,d as v}from"./select-D5qUzdAs.js";import{T as nt,a as st,b as M,c as F}from"./tabs-CIh_yD4s.js";import{S as ot}from"./switch-CGiGgOnh.js";import{t as m}from"./index-a3ybMjbR.js";import{a as D,b as z}from"./monitor-BAaBXIsC.js";import{a as K}from"./agent-DqqIRCQX.js";import{Z as ke}from"./zap-D2uWSK32.js";import{L as h}from"./label-BK0h2apY.js";import{A as ct}from"./AlertRuleDialog-DnF-_Zoj.js";import{T as at}from"./textarea-NXY8u32k.js";import{R as Y}from"./refresh-cw-DUB_tAG-.js";import{P as ee}from"./plus-CUG-9kpu.js";import"./index-CWVNW_qu.js";import"./message-square-DyxabBvb.js";import"./phone-DgvWDdJl.js";const lt=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]],Se=Qe("volume-x",lt);function it(r){return{id:String(r.id),title:r.rule_name||r.title||`告警 #${r.id}`,description:r.message||r.description||"",severity:r.severity||"info",status:r.status||"firing",source:r.target||r.source||"",service:r.service||"",metric:r.metric||"",value:r.value||0,threshold:r.threshold||0,startedAt:r.started_at||r.startedAt||r.created_at||new Date().toISOString(),resolvedAt:r.resolved_at||r.resolvedAt,labels:typeof r.labels=="string"?(()=>{try{return JSON.parse(r.labels||"{}")}catch{return{}}})():r.labels||{},annotations:typeof r.annotations=="string"?(()=>{try{return JSON.parse(r.annotations||"{}")}catch{return{}}})():r.annotations||{}}}function ae(r){switch(r){case"critical":return e.jsxs(u,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:106:14",variant:"destructive",className:"gap-1",children:[e.jsx(De,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:106:61",className:"w-3 h-3"}),"严重"]});case"warning":return e.jsxs(u,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:108:14",variant:"default",className:"bg-orange-500 gap-1",children:[e.jsx(te,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:108:71",className:"w-3 h-3"}),"警告"]});case"info":return e.jsxs(u,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:110:14",variant:"default",className:"bg-blue-500 gap-1",children:[e.jsx(Ze,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:110:69",className:"w-3 h-3"}),"信息"]});default:return e.jsx(u,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:112:14",variant:"secondary",children:"未知"})}}function mt(r){switch(r){case"firing":return e.jsxs(u,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:120:14",variant:"destructive",className:"gap-1 animate-pulse",children:[e.jsx(ke,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:120:75",className:"w-3 h-3"}),"触发中"]});case"acknowledged":return e.jsxs(u,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:122:14",variant:"default",className:"bg-yellow-500 gap-1",children:[e.jsx(Xe,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:122:71",className:"w-3 h-3"}),"已确认"]});case"resolved":return e.jsxs(u,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:124:14",variant:"default",className:"bg-green-500 gap-1",children:[e.jsx(re,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:124:70",className:"w-3 h-3"}),"已解决"]});case"suppressed":return e.jsxs(u,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:126:14",variant:"secondary",className:"gap-1",children:[e.jsx(Se,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:126:59",className:"w-3 h-3"}),"已静默"]});default:return e.jsx(u,{"code-path":"src/components/monitor/alert-center/alert-center-helpers.tsx:128:14",variant:"secondary",children:"未知"})}}function dt(r){return{dingtalk:"钉钉",wechat:"企业微信",feishu:"飞书",email:"邮件",sms:"短信",webhook:"Webhook"}[r]||r}function pt({alert:r,open:C,onOpenChange:c,onAcknowledge:A}){return e.jsx(q,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:22:5",open:C,onOpenChange:c,children:e.jsxs(B,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:23:7",className:"max-w-3xl",children:[e.jsxs(P,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:24:9",children:[e.jsxs(U,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:25:11",className:"flex items-center gap-2",children:[r?.title,r&&ae(r.severity)]}),e.jsx(V,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:29:11",className:"sr-only",children:"查看告警详情"})]}),r&&e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:32:11",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:33:13",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:34:15",className:"text-muted-foreground",children:"描述"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:35:15",className:"mt-1",children:r.description})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:37:13",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:38:15",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:39:17",className:"text-muted-foreground",children:"来源"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:40:17",className:"font-medium",children:r.source})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:42:15",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:43:17",className:"text-muted-foreground",children:"服务"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:44:17",className:"font-medium",children:r.service})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:46:15",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:47:17",className:"text-muted-foreground",children:"指标"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:48:17",className:"font-medium",children:r.metric})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:50:15",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:51:17",className:"text-muted-foreground",children:"当前值 / 阈值"}),e.jsxs("p",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:52:17",className:"font-medium",children:[r.value," / ",r.threshold]})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:54:15",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:55:17",className:"text-muted-foreground",children:"开始时间"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:56:17",className:"font-medium",children:r.startedAt})]}),r.resolvedAt&&e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:59:17",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:60:19",className:"text-muted-foreground",children:"解决时间"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:61:19",className:"font-medium",children:r.resolvedAt})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:65:13",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:66:15",className:"text-muted-foreground",children:"标签"}),e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:67:15",className:"flex flex-wrap gap-2 mt-1",children:Object.entries(r.labels).map(([j,x])=>e.jsxs(u,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:69:19",variant:"outline",children:[j,"=",x]},j))})]}),r.runbookUrl&&e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:74:15",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:75:17",className:"text-muted-foreground",children:"处理手册"}),e.jsx("a",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:76:17",href:r.runbookUrl,target:"_blank",rel:"noopener noreferrer",className:"text-blue-500 hover:underline block mt-1",children:"查看处理手册 →"})]})]}),e.jsxs(le,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:83:9",children:[e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:84:11",variant:"outline",onClick:()=>c(!1),children:"关闭"}),r?.status==="firing"&&e.jsxs(a,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:86:13",onClick:()=>{A(r.id),c(!1)},children:[e.jsx(be,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:87:15",className:"w-4 h-4 mr-2"}),"确认告警"]})]})]})})}function xt({alert:r,open:C,onOpenChange:c,onSilence:A}){return e.jsx(q,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:109:5",open:C,onOpenChange:c,children:e.jsxs(B,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:110:7",children:[e.jsxs(P,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:111:9",children:[e.jsx(U,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:112:11",children:"静默告警"}),e.jsx(V,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:113:11",children:"选择静默持续时间"})]}),e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:115:9",className:"space-y-2",children:["1h","4h","8h","24h","7d"].map(j=>e.jsxs(a,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:117:13",variant:"outline",className:"w-full justify-between",onClick:()=>r&&A(r.id,j),children:[e.jsxs("span",{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:123:15",children:["静默 ",j]}),e.jsx(Ke,{"code-path":"src/components/monitor/alert-center/AlertCenterDetail.tsx:124:15",className:"w-4 h-4"})]},j))})]})})}const we=[{value:"feishu",label:"飞书",placeholder:"https://open.feishu.cn/open-apis/bot/v2/hook/..."},{value:"dingtalk",label:"钉钉",placeholder:"https://oapi.dingtalk.com/robot/send?access_token=..."},{value:"wechat",label:"企业微信",placeholder:"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=..."},{value:"webhook",label:"自定义Webhook",placeholder:"https://your-webhook-url..."}];function ht({open:r,onOpenChange:C,editingContact:c,onSaved:A}){const[j,x]=o.useState("feishu"),[i,g]=o.useState({name:"",phone:"",email:"",webhook_url:""}),[b,f]=o.useState(!1);o.useEffect(()=>{r&&(c?(x(c.channel_type||"feishu"),g({name:c.name||"",phone:c.phone||"",email:c.email||"",webhook_url:c.webhook_url||""})):(x("feishu"),g({name:"",phone:"",email:"",webhook_url:""})))},[r,c]);const G=async()=>{if(!(!i.name.trim()||!i.webhook_url.trim())){f(!0);try{const d={name:i.name.trim(),phone:i.phone.trim()||void 0,email:i.email.trim()||void 0,channel_type:j,webhook_url:i.webhook_url.trim()};c?(await D.updateContact(c.id,d),m.success("联系人已更新")):(await D.createContact(d),m.success("联系人已添加")),C(!1),A()}catch{m.error("保存失败")}finally{f(!1)}}},l=we.find(d=>d.value===j);return e.jsx(q,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:85:5",open:r,onOpenChange:C,children:e.jsxs(B,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:86:7",children:[e.jsxs(P,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:87:9",children:[e.jsx(U,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:88:11",children:c?"编辑报警联系人":"添加报警联系人"}),e.jsx(V,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:89:11",children:"选择通知渠道并填入 Webhook 地址"})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:91:9",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:92:11",className:"space-y-2",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:93:13",children:"姓名 *"}),e.jsx(T,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:94:13",value:i.name,onChange:d=>g({...i,name:d.target.value}),placeholder:"如:张三"})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:100:11",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:101:13",className:"space-y-2",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:102:15",children:"手机号"}),e.jsx(T,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:103:15",value:i.phone,onChange:d=>g({...i,phone:d.target.value}),placeholder:"13800138000"})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:109:13",className:"space-y-2",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:110:15",children:"邮箱"}),e.jsx(T,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:111:15",value:i.email,onChange:d=>g({...i,email:d.target.value}),placeholder:"zhangsan@example.com"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:118:11",className:"space-y-2",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:119:13",children:"渠道类型 *"}),e.jsxs(ne,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:120:13",value:j,onValueChange:x,children:[e.jsx(se,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:121:15",children:e.jsx(oe,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:122:17",placeholder:"选择渠道类型"})}),e.jsx(ce,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:124:15",children:we.map(d=>e.jsx(v,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:126:19",value:d.value,children:d.label},d.value))})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:131:11",className:"space-y-2",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:132:13",children:"Webhook URL *"}),e.jsx(T,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:133:13",value:i.webhook_url,onChange:d=>g({...i,webhook_url:d.target.value}),placeholder:l?.placeholder||"https://...",className:"font-mono text-xs"})]})]}),e.jsxs(le,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:141:9",children:[e.jsx(a,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:142:11",variant:"outline",onClick:()=>C(!1),children:"取消"}),e.jsx(a,{"code-path":"src/components/monitor/alert-center/ContactDialog.tsx:143:11",onClick:G,disabled:!i.name.trim()||!i.webhook_url.trim()||b,children:b?"保存中...":c?"保存修改":"添加联系人"})]})]})})}function ut({open:r,onOpenChange:C,editingGroup:c,contacts:A,onSaved:j}){const[x,i]=o.useState({group_name:"",notes:"",contact_ids:[]}),[g,b]=o.useState(!1);o.useEffect(()=>{if(r)if(c){let l=[];try{l=JSON.parse(c.contact_ids||"[]")}catch{}i({group_name:c.group_name||"",notes:c.notes||"",contact_ids:l})}else i({group_name:"",notes:"",contact_ids:[]})},[r,c]);const f=l=>{i(d=>({...d,contact_ids:d.contact_ids.includes(l)?d.contact_ids.filter(S=>S!==l):[...d.contact_ids,l]}))},G=async()=>{if(x.group_name.trim()){b(!0);try{const l={group_name:x.group_name.trim(),notes:x.notes.trim()||void 0,contact_ids:x.contact_ids};c?(await D.updateContactGroup(c.id,l),m.success("联系组已更新")):(await D.createContactGroup(l),m.success("联系组已添加")),C(!1),j()}catch{m.error("保存失败")}finally{b(!1)}}};return e.jsx(q,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:84:5",open:r,onOpenChange:C,children:e.jsxs(B,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:85:7",children:[e.jsxs(P,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:86:9",children:[e.jsx(U,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:87:11",children:c?"编辑报警联系组":"添加报警联系组"}),e.jsx(V,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:88:11",children:"配置报警联系组,选择组内成员"})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:90:9",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:91:11",className:"space-y-2",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:92:13",children:"组名称 *"}),e.jsx(T,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:93:13",value:x.group_name,onChange:l=>i({...x,group_name:l.target.value}),placeholder:"如:运维值班组"})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:99:11",className:"space-y-2",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:100:13",children:"备注"}),e.jsx(at,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:101:13",value:x.notes,onChange:l=>i({...x,notes:l.target.value}),placeholder:"如:周一至周五 9:00-21:00",rows:2})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:108:11",className:"space-y-2",children:[e.jsx(h,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:109:13",children:"选择联系人"}),A.length===0?e.jsx("p",{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:111:15",className:"text-xs text-muted-foreground",children:"暂无联系人,请先在「报警联系人」标签页添加"}):e.jsx("div",{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:113:15",className:"flex flex-wrap gap-1.5 max-h-[180px] overflow-y-auto border rounded-md p-2",children:A.map(l=>e.jsxs(u,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:115:19",variant:x.contact_ids.includes(l.id)?"default":"outline",className:"cursor-pointer text-xs",onClick:()=>f(l.id),children:[l.name,x.contact_ids.includes(l.id)&&" ✓"]},l.id))}),x.contact_ids.length>0&&e.jsxs("p",{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:128:15",className:"text-xs text-muted-foreground",children:["已选择 ",x.contact_ids.length," 位联系人"]})]})]}),e.jsxs(le,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:132:9",children:[e.jsx(a,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:133:11",variant:"outline",onClick:()=>C(!1),children:"取消"}),e.jsx(a,{"code-path":"src/components/monitor/alert-center/ContactGroupDialog.tsx:134:11",onClick:G,disabled:!x.group_name.trim()||g,children:g?"保存中...":c?"保存修改":"添加联系组"})]})]})})}const zt=()=>{const r=Ye(),[C,c]=o.useState([]),[A,j]=o.useState([]),[x,i]=o.useState(!1),[g,b]=o.useState(""),[f,G]=o.useState("all"),[l,d]=o.useState("all"),[S,_e]=o.useState("alerts"),[ie,me]=o.useState(null),[Te,de]=o.useState(!1),[Ge,W]=o.useState(!1),[N,Oe]=o.useState({firing:0,critical:0,warning:0,resolved:0}),[Re,J]=o.useState(!1),[ze,H]=o.useState(null),[pe,xe]=o.useState(!1),[L,Le]=o.useState([]),[he,Ee]=o.useState([]),[$e,Q]=o.useState(!1),[Ie,ue]=o.useState(null),[Me,Z]=o.useState(!1),[Fe,Ce]=o.useState(null),[k,E]=o.useState(1),[je]=o.useState(10),[X,qe]=o.useState(0),_=Math.max(1,Math.ceil(X/je));o.useEffect(()=>{ge(),S==="contacts"&&$(),S==="groups"&&($(),I());const t=setInterval(ge,3e4);return()=>clearInterval(t)},[k,f,l,S]);const ge=async()=>{await Promise.all([O(),R()])},O=async()=>{i(!0);try{const t=await z.getAlerts({page:k,page_size:je,severity:f!=="all"?f:void 0,status:l!=="all"?l:void 0}),s=(t.list||t.data?.list||[]).map(it);c(s),qe(t.total||t.data?.total||s.length),Oe({firing:s.filter(p=>p.status==="firing").length,critical:s.filter(p=>p.severity==="critical"&&p.status==="firing").length,warning:s.filter(p=>p.severity==="warning"&&p.status==="firing").length,resolved:s.filter(p=>p.status==="resolved").length})}catch{m.error("获取告警失败")}finally{i(!1)}},R=async()=>{try{const t=await K.listRules(),n=Array.isArray(t)?t:t.list||[];j(n.map(s=>({id:s.id,name:s.name,description:`${s.metric} ${s.operator} ${s.threshold}%`,enabled:s.enabled,severity:"warning",type:s.metric,hostname:s.hostname||"全部主机",threshold:s.threshold})))}catch{m.error("获取告警规则失败")}},$=async()=>{try{const t=await D.getContacts();Le(t?.data?.list||t?.list||[])}catch{}},I=async()=>{try{const t=await D.getContactGroups();Ee(t?.data?.list||t?.list||[])}catch{}},Ae=async t=>{try{await z.acknowledge(t),m.success("告警已确认"),O()}catch{m.error("操作失败")}},Be=async t=>{try{await z.resolve(t),m.success("告警已解决"),O()}catch{m.error("操作失败")}},Pe=async(t,n)=>{try{await z.silence(t,n),m.success("告警已静默"),W(!1),O()}catch{m.error("操作失败")}},Ue=async(t,n)=>{try{await K.updateRule(Number(t),{enabled:n}),j(A.map(s=>String(s.id)===t?{...s,enabled:n}:s)),m.success("规则状态已更新")}catch{m.error("更新失败")}},Ve=()=>{H(null),J(!0)},We=t=>{H(t),J(!0)},fe=()=>{J(!1),H(null)},Je=async()=>{if(await r({title:"一键报警",description:"为 Agent 在线主机创建 CPU(>80%)/内存(>80%)/磁盘(>90%)/TIME_WAIT(>15000)/CLOSE_WAIT(>200)/进程检测 6 条告警规则。",confirmText:"确认创建"})){xe(!0);try{const n=await z.quickSetup("ecs");m.success(typeof n=="string"?n:n?.message||"默认告警规则创建成功"),R()}catch{m.error("创建失败,请检查 Agent 主机是否在线")}finally{xe(!1)}}},He=async t=>{if(await r({title:"删除规则",description:`确定删除规则「${t.name}」?`,confirmText:"删除",variant:"destructive"}))try{await K.deleteRule(Number(t.id)),m.success("已删除"),R()}catch{m.error("删除失败")}},ve=(t,n)=>{t==="severity"?G(n):d(n),E(1)};return e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:207:5",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:209:7",className:"grid grid-cols-4 gap-3",children:[e.jsx(y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:210:9",className:N.firing>0?"border-red-500 border-2":"",children:e.jsx(w,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:211:11",className:"p-3",children:e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:212:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:213:15",children:[e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:214:17",className:"text-xs text-muted-foreground",children:"触发中"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:215:17",className:`text-xl font-bold ${N.firing>0?"text-red-600":""}`,children:N.firing})]}),e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:217:15",className:`p-2 rounded-md ${N.firing>0?"bg-red-100":"bg-gray-100"}`,children:e.jsx(ke,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:218:17",className:`w-4 h-4 ${N.firing>0?"text-red-600":"text-gray-600"}`})})]})})}),e.jsx(y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:223:9",children:e.jsx(w,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:224:11",className:"p-3",children:e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:225:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:226:15",children:[e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:227:17",className:"text-xs text-muted-foreground",children:"严重告警"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:228:17",className:"text-xl font-bold text-red-600",children:N.critical})]}),e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:230:15",className:"p-2 bg-red-100 rounded-md",children:e.jsx(De,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:231:17",className:"w-4 h-4 text-red-600"})})]})})}),e.jsx(y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:236:9",children:e.jsx(w,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:237:11",className:"p-3",children:e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:238:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:239:15",children:[e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:240:17",className:"text-xs text-muted-foreground",children:"警告告警"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:241:17",className:"text-xl font-bold text-orange-600",children:N.warning})]}),e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:243:15",className:"p-2 bg-orange-100 rounded-md",children:e.jsx(te,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:244:17",className:"w-4 h-4 text-orange-600"})})]})})}),e.jsx(y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:249:9",children:e.jsx(w,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:250:11",className:"p-3",children:e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:251:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:252:15",children:[e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:253:17",className:"text-xs text-muted-foreground",children:"今日已解决"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:254:17",className:"text-xl font-bold text-green-600",children:N.resolved})]}),e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:256:15",className:"p-2 bg-green-100 rounded-md",children:e.jsx(re,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:257:17",className:"w-4 h-4 text-green-600"})})]})})})]}),e.jsxs(nt,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:264:7",value:S,onValueChange:_e,children:[e.jsxs(st,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:265:9",className:"grid w-full grid-cols-4 lg:w-[480px] h-9",children:[e.jsx(M,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:266:11",value:"alerts",className:"text-xs",children:"告警列表"}),e.jsx(M,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:267:11",value:"rules",className:"text-xs",children:"告警规则"}),e.jsx(M,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:268:11",value:"contacts",className:"text-xs",children:"报警联系人"}),e.jsx(M,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:269:11",value:"groups",className:"text-xs",children:"报警联系组"})]}),e.jsxs(F,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:273:9",value:"alerts",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:274:11",className:"flex flex-wrap items-center justify-between gap-2",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:275:13",className:"flex items-center gap-2 flex-1 min-w-[280px]",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:276:15",className:"relative flex-1",children:[e.jsx(et,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:277:17",className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground"}),e.jsx(T,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:278:17",placeholder:"搜索告警...",value:g,onChange:t=>b(t.target.value),className:"pl-8 h-8 text-xs"})]}),e.jsxs(ne,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:285:15",value:f,onValueChange:t=>ve("severity",t),children:[e.jsx(se,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:286:17",className:"w-[100px] h-8 text-xs",children:e.jsx(oe,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:287:19",placeholder:"级别"})}),e.jsxs(ce,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:289:17",children:[e.jsx(v,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:290:19",value:"all",children:"全部级别"}),e.jsx(v,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:291:19",value:"critical",children:"严重"}),e.jsx(v,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:292:19",value:"warning",children:"警告"}),e.jsx(v,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:293:19",value:"info",children:"信息"})]})]}),e.jsxs(ne,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:296:15",value:l,onValueChange:t=>ve("status",t),children:[e.jsx(se,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:297:17",className:"w-[100px] h-8 text-xs",children:e.jsx(oe,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:298:19",placeholder:"状态"})}),e.jsxs(ce,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:300:17",children:[e.jsx(v,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:301:19",value:"all",children:"全部状态"}),e.jsx(v,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:302:19",value:"firing",children:"触发中"}),e.jsx(v,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:303:19",value:"acknowledged",children:"已确认"}),e.jsx(v,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:304:19",value:"resolved",children:"已解决"})]})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:308:13",className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsxs("span",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:309:15",children:["共 ",X," 条"]}),e.jsxs(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:310:15",variant:"outline",size:"sm",onClick:O,className:"h-7 text-xs px-2",children:[e.jsx(Y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:311:17",className:"w-3 h-3 mr-1"}),"刷新"]})]})]}),e.jsx(y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:317:11",children:e.jsxs(w,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:318:13",className:"p-0",children:[e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:319:15",className:"overflow-x-auto",children:e.jsxs("table",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:320:17",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:321:19",className:"bg-muted/50",children:e.jsxs("tr",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:322:21",children:[e.jsx("th",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:323:23",className:"px-3 py-2 text-left text-xs font-medium",children:"告警信息"}),e.jsx("th",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:324:23",className:"px-3 py-2 text-left text-xs font-medium w-16",children:"级别"}),e.jsx("th",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:325:23",className:"px-3 py-2 text-left text-xs font-medium w-16",children:"状态"}),e.jsx("th",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:326:23",className:"px-3 py-2 text-left text-xs font-medium w-24",children:"来源"}),e.jsx("th",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:327:23",className:"px-3 py-2 text-left text-xs font-medium w-20",children:"持续"}),e.jsx("th",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:328:23",className:"px-3 py-2 text-left text-xs font-medium w-28",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:331:19",className:"divide-y",children:x?e.jsx("tr",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:333:23",children:e.jsx("td",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:333:27",colSpan:6,className:"px-3 py-6 text-center text-xs text-muted-foreground",children:"加载中..."})}):C.length===0?e.jsx("tr",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:335:23",children:e.jsx("td",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:335:27",colSpan:6,className:"px-3 py-6 text-center text-xs text-muted-foreground",children:"暂无告警"})}):C.filter(t=>{if(!g)return!0;const n=g.toLowerCase();return t.title.toLowerCase().includes(n)||t.description.toLowerCase().includes(n)||t.source.toLowerCase().includes(n)}).map(t=>e.jsxs("tr",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:345:25",className:"hover:bg-muted/50",children:[e.jsxs("td",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:346:27",className:"px-3 py-2",children:[e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:347:29",className:"font-medium text-xs",children:t.title}),e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:348:29",className:"text-xs text-muted-foreground line-clamp-1",children:t.description}),e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:349:29",className:"flex gap-1 mt-0.5",children:Object.entries(t.labels).slice(0,2).map(([n,s])=>e.jsxs(u,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:351:33",variant:"outline",className:"text-[10px] px-1 py-0",children:[n,"=",s]},n))})]}),e.jsx("td",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:355:27",className:"px-3 py-2",children:ae(t.severity)}),e.jsx("td",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:356:27",className:"px-3 py-2",children:mt(t.status)}),e.jsxs("td",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:357:27",className:"px-3 py-2 text-xs",children:[e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:358:29",children:t.source}),e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:359:29",className:"text-muted-foreground text-[10px]",children:t.service})]}),e.jsx("td",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:361:27",className:"px-3 py-2 text-xs text-muted-foreground",children:t.status==="resolved"&&t.resolvedAt?`${Math.floor((new Date(t.resolvedAt).getTime()-new Date(t.startedAt).getTime())/6e4)}分`:`${Math.floor((Date.now()-new Date(t.startedAt).getTime())/6e4)}分`}),e.jsx("td",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:366:27",className:"px-3 py-2",children:e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:367:29",className:"flex items-center gap-0.5",children:[e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:368:31",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{me(t),de(!0)},children:e.jsx(tt,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:370:33",className:"w-3.5 h-3.5"})}),t.status==="firing"&&e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:373:33",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>Ae(t.id),children:e.jsx(be,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:375:35",className:"w-3.5 h-3.5 text-blue-600"})}),(t.status==="firing"||t.status==="acknowledged")&&e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:379:33",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>Be(t.id),children:e.jsx(re,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:381:35",className:"w-3.5 h-3.5 text-green-600"})}),e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:384:31",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>{me(t),W(!0)},children:e.jsx(Se,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:386:33",className:"w-3.5 h-3.5 text-orange-600"})})]})})]},t.id))})]})}),_>1&&e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:398:17",className:"flex items-center justify-between px-3 py-2 border-t text-xs",children:[e.jsxs("span",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:399:19",className:"text-muted-foreground",children:["第 ",k,"/",_," 页,共 ",X," 条"]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:400:19",className:"flex items-center gap-1",children:[e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:401:21",variant:"outline",size:"sm",className:"h-7 text-xs px-2",disabled:k<=1,onClick:()=>E(t=>t-1),children:"上一页"}),Array.from({length:Math.min(_,5)},(t,n)=>{const p=Math.max(1,Math.min(k-2,_-4))+n;return p>_?null:e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:410:25",variant:p===k?"default":"outline",size:"sm",className:"h-7 min-w-[28px] text-xs px-1",onClick:()=>E(p),children:p},p)}),e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:417:21",variant:"outline",size:"sm",className:"h-7 text-xs px-2",disabled:k>=_,onClick:()=>E(t=>t+1),children:"下一页"})]})]})]})})]}),e.jsxs(F,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:429:9",value:"rules",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:430:11",className:"flex justify-between items-center",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:431:13",className:"flex items-center gap-2",children:[e.jsxs(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:432:15",onClick:Ve,children:[e.jsx(ee,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:433:17",className:"w-4 h-4 mr-1"}),"添加规则"]}),e.jsxs(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:435:15",variant:"secondary",onClick:Je,disabled:pe,children:[e.jsx(rt,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:436:17",className:"w-4 h-4 mr-1"}),pe?"创建中…":"一键报警"]})]}),e.jsxs(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:440:13",variant:"outline",onClick:R,children:[e.jsx(Y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:441:15",className:"w-4 h-4 mr-2"}),"刷新"]})]}),A.length===0?e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:446:13",className:"text-center py-12 text-muted-foreground",children:[e.jsx(te,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:447:15",className:"w-10 h-10 mx-auto mb-2 opacity-50"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:448:15",className:"text-sm",children:"暂无告警规则"}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:449:15",className:"text-xs mt-1",children:"点击「添加规则」或「一键报警」快速创建"})]}):e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:452:11",className:"grid grid-cols-1 gap-4",children:A.map(t=>e.jsx(y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:454:15",children:e.jsx(w,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:455:17",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:456:19",className:"flex items-start justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:457:21",className:"flex-1",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:458:23",className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:459:25",className:"font-medium",children:t.name}),ae(t.severity),e.jsx(u,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:461:25",variant:t.enabled?"default":"secondary",children:t.enabled?"已启用":"已禁用"})]}),e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:465:23",className:"text-sm text-muted-foreground mb-2",children:t.description}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:466:23",className:"flex items-center gap-4 text-xs text-muted-foreground",children:[t.expression&&e.jsx("span",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:468:27",className:"font-mono bg-muted px-2 py-1 rounded",children:t.expression}),t.duration?e.jsxs("span",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:470:42",children:["持续 ",t.duration,"秒"]}):null]}),(()=>{let n=[];try{const s=t.notify_channels;s&&(n=Array.isArray(s)?s:JSON.parse(s))}catch{}return n.length?e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:480:27",className:"flex gap-1 mt-2",children:n.map(s=>e.jsx(u,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:482:31",variant:"outline",className:"text-xs",children:s},s))}):null})()]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:488:21",className:"flex items-center gap-2",children:[e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:489:23",variant:"ghost",size:"sm",onClick:()=>We(t),children:"编辑"}),e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:490:23",variant:"ghost",size:"sm",className:"text-red-400",onClick:()=>He(t),children:"删除"}),e.jsx(ot,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:491:23",checked:t.enabled,onCheckedChange:n=>Ue(String(t.id),n)})]})]})})},t.id))})]}),e.jsxs(F,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:505:9",value:"contacts",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:506:13",className:"flex justify-between items-center",children:[e.jsx("h3",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:507:15",className:"text-sm font-medium",children:"报警联系人"}),e.jsxs(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:508:15",size:"sm",onClick:()=>{ue(null),Q(!0)},children:[e.jsx(ee,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:509:17",className:"w-4 h-4 mr-1"}),"添加联系人"]})]}),L.length===0?e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:514:15",className:"text-center py-8 text-muted-foreground border border-dashed rounded-lg text-xs",children:"暂无报警联系人,点击「添加联系人」创建"}):e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:518:15",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:L.map(t=>e.jsxs(y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:520:19",className:"hover:border-primary/50 transition-colors",children:[e.jsx(Ne,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:521:21",className:"pb-2",children:e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:522:23",className:"flex items-start justify-between",children:e.jsx(ye,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:523:25",className:"text-sm",children:t.name})})}),e.jsxs(w,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:526:21",className:"pt-0 space-y-1 text-xs text-muted-foreground",children:[t.phone&&e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:527:35",children:["📱 ",t.phone]}),t.email&&e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:528:35",children:["📧 ",t.email]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:529:23",className:"flex gap-1 flex-wrap",children:[t.channel_type&&e.jsx(u,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:531:27",variant:"outline",className:"text-[10px]",children:dt(t.channel_type)}),t.webhook_url&&e.jsx("span",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:536:27",className:"text-[10px] text-muted-foreground truncate max-w-[200px]",title:t.webhook_url,children:t.webhook_url})]}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:541:23",className:"flex gap-1.5 pt-1.5",children:[e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:542:25",variant:"outline",size:"sm",className:"h-7 text-xs flex-1",onClick:()=>{ue(t),Q(!0)},children:"编辑"}),e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:546:25",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:async()=>{if(await r({title:"删除联系人",description:`确定删除「${t.name}」?`,confirmText:"删除",variant:"destructive"}))try{await D.deleteContact(t.id),m.success("已删除"),$()}catch{m.error("删除失败")}},children:"删除"})]})]})]},t.id))})]}),e.jsxs(F,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:564:9",value:"groups",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:565:11",className:"flex justify-between items-center",children:[e.jsxs(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:566:13",variant:"outline",onClick:I,children:[e.jsx(Y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:567:15",className:"w-4 h-4 mr-2"}),"刷新"]}),e.jsxs(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:570:13",onClick:()=>{Ce(null),Z(!0)},children:[e.jsx(ee,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:571:15",className:"w-4 h-4 mr-2"}),"添加联系组"]})]}),he.length===0?e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:576:13",className:"text-center py-16 text-muted-foreground border border-dashed rounded-lg",children:"暂无报警联系组,点击「添加联系组」创建"}):e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:580:13",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:he.map(t=>{let n=[];try{n=JSON.parse(t.contact_ids||"[]")}catch{}const s=L.filter(p=>n.includes(p.id)).map(p=>p.name);return e.jsxs(y,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:588:19",className:"hover:border-primary/50 transition-colors",children:[e.jsx(Ne,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:589:21",children:e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:590:23",className:"flex items-start justify-between",children:[e.jsx(ye,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:591:25",className:"text-base",children:t.group_name}),e.jsxs(u,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:592:25",variant:"secondary",children:[n.length," 人"]})]})}),e.jsxs(w,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:595:21",className:"pt-0 space-y-2",children:[t.notes&&e.jsx("p",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:596:35",className:"text-sm text-muted-foreground",children:t.notes}),e.jsx("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:597:23",className:"flex flex-wrap gap-1",children:s.map(p=>e.jsx(u,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:599:27",variant:"outline",className:"text-xs",children:p},p))}),e.jsxs("div",{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:602:23",className:"flex gap-2 pt-2",children:[e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:603:25",variant:"outline",size:"sm",className:"flex-1",onClick:()=>{Ce(t),Z(!0)},children:"编辑"}),e.jsx(a,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:607:25",variant:"outline",size:"sm",onClick:async()=>{if(await r({title:"删除联系组",description:`确定删除联系组「${t.group_name}」?`,confirmText:"删除",variant:"destructive"}))try{await D.deleteContactGroup(t.id),m.success("已删除"),I()}catch{m.error("删除失败")}},children:"删除"})]})]})]},t.id)})})]})]}),e.jsx(pt,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:626:7",alert:ie,open:Te,onOpenChange:de,onAcknowledge:Ae}),e.jsx(xt,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:632:7",alert:ie,open:Ge,onOpenChange:W,onSilence:Pe}),e.jsx(ct,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:638:7",open:Re,onOpenChange:fe,editingRule:ze,notifyChannels:[],onSaved:()=>{fe(),R()}}),e.jsx(ht,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:645:7",open:$e,onOpenChange:Q,editingContact:Ie,onSaved:$}),e.jsx(ut,{"code-path":"src/components/monitor/alert-center/AlertCenter.tsx:651:7",open:Me,onOpenChange:Z,editingGroup:Fe,contacts:L,onSaved:()=>{I()}})]})};export{zt as default}; diff --git a/backend/static/assets/AlertManager-BaUrn6Bk.js b/backend/static/assets/AlertManager-BaUrn6Bk.js new file mode 100644 index 0000000..94ca5a5 --- /dev/null +++ b/backend/static/assets/AlertManager-BaUrn6Bk.js @@ -0,0 +1 @@ +import{a as _,r as l,j as e,S as ee,I as Y,L as O,B as A,a3 as $,J,T as z,E as Q,D as te,b as se,c as oe,d as ae,e as ne,f as re,x as ce}from"./index-DfyorCky.js";import{C as w,a as M,b as le,c as ie,d as me}from"./card-C55cvSHg.js";import{T as de,a as xe,b as H,c as I}from"./tabs-CIh_yD4s.js";import{a as g}from"./monitor-BAaBXIsC.js";import{B as f}from"./badge-xNW8x0G1.js";import{T as X,a as V,b as E,c as i,d as q,e as c}from"./table-5sHV4Akp.js";import{S as B}from"./switch-CGiGgOnh.js";import{C as G}from"./checkbox-CH0bpj6b.js";import{t as R}from"./index-a3ybMjbR.js";import{r as pe,g as he,C as K,A as ge}from"./AlertRuleDialog-DnF-_Zoj.js";import{T as P}from"./trash-2-Dx32pOzT.js";import{L as D}from"./label-BK0h2apY.js";import{T as be}from"./textarea-NXY8u32k.js";import{P as U}from"./plus-CUG-9kpu.js";import{R as Ae,C as je,X as ue,Y as Ne,T as ve}from"./generateCategoricalChart-6v9BPbG2.js";import{A as fe,a as W}from"./AreaChart-B2zlWfdX.js";import"./index-CWVNW_qu.js";import"./message-square-DyxabBvb.js";import"./phone-DgvWDdJl.js";function Te({alerts:m,loading:T,onReload:d}){_();const[p,u]=l.useState(""),[o,h]=l.useState("all"),[b,C]=l.useState("all"),j=m.filter(t=>{const r=(t.rule&&t.rule.name||t.message||"").toLowerCase().includes(p.toLowerCase())||(t.target||"").toLowerCase().includes(p.toLowerCase()),N=o==="all"||t.severity===o,v=b==="all"||t.status===b;return r&&N&&v}),y=t=>{switch(t){case"critical":return e.jsxs(f,{"code-path":"src/components/monitor/AlertEventsTab.tsx:45:11",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10",children:[e.jsx(z,{"code-path":"src/components/monitor/AlertEventsTab.tsx:46:13",className:"h-3 w-3 mr-1"}),"严重"]});case"warning":return e.jsxs(f,{"code-path":"src/components/monitor/AlertEventsTab.tsx:52:11",variant:"outline",className:"border-amber-500/30 text-amber-400 bg-amber-500/10",children:[e.jsx(z,{"code-path":"src/components/monitor/AlertEventsTab.tsx:53:13",className:"h-3 w-3 mr-1"}),"警告"]});case"info":return e.jsxs(f,{"code-path":"src/components/monitor/AlertEventsTab.tsx:59:11",variant:"outline",className:"border-blue-500/30 text-blue-400 bg-blue-500/10",children:[e.jsx(J,{"code-path":"src/components/monitor/AlertEventsTab.tsx:60:13",className:"h-3 w-3 mr-1"}),"提示"]});default:return null}},a=t=>{switch(t){case"firing":return e.jsx(f,{"code-path":"src/components/monitor/AlertEventsTab.tsx:73:11",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10 animate-pulse",children:"触发中"});case"resolved":return e.jsx(f,{"code-path":"src/components/monitor/AlertEventsTab.tsx:79:11",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:"已恢复"});default:return null}},x=async t=>{try{await g.acknowledge(t),d()}catch(r){console.error("Failed to acknowledge alert:",r)}};return e.jsxs("div",{"code-path":"src/components/monitor/AlertEventsTab.tsx:98:5",className:"mt-4 space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertEventsTab.tsx:100:7",className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertEventsTab.tsx:101:9",className:"relative w-64",children:[e.jsx(ee,{"code-path":"src/components/monitor/AlertEventsTab.tsx:102:11",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(Y,{"code-path":"src/components/monitor/AlertEventsTab.tsx:103:11",placeholder:"搜索告警名称或目标...",value:p,onChange:t=>u(t.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"})]}),e.jsxs("select",{"code-path":"src/components/monitor/AlertEventsTab.tsx:110:9",value:o,onChange:t=>h(t.target.value),className:"h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm",children:[e.jsx("option",{"code-path":"src/components/monitor/AlertEventsTab.tsx:115:11",value:"all",children:"全部级别"}),e.jsx("option",{"code-path":"src/components/monitor/AlertEventsTab.tsx:116:11",value:"critical",children:"严重"}),e.jsx("option",{"code-path":"src/components/monitor/AlertEventsTab.tsx:117:11",value:"warning",children:"警告"}),e.jsx("option",{"code-path":"src/components/monitor/AlertEventsTab.tsx:118:11",value:"info",children:"提示"})]}),e.jsxs("select",{"code-path":"src/components/monitor/AlertEventsTab.tsx:120:9",value:b,onChange:t=>C(t.target.value),className:"h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm",children:[e.jsx("option",{"code-path":"src/components/monitor/AlertEventsTab.tsx:125:11",value:"all",children:"全部状态"}),e.jsx("option",{"code-path":"src/components/monitor/AlertEventsTab.tsx:126:11",value:"firing",children:"触发中"}),e.jsx("option",{"code-path":"src/components/monitor/AlertEventsTab.tsx:127:11",value:"resolved",children:"已恢复"})]})]}),e.jsx(w,{"code-path":"src/components/monitor/AlertEventsTab.tsx:132:7",className:"bg-slate-900 border-slate-800",children:e.jsx(M,{"code-path":"src/components/monitor/AlertEventsTab.tsx:133:9",className:"p-0",children:e.jsx("div",{"code-path":"src/components/monitor/AlertEventsTab.tsx:134:11",className:"border-t border-slate-800",children:e.jsxs(X,{"code-path":"src/components/monitor/AlertEventsTab.tsx:135:13",children:[e.jsx(V,{"code-path":"src/components/monitor/AlertEventsTab.tsx:136:15",children:e.jsxs(E,{"code-path":"src/components/monitor/AlertEventsTab.tsx:137:17",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(i,{"code-path":"src/components/monitor/AlertEventsTab.tsx:138:19",className:"text-slate-400",children:"级别"}),e.jsx(i,{"code-path":"src/components/monitor/AlertEventsTab.tsx:139:19",className:"text-slate-400",children:"告警名称"}),e.jsx(i,{"code-path":"src/components/monitor/AlertEventsTab.tsx:140:19",className:"text-slate-400",children:"状态"}),e.jsx(i,{"code-path":"src/components/monitor/AlertEventsTab.tsx:141:19",className:"text-slate-400",children:"目标"}),e.jsx(i,{"code-path":"src/components/monitor/AlertEventsTab.tsx:142:19",className:"text-slate-400",children:"当前值"}),e.jsx(i,{"code-path":"src/components/monitor/AlertEventsTab.tsx:143:19",className:"text-slate-400",children:"阈值"}),e.jsx(i,{"code-path":"src/components/monitor/AlertEventsTab.tsx:144:19",className:"text-slate-400",children:"开始时间"}),e.jsx(i,{"code-path":"src/components/monitor/AlertEventsTab.tsx:145:19",className:"text-slate-400 text-right",children:"操作"})]})}),e.jsx(q,{"code-path":"src/components/monitor/AlertEventsTab.tsx:148:15",children:T?e.jsx(E,{"code-path":"src/components/monitor/AlertEventsTab.tsx:150:19",className:"border-slate-800",children:e.jsxs(c,{"code-path":"src/components/monitor/AlertEventsTab.tsx:151:21",colSpan:8,className:"text-center text-slate-500 py-8",children:[e.jsx(O,{"code-path":"src/components/monitor/AlertEventsTab.tsx:152:23",className:"h-5 w-5 animate-spin inline mr-2"}),"加载中..."]})}):j.map(t=>e.jsxs(E,{"code-path":"src/components/monitor/AlertEventsTab.tsx:157:19",className:"border-slate-800 hover:bg-slate-800/50",children:[e.jsx(c,{"code-path":"src/components/monitor/AlertEventsTab.tsx:158:21",children:y(t.severity)}),e.jsx(c,{"code-path":"src/components/monitor/AlertEventsTab.tsx:159:21",children:e.jsx("span",{"code-path":"src/components/monitor/AlertEventsTab.tsx:160:23",className:"text-sm font-medium text-slate-200",children:t.rule&&t.rule.name||t.message})}),e.jsx(c,{"code-path":"src/components/monitor/AlertEventsTab.tsx:164:21",children:a(t.status)}),e.jsx(c,{"code-path":"src/components/monitor/AlertEventsTab.tsx:165:21",className:"max-w-[160px]",children:e.jsx("span",{"code-path":"src/components/monitor/AlertEventsTab.tsx:166:23",className:"text-sm text-slate-300 block truncate",title:t.target,children:t.target})}),e.jsx(c,{"code-path":"src/components/monitor/AlertEventsTab.tsx:168:21",children:e.jsx("span",{"code-path":"src/components/monitor/AlertEventsTab.tsx:169:23",className:"text-sm text-slate-300",children:typeof t.value=="number"?t.value.toFixed(1):t.value})}),e.jsx(c,{"code-path":"src/components/monitor/AlertEventsTab.tsx:171:21",children:e.jsx("span",{"code-path":"src/components/monitor/AlertEventsTab.tsx:172:23",className:"text-sm text-slate-500",children:t.threshold})}),e.jsx(c,{"code-path":"src/components/monitor/AlertEventsTab.tsx:174:21",children:e.jsx("span",{"code-path":"src/components/monitor/AlertEventsTab.tsx:175:23",className:"text-sm text-slate-400",children:t.created_at?new Date(t.created_at).toLocaleString():"--"})}),e.jsx(c,{"code-path":"src/components/monitor/AlertEventsTab.tsx:179:21",className:"text-right",children:e.jsx("div",{"code-path":"src/components/monitor/AlertEventsTab.tsx:180:23",className:"flex items-center justify-end gap-1",children:t.status==="firing"&&e.jsxs(A,{"code-path":"src/components/monitor/AlertEventsTab.tsx:182:27",variant:"ghost",size:"sm",className:"h-8 text-slate-400 hover:text-emerald-400",onClick:()=>x(t.id),children:[e.jsx($,{"code-path":"src/components/monitor/AlertEventsTab.tsx:188:29",className:"h-4 w-4 mr-1"}),"确认"]})})})]},t.id))})]})})})})]})}const Ce=9;function ye({rules:m,notifyChannels:T,onReload:d,onEditRule:p}){const u=_(),[o,h]=l.useState([]),b=()=>{m.length>0&&o.length===m.length?h([]):h(m.map(t=>t.id))},C=t=>{h(r=>r.includes(t)?r.filter(N=>N!==t):[...r,t])},j=async t=>{if(await u({title:"删除告警规则",description:"确定删除此告警规则?",confirmText:"删除",variant:"destructive"}))try{await g.deleteRule(t),R.success("告警规则已删除"),d()}catch(N){console.error("Failed to delete rule:",N),R.error("删除失败")}},y=async()=>{if(!(o.length===0||!await u({title:"批量删除告警规则",description:`确定删除选中的 ${o.length} 条告警规则吗?此操作不可撤销。`,confirmText:"批量删除",variant:"destructive"})))try{await g.batchDeleteRules(o),R.success(`已删除 ${o.length} 条告警规则`),h([]),d()}catch(r){console.error("Failed to batch delete rules:",r),R.error("批量删除失败")}},a=async t=>{try{await g.toggleRule(t),d()}catch(r){console.error("Failed to toggle rule:",r)}},x=m.length>0&&o.length===m.length;return e.jsxs("div",{"code-path":"src/components/monitor/AlertRulesTab.tsx:104:5",className:"mt-4",children:[o.length>0&&e.jsxs("div",{"code-path":"src/components/monitor/AlertRulesTab.tsx:107:9",className:"flex items-center gap-2 mb-3",children:[e.jsxs("span",{"code-path":"src/components/monitor/AlertRulesTab.tsx:108:11",className:"text-sm text-slate-400",children:["已选择 ",o.length," 项"]}),e.jsxs(A,{"code-path":"src/components/monitor/AlertRulesTab.tsx:109:11",variant:"outline",size:"sm",className:"border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:y,children:[e.jsx(P,{"code-path":"src/components/monitor/AlertRulesTab.tsx:115:13",className:"h-4 w-4 mr-2"}),"批量删除"]})]}),e.jsx(w,{"code-path":"src/components/monitor/AlertRulesTab.tsx:121:7",className:"bg-slate-900 border-slate-800",children:e.jsx(M,{"code-path":"src/components/monitor/AlertRulesTab.tsx:122:9",className:"p-0",children:e.jsx("div",{"code-path":"src/components/monitor/AlertRulesTab.tsx:123:11",className:"border-t border-slate-800",children:e.jsxs(X,{"code-path":"src/components/monitor/AlertRulesTab.tsx:124:13",children:[e.jsx(V,{"code-path":"src/components/monitor/AlertRulesTab.tsx:125:15",children:e.jsxs(E,{"code-path":"src/components/monitor/AlertRulesTab.tsx:126:17",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(i,{"code-path":"src/components/monitor/AlertRulesTab.tsx:127:19",className:"w-12",children:e.jsx(G,{"code-path":"src/components/monitor/AlertRulesTab.tsx:128:21",checked:x,onCheckedChange:b,className:"border-slate-600"})}),e.jsx(i,{"code-path":"src/components/monitor/AlertRulesTab.tsx:134:19",className:"text-slate-400",children:"规则名称"}),e.jsx(i,{"code-path":"src/components/monitor/AlertRulesTab.tsx:135:19",className:"text-slate-400",children:"数据源"}),e.jsx(i,{"code-path":"src/components/monitor/AlertRulesTab.tsx:136:19",className:"text-slate-400",children:"触发条件"}),e.jsx(i,{"code-path":"src/components/monitor/AlertRulesTab.tsx:137:19",className:"text-slate-400",children:"级别"}),e.jsx(i,{"code-path":"src/components/monitor/AlertRulesTab.tsx:138:19",className:"text-slate-400",children:"持续时间"}),e.jsx(i,{"code-path":"src/components/monitor/AlertRulesTab.tsx:139:19",className:"text-slate-400",children:"通知渠道"}),e.jsx(i,{"code-path":"src/components/monitor/AlertRulesTab.tsx:140:19",className:"text-slate-400",children:"状态"}),e.jsx(i,{"code-path":"src/components/monitor/AlertRulesTab.tsx:141:19",className:"text-slate-400 text-right",children:"操作"})]})}),e.jsx(q,{"code-path":"src/components/monitor/AlertRulesTab.tsx:144:15",children:m.length===0?e.jsx(E,{"code-path":"src/components/monitor/AlertRulesTab.tsx:146:19",className:"border-slate-800",children:e.jsx(c,{"code-path":"src/components/monitor/AlertRulesTab.tsx:147:21",colSpan:Ce,className:"text-center text-slate-500 py-12",children:"暂无告警规则"})}):m.map(t=>e.jsxs(E,{"code-path":"src/components/monitor/AlertRulesTab.tsx:153:21",className:"border-slate-800 hover:bg-slate-800/50",children:[e.jsx(c,{"code-path":"src/components/monitor/AlertRulesTab.tsx:154:23",children:e.jsx(G,{"code-path":"src/components/monitor/AlertRulesTab.tsx:155:25",checked:o.includes(t.id),onCheckedChange:()=>C(t.id),className:"border-slate-600"})}),e.jsx(c,{"code-path":"src/components/monitor/AlertRulesTab.tsx:161:23",children:e.jsxs("div",{"code-path":"src/components/monitor/AlertRulesTab.tsx:162:25",children:[e.jsx("span",{"code-path":"src/components/monitor/AlertRulesTab.tsx:163:27",className:"text-sm font-medium text-slate-200",children:t.name}),t.description&&e.jsx("p",{"code-path":"src/components/monitor/AlertRulesTab.tsx:165:29",className:"text-xs text-slate-500",children:t.description})]})}),e.jsx(c,{"code-path":"src/components/monitor/AlertRulesTab.tsx:169:23",children:e.jsx("code",{"code-path":"src/components/monitor/AlertRulesTab.tsx:170:25",className:"text-xs text-slate-300 bg-slate-800 px-2 py-0.5 rounded",children:t.source||"--"})}),e.jsx(c,{"code-path":"src/components/monitor/AlertRulesTab.tsx:174:23",className:"max-w-[180px]",children:e.jsx("code",{"code-path":"src/components/monitor/AlertRulesTab.tsx:175:25",className:"text-xs text-blue-300 block truncate",title:t.expression,children:t.expression||"--"})}),e.jsx(c,{"code-path":"src/components/monitor/AlertRulesTab.tsx:179:23",children:t.severity==="critical"?e.jsx(f,{"code-path":"src/components/monitor/AlertRulesTab.tsx:181:27",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10",children:"严重"}):t.severity==="warning"?e.jsx(f,{"code-path":"src/components/monitor/AlertRulesTab.tsx:185:27",variant:"outline",className:"border-amber-500/30 text-amber-400 bg-amber-500/10",children:"警告"}):e.jsx(f,{"code-path":"src/components/monitor/AlertRulesTab.tsx:189:27",variant:"outline",className:"border-blue-500/30 text-blue-400 bg-blue-500/10",children:"提示"})}),e.jsx(c,{"code-path":"src/components/monitor/AlertRulesTab.tsx:194:23",children:e.jsxs("span",{"code-path":"src/components/monitor/AlertRulesTab.tsx:195:25",className:"text-sm text-slate-300",children:[(t.duration||0)/60,"分钟"]})}),e.jsx(c,{"code-path":"src/components/monitor/AlertRulesTab.tsx:197:23",children:pe(t,T)}),e.jsx(c,{"code-path":"src/components/monitor/AlertRulesTab.tsx:200:23",children:e.jsx(B,{"code-path":"src/components/monitor/AlertRulesTab.tsx:201:25",checked:!!t.enabled,className:"data-[state=checked]:bg-blue-600",onCheckedChange:()=>a(t.id)})}),e.jsx(c,{"code-path":"src/components/monitor/AlertRulesTab.tsx:207:23",className:"text-right",children:e.jsxs("div",{"code-path":"src/components/monitor/AlertRulesTab.tsx:208:25",className:"flex items-center justify-end gap-1",children:[e.jsx(A,{"code-path":"src/components/monitor/AlertRulesTab.tsx:209:27",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-slate-100",onClick:()=>p(t),children:e.jsx(Q,{"code-path":"src/components/monitor/AlertRulesTab.tsx:215:29",className:"h-4 w-4"})}),e.jsx(A,{"code-path":"src/components/monitor/AlertRulesTab.tsx:217:27",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-red-400",onClick:()=>j(t.id),children:e.jsx(P,{"code-path":"src/components/monitor/AlertRulesTab.tsx:223:29",className:"h-4 w-4"})})]})})]},t.id))})]})})})})]})}const L={name:"",type:"dingtalk",config:"",enabled:!0};function we({open:m,onOpenChange:T,notifyChannels:d,onChannelsChanged:p}){const u=_(),[o,h]=l.useState(null),[b,C]=l.useState(!1),[j,y]=l.useState(null),[a,x]=l.useState({...L});l.useEffect(()=>{m&&(h(null),x({...L}))},[m]);const t=s=>{h(s),x({name:s.name||"",type:s.type||"dingtalk",config:s.config||"",enabled:s.enabled!==!1})},r=()=>{h(null),x({...L})},N=async()=>{if(a.name.trim()){C(!0);try{const s={name:a.name.trim(),type:a.type,config:a.config.trim()};o?await g.updateNotifyChannel(o.id,{...s,enabled:a.enabled}):await g.createNotifyChannel(s),r(),p()}catch(s){console.error("Failed to save notify channel:",s)}finally{C(!1)}}},v=async s=>{if(await u({title:"删除通知渠道",description:"确定删除此通知渠道?",confirmText:"删除",variant:"destructive"}))try{await g.deleteNotifyChannel(s),o&&o.id===s&&r(),p()}catch(n){console.error("Failed to delete notify channel:",n)}},k=async s=>{try{await g.updateNotifyChannel(s.id,{enabled:!s.enabled}),p()}catch(n){console.error("Failed to toggle notify channel:",n)}},S=async s=>{y(s);try{await g.testNotifyChannel(s),p()}catch(n){console.error("Failed to test notify channel:",n)}finally{y(null)}};return e.jsx(te,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:119:5",open:m,onOpenChange:T,children:e.jsxs(se,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:120:7",className:"bg-slate-900 border-slate-700 text-slate-100 max-w-2xl",children:[e.jsxs(oe,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:121:9",children:[e.jsx(ae,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:122:11",className:"text-slate-100",children:"通知渠道配置"}),e.jsx(ne,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:123:11",className:"text-slate-500",children:"管理告警通知渠道(钉钉/企业微信/邮件/短信/Webhook),配置后可在告警规则中引用"})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:128:9",className:"grid grid-cols-1 lg:grid-cols-2 gap-4 max-h-[65vh] overflow-y-auto pr-1",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:130:11",className:"space-y-2",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:131:13",className:"flex items-center justify-between",children:[e.jsx(D,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:132:15",className:"text-slate-300 text-sm",children:"已配置渠道"}),e.jsxs(A,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:133:15",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 hover:bg-slate-800 text-xs",onClick:r,children:[e.jsx(U,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:139:17",className:"h-3 w-3 mr-1"}),"新建"]})]}),d.length===0?e.jsx("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:144:15",className:"text-center py-8 text-sm text-slate-600 border border-dashed border-slate-800 rounded-lg",children:"暂无通知渠道,请在右侧添加"}):e.jsx("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:148:15",className:"space-y-2",children:d.map(s=>e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:150:19",className:`p-3 rounded-lg border cursor-pointer transition-colors ${o&&o.id===s.id?"border-blue-500/50 bg-blue-500/5":"border-slate-800 bg-slate-800/30 hover:border-slate-700"}`,onClick:()=>t(s),children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:159:21",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:160:23",className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:161:25",className:"text-sm text-slate-200 truncate",children:s.name}),e.jsx(f,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:162:25",variant:"outline",className:"border-slate-600 text-slate-400 text-[10px] py-0",children:he(s.type)})]}),e.jsx(B,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:166:23",checked:s.enabled!==!1,onCheckedChange:()=>k(s),onClick:n=>n.stopPropagation(),className:"data-[state=checked]:bg-emerald-600 scale-90"})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:173:21",className:"flex items-center justify-between mt-2",children:[s.test_status==="success"?e.jsx("span",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:175:25",className:"text-[11px] text-emerald-400",children:"测试通过"}):e.jsx("span",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:177:25",className:"text-[11px] text-slate-600",children:"未测试"}),e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:179:23",className:"flex items-center gap-1",onClick:n=>n.stopPropagation(),children:[e.jsx(A,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:180:25",size:"sm",variant:"ghost",className:"h-6 px-2 text-slate-400 hover:text-slate-200 hover:bg-slate-700 text-xs",disabled:j===s.id,onClick:()=>S(s.id),children:j===s.id?e.jsx(O,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:187:55",className:"h-3 w-3 animate-spin"}):"测试"}),e.jsx(A,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:189:25",size:"sm",variant:"ghost",className:"h-6 px-2 text-red-400/70 hover:text-red-400 hover:bg-red-500/10 text-xs",onClick:()=>v(s.id),children:e.jsx(P,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:195:27",className:"h-3 w-3"})})]})]})]},s.id))})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:206:11",className:"space-y-4",children:[e.jsx(D,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:207:13",className:"text-slate-300 text-sm",children:o?"编辑渠道":"新建渠道"}),e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:210:13",className:"space-y-1.5",children:[e.jsxs(D,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:211:15",className:"text-slate-400 text-xs",children:["渠道名称 ",e.jsx("span",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:211:62",className:"text-red-400",children:"*"})]}),e.jsx(Y,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:212:15",value:a.name,onChange:s=>x({...a,name:s.target.value}),placeholder:"如:运维告警群",className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600 h-9"})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:219:13",className:"space-y-1.5",children:[e.jsx(D,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:220:15",className:"text-slate-400 text-xs",children:"渠道类型"}),e.jsx("select",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:221:15",value:a.type,onChange:s=>x({...a,type:s.target.value}),className:"w-full h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm",children:K.map(({key:s,label:n})=>e.jsx("option",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:227:19",value:s,children:n},s))})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:231:13",className:"space-y-1.5",children:[e.jsx(D,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:232:15",className:"text-slate-400 text-xs",children:"配置(JSON)"}),e.jsx(be,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:233:15",value:a.config,onChange:s=>x({...a,config:s.target.value}),placeholder:K.find(s=>s.key===a.type)?.placeholder||"",rows:5,className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600 font-mono text-xs resize-none"})]}),o&&e.jsxs("div",{"code-path":"src/components/monitor/AlertChannelDialog.tsx:242:15",className:"flex items-center gap-2",children:[e.jsx(B,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:243:17",checked:a.enabled,onCheckedChange:s=>x({...a,enabled:s}),className:"data-[state=checked]:bg-emerald-600"}),e.jsx(D,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:248:17",className:"text-slate-400 text-xs",children:"启用此渠道"})]})]})]}),e.jsxs(re,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:254:9",children:[e.jsx(A,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:255:11",variant:"outline",className:"border-slate-700 text-slate-300 hover:bg-slate-800",onClick:()=>T(!1),children:"关闭"}),e.jsxs(A,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:262:11",className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:!a.name.trim()||b,onClick:N,children:[b&&e.jsx(O,{"code-path":"src/components/monitor/AlertChannelDialog.tsx:267:31",className:"h-4 w-4 mr-2 animate-spin"}),o?"保存修改":"添加渠道"]})]})]})})}function $e(){const[m,T]=l.useState("events"),[d,p]=l.useState([]),[u,o]=l.useState([]),[h,b]=l.useState(!0),[C,j]=l.useState(!1),[y,a]=l.useState(null),[x,t]=l.useState(!1),[r,N]=l.useState([]),v=async()=>{try{b(!0);const[n,F,Z]=await Promise.all([g.getAlerts(),g.getRules(),g.getNotifyChannels()]);p(n?.list||[]),o(F?.list||(Array.isArray(F)?F:[])),N(Z?.list||[])}catch(n){console.error("Failed to load alert data:",n)}finally{b(!1)}};l.useEffect(()=>{v()},[]);const k=()=>{a(null),j(!0)},S=n=>{a(n),j(!0)},s=[{time:"00:00",critical:2,warning:5,info:8},{time:"04:00",critical:1,warning:3,info:6},{time:"08:00",critical:3,warning:7,info:12},{time:"12:00",critical:5,warning:10,info:15},{time:"16:00",critical:4,warning:8,info:10},{time:"20:00",critical:3,warning:6,info:9},{time:"24:00",critical:2,warning:4,info:7}];return e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:75:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:77:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:78:9",children:[e.jsx("h1",{"code-path":"src/components/monitor/AlertManager.tsx:79:11",className:"text-2xl font-bold text-slate-100",children:"监控告警"}),e.jsx("p",{"code-path":"src/components/monitor/AlertManager.tsx:80:11",className:"text-sm text-slate-500 mt-1",children:"告警规则管理与告警事件处理"})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:82:9",className:"flex items-center gap-2",children:[e.jsxs(A,{"code-path":"src/components/monitor/AlertManager.tsx:83:11",variant:"outline",className:"border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800",onClick:()=>t(!0),children:[e.jsx(Q,{"code-path":"src/components/monitor/AlertManager.tsx:88:13",className:"h-4 w-4 mr-2"}),"通知配置"]}),e.jsxs(A,{"code-path":"src/components/monitor/AlertManager.tsx:91:11",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:k,children:[e.jsx(U,{"code-path":"src/components/monitor/AlertManager.tsx:92:13",className:"h-4 w-4 mr-2"}),"新建规则"]})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:99:7",className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(w,{"code-path":"src/components/monitor/AlertManager.tsx:100:9",className:"bg-slate-900 border-slate-800",children:e.jsx(M,{"code-path":"src/components/monitor/AlertManager.tsx:101:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:102:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:103:15",children:[e.jsx("p",{"code-path":"src/components/monitor/AlertManager.tsx:104:17",className:"text-sm text-slate-500",children:"告警规则"}),e.jsx("p",{"code-path":"src/components/monitor/AlertManager.tsx:105:17",className:"text-2xl font-bold text-slate-100",children:u.length})]}),e.jsx("div",{"code-path":"src/components/monitor/AlertManager.tsx:107:15",className:"p-3 rounded-lg bg-blue-500/10 text-blue-400",children:e.jsx(J,{"code-path":"src/components/monitor/AlertManager.tsx:108:17",className:"h-5 w-5"})})]})})}),e.jsx(w,{"code-path":"src/components/monitor/AlertManager.tsx:113:9",className:"bg-slate-900 border-slate-800",children:e.jsx(M,{"code-path":"src/components/monitor/AlertManager.tsx:114:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:115:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:116:15",children:[e.jsx("p",{"code-path":"src/components/monitor/AlertManager.tsx:117:17",className:"text-sm text-slate-500",children:"触发中"}),e.jsx("p",{"code-path":"src/components/monitor/AlertManager.tsx:118:17",className:"text-2xl font-bold text-red-400",children:d.filter(n=>n.status==="firing").length})]}),e.jsx("div",{"code-path":"src/components/monitor/AlertManager.tsx:122:15",className:"p-3 rounded-lg bg-red-500/10 text-red-400",children:e.jsx(z,{"code-path":"src/components/monitor/AlertManager.tsx:123:17",className:"h-5 w-5"})})]})})}),e.jsx(w,{"code-path":"src/components/monitor/AlertManager.tsx:128:9",className:"bg-slate-900 border-slate-800",children:e.jsx(M,{"code-path":"src/components/monitor/AlertManager.tsx:129:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:130:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:131:15",children:[e.jsx("p",{"code-path":"src/components/monitor/AlertManager.tsx:132:17",className:"text-sm text-slate-500",children:"今日告警"}),e.jsx("p",{"code-path":"src/components/monitor/AlertManager.tsx:133:17",className:"text-2xl font-bold text-amber-400",children:d.length})]}),e.jsx("div",{"code-path":"src/components/monitor/AlertManager.tsx:135:15",className:"p-3 rounded-lg bg-amber-500/10 text-amber-400",children:e.jsx(ce,{"code-path":"src/components/monitor/AlertManager.tsx:136:17",className:"h-5 w-5"})})]})})}),e.jsx(w,{"code-path":"src/components/monitor/AlertManager.tsx:141:9",className:"bg-slate-900 border-slate-800",children:e.jsx(M,{"code-path":"src/components/monitor/AlertManager.tsx:142:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:143:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertManager.tsx:144:15",children:[e.jsx("p",{"code-path":"src/components/monitor/AlertManager.tsx:145:17",className:"text-sm text-slate-500",children:"已恢复"}),e.jsx("p",{"code-path":"src/components/monitor/AlertManager.tsx:146:17",className:"text-2xl font-bold text-emerald-400",children:d.filter(n=>n.status==="resolved").length})]}),e.jsx("div",{"code-path":"src/components/monitor/AlertManager.tsx:150:15",className:"p-3 rounded-lg bg-emerald-500/10 text-emerald-400",children:e.jsx($,{"code-path":"src/components/monitor/AlertManager.tsx:151:17",className:"h-5 w-5"})})]})})})]}),e.jsxs(w,{"code-path":"src/components/monitor/AlertManager.tsx:159:7",className:"bg-slate-900 border-slate-800",children:[e.jsxs(le,{"code-path":"src/components/monitor/AlertManager.tsx:160:9",className:"pb-2",children:[e.jsx(ie,{"code-path":"src/components/monitor/AlertManager.tsx:161:11",className:"text-slate-100",children:"告警趋势"}),e.jsx(me,{"code-path":"src/components/monitor/AlertManager.tsx:162:11",className:"text-slate-500",children:"过去24小时告警统计"})]}),e.jsx(M,{"code-path":"src/components/monitor/AlertManager.tsx:164:9",children:e.jsx("div",{"code-path":"src/components/monitor/AlertManager.tsx:165:11",className:"h-[200px]",children:e.jsx(Ae,{"code-path":"src/components/monitor/AlertManager.tsx:166:13",width:"100%",height:"100%",children:e.jsxs(fe,{"code-path":"src/components/monitor/AlertManager.tsx:167:15",data:s,children:[e.jsxs("defs",{"code-path":"src/components/monitor/AlertManager.tsx:168:17",children:[e.jsxs("linearGradient",{"code-path":"src/components/monitor/AlertManager.tsx:169:19",id:"colorCritical",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{"code-path":"src/components/monitor/AlertManager.tsx:170:21",offset:"5%",stopColor:"#ef4444",stopOpacity:.3}),e.jsx("stop",{"code-path":"src/components/monitor/AlertManager.tsx:171:21",offset:"95%",stopColor:"#ef4444",stopOpacity:0})]}),e.jsxs("linearGradient",{"code-path":"src/components/monitor/AlertManager.tsx:173:19",id:"colorWarning",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{"code-path":"src/components/monitor/AlertManager.tsx:174:21",offset:"5%",stopColor:"#f59e0b",stopOpacity:.3}),e.jsx("stop",{"code-path":"src/components/monitor/AlertManager.tsx:175:21",offset:"95%",stopColor:"#f59e0b",stopOpacity:0})]})]}),e.jsx(je,{"code-path":"src/components/monitor/AlertManager.tsx:178:17",strokeDasharray:"3 3",stroke:"#1e293b"}),e.jsx(ue,{"code-path":"src/components/monitor/AlertManager.tsx:179:17",dataKey:"time",stroke:"#475569",fontSize:12}),e.jsx(Ne,{"code-path":"src/components/monitor/AlertManager.tsx:180:17",stroke:"#475569",fontSize:12}),e.jsx(ve,{"code-path":"src/components/monitor/AlertManager.tsx:181:17",contentStyle:{backgroundColor:"#0f172a",border:"1px solid #1e293b",borderRadius:"6px",color:"#f8fafc"}}),e.jsx(W,{"code-path":"src/components/monitor/AlertManager.tsx:189:17",type:"monotone",dataKey:"critical",stroke:"#ef4444",fillOpacity:1,fill:"url(#colorCritical)",name:"严重"}),e.jsx(W,{"code-path":"src/components/monitor/AlertManager.tsx:197:17",type:"monotone",dataKey:"warning",stroke:"#f59e0b",fillOpacity:1,fill:"url(#colorWarning)",name:"警告"})]})})})})]}),e.jsxs(de,{"code-path":"src/components/monitor/AlertManager.tsx:212:7",value:m,onValueChange:T,className:"w-full",children:[e.jsxs(xe,{"code-path":"src/components/monitor/AlertManager.tsx:213:9",className:"bg-slate-800 border border-slate-700",children:[e.jsx(H,{"code-path":"src/components/monitor/AlertManager.tsx:214:11",value:"events",className:"data-[state=active]:bg-slate-700",children:"告警事件"}),e.jsx(H,{"code-path":"src/components/monitor/AlertManager.tsx:217:11",value:"rules",className:"data-[state=active]:bg-slate-700",children:"告警规则"})]}),e.jsx(I,{"code-path":"src/components/monitor/AlertManager.tsx:223:9",value:"events",children:e.jsx(Te,{"code-path":"src/components/monitor/AlertManager.tsx:224:11",alerts:d,loading:h,onReload:v})}),e.jsx(I,{"code-path":"src/components/monitor/AlertManager.tsx:227:9",value:"rules",children:e.jsx(ye,{"code-path":"src/components/monitor/AlertManager.tsx:228:11",rules:u,notifyChannels:r,onReload:v,onEditRule:S})})]}),e.jsx(ge,{"code-path":"src/components/monitor/AlertManager.tsx:239:7",open:C,onOpenChange:j,editingRule:y,notifyChannels:r,onSaved:v}),e.jsx(we,{"code-path":"src/components/monitor/AlertManager.tsx:246:7",open:x,onOpenChange:t,notifyChannels:r,onChannelsChanged:v})]})}export{$e as AlertManager}; diff --git a/backend/static/assets/AlertRuleDialog-DnF-_Zoj.js b/backend/static/assets/AlertRuleDialog-DnF-_Zoj.js new file mode 100644 index 0000000..7882ee7 --- /dev/null +++ b/backend/static/assets/AlertRuleDialog-DnF-_Zoj.js @@ -0,0 +1,14 @@ +import{j as e,J as R,r as d,D as v,b as w,c as k,d as S,e as _,I as x,f as C,B as g,L}from"./index-DfyorCky.js";import{L as n}from"./label-BK0h2apY.js";import{T as E}from"./textarea-NXY8u32k.js";import{S as P}from"./switch-CGiGgOnh.js";import{a as A}from"./monitor-BAaBXIsC.js";import{M as T}from"./message-square-DyxabBvb.js";import{P as I,M as B}from"./phone-DgvWDdJl.js";function D(o){if(!o)return[];if(Array.isArray(o))return o;if(typeof o=="string"){try{const r=JSON.parse(o);if(Array.isArray(r))return r}catch{}return o.split(",").map(r=>r.trim()).filter(Boolean)}return[]}const F=["email","sms","dingtalk","wechat","webhook"],q={dingtalk:"钉钉",wechat:"企业微信",email:"邮件",sms:"短信",webhook:"Webhook"};function H(o,r){if(!o)return null;const a=r.find(c=>String(c.id)===String(o));return a?{type:a.type||"unknown",name:a.name||a.type||"未命名",isLegacy:!1}:F.includes(o)?{type:o,name:q[o]||o,isLegacy:!0}:null}const M=[{key:"dingtalk",label:"钉钉",placeholder:`{ + "webhook": "https://oapi.dingtalk.com/robot/send?access_token=***", + "secret": "SECxxx" +}`},{key:"wechat",label:"企业微信",placeholder:`{ + "webhook": "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=***" +}`},{key:"email",label:"邮件",placeholder:`{ + "to": "ops@ezops.io", + "subject": "告警通知" +}`},{key:"sms",label:"短信",placeholder:`{ + "phones": "13800138000", + "sign": "AIOps" +}`},{key:"webhook",label:"Webhook",placeholder:`{ + "url": "https://example.com/alert" +}`}];function y(o){return M.find(r=>r.key===o)?.label||o}function j(o){switch(o){case"email":return B;case"sms":return I;case"dingtalk":case"wechat":return T;default:return R}}function Q(o,r){const a=D(o.notify_channels);return a.length===0?e.jsx("span",{"code-path":"src/components/monitor/alertShared.tsx:76:33",className:"text-xs text-slate-600",children:"--"}):e.jsx("div",{"code-path":"src/components/monitor/alertShared.tsx:78:5",className:"flex flex-wrap gap-1",children:a.map(c=>{const i=H(c,r);if(!i)return null;const t=j(i.type);return e.jsxs("span",{"code-path":"src/components/monitor/alertShared.tsx:84:11",title:`${i.name} (${y(i.type)})`,className:"inline-flex items-center gap-1 text-xs px-1.5 py-0.5 rounded bg-slate-800 text-slate-300",children:[e.jsx(t,{"code-path":"src/components/monitor/alertShared.tsx:89:13",className:"h-3 w-3 text-slate-400"}),i.name]},c)})})}const b={name:"",description:"",type:"metric",source:"prometheus",expression:"",severity:"warning",duration:300,notify_channels:[]};function U({open:o,onOpenChange:r,editingRule:a,notifyChannels:c,onSaved:i}){const[t,l]=d.useState({...b}),[h,u]=d.useState(!1);d.useEffect(()=>{o&&l(a?{name:a.name||"",description:a.description||"",type:a.type||"metric",source:a.source||"prometheus",expression:a.expression||"",severity:a.severity||"warning",duration:a.duration||300,notify_channels:D(a.notify_channels)}:{...b})},[o,a]);const f=s=>{l(m=>({...m,notify_channels:m.notify_channels.includes(s)?m.notify_channels.filter(p=>p!==s):[...m.notify_channels,s]}))},N=async()=>{if(!(!t.name.trim()||!t.expression.trim())){u(!0);try{const s={name:t.name.trim(),description:t.description.trim(),type:t.type,source:t.source,expression:t.expression.trim(),severity:t.severity,duration:Number(t.duration)||0,notify_channels:t.notify_channels};a?await A.updateRule(a.id,s):await A.createRule(s),r(!1),i()}catch(s){console.error("Failed to save rule:",s)}finally{u(!1)}}};return e.jsx(v,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:103:5",open:o,onOpenChange:r,children:e.jsxs(w,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:104:7",className:"bg-slate-900 border-slate-700 text-slate-100 max-w-lg",children:[e.jsxs(k,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:105:9",children:[e.jsx(S,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:106:11",className:"text-slate-100",children:a?"编辑告警规则":"新建告警规则"}),e.jsx(_,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:109:11",className:"text-slate-500",children:a?"修改告警规则的触发条件和通知方式":"配置监控指标的告警触发条件"})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:114:9",className:"space-y-4 max-h-[60vh] overflow-y-auto pr-1",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:115:11",className:"space-y-1.5",children:[e.jsxs(n,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:116:13",className:"text-slate-300",children:["规则名称 ",e.jsx("span",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:116:52",className:"text-red-400",children:"*"})]}),e.jsx(x,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:117:13",value:t.name,onChange:s=>l({...t,name:s.target.value}),placeholder:"如:CPU 使用率告警",className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600"})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:125:11",className:"space-y-1.5",children:[e.jsx(n,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:126:13",className:"text-slate-300",children:"描述"}),e.jsx(E,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:127:13",value:t.description,onChange:s=>l({...t,description:s.target.value}),placeholder:"规则说明",rows:2,className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600 resize-none"})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:136:11",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:137:13",className:"space-y-1.5",children:[e.jsx(n,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:138:15",className:"text-slate-300",children:"规则类型"}),e.jsxs("select",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:139:15",value:t.type,onChange:s=>l({...t,type:s.target.value}),className:"w-full h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm",children:[e.jsx("option",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:144:17",value:"metric",children:"指标监控"}),e.jsx("option",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:145:17",value:"log",children:"日志告警"}),e.jsx("option",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:146:17",value:"event",children:"事件告警"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:149:13",className:"space-y-1.5",children:[e.jsx(n,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:150:15",className:"text-slate-300",children:"数据源"}),e.jsxs("select",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:151:15",value:t.source,onChange:s=>l({...t,source:s.target.value}),className:"w-full h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm",children:[e.jsx("option",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:156:17",value:"prometheus",children:"Prometheus"}),e.jsx("option",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:157:17",value:"zabbix",children:"Zabbix"}),e.jsx("option",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:158:17",value:"custom",children:"自定义"})]})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:163:11",className:"space-y-1.5",children:[e.jsxs(n,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:164:13",className:"text-slate-300",children:["触发表达式 ",e.jsx("span",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:164:53",className:"text-red-400",children:"*"})]}),e.jsx(x,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:165:13",value:t.expression,onChange:s=>l({...t,expression:s.target.value}),placeholder:"如:cpu_usage > 80",className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600 font-mono text-sm"}),e.jsx("p",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:171:13",className:"text-xs text-slate-600",children:"PromQL 或指标表达式,例如 cpu_usage > 80"})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:174:11",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:175:13",className:"space-y-1.5",children:[e.jsx(n,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:176:15",className:"text-slate-300",children:"告警级别"}),e.jsxs("select",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:177:15",value:t.severity,onChange:s=>l({...t,severity:s.target.value}),className:"w-full h-9 px-3 rounded-md bg-slate-800/50 border border-slate-700 text-slate-200 text-sm",children:[e.jsx("option",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:182:17",value:"info",children:"提示"}),e.jsx("option",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:183:17",value:"warning",children:"警告"}),e.jsx("option",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:184:17",value:"critical",children:"严重"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:187:13",className:"space-y-1.5",children:[e.jsx(n,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:188:15",className:"text-slate-300",children:"持续时间(秒)"}),e.jsx(x,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:189:15",type:"number",value:t.duration,onChange:s=>l({...t,duration:Number(s.target.value)}),className:"bg-slate-800/50 border-slate-700 text-slate-200"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:198:11",className:"space-y-1.5",children:[e.jsx(n,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:199:13",className:"text-slate-300",children:"通知渠道"}),c.length===0?e.jsx("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:201:15",className:"text-xs text-amber-400/80 bg-amber-500/5 border border-amber-500/20 rounded-md px-3 py-2",children:"暂无已配置的通知渠道,请先在「通知渠道配置」中添加"}):e.jsx("div",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:205:15",className:"flex flex-wrap gap-3 pt-1",children:c.map(s=>{const m=j(s.type),p=t.notify_channels.includes(String(s.id));return e.jsxs("label",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:210:21",className:"flex items-center gap-2 cursor-pointer select-none text-sm text-slate-300",children:[e.jsx(P,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:214:23",checked:p,onCheckedChange:()=>f(String(s.id)),className:"data-[state=checked]:bg-blue-600"}),e.jsx(m,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:219:23",className:"h-4 w-4 text-slate-400"}),e.jsxs("span",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:220:23",children:[s.name,e.jsxs("span",{"code-path":"src/components/monitor/AlertRuleDialog.tsx:222:25",className:"text-xs text-slate-500 ml-1",children:["(",y(s.type),")"]})]})]},s.id)})})]})]}),e.jsxs(C,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:232:9",children:[e.jsx(g,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:233:11",variant:"outline",className:"border-slate-700 text-slate-300 hover:bg-slate-800",onClick:()=>r(!1),children:"取消"}),e.jsxs(g,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:240:11",className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:!t.name.trim()||!t.expression.trim()||h,onClick:N,children:[h&&e.jsx(L,{"code-path":"src/components/monitor/AlertRuleDialog.tsx:245:28",className:"h-4 w-4 mr-2 animate-spin"}),a?"保存修改":"创建规则"]})]})]})})}export{U as A,M as C,y as g,Q as r}; diff --git a/backend/static/assets/ApprovalFlow-5mIFjuJZ.js b/backend/static/assets/ApprovalFlow-5mIFjuJZ.js new file mode 100644 index 0000000..ae980c0 --- /dev/null +++ b/backend/static/assets/ApprovalFlow-5mIFjuJZ.js @@ -0,0 +1 @@ +import{g as ye,q as Ne,j as e,X as b,L as $,S as we,I as pe,B as i,U as fe,a0 as oe,D as V,b as J,c as q,d as H,e as G,x as le,f as Q,r as v}from"./index-DfyorCky.js";import{C as u,a as j,b as Te,c as De,d as Fe}from"./card-C55cvSHg.js";import{B as C}from"./badge-xNW8x0G1.js";import{T as ce}from"./textarea-NXY8u32k.js";import{t as T}from"./index-a3ybMjbR.js";import{b as k}from"./system-BgtMMm0X.js";import{F as _}from"./file-text-C9G5abwR.js";import{C as D}from"./circle-check-DWcXrx2k.js";import{C as F}from"./circle-x-DK79Dhg2.js";import{F as Ce}from"./funnel-D2FHr15I.js";import{S as Pe}from"./square-pen-BxUFAe0F.js";import{A as Se}from"./arrow-right-DyIltvNZ.js";import{L as ke}from"./label-BK0h2apY.js";import{S as _e,a as Le,b as Oe,c as Ie,d as $e}from"./select-D5qUzdAs.js";import{P as ze}from"./plus-CUG-9kpu.js";import"./index-CWVNW_qu.js";const Re=[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]],Be=ye("git-commit-horizontal",Re);function Ee(a){if(Array.isArray(a))return a;if(typeof a=="string")try{const s=JSON.parse(a);return Array.isArray(s)?s:[]}catch{return[]}return[]}function I(a){if(!a)return[];const s=typeof a=="string"?(()=>{try{return JSON.parse(a)}catch{return null}})():a;return s?Array.isArray(s.fields)?s.fields:[]:[]}function Me(a,s){if(!a)return null;let r;try{r=typeof a=="string"?JSON.parse(a):a}catch{return null}if(!r||typeof r!="object")return null;const o=I(s?.form_schema),n=new Map;o.forEach(p=>n.set(p.key,p.label));const m=Object.entries(r).filter(([,p])=>p!=null&&p!=="");return m.length===0?null:e.jsx("div",{"code-path":"src/components/approval/helpers.tsx:53:5",className:"grid grid-cols-2 gap-x-4 gap-y-3",children:m.map(([p,d])=>e.jsxs("div",{"code-path":"src/components/approval/helpers.tsx:55:9",className:"min-w-0",children:[e.jsx("p",{"code-path":"src/components/approval/helpers.tsx:56:11",className:"text-xs text-[var(--dg-text-muted)] mb-0.5",children:n.get(p)||p}),e.jsx("p",{"code-path":"src/components/approval/helpers.tsx:57:11",className:"text-sm text-[var(--dg-text-primary)] break-words",children:String(d)})]},p))})}const z=[{value:"server_apply",label:"云服务器申请",icon:Ne,color:"var(--dg-cyan)"},{value:"app_deploy",label:"应用部署申请",icon:Be,color:"var(--dg-blue)"}],U=a=>z.find(s=>s.value===a)?.label||a||"通用审批",L=a=>z.find(s=>s.value===a)?.color||"var(--dg-text-secondary)",Ve=a=>z.find(s=>s.value===a)?.icon||_,A=a=>a?.template?.type||a?.type||"";function X(a){const s=Ee(a.steps),r=a.current_step??0,o=s.length,n=s.filter(p=>p.status==="approved"||p.status==="completed").length,m=o>0?Math.round(n/o*100):0;return{steps:s,currentIndex:r,total:o,completed:n,percentage:m}}function Y(a){const{steps:s,currentIndex:r}=X(a);return s.length===0?null:e.jsx("div",{"code-path":"src/components/approval/helpers.tsx:99:5",className:"flex items-center gap-1 overflow-x-auto",children:s.map((o,n)=>{const m=o.status==="approved"||o.status==="completed",p=n===r,d=o.status==="rejected";return e.jsxs("div",{"code-path":"src/components/approval/helpers.tsx:105:11",className:"flex items-center",children:[e.jsxs("div",{"code-path":"src/components/approval/helpers.tsx:106:13",className:b("flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs whitespace-nowrap",m&&"bg-emerald-500/10 text-emerald-400",p&&!d&&"bg-amber-500/10 text-amber-400 border border-amber-500/30",d&&"bg-red-500/10 text-red-400",!m&&!p&&!d&&"bg-[var(--dg-bg-tertiary)] text-[var(--dg-text-muted)]"),children:[m&&e.jsx(D,{"code-path":"src/components/approval/helpers.tsx:115:31",className:"h-3 w-3"}),d&&e.jsx(F,{"code-path":"src/components/approval/helpers.tsx:116:30",className:"h-3 w-3"}),p&&!d&&e.jsx($,{"code-path":"src/components/approval/helpers.tsx:117:44",className:"h-3 w-3 animate-spin"}),e.jsx("span",{"code-path":"src/components/approval/helpers.tsx:118:15",children:o.name||o.approver_name||`步骤 ${n+1}`})]}),no(c.target.value),className:"pl-9 h-9 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:108:9",className:"flex items-center gap-1 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-lg p-1",children:Je.map(c=>e.jsx("button",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:110:13",onClick:()=>m(c.value),className:b("px-3 py-1.5 rounded-md text-sm transition-colors",n===c.value?"bg-[var(--dg-bg-hover)] text-[var(--dg-text-primary)] font-medium":"text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"),children:c.label},c.key))})]}),s?e.jsx(u,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:128:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(j,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:129:11",className:"p-12",children:e.jsxs("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:130:13",className:"flex items-center justify-center text-[var(--dg-text-muted)]",children:[e.jsx($,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:131:15",className:"h-6 w-6 animate-spin mr-2"}),"加载中..."]})})}):a.length===0?e.jsx(u,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:137:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(j,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:138:11",className:"p-12",children:e.jsxs("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:139:13",className:"text-center",children:[e.jsx(_,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:140:15",className:"h-12 w-12 mx-auto text-[var(--dg-text-muted)] mb-4"}),e.jsx("h3",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:141:15",className:"text-lg font-medium text-[var(--dg-text-secondary)] mb-2",children:"暂无审批流程"}),e.jsx("p",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:142:15",className:"text-sm text-[var(--dg-text-muted)]",children:"当前筛选条件下没有匹配的流程实例"})]})})}):e.jsx("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:147:9",className:"grid grid-cols-1 gap-4",children:a.map(c=>{const w=Ve(A(c)),{percentage:l}=X(c);return e.jsx(u,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:152:15",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] hover:border-[var(--dg-border)] transition-colors",children:e.jsxs(j,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:153:17",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:154:19",className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:155:21",className:"flex items-start gap-3",children:[e.jsx("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:156:23",className:"w-10 h-10 rounded-lg bg-[var(--dg-bg-tertiary)] flex items-center justify-center",style:{color:L(A(c))},children:e.jsx(w,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:157:25",className:"h-5 w-5"})}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:159:23",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:160:25",className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:161:27",className:"font-medium text-[var(--dg-text-primary)]",children:c.title}),qe(c.status)]}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:164:25",className:"flex items-center gap-3 text-xs text-[var(--dg-text-muted)]",children:[e.jsx("span",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:165:27",className:"flex items-center gap-1",children:e.jsx(C,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:166:29",variant:"outline",className:"text-xs border-[var(--dg-border)]",style:{color:L(A(c))},children:U(A(c))})}),e.jsxs("span",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:170:27",children:["申请人:",c.applicant_name||c.applicant||"--"]}),e.jsxs("span",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:171:27",children:["提交于 ",c.created_at?new Date(c.created_at).toLocaleString():"--"]})]})]})]}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:175:21",className:"flex items-center gap-2",children:[e.jsxs(i,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:176:23",variant:"ghost",size:"sm",className:"text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]",onClick:()=>p(c),children:[e.jsx(fe,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:177:25",className:"h-4 w-4 mr-1"}),"详情"]}),c.status==="pending"&&e.jsxs(e.Fragment,{children:[e.jsxs(i,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:182:27",variant:"outline",size:"sm",className:"border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/10",onClick:()=>d(c),children:[e.jsx(D,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:188:29",className:"h-4 w-4 mr-1"}),"通过"]}),e.jsxs(i,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:191:27",variant:"outline",size:"sm",className:"border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:()=>y(c),children:[e.jsx(F,{"code-path":"src/components/approval/ApprovalProcessTab.tsx:197:29",className:"h-4 w-4 mr-1"}),"拒绝"]})]})]})]}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:205:19",className:"mb-3",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:206:21",className:"flex items-center justify-between text-xs text-[var(--dg-text-muted)] mb-1.5",children:[e.jsx("span",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:207:23",children:"审批进度"}),e.jsxs("span",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:208:23",children:[l,"%"]})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:210:21",className:"w-full h-1.5 bg-[var(--dg-bg-tertiary)] rounded-full overflow-hidden",children:e.jsx("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:211:23",className:b("h-full rounded-full transition-all",c.status==="rejected"?"bg-red-400":"bg-[var(--dg-blue)]"),style:{width:`${l}%`}})})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalProcessTab.tsx:221:19",className:"bg-[var(--dg-bg-primary)] rounded-lg p-3",children:Y(c)})]})},c.id)})})]})}function ne(a){if(Array.isArray(a))return a;if(typeof a=="string")try{const s=JSON.parse(a);return Array.isArray(s)?s:[]}catch{return[]}return[]}const K=[{value:"deploy",label:"发布审批",color:"var(--dg-blue)"},{value:"server",label:"服务器操作",color:"var(--dg-cyan)"},{value:"permission",label:"权限申请",color:"var(--dg-purple)"}],Ge=a=>K.find(s=>s.value===a)?.label||a||"通用审批",Qe=a=>K.find(s=>s.value===a)?.color||"var(--dg-text-secondary)";function Ue(a){const s=ne(a.steps);return s.length===0?e.jsx("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:37:12",className:"text-[var(--dg-text-muted)] text-center py-4",children:"暂无流程节点"}):e.jsx("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:40:5",className:"flex items-center gap-2 overflow-x-auto py-4",children:s.map((r,o)=>e.jsxs("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:42:9",className:"flex items-center",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:43:11",className:b("px-4 py-2 rounded-lg border min-w-[100px] text-center",r.type==="start"&&"bg-emerald-500/10 border-emerald-500/30 text-emerald-400",r.type==="approval"&&"bg-[var(--dg-blue)]/10 border-[var(--dg-blue)]/30 text-[var(--dg-blue)]",r.type==="condition"&&"bg-amber-500/10 border-amber-500/30 text-amber-400",r.type==="end"&&"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-secondary)]"),children:[e.jsx("p",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:52:13",className:"text-sm font-medium",children:r.name}),r.approvers&&e.jsx("p",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:54:15",className:"text-xs text-[var(--dg-text-muted)] mt-1",children:Array.isArray(r.approvers)?r.approvers.join(", "):r.approvers})]}),or("all"),className:b("px-3 py-1.5 rounded-md text-sm transition-colors",s==="all"?"bg-[var(--dg-bg-hover)] text-[var(--dg-text-primary)] font-medium":"text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"),children:"全部类型"}),K.map(o=>e.jsxs("button",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:100:13",onClick:()=>r(o.value),className:b("px-3 py-1.5 rounded-md text-sm transition-colors flex items-center gap-1.5",s===o.value?"bg-[var(--dg-bg-hover)] text-[var(--dg-text-primary)] font-medium":"text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"),children:[e.jsx("span",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:110:15",style:{color:o.color},children:"●"}),o.label]},o.value))]})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:117:7",className:"grid grid-cols-1 gap-4",children:a.length===0?e.jsx(u,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:119:11",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(j,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:120:13",className:"p-8",children:e.jsxs("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:121:15",className:"text-center",children:[e.jsx(oe,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:122:17",className:"h-12 w-12 mx-auto text-[var(--dg-text-muted)] mb-4"}),e.jsx("h3",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:123:17",className:"text-lg font-medium text-[var(--dg-text-secondary)] mb-2",children:"暂无流程模板"}),e.jsx("p",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:124:17",className:"text-sm text-[var(--dg-text-muted)]",children:"当前筛选条件下没有匹配的模板"})]})})}):a.map(o=>e.jsxs(u,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:130:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:[e.jsx(Te,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:131:15",className:"pb-2",children:e.jsxs("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:132:17",className:"flex items-start justify-between",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:133:19",className:"flex items-center gap-3",children:[e.jsx("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:134:21",className:"w-10 h-10 rounded-lg bg-[var(--dg-blue)]/10 flex items-center justify-center",children:e.jsx(oe,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:135:23",className:"h-5 w-5 text-[var(--dg-blue)]"})}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:137:21",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:138:23",className:"flex items-center gap-2",children:[e.jsx(De,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:139:25",className:"text-base text-[var(--dg-text-primary)]",children:o.name}),o.type&&e.jsx(C,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:141:27",variant:"outline",className:"text-xs border-[var(--dg-border)]",style:{color:Qe(o.type)},children:Ge(o.type)})]}),e.jsx(Fe,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:150:23",className:"text-[var(--dg-text-muted)]",children:o.description})]})]}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:153:19",className:"flex items-center gap-2",children:[e.jsx(C,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:154:21",variant:"outline",className:o.status===1||o.status==="active"||o.status===!0?"border-emerald-500/30 text-emerald-400 bg-emerald-500/10":"border-[var(--dg-border)] text-[var(--dg-text-secondary)] bg-[var(--dg-bg-tertiary)]",children:o.status===1||o.status==="active"||o.status===!0?"已启用":"已停用"}),e.jsx(i,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:164:21",variant:"ghost",size:"icon",className:"h-8 w-8 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]",children:e.jsx(Pe,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:165:23",className:"h-4 w-4"})})]})]})}),e.jsxs(j,{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:170:15",children:[e.jsx("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:171:17",className:"bg-[var(--dg-bg-primary)] rounded-lg p-4 overflow-x-auto",children:Ue(o)}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:174:17",className:"flex items-center justify-between mt-4 text-sm text-[var(--dg-text-muted)]",children:[e.jsxs("span",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:175:19",children:["创建于 ",o.created_at?new Date(o.created_at).toLocaleDateString():"--"]}),e.jsxs("span",{"code-path":"src/components/approval/ApprovalTemplateTab.tsx:176:19",children:[ne(o.steps).length," 个节点"]})]})]})]},o.id))})]})}function Ye({open:a,onOpenChange:s,instance:r,templates:o,onApprove:n,onReject:m}){return r?e.jsx(V,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:41:5",open:a,onOpenChange:s,children:e.jsxs(J,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:42:7",className:"max-w-2xl bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-h-[90vh] overflow-y-auto",children:[e.jsxs(q,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:43:9",children:[e.jsx(H,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:44:11",className:"text-[var(--dg-text-primary)]",children:"审批详情"}),e.jsx(G,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:45:11",className:"text-[var(--dg-text-muted)]",children:"查看审批流程详细信息"})]}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:47:9",className:"space-y-4 py-2",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:48:11",children:[e.jsx("h3",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:49:13",className:"text-lg font-medium text-[var(--dg-text-primary)]",children:r.title}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:50:13",className:"flex items-center gap-2 mt-1",children:[e.jsx(C,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:51:15",variant:"outline",className:"text-xs border-[var(--dg-border)]",style:{color:L(A(r))},children:U(A(r))}),e.jsxs("span",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:54:15",className:"text-xs text-[var(--dg-text-muted)]",children:["申请人:",r.applicant_name||r.applicant||"--"]}),e.jsxs("span",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:57:15",className:"text-xs text-[var(--dg-text-muted)]",children:["提交于 ",r.created_at?new Date(r.created_at).toLocaleString():"--"]})]})]}),r.content&&e.jsx("div",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:65:13",className:"bg-[var(--dg-bg-primary)] rounded-lg p-4",children:e.jsx("p",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:66:15",className:"text-sm text-[var(--dg-text-secondary)] whitespace-pre-wrap",children:r.content})}),(()=>{const p=o.find(y=>y.id===r.template_id),d=Me(r.form_data,p);return d?e.jsxs("div",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:76:15",className:"bg-[var(--dg-bg-primary)] rounded-lg p-4",children:[e.jsx("p",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:77:17",className:"text-sm font-medium text-[var(--dg-text-secondary)] mb-3",children:"申请表单"}),d]}):null})(),e.jsxs("div",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:84:11",className:"bg-[var(--dg-bg-primary)] rounded-lg p-4",children:[e.jsx("p",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:85:13",className:"text-sm font-medium text-[var(--dg-text-secondary)] mb-3",children:"审批进度"}),Y(r)]}),r.actions&&e.jsxs("div",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:91:13",className:"bg-[var(--dg-bg-primary)] rounded-lg p-4",children:[e.jsx("p",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:92:15",className:"text-sm font-medium text-[var(--dg-text-secondary)] mb-3",children:"操作记录"}),e.jsx("div",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:93:15",className:"space-y-2",children:r.actions.map((p,d)=>e.jsxs("div",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:95:19",className:"flex items-center gap-3 text-sm",children:[p.action==="approve"?e.jsx(D,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:97:23",className:"h-4 w-4 text-emerald-400"}):p.action==="reject"?e.jsx(F,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:99:23",className:"h-4 w-4 text-red-400"}):e.jsx(le,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:101:23",className:"h-4 w-4 text-[var(--dg-text-muted)]"}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:103:21",children:[e.jsx("span",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:104:23",className:"text-[var(--dg-text-secondary)]",children:p.operator_name||p.operator}),e.jsx("span",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:107:23",className:"text-[var(--dg-text-muted)] mx-1",children:"·"}),e.jsx("span",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:108:23",className:"text-[var(--dg-text-secondary)]",children:p.action==="approve"?"通过":p.action==="reject"?"拒绝":"提交"}),p.comment&&e.jsx("p",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:112:25",className:"text-xs text-[var(--dg-text-muted)] mt-0.5",children:p.comment})]}),e.jsx("span",{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:115:21",className:"text-xs text-[var(--dg-text-muted)] ml-auto",children:p.created_at?new Date(p.created_at).toLocaleString():""})]},d))})]})]}),e.jsxs(Q,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:124:9",children:[r.status==="pending"&&e.jsxs(e.Fragment,{children:[e.jsxs(i,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:127:15",variant:"outline",className:"border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:()=>{s(!1),m(r)},children:[e.jsx(F,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:128:17",className:"h-4 w-4 mr-2"}),"拒绝"]}),e.jsxs(i,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:130:15",className:"bg-emerald-500/90 hover:bg-emerald-500 text-white",onClick:()=>{s(!1),n(r)},children:[e.jsx(D,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:131:17",className:"h-4 w-4 mr-2"}),"通过"]})]}),e.jsx(i,{"code-path":"src/components/approval/ApprovalDetailDialog.tsx:135:11",variant:"ghost",onClick:()=>s(!1),children:"关闭"})]})]})}):null}function Ke({open:a,onOpenChange:s,templates:r,onSuccess:o}){const[n,m]=v.useState(null),[p,d]=v.useState({}),[y,c]=v.useState(!1),w=async()=>{if(!n){T.error("请先选择申请类型");return}const l=I(n.form_schema);for(const x of l)if(x.required&&!p[x.key]){T.error(`请填写${x.label}`);return}c(!0);try{await k.createProcess({template_id:n.id,title:p.app_name||n.name,form_data:JSON.stringify(p)}),T.success("申请已提交"),s(!1),m(null),d({}),o()}catch(x){T.error("提交失败",{description:x?.message})}finally{c(!1)}};return e.jsx(V,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:78:5",open:a,onOpenChange:l=>{l||(m(null),d({})),s(l)},children:e.jsxs(J,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:89:7",className:"max-w-2xl bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-h-[90vh] overflow-y-auto",children:[e.jsxs(q,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:90:9",children:[e.jsx(H,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:91:11",className:"text-[var(--dg-text-primary)]",children:"新建资源申请"}),e.jsx(G,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:92:11",className:"text-[var(--dg-text-muted)]",children:n?"请填写申请信息":"请选择申请类型"})]}),n?e.jsxs("div",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:135:11",className:"py-2",children:[e.jsx("div",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:136:13",className:"flex items-center gap-2 mb-4",children:e.jsx("button",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:137:15",type:"button",onClick:()=>{m(null),d({})},className:"text-xs text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)]",children:"← 返回选择类型"})}),e.jsx("div",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:145:13",className:"grid grid-cols-2 gap-x-4 gap-y-4",children:I(n.form_schema).map(l=>{const x=l.type==="textarea";return e.jsxs("div",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:149:19",className:b("space-y-1.5",x&&"col-span-2"),children:[e.jsxs(ke,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:150:21",className:"text-sm font-medium text-[var(--dg-text-secondary)]",children:[l.label,l.required&&e.jsx("span",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:152:42",className:"text-red-400 ml-0.5",children:"*"})]}),l.type==="select"?e.jsxs(_e,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:155:23",value:String(p[l.key]??""),onValueChange:h=>d(g=>({...g,[l.key]:h})),children:[e.jsx(Le,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:159:25",className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(Oe,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:160:27",placeholder:l.placeholder||`请选择${l.label}`})}),e.jsx(Ie,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:162:25",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:(l.options||[]).map(h=>e.jsx($e,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:164:29",value:h,className:"text-[var(--dg-text-primary)] focus:bg-[var(--dg-bg-hover)]",children:h},h))})]}):l.type==="textarea"?e.jsx(ce,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:171:23",placeholder:l.placeholder||`请输入${l.label}`,value:p[l.key]??"",onChange:h=>d(g=>({...g,[l.key]:h.target.value})),className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] min-h-[80px]"}):e.jsx(pe,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:178:23",type:l.type==="number"?"number":"text",placeholder:l.placeholder||`请输入${l.label}`,value:p[l.key]??"",onChange:h=>d(g=>({...g,[l.key]:h.target.value})),className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]},l.key)})})]}):e.jsx("div",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:99:11",className:"grid grid-cols-2 gap-4 py-2",children:z.map(l=>{const x=r.find(g=>g.type===l.value&&g.enabled!==!1),h=l.icon;return e.jsxs("button",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:106:17",type:"button",disabled:!x,onClick:()=>{m(x),d({})},className:b("flex flex-col items-start gap-3 p-5 rounded-xl text-left transition-colors","bg-[var(--dg-bg-tertiary)] hover:bg-[var(--dg-bg-hover)]",!x&&"opacity-40 cursor-not-allowed hover:bg-[var(--dg-bg-tertiary)]"),children:[e.jsx("div",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:117:19",className:"w-10 h-10 rounded-lg flex items-center justify-center",style:{backgroundColor:`color-mix(in srgb, ${l.color} 15%, transparent)`,color:l.color},children:e.jsx(h,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:121:21",className:"h-5 w-5"})}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:123:19",children:[e.jsx("p",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:124:21",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:l.label}),e.jsx("p",{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:125:21",className:"text-xs text-[var(--dg-text-muted)] mt-0.5",children:x?x.description||`共 ${I(x.form_schema).length} 个字段`:"暂无可用模板"})]})]},l.value)})}),e.jsxs(Q,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:196:9",children:[e.jsx(i,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:197:11",variant:"ghost",onClick:()=>s(!1),children:"取消"}),n&&e.jsxs(i,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:199:13",className:"bg-[var(--dg-blue)] hover:opacity-90 text-white",onClick:w,disabled:y,children:[y&&e.jsx($,{"code-path":"src/components/approval/ApprovalCreateDialog.tsx:204:30",className:"h-4 w-4 mr-2 animate-spin"}),"提交申请"]})]})]})})}function We(){const[a,s]=v.useState("instances"),[r,o]=v.useState([]),[n,m]=v.useState([]),[p,d]=v.useState([]),[y,c]=v.useState(!0),[w,l]=v.useState(""),[x,h]=v.useState(""),[g,de]=v.useState("all"),[me,W]=v.useState(!1),[P,Z]=v.useState(null),[ve,O]=v.useState(!1),[f,xe]=v.useState("approve"),[R,ee]=v.useState(""),[ae,te]=v.useState(!1),[ie,re]=v.useState(!1),B=async()=>{try{c(!0);const[t,N,M]=await Promise.all([k.getProcesses().catch(()=>null),k.getTemplates().catch(()=>null),k.getProcesses({status:"pending"}).catch(()=>null)]);o(t?.list||[]),m(N?.list||[]),d(M?.list||[])}catch(t){console.error("加载审批数据失败:",t)}finally{c(!1)}};v.useEffect(()=>{B()},[]);const he=r.filter(t=>{const N=(t.title||"").toLowerCase().includes(w.toLowerCase())||(t.applicant_name||t.applicant||"").toLowerCase().includes(w.toLowerCase()),M=!x||t.status===x;return N&&M}),ge=n.filter(t=>g==="all"||t.type===g),se=t=>{Z(t),W(!0)},S=(t,N)=>{xe(t),Z(N),ee(""),O(!0)},be=async()=>{if(P)try{te(!0),f==="approve"?(await k.approveProcess(P.id,R),T.success("审批通过")):(await k.rejectProcess(P.id,R),T.success("已拒绝")),O(!1),B()}catch(t){T.error("操作失败",{description:t.message})}finally{te(!1)}},ue=r.filter(t=>t.status==="pending").length,je=r.filter(t=>t.status==="approved").length,Ae=r.filter(t=>t.status==="rejected").length,E=p.filter(t=>t.status==="pending").length;return e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:139:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:141:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:142:9",children:[e.jsx("h1",{"code-path":"src/components/approval/ApprovalFlow.tsx:143:11",className:"text-2xl font-bold text-[var(--dg-text-primary)]",children:"资源申请"}),e.jsx("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:144:11",className:"text-sm text-[var(--dg-text-muted)] mt-1",children:"云服务器申请 · 应用部署申请"})]}),e.jsxs(i,{"code-path":"src/components/approval/ApprovalFlow.tsx:146:9",className:"bg-[var(--dg-blue)] hover:opacity-90 text-white",onClick:()=>re(!0),children:[e.jsx(ze,{"code-path":"src/components/approval/ApprovalFlow.tsx:150:11",className:"h-4 w-4 mr-2"}),"新建申请"]})]}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:156:7",className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(u,{"code-path":"src/components/approval/ApprovalFlow.tsx:157:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(j,{"code-path":"src/components/approval/ApprovalFlow.tsx:158:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:159:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:160:15",children:[e.jsx("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:161:17",className:"text-sm text-[var(--dg-text-muted)]",children:"待审批"}),e.jsx("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:162:17",className:"text-2xl font-bold text-amber-400",children:ue})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:164:15",className:"p-3 rounded-lg bg-amber-500/10 text-amber-400",children:e.jsx(le,{"code-path":"src/components/approval/ApprovalFlow.tsx:165:17",className:"h-5 w-5"})})]})})}),e.jsx(u,{"code-path":"src/components/approval/ApprovalFlow.tsx:170:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(j,{"code-path":"src/components/approval/ApprovalFlow.tsx:171:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:172:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:173:15",children:[e.jsx("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:174:17",className:"text-sm text-[var(--dg-text-muted)]",children:"已通过"}),e.jsx("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:175:17",className:"text-2xl font-bold text-emerald-400",children:je})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:177:15",className:"p-3 rounded-lg bg-emerald-500/10 text-emerald-400",children:e.jsx(D,{"code-path":"src/components/approval/ApprovalFlow.tsx:178:17",className:"h-5 w-5"})})]})})}),e.jsx(u,{"code-path":"src/components/approval/ApprovalFlow.tsx:183:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(j,{"code-path":"src/components/approval/ApprovalFlow.tsx:184:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:185:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:186:15",children:[e.jsx("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:187:17",className:"text-sm text-[var(--dg-text-muted)]",children:"已拒绝"}),e.jsx("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:188:17",className:"text-2xl font-bold text-red-400",children:Ae})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:190:15",className:"p-3 rounded-lg bg-red-500/10 text-red-400",children:e.jsx(F,{"code-path":"src/components/approval/ApprovalFlow.tsx:191:17",className:"h-5 w-5"})})]})})}),e.jsx(u,{"code-path":"src/components/approval/ApprovalFlow.tsx:196:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(j,{"code-path":"src/components/approval/ApprovalFlow.tsx:197:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:198:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:199:15",children:[e.jsx("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:200:17",className:"text-sm text-[var(--dg-text-muted)]",children:"我的待办"}),e.jsx("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:201:17",className:"text-2xl font-bold text-[var(--dg-blue)]",children:E})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:203:15",className:"p-3 rounded-lg bg-[var(--dg-blue)]/10 text-[var(--dg-blue)]",children:e.jsx(_,{"code-path":"src/components/approval/ApprovalFlow.tsx:204:17",className:"h-5 w-5"})})]})})})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:212:7",className:"flex items-center gap-1 border-b border-[var(--dg-border)]",children:[{key:"instances",label:"审批实例"},{key:"flows",label:"流程模板"},{key:"my-approvals",label:"我的审批"}].map(t=>e.jsxs("button",{"code-path":"src/components/approval/ApprovalFlow.tsx:218:11",onClick:()=>s(t.key),className:b("px-4 py-2 text-sm font-medium border-b-2 -mb-px transition-colors",a===t.key?"border-[var(--dg-blue)] text-[var(--dg-blue)]":"border-transparent text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"),children:[t.label,t.key==="my-approvals"&&E>0&&e.jsx(C,{"code-path":"src/components/approval/ApprovalFlow.tsx:230:15",className:"ml-2 bg-red-500/20 text-red-400 border-0 text-xs",children:E})]},t.key))}),a==="instances"&&e.jsx(He,{"code-path":"src/components/approval/ApprovalFlow.tsx:238:9",processes:r,filteredInstances:he,loading:y,searchQuery:w,setSearchQuery:l,statusFilter:x,setStatusFilter:h,onView:se,onApprove:t=>S("approve",t),onReject:t=>S("reject",t)}),a==="flows"&&e.jsx(Xe,{"code-path":"src/components/approval/ApprovalFlow.tsx:253:9",filteredTemplates:ge,templateTypeFilter:g,setTemplateTypeFilter:de}),a==="my-approvals"&&e.jsx("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:261:9",className:"grid grid-cols-1 gap-4",children:p.length===0?e.jsx(u,{"code-path":"src/components/approval/ApprovalFlow.tsx:263:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(j,{"code-path":"src/components/approval/ApprovalFlow.tsx:264:15",className:"p-12",children:e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:265:17",className:"text-center",children:[e.jsx(_,{"code-path":"src/components/approval/ApprovalFlow.tsx:266:19",className:"h-12 w-12 mx-auto text-[var(--dg-text-muted)] mb-4"}),e.jsx("h3",{"code-path":"src/components/approval/ApprovalFlow.tsx:267:19",className:"text-lg font-medium text-[var(--dg-text-secondary)] mb-2",children:"暂无待办"}),e.jsx("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:268:19",className:"text-sm text-[var(--dg-text-muted)]",children:"没有等待你处理的审批"})]})})}):p.map(t=>{const{percentage:N}=X(t);return e.jsx(u,{"code-path":"src/components/approval/ApprovalFlow.tsx:276:17",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(j,{"code-path":"src/components/approval/ApprovalFlow.tsx:277:19",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:278:21",className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:279:23",className:"flex items-start gap-3",children:[e.jsx("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:280:25",className:"w-10 h-10 rounded-lg bg-[var(--dg-bg-tertiary)] flex items-center justify-center",style:{color:L(A(t))},children:e.jsx(_,{"code-path":"src/components/approval/ApprovalFlow.tsx:281:27",className:"h-5 w-5"})}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:283:25",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:284:27",className:"flex items-center gap-2 mb-1",children:[e.jsx("h3",{"code-path":"src/components/approval/ApprovalFlow.tsx:285:29",className:"font-medium text-[var(--dg-text-primary)]",children:t.title}),e.jsx(C,{"code-path":"src/components/approval/ApprovalFlow.tsx:286:29",variant:"outline",className:"text-xs border-[var(--dg-border)]",style:{color:L(A(t))},children:U(A(t))})]}),e.jsxs("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:290:27",className:"text-xs text-[var(--dg-text-muted)]",children:["申请人:",t.applicant_name||t.applicant||"--"]}),e.jsxs("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:293:27",className:"text-xs text-[var(--dg-text-muted)]",children:["提交于 ",t.created_at?new Date(t.created_at).toLocaleString():"--"]})]})]}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:298:23",className:"flex items-center gap-2",children:[e.jsxs(i,{"code-path":"src/components/approval/ApprovalFlow.tsx:299:25",variant:"ghost",size:"sm",onClick:()=>se(t),children:[e.jsx(_,{"code-path":"src/components/approval/ApprovalFlow.tsx:300:27",className:"h-4 w-4 mr-1"}),"详情"]}),t.status==="pending"&&e.jsxs(e.Fragment,{children:[e.jsxs(i,{"code-path":"src/components/approval/ApprovalFlow.tsx:305:29",variant:"outline",size:"sm",className:"border-emerald-500/30 text-emerald-400 hover:bg-emerald-500/10",onClick:()=>S("approve",t),children:[e.jsx(D,{"code-path":"src/components/approval/ApprovalFlow.tsx:306:31",className:"h-4 w-4 mr-1"}),"通过"]}),e.jsxs(i,{"code-path":"src/components/approval/ApprovalFlow.tsx:308:29",variant:"outline",size:"sm",className:"border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:()=>S("reject",t),children:[e.jsx(F,{"code-path":"src/components/approval/ApprovalFlow.tsx:309:31",className:"h-4 w-4 mr-1"}),"拒绝"]})]})]})]}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:315:21",className:"mb-3",children:[e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:316:23",className:"flex items-center justify-between text-xs text-[var(--dg-text-muted)] mb-1.5",children:[e.jsx("span",{"code-path":"src/components/approval/ApprovalFlow.tsx:317:25",children:"审批进度"}),e.jsxs("span",{"code-path":"src/components/approval/ApprovalFlow.tsx:318:25",children:[N,"%"]})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:320:23",className:"w-full h-1.5 bg-[var(--dg-bg-tertiary)] rounded-full overflow-hidden",children:e.jsx("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:321:25",className:b("h-full rounded-full",t.status==="rejected"?"bg-red-400":"bg-[var(--dg-blue)]"),style:{width:`${N}%`}})})]}),e.jsx("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:324:21",className:"bg-[var(--dg-bg-primary)] rounded-lg p-3",children:Y(t)})]})},t.id)})}),e.jsx(Ye,{"code-path":"src/components/approval/ApprovalFlow.tsx:336:7",open:me,onOpenChange:W,instance:P,templates:n,onApprove:t=>S("approve",t),onReject:t=>S("reject",t)}),e.jsx(V,{"code-path":"src/components/approval/ApprovalFlow.tsx:346:7",open:ve,onOpenChange:O,children:e.jsxs(J,{"code-path":"src/components/approval/ApprovalFlow.tsx:347:9",className:"max-w-md bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:[e.jsxs(q,{"code-path":"src/components/approval/ApprovalFlow.tsx:348:11",children:[e.jsx(H,{"code-path":"src/components/approval/ApprovalFlow.tsx:349:13",className:"text-[var(--dg-text-primary)] flex items-center gap-2",children:f==="approve"?e.jsxs(e.Fragment,{children:[e.jsx(D,{"code-path":"src/components/approval/ApprovalFlow.tsx:352:19",className:"h-5 w-5 text-emerald-400"}),"确认通过审批"]}):e.jsxs(e.Fragment,{children:[e.jsx(F,{"code-path":"src/components/approval/ApprovalFlow.tsx:357:19",className:"h-5 w-5 text-red-400"}),"确认拒绝审批"]})}),e.jsx(G,{"code-path":"src/components/approval/ApprovalFlow.tsx:362:13",className:"text-[var(--dg-text-muted)]",children:f==="approve"?"请填写审批意见后确认通过":"请填写拒绝原因后确认拒绝"})]}),P&&e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:367:13",className:"py-2",children:[e.jsxs("p",{"code-path":"src/components/approval/ApprovalFlow.tsx:368:15",className:"text-sm text-[var(--dg-text-secondary)] mb-2",children:["审批标题:",e.jsx("span",{"code-path":"src/components/approval/ApprovalFlow.tsx:369:22",className:"text-[var(--dg-text-primary)]",children:P.title})]}),e.jsxs("div",{"code-path":"src/components/approval/ApprovalFlow.tsx:371:15",className:"space-y-2",children:[e.jsx("label",{"code-path":"src/components/approval/ApprovalFlow.tsx:372:17",className:"text-sm font-medium text-[var(--dg-text-secondary)]",children:f==="approve"?"审批意见":"拒绝原因"}),e.jsx(ce,{"code-path":"src/components/approval/ApprovalFlow.tsx:375:17",placeholder:f==="approve"?"请填写审批意见(可选)":"请填写拒绝原因",value:R,onChange:t=>ee(t.target.value),className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] min-h-[80px]"})]})]}),e.jsxs(Q,{"code-path":"src/components/approval/ApprovalFlow.tsx:384:11",children:[e.jsx(i,{"code-path":"src/components/approval/ApprovalFlow.tsx:385:13",variant:"outline",onClick:()=>O(!1),className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",children:"取消"}),e.jsxs(i,{"code-path":"src/components/approval/ApprovalFlow.tsx:388:13",onClick:be,disabled:ae,className:f==="approve"?"bg-emerald-500/90 hover:bg-emerald-500 text-white":"bg-red-500 hover:bg-red-600 text-white",children:[ae&&e.jsx($,{"code-path":"src/components/approval/ApprovalFlow.tsx:393:36",className:"h-4 w-4 mr-2 animate-spin"}),f==="approve"?"确认通过":"确认拒绝"]})]})]})}),e.jsx(Ke,{"code-path":"src/components/approval/ApprovalFlow.tsx:401:7",open:ie,onOpenChange:re,templates:n,onSuccess:B})]})}const ha=We;export{We as ApprovalFlow,ha as ApprovalFlowManager}; diff --git a/backend/static/assets/AreaChart-B2zlWfdX.js b/backend/static/assets/AreaChart-B2zlWfdX.js new file mode 100644 index 0000000..03e9a00 --- /dev/null +++ b/backend/static/assets/AreaChart-B2zlWfdX.js @@ -0,0 +1 @@ +import{b as R,L as W,m as T,i as C,c as F,A as ie,d as B,e as G,h as oe,j as q,k as se,l as le,u as ue,n as K,G as ce,o as J,p as Q,D as fe,g as pe,X as he,Y as de,f as me}from"./generateCategoricalChart-6v9BPbG2.js";import{_ as p,ab as ee,r as ve}from"./index-DfyorCky.js";var ye=["layout","type","stroke","connectNulls","isRange","ref"],be=["key"],te;function M(e){"@babel/helpers - typeof";return M=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},M(e)}function ae(e,t){if(e==null)return{};var r=Ae(e,t),a,n;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(e);for(n=0;n=0)&&Object.prototype.propertyIsEnumerable.call(e,a)&&(r[a]=e[a])}return r}function Ae(e,t){if(e==null)return{};var r={};for(var a in e)if(Object.prototype.hasOwnProperty.call(e,a)){if(t.indexOf(a)>=0)continue;r[a]=e[a]}return r}function D(){return D=Object.assign?Object.assign.bind():function(e){for(var t=1;t0||!q(f,o)||!q(c,s))?this.renderAreaWithAnimation(a,n):this.renderAreaStatically(o,s,a,n)}},{key:"render",value:function(){var a,n=this.props,i=n.hide,o=n.dot,s=n.points,u=n.className,l=n.top,f=n.left,c=n.xAxis,h=n.yAxis,A=n.width,g=n.height,x=n.isAnimationActive,v=n.id;if(i||!s||!s.length)return null;var O=this.state.isAnimationFinished,y=s.length===1,_=ee("recharts-area",u),d=c&&c.allowDataOverflow,m=h&&h.allowDataOverflow,b=d||m,w=G(v)?this.id:v,P=(a=R(o,!1))!==null&&a!==void 0?a:{r:3,strokeWidth:2},N=P.r,k=N===void 0?3:N,j=P.strokeWidth,I=j===void 0?2:j,V=se(o)?o:{},Y=V.clipDot,H=Y===void 0?!0:Y,z=k*2+I;return p.createElement(W,{className:_},d||m?p.createElement("defs",null,p.createElement("clipPath",{id:"clipPath-".concat(w)},p.createElement("rect",{x:d?f:f-A/2,y:m?l:l-g/2,width:d?A:A*2,height:m?g:g*2})),!H&&p.createElement("clipPath",{id:"clipPath-dots-".concat(w)},p.createElement("rect",{x:f-z/2,y:l-z/2,width:A+z,height:g+z}))):null,y?null:this.renderArea(b,w),(o||y)&&this.renderDots(b,H,w),(!x||O)&&le.renderCallByParent(this.props,s))}}],[{key:"getDerivedStateFromProps",value:function(a,n){return a.animationId!==n.prevAnimationId?{prevAnimationId:a.animationId,curPoints:a.points,curBaseLine:a.baseLine,prevPoints:n.curPoints,prevBaseLine:n.curBaseLine}:a.points!==n.curPoints||a.baseLine!==n.curBaseLine?{curPoints:a.points,curBaseLine:a.baseLine}:null}}])})(ve.PureComponent);te=L;E(L,"displayName","Area");E(L,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!ce.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});E(L,"getBaseValue",function(e,t,r,a){var n=e.layout,i=e.baseValue,o=t.props.baseValue,s=o??i;if(C(s)&&typeof s=="number")return s;var u=n==="horizontal"?a:r,l=u.scale.domain();if(u.type==="number"){var f=Math.max(l[0],l[1]),c=Math.min(l[0],l[1]);return s==="dataMin"?c:s==="dataMax"||f<0?f:Math.max(Math.min(l[0],l[1]),0)}return s==="dataMin"?l[0]:s==="dataMax"?l[1]:l[0]});E(L,"getComposedData",function(e){var t=e.props,r=e.item,a=e.xAxis,n=e.yAxis,i=e.xAxisTicks,o=e.yAxisTicks,s=e.bandSize,u=e.dataKey,l=e.stackedData,f=e.dataStartIndex,c=e.displayedData,h=e.offset,A=t.layout,g=l&&l.length,x=te.getBaseValue(t,r,a,n),v=A==="horizontal",O=!1,y=c.map(function(d,m){var b;g?b=l[f+m]:(b=J(d,u),Array.isArray(b)?O=!0:b=[x,b]);var w=b[1]==null||g&&J(d,u)==null;return v?{x:Q({axis:a,ticks:i,bandSize:s,entry:d,index:m}),y:w?null:n.scale(b[1]),value:b,payload:d}:{x:w?null:a.scale(b[1]),y:Q({axis:n,ticks:o,bandSize:s,entry:d,index:m}),value:b,payload:d}}),_;return g||O?_=y.map(function(d){var m=Array.isArray(d.value)?d.value[0]:null;return v?{x:d.x,y:m!=null&&d.y!=null?n.scale(m):null}:{x:m!=null?a.scale(m):null,y:d.y}}):_=v?n.scale(x):a.scale(x),S({points:y,baseLine:_,layout:A,isRange:O},h)});E(L,"renderDotItem",function(e,t){var r;if(p.isValidElement(e))r=p.cloneElement(e,t);else if(K(e))r=e(t);else{var a=ee("recharts-area-dot",typeof e!="boolean"?e.className:""),n=t.key,i=ae(t,be);r=p.createElement(fe,D({},i,{key:n,className:a}))}return r});var ke=pe({chartName:"AreaChart",GraphicalChild:L,axisComponents:[{axisType:"xAxis",AxisComp:he},{axisType:"yAxis",AxisComp:de}],formatAxisMap:me});export{ke as A,L as a}; diff --git a/backend/static/assets/AuditPage-BdPy-cgE.js b/backend/static/assets/AuditPage-BdPy-cgE.js new file mode 100644 index 0000000..ac34dbc --- /dev/null +++ b/backend/static/assets/AuditPage-BdPy-cgE.js @@ -0,0 +1,3 @@ +import{g as Le,r as a,j as e,D as ie,b as le,c as oe,d as ne,e as de,L as pe,W as we,aq as Q,a8 as Oe,q as Se,x as Ce,a as xe,A as he,S as I,X as _e,I as E,B as y,U as me,a5 as ue,aQ as ke,O as De,z as Me}from"./index-DfyorCky.js";import{C as P,a as K}from"./card-C55cvSHg.js";import{B as w}from"./badge-xNW8x0G1.js";import{T as H,a as W,b as M,c as i,d as U,e as l}from"./table-5sHV4Akp.js";import{t as F,s as Re,a as X,l as ze}from"./system-BgtMMm0X.js";import{x as ge,a as be}from"./xterm-DSqgeKvr.js";import{R as q}from"./refresh-cw-DUB_tAG-.js";import{P as Be}from"./play-cdPayOtJ.js";import{D as Te}from"./download-DoZfYs2h.js";const Ie=[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],$e=Le("octagon-x",Ie);function Ee({open:s,onOpenChange:o,sessionId:d}){const n=a.useRef(null),p=a.useRef(null),T=a.useRef(null),[h,L]=a.useState(!1),[b,O]=a.useState(""),[j,v]=a.useState(0);return a.useEffect(()=>{if(!s||!d)return;const r=new ge.Terminal({cursorBlink:!1,fontSize:13,fontFamily:'Menlo, Monaco, "Courier New", monospace',disableStdin:!0,cols:80,rows:24,theme:{background:"#0a0e14",foreground:"#d6d6d6",cursor:"#0a0e14",selectionBackground:"rgba(255,255,255,0.2)"}}),m=new be.FitAddon;r.loadAddon(m),p.current=r;let f=!1;return L(!0),O(""),v(0),F.getRecord(d).then(u=>{if(f)return;const C=typeof u=="string"?u:u?.data||u?.record_data||"";if(!C||C.trim()===""){O("No recording data available for this session"),L(!1);return}if(n.current){r.open(n.current);try{m.fit()}catch{}}const R=C.split(` +`).filter(x=>x.trim()),S=[];for(const x of R)try{const g=JSON.parse(x);Array.isArray(g)&&g.length>=3&&S.push({time:g[0],eventType:g[1],data:g[2]})}catch{}if(S.length===0){r.write(C),v(100),L(!1);return}L(!1);const $=S[S.length-1].time;let N=0,z=0;const _=()=>{if(f||N>=S.length){v(100);return}const x=S[N],g=(x.time-z)*1e3;z=x.time,N++;const B=Math.min(g,2e3);T.current=setTimeout(()=>{f||(r.write(x.data),v(Math.round(x.time/$*100)),_())},B)};_()}).catch(u=>{f||(console.error("[Replay] Load failed:",u),O("Failed to load recording data"),L(!1))}),()=>{f=!0,T.current&&clearTimeout(T.current);try{r.dispose()}catch{}p.current=null}},[s,d]),e.jsx(ie,{"code-path":"src/components/system/ReplayDialog.tsx:153:5",open:s,onOpenChange:o,children:e.jsxs(le,{"code-path":"src/components/system/ReplayDialog.tsx:154:7",showOverlay:!1,className:"bg-slate-900 border-slate-800 p-0 gap-0",style:{maxWidth:"900px",width:"90vw"},children:[e.jsxs(oe,{"code-path":"src/components/system/ReplayDialog.tsx:155:9",className:"px-4 py-3 border-b border-slate-800",children:[e.jsxs(ne,{"code-path":"src/components/system/ReplayDialog.tsx:156:11",className:"text-slate-100 text-base flex items-center gap-2",children:["Terminal Replay #",d??"",j>0&&j<100&&e.jsxs("span",{"code-path":"src/components/system/ReplayDialog.tsx:159:15",className:"text-xs text-slate-500 font-normal ml-2",children:[j,"%"]})]}),e.jsx(de,{"code-path":"src/components/system/ReplayDialog.tsx:162:11",className:"text-slate-500 sr-only",children:"Replay recorded terminal output"})]}),e.jsxs("div",{"code-path":"src/components/system/ReplayDialog.tsx:164:9",className:"relative bg-[#0a0e14]",style:{height:"460px"},children:[h&&e.jsx("div",{"code-path":"src/components/system/ReplayDialog.tsx:166:13",className:"absolute inset-0 z-10 flex items-center justify-center bg-black/40",children:e.jsx(pe,{"code-path":"src/components/system/ReplayDialog.tsx:167:15",className:"h-6 w-6 animate-spin text-blue-400"})}),b&&e.jsx("div",{"code-path":"src/components/system/ReplayDialog.tsx:171:13",className:"absolute inset-0 z-10 flex items-center justify-center bg-black/40",children:e.jsx("p",{"code-path":"src/components/system/ReplayDialog.tsx:172:15",className:"text-red-400 text-sm",children:b})}),j>0&&j<100&&e.jsx("div",{"code-path":"src/components/system/ReplayDialog.tsx:176:13",className:"absolute bottom-0 left-0 right-0 h-0.5 bg-slate-800 z-10",children:e.jsx("div",{"code-path":"src/components/system/ReplayDialog.tsx:177:15",className:"h-full bg-blue-500 transition-all duration-300",style:{width:`${j}%`}})}),e.jsx("div",{"code-path":"src/components/system/ReplayDialog.tsx:183:11",ref:n,className:"absolute inset-0 p-1"})]})]})})}function Fe({open:s,onOpenChange:o,sessionId:d,sessionInfo:n}){const p=a.useRef(null),T=a.useRef(null),h=a.useRef(null),[L,b]=a.useState(!1),[O,j]=a.useState(""),[v,r]=a.useState(n||null);a.useEffect(()=>{if(!s||!d)return;const f=p.current;if(!f)return;const u=new ge.Terminal({cursorBlink:!1,fontSize:13,fontFamily:'Menlo, Monaco, "Courier New", monospace',disableStdin:!0,theme:{background:"#0a0e14",foreground:"#d6d6d6",cursor:"#d6d6d6",selectionBackground:"#264f78",black:"#1a1a2e",red:"#ff6b6b",green:"#69db7c",yellow:"#ffd43b",blue:"#4dabf7",magenta:"#da77f2",cyan:"#63e6be",white:"#d6d6d6",brightBlack:"#4a4a4a",brightRed:"#ff8787",brightGreen:"#8ce99a",brightYellow:"#ffe066",brightBlue:"#74c0fc",brightMagenta:"#e599f7",brightCyan:"#7ae5d5",brightWhite:"#f8f9fa"}}),C=new be.FitAddon;u.loadAddon(C),u.open(f),C.fit(),T.current=u;let R=we.getState().token;if(!R)try{R=JSON.parse(localStorage.getItem("user-storage")||"")?.state?.token||""}catch{}const $=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/audit/${d}?token=${encodeURIComponent(R||"")}`;console.debug("[LiveMonitor] Connecting to:",$.replace(/token=[^&]+/,"token=***"));const N=new WebSocket($);h.current=N;let z=!1;N.onopen=()=>{console.debug("[LiveMonitor] WS connected for session:",d),z=!0,b(!0),j(""),u.writeln("\x1B[36m[审计监控] 已连接到会话...\x1B[0m")},N.onmessage=x=>{try{const g=JSON.parse(x.data);switch(g.type){case"session_info":r(g.payload),u.writeln(`\x1B[36m用户: ${g.payload.username} 服务器: ${g.payload.server_name}\x1B[0m`);break;case"history":g.data&&u.write(g.data);break;case"output":g.data&&u.write(g.data);break}}catch{}},N.onerror=x=>{console.debug("[LiveMonitor] WS error:",x),j("WebSocket 连接失败")},N.onclose=x=>{console.debug("[LiveMonitor] WS closed code:",x.code,"reason:",x.reason),z||j(`连接失败 (code=${x.code}): ${x.reason||"认证失败或网络问题"}`),b(!1),u.writeln(`\r +\x1B[33m[审计监控] 连接已断开\x1B[0m`)};const _=setTimeout(()=>{z||(j("连接超时 — 请确认已登录且有活跃会话"),N.close())},5e3);return()=>{clearTimeout(_),N.close(),u.dispose(),T.current=null,h.current=null,b(!1)}},[s,d]);const m=f=>f?new Date(f).toLocaleString():"--";return e.jsx(ie,{"code-path":"src/components/system/LiveMonitorDialog.tsx:169:5",open:s,onOpenChange:o,children:e.jsxs(le,{"code-path":"src/components/system/LiveMonitorDialog.tsx:170:7",showOverlay:!1,className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-[95vw] max-h-[90vh] w-[1200px]",children:[e.jsxs(oe,{"code-path":"src/components/system/LiveMonitorDialog.tsx:171:9",children:[e.jsxs(ne,{"code-path":"src/components/system/LiveMonitorDialog.tsx:172:11",className:"text-[var(--dg-text-primary)] flex items-center gap-2",children:[e.jsx(Q,{"code-path":"src/components/system/LiveMonitorDialog.tsx:173:13",className:"h-5 w-5 text-emerald-400"}),"终端实时监控",L&&e.jsx(w,{"code-path":"src/components/system/LiveMonitorDialog.tsx:176:15",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10 ml-2 text-xs",children:"● 在线"}),!L&&!O&&e.jsxs(w,{"code-path":"src/components/system/LiveMonitorDialog.tsx:181:15",variant:"outline",className:"border-yellow-500/30 text-yellow-400 bg-yellow-500/10 ml-2 text-xs",children:[e.jsx(pe,{"code-path":"src/components/system/LiveMonitorDialog.tsx:182:17",className:"h-3 w-3 animate-spin mr-1"}),"连接中"]}),O&&e.jsx(w,{"code-path":"src/components/system/LiveMonitorDialog.tsx:187:15",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10 ml-2 text-xs",children:"连接失败"})]}),e.jsx(de,{"code-path":"src/components/system/LiveMonitorDialog.tsx:192:11",className:"text-[var(--dg-text-secondary)]",children:v&&e.jsxs("div",{"code-path":"src/components/system/LiveMonitorDialog.tsx:194:15",className:"flex items-center gap-4 text-xs mt-1 flex-wrap",children:[e.jsxs("span",{"code-path":"src/components/system/LiveMonitorDialog.tsx:195:17",className:"flex items-center gap-1",children:[e.jsx(Oe,{"code-path":"src/components/system/LiveMonitorDialog.tsx:196:19",className:"h-3 w-3"}),v.username]}),e.jsxs("span",{"code-path":"src/components/system/LiveMonitorDialog.tsx:199:17",className:"flex items-center gap-1",children:[e.jsx(Se,{"code-path":"src/components/system/LiveMonitorDialog.tsx:200:19",className:"h-3 w-3"}),v.server_name," (",v.server_ip,")"]}),e.jsxs("span",{"code-path":"src/components/system/LiveMonitorDialog.tsx:203:17",className:"flex items-center gap-1",children:[e.jsx(Ce,{"code-path":"src/components/system/LiveMonitorDialog.tsx:204:19",className:"h-3 w-3"}),m(v.start_time)]})]})})]}),e.jsx("div",{"code-path":"src/components/system/LiveMonitorDialog.tsx:212:9",ref:p,className:"w-full rounded-md overflow-hidden border border-[var(--dg-border)]",style:{height:"55vh"}})]})})}function je(s){if(!s||s<0)return"--";if(s<60)return`${s}秒`;const o=Math.floor(s/60),d=s%60;if(o<60)return`${o}分${d>0?`${d}秒`:""}`;const n=Math.floor(o/60),p=o%60;return`${n}时${p>0?`${p}分`:""}`}function Pe(s){return s?s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(1)} KB`:`${(s/1024/1024).toFixed(2)} MB`:"0 B"}function fe(s){return s==="active"?e.jsxs(w,{"code-path":"src/pages/TerminalAuditTab.tsx:84:7",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:[e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:85:9",className:"w-1.5 h-1.5 rounded-full bg-emerald-400 mr-1.5 inline-block animate-pulse"}),"活动中"]}):s==="failed"?e.jsx(w,{"code-path":"src/pages/TerminalAuditTab.tsx:92:7",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10",children:"失败"}):e.jsx(w,{"code-path":"src/pages/TerminalAuditTab.tsx:98:5",variant:"outline",className:"border-slate-500/30 text-slate-400 bg-slate-500/10",children:"已关闭"})}function Ke(s){const[o,d]=a.useState(0);return a.useEffect(()=>{if(!s)return;const n=new Date(s).getTime(),p=()=>d(Math.floor((Date.now()-n)/1e3));p();const T=setInterval(p,1e3);return()=>clearInterval(T)},[s]),o}const He=[{id:"active",name:"在线会话",icon:he},{id:"history",name:"历史会话",icon:Q},{id:"commands",name:"会话命令",icon:I}];function ce(){const s=xe(),[o,d]=a.useState("active"),[n,p]=a.useState([]),[T,h]=a.useState(!0),[L,b]=a.useState(""),[O,j]=a.useState([]),[v,r]=a.useState(!0),[m,f]=a.useState(""),[u,C]=a.useState(null),[R,S]=a.useState(!1),[$,N]=a.useState([]),[z,_]=a.useState(!0),[x,g]=a.useState(""),[B,V]=a.useState(""),[Y,c]=a.useState(!1),[k,Z]=a.useState(null),J=a.useCallback(async()=>{h(!0);try{const t=await F.list({page:1,page_size:100,status:"active"});p(t?.list??[])}catch{p([])}finally{h(!1)}},[]);a.useEffect(()=>{J()},[J]);const te=n.filter(t=>{const A=L.toLowerCase();return!A||(t.username||"").toLowerCase().includes(A)||(t.server_name||"").toLowerCase().includes(A)||(t.server_ip||"").toLowerCase().includes(A)}),Ae=async(t,A)=>{if(await s({title:"阻断会话",description:`确认强制断开用户「${A}」的当前会话吗?`,confirmText:"阻断",variant:"destructive"}))try{await F.kill(t),await J()}catch{}},ve=t=>{Z(t),c(!0)},ee=a.useCallback(async()=>{r(!0);try{const t=await F.list({page:1,page_size:100,status:"closed"});j(t?.list??[])}catch{j([])}finally{r(!1)}},[]);a.useEffect(()=>{ee()},[ee]);const ae=O.filter(t=>{const A=m.toLowerCase();return!A||(t.username||"").toLowerCase().includes(A)||(t.server_name||"").toLowerCase().includes(A)||(t.server_ip||"").toLowerCase().includes(A)}),Ne=t=>{C(t),S(!0)},ye=async t=>{try{await F.download(t)}catch{}},se=a.useCallback(async()=>{_(!0);try{const t={page:1,page_size:200};B&&(t.session_id=Number(B));const A=await Re.list(t);N(A?.list??[])}catch{N([])}finally{_(!1)}},[B]);a.useEffect(()=>{se()},[se]);const re=$.filter(t=>{const A=x.toLowerCase();return!A||(t.username||"").toLowerCase().includes(A)||(t.command||"").toLowerCase().includes(A)});return e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:278:5",className:"space-y-4",children:[e.jsx("div",{"code-path":"src/pages/TerminalAuditTab.tsx:280:7",className:"flex gap-1 bg-[var(--dg-bg-secondary)] p-1 rounded-lg border border-[var(--dg-border)] w-fit",children:He.map(t=>e.jsxs("button",{"code-path":"src/pages/TerminalAuditTab.tsx:282:11",onClick:()=>d(t.id),className:_e("flex items-center gap-2 px-4 py-2 rounded-md text-sm font-medium transition-all",o===t.id?"bg-[var(--dg-bg-tertiary)] text-[var(--dg-text-primary)] shadow-sm":"text-[var(--dg-text-muted)] hover:text-[var(--dg-text-secondary)]"),children:[e.jsx(t.icon,{"code-path":"src/pages/TerminalAuditTab.tsx:292:13",className:"h-4 w-4"}),t.name]},t.id))}),o==="active"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:301:11",className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:302:13",className:"relative w-64",children:[e.jsx(I,{"code-path":"src/pages/TerminalAuditTab.tsx:303:15",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(E,{"code-path":"src/pages/TerminalAuditTab.tsx:304:15",placeholder:"搜索用户/服务器...",value:L,onChange:t=>b(t.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"})]}),e.jsxs(y,{"code-path":"src/pages/TerminalAuditTab.tsx:311:13",variant:"outline",className:"border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800",onClick:J,children:[e.jsx(q,{"code-path":"src/pages/TerminalAuditTab.tsx:316:15",className:"h-4 w-4 mr-2"}),"刷新"]})]}),e.jsx(P,{"code-path":"src/pages/TerminalAuditTab.tsx:321:11",className:"bg-slate-900 border-slate-800",children:e.jsx(K,{"code-path":"src/pages/TerminalAuditTab.tsx:322:13",className:"p-0",children:e.jsx("div",{"code-path":"src/pages/TerminalAuditTab.tsx:323:15",className:"border-t border-slate-800",children:T?e.jsx("div",{"code-path":"src/pages/TerminalAuditTab.tsx:325:19",className:"flex items-center justify-center py-16",children:e.jsx("div",{"code-path":"src/pages/TerminalAuditTab.tsx:326:21",className:"w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"})}):te.length===0?e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:329:19",className:"flex flex-col items-center justify-center py-16 text-slate-500",children:[e.jsx(he,{"code-path":"src/pages/TerminalAuditTab.tsx:330:21",className:"h-8 w-8 mb-3 opacity-40"}),e.jsx("p",{"code-path":"src/pages/TerminalAuditTab.tsx:331:21",className:"text-sm",children:"暂无在线会话"})]}):e.jsxs(H,{"code-path":"src/pages/TerminalAuditTab.tsx:334:19",children:[e.jsx(W,{"code-path":"src/pages/TerminalAuditTab.tsx:335:21",children:e.jsxs(M,{"code-path":"src/pages/TerminalAuditTab.tsx:336:23",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:337:25",className:"text-slate-400",children:"ID"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:338:25",className:"text-slate-400",children:"用户"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:339:25",className:"text-slate-400",children:"目标服务器"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:340:25",className:"text-slate-400",children:"端口"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:341:25",className:"text-slate-400",children:"开始时间"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:342:25",className:"text-slate-400",children:"时长"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:343:25",className:"text-slate-400",children:"状态"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:344:25",className:"text-slate-400 text-right",children:"操作"})]})}),e.jsx(U,{"code-path":"src/pages/TerminalAuditTab.tsx:347:21",children:te.map(t=>e.jsx(We,{"code-path":"src/pages/TerminalAuditTab.tsx:349:25",session:t,onKill:Ae,onMonitor:ve},t.id))})]})})})})]}),o==="history"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:368:11",className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:369:13",className:"relative w-64",children:[e.jsx(I,{"code-path":"src/pages/TerminalAuditTab.tsx:370:15",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(E,{"code-path":"src/pages/TerminalAuditTab.tsx:371:15",placeholder:"搜索用户/服务器/IP...",value:m,onChange:t=>f(t.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"})]}),e.jsxs(y,{"code-path":"src/pages/TerminalAuditTab.tsx:378:13",variant:"outline",className:"border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800",onClick:ee,children:[e.jsx(q,{"code-path":"src/pages/TerminalAuditTab.tsx:383:15",className:"h-4 w-4 mr-2"}),"刷新"]})]}),e.jsx(P,{"code-path":"src/pages/TerminalAuditTab.tsx:388:11",className:"bg-slate-900 border-slate-800",children:e.jsx(K,{"code-path":"src/pages/TerminalAuditTab.tsx:389:13",className:"p-0",children:e.jsx("div",{"code-path":"src/pages/TerminalAuditTab.tsx:390:15",className:"border-t border-slate-800",children:v?e.jsx("div",{"code-path":"src/pages/TerminalAuditTab.tsx:392:19",className:"flex items-center justify-center py-16",children:e.jsx("div",{"code-path":"src/pages/TerminalAuditTab.tsx:393:21",className:"w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"})}):ae.length===0?e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:396:19",className:"flex flex-col items-center justify-center py-16 text-slate-500",children:[e.jsx(Q,{"code-path":"src/pages/TerminalAuditTab.tsx:397:21",className:"h-8 w-8 mb-3 opacity-40"}),e.jsx("p",{"code-path":"src/pages/TerminalAuditTab.tsx:398:21",className:"text-sm",children:"暂无历史会话"})]}):e.jsxs(H,{"code-path":"src/pages/TerminalAuditTab.tsx:401:19",children:[e.jsx(W,{"code-path":"src/pages/TerminalAuditTab.tsx:402:21",children:e.jsxs(M,{"code-path":"src/pages/TerminalAuditTab.tsx:403:23",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:404:25",className:"text-slate-400",children:"ID"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:405:25",className:"text-slate-400",children:"用户"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:406:25",className:"text-slate-400",children:"目标服务器"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:407:25",className:"text-slate-400",children:"端口"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:408:25",className:"text-slate-400",children:"开始时间"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:409:25",className:"text-slate-400",children:"结束时间"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:410:25",className:"text-slate-400",children:"时长"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:411:25",className:"text-slate-400",children:"状态"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:412:25",className:"text-slate-400 text-right",children:"操作"})]})}),e.jsx(U,{"code-path":"src/pages/TerminalAuditTab.tsx:415:21",children:ae.map(t=>e.jsxs(M,{"code-path":"src/pages/TerminalAuditTab.tsx:417:25",className:"border-slate-800 hover:bg-slate-800/50",children:[e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:418:27",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:419:29",className:"text-sm text-slate-400",children:t.id})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:421:27",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:422:29",className:"text-sm text-slate-200",children:t.username||"--"})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:424:27",children:e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:425:29",className:"flex flex-col",children:[e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:426:31",className:"text-sm text-slate-200",children:t.server_name||"--"}),e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:427:31",className:"text-xs text-slate-500",children:t.server_ip})]})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:430:27",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:431:29",className:"text-sm text-slate-400",children:t.server_port})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:433:27",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:434:29",className:"text-sm text-slate-400",children:t.start_time?new Date(t.start_time).toLocaleString():"--"})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:438:27",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:439:29",className:"text-sm text-slate-400",children:t.end_time?new Date(t.end_time).toLocaleString():"--"})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:443:27",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:444:29",className:"text-sm text-slate-300",children:je(t.duration)})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:446:27",children:fe(t.status)}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:447:27",children:e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:448:29",className:"flex items-center justify-end gap-1",children:[e.jsx(y,{"code-path":"src/pages/TerminalAuditTab.tsx:449:31",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-blue-400 hover:bg-slate-800",onClick:()=>Ne(t.id),title:"回放",children:e.jsx(Be,{"code-path":"src/pages/TerminalAuditTab.tsx:456:33",className:"h-4 w-4"})}),e.jsx(y,{"code-path":"src/pages/TerminalAuditTab.tsx:458:31",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-green-400 hover:bg-slate-800",onClick:()=>ye(t.id),title:"下载录制",children:e.jsx(Te,{"code-path":"src/pages/TerminalAuditTab.tsx:465:33",className:"h-4 w-4"})})]})})]},t.id))})]})})})})]}),o==="commands"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:483:11",className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:484:13",className:"relative w-64",children:[e.jsx(I,{"code-path":"src/pages/TerminalAuditTab.tsx:485:15",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(E,{"code-path":"src/pages/TerminalAuditTab.tsx:486:15",placeholder:"搜索用户/命令...",value:x,onChange:t=>g(t.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"})]}),e.jsx(E,{"code-path":"src/pages/TerminalAuditTab.tsx:493:13",placeholder:"会话 ID(可选)",value:B,onChange:t=>V(t.target.value),className:"w-32 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"}),e.jsxs(y,{"code-path":"src/pages/TerminalAuditTab.tsx:499:13",variant:"outline",className:"border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800",onClick:se,children:[e.jsx(q,{"code-path":"src/pages/TerminalAuditTab.tsx:504:15",className:"h-4 w-4 mr-2"}),"刷新"]})]}),e.jsx(P,{"code-path":"src/pages/TerminalAuditTab.tsx:509:11",className:"bg-slate-900 border-slate-800",children:e.jsx(K,{"code-path":"src/pages/TerminalAuditTab.tsx:510:13",className:"p-0",children:e.jsx("div",{"code-path":"src/pages/TerminalAuditTab.tsx:511:15",className:"border-t border-slate-800",children:z?e.jsx("div",{"code-path":"src/pages/TerminalAuditTab.tsx:513:19",className:"flex items-center justify-center py-16",children:e.jsx("div",{"code-path":"src/pages/TerminalAuditTab.tsx:514:21",className:"w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"})}):re.length===0?e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:517:19",className:"flex flex-col items-center justify-center py-16 text-slate-500",children:[e.jsx(I,{"code-path":"src/pages/TerminalAuditTab.tsx:518:21",className:"h-8 w-8 mb-3 opacity-40"}),e.jsx("p",{"code-path":"src/pages/TerminalAuditTab.tsx:519:21",className:"text-sm",children:"暂无会话命令记录"})]}):e.jsxs(H,{"code-path":"src/pages/TerminalAuditTab.tsx:522:19",children:[e.jsx(W,{"code-path":"src/pages/TerminalAuditTab.tsx:523:21",children:e.jsxs(M,{"code-path":"src/pages/TerminalAuditTab.tsx:524:23",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:525:25",className:"text-slate-400",children:"时间"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:526:25",className:"text-slate-400",children:"用户"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:527:25",className:"text-slate-400",children:"命令"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:528:25",className:"text-slate-400",children:"退出码"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:529:25",className:"text-slate-400",children:"输出大小"}),e.jsx(i,{"code-path":"src/pages/TerminalAuditTab.tsx:530:25",className:"text-slate-400",children:"关联会话"})]})}),e.jsx(U,{"code-path":"src/pages/TerminalAuditTab.tsx:533:21",children:re.map(t=>e.jsxs(M,{"code-path":"src/pages/TerminalAuditTab.tsx:535:25",className:"border-slate-800 hover:bg-slate-800/50",children:[e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:536:27",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:537:29",className:"text-sm text-slate-400",children:t.created_at?new Date(t.created_at).toLocaleString():"--"})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:541:27",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:542:29",className:"text-sm text-slate-200",children:t.username||"--"})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:544:27",children:e.jsx("code",{"code-path":"src/pages/TerminalAuditTab.tsx:545:29",className:"text-xs text-slate-300 bg-slate-800 px-2 py-0.5 rounded max-w-[400px] truncate block",children:t.command||"--"})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:549:27",children:e.jsx(w,{"code-path":"src/pages/TerminalAuditTab.tsx:550:29",variant:"outline",className:t.exit_code===0?"border-emerald-500/30 text-emerald-400 bg-emerald-500/10":"border-red-500/30 text-red-400 bg-red-500/10",children:t.exit_code})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:561:27",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:562:29",className:"text-sm text-slate-400",children:Pe(t.output_size)})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:564:27",children:e.jsxs("span",{"code-path":"src/pages/TerminalAuditTab.tsx:565:29",className:"text-xs text-slate-500",children:["#",t.session_id]})})]},t.id))})]})})})})]}),e.jsx(Ee,{"code-path":"src/pages/TerminalAuditTab.tsx:579:7",open:R,onOpenChange:S,sessionId:u}),e.jsx(Fe,{"code-path":"src/pages/TerminalAuditTab.tsx:582:7",open:Y,onOpenChange:c,sessionId:k})]})}function We({session:s,onKill:o,onMonitor:d}){const n=Ke(s.start_time);return e.jsxs(M,{"code-path":"src/pages/TerminalAuditTab.tsx:603:5",className:"border-slate-800 hover:bg-slate-800/50",children:[e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:604:7",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:605:9",className:"text-sm text-slate-400",children:s.id})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:607:7",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:608:9",className:"text-sm text-slate-200",children:s.username||"--"})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:610:7",children:e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:611:9",className:"flex flex-col",children:[e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:612:11",className:"text-sm text-slate-200",children:s.server_name||"--"}),e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:613:11",className:"text-xs text-slate-500",children:s.server_ip})]})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:616:7",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:617:9",className:"text-sm text-slate-400",children:s.server_port})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:619:7",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:620:9",className:"text-sm text-slate-400",children:s.start_time?new Date(s.start_time).toLocaleString():"--"})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:624:7",children:e.jsx("span",{"code-path":"src/pages/TerminalAuditTab.tsx:625:9",className:"text-sm text-emerald-400 font-mono",children:je(n)})}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:627:7",children:fe(s.status)}),e.jsx(l,{"code-path":"src/pages/TerminalAuditTab.tsx:628:7",children:e.jsxs("div",{"code-path":"src/pages/TerminalAuditTab.tsx:629:9",className:"flex items-center justify-end gap-1",children:[e.jsx(y,{"code-path":"src/pages/TerminalAuditTab.tsx:630:11",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-red-400 hover:bg-slate-800",onClick:()=>o(s.id,s.username),title:"阻断会话",children:e.jsx($e,{"code-path":"src/pages/TerminalAuditTab.tsx:637:13",className:"h-4 w-4"})}),e.jsx(y,{"code-path":"src/pages/TerminalAuditTab.tsx:639:11",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-blue-400 hover:bg-slate-800",onClick:()=>d(s.id),title:"实时查看",children:e.jsx(me,{"code-path":"src/pages/TerminalAuditTab.tsx:646:13",className:"h-4 w-4"})})]})})]})}function Ue(s){return{id:String(s.id??""),userId:String(s.user_id??s.userId??""),username:s.username??"",module:s.module??s.resource??"",action:s.action??"",resource:s.resource??"",ip:s.ip??"",userAgent:s.user_agent??s.userAgent??"",result:s.result==="failure"?"failure":"success",message:s.message??s.detail??"",createdAt:s.createdAt??s.created_at??""}}function qe(){xe();const[s,o]=a.useState([]),[d,n]=a.useState(!0),[p,T]=a.useState(""),[h,L]=a.useState(""),[b,O]=a.useState(""),[j,v]=a.useState([]),[r,m]=a.useState([]),[f,u]=a.useState(null),[C,R]=a.useState(!1),[S,$]=a.useState(null),[N,z]=a.useState(!1),_=a.useCallback(async()=>{n(!0);try{const c={page:1,page_size:100};h&&(c.module=h),b&&(c.action=b);const Z=(await X.getLogs(c))?.list??[];o(Z.map(Ue))}catch{o([])}finally{n(!1)}},[h,b]),x=a.useCallback(async()=>{try{const[c,k]=await Promise.all([X.getModules(),X.getActions()]);v(c?.list??c??[]),m(k?.list??k??[])}catch{}},[]);a.useEffect(()=>{_(),x()},[_,x]);const g=s.filter(c=>{const k=p.toLowerCase();return!k||c.username.toLowerCase().includes(k)||c.module.toLowerCase().includes(k)||c.action.toLowerCase().includes(k)||c.resource.toLowerCase().includes(k)}),B=c=>c==="success"?e.jsx(w,{"code-path":"src/pages/AuditOperationsTab.tsx:118:7",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:"成功"}):e.jsx(w,{"code-path":"src/pages/AuditOperationsTab.tsx:122:7",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10",children:"失败"}),V=async()=>{try{const c={};h&&(c.module=h),b&&(c.action=b),await X.exportLogs(c)}catch{}},Y=c=>{u(c)};return e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:157:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:159:7",className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:160:9",className:"relative w-64",children:[e.jsx(I,{"code-path":"src/pages/AuditOperationsTab.tsx:161:11",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(E,{"code-path":"src/pages/AuditOperationsTab.tsx:162:11",placeholder:"搜索操作日志...",value:p,onChange:c=>T(c.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"})]}),e.jsxs("select",{"code-path":"src/pages/AuditOperationsTab.tsx:171:9",value:h,onChange:c=>L(c.target.value),className:"h-9 px-3 text-sm rounded-md bg-slate-800/50 border border-slate-700 text-slate-300 focus:outline-none focus:border-blue-500",children:[e.jsx("option",{"code-path":"src/pages/AuditOperationsTab.tsx:176:11",value:"",children:"全部模块"}),j.map(c=>e.jsx("option",{"code-path":"src/pages/AuditOperationsTab.tsx:178:13",value:c.value,children:c.label},c.value))]}),e.jsxs("select",{"code-path":"src/pages/AuditOperationsTab.tsx:185:9",value:b,onChange:c=>O(c.target.value),className:"h-9 px-3 text-sm rounded-md bg-slate-800/50 border border-slate-700 text-slate-300 focus:outline-none focus:border-blue-500",children:[e.jsx("option",{"code-path":"src/pages/AuditOperationsTab.tsx:190:11",value:"",children:"全部操作"}),r.map(c=>e.jsx("option",{"code-path":"src/pages/AuditOperationsTab.tsx:192:13",value:c.value,children:c.label},c.value))]}),e.jsxs(y,{"code-path":"src/pages/AuditOperationsTab.tsx:198:9",variant:"outline",className:"border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800",onClick:_,children:[e.jsx(q,{"code-path":"src/pages/AuditOperationsTab.tsx:203:11",className:"h-4 w-4 mr-2"}),"刷新"]}),e.jsxs(y,{"code-path":"src/pages/AuditOperationsTab.tsx:206:9",variant:"outline",className:"border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800",onClick:V,children:[e.jsx(Te,{"code-path":"src/pages/AuditOperationsTab.tsx:211:11",className:"h-4 w-4 mr-2"}),"导出"]})]}),e.jsx(P,{"code-path":"src/pages/AuditOperationsTab.tsx:217:7",className:"bg-slate-900 border-slate-800",children:e.jsx(K,{"code-path":"src/pages/AuditOperationsTab.tsx:218:9",className:"p-0",children:e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:219:11",className:"border-t border-slate-800",children:d?e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:221:15",className:"flex items-center justify-center py-16",children:e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:222:17",className:"w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"})}):g.length===0?e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:225:15",className:"flex flex-col items-center justify-center py-16 text-slate-500",children:[e.jsx(I,{"code-path":"src/pages/AuditOperationsTab.tsx:226:17",className:"h-8 w-8 mb-3 opacity-40"}),e.jsx("p",{"code-path":"src/pages/AuditOperationsTab.tsx:227:17",className:"text-sm",children:"暂无操作日志"})]}):e.jsxs(H,{"code-path":"src/pages/AuditOperationsTab.tsx:230:15",children:[e.jsx(W,{"code-path":"src/pages/AuditOperationsTab.tsx:231:17",children:e.jsxs(M,{"code-path":"src/pages/AuditOperationsTab.tsx:232:19",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(i,{"code-path":"src/pages/AuditOperationsTab.tsx:233:21",className:"text-slate-400",children:"时间"}),e.jsx(i,{"code-path":"src/pages/AuditOperationsTab.tsx:234:21",className:"text-slate-400",children:"用户"}),e.jsx(i,{"code-path":"src/pages/AuditOperationsTab.tsx:235:21",className:"text-slate-400",children:"模块"}),e.jsx(i,{"code-path":"src/pages/AuditOperationsTab.tsx:236:21",className:"text-slate-400",children:"操作类型"}),e.jsx(i,{"code-path":"src/pages/AuditOperationsTab.tsx:237:21",className:"text-slate-400",children:"资源"}),e.jsx(i,{"code-path":"src/pages/AuditOperationsTab.tsx:238:21",className:"text-slate-400",children:"IP"}),e.jsx(i,{"code-path":"src/pages/AuditOperationsTab.tsx:239:21",className:"text-slate-400",children:"结果"}),e.jsx(i,{"code-path":"src/pages/AuditOperationsTab.tsx:240:21",className:"text-slate-400 text-right",children:"详情"})]})}),e.jsx(U,{"code-path":"src/pages/AuditOperationsTab.tsx:243:17",children:g.map(c=>e.jsxs(M,{"code-path":"src/pages/AuditOperationsTab.tsx:245:21",className:"border-slate-800 hover:bg-slate-800/50",children:[e.jsx(l,{"code-path":"src/pages/AuditOperationsTab.tsx:246:23",children:e.jsx("span",{"code-path":"src/pages/AuditOperationsTab.tsx:247:25",className:"text-sm text-slate-400",children:c.createdAt?new Date(c.createdAt).toLocaleString():"--"})}),e.jsx(l,{"code-path":"src/pages/AuditOperationsTab.tsx:251:23",children:e.jsx("span",{"code-path":"src/pages/AuditOperationsTab.tsx:252:25",className:"text-sm text-slate-200",children:c.username||"--"})}),e.jsx(l,{"code-path":"src/pages/AuditOperationsTab.tsx:254:23",children:e.jsx("span",{"code-path":"src/pages/AuditOperationsTab.tsx:255:25",className:"text-sm text-slate-300",children:c.module||"--"})}),e.jsx(l,{"code-path":"src/pages/AuditOperationsTab.tsx:257:23",children:e.jsx(w,{"code-path":"src/pages/AuditOperationsTab.tsx:258:25",variant:"outline",className:"border-blue-500/30 text-blue-400 bg-blue-500/10",children:c.action||"--"})}),e.jsx(l,{"code-path":"src/pages/AuditOperationsTab.tsx:262:23",children:e.jsx("code",{"code-path":"src/pages/AuditOperationsTab.tsx:263:25",className:"text-xs text-slate-400 bg-slate-800 px-2 py-0.5 rounded",children:c.resource||"--"})}),e.jsx(l,{"code-path":"src/pages/AuditOperationsTab.tsx:267:23",children:e.jsx("span",{"code-path":"src/pages/AuditOperationsTab.tsx:268:25",className:"text-sm text-slate-400",children:c.ip||"--"})}),e.jsx(l,{"code-path":"src/pages/AuditOperationsTab.tsx:270:23",children:B(c.result)}),e.jsx(l,{"code-path":"src/pages/AuditOperationsTab.tsx:271:23",children:e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:272:25",className:"flex items-center justify-end",children:e.jsx(y,{"code-path":"src/pages/AuditOperationsTab.tsx:273:27",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-blue-400 hover:bg-slate-800",onClick:()=>Y(c),title:"查看详情",children:e.jsx(me,{"code-path":"src/pages/AuditOperationsTab.tsx:280:29",className:"h-4 w-4"})})})})]},c.id))})]})})})}),e.jsx(Je,{"code-path":"src/pages/AuditOperationsTab.tsx:294:7",log:f,onClose:()=>u(null)}),e.jsx(Xe,{"code-path":"src/pages/AuditOperationsTab.tsx:297:7",open:C,onClose:()=>R(!1),loading:N,stats:S})]})}function Je({log:s,onClose:o}){return s?e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:315:5",className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:316:7",className:"absolute inset-0 bg-black/60",onClick:o}),e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:317:7",className:"relative bg-slate-900 border border-slate-800 rounded-lg p-6 max-w-lg w-full mx-4 shadow-2xl",children:[e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:318:9",className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{"code-path":"src/pages/AuditOperationsTab.tsx:319:11",className:"text-lg font-semibold text-slate-100",children:"操作日志详情"}),e.jsx(y,{"code-path":"src/pages/AuditOperationsTab.tsx:320:11",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-slate-100",onClick:o,children:e.jsx(ue,{"code-path":"src/pages/AuditOperationsTab.tsx:326:13",className:"h-4 w-4"})})]}),e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:330:9",className:"space-y-3 text-sm",children:[e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:331:11",label:"ID",value:s.id}),e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:332:11",label:"时间",value:s.createdAt?new Date(s.createdAt).toLocaleString():"--"}),e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:333:11",label:"用户",value:s.username||"--"}),e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:334:11",label:"用户ID",value:s.userId||"--"}),e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:335:11",label:"模块",value:s.module||"--"}),e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:336:11",label:"操作类型",value:s.action||"--"}),e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:337:11",label:"资源",value:s.resource||"--"}),e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:338:11",label:"IP地址",value:s.ip||"--"}),e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:339:11",label:"User-Agent",value:s.userAgent||"--"}),e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:340:11",label:"结果",value:e.jsx(w,{"code-path":"src/pages/AuditOperationsTab.tsx:343:15",variant:"outline",className:s.result==="success"?"border-emerald-500/30 text-emerald-400 bg-emerald-500/10":"border-red-500/30 text-red-400 bg-red-500/10",children:s.result==="success"?"成功":"失败"})}),s.message&&e.jsx(D,{"code-path":"src/pages/AuditOperationsTab.tsx:355:27",label:"详情",value:s.message,mono:!0})]}),e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:358:9",className:"mt-5 flex justify-end",children:e.jsx(y,{"code-path":"src/pages/AuditOperationsTab.tsx:359:11",variant:"outline",className:"border-slate-700 text-slate-300 hover:bg-slate-800",onClick:o,children:"关闭"})})]})]}):null}function D({label:s,value:o,mono:d}){return e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:374:5",className:"flex items-start gap-4",children:[e.jsx("span",{"code-path":"src/pages/AuditOperationsTab.tsx:375:7",className:"text-slate-500 w-20 flex-shrink-0",children:s}),e.jsx("span",{"code-path":"src/pages/AuditOperationsTab.tsx:376:7",className:d?"text-slate-300 font-mono text-xs break-all":"text-slate-200 break-all",children:o})]})}function Xe({open:s,onClose:o,loading:d,stats:n}){return s?e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:401:5",className:"fixed inset-0 z-50 flex items-center justify-center",children:[e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:402:7",className:"absolute inset-0 bg-black/60",onClick:o}),e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:403:7",className:"relative bg-slate-900 border border-slate-800 rounded-lg p-6 max-w-md w-full mx-4 shadow-2xl",children:[e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:404:9",className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{"code-path":"src/pages/AuditOperationsTab.tsx:405:11",className:"text-lg font-semibold text-slate-100",children:"审计统计"}),e.jsx(y,{"code-path":"src/pages/AuditOperationsTab.tsx:406:11",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-slate-100",onClick:o,children:e.jsx(ue,{"code-path":"src/pages/AuditOperationsTab.tsx:412:13",className:"h-4 w-4"})})]}),d?e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:417:11",className:"flex items-center justify-center py-10",children:e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:418:13",className:"w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"})}):n?e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:421:11",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:422:13",className:"grid grid-cols-2 gap-3",children:[e.jsx(G,{"code-path":"src/pages/AuditOperationsTab.tsx:423:15",label:"总日志数",value:String(n.total_logs??"--"),color:"blue"}),e.jsx(G,{"code-path":"src/pages/AuditOperationsTab.tsx:424:15",label:"今日日志",value:String(n.today_count??"--"),color:"emerald"}),e.jsx(G,{"code-path":"src/pages/AuditOperationsTab.tsx:425:15",label:"成功数",value:String(n.success_count??"--"),color:"emerald"}),e.jsx(G,{"code-path":"src/pages/AuditOperationsTab.tsx:426:15",label:"失败数",value:String(n.failure_count??"--"),color:"red"})]}),n.top_modules&&n.top_modules.length>0&&e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:430:15",children:[e.jsx("h4",{"code-path":"src/pages/AuditOperationsTab.tsx:431:17",className:"text-xs font-semibold text-slate-400 mb-2",children:"热门模块"}),e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:432:17",className:"space-y-1",children:n.top_modules.slice(0,5).map((p,T)=>e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:434:21",className:"flex justify-between text-xs",children:[e.jsx("span",{"code-path":"src/pages/AuditOperationsTab.tsx:435:23",className:"text-slate-300",children:p.module}),e.jsx("span",{"code-path":"src/pages/AuditOperationsTab.tsx:436:23",className:"text-slate-500",children:p.count})]},T))})]}),n.top_users&&n.top_users.length>0&&e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:444:15",children:[e.jsx("h4",{"code-path":"src/pages/AuditOperationsTab.tsx:445:17",className:"text-xs font-semibold text-slate-400 mb-2",children:"活跃用户"}),e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:446:17",className:"space-y-1",children:n.top_users.slice(0,5).map((p,T)=>e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:448:21",className:"flex justify-between text-xs",children:[e.jsx("span",{"code-path":"src/pages/AuditOperationsTab.tsx:449:23",className:"text-slate-300",children:p.username}),e.jsx("span",{"code-path":"src/pages/AuditOperationsTab.tsx:450:23",className:"text-slate-500",children:p.count})]},T))})]})]}):e.jsx("p",{"code-path":"src/pages/AuditOperationsTab.tsx:458:11",className:"text-slate-500 text-center py-10 text-sm",children:"暂无统计数据"}),e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:461:9",className:"mt-5 flex justify-end",children:e.jsx(y,{"code-path":"src/pages/AuditOperationsTab.tsx:462:11",variant:"outline",className:"border-slate-700 text-slate-300 hover:bg-slate-800",onClick:o,children:"关闭"})})]})]}):null}function G({label:s,value:o,color:d}){const n={blue:"border-blue-500/20 bg-blue-500/5 text-blue-400",emerald:"border-emerald-500/20 bg-emerald-500/5 text-emerald-400",red:"border-red-500/20 bg-red-500/5 text-red-400"};return e.jsxs("div",{"code-path":"src/pages/AuditOperationsTab.tsx:482:5",className:`rounded-lg border p-3 ${n[d]}`,children:[e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:483:7",className:"text-xs text-slate-500",children:s}),e.jsx("div",{"code-path":"src/pages/AuditOperationsTab.tsx:484:7",className:"text-xl font-bold mt-0.5",children:o})]})}function Ge(s){return{id:s.id??0,username:s.username??"",login_type:s.login_type??"password",ip:s.ip??"",location:s.location??"",browser:s.browser??"",os:s.os??"",user_agent:s.user_agent??s.userAgent??"",status:s.status==="failed"||s.status==="fail"?"fail":"success",fail_reason:s.fail_reason??s.message??"",login_at:s.login_at??s.created_at??"",created_at:s.created_at??s.login_at??""}}function Qe(){const[s,o]=a.useState([]),[d,n]=a.useState(!0),[p,T]=a.useState(""),[h,L]=a.useState(""),b=a.useCallback(async()=>{n(!0);try{const r={page:1,page_size:100};h&&(r.status=h==="fail"?"failed":h);const f=(await ze.list(r))?.list??[];o(f.map(Ge))}catch{o([])}finally{n(!1)}},[h]);a.useEffect(()=>{b()},[b]);const O=s.filter(r=>{const m=p.toLowerCase();return!m||(r.username||"").toLowerCase().includes(m)||(r.ip||"").toLowerCase().includes(m)||(r.location||"").toLowerCase().includes(m)||(r.user_agent||"").toLowerCase().includes(m)}),j=(r,m)=>r==="success"?e.jsx(w,{"code-path":"src/pages/LoginLogsTab.tsx:88:7",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:"成功"}):e.jsx(w,{"code-path":"src/pages/LoginLogsTab.tsx:92:7",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10",title:m||void 0,children:m||"失败"}),v=r=>{switch(r){case"password":return"密码登录";case"ldap":return"LDAP";case"token":return"Token";case"oauth":return"OAuth";default:return r||"密码登录"}};return e.jsxs("div",{"code-path":"src/pages/LoginLogsTab.tsx:113:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/pages/LoginLogsTab.tsx:115:7",className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{"code-path":"src/pages/LoginLogsTab.tsx:116:9",className:"relative w-64",children:[e.jsx(I,{"code-path":"src/pages/LoginLogsTab.tsx:117:11",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(E,{"code-path":"src/pages/LoginLogsTab.tsx:118:11",placeholder:"搜索用户/IP/归属地...",value:p,onChange:r=>T(r.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"})]}),e.jsx("div",{"code-path":"src/pages/LoginLogsTab.tsx:126:9",className:"flex items-center gap-1",children:[{value:"",label:"全部"},{value:"success",label:"成功"},{value:"fail",label:"失败"}].map(({value:r,label:m})=>e.jsx(y,{"code-path":"src/pages/LoginLogsTab.tsx:132:13",variant:h===r?"default":"outline",size:"sm",className:h===r?"h-8 bg-blue-600 hover:bg-blue-700 text-white":"h-8 border-slate-700 text-slate-400 hover:text-slate-100 hover:bg-slate-800",onClick:()=>L(r),children:m},r||"all"))}),e.jsxs(y,{"code-path":"src/pages/LoginLogsTab.tsx:148:9",variant:"outline",className:"border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800",onClick:b,children:[e.jsx(q,{"code-path":"src/pages/LoginLogsTab.tsx:153:11",className:"h-4 w-4 mr-2"}),"刷新"]})]}),e.jsx(P,{"code-path":"src/pages/LoginLogsTab.tsx:159:7",className:"bg-slate-900 border-slate-800",children:e.jsx(K,{"code-path":"src/pages/LoginLogsTab.tsx:160:9",className:"p-0",children:e.jsx("div",{"code-path":"src/pages/LoginLogsTab.tsx:161:11",className:"border-t border-slate-800",children:d?e.jsx("div",{"code-path":"src/pages/LoginLogsTab.tsx:163:15",className:"flex items-center justify-center py-16",children:e.jsx("div",{"code-path":"src/pages/LoginLogsTab.tsx:164:17",className:"w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"})}):O.length===0?e.jsxs("div",{"code-path":"src/pages/LoginLogsTab.tsx:167:15",className:"flex flex-col items-center justify-center py-16 text-slate-500",children:[e.jsx(ke,{"code-path":"src/pages/LoginLogsTab.tsx:168:17",className:"h-8 w-8 mb-3 opacity-40"}),e.jsx("p",{"code-path":"src/pages/LoginLogsTab.tsx:169:17",className:"text-sm",children:"暂无登录日志"})]}):e.jsxs(H,{"code-path":"src/pages/LoginLogsTab.tsx:172:15",children:[e.jsx(W,{"code-path":"src/pages/LoginLogsTab.tsx:173:17",children:e.jsxs(M,{"code-path":"src/pages/LoginLogsTab.tsx:174:19",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(i,{"code-path":"src/pages/LoginLogsTab.tsx:175:21",className:"text-slate-400",children:"登录时间"}),e.jsx(i,{"code-path":"src/pages/LoginLogsTab.tsx:176:21",className:"text-slate-400",children:"用户"}),e.jsx(i,{"code-path":"src/pages/LoginLogsTab.tsx:177:21",className:"text-slate-400",children:"登录方式"}),e.jsx(i,{"code-path":"src/pages/LoginLogsTab.tsx:178:21",className:"text-slate-400",children:"IP"}),e.jsx(i,{"code-path":"src/pages/LoginLogsTab.tsx:179:21",className:"text-slate-400",children:"归属地"}),e.jsx(i,{"code-path":"src/pages/LoginLogsTab.tsx:180:21",className:"text-slate-400",children:"浏览器/OS"}),e.jsx(i,{"code-path":"src/pages/LoginLogsTab.tsx:181:21",className:"text-slate-400",children:"状态"})]})}),e.jsx(U,{"code-path":"src/pages/LoginLogsTab.tsx:184:17",children:O.map(r=>e.jsxs(M,{"code-path":"src/pages/LoginLogsTab.tsx:186:21",className:"border-slate-800 hover:bg-slate-800/50",children:[e.jsx(l,{"code-path":"src/pages/LoginLogsTab.tsx:187:23",children:e.jsx("span",{"code-path":"src/pages/LoginLogsTab.tsx:188:25",className:"text-sm text-slate-400",children:r.login_at?new Date(r.login_at).toLocaleString():"--"})}),e.jsx(l,{"code-path":"src/pages/LoginLogsTab.tsx:192:23",children:e.jsx("span",{"code-path":"src/pages/LoginLogsTab.tsx:193:25",className:"text-sm text-slate-200 font-medium",children:r.username||"--"})}),e.jsx(l,{"code-path":"src/pages/LoginLogsTab.tsx:195:23",children:e.jsx(w,{"code-path":"src/pages/LoginLogsTab.tsx:196:25",variant:"outline",className:"border-blue-500/30 text-blue-400 bg-blue-500/10 text-xs",children:v(r.login_type)})}),e.jsx(l,{"code-path":"src/pages/LoginLogsTab.tsx:200:23",children:e.jsx("code",{"code-path":"src/pages/LoginLogsTab.tsx:201:25",className:"text-xs text-slate-400 bg-slate-800 px-2 py-0.5 rounded",children:r.ip||"--"})}),e.jsx(l,{"code-path":"src/pages/LoginLogsTab.tsx:205:23",children:e.jsxs("span",{"code-path":"src/pages/LoginLogsTab.tsx:206:25",className:"text-xs text-slate-500 flex items-center gap-1",children:[e.jsx(De,{"code-path":"src/pages/LoginLogsTab.tsx:207:27",className:"h-3 w-3"}),r.location||"--"]})}),e.jsx(l,{"code-path":"src/pages/LoginLogsTab.tsx:211:23",children:e.jsxs("span",{"code-path":"src/pages/LoginLogsTab.tsx:212:25",className:"text-xs text-slate-500 flex items-center gap-1",title:r.user_agent,children:[e.jsx(Q,{"code-path":"src/pages/LoginLogsTab.tsx:213:27",className:"h-3 w-3 flex-shrink-0"}),r.browser||r.os?[r.browser,r.os].filter(Boolean).join(" / "):r.user_agent?r.user_agent.length>40?r.user_agent.slice(0,40)+"...":r.user_agent:"--"]})}),e.jsx(l,{"code-path":"src/pages/LoginLogsTab.tsx:223:23",children:j(r.status,r.fail_reason)})]},r.id))})]})})})})]})}function ls(){const{pathname:s}=Me();return console.debug("[AuditPage v2] pathname:",s),s.includes("/audit/terminal")?e.jsx(ce,{"code-path":"src/pages/AuditPage.tsx:11:52"}):s.includes("/audit/operations")?e.jsx(qe,{"code-path":"src/pages/AuditPage.tsx:12:54"}):s.includes("/audit/login-logs")?e.jsx(Qe,{"code-path":"src/pages/AuditPage.tsx:13:54"}):e.jsx(ce,{"code-path":"src/pages/AuditPage.tsx:15:10"})}export{ls as AuditPage}; diff --git a/backend/static/assets/BarChart-DlFprovY.js b/backend/static/assets/BarChart-DlFprovY.js new file mode 100644 index 0000000..3d09032 --- /dev/null +++ b/backend/static/assets/BarChart-DlFprovY.js @@ -0,0 +1 @@ +import{g as a,B as i,X as s,Y as t,f as e}from"./generateCategoricalChart-6v9BPbG2.js";var x=a({chartName:"BarChart",GraphicalChild:i,defaultTooltipEventType:"axis",validateTooltipEventTypes:["axis","item"],axisComponents:[{axisType:"xAxis",AxisComp:s},{axisType:"yAxis",AxisComp:t}],formatAxisMap:e});export{x as B}; diff --git a/backend/static/assets/CapacityPage-Dz7l4ubk.js b/backend/static/assets/CapacityPage-Dz7l4ubk.js new file mode 100644 index 0000000..66320b8 --- /dev/null +++ b/backend/static/assets/CapacityPage-Dz7l4ubk.js @@ -0,0 +1 @@ +import{i as E,k as D,r as c,j as e,m as k,n as j,K as H,B as P,o as N}from"./index-DfyorCky.js";import{C as L,a as M}from"./card-C55cvSHg.js";import{B as z}from"./badge-xNW8x0G1.js";import{S as f,a as v,b as S,c as w,d as x}from"./select-D5qUzdAs.js";import{T as U,a as F,b as d,c as r,d as I,e as n}from"./table-5sHV4Akp.js";import{k as p}from"./kubernetes-J8O09fK7.js";import{R as K}from"./refresh-cw-DUB_tAG-.js";import{D as G}from"./download-DoZfYs2h.js";import{H as _}from"./hard-drive-BbPmnARR.js";import"./index-CWVNW_qu.js";function ae(){const{clusterCode:$}=E(),h=D(),[l,u]=c.useState(!1),[b,g]=c.useState([]),[q,T]=c.useState([]),[A,R]=c.useState([]),[o,V]=c.useState("all"),[a,C]=c.useState($||"");c.useEffect(()=>{p.getClusters().then(s=>{const t=s?.list||[];if(T(t),!a&&t.length>0){const y=t[0].code||String(t[0].id);C(y),h(`/kubernetes/${y}/capacity`,{replace:!0})}}).catch(()=>{})},[]),c.useEffect(()=>{a&&p.getNamespaces(a).then(s=>{R(Array.isArray(s)?s:s?.list||s?.data||[])}).catch(()=>{})},[a]);const i=c.useCallback(async()=>{if(a){u(!0);try{const s=o==="all"?void 0:o,t=await p.getCapacity(a,s);g(Array.isArray(t)?t:t?.list||[])}catch{g([])}finally{u(!1)}}},[a,o]);c.useEffect(()=>{i()},[i]);const m=c.useMemo(()=>b.flatMap(s=>(s.containers||[]).map(t=>({namespace:s.namespace,deployment:s.name,replicas:s.replicas,container:t.name,cpu_req:t.cpu_request||"-",cpu_lim:t.cpu_limit||"-",mem_req:t.mem_request||"-",mem_lim:t.mem_limit||"-"}))),[b]),B=()=>p.exportAsCSV(`capacity-${a}.csv`,m);return e.jsxs("div",{"code-path":"src/components/kubernetes/CapacityPage.tsx:73:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/CapacityPage.tsx:74:7",className:"flex items-center gap-2 text-sm text-slate-500",children:[e.jsx(k,{"code-path":"src/components/kubernetes/CapacityPage.tsx:75:9",to:"/kubernetes",className:"hover:text-slate-300",children:"集群"}),a&&e.jsxs(e.Fragment,{children:[e.jsx(j,{"code-path":"src/components/kubernetes/CapacityPage.tsx:76:29",className:"h-3 w-3"}),e.jsx(k,{"code-path":"src/components/kubernetes/CapacityPage.tsx:76:65",to:`/kubernetes/${a}`,className:"hover:text-slate-300",children:a})]}),e.jsx(j,{"code-path":"src/components/kubernetes/CapacityPage.tsx:77:9",className:"h-3 w-3"}),e.jsx("span",{"code-path":"src/components/kubernetes/CapacityPage.tsx:77:45",className:"text-slate-300",children:"容量分析"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/CapacityPage.tsx:80:7",className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/CapacityPage.tsx:81:9",className:"text-lg font-semibold text-slate-100 flex items-center gap-2",children:[e.jsx(H,{"code-path":"src/components/kubernetes/CapacityPage.tsx:81:86",className:"h-5 w-5 text-purple-400"}),"资源容量分析"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/CapacityPage.tsx:82:9",className:"flex items-center gap-2",children:[e.jsxs(f,{"code-path":"src/components/kubernetes/CapacityPage.tsx:83:11",value:a,onValueChange:s=>{C(s),h(`/kubernetes/${s}/capacity`)},children:[e.jsx(v,{"code-path":"src/components/kubernetes/CapacityPage.tsx:84:13",className:"w-40 h-8 text-xs bg-slate-800 border-slate-700",children:e.jsx(S,{"code-path":"src/components/kubernetes/CapacityPage.tsx:84:87"})}),e.jsx(w,{"code-path":"src/components/kubernetes/CapacityPage.tsx:85:13",className:"bg-slate-800 border-slate-700",children:q.map(s=>e.jsx(x,{"code-path":"src/components/kubernetes/CapacityPage.tsx:86:42",value:s.code||String(s.id),className:"text-xs",children:s.name||s.code},s.id))})]}),e.jsxs(f,{"code-path":"src/components/kubernetes/CapacityPage.tsx:89:11",value:o,onValueChange:V,children:[e.jsx(v,{"code-path":"src/components/kubernetes/CapacityPage.tsx:90:13",className:"w-32 h-8 text-xs bg-slate-800 border-slate-700",children:e.jsx(S,{"code-path":"src/components/kubernetes/CapacityPage.tsx:90:87",placeholder:"所有命名空间"})}),e.jsxs(w,{"code-path":"src/components/kubernetes/CapacityPage.tsx:91:13",className:"bg-slate-800 border-slate-700",children:[e.jsx(x,{"code-path":"src/components/kubernetes/CapacityPage.tsx:92:15",value:"all",className:"text-xs",children:"所有命名空间"}),A.map(s=>e.jsx(x,{"code-path":"src/components/kubernetes/CapacityPage.tsx:93:36",value:s,className:"text-xs",children:s},s))]})]}),e.jsxs(P,{"code-path":"src/components/kubernetes/CapacityPage.tsx:96:11",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300 text-xs",onClick:i,disabled:l,children:[e.jsx(K,{"code-path":"src/components/kubernetes/CapacityPage.tsx:97:13",className:`h-3 w-3 mr-1 ${l?"animate-spin":""}`}),"刷新"]}),e.jsxs(P,{"code-path":"src/components/kubernetes/CapacityPage.tsx:99:11",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300 text-xs",onClick:B,children:[e.jsx(G,{"code-path":"src/components/kubernetes/CapacityPage.tsx:100:13",className:"h-3 w-3 mr-1"}),"CSV"]})]})]}),e.jsx(L,{"code-path":"src/components/kubernetes/CapacityPage.tsx:105:7",className:"bg-slate-900 border-slate-800",children:e.jsx(M,{"code-path":"src/components/kubernetes/CapacityPage.tsx:106:9",className:"p-0",children:e.jsxs(U,{"code-path":"src/components/kubernetes/CapacityPage.tsx:107:11",children:[e.jsx(F,{"code-path":"src/components/kubernetes/CapacityPage.tsx:108:13",children:e.jsxs(d,{"code-path":"src/components/kubernetes/CapacityPage.tsx:108:26",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(r,{"code-path":"src/components/kubernetes/CapacityPage.tsx:109:15",className:"text-slate-400",children:"Deployment"}),e.jsx(r,{"code-path":"src/components/kubernetes/CapacityPage.tsx:110:15",className:"text-slate-400",children:"命名空间"}),e.jsx(r,{"code-path":"src/components/kubernetes/CapacityPage.tsx:111:15",className:"text-slate-400",children:"副本"}),e.jsx(r,{"code-path":"src/components/kubernetes/CapacityPage.tsx:112:15",className:"text-slate-400",children:"容器"}),e.jsxs(r,{"code-path":"src/components/kubernetes/CapacityPage.tsx:113:15",className:"text-slate-400",children:[e.jsx(N,{"code-path":"src/components/kubernetes/CapacityPage.tsx:113:53",className:"h-3 w-3 inline mr-1"}),"CPU Req"]}),e.jsxs(r,{"code-path":"src/components/kubernetes/CapacityPage.tsx:114:15",className:"text-slate-400",children:[e.jsx(N,{"code-path":"src/components/kubernetes/CapacityPage.tsx:114:53",className:"h-3 w-3 inline mr-1"}),"CPU Lim"]}),e.jsxs(r,{"code-path":"src/components/kubernetes/CapacityPage.tsx:115:15",className:"text-slate-400",children:[e.jsx(_,{"code-path":"src/components/kubernetes/CapacityPage.tsx:115:53",className:"h-3 w-3 inline mr-1"}),"Mem Req"]}),e.jsxs(r,{"code-path":"src/components/kubernetes/CapacityPage.tsx:116:15",className:"text-slate-400",children:[e.jsx(_,{"code-path":"src/components/kubernetes/CapacityPage.tsx:116:53",className:"h-3 w-3 inline mr-1"}),"Mem Lim"]})]})}),e.jsx(I,{"code-path":"src/components/kubernetes/CapacityPage.tsx:118:13",children:m.length===0?e.jsx(d,{"code-path":"src/components/kubernetes/CapacityPage.tsx:120:17",children:e.jsxs(n,{"code-path":"src/components/kubernetes/CapacityPage.tsx:120:27",colSpan:8,className:"text-center text-slate-500 py-8",children:["暂无数据",l?e.jsx("span",{"code-path":"src/components/kubernetes/CapacityPage.tsx:120:109",className:"animate-spin inline-block ml-2",children:"⏳"}):""]})}):m.map((s,t)=>e.jsxs(d,{"code-path":"src/components/kubernetes/CapacityPage.tsx:122:17",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(n,{"code-path":"src/components/kubernetes/CapacityPage.tsx:123:19",className:"font-medium text-slate-200 text-sm",children:s.deployment}),e.jsx(n,{"code-path":"src/components/kubernetes/CapacityPage.tsx:124:19",children:e.jsx(z,{"code-path":"src/components/kubernetes/CapacityPage.tsx:124:30",variant:"outline",className:"border-slate-700 text-slate-400 text-xs",children:s.namespace})}),e.jsx(n,{"code-path":"src/components/kubernetes/CapacityPage.tsx:125:19",className:"text-sm text-slate-300",children:s.replicas}),e.jsx(n,{"code-path":"src/components/kubernetes/CapacityPage.tsx:126:19",className:"text-sm text-slate-400",children:s.container}),e.jsx(n,{"code-path":"src/components/kubernetes/CapacityPage.tsx:127:19",className:`text-sm ${s.cpu_req!=="-"?"text-blue-400":"text-slate-600"}`,children:s.cpu_req}),e.jsx(n,{"code-path":"src/components/kubernetes/CapacityPage.tsx:128:19",className:`text-sm ${s.cpu_lim!=="-"?"text-cyan-400":"text-slate-600"}`,children:s.cpu_lim}),e.jsx(n,{"code-path":"src/components/kubernetes/CapacityPage.tsx:129:19",className:`text-sm ${s.mem_req!=="-"?"text-emerald-400":"text-slate-600"}`,children:s.mem_req}),e.jsx(n,{"code-path":"src/components/kubernetes/CapacityPage.tsx:130:19",className:`text-sm ${s.mem_lim!=="-"?"text-teal-400":"text-slate-600"}`,children:s.mem_lim})]},`${s.deployment}-${s.container}-${t}`))})]})})})]})}export{ae as default}; diff --git a/backend/static/assets/CloudAccountManager-DU9759_X.js b/backend/static/assets/CloudAccountManager-DU9759_X.js new file mode 100644 index 0000000..b4b4d37 --- /dev/null +++ b/backend/static/assets/CloudAccountManager-DU9759_X.js @@ -0,0 +1 @@ +import{j as e,r as a,B as p,s as S,P as f,S as $,I as C,D as G,b as X,c as Z,d as q,e as J,f as U,L as Y}from"./index-DfyorCky.js";import{L as x}from"./label-BK0h2apY.js";import{C as r,a as d}from"./card-C55cvSHg.js";import{B as v}from"./badge-xNW8x0G1.js";import{c as N}from"./cloud-Dzoer-2i.js";import{R as k}from"./refresh-cw-DUB_tAG-.js";import{P as L}from"./plus-CUG-9kpu.js";import{C as B}from"./circle-check-DWcXrx2k.js";import{C as D}from"./circle-x-DK79Dhg2.js";import{P}from"./pencil-BqUotcjf.js";import{T as ee}from"./trash-2-Dx32pOzT.js";const E={aws:{viewBox:"0 0 24 24",color:"#FF9900",path:"M6.763 10.036c0 .296.032.535.088.71.064.176.144.368.256.576.04.063.056.127.056.183 0 .08-.048.16-.152.24l-.503.335a.383.383 0 0 1-.208.072c-.08 0-.16-.04-.24-.112a2.47 2.47 0 0 1-.288-.375 6.18 6.18 0 0 1-.248-.471c-.622.734-1.405 1.101-2.347 1.101-.671 0-1.205-.191-1.596-.574-.391-.384-.59-.894-.59-1.533 0-.678.239-1.23.726-1.644.487-.415 1.133-.623 1.955-.623.272 0 .551.024.846.064.296.04.6.104.918.176v-.583c0-.607-.127-1.03-.375-1.277-.255-.248-.686-.367-1.3-.367-.28 0-.568.031-.863.103-.295.072-.583.16-.862.272a2.287 2.287 0 0 1-.28.104.488.488 0 0 1-.127.023c-.112 0-.168-.08-.168-.247v-.391c0-.128.016-.224.056-.28a.597.597 0 0 1 .224-.167c.279-.144.614-.264 1.005-.36a4.84 4.84 0 0 1 1.246-.151c.95 0 1.644.216 2.091.647.439.43.662 1.085.662 1.963v2.586zm-3.24 1.21c.265 0 .538-.048.822-.144.283-.096.535-.271.742-.51.128-.152.224-.32.264-.512.04-.191.072-.423.072-.694v-.335a6.66 6.66 0 0 0-.735-.136 6.02 6.02 0 0 0-.75-.048c-.535 0-.926.104-1.19.32-.263.215-.39.518-.39.917 0 .375.095.654.295.846.191.2.47.296.838.296zm3.89.527c-.073 0-.12-.016-.152-.048-.032-.024-.064-.08-.088-.152L6.155 5.563a.715.715 0 0 1-.032-.16c0-.128.064-.2.192.2h.703c.08 0 .136.016.168.048.032.024.064.08.088.152l1.348 5.298 1.252-5.298c.024-.08.056-.128.088-.152a.355.355 0 0 1 .176-.048h.575c.08 0 .136.016.176.048.032.024.072.08.088.152l1.268 5.362 1.39-5.362c.024-.08.056-.128.088-.152a.344.344 0 0 1 .168-.048h.67c.128 0 .2.072.2.2 0 .04-.008.072-.016.112 0 0-.04.128-.088.152l-1.916 6.15c-.032.08-.064.128-.096.152a.355.355 0 0 1-.176.048h-.622c-.08 0-.136-.016-.176-.048-.032-.024-.064-.08-.088-.152l-1.26-5.186-1.252 5.178c-.024.08-.056.128-.088.152a.355.355 0 0 1-.176.048h-.623zm9.166.215c-.367 0-.734-.04-1.094-.127-.359-.088-.638-.184-.822-.296-.112-.064-.191-.136-.223-.2a.498.498 0 0 1-.032-.128v-.399c0-.167.064-.247.183-.247a.45.45 0 0 1 .144.024c.048.016.12.048.2.08.271.12.566.215.878.279.319.064.63.096.95.096.502 0 .893-.088 1.164-.264a.86.86 0 0 0 .415-.758.777.777 0 0 0-.215-.55c-.144-.151-.423-.287-.83-.415l-1.188-.367c-.598-.192-1.044-.471-1.316-.838a1.95 1.95 0 0 1-.415-1.205c0-.351.072-.662.215-.918.144-.255.335-.479.575-.654.24-.184.51-.319.822-.415.311-.096.638-.136.982-.136.176 0 .36.008.535.032.184.024.351.056.518.088.152.04.303.08.439.127.136.048.24.096.311.144a.66.66 0 0 1 .176.144.298.298 0 0 1 .048.184v.359c0 .168-.064.256-.183.256a.83.83 0 0 1-.304-.096 3.68 3.68 0 0 0-1.548-.311c-.463 0-.83.072-1.085.231-.255.16-.39.4-.39.743 0 .351.128.59.383.758.255.168.702.335 1.331.48.583.135 1.005.311 1.268.518.263.207.39.495.39.862 0 .367-.128.662-.375.902-.247.247-.67.375-1.26.375zm2.004 1.332c-2.637 1.948-6.488 2.984-9.793 2.984-4.635 0-8.81-1.715-11.966-4.566-.255-.224-.024-.335.271-.144 3.41 1.987 7.622 3.183 11.966 3.183 2.936 0 6.158-.61 9.119-1.876.44-.207.815.287.383.615zm1.078-1.23c-.336-.431-2.223-.2-3.073-.103-.255.024-.295-.192-.064-.351 1.5-1.053 3.962-.75 4.246-.4.287.359-.08 2.824-1.484 4.004-.215.184-.423.088-.319-.151.311-.774 1.005-2.51.662-2.956v-.443z"},azure:{viewBox:"0 0 24 24",color:"#0078D4",path:"M5.483 21.3H24L14.025 4.013l-3.022 5.915 5.99 9.357H8.787l-3.304 6.015zM8.7 3.197L0 21.3h6.395l4.49-8.51L8.7 3.196z"},gcp:{viewBox:"0 0 24 24",color:"#4285F4",path:"M12.19 2.38a9.344 9.344 0 0 0-9.234 6.893c.053-.02-.055.013 0 0-3.875 2.551-3.922 8.11-.247 10.941l.006-.007-.007.03a6.717 6.717 0 0 0 4.077 1.356h5.173l.03.03h5.192c6.687.053 9.376-8.605 3.835-12.35a9.365 9.365 0 0 0-2.821-4.552l-.043.043.006-.05A9.344 9.344 0 0 0 12.19 2.38zm-.358 4.146c1.244-.04 2.518.368 3.486 1.15a5.186 5.186 0 0 1 1.862 4.078v.518c3.53-.07 3.53 5.262 0 5.193h-5.193l-.008.009v-.04H6.785a2.59 2.59 0 0 1-1.067-.23h.001a2.597 2.597 0 1 1 3.437-3.437l3.013-3.012A6.747 6.747 0 0 0 8.11 8.24c.018-.01.04-.026.054-.023a5.186 5.186 0 0 1 3.67-1.69z"},aliyun:{viewBox:"0 0 24 24",color:"#FF6A00",path:"M3.996 4.517h5.291L8.01 6.324 4.153 7.506a1.668 1.668 0 0 0-1.165 1.601v5.786a1.668 1.668 0 0 0 1.165 1.6l3.857 1.183 1.277 1.807H3.996A3.996 3.996 0 0 1 0 15.487V8.513a3.996 3.996 0 0 1 3.996-3.996m16.008 0h-5.291l1.277 1.807 3.857 1.182c.715.227 1.17.889 1.165 1.601v5.786a1.668 1.668 0 0 1-1.165 1.6l-3.857 1.183-1.277 1.807h5.291A3.996 3.996 0 0 0 24 15.487V8.513a3.996 3.996 0 0 0-3.996-3.996m-4.007 8.345H8.002v-1.804h7.995Z"},tencent:{viewBox:"220 60 620 430",color:"#006EFF",paths:[{fill:"#006EFF",d:"M685.3,188.5c-24.7-66.3-88-110.4-158.8-110.5c-84.8,0-152.2,62.8-165.3,140.8c6.5,0,13.1-2.1,21.8-2.1c8.7,0,19.6,2.1,28.3,2.1c10.9-54.2,58.7-93.2,115.3-93.2c47.8,0,89.2,28.2,108.7,69.3c0,0,2.2,2.2,2.2,0C652.6,192.8,670,188.5,685.3,188.5L685.3,188.5"},{fill:"#00C8DC",d:"M456.9,242.6c-23.9-17.3-47.9-26-76.1-26c-33.9,0-66.2,14.2-89.2,39c-48.4,49.7-47.4,129.2,2.2,177.7c21.7,19.5,43.5,30.3,69.6,32.5l50-47.7h-28.3c-28.3-2.1-45.7-10.8-56.5-21.6c-30-29.6-30.9-77.6-2.2-108.3c15.2-15.2,32.6-21.7,54.4-21.7c13.1,0,32.6,2.1,52.2,21.6c8.7,8.7,32.6,26,41.3,34.7h2.1l32.6-32.5v-2.2C493.9,273,470,253.5,456.9,242.6"},{fill:"#00A3FF",d:"M724.4,396.5c-8.7,8.7-26.1,21.7-56.5,21.7h-187c56.5-54.1,104.4-99.6,108.8-104c8.3-8.4,17-16.3,26.1-23.8c21.8-19.5,39.1-21.7,54.4-21.7c21.7,0,39.1,8.7,54.4,21.6C754.9,318.5,754.9,368.4,724.4,396.5z M761.4,255.6c-23-24.8-55.3-39-89.2-39c-30.4,0-56.5,10.9-80.5,28.2c-8.8,8.7-21.8,17.3-32.7,30.3c-8.7,8.7-195.7,190.7-195.7,190.7c10.9,2.2,23.9,2.2,34.8,2.2h237.1c17.4,0,30.5,0,43.5-2.2c30-2.2,58.3-14.4,80.5-34.7C809.2,383.5,809.2,303.4,761.4,255.6L761.4,255.6"}]},huawei:{viewBox:"0 0 24 24",color:"#FF0000",path:"M3.67 6.14S1.82 7.91 1.72 9.78v.35c.08 1.51 1.22 2.4 1.22 2.4 1.83 1.79 6.26 4.04 7.3 4.55 0 0 .06.03.1-.01l.02-.04v-.04C7.52 10.8 3.67 6.14 3.67 6.14zM9.65 18.6c-.02-.08-.1-.08-.1-.08l-7.38.26c.8 1.43 2.15 2.53 3.56 2.2.96-.25 3.16-1.78 3.88-2.3.06-.05.04-.09.04-.09zm.08-.78C6.49 15.63.21 12.28.21 12.28c-.15.46-.2.9-.21 1.3v.07c0 1.07.4 1.82.4 1.82.8 1.69 2.34 2.2 2.34 2.2.7.3 1.4.31 1.4.31.12.02 4.4 0 5.54 0 .05 0 .08-.05.08-.05v-.06c0-.03-.03-.05-.03-.05zM9.06 3.19a3.42 3.42 0 00-2.57 3.15v.41c.03.6.16 1.05.16 1.05.66 2.9 3.86 7.65 4.55 8.65.05.05.1.03.1.03a.1.1 0 00.06-.1c1.06-10.6-1.11-13.42-1.11-13.42-.32.02-1.19.23-1.19.23zm8.299 2.27s-.49-1.8-2.44-2.28c0 0-.57-.14-1.17-.22 0 0-2.18 2.81-1.12 13.43.01.07.06.08.06.08.07.03.1-.03.1-.03.72-1.03 3.9-5.76 4.55-8.64 0 0 .36-1.4.02-2.34zm-2.92 13.07s-.07 0-.09.05c0 0-.01.07.03.1.7.51 2.85 2 3.88 2.3 0 0 .16.05.43.06h.14c.69-.02 1.9-.37 3-2.26l-7.4-.25zm7.83-8.41c.14-2.06-1.94-3.97-1.94-3.98 0 0-3.85 4.66-6.67 10.8 0 0-.03.08.02.13l.04.01h.06c1.06-.53 5.46-2.77 7.28-4.54 0 0 1.15-.93 1.21-2.42zm1.52 2.14s-6.28 3.37-9.52 5.55c0 0-.05.04-.03.11 0 0 .03.06.07.06 1.16 0 5.56 0 5.67-.02 0 0 .57-.02 1.27-.29 0 0 1.56-.5 2.37-2.27 0 0 .73-1.45.17-3.14z"}};function ce({provider:t,className:m="h-5 w-5"}){const n=E[t]||E.aliyun;return e.jsx("svg",{"code-path":"src/components/icons/CloudBrandIcon.tsx:69:5",className:m,viewBox:n.viewBox,fill:"currentColor",style:{color:n.color},role:"img","aria-label":t,children:n.paths?n.paths.map((h,i)=>e.jsx("path",{"code-path":"src/components/icons/CloudBrandIcon.tsx:79:11",d:h.d,fill:h.fill||"currentColor"},i)):e.jsx("path",{"code-path":"src/components/icons/CloudBrandIcon.tsx:82:9",d:n.path})})}function se(t){return{aws:"#FF9900",azure:"#0078D4",gcp:"#4285F4",aliyun:"#FF6A00",tencent:"#006EFF",huawei:"#FF0000"}[t]||"#64748B"}const te={aws:"AWS",aliyun:"阿里云",tencent:"腾讯云",huawei:"华为云",azure:"Azure",gcp:"GCP"};function ie(){const[t,m]=a.useState([]),[n,h]=a.useState(!0),[i,I]=a.useState(""),[b,K]=a.useState("all"),[H,g]=a.useState(!1),[w,z]=a.useState(!1),[o,_]=a.useState(null),[s,l]=a.useState({name:"",provider:"aliyun",access_key:"",secret_key:"",monthly_cost:"",status:"active"}),O=()=>{_(null),l({name:"",provider:"aliyun",access_key:"",secret_key:"",monthly_cost:"",status:"active"})},T=()=>{O(),g(!0)},R=c=>{_(c),l({name:c.name||"",provider:c.provider||"aliyun",access_key:"",secret_key:"",monthly_cost:String(c.monthly_cost??0),status:c.status||"active"}),g(!0)},W=async()=>{if(!(!s.name.trim()||!s.provider.trim()))try{z(!0);const c={name:s.name.trim(),provider:s.provider,access_key:s.access_key.trim(),secret_key:s.secret_key.trim(),monthly_cost:Number(s.monthly_cost)||0,status:s.status};o?await N.updateAccount(o.id,c):await N.createAccount(c),g(!1),A()}catch(c){console.error(o?"更新云账号失败:":"创建云账号失败:",c)}finally{z(!1)}},A=async()=>{try{h(!0);const c=await N.getAccounts();m(c?.list||[])}catch(c){console.error("加载云账号列表失败:",c),m([])}finally{h(!1)}};a.useEffect(()=>{A()},[]);const Q=async c=>{try{await N.deleteAccount(c),A()}catch(u){console.error("删除云账号失败:",u)}},F=t.filter(c=>{const u=c.access_key||c.accessKey||"",y=(c.name||"").toLowerCase().includes(i.toLowerCase())||u.toLowerCase().includes(i.toLowerCase()),M=b==="all"||c.provider===b;return y&&M}),j={total:t.length,active:t.filter(c=>c.status==="active").length,inactive:t.filter(c=>c.status==="inactive").length,error:t.filter(c=>c.status==="error").length};return e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:156:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:158:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:159:9",children:[e.jsx("h1",{"code-path":"src/components/cloud/CloudAccountManager.tsx:160:11",className:"text-2xl font-bold text-slate-100",children:"云账号管理"}),e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:161:11",className:"text-slate-400 mt-1",children:"管理多云平台的访问凭证和账号信息"})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:163:9",className:"flex items-center gap-2",children:[e.jsxs(p,{"code-path":"src/components/cloud/CloudAccountManager.tsx:164:11",variant:"outline",onClick:A,className:"border-slate-700 text-slate-300",children:[e.jsx(k,{"code-path":"src/components/cloud/CloudAccountManager.tsx:165:13",className:`h-4 w-4 mr-2 ${n?"animate-spin":""}`}),"刷新"]}),e.jsxs(p,{"code-path":"src/components/cloud/CloudAccountManager.tsx:168:11",className:"bg-blue-600 hover:bg-blue-700",onClick:T,children:[e.jsx(L,{"code-path":"src/components/cloud/CloudAccountManager.tsx:169:13",className:"h-4 w-4 mr-2"}),"添加账号"]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:176:7",className:"grid grid-cols-4 gap-4",children:[e.jsx(r,{"code-path":"src/components/cloud/CloudAccountManager.tsx:177:9",className:"bg-slate-800 border-slate-700",children:e.jsx(d,{"code-path":"src/components/cloud/CloudAccountManager.tsx:178:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:179:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:180:15",children:[e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:181:17",className:"text-slate-400 text-sm",children:"账号总数"}),e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:182:17",className:"text-2xl font-bold text-slate-100 mt-1",children:j.total})]}),e.jsx("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:184:15",className:"w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center",children:e.jsx(S,{"code-path":"src/components/cloud/CloudAccountManager.tsx:185:17",className:"h-5 w-5 text-blue-400"})})]})})}),e.jsx(r,{"code-path":"src/components/cloud/CloudAccountManager.tsx:190:9",className:"bg-slate-800 border-slate-700",children:e.jsx(d,{"code-path":"src/components/cloud/CloudAccountManager.tsx:191:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:192:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:193:15",children:[e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:194:17",className:"text-slate-400 text-sm",children:"正常"}),e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:195:17",className:"text-2xl font-bold text-green-400 mt-1",children:j.active})]}),e.jsx("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:197:15",className:"w-10 h-10 rounded-lg bg-green-500/20 flex items-center justify-center",children:e.jsx(B,{"code-path":"src/components/cloud/CloudAccountManager.tsx:198:17",className:"h-5 w-5 text-green-400"})})]})})}),e.jsx(r,{"code-path":"src/components/cloud/CloudAccountManager.tsx:203:9",className:"bg-slate-800 border-slate-700",children:e.jsx(d,{"code-path":"src/components/cloud/CloudAccountManager.tsx:204:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:205:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:206:15",children:[e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:207:17",className:"text-slate-400 text-sm",children:"已停用"}),e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:208:17",className:"text-2xl font-bold text-slate-400 mt-1",children:j.inactive})]}),e.jsx("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:210:15",className:"w-10 h-10 rounded-lg bg-slate-500/20 flex items-center justify-center",children:e.jsx(D,{"code-path":"src/components/cloud/CloudAccountManager.tsx:211:17",className:"h-5 w-5 text-slate-400"})})]})})}),e.jsx(r,{"code-path":"src/components/cloud/CloudAccountManager.tsx:216:9",className:"bg-slate-800 border-slate-700",children:e.jsx(d,{"code-path":"src/components/cloud/CloudAccountManager.tsx:217:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:218:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:219:15",children:[e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:220:17",className:"text-slate-400 text-sm",children:"异常"}),e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:221:17",className:"text-2xl font-bold text-red-400 mt-1",children:j.error})]}),e.jsx("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:223:15",className:"w-10 h-10 rounded-lg bg-red-500/20 flex items-center justify-center",children:e.jsx(f,{"code-path":"src/components/cloud/CloudAccountManager.tsx:224:17",className:"h-5 w-5 text-red-400"})})]})})})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:232:7",className:"flex items-center gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:233:9",className:"relative flex-1 max-w-md",children:[e.jsx($,{"code-path":"src/components/cloud/CloudAccountManager.tsx:234:11",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(C,{"code-path":"src/components/cloud/CloudAccountManager.tsx:235:11",placeholder:"搜索账号名称或AccessKey...",value:i,onChange:c=>I(c.target.value),className:"pl-10 bg-slate-800 border-slate-700 text-slate-100"})]}),e.jsxs("select",{"code-path":"src/components/cloud/CloudAccountManager.tsx:242:9",value:b,onChange:c=>K(c.target.value),className:"px-3 py-2 bg-slate-800 border border-slate-700 rounded-md text-slate-100 text-sm",children:[e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:247:11",value:"all",children:"全部平台"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:248:11",value:"aws",children:"AWS"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:249:11",value:"aliyun",children:"阿里云"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:250:11",value:"tencent",children:"腾讯云"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:251:11",value:"huawei",children:"华为云"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:252:11",value:"azure",children:"Azure"})]})]}),n?e.jsx(r,{"code-path":"src/components/cloud/CloudAccountManager.tsx:258:9",className:"bg-slate-800 border-slate-700",children:e.jsxs(d,{"code-path":"src/components/cloud/CloudAccountManager.tsx:259:11",className:"p-12 text-center text-slate-500",children:[e.jsx(k,{"code-path":"src/components/cloud/CloudAccountManager.tsx:260:13",className:"h-6 w-6 animate-spin mx-auto mb-3"}),"加载中..."]})}):F.length===0?e.jsx(r,{"code-path":"src/components/cloud/CloudAccountManager.tsx:265:9",className:"bg-slate-800 border-slate-700",children:e.jsx(d,{"code-path":"src/components/cloud/CloudAccountManager.tsx:266:11",className:"p-12 text-center text-slate-500",children:"暂无云账号数据"})}):e.jsx("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:269:9",className:"grid grid-cols-2 gap-4",children:F.map(c=>{const u=c.access_key||c.accessKey||"",y=c.server_count??c.serverCount??0,M=c.last_sync||c.lastSync||c.created_at||"-",V=c.monthly_cost??c.monthlyCost??0;return e.jsx(r,{"code-path":"src/components/cloud/CloudAccountManager.tsx:276:15",className:"bg-slate-800 border-slate-700",children:e.jsxs(d,{"code-path":"src/components/cloud/CloudAccountManager.tsx:277:17",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:278:19",className:"flex items-start justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:279:21",className:"flex items-start gap-3",children:[e.jsx("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:280:23",className:"w-10 h-10 rounded-lg bg-slate-800 flex items-center justify-center",style:{borderBottom:`2px solid ${se(c.provider)}`},children:e.jsx(ce,{"code-path":"src/components/cloud/CloudAccountManager.tsx:281:25",provider:c.provider,className:"h-6 w-6"})}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:283:23",children:[e.jsx("h3",{"code-path":"src/components/cloud/CloudAccountManager.tsx:284:25",className:"font-medium text-slate-100",children:c.name}),e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:285:25",className:"text-sm text-slate-400 mt-0.5",children:te[c.provider]||c.provider}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:286:25",className:"flex items-center gap-3 mt-2",children:[u&&e.jsxs(v,{"code-path":"src/components/cloud/CloudAccountManager.tsx:288:29",variant:"secondary",className:"bg-slate-700 text-slate-300",children:[e.jsx(f,{"code-path":"src/components/cloud/CloudAccountManager.tsx:289:31",className:"h-3 w-3 mr-1"}),u.slice(0,8),"..."]}),c.status==="active"&&e.jsxs(v,{"code-path":"src/components/cloud/CloudAccountManager.tsx:294:29",className:"bg-green-500/20 text-green-400 border-0",children:[e.jsx(B,{"code-path":"src/components/cloud/CloudAccountManager.tsx:295:31",className:"h-3 w-3 mr-1"}),"正常"]}),c.status==="inactive"&&e.jsxs(v,{"code-path":"src/components/cloud/CloudAccountManager.tsx:300:29",className:"bg-slate-500/20 text-slate-400 border-0",children:[e.jsx(D,{"code-path":"src/components/cloud/CloudAccountManager.tsx:301:31",className:"h-3 w-3 mr-1"}),"已停用"]}),c.status==="error"&&e.jsxs(v,{"code-path":"src/components/cloud/CloudAccountManager.tsx:306:29",className:"bg-red-500/20 text-red-400 border-0",children:[e.jsx(f,{"code-path":"src/components/cloud/CloudAccountManager.tsx:307:31",className:"h-3 w-3 mr-1"}),"异常"]})]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:314:21",className:"flex items-center gap-1",children:[e.jsx(p,{"code-path":"src/components/cloud/CloudAccountManager.tsx:315:23",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-blue-400",onClick:()=>R(c),children:e.jsx(P,{"code-path":"src/components/cloud/CloudAccountManager.tsx:321:25",className:"h-4 w-4"})}),e.jsx(p,{"code-path":"src/components/cloud/CloudAccountManager.tsx:323:23",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-red-400",onClick:()=>Q(c.id),children:e.jsx(ee,{"code-path":"src/components/cloud/CloudAccountManager.tsx:329:25",className:"h-4 w-4"})})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:333:19",className:"grid grid-cols-3 gap-4 mt-4 pt-4 border-t border-slate-700",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:334:21",children:[e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:335:23",className:"text-xs text-slate-400",children:"月费用"}),e.jsxs("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:336:23",className:"text-lg font-medium text-emerald-400",children:["¥",Number(V).toLocaleString()]})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:338:21",children:[e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:339:23",className:"text-xs text-slate-400",children:"服务器数"}),e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:340:23",className:"text-lg font-medium text-slate-100",children:y})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:342:21",children:[e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:343:23",className:"text-xs text-slate-400",children:"最后同步"}),e.jsx("p",{"code-path":"src/components/cloud/CloudAccountManager.tsx:344:23",className:"text-sm text-slate-300",children:M!=="-"?new Date(M).toLocaleString():"-"})]})]})]})},c.id)})}),e.jsx(G,{"code-path":"src/components/cloud/CloudAccountManager.tsx:357:7",open:H,onOpenChange:g,children:e.jsxs(X,{"code-path":"src/components/cloud/CloudAccountManager.tsx:358:9",className:"bg-slate-800 border-slate-700 text-slate-100 max-w-lg",children:[e.jsxs(Z,{"code-path":"src/components/cloud/CloudAccountManager.tsx:359:11",children:[e.jsxs(q,{"code-path":"src/components/cloud/CloudAccountManager.tsx:360:13",className:"text-slate-100 flex items-center gap-2",children:[e.jsx(S,{"code-path":"src/components/cloud/CloudAccountManager.tsx:361:15",className:"h-5 w-5 text-blue-400"}),o?"编辑云账号":"添加云账号"]}),e.jsx(J,{"code-path":"src/components/cloud/CloudAccountManager.tsx:364:13",className:"text-slate-400",children:o?"修改账号信息和访问凭证,留空则保持原凭证不变":"录入多云平台的访问凭证,用于资源同步与成本统计"})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:369:11",className:"space-y-4 py-2",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:370:13",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:371:15",className:"space-y-1.5",children:[e.jsxs(x,{"code-path":"src/components/cloud/CloudAccountManager.tsx:372:17",className:"text-slate-300",children:["账号名称 ",e.jsx("span",{"code-path":"src/components/cloud/CloudAccountManager.tsx:373:24",className:"text-red-400",children:"*"})]}),e.jsx(C,{"code-path":"src/components/cloud/CloudAccountManager.tsx:375:17",placeholder:"阿里云生产账号",value:s.name,onChange:c=>l({...s,name:c.target.value}),className:"bg-slate-900 border-slate-700 text-slate-100 placeholder:text-slate-500"})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:382:15",className:"space-y-1.5",children:[e.jsxs(x,{"code-path":"src/components/cloud/CloudAccountManager.tsx:383:17",className:"text-slate-300",children:["云平台 ",e.jsx("span",{"code-path":"src/components/cloud/CloudAccountManager.tsx:384:23",className:"text-red-400",children:"*"})]}),e.jsxs("select",{"code-path":"src/components/cloud/CloudAccountManager.tsx:386:17",value:s.provider,onChange:c=>l({...s,provider:c.target.value}),className:"w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-md text-slate-100 text-sm",children:[e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:391:19",value:"aliyun",children:"阿里云"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:392:19",value:"tencent",children:"腾讯云"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:393:19",value:"aws",children:"AWS"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:394:19",value:"huawei",children:"华为云"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:395:19",value:"azure",children:"Azure"})]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:400:13",className:"space-y-1.5",children:[e.jsxs(x,{"code-path":"src/components/cloud/CloudAccountManager.tsx:401:15",className:"text-slate-300",children:["AccessKey",o&&e.jsx("span",{"code-path":"src/components/cloud/CloudAccountManager.tsx:403:36",className:"text-xs text-slate-500 ml-2",children:"留空保持不变"})]}),e.jsx(C,{"code-path":"src/components/cloud/CloudAccountManager.tsx:405:15",placeholder:"LTAI...",value:s.access_key,onChange:c=>l({...s,access_key:c.target.value}),className:"bg-slate-900 border-slate-700 text-slate-100 placeholder:text-slate-500 font-mono text-sm"})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:413:13",className:"space-y-1.5",children:[e.jsxs(x,{"code-path":"src/components/cloud/CloudAccountManager.tsx:414:15",className:"text-slate-300",children:["SecretKey",o&&e.jsx("span",{"code-path":"src/components/cloud/CloudAccountManager.tsx:416:36",className:"text-xs text-slate-500 ml-2",children:"留空保持不变"})]}),e.jsx(C,{"code-path":"src/components/cloud/CloudAccountManager.tsx:418:15",type:"password",placeholder:"••••••••",value:s.secret_key,onChange:c=>l({...s,secret_key:c.target.value}),className:"bg-slate-900 border-slate-700 text-slate-100 placeholder:text-slate-500 font-mono text-sm"})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:427:13",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:428:15",className:"space-y-1.5",children:[e.jsx(x,{"code-path":"src/components/cloud/CloudAccountManager.tsx:429:17",className:"text-slate-300",children:"月费用 (元)"}),e.jsx(C,{"code-path":"src/components/cloud/CloudAccountManager.tsx:430:17",type:"number",min:"0",placeholder:"0",value:s.monthly_cost,onChange:c=>l({...s,monthly_cost:c.target.value}),className:"bg-slate-900 border-slate-700 text-slate-100 placeholder:text-slate-500"})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudAccountManager.tsx:439:15",className:"space-y-1.5",children:[e.jsx(x,{"code-path":"src/components/cloud/CloudAccountManager.tsx:440:17",className:"text-slate-300",children:"状态"}),e.jsxs("select",{"code-path":"src/components/cloud/CloudAccountManager.tsx:441:17",value:s.status,onChange:c=>l({...s,status:c.target.value}),className:"w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-md text-slate-100 text-sm",children:[e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:446:19",value:"active",children:"正常"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:447:19",value:"inactive",children:"已停用"}),e.jsx("option",{"code-path":"src/components/cloud/CloudAccountManager.tsx:448:19",value:"error",children:"异常"})]})]})]})]}),e.jsxs(U,{"code-path":"src/components/cloud/CloudAccountManager.tsx:454:11",children:[e.jsx(p,{"code-path":"src/components/cloud/CloudAccountManager.tsx:455:13",variant:"outline",onClick:()=>g(!1),className:"border-slate-700 text-slate-300 hover:bg-slate-700",children:"取消"}),e.jsxs(p,{"code-path":"src/components/cloud/CloudAccountManager.tsx:458:13",className:"bg-blue-600 hover:bg-blue-700",disabled:!s.name.trim()||w,onClick:W,children:[w?e.jsx(Y,{"code-path":"src/components/cloud/CloudAccountManager.tsx:463:29",className:"h-4 w-4 mr-2 animate-spin"}):o?e.jsx(P,{"code-path":"src/components/cloud/CloudAccountManager.tsx:463:98",className:"h-4 w-4 mr-2"}):e.jsx(L,{"code-path":"src/components/cloud/CloudAccountManager.tsx:463:136",className:"h-4 w-4 mr-2"}),o?"保存修改":"创建账号"]})]})]})})]})}export{ie as CloudAccountManager}; diff --git a/backend/static/assets/CloudBilling-BUyc8wKP.js b/backend/static/assets/CloudBilling-BUyc8wKP.js new file mode 100644 index 0000000..1ae729b --- /dev/null +++ b/backend/static/assets/CloudBilling-BUyc8wKP.js @@ -0,0 +1 @@ +import{g as Z,j as e,r as a,D as ee,b as se,c as le,d as oe,e as te,I as j,f as ce,B as m,L as R,a as ye,T as De,J as M}from"./index-DfyorCky.js";import{L as r}from"./label-BK0h2apY.js";import{C as A,a as V}from"./card-C55cvSHg.js";import{B as Re}from"./badge-xNW8x0G1.js";import{S as ne}from"./switch-CGiGgOnh.js";import{S as w,a as S,b as k,c as _,d as h}from"./select-D5qUzdAs.js";import{t as p}from"./index-a3ybMjbR.js";import{b as g}from"./cloud-Dzoer-2i.js";import{T as ae}from"./trending-up-CdusV6gc.js";import{T as we}from"./trending-down-BGTWG_dA.js";import{R as J}from"./refresh-cw-DUB_tAG-.js";import{P as U}from"./plus-CUG-9kpu.js";import{P as G}from"./pencil-BqUotcjf.js";import{T as K}from"./trash-2-Dx32pOzT.js";import"./index-CWVNW_qu.js";const Se=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]],ke=Z("calendar-days",Se);const _e=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]],Q=Z("wallet",_e),v={aliyun:"阿里云",tencent:"腾讯云",aws:"AWS",huawei:"华为云",azure:"Azure"},O={aliyun:"bg-orange-500",tencent:"bg-blue-500",aws:"bg-amber-500",huawei:"bg-red-500",azure:"bg-sky-500"};function u(d){return`¥${d.toLocaleString("zh-CN",{minimumFractionDigits:2,maximumFractionDigits:2})}`}function E({icon:d,label:i,value:t,trend:c,trendLabel:o,alert:n}){return e.jsxs("div",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:35:5",className:`rounded-lg border p-4 ${n?"border-amber-500/30 bg-amber-500/5":"border-slate-800 bg-slate-900/50"}`,children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:36:7",className:"flex items-center justify-between mb-2",children:[e.jsx("span",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:37:9",className:"text-slate-400 text-sm",children:i}),e.jsx("span",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:38:9",className:n?"text-amber-400":"text-slate-500",children:d})]}),e.jsx("div",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:40:7",className:`text-2xl font-bold ${n?"text-amber-300":"text-slate-100"}`,children:t}),o&&e.jsxs("div",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:42:9",className:"flex items-center gap-1 mt-1 text-xs",children:[c!==void 0&&c>0&&e.jsx(ae,{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:43:48",className:"h-3 w-3 text-red-400"}),c!==void 0&&c<0&&e.jsx(we,{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:44:48",className:"h-3 w-3 text-green-400"}),e.jsx("span",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:45:11",className:"text-slate-500",children:o})]})]})}function He({data:d}){if(d.length===0)return e.jsx("p",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:54:12",className:"text-sm text-slate-500 py-8 text-center",children:"暂无数据"});const i=Math.max(...d.map(c=>c.cost),1),t=d.slice(-30);return e.jsxs("div",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:60:5",children:[e.jsx("div",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:61:7",className:"flex items-end gap-0.5 h-40",children:t.map((c,o)=>{const n=Math.max(c.cost/i*100,2);return e.jsxs("div",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:65:13",className:"flex-1 group relative",style:{height:"100%"},children:[e.jsx("div",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:70:15",className:"absolute bottom-0 w-full rounded-t-sm bg-gradient-to-t from-blue-600/60 to-blue-400/80 group-hover:from-blue-500 group-hover:to-blue-300 transition-colors",style:{height:`${n}%`}}),e.jsxs("div",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:74:15",className:"absolute bottom-full left-1/2 -translate-x-1/2 mb-2 hidden group-hover:block whitespace-nowrap text-xs bg-slate-800 text-slate-200 px-2 py-1 rounded border border-slate-700 z-10",children:[c.date,": ",u(c.cost)]})]},o)})}),e.jsxs("div",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:81:7",className:"flex justify-between mt-2 text-xs text-slate-500",children:[e.jsx("span",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:82:9",children:t[0]?.date}),e.jsx("span",{"code-path":"src/components/cloud/CloudBillingHelpers.tsx:83:9",children:t[t.length-1]?.date})]})]})}const X={provider:"aliyun",billing_date:"",cost:"",service:"",region:"",account_name:"",description:""};function ze({open:d,onOpenChange:i,editingRecord:t,onSuccess:c}){const[o,n]=a.useState(X),[B,C]=a.useState(!1);a.useEffect(()=>{d&&n(t?{provider:t.provider,billing_date:t.billing_date,cost:t.cost,service:t.service||"",region:t.region||"",account_name:t.account_name||"",description:t.description||""}:{...X,billing_date:new Date().toISOString().slice(0,10)})},[d,t]);const D=async()=>{if(!o.provider||!o.billing_date||!o.cost){p.error("请填写必填字段");return}C(!0);try{const l={...o,cost:parseFloat(o.cost)};t?(await g.remove(t.id),await g.create(l)):await g.create(l),i(!1),c(),p("保存成功")}catch(l){p.error("保存失败",{description:l.message})}finally{C(!1)}};return e.jsx(ee,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:90:5",open:d,onOpenChange:i,children:e.jsxs(se,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:91:7",className:"max-w-md",children:[e.jsxs(le,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:92:9",children:[e.jsx(oe,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:93:11",children:t?"编辑成本记录":"记录成本"}),e.jsx(te,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:94:11",children:"记录一条每日云资源成本"})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:96:9",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:97:11",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:98:13",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:99:15",className:"text-sm text-slate-300",children:"厂商 *"}),e.jsxs(w,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:100:15",value:o.provider,onValueChange:l=>n({...o,provider:l}),children:[e.jsx(S,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:101:17",className:"mt-1",children:e.jsx(k,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:101:49"})}),e.jsx(_,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:102:17",children:Object.entries(v).map(([l,f])=>e.jsx(h,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:104:21",value:l,children:f},l))})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:109:13",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:110:15",className:"text-sm text-slate-300",children:"日期 *"}),e.jsx(j,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:111:15",type:"date",className:"mt-1",value:o.billing_date,onChange:l=>n({...o,billing_date:l.target.value})})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:114:11",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:115:13",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:116:15",className:"text-sm text-slate-300",children:"费用(元) *"}),e.jsx(j,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:117:15",type:"number",step:"0.01",className:"mt-1",placeholder:"0.00",value:o.cost,onChange:l=>n({...o,cost:l.target.value})})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:119:13",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:120:15",className:"text-sm text-slate-300",children:"服务"}),e.jsx(j,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:121:15",className:"mt-1",placeholder:"ECS, RDS...",value:o.service,onChange:l=>n({...o,service:l.target.value})})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:124:11",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:125:13",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:126:15",className:"text-sm text-slate-300",children:"区域"}),e.jsx(j,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:127:15",className:"mt-1",placeholder:"cn-hangzhou",value:o.region,onChange:l=>n({...o,region:l.target.value})})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:129:13",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:130:15",className:"text-sm text-slate-300",children:"账号名称"}),e.jsx(j,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:131:15",className:"mt-1",placeholder:"主账号",value:o.account_name,onChange:l=>n({...o,account_name:l.target.value})})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRecordDialog.tsx:134:11",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:135:13",className:"text-sm text-slate-300",children:"备注"}),e.jsx(j,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:136:13",className:"mt-1",placeholder:"可选",value:o.description,onChange:l=>n({...o,description:l.target.value})})]})]}),e.jsxs(ce,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:139:9",children:[e.jsx(m,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:140:11",variant:"outline",onClick:()=>i(!1),children:"取消"}),e.jsxs(m,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:141:11",onClick:D,disabled:B,children:[B&&e.jsx(R,{"code-path":"src/components/cloud/BillingRecordDialog.tsx:142:28",className:"h-4 w-4 mr-1 animate-spin"}),"保存"]})]})]})})}const Y={name:"",provider:"",metric:"daily",threshold:"",operator:">",enabled:!0};function $e({open:d,onOpenChange:i,editingRule:t,onSuccess:c}){const[o,n]=a.useState(Y),[B,C]=a.useState(!1);a.useEffect(()=>{d&&n(t?{name:t.name,provider:t.provider||"",metric:t.metric||"daily",threshold:t.threshold,operator:t.operator||">",enabled:t.enabled}:{...Y})},[d,t]);const D=async()=>{if(!o.name||!o.threshold){p.error("请填写规则名称和阈值");return}C(!0);try{const l={...o,threshold:parseFloat(o.threshold)};t?await g.updateAlertRule(t.id,l):await g.createAlertRule(l),i(!1),c(),p("保存成功")}catch(l){p.error("保存失败",{description:l.message})}finally{C(!1)}};return e.jsx(ee,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:81:5",open:d,onOpenChange:i,children:e.jsxs(se,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:82:7",className:"max-w-md",children:[e.jsxs(le,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:83:9",children:[e.jsx(oe,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:84:11",children:t?"编辑预警规则":"添加预警规则"}),e.jsx(te,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:85:11",children:"设置成本阈值,超标时自动预警"})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRuleDialog.tsx:87:9",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/BillingRuleDialog.tsx:88:11",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:89:13",className:"text-sm text-slate-300",children:"规则名称 *"}),e.jsx(j,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:90:13",className:"mt-1",placeholder:"如:日成本超 500 元预警",value:o.name,onChange:l=>n({...o,name:l.target.value})})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRuleDialog.tsx:92:11",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/BillingRuleDialog.tsx:93:13",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:94:15",className:"text-sm text-slate-300",children:"厂商"}),e.jsxs(w,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:95:15",value:o.provider||"all",onValueChange:l=>n({...o,provider:l==="all"?"":l}),children:[e.jsx(S,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:96:17",className:"mt-1",children:e.jsx(k,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:96:49"})}),e.jsxs(_,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:97:17",children:[e.jsx(h,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:98:19",value:"all",children:"全部厂商"}),Object.entries(v).map(([l,f])=>e.jsx(h,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:100:21",value:l,children:f},l))]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRuleDialog.tsx:105:13",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:106:15",className:"text-sm text-slate-300",children:"指标"}),e.jsxs(w,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:107:15",value:o.metric,onValueChange:l=>n({...o,metric:l}),children:[e.jsx(S,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:108:17",className:"mt-1",children:e.jsx(k,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:108:49"})}),e.jsxs(_,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:109:17",children:[e.jsx(h,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:110:19",value:"daily",children:"日成本"}),e.jsx(h,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:111:19",value:"monthly",children:"月累计"})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRuleDialog.tsx:116:11",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/BillingRuleDialog.tsx:117:13",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:118:15",className:"text-sm text-slate-300",children:"比较"}),e.jsxs(w,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:119:15",value:o.operator,onValueChange:l=>n({...o,operator:l}),children:[e.jsx(S,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:120:17",className:"mt-1",children:e.jsx(k,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:120:49"})}),e.jsxs(_,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:121:17",children:[e.jsx(h,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:122:19",value:">",children:"大于 >"}),e.jsx(h,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:123:19",value:">=",children:"大于等于 ≥"}),e.jsx(h,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:124:19",value:"<",children:"小于 <"}),e.jsx(h,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:125:19",value:"<=",children:"小于等于 ≤"})]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRuleDialog.tsx:129:13",children:[e.jsx(r,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:130:15",className:"text-sm text-slate-300",children:"阈值(元) *"}),e.jsx(j,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:131:15",type:"number",step:"0.01",className:"mt-1",placeholder:"500.00",value:o.threshold,onChange:l=>n({...o,threshold:l.target.value})})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/BillingRuleDialog.tsx:134:11",className:"flex items-center gap-2",children:[e.jsx(ne,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:135:13",checked:o.enabled,onCheckedChange:l=>n({...o,enabled:l})}),e.jsx(r,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:136:13",className:"text-sm text-slate-300",children:"启用"})]})]}),e.jsxs(ce,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:139:9",children:[e.jsx(m,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:140:11",variant:"outline",onClick:()=>i(!1),children:"取消"}),e.jsxs(m,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:141:11",onClick:D,disabled:B,children:[B&&e.jsx(R,{"code-path":"src/components/cloud/BillingRuleDialog.tsx:142:28",className:"h-4 w-4 mr-1 animate-spin"}),"保存"]})]})]})})}function Ke(){const d=ye(),[i,t]=a.useState("overview"),[c,o]=a.useState(null),[n,B]=a.useState(!0),[C,D]=a.useState([]),[l,f]=a.useState(!0),[H,ie]=a.useState(""),[z,de]=a.useState(""),[$,re]=a.useState(""),[P,pe]=a.useState([]),[xe,I]=a.useState(!0),[me,L]=a.useState(!1),[ue,W]=a.useState(null),[he,T]=a.useState(!1),[ge,q]=a.useState(null),N=a.useCallback(async()=>{B(!0);try{const s=await g.getStats();o(s)}catch(s){p.error("加载统计失败",{description:s.message})}finally{B(!1)}},[]),b=a.useCallback(async()=>{f(!0);try{const s={};H&&(s.provider=H),z&&(s.start_date=z),$&&(s.end_date=$);const x=await g.list(s);D(x.list||[])}catch(s){p.error("加载账单失败",{description:s.message})}finally{f(!1)}},[H,z,$]),y=a.useCallback(async()=>{I(!0);try{const s=await g.listAlertRules();pe(s.list||[])}catch(s){p.error("加载预警规则失败",{description:s.message})}finally{I(!1)}},[]);a.useEffect(()=>{N()},[N]),a.useEffect(()=>{i==="records"&&b()},[i,b]),a.useEffect(()=>{i==="alerts"&&y()},[i,y]);const je=()=>{W(null),L(!0)},Be=s=>{W(s),L(!0)},Ce=()=>{q(null),T(!0)},ve=s=>{q(s),T(!0)},Ne=async s=>{if(await d({title:"删除账单记录",description:"确定删除这条成本记录?",variant:"destructive"}))try{await g.remove(s),b(),N(),p("删除成功")}catch(F){p.error("删除失败",{description:F.message})}},fe=async s=>{if(await d({title:"删除预警规则",description:"确定删除此预警规则?",variant:"destructive"}))try{await g.deleteAlertRule(s),y(),p("删除成功")}catch(F){p.error("删除失败",{description:F.message})}},be=async s=>{try{await g.toggleAlertRule(s),y(),N()}catch(x){p.error("操作失败",{description:x.message})}};return e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:165:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:166:7",className:"flex items-center justify-between",children:[e.jsx("h2",{"code-path":"src/components/cloud/CloudBilling.tsx:167:9",className:"text-lg font-semibold text-slate-100",children:"云账单管理"}),e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:168:9",className:"flex items-center gap-2",children:[e.jsxs(m,{"code-path":"src/components/cloud/CloudBilling.tsx:169:11",variant:"outline",size:"sm",onClick:()=>{N(),i==="records"&&b(),i==="alerts"&&y()},children:[e.jsx(J,{"code-path":"src/components/cloud/CloudBilling.tsx:170:13",className:"h-4 w-4 mr-1"}),"刷新"]}),i==="records"&&e.jsxs(m,{"code-path":"src/components/cloud/CloudBilling.tsx:173:13",size:"sm",onClick:je,children:[e.jsx(U,{"code-path":"src/components/cloud/CloudBilling.tsx:174:15",className:"h-4 w-4 mr-1"}),"记录成本"]}),i==="alerts"&&e.jsxs(m,{"code-path":"src/components/cloud/CloudBilling.tsx:178:13",size:"sm",onClick:Ce,children:[e.jsx(U,{"code-path":"src/components/cloud/CloudBilling.tsx:179:15",className:"h-4 w-4 mr-1"}),"添加规则"]})]})]}),e.jsx("div",{"code-path":"src/components/cloud/CloudBilling.tsx:185:7",className:"flex gap-1 border-b border-slate-800",children:[{key:"overview",label:"概览统计"},{key:"records",label:"成本记录"},{key:"alerts",label:"预警规则"}].map(s=>e.jsx("button",{"code-path":"src/components/cloud/CloudBilling.tsx:191:11",onClick:()=>t(s.key),className:`px-4 py-2 text-sm font-medium transition-colors border-b-2 -mb-px ${i===s.key?"text-blue-400 border-blue-400":"text-slate-400 border-transparent hover:text-slate-200"}`,children:s.label},s.key))}),i==="overview"&&e.jsx("div",{"code-path":"src/components/cloud/CloudBilling.tsx:206:9",className:"space-y-4",children:n?e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:208:13",className:"flex items-center justify-center py-20 text-slate-500",children:[e.jsx(R,{"code-path":"src/components/cloud/CloudBilling.tsx:208:84",className:"h-6 w-6 animate-spin mr-2"}),"加载中..."]}):c?e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:211:15",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(E,{"code-path":"src/components/cloud/CloudBilling.tsx:212:17",icon:e.jsx(Q,{"code-path":"src/components/cloud/CloudBilling.tsx:213:25",className:"h-5 w-5"}),label:"今日成本",value:u(c.today_cost||0),trend:c.today_cost-(c.yesterday_cost||0),trendLabel:`昨日 ${u(c.yesterday_cost||0)}`}),e.jsx(E,{"code-path":"src/components/cloud/CloudBilling.tsx:219:17",icon:e.jsx(ke,{"code-path":"src/components/cloud/CloudBilling.tsx:220:25",className:"h-5 w-5"}),label:"本月成本",value:u(c.month_cost||0)}),e.jsx(E,{"code-path":"src/components/cloud/CloudBilling.tsx:224:17",icon:e.jsx(ae,{"code-path":"src/components/cloud/CloudBilling.tsx:225:25",className:"h-5 w-5"}),label:"年度成本",value:u(c.year_cost||0)}),e.jsx(E,{"code-path":"src/components/cloud/CloudBilling.tsx:229:17",icon:e.jsx(De,{"code-path":"src/components/cloud/CloudBilling.tsx:230:25",className:"h-5 w-5"}),label:"活跃预警",value:`${c.alerts?.length||0} 条`,alert:c.alerts?.length>0})]}),c.alerts?.length>0&&e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:238:17",className:"rounded-lg border border-amber-500/30 bg-amber-500/5 p-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:239:19",className:"flex items-center gap-2 mb-3",children:[e.jsx(M,{"code-path":"src/components/cloud/CloudBilling.tsx:240:21",className:"h-4 w-4 text-amber-400"}),e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:241:21",className:"text-sm font-medium text-amber-300",children:"成本预警"})]}),e.jsx("div",{"code-path":"src/components/cloud/CloudBilling.tsx:243:19",className:"space-y-2",children:c.alerts.map((s,x)=>e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:245:23",className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:246:25",className:"flex items-center gap-2",children:[e.jsx(Re,{"code-path":"src/components/cloud/CloudBilling.tsx:247:27",variant:"outline",className:"border-amber-500/50 text-amber-300",children:s.rule_name}),e.jsxs("span",{"code-path":"src/components/cloud/CloudBilling.tsx:248:27",className:"text-slate-400",children:[s.provider," · ",s.metric==="daily"?"日":"月","成本"]})]}),e.jsxs("span",{"code-path":"src/components/cloud/CloudBilling.tsx:252:25",className:"text-slate-300",children:["当前 ",e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:253:30",className:"text-amber-300 font-medium",children:u(s.current)})," ",s.operator," ","阈值 ",e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:255:30",className:"text-red-400 font-medium",children:u(s.threshold)})]})]},x))})]}),e.jsx(A,{"code-path":"src/components/cloud/CloudBilling.tsx:263:15",className:"bg-slate-900/50 border-slate-800",children:e.jsxs(V,{"code-path":"src/components/cloud/CloudBilling.tsx:264:17",className:"pt-4",children:[e.jsx("h3",{"code-path":"src/components/cloud/CloudBilling.tsx:265:19",className:"text-sm font-medium text-slate-200 mb-4",children:"近 30 天成本趋势"}),e.jsx(He,{"code-path":"src/components/cloud/CloudBilling.tsx:266:19",data:c.month_trend||[]})]})}),e.jsx(A,{"code-path":"src/components/cloud/CloudBilling.tsx:270:15",className:"bg-slate-900/50 border-slate-800",children:e.jsxs(V,{"code-path":"src/components/cloud/CloudBilling.tsx:271:17",className:"pt-4",children:[e.jsx("h3",{"code-path":"src/components/cloud/CloudBilling.tsx:272:19",className:"text-sm font-medium text-slate-200 mb-4",children:"本月厂商成本分布"}),(c.provider_dist||[]).length===0?e.jsx("p",{"code-path":"src/components/cloud/CloudBilling.tsx:274:21",className:"text-sm text-slate-500 py-8 text-center",children:"暂无数据"}):e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:276:21",className:"space-y-3",children:[e.jsx("div",{"code-path":"src/components/cloud/CloudBilling.tsx:277:23",className:"flex h-8 rounded-lg overflow-hidden",children:c.provider_dist.map((s,x)=>e.jsx("div",{"code-path":"src/components/cloud/CloudBilling.tsx:279:27",className:`${O[s.provider]||"bg-slate-600"} flex items-center justify-center text-xs text-white font-medium`,style:{width:`${s.percent}%`},title:`${v[s.provider]||s.provider}: ${u(s.cost)} (${s.percent.toFixed(1)}%)`,children:s.percent>8?v[s.provider]||s.provider:""},x))}),e.jsx("div",{"code-path":"src/components/cloud/CloudBilling.tsx:289:23",className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:c.provider_dist.map((s,x)=>e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:291:27",className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:292:29",className:"flex items-center gap-2",children:[e.jsx("div",{"code-path":"src/components/cloud/CloudBilling.tsx:293:31",className:`w-3 h-3 rounded ${O[s.provider]||"bg-slate-600"}`}),e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:294:31",className:"text-slate-300",children:v[s.provider]||s.provider})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:296:29",className:"text-right",children:[e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:297:31",className:"text-slate-200 font-medium",children:u(s.cost)}),e.jsxs("span",{"code-path":"src/components/cloud/CloudBilling.tsx:298:31",className:"text-slate-500 ml-2",children:[s.percent.toFixed(1),"%"]})]})]},x))})]})]})})]}):null}),i==="records"&&e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:313:9",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:314:11",className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:315:13",children:[e.jsx(r,{"code-path":"src/components/cloud/CloudBilling.tsx:316:15",className:"text-xs text-slate-400 mb-1",children:"厂商"}),e.jsxs(w,{"code-path":"src/components/cloud/CloudBilling.tsx:317:15",value:H||"all",onValueChange:s=>ie(s==="all"?"":s),children:[e.jsx(S,{"code-path":"src/components/cloud/CloudBilling.tsx:318:17",className:"w-32 h-9",children:e.jsx(k,{"code-path":"src/components/cloud/CloudBilling.tsx:318:53"})}),e.jsxs(_,{"code-path":"src/components/cloud/CloudBilling.tsx:319:17",children:[e.jsx(h,{"code-path":"src/components/cloud/CloudBilling.tsx:320:19",value:"all",children:"全部"}),Object.entries(v).map(([s,x])=>e.jsx(h,{"code-path":"src/components/cloud/CloudBilling.tsx:322:21",value:s,children:x},s))]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:327:13",children:[e.jsx(r,{"code-path":"src/components/cloud/CloudBilling.tsx:328:15",className:"text-xs text-slate-400 mb-1",children:"开始日期"}),e.jsx(j,{"code-path":"src/components/cloud/CloudBilling.tsx:329:15",type:"date",className:"w-40 h-9",value:z,onChange:s=>de(s.target.value)})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:331:13",children:[e.jsx(r,{"code-path":"src/components/cloud/CloudBilling.tsx:332:15",className:"text-xs text-slate-400 mb-1",children:"结束日期"}),e.jsx(j,{"code-path":"src/components/cloud/CloudBilling.tsx:333:15",type:"date",className:"w-40 h-9",value:$,onChange:s=>re(s.target.value)})]}),e.jsxs(m,{"code-path":"src/components/cloud/CloudBilling.tsx:335:13",variant:"outline",size:"sm",onClick:b,children:[e.jsx(J,{"code-path":"src/components/cloud/CloudBilling.tsx:336:15",className:"h-4 w-4 mr-1"}),"查询"]})]}),l?e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:341:13",className:"flex items-center justify-center py-20 text-slate-500",children:[e.jsx(R,{"code-path":"src/components/cloud/CloudBilling.tsx:341:84",className:"h-6 w-6 animate-spin mr-2"}),"加载中..."]}):C.length===0?e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:343:13",className:"py-20 text-center text-slate-500",children:[e.jsx(Q,{"code-path":"src/components/cloud/CloudBilling.tsx:344:15",className:"h-12 w-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{"code-path":"src/components/cloud/CloudBilling.tsx:345:15",className:"text-sm",children:"暂无成本记录"})]}):e.jsx("div",{"code-path":"src/components/cloud/CloudBilling.tsx:348:13",className:"overflow-x-auto rounded-lg border border-slate-800",children:e.jsxs("table",{"code-path":"src/components/cloud/CloudBilling.tsx:349:15",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/cloud/CloudBilling.tsx:350:17",className:"bg-slate-900/80 text-slate-400",children:e.jsxs("tr",{"code-path":"src/components/cloud/CloudBilling.tsx:351:19",children:[e.jsx("th",{"code-path":"src/components/cloud/CloudBilling.tsx:352:21",className:"px-4 py-2.5 text-left font-medium",children:"日期"}),e.jsx("th",{"code-path":"src/components/cloud/CloudBilling.tsx:353:21",className:"px-4 py-2.5 text-left font-medium",children:"厂商"}),e.jsx("th",{"code-path":"src/components/cloud/CloudBilling.tsx:354:21",className:"px-4 py-2.5 text-left font-medium",children:"服务"}),e.jsx("th",{"code-path":"src/components/cloud/CloudBilling.tsx:355:21",className:"px-4 py-2.5 text-left font-medium",children:"区域"}),e.jsx("th",{"code-path":"src/components/cloud/CloudBilling.tsx:356:21",className:"px-4 py-2.5 text-left font-medium",children:"账号"}),e.jsx("th",{"code-path":"src/components/cloud/CloudBilling.tsx:357:21",className:"px-4 py-2.5 text-right font-medium",children:"费用"}),e.jsx("th",{"code-path":"src/components/cloud/CloudBilling.tsx:358:21",className:"px-4 py-2.5 text-left font-medium",children:"说明"}),e.jsx("th",{"code-path":"src/components/cloud/CloudBilling.tsx:359:21",className:"px-4 py-2.5 text-center font-medium",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/cloud/CloudBilling.tsx:362:17",children:C.map(s=>e.jsxs("tr",{"code-path":"src/components/cloud/CloudBilling.tsx:364:21",className:"border-t border-slate-800 hover:bg-slate-800/30",children:[e.jsx("td",{"code-path":"src/components/cloud/CloudBilling.tsx:365:23",className:"px-4 py-2.5 text-slate-300",children:s.billing_date}),e.jsx("td",{"code-path":"src/components/cloud/CloudBilling.tsx:366:23",className:"px-4 py-2.5",children:e.jsxs("span",{"code-path":"src/components/cloud/CloudBilling.tsx:367:25",className:"inline-flex items-center gap-1.5",children:[e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:368:27",className:`w-2 h-2 rounded-full ${O[s.provider]||"bg-slate-500"}`}),v[s.provider]||s.provider]})}),e.jsx("td",{"code-path":"src/components/cloud/CloudBilling.tsx:372:23",className:"px-4 py-2.5 text-slate-400",children:s.service||"-"}),e.jsx("td",{"code-path":"src/components/cloud/CloudBilling.tsx:373:23",className:"px-4 py-2.5 text-slate-400",children:s.region||"-"}),e.jsx("td",{"code-path":"src/components/cloud/CloudBilling.tsx:374:23",className:"px-4 py-2.5 text-slate-400",children:s.account_name||"-"}),e.jsx("td",{"code-path":"src/components/cloud/CloudBilling.tsx:375:23",className:"px-4 py-2.5 text-right text-slate-200 font-medium",children:u(s.cost)}),e.jsx("td",{"code-path":"src/components/cloud/CloudBilling.tsx:376:23",className:"px-4 py-2.5 text-slate-500 max-w-xs truncate",children:s.description||"-"}),e.jsx("td",{"code-path":"src/components/cloud/CloudBilling.tsx:377:23",className:"px-4 py-2.5",children:e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:378:25",className:"flex items-center justify-center gap-1",children:[e.jsx(m,{"code-path":"src/components/cloud/CloudBilling.tsx:379:27",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>Be(s),children:e.jsx(G,{"code-path":"src/components/cloud/CloudBilling.tsx:380:29",className:"h-3.5 w-3.5"})}),e.jsx(m,{"code-path":"src/components/cloud/CloudBilling.tsx:382:27",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-400 hover:text-red-300",onClick:()=>Ne(s.id),children:e.jsx(K,{"code-path":"src/components/cloud/CloudBilling.tsx:383:29",className:"h-3.5 w-3.5"})})]})})]},s.id))})]})})]}),i==="alerts"&&e.jsx("div",{"code-path":"src/components/cloud/CloudBilling.tsx:397:9",className:"space-y-3",children:xe?e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:399:13",className:"flex items-center justify-center py-20 text-slate-500",children:[e.jsx(R,{"code-path":"src/components/cloud/CloudBilling.tsx:399:84",className:"h-6 w-6 animate-spin mr-2"}),"加载中..."]}):P.length===0?e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:401:13",className:"py-20 text-center text-slate-500",children:[e.jsx(M,{"code-path":"src/components/cloud/CloudBilling.tsx:402:15",className:"h-12 w-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{"code-path":"src/components/cloud/CloudBilling.tsx:403:15",className:"text-sm",children:"暂无预警规则"})]}):e.jsx("div",{"code-path":"src/components/cloud/CloudBilling.tsx:406:13",className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:P.map(s=>e.jsx(A,{"code-path":"src/components/cloud/CloudBilling.tsx:408:17",className:"bg-slate-900/50 border-slate-800",children:e.jsxs(V,{"code-path":"src/components/cloud/CloudBilling.tsx:409:19",className:"pt-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:410:21",className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:411:23",className:"flex items-center gap-2",children:[e.jsx(M,{"code-path":"src/components/cloud/CloudBilling.tsx:412:25",className:`h-4 w-4 ${s.enabled?"text-amber-400":"text-slate-600"}`}),e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:413:25",className:"text-sm font-medium text-slate-200",children:s.name})]}),e.jsx(ne,{"code-path":"src/components/cloud/CloudBilling.tsx:415:23",checked:s.enabled,onCheckedChange:()=>be(s.id)})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:417:21",className:"grid grid-cols-2 gap-2 text-sm",children:[e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:418:23",children:[e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:419:25",className:"text-slate-500",children:"厂商"}),e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:420:25",className:"ml-2 text-slate-300",children:s.provider?v[s.provider]||s.provider:"全部"})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:422:23",children:[e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:423:25",className:"text-slate-500",children:"指标"}),e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:424:25",className:"ml-2 text-slate-300",children:s.metric==="daily"?"日成本":"月累计"})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:426:23",children:[e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:427:25",className:"text-slate-500",children:"阈值"}),e.jsxs("span",{"code-path":"src/components/cloud/CloudBilling.tsx:428:25",className:"ml-2 text-amber-300 font-medium",children:[s.operator," ",u(s.threshold)]})]}),s.last_triggered&&e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:431:25",children:[e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:432:27",className:"text-slate-500",children:"最后触发"}),e.jsx("span",{"code-path":"src/components/cloud/CloudBilling.tsx:433:27",className:"ml-2 text-slate-400",children:new Date(s.last_triggered).toLocaleString("zh-CN")})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/CloudBilling.tsx:437:21",className:"flex justify-end gap-1 mt-3",children:[e.jsx(m,{"code-path":"src/components/cloud/CloudBilling.tsx:438:23",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>ve(s),children:e.jsx(G,{"code-path":"src/components/cloud/CloudBilling.tsx:439:25",className:"h-3.5 w-3.5"})}),e.jsx(m,{"code-path":"src/components/cloud/CloudBilling.tsx:441:23",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-400 hover:text-red-300",onClick:()=>fe(s.id),children:e.jsx(K,{"code-path":"src/components/cloud/CloudBilling.tsx:442:25",className:"h-3.5 w-3.5"})})]})]})},s.id))})}),e.jsx(ze,{"code-path":"src/components/cloud/CloudBilling.tsx:453:7",open:me,onOpenChange:L,editingRecord:ue,onSuccess:()=>{b(),N()}}),e.jsx($e,{"code-path":"src/components/cloud/CloudBilling.tsx:459:7",open:he,onOpenChange:T,editingRule:ge,onSuccess:()=>{y(),N()}})]})}export{Ke as CloudBilling}; diff --git a/backend/static/assets/ClusterOverviewPage-CYcNLUM0.js b/backend/static/assets/ClusterOverviewPage-CYcNLUM0.js new file mode 100644 index 0000000..3e1dae8 --- /dev/null +++ b/backend/static/assets/ClusterOverviewPage-CYcNLUM0.js @@ -0,0 +1 @@ +import{i as F,k as K,r as c,j as e,m as w,n as C,B as G,L as A,o as k,p as R,q as T,s as H,A as q,t as z,v as D}from"./index-DfyorCky.js";import{C as i,a as u}from"./card-C55cvSHg.js";import{B as M}from"./badge-xNW8x0G1.js";import{T as J,a as Q,b as x,c as n,d as V,e as a}from"./table-5sHV4Akp.js";import{k as j}from"./kubernetes-J8O09fK7.js";import{u as W}from"./use-toast-CrSOP4cJ.js";import{R as X}from"./refresh-cw-DUB_tAG-.js";const Y={"kube-system":T,"kube-public":z,"kube-node-lease":q,default:H};function ne(){const{clusterCode:r}=F(),B=K(),{toast:E}=W(),[,P]=c.useState([]),[m,O]=c.useState([]),[N,f]=c.useState([]),[d,I]=c.useState(null),[p,y]=c.useState(!1),_=c.useCallback(async()=>{try{const t=(await j.getClusters())?.list||[];P(t);const o=t.find(l=>(l.code||String(l.id))===r);I(o||null),!o&&t.length>0&&r&&E({title:"集群未找到",description:`找不到集群 ${r}`,variant:"destructive"})}catch{P([])}},[r]),v=c.useCallback(async()=>{if(r){y(!0);try{const[s,t]=await Promise.all([j.getNodes(r).catch(()=>[]),j.getNamespaces(r).catch(()=>[])]);O(Array.isArray(s)?s:s?.list||s?.data||[]);const o=Array.isArray(t)?t:t?.list||t?.data||[];f(o)}catch{O([]),f([])}finally{y(!1)}}},[r]);c.useEffect(()=>{_()},[_]),c.useEffect(()=>{v()},[v]);const L=s=>s?.role==="master"||s?.role==="control-plane"?"bg-blue-500/20 text-blue-400 border-blue-500/30":"bg-slate-500/20 text-slate-400 border-slate-500/30";return e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:81:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:83:7",className:"flex items-center gap-2 text-sm text-slate-500",children:[e.jsx(w,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:84:9",to:"/kubernetes",className:"hover:text-slate-300 transition-colors",children:"集群"}),e.jsx(C,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:85:9",className:"h-3 w-3"}),e.jsx("span",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:86:9",className:"text-slate-300",children:r})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:90:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:91:9",children:[e.jsx("h1",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:92:11",className:"text-2xl font-bold text-slate-100",children:r}),e.jsxs("p",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:93:11",className:"text-sm text-slate-500 mt-1",children:["集群概览",d?.version?` — Kubernetes ${d.version}`:""]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:98:9",className:"flex items-center gap-2",children:e.jsx(G,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:99:11",variant:"outline",size:"icon",className:"h-9 w-9 border-slate-700 text-slate-400",onClick:v,disabled:p,children:p?e.jsx(A,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:101:24",className:"h-4 w-4 animate-spin"}):e.jsx(X,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:101:71",className:"h-4 w-4"})})})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:107:7",className:"grid grid-cols-3 md:grid-cols-3 gap-4",children:[e.jsx(i,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:108:9",className:"bg-slate-900 border-slate-800",children:e.jsx(u,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:109:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:110:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:111:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:111:20",className:"text-sm text-slate-500",children:"节点"}),e.jsx("p",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:111:64",className:"text-2xl font-bold text-blue-400",children:m.length})]}),e.jsx(k,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:112:15",className:"h-8 w-8 opacity-30 text-blue-400"})]})})}),e.jsx(i,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:116:9",className:"bg-slate-900 border-slate-800",children:e.jsx(u,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:117:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:118:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:119:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:119:20",className:"text-sm text-slate-500",children:"命名空间"}),e.jsx("p",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:119:66",className:"text-2xl font-bold text-emerald-400",children:N.length})]}),e.jsx(R,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:120:15",className:"h-8 w-8 opacity-30 text-emerald-400"})]})})}),e.jsx(i,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:124:9",className:"bg-slate-900 border-slate-800",children:e.jsx(u,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:125:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:126:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:127:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:127:20",className:"text-sm text-slate-500",children:"版本"}),e.jsx("p",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:127:64",className:"text-lg font-bold text-slate-300",children:d?.version||"-"})]}),e.jsx(T,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:128:15",className:"h-8 w-8 opacity-30 text-slate-400"})]})})})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:135:7",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:136:9",className:"text-lg font-semibold text-slate-100 mb-3 flex items-center gap-2",children:[e.jsx(k,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:137:11",className:"h-4 w-4 text-blue-400"}),"节点列表"]}),e.jsx(i,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:139:9",className:"bg-slate-900 border-slate-800",children:e.jsx(u,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:140:11",className:"p-0",children:e.jsxs(J,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:141:13",children:[e.jsx(Q,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:142:15",children:e.jsxs(x,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:143:17",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(n,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:144:19",className:"text-slate-400",children:"名称"}),e.jsx(n,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:145:19",className:"text-slate-400",children:"角色"}),e.jsx(n,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:146:19",className:"text-slate-400",children:"状态"}),e.jsx(n,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:147:19",className:"text-slate-400",children:"IP"}),e.jsx(n,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:148:19",className:"text-slate-400",children:"OS"}),e.jsx(n,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:149:19",className:"text-slate-400",children:"Kubelet"}),e.jsx(n,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:150:19",className:"text-slate-400",children:"CPU"}),e.jsx(n,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:151:19",className:"text-slate-400",children:"内存"})]})}),e.jsx(V,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:154:15",children:p?e.jsx(x,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:156:19",children:e.jsxs(a,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:156:29",colSpan:8,className:"text-center text-slate-500 py-12",children:[e.jsx(A,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:156:97",className:"h-5 w-5 animate-spin mx-auto mb-2"}),"加载中..."]})}):m.length===0?e.jsx(x,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:158:19",children:e.jsxs(a,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:158:29",colSpan:8,className:"text-center text-slate-500 py-12",children:[e.jsx(k,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:158:97",className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"暂无节点"]})}):m.map(s=>{const t=s.cpu||0,o=s.cpu_usage_m?parseFloat(s.cpu_usage_m.replace("m","")):0,l=t>0?o/1e3/t*100:0,h=s.memory_mb||0,b=s.mem_usage_mi?parseFloat(s.mem_usage_mi.replace("Mi","").replace("Ki","").replace("Gi","")):0,U=s.mem_usage_mi?.includes("Ki")?b/1024:s.mem_usage_mi?.includes("Gi")?b*1024:b,g=h>0?U/h*100:0,S=$=>$>80?"bg-red-500":$>60?"bg-yellow-500":"bg-emerald-500";return e.jsxs(x,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:171:21",className:"border-slate-800 hover:bg-slate-800/30 cursor-pointer",onClick:()=>B(`/kubernetes/${r}/nodes/${s.name}`),children:[e.jsx(a,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:173:23",className:"font-medium text-blue-400 hover:text-blue-300",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:174:23",children:e.jsx(M,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:174:34",className:L(s),children:s.role||"worker"})}),e.jsx(a,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:175:23",children:e.jsx(M,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:175:34",className:s.status==="Ready"?"bg-emerald-500/20 text-emerald-400":"bg-red-500/20 text-red-400",children:s.status||"Unknown"})}),e.jsx(a,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:176:23",className:"text-sm text-slate-400",children:s.ip||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:177:23",className:"text-sm text-slate-400 max-w-[200px] truncate",children:s.os||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:178:23",className:"text-sm text-slate-400",children:s.kubelet_version||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:179:23",className:"text-xs",children:s.cpu_usage_m?e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:181:27",className:"flex items-center gap-1.5 min-w-[80px]",children:[e.jsx("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:182:29",className:"flex-1 h-1.5 rounded-full bg-slate-700/50 overflow-hidden",children:e.jsx("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:183:31",className:`h-full rounded-full ${S(l)}`,style:{width:`${Math.min(l,100)}%`}})}),e.jsxs("span",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:185:29",className:"text-slate-400",children:[l.toFixed(0),"%"]})]}):e.jsxs("span",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:188:27",className:"text-slate-500",children:[t," 核"]})}),e.jsx(a,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:191:23",className:"text-xs",children:s.mem_usage_mi?e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:193:27",className:"flex items-center gap-1.5 min-w-[80px]",children:[e.jsx("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:194:29",className:"flex-1 h-1.5 rounded-full bg-slate-700/50 overflow-hidden",children:e.jsx("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:195:31",className:`h-full rounded-full ${S(g)}`,style:{width:`${Math.min(g,100)}%`}})}),e.jsxs("span",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:197:29",className:"text-slate-400",children:[g.toFixed(0),"%"]})]}):e.jsxs("span",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:200:27",className:"text-slate-500",children:[h,"Mi"]})})]},s.name)})})]})})})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:214:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:215:9",className:"flex items-center justify-between mb-3",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:216:11",className:"text-lg font-semibold text-slate-100 flex items-center gap-2",children:[e.jsx(R,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:217:13",className:"h-4 w-4 text-emerald-400"}),"命名空间"]}),e.jsxs(w,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:219:11",to:`/kubernetes/${r}/namespaces`,className:"text-sm text-blue-400 hover:text-blue-300 transition-colors flex items-center gap-1",children:["管理全部 ",e.jsx(C,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:220:18",className:"h-3 w-3"})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:223:9",className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:N.map(s=>{const t=Y[s]||D;return e.jsx(w,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:227:15",to:`/kubernetes/${r}/namespace/${s}`,className:"bg-slate-900 border border-slate-800 rounded-lg p-4 hover:border-slate-600 hover:bg-slate-800/50 transition-all group",children:e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:231:17",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:232:19",className:"flex items-center gap-2",children:[e.jsx(t,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:233:21",className:"h-5 w-5 text-slate-500 group-hover:text-slate-300 transition-colors"}),e.jsx("span",{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:234:21",className:"text-sm font-medium text-slate-300 group-hover:text-slate-100 transition-colors",children:s})]}),e.jsx(C,{"code-path":"src/components/kubernetes/ClusterOverviewPage.tsx:236:19",className:"h-4 w-4 text-slate-600 group-hover:text-slate-400 transition-colors"})]})},s)})})]})]})}export{ne as default}; diff --git a/backend/static/assets/CredentialManager-DlhOOSIa.js b/backend/static/assets/CredentialManager-DlhOOSIa.js new file mode 100644 index 0000000..d53fc43 --- /dev/null +++ b/backend/static/assets/CredentialManager-DlhOOSIa.js @@ -0,0 +1 @@ +import{a as st,r as a,h as I,j as e,B as b,S as rt,I as p,t as qe,O as nt,G as ot,s as ct,v as dt,q as lt,P as V,x as pt,D as $e,b as Ue,c as ze,d as Be,e as it,f as Ge,T as xt,Q as Qe,U as Ye,V as mt}from"./index-DfyorCky.js";import{L as l}from"./label-BK0h2apY.js";import{B as S}from"./badge-xNW8x0G1.js";import{S as Ke,a as De,b as Ae,c as Pe,d as _}from"./select-D5qUzdAs.js";import{t as y}from"./index-a3ybMjbR.js";import{R as gt}from"./refresh-cw-DUB_tAG-.js";import{P as Re}from"./plus-CUG-9kpu.js";import{Z as ht}from"./zap-D2uWSK32.js";import{F as yt}from"./file-text-C9G5abwR.js";import{P as vt}from"./pencil-BqUotcjf.js";import{C as Ze}from"./circle-x-DK79Dhg2.js";import{C as We}from"./circle-check-DWcXrx2k.js";import{T as Ct}from"./trash-2-Dx32pOzT.js";import{C as Ve}from"./copy-DXW4LnkN.js";import"./index-CWVNW_qu.js";const O={ssh:{label:"SSH 密钥",icon:lt,color:"text-amber-400",desc:"SSH 私钥/公钥/密码"},docker:{label:"Docker 凭证",icon:dt,color:"text-cyan-400",desc:"Docker Registry 登录凭据"},tls:{label:"TLS 证书",icon:qe,color:"text-green-400",desc:"TLS/SSL 证书与私钥"},aksk:{label:"AKSK 密钥",icon:ct,color:"text-purple-400",desc:"云服务 AccessKey/SecretKey"},database:{label:"数据库凭证",icon:ot,color:"text-blue-400",desc:"数据库连接信息"},api:{label:"API 密钥",icon:nt,color:"text-orange-400",desc:"API Token/Key + 端点"},generic:{label:"通用凭证",icon:yt,color:"text-gray-400",desc:"自定义 Key/Value 键值对"}},Xe={ssh:"bg-amber-500/20 text-amber-400 border-amber-500/30",docker:"bg-cyan-500/20 text-cyan-400 border-cyan-500/30",tls:"bg-green-500/20 text-green-400 border-green-500/30",aksk:"bg-purple-500/20 text-purple-400 border-purple-500/30",database:"bg-blue-500/20 text-blue-400 border-blue-500/30",api:"bg-orange-500/20 text-orange-400 border-orange-500/30",generic:"bg-gray-500/20 text-gray-400 border-gray-500/30"};function ut({open:j,onClose:M,credId:k}){const[n,h]=a.useState(null),[T,v]=a.useState(!1),[E,w]=a.useState({});if(a.useEffect(()=>{!k||!j||(v(!0),I.get(`/credentials/${k}`).then(d=>{h(d)}).catch(()=>y.error("加载详情失败")).finally(()=>v(!1)))},[k,j]),!j||!k)return null;const c=d=>w(i=>({...i,[d]:!i[d]})),K=d=>{navigator.clipboard.writeText(d),y.success("已复制")},x=n?.secret_type,C=O[x],r=n?.content||{},o=({label:d,value:i,sensitive:m,fieldKey:D})=>{if(i==null||i==="")return null;const L=typeof i=="string"&&i.length>80,A=D?E[D]:!1;return e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:107:7",className:"mb-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:108:9",className:"flex items-center gap-2 text-xs text-[var(--dg-text-muted)] mb-1",children:[e.jsx(mt,{"code-path":"src/components/deploy/CredentialManager.tsx:109:11",className:"h-3 w-3"}),d]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:111:9",className:"flex gap-1",children:[L?e.jsx("textarea",{"code-path":"src/components/deploy/CredentialManager.tsx:113:13",readOnly:!0,value:m&&!A?"••••••••":i,className:"flex-1 rounded-md bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] text-[var(--dg-text-primary)] p-2 text-xs font-mono resize-none",rows:4}):e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:117:13",readOnly:!0,value:m&&!A?"••••••••":String(i),className:"flex-1 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono text-xs"}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:120:11",className:"flex flex-col gap-0.5 shrink-0",children:[m&&e.jsx(b,{"code-path":"src/components/deploy/CredentialManager.tsx:122:15",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>c(D),children:A?e.jsx(Qe,{"code-path":"src/components/deploy/CredentialManager.tsx:123:25",className:"h-3 w-3"}):e.jsx(Ye,{"code-path":"src/components/deploy/CredentialManager.tsx:123:58",className:"h-3 w-3"})}),e.jsx(b,{"code-path":"src/components/deploy/CredentialManager.tsx:126:13",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>K(String(i)),children:e.jsx(Ve,{"code-path":"src/components/deploy/CredentialManager.tsx:127:15",className:"h-3 w-3"})})]})]})]})};return e.jsx($e,{"code-path":"src/components/deploy/CredentialManager.tsx:136:5",open:j,onOpenChange:M,children:e.jsxs(Ue,{"code-path":"src/components/deploy/CredentialManager.tsx:137:7",className:"sm:max-w-[680px] max-h-[85vh] overflow-y-auto bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:[e.jsx(ze,{"code-path":"src/components/deploy/CredentialManager.tsx:138:9",children:e.jsxs(Be,{"code-path":"src/components/deploy/CredentialManager.tsx:139:11",className:"text-[var(--dg-text-primary)] flex items-center gap-2",children:[C?e.jsx(C.icon,{"code-path":"src/components/deploy/CredentialManager.tsx:140:20",className:`h-5 w-5 ${C.color}`}):e.jsx(V,{"code-path":"src/components/deploy/CredentialManager.tsx:140:70",className:"h-5 w-5 text-[var(--dg-text-muted)]"}),"凭据详情"]})}),T?e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:145:11",className:"text-center py-8 text-[var(--dg-text-muted)]",children:"加载中..."}):n?e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:147:11",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:149:13",className:"grid grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:150:15",children:[e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:150:20",className:"text-[var(--dg-text-muted)]",children:"名称:"}),e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:150:76",className:"text-[var(--dg-text-primary)] font-medium",children:n.name})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:151:15",children:[e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:151:20",className:"text-[var(--dg-text-muted)]",children:"类型:"}),e.jsx(S,{"code-path":"src/components/deploy/CredentialManager.tsx:152:17",variant:"outline",className:`text-xs ml-1 ${Xe[x]||""}`,children:C?.label||x})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:154:15",children:[e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:154:20",className:"text-[var(--dg-text-muted)]",children:"状态:"}),n.is_active?e.jsxs(S,{"code-path":"src/components/deploy/CredentialManager.tsx:156:21",className:"bg-green-500/20 text-green-400 text-xs ml-1",children:[e.jsx(We,{"code-path":"src/components/deploy/CredentialManager.tsx:156:84",className:"h-3 w-3 mr-0.5"}),"启用"]}):e.jsxs(S,{"code-path":"src/components/deploy/CredentialManager.tsx:157:21",className:"bg-red-500/20 text-red-400 text-xs ml-1",children:[e.jsx(Ze,{"code-path":"src/components/deploy/CredentialManager.tsx:157:80",className:"h-3 w-3 mr-0.5"}),"禁用"]}),n.expires_at&&new Date(n.expires_at)K(n.env_prefix||""),children:[e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:163:17",className:"text-[var(--dg-text-muted)]",children:"引用ID:"}),e.jsx("code",{"code-path":"src/components/deploy/CredentialManager.tsx:164:17",className:"text-[var(--dg-blue)] font-mono text-xs",children:n.env_prefix||"无"}),e.jsx(Ve,{"code-path":"src/components/deploy/CredentialManager.tsx:165:17",className:"h-3 w-3 inline ml-1 text-[var(--dg-text-muted)]"})]}),n.tags?.length>0&&e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:168:17",className:"col-span-2",children:[e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:169:19",className:"text-[var(--dg-text-muted)]",children:"标签:"}),n.tags.map(d=>e.jsx(S,{"code-path":"src/components/deploy/CredentialManager.tsx:171:21",variant:"outline",className:"text-xs ml-1 border-[var(--dg-border)]",children:d},d))]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:175:15",className:"col-span-2",children:[e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:175:43",className:"text-[var(--dg-text-muted)]",children:"描述:"}),e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:175:99",className:"text-[var(--dg-text-secondary)]",children:n.description||"无"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:176:15",children:[e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:176:20",className:"text-[var(--dg-text-muted)]",children:"创建:"}),e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:176:76",className:"text-[var(--dg-text-secondary)] text-xs",children:new Date(n.created_at).toLocaleString()})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:177:15",children:[e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:177:20",className:"text-[var(--dg-text-muted)]",children:"更新:"}),e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:177:76",className:"text-[var(--dg-text-secondary)] text-xs",children:new Date(n.updated_at).toLocaleString()})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:181:13",className:"border-t border-[var(--dg-border)] pt-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:182:15",className:"flex items-center gap-2 text-sm text-[var(--dg-text-primary)] font-medium mb-3",children:[e.jsx(V,{"code-path":"src/components/deploy/CredentialManager.tsx:183:17",className:"h-4 w-4 text-yellow-500"}),"密钥数据"]}),e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:185:15",className:"p-3 rounded-md bg-yellow-500/5 border border-yellow-500/20 mb-3",children:e.jsx("p",{"code-path":"src/components/deploy/CredentialManager.tsx:186:17",className:"text-xs text-yellow-400/80",children:"以下内容包含敏感信息,请妥善保管,不要泄露给他人。"})}),x==="ssh"&&e.jsxs(e.Fragment,{children:[e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:190:17",label:"SSH 用户",value:r.ssh_user}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:191:17",label:"SSH 端口",value:r.ssh_port}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:192:17",label:"SSH 密码",value:r.password,sensitive:!0,fieldKey:"ssh_password"}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:193:17",label:"私钥",value:r.private_key,sensitive:!0,fieldKey:"ssh_private_key"}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:194:17",label:"公钥",value:r.public_key,fieldKey:"ssh_public_key"})]}),x==="docker"&&e.jsxs(e.Fragment,{children:[e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:197:17",label:"Registry 地址",value:r.server}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:198:17",label:"用户名",value:r.username}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:199:17",label:"密码",value:r.password,sensitive:!0,fieldKey:"docker_password"})]}),x==="tls"&&e.jsxs(e.Fragment,{children:[e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:202:17",label:"证书",value:r.cert,sensitive:!0,fieldKey:"tls_cert"}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:203:17",label:"私钥",value:r.key,sensitive:!0,fieldKey:"tls_key"}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:204:17",label:"CA 证书",value:r.ca,sensitive:!0,fieldKey:"tls_ca"})]}),x==="aksk"&&e.jsxs(e.Fragment,{children:[e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:207:17",label:"Access Key ID",value:r.access_key}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:208:17",label:"Secret Access Key",value:r.secret_key,sensitive:!0,fieldKey:"aksk_secret_key"})]}),x==="database"&&e.jsxs(e.Fragment,{children:[e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:211:17",label:"数据库类型",value:(r.db_type||"").toUpperCase()}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:212:17",label:"主机",value:r.host}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:213:17",label:"端口",value:r.port}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:214:17",label:"数据库名",value:r.db_name}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:215:17",label:"用户名",value:r.username}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:216:17",label:"密码",value:r.password,sensitive:!0,fieldKey:"db_password"})]}),x==="api"&&e.jsxs(e.Fragment,{children:[e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:219:17",label:"API Key",value:r.api_key,sensitive:!0,fieldKey:"api_key"}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:220:17",label:"API 端点",value:r.endpoint})]}),x==="generic"&&e.jsxs(e.Fragment,{children:[e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:223:17",label:"Key",value:r.generic_key}),e.jsx(o,{"code-path":"src/components/deploy/CredentialManager.tsx:224:17",label:"Value",value:r.generic_value,sensitive:!0,fieldKey:"generic_value"})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:229:13",className:"border-t border-[var(--dg-border)] pt-3",children:[e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:230:15",className:"text-xs text-[var(--dg-text-muted)] mb-2",children:"在流水线/脚本中引用此凭据:"}),e.jsxs("code",{"code-path":"src/components/deploy/CredentialManager.tsx:231:15",className:"text-xs bg-[var(--dg-bg-tertiary)] px-3 py-1.5 rounded block text-[var(--dg-blue)]",children:["${",n.variable_name||n.name.toUpperCase().replace(/[^A-Z0-9]/g,"_"),"}"]})]})]}):e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:237:11",className:"text-center py-8 text-[var(--dg-text-muted)]",children:"未找到凭据数据"}),e.jsx(Ge,{"code-path":"src/components/deploy/CredentialManager.tsx:239:9",children:e.jsx(b,{"code-path":"src/components/deploy/CredentialManager.tsx:240:11",variant:"outline",onClick:M,children:"关闭"})})]})})}function bt({open:j,onClose:M,onSaved:k,editData:n}){const h=!!n,[T,v]=a.useState(""),[E,w]=a.useState(""),[c,K]=a.useState("ssh"),[x,C]=a.useState(""),[r,o]=a.useState(""),[d,i]=a.useState(!0),[m,D]=a.useState(!1),[L,A]=a.useState({}),[F,s]=a.useState("root"),[g,P]=a.useState("22"),[H,N]=a.useState(""),[q,$]=a.useState(""),[U,z]=a.useState(""),[B,G]=a.useState(""),[Q,Y]=a.useState(""),[Z,W]=a.useState(""),[X,J]=a.useState(""),[ee,te]=a.useState(""),[ae,se]=a.useState(""),[,Te]=a.useState(""),[re,ne]=a.useState(""),[oe,ce]=a.useState(""),[,Ee]=a.useState(""),[de,le]=a.useState("mysql"),[pe,ie]=a.useState(""),[xe,me]=a.useState("3306"),[ge,he]=a.useState(""),[ye,ve]=a.useState(""),[Ce,ue]=a.useState(""),[be,je]=a.useState(""),[Me,Ne]=a.useState(""),[fe,Se]=a.useState(""),[we,_e]=a.useState("");a.useEffect(()=>{j&&(n?(v(n.name),w(n.variable_name||""),K(n.secret_type),C(n.description||""),o((n.tags||[]).join(", ")),i(n.is_active),s(""),P("22"),N(""),$(""),z(""),G(""),Y(""),W(""),J(""),te(""),se(""),Te(""),ne(""),ce(""),Ee(""),le("mysql"),ie(""),me("3306"),he(""),ve(""),ue(""),je(""),Ne(""),Se(""),_e("")):(v(""),w(""),K("ssh"),C(""),o(""),i(!0),s("root"),P("22"),N(""),$(""),z(""),G(""),Y(""),W(""),J(""),te(""),se(""),Te(""),ne(""),ce(""),Ee(""),le("mysql"),ie(""),me("3306"),he(""),ve(""),ue(""),je(""),Ne(""),Se(""),_e("")),A({}))},[n,j]);const Je=t=>A(f=>({...f,[t]:!f[t]})),et=async()=>{if(!T.trim()){y.error("请填写凭据名称");return}D(!0);try{const t={name:T.trim(),secret_type:c,description:x.trim(),tags:r.split(",").map(f=>f.trim()).filter(Boolean),is_active:d};E.trim()&&(t.variable_name=E.trim()),c==="ssh"?(F.trim()&&(t.ssh_user=F.trim()),g&&(t.ssh_port=parseInt(g)||22),H.trim()&&(t.ssh_password=H.trim()),q.trim()&&(t.ssh_private_key=q.trim()),U.trim()&&(t.ssh_public_key=U.trim())):c==="docker"?(B.trim()&&(t.docker_server=B.trim()),Q.trim()&&(t.docker_username=Q.trim()),Z.trim()&&(t.docker_password=Z.trim())):c==="tls"?(X.trim()&&(t.tls_cert=X.trim()),ee.trim()&&(t.tls_key=ee.trim()),ae.trim()&&(t.tls_ca=ae.trim())):c==="aksk"?(re.trim()&&(t.aksk_access_key=re.trim()),oe.trim()&&(t.aksk_secret_key=oe.trim())):c==="database"?(de.trim()&&(t.db_type=de.trim()),pe.trim()&&(t.db_host=pe.trim()),xe&&(t.db_port=parseInt(xe)||3306),ge.trim()&&(t.db_name=ge.trim()),ye.trim()&&(t.db_username=ye.trim()),Ce.trim()&&(t.db_password=Ce.trim())):c==="api"?(be.trim()&&(t.api_key=be.trim()),Me.trim()&&(t.api_endpoint=Me.trim())):c==="generic"&&(fe.trim()&&(t.generic_key=fe.trim()),we.trim()&&(t.generic_value=we.trim())),h?(await I.put(`/credentials/${n.id}`,t),y.success("已更新")):(await I.post("/credentials",t),y.success("已创建")),k(),M()}catch(t){y.error(t?.response?.data?.message||"操作失败")}finally{D(!1)}},u=({label:t,value:f,onChange:Le,placeholder:Fe,fieldKey:He,required:tt,isLong:at})=>{const Oe=L[He];return e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:394:7",className:"space-y-1",children:[e.jsxs(l,{"code-path":"src/components/deploy/CredentialManager.tsx:395:9",className:"text-[var(--dg-text-secondary)] text-xs",children:[t,tt&&!h&&e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:395:99",className:"text-red-400",children:" *"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:396:9",className:"relative",children:[at?e.jsx("textarea",{"code-path":"src/components/deploy/CredentialManager.tsx:398:13",value:f,onChange:ke=>Le(ke.target.value),placeholder:Fe,rows:5,className:"w-full rounded-md bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] text-[var(--dg-text-primary)] p-2 text-sm font-mono placeholder:text-[var(--dg-text-muted)]"}):e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:402:13",value:f,onChange:ke=>Le(ke.target.value),type:Oe?"text":"password",placeholder:Fe,className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] pr-10 font-mono text-sm"}),e.jsx("button",{"code-path":"src/components/deploy/CredentialManager.tsx:406:11",type:"button",onClick:()=>Je(He),className:"absolute right-2 top-1/2 -translate-y-1/2 text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)] text-xs",children:Oe?e.jsx(Qe,{"code-path":"src/components/deploy/CredentialManager.tsx:408:21",className:"h-3.5 w-3.5"}):e.jsx(Ye,{"code-path":"src/components/deploy/CredentialManager.tsx:408:58",className:"h-3.5 w-3.5"})})]})]})},R=O[c],Ie=R?.icon||V;return e.jsx($e,{"code-path":"src/components/deploy/CredentialManager.tsx:419:5",open:j,onOpenChange:M,children:e.jsxs(Ue,{"code-path":"src/components/deploy/CredentialManager.tsx:420:7",className:"sm:max-w-[620px] max-h-[90vh] overflow-y-auto bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:[e.jsxs(ze,{"code-path":"src/components/deploy/CredentialManager.tsx:421:9",children:[e.jsxs(Be,{"code-path":"src/components/deploy/CredentialManager.tsx:422:11",className:"text-[var(--dg-text-primary)] flex items-center gap-2",children:[e.jsx(Ie,{"code-path":"src/components/deploy/CredentialManager.tsx:423:13",className:`h-5 w-5 ${R?.color||""}`}),h?"编辑凭据":"新增凭据"]}),e.jsx(it,{"code-path":"src/components/deploy/CredentialManager.tsx:426:11",className:"text-[var(--dg-text-muted)] text-xs",children:R?.desc||"管理敏感凭据信息"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:430:9",className:"space-y-4 py-2",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:432:11",className:"border-b border-[var(--dg-border)] pb-3",children:[e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:433:13",className:"text-xs font-medium text-[var(--dg-text-secondary)] mb-2",children:"基本信息"}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:434:13",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:435:15",className:"space-y-1",children:[e.jsxs(l,{"code-path":"src/components/deploy/CredentialManager.tsx:436:17",className:"text-[var(--dg-text-secondary)] text-xs",children:["凭据名称 ",e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:436:81",className:"text-red-400",children:"*"})]}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:437:17",value:T,onChange:t=>v(t.target.value),placeholder:"如:生产环境 SSH",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:440:15",className:"space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:441:17",className:"text-[var(--dg-text-secondary)] text-xs",children:"变量别名"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:442:17",value:E,onChange:t=>w(t.target.value),placeholder:"如:MYSQL_PROD",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono text-sm"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:445:15",className:"space-y-1",children:[e.jsxs(l,{"code-path":"src/components/deploy/CredentialManager.tsx:446:17",className:"text-[var(--dg-text-secondary)] text-xs",children:["类型",!h&&e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:446:90",className:"text-red-400",children:" *"})]}),e.jsxs(Ke,{"code-path":"src/components/deploy/CredentialManager.tsx:447:17",value:c,onValueChange:t=>K(t),disabled:h,children:[e.jsx(De,{"code-path":"src/components/deploy/CredentialManager.tsx:448:19",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(Ae,{"code-path":"src/components/deploy/CredentialManager.tsx:449:21"})}),e.jsx(Pe,{"code-path":"src/components/deploy/CredentialManager.tsx:451:19",className:"max-h-[300px]",children:Object.entries(O).map(([t,f])=>e.jsx(_,{"code-path":"src/components/deploy/CredentialManager.tsx:453:23",value:t,children:e.jsxs("span",{"code-path":"src/components/deploy/CredentialManager.tsx:454:25",className:"flex items-center gap-2",children:[e.jsx(f.icon,{"code-path":"src/components/deploy/CredentialManager.tsx:454:67",className:"h-4 w-4"}),f.label]})},t))})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:460:15",className:"space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:461:17",className:"text-[var(--dg-text-secondary)] text-xs",children:"标签"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:462:17",value:r,onChange:t=>o(t.target.value),placeholder:"生产环境, 阿里云",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:466:13",className:"mt-2 space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:467:15",className:"text-[var(--dg-text-secondary)] text-xs",children:"描述"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:468:15",value:x,onChange:t=>C(t.target.value),placeholder:"可选备注信息",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:474:11",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:475:13",className:"text-xs font-medium text-[var(--dg-text-secondary)] mb-2 flex items-center gap-2",children:[e.jsx(Ie,{"code-path":"src/components/deploy/CredentialManager.tsx:476:15",className:"h-3.5 w-3.5"}),R?.label||c," 配置",h&&e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:477:26",className:"text-[var(--dg-text-muted)]",children:"(仅填写需要修改的字段)"})]}),c==="ssh"&&e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:481:15",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:482:17",className:"space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:483:19",className:"text-[var(--dg-text-secondary)] text-xs",children:"SSH 用户"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:484:19",value:F,onChange:t=>s(t.target.value),placeholder:"root",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:487:17",className:"space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:488:19",className:"text-[var(--dg-text-secondary)] text-xs",children:"SSH 端口"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:489:19",value:g,onChange:t=>P(t.target.value),placeholder:"22",type:"number",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:492:17",className:"col-span-2",children:e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:493:19",label:"SSH 密码",value:H,onChange:N,placeholder:"密码(或留空用密钥)",fieldKey:"ssh_pwd"})}),e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:496:17",className:"col-span-2",children:e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:497:19",label:"私钥内容",value:q,onChange:$,placeholder:"粘贴 SSH 私钥...",fieldKey:"ssh_pk",isLong:!0})}),e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:500:17",className:"col-span-2",children:e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:501:19",label:"公钥内容",value:U,onChange:z,placeholder:"粘贴 SSH 公钥...",fieldKey:"ssh_pub",isLong:!0})})]}),c==="docker"&&e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:508:15",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:509:17",className:"col-span-2 space-y-1",children:[e.jsxs(l,{"code-path":"src/components/deploy/CredentialManager.tsx:510:19",className:"text-[var(--dg-text-secondary)] text-xs",children:["Registry 地址 ",e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:510:90",className:"text-red-400",children:"*"})]}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:511:19",value:B,onChange:t=>G(t.target.value),placeholder:"registry.example.com",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:514:17",className:"space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:515:19",className:"text-[var(--dg-text-secondary)] text-xs",children:"用户名"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:516:19",value:Q,onChange:t=>Y(t.target.value),placeholder:"admin",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:519:17",children:e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:519:22",label:"密码",value:Z,onChange:W,placeholder:"Registry 密码",fieldKey:"docker_pwd",required:!0})})]}),c==="tls"&&e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:525:15",className:"space-y-3",children:[e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:526:17",label:"证书 (PEM)",value:X,onChange:J,placeholder:"-----BEGIN CERTIFICATE-----",fieldKey:"tls_cert",isLong:!0,required:!0}),e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:528:17",label:"私钥 (PEM)",value:ee,onChange:te,placeholder:"-----BEGIN PRIVATE KEY-----",fieldKey:"tls_key",isLong:!0,required:!0}),e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:530:17",label:"CA 证书",value:ae,onChange:se,placeholder:"CA 证书内容...",fieldKey:"tls_ca",isLong:!0})]}),c==="aksk"&&e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:536:15",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:537:17",className:"col-span-2 space-y-1",children:[e.jsxs(l,{"code-path":"src/components/deploy/CredentialManager.tsx:538:19",className:"text-[var(--dg-text-secondary)] text-xs",children:["Access Key ID ",e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:538:92",className:"text-red-400",children:"*"})]}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:539:19",value:re,onChange:t=>ne(t.target.value),placeholder:"AKIDxxxx...",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono"})]}),e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:542:17",className:"col-span-2",children:e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:543:19",label:"Secret Access Key",value:oe,onChange:ce,placeholder:"输入 Secret Key",fieldKey:"aksk_sk",required:!0})})]}),c==="database"&&e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:550:15",className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:551:17",className:"space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:552:19",className:"text-[var(--dg-text-secondary)] text-xs",children:"数据库类型"}),e.jsxs(Ke,{"code-path":"src/components/deploy/CredentialManager.tsx:553:19",value:de,onValueChange:le,children:[e.jsx(De,{"code-path":"src/components/deploy/CredentialManager.tsx:554:21",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(Ae,{"code-path":"src/components/deploy/CredentialManager.tsx:555:23"})}),e.jsxs(Pe,{"code-path":"src/components/deploy/CredentialManager.tsx:557:21",children:[e.jsx(_,{"code-path":"src/components/deploy/CredentialManager.tsx:558:23",value:"mysql",children:"MySQL"}),e.jsx(_,{"code-path":"src/components/deploy/CredentialManager.tsx:559:23",value:"postgres",children:"PostgreSQL"}),e.jsx(_,{"code-path":"src/components/deploy/CredentialManager.tsx:560:23",value:"mongodb",children:"MongoDB"}),e.jsx(_,{"code-path":"src/components/deploy/CredentialManager.tsx:561:23",value:"redis",children:"Redis"}),e.jsx(_,{"code-path":"src/components/deploy/CredentialManager.tsx:562:23",value:"mssql",children:"SQL Server"}),e.jsx(_,{"code-path":"src/components/deploy/CredentialManager.tsx:563:23",value:"oracle",children:"Oracle"})]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:567:17",className:"space-y-1",children:[e.jsxs(l,{"code-path":"src/components/deploy/CredentialManager.tsx:568:19",className:"text-[var(--dg-text-secondary)] text-xs",children:["主机 ",e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:568:81",className:"text-red-400",children:"*"})]}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:569:19",value:pe,onChange:t=>ie(t.target.value),placeholder:"10.0.0.1",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:572:17",className:"space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:573:19",className:"text-[var(--dg-text-secondary)] text-xs",children:"端口"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:574:19",value:xe,onChange:t=>me(t.target.value),placeholder:"3306",type:"number",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:577:17",className:"space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:578:19",className:"text-[var(--dg-text-secondary)] text-xs",children:"数据库名"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:579:19",value:ge,onChange:t=>he(t.target.value),placeholder:"aiops",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:582:17",className:"space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:583:19",className:"text-[var(--dg-text-secondary)] text-xs",children:"用户名"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:584:19",value:ye,onChange:t=>ve(t.target.value),placeholder:"root",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:587:17",children:e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:587:22",label:"密码",value:Ce,onChange:ue,placeholder:"数据库密码",fieldKey:"db_pwd"})})]}),c==="api"&&e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:593:15",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:594:17",className:"space-y-1",children:[e.jsx(l,{"code-path":"src/components/deploy/CredentialManager.tsx:595:19",className:"text-[var(--dg-text-secondary)] text-xs",children:"API 端点"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:596:19",value:Me,onChange:t=>Ne(t.target.value),placeholder:"https://api.example.com",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono"})]}),e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:599:17",label:"API Key / Token",value:be,onChange:je,placeholder:"sk-xxxx...",fieldKey:"api_key",required:!0})]}),c==="generic"&&e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:605:15",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:606:17",className:"space-y-1",children:[e.jsxs(l,{"code-path":"src/components/deploy/CredentialManager.tsx:607:19",className:"text-[var(--dg-text-secondary)] text-xs",children:["Key ",e.jsx("span",{"code-path":"src/components/deploy/CredentialManager.tsx:607:82",className:"text-red-400",children:"*"})]}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:608:19",value:fe,onChange:t=>Se(t.target.value),placeholder:"MY_SECRET",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] font-mono"})]}),e.jsx(u,{"code-path":"src/components/deploy/CredentialManager.tsx:611:17",label:"Value",value:we,onChange:_e,placeholder:"密钥值",fieldKey:"generic_val",required:!0})]})]})]}),e.jsxs(Ge,{"code-path":"src/components/deploy/CredentialManager.tsx:617:9",children:[e.jsx(b,{"code-path":"src/components/deploy/CredentialManager.tsx:618:11",variant:"outline",onClick:M,children:"取消"}),e.jsx(b,{"code-path":"src/components/deploy/CredentialManager.tsx:619:11",onClick:et,disabled:m,className:"bg-[var(--dg-blue)] hover:bg-[var(--dg-blue)]/80",children:m?"保存中...":h?"更新":"创建"})]})]})})}function Lt(){const j=st(),[M,k]=a.useState([]),[n,h]=a.useState(!1),[T,v]=a.useState(!1),[E,w]=a.useState(null),[c,K]=a.useState(null),[x,C]=a.useState(!1),[r,o]=a.useState(""),[d,i]=a.useState(""),m=a.useCallback(async()=>{h(!0);try{const s=new URLSearchParams;r&&s.set("secret_type",r),d&&s.set("search",d),s.set("page_size","100");const g=await I.get(`/credentials?${s.toString()}`);k(g?.list||[])}catch{y.error("获取凭证列表失败")}finally{h(!1)}},[r,d]);a.useEffect(()=>{m()},[m]);const D=async s=>{if(await j({title:"删除凭据",description:`确定删除凭据「${s.name}」?此操作不可撤销。`,confirmText:"删除",variant:"destructive"}))try{await I.delete(`/credentials/${s.id}`),y.success("已删除"),m()}catch{y.error("删除失败")}},L=async s=>{try{await I.put(`/credentials/${s.id}`,{is_active:!s.is_active}),y.success(s.is_active?"已禁用":"已启用"),m()}catch{y.error("操作失败")}},A=s=>{navigator.clipboard.writeText(s),y.success("引用 ID 已复制")},F=Object.entries(O);return e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:689:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:690:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:691:9",children:[e.jsx("h2",{"code-path":"src/components/deploy/CredentialManager.tsx:692:11",className:"text-lg font-semibold text-[var(--dg-text-primary)]",children:"凭据管理"}),e.jsx("p",{"code-path":"src/components/deploy/CredentialManager.tsx:693:11",className:"text-sm text-[var(--dg-text-muted)] mt-0.5",children:"统一管理 SSH 密钥、Docker 密码、AKSK、数据库等敏感凭据(AES 加密存储)"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:697:9",className:"flex items-center gap-2",children:[e.jsxs(b,{"code-path":"src/components/deploy/CredentialManager.tsx:698:11",variant:"outline",size:"sm",onClick:m,children:[e.jsx(gt,{"code-path":"src/components/deploy/CredentialManager.tsx:699:13",className:"w-4 h-4 mr-1"}),"刷新"]}),e.jsxs(b,{"code-path":"src/components/deploy/CredentialManager.tsx:701:11",size:"sm",onClick:()=>{w(null),v(!0)},children:[e.jsx(Re,{"code-path":"src/components/deploy/CredentialManager.tsx:702:13",className:"w-4 h-4 mr-1"}),"新增凭据"]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:708:7",className:"flex items-center gap-3 flex-wrap",children:[e.jsxs(Ke,{"code-path":"src/components/deploy/CredentialManager.tsx:709:9",value:r,onValueChange:o,children:[e.jsx(De,{"code-path":"src/components/deploy/CredentialManager.tsx:710:11",className:"w-[140px] bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] h-9 text-sm",children:e.jsx(Ae,{"code-path":"src/components/deploy/CredentialManager.tsx:711:13",placeholder:"全部类型"})}),e.jsxs(Pe,{"code-path":"src/components/deploy/CredentialManager.tsx:713:11",children:[e.jsx(_,{"code-path":"src/components/deploy/CredentialManager.tsx:714:13",value:"all",children:"全部类型"}),F.map(([s,g])=>e.jsx(_,{"code-path":"src/components/deploy/CredentialManager.tsx:716:15",value:s,children:e.jsxs("span",{"code-path":"src/components/deploy/CredentialManager.tsx:717:17",className:"flex items-center gap-2",children:[e.jsx(g.icon,{"code-path":"src/components/deploy/CredentialManager.tsx:717:59",className:"h-3.5 w-3.5"}),g.label]})},s))]})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:722:9",className:"relative flex-1 max-w-xs",children:[e.jsx(rt,{"code-path":"src/components/deploy/CredentialManager.tsx:723:11",className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-4 w-4 text-[var(--dg-text-muted)]"}),e.jsx(p,{"code-path":"src/components/deploy/CredentialManager.tsx:724:11",value:d,onChange:s=>i(s.target.value),placeholder:"搜索名称、描述...",className:"pl-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] h-9 text-sm"})]}),e.jsxs("span",{"code-path":"src/components/deploy/CredentialManager.tsx:728:9",className:"text-xs text-[var(--dg-text-muted)]",children:[M.length," 个凭据"]})]}),n?e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:732:9",className:"text-center py-16 text-[var(--dg-text-secondary)]",children:[e.jsx(ht,{"code-path":"src/components/deploy/CredentialManager.tsx:733:11",className:"w-6 h-6 animate-spin mx-auto mb-2 text-[var(--dg-blue)]"}),"加载中..."]}):M.length===0?e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:736:9",className:"text-center py-16 border border-dashed border-[var(--dg-border)] rounded-lg",children:[e.jsx(qe,{"code-path":"src/components/deploy/CredentialManager.tsx:737:11",className:"w-12 h-12 mx-auto mb-3 text-[var(--dg-text-muted)]"}),e.jsx("p",{"code-path":"src/components/deploy/CredentialManager.tsx:738:11",className:"text-[var(--dg-text-secondary)] mb-2",children:"暂无凭据"}),e.jsx("p",{"code-path":"src/components/deploy/CredentialManager.tsx:739:11",className:"text-xs text-[var(--dg-text-muted)] mb-4",children:"创建 SSH、Docker、AKSK 等类型的凭据,供流水线和服务器使用"}),e.jsxs(b,{"code-path":"src/components/deploy/CredentialManager.tsx:740:11",onClick:()=>{w(null),v(!0)},children:[e.jsx(Re,{"code-path":"src/components/deploy/CredentialManager.tsx:741:13",className:"w-4 h-4 mr-1"}),"创建第一个凭据"]})]}):e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:745:9",className:"rounded-md border border-[var(--dg-border)] overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/deploy/CredentialManager.tsx:746:11",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/deploy/CredentialManager.tsx:747:13",className:"bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]",children:e.jsxs("tr",{"code-path":"src/components/deploy/CredentialManager.tsx:748:15",children:[e.jsx("th",{"code-path":"src/components/deploy/CredentialManager.tsx:749:17",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]",children:"名称"}),e.jsx("th",{"code-path":"src/components/deploy/CredentialManager.tsx:750:17",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]",children:"类型"}),e.jsx("th",{"code-path":"src/components/deploy/CredentialManager.tsx:751:17",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] hidden md:table-cell",children:"摘要"}),e.jsx("th",{"code-path":"src/components/deploy/CredentialManager.tsx:752:17",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] hidden lg:table-cell",children:"标签"}),e.jsx("th",{"code-path":"src/components/deploy/CredentialManager.tsx:753:17",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] hidden xl:table-cell",children:"引用ID"}),e.jsx("th",{"code-path":"src/components/deploy/CredentialManager.tsx:754:17",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]",children:"状态"}),e.jsx("th",{"code-path":"src/components/deploy/CredentialManager.tsx:755:17",className:"px-3 py-2.5 text-right font-medium text-[var(--dg-text-secondary)]",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/deploy/CredentialManager.tsx:758:13",children:M.map(s=>{const g=s.secret_type,P=O[g],H=s.expires_at&&new Date(s.expires_at){K(s.id),C(!0)},children:[e.jsx("td",{"code-path":"src/components/deploy/CredentialManager.tsx:767:21",className:"px-3 py-2.5",children:e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:768:23",className:"flex items-center gap-2",children:[P?e.jsx(P.icon,{"code-path":"src/components/deploy/CredentialManager.tsx:769:32",className:`h-4 w-4 ${P.color} shrink-0`}):e.jsx(V,{"code-path":"src/components/deploy/CredentialManager.tsx:769:91",className:"h-4 w-4 text-[var(--dg-text-muted)] shrink-0"}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:770:25",children:[e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:771:27",className:"font-medium text-[var(--dg-text-primary)]",children:s.name}),s.variable_name&&e.jsx("div",{"code-path":"src/components/deploy/CredentialManager.tsx:773:29",className:"text-xs text-[var(--dg-text-muted)] font-mono",children:s.variable_name})]})]})}),e.jsx("td",{"code-path":"src/components/deploy/CredentialManager.tsx:778:21",className:"px-3 py-2.5",children:e.jsx(S,{"code-path":"src/components/deploy/CredentialManager.tsx:779:23",variant:"outline",className:`text-xs ${Xe[g]||""}`,children:P?.label||g})}),e.jsx("td",{"code-path":"src/components/deploy/CredentialManager.tsx:783:21",className:"px-3 py-2.5 text-[var(--dg-text-secondary)] text-xs hidden md:table-cell max-w-[180px] truncate font-mono",children:s.summary||"-"}),e.jsx("td",{"code-path":"src/components/deploy/CredentialManager.tsx:786:21",className:"px-3 py-2.5 hidden lg:table-cell",children:e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:787:23",className:"flex gap-1 flex-wrap",children:[(s.tags||[]).slice(0,3).map(N=>e.jsx(S,{"code-path":"src/components/deploy/CredentialManager.tsx:789:27",variant:"outline",className:"text-xs border-[var(--dg-border)] text-[var(--dg-text-muted)]",children:N},N)),(s.tags||[]).length>3&&e.jsxs("span",{"code-path":"src/components/deploy/CredentialManager.tsx:792:27",className:"text-xs text-[var(--dg-text-muted)]",children:["+",s.tags.length-3]})]})}),e.jsx("td",{"code-path":"src/components/deploy/CredentialManager.tsx:796:21",className:"px-3 py-2.5 hidden xl:table-cell",children:e.jsx("code",{"code-path":"src/components/deploy/CredentialManager.tsx:797:23",className:"text-xs text-[var(--dg-blue)] cursor-pointer font-mono",onClick:N=>{N.stopPropagation(),A(s.env_prefix)},children:s.env_prefix})}),e.jsx("td",{"code-path":"src/components/deploy/CredentialManager.tsx:802:21",className:"px-3 py-2.5",children:e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:803:23",className:"flex items-center gap-1",children:[s.is_active?e.jsx(S,{"code-path":"src/components/deploy/CredentialManager.tsx:805:27",className:"bg-green-500/20 text-green-400 text-xs border-0",children:"启用"}):e.jsx(S,{"code-path":"src/components/deploy/CredentialManager.tsx:807:27",className:"bg-red-500/20 text-red-400 text-xs border-0",children:"禁用"}),H&&e.jsxs(S,{"code-path":"src/components/deploy/CredentialManager.tsx:810:27",className:"bg-yellow-500/20 text-yellow-400 text-xs border-0",children:[e.jsx(pt,{"code-path":"src/components/deploy/CredentialManager.tsx:810:96",className:"h-2.5 w-2.5 mr-0.5"}),"过期"]})]})}),e.jsx("td",{"code-path":"src/components/deploy/CredentialManager.tsx:814:21",className:"px-3 py-2.5 text-right",onClick:N=>N.stopPropagation(),children:e.jsxs("div",{"code-path":"src/components/deploy/CredentialManager.tsx:815:23",className:"flex justify-end gap-1",children:[e.jsx(b,{"code-path":"src/components/deploy/CredentialManager.tsx:816:25",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{w(s),v(!0)},title:"编辑",children:e.jsx(vt,{"code-path":"src/components/deploy/CredentialManager.tsx:818:27",className:"w-3.5 h-3.5"})}),e.jsx(b,{"code-path":"src/components/deploy/CredentialManager.tsx:820:25",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>L(s),title:s.is_active?"禁用":"启用",children:s.is_active?e.jsx(Ze,{"code-path":"src/components/deploy/CredentialManager.tsx:823:45",className:"w-3.5 h-3.5 text-yellow-500"}):e.jsx(We,{"code-path":"src/components/deploy/CredentialManager.tsx:823:99",className:"w-3.5 h-3.5 text-green-500"})}),e.jsx(b,{"code-path":"src/components/deploy/CredentialManager.tsx:825:25",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-500",onClick:()=>D(s),title:"删除",children:e.jsx(Ct,{"code-path":"src/components/deploy/CredentialManager.tsx:827:27",className:"w-3.5 h-3.5"})})]})})]},s.id)})})]})}),e.jsx(bt,{"code-path":"src/components/deploy/CredentialManager.tsx:839:7",open:T,onClose:()=>v(!1),onSaved:m,editData:E}),e.jsx(ut,{"code-path":"src/components/deploy/CredentialManager.tsx:840:7",open:x,onClose:()=>C(!1),credId:c})]})}export{Lt as default}; diff --git a/backend/static/assets/CronJobManager-BMfKpm0z.js b/backend/static/assets/CronJobManager-BMfKpm0z.js new file mode 100644 index 0000000..992250c --- /dev/null +++ b/backend/static/assets/CronJobManager-BMfKpm0z.js @@ -0,0 +1,2 @@ +import{j as t,L,a3 as mt,r as n,D as K,b as U,c as W,d as Y,e as Z,I as $,f as xt,B as p,H as tt,a as pt,S as ht,x as gt,F as ut}from"./index-DfyorCky.js";import{C as w,a as S}from"./card-C55cvSHg.js";import{B as C}from"./badge-xNW8x0G1.js";import{C as B}from"./checkbox-CH0bpj6b.js";import{t as d}from"./index-a3ybMjbR.js";import{s as z,c as y,t as bt}from"./automation-mtL167W_.js";import{C as vt}from"./circle-x-DK79Dhg2.js";import{S as O,a as R,b as A,c as V,d as N}from"./select-D5qUzdAs.js";import{T as Q}from"./textarea-NXY8u32k.js";import{L as J}from"./label-BK0h2apY.js";import{T as yt,a as Ct,b as I,c as E,d as jt,e as f}from"./table-5sHV4Akp.js";import{H as ot}from"./history-D_9jPUQg.js";import{R as Nt}from"./refresh-cw-DUB_tAG-.js";import{P as Jt}from"./plus-CUG-9kpu.js";import{T as q}from"./trash-2-Dx32pOzT.js";import{P as ft}from"./package-open-CUXo2Tda.js";import{P as X}from"./play-cdPayOtJ.js";import{P as Dt}from"./pause-D_famo9P.js";import{S as Mt}from"./square-pen-BxUFAe0F.js";import"./index-CWVNW_qu.js";function et(i){switch(i){case"success":return t.jsxs(C,{"code-path":"src/components/automation/cronJobHelpers.tsx:9:9",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:[t.jsx(mt,{"code-path":"src/components/automation/cronJobHelpers.tsx:10:11",className:"h-3 w-3 mr-1"}),"成功"]});case"failed":return t.jsxs(C,{"code-path":"src/components/automation/cronJobHelpers.tsx:16:9",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10",children:[t.jsx(vt,{"code-path":"src/components/automation/cronJobHelpers.tsx:17:11",className:"h-3 w-3 mr-1"}),"失败"]});case"running":return t.jsxs(C,{"code-path":"src/components/automation/cronJobHelpers.tsx:23:9",variant:"outline",className:"border-blue-500/30 text-blue-400 bg-blue-500/10 animate-pulse",children:[t.jsx(L,{"code-path":"src/components/automation/cronJobHelpers.tsx:24:11",className:"h-3 w-3 mr-1 animate-spin"}),"执行中"]});default:return t.jsx(C,{"code-path":"src/components/automation/cronJobHelpers.tsx:30:9",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-muted)]",children:"从未执行"})}}function Ft(i){return{"0 2 * * *":"每天 02:00","0 3 * * 0":"每周日 03:00","*/5 * * * *":"每 5 分钟","0 * * * *":"每小时","0 9 * * 1":"每周一 09:00"}[i]||i}const G=[{value:"shell",label:"Shell 脚本",desc:"关联脚本库中的 Shell 脚本"},{value:"python",label:"Python 脚本",desc:"关联脚本库中的 Python 脚本"},{value:"command",label:"自定义命令",desc:"手动输入命令或脚本路径"}];function wt({open:i,onOpenChange:g,editJob:s,onSuccess:D}){const[a,l]=n.useState({name:"",description:"",cron_expr:"",type:"shell",content:"",script_id:null}),[h,v]=n.useState([]),[r,m]=n.useState(null),[H,M]=n.useState(!1);n.useEffect(()=>{i&&(z.getScripts({page_size:200}).then(e=>{v(e?.list||[])}).catch(()=>v([])),s?(l({name:s.name||"",description:s.description||"",cron_expr:s.cron_expr||"",type:s.type||"shell",content:s.content||"",script_id:s.script_id||null}),s.script_id?z.getScript(s.script_id).then(e=>{m(e)}).catch(()=>m(null)):m(null)):(l({name:"",description:"",cron_expr:"",type:"shell",content:"",script_id:null}),m(null)))},[i,s]);const F=a.type==="shell"||a.type==="python"?h.filter(e=>e.type===a.type):[],_=e=>{const x=h.find(j=>String(j.id)===e);x&&(m(x),l(j=>({...j,script_id:x.id,content:x.content})))},P=e=>{l(x=>({...x,type:e,script_id:null,content:e==="command"?x.content:""})),m(null)},k=async()=>{if(!a.name||!a.cron_expr){d.error("请填写任务名称和 Cron 表达式");return}if((a.type==="shell"||a.type==="python")&&!a.script_id){d.error("请选择关联的脚本");return}try{M(!0);const e={name:a.name,description:a.description,cron_expr:a.cron_expr,type:a.type,content:a.content,script_id:a.script_id};s?(await y.updateJob(s.id,e),d.success("任务更新成功")):(await y.createJob(e),d.success("任务创建成功")),g(!1),D()}catch(e){console.error("Failed to save cron job:",e),d.error(s?"更新失败":"创建失败")}finally{M(!1)}};return t.jsx(K,{"code-path":"src/components/automation/CronJobFormDialog.tsx:149:5",open:i,onOpenChange:g,children:t.jsxs(U,{"code-path":"src/components/automation/CronJobFormDialog.tsx:150:7",className:"max-w-2xl bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:[t.jsxs(W,{"code-path":"src/components/automation/CronJobFormDialog.tsx:151:9",children:[t.jsx(Y,{"code-path":"src/components/automation/CronJobFormDialog.tsx:152:11",children:s?"编辑定时任务":"新建定时任务"}),t.jsx(Z,{"code-path":"src/components/automation/CronJobFormDialog.tsx:153:11",className:"text-[var(--dg-text-secondary)]",children:"配置 Cron 定时任务"})]}),t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:155:9",className:"space-y-4 py-4 max-h-[60vh] overflow-y-auto pr-1",children:[t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:157:11",children:[t.jsx(J,{"code-path":"src/components/automation/CronJobFormDialog.tsx:158:13",className:"text-[var(--dg-text-primary)]",children:"任务名称"}),t.jsx($,{"code-path":"src/components/automation/CronJobFormDialog.tsx:159:13",value:a.name,onChange:e=>l({...a,name:e.target.value}),placeholder:"例如: 数据库备份",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] mt-1"})]}),t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:168:11",children:[t.jsx(J,{"code-path":"src/components/automation/CronJobFormDialog.tsx:169:13",className:"text-[var(--dg-text-primary)]",children:"描述"}),t.jsx(Q,{"code-path":"src/components/automation/CronJobFormDialog.tsx:170:13",value:a.description,onChange:e=>l({...a,description:e.target.value}),placeholder:"任务描述...",rows:2,className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] mt-1"})]}),t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:180:11",children:[t.jsx(J,{"code-path":"src/components/automation/CronJobFormDialog.tsx:181:13",className:"text-[var(--dg-text-primary)]",children:"Cron 表达式"}),t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:182:13",className:"flex gap-2",children:[t.jsx($,{"code-path":"src/components/automation/CronJobFormDialog.tsx:183:15",value:a.cron_expr,onChange:e=>l({...a,cron_expr:e.target.value}),placeholder:"0 2 * * *",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] mt-1"}),t.jsxs(O,{"code-path":"src/components/automation/CronJobFormDialog.tsx:189:15",onValueChange:e=>l({...a,cron_expr:e}),children:[t.jsx(R,{"code-path":"src/components/automation/CronJobFormDialog.tsx:190:17",className:"w-48 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] mt-1",children:t.jsx(A,{"code-path":"src/components/automation/CronJobFormDialog.tsx:191:19",placeholder:"快速选择"})}),t.jsxs(V,{"code-path":"src/components/automation/CronJobFormDialog.tsx:193:17",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:[t.jsx(N,{"code-path":"src/components/automation/CronJobFormDialog.tsx:194:19",value:"*/5 * * * *",className:"text-[var(--dg-text-primary)]",children:"每 5 分钟"}),t.jsx(N,{"code-path":"src/components/automation/CronJobFormDialog.tsx:195:19",value:"0 * * * *",className:"text-[var(--dg-text-primary)]",children:"每小时"}),t.jsx(N,{"code-path":"src/components/automation/CronJobFormDialog.tsx:196:19",value:"0 2 * * *",className:"text-[var(--dg-text-primary)]",children:"每天 02:00"}),t.jsx(N,{"code-path":"src/components/automation/CronJobFormDialog.tsx:197:19",value:"0 3 * * 0",className:"text-[var(--dg-text-primary)]",children:"每周日 03:00"}),t.jsx(N,{"code-path":"src/components/automation/CronJobFormDialog.tsx:198:19",value:"0 9 * * 1",className:"text-[var(--dg-text-primary)]",children:"每周一 09:00"})]})]})]}),t.jsx("p",{"code-path":"src/components/automation/CronJobFormDialog.tsx:202:13",className:"text-xs text-[var(--dg-text-muted)] mt-1",children:"格式: 分 时 日 月 周"})]}),t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:206:11",children:[t.jsx(J,{"code-path":"src/components/automation/CronJobFormDialog.tsx:207:13",className:"text-[var(--dg-text-primary)]",children:"执行类型"}),t.jsx("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:208:13",className:"grid grid-cols-3 gap-2 mt-1",children:G.map(e=>t.jsx("button",{"code-path":"src/components/automation/CronJobFormDialog.tsx:210:17",type:"button",onClick:()=>P(e.value),className:`px-3 py-2 rounded-md border text-sm transition-colors text-left ${a.type===e.value?"border-[var(--dg-blue)] bg-[var(--dg-blue)]/10 text-[var(--dg-blue)]":"border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-hover)]"}`,children:t.jsx("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:220:19",className:"font-medium",children:e.label})},e.value))}),t.jsx("p",{"code-path":"src/components/automation/CronJobFormDialog.tsx:224:13",className:"text-xs text-[var(--dg-text-muted)] mt-1",children:G.find(e=>e.value===a.type)?.desc})]}),a.type==="shell"||a.type==="python"?t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:231:13",className:"space-y-3",children:[t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:232:15",children:[t.jsxs(J,{"code-path":"src/components/automation/CronJobFormDialog.tsx:233:17",className:"text-[var(--dg-text-primary)]",children:["选择脚本 ",t.jsx("span",{"code-path":"src/components/automation/CronJobFormDialog.tsx:234:24",className:"text-red-400",children:"*"})]}),F.length===0?t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:237:19",className:"mt-1 px-3 py-4 rounded-md border border-dashed border-[var(--dg-border)] text-center",children:[t.jsxs("p",{"code-path":"src/components/automation/CronJobFormDialog.tsx:238:21",className:"text-sm text-[var(--dg-text-muted)]",children:["脚本库中没有 ",a.type==="shell"?"Shell":"Python"," 脚本"]}),t.jsxs("p",{"code-path":"src/components/automation/CronJobFormDialog.tsx:241:21",className:"text-xs text-[var(--dg-text-muted)] mt-1",children:["请先到「脚本库」创建 ",a.type==="shell"?"Shell":"Python"," 脚本"]})]}):t.jsxs(O,{"code-path":"src/components/automation/CronJobFormDialog.tsx:246:19",value:a.script_id?String(a.script_id):"",onValueChange:_,children:[t.jsx(R,{"code-path":"src/components/automation/CronJobFormDialog.tsx:250:21",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] mt-1",children:t.jsx(A,{"code-path":"src/components/automation/CronJobFormDialog.tsx:251:23",placeholder:"选择脚本库中的脚本..."})}),t.jsx(V,{"code-path":"src/components/automation/CronJobFormDialog.tsx:253:21",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:F.map(e=>t.jsxs(N,{"code-path":"src/components/automation/CronJobFormDialog.tsx:255:25",value:String(e.id),className:"text-[var(--dg-text-primary)]",children:[e.name,e.description?` — ${e.description}`:""]},e.id))})]})]}),r&&t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:266:17",children:[t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:267:19",className:"flex items-center gap-2 mb-1",children:[t.jsx(C,{"code-path":"src/components/automation/CronJobFormDialog.tsx:268:21",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-muted)]",children:r.type==="shell"?"Shell":"Python"}),t.jsxs("span",{"code-path":"src/components/automation/CronJobFormDialog.tsx:271:21",className:"text-xs text-[var(--dg-text-muted)]",children:[(r.content||"").split(` +`).length," 行"]})]}),t.jsx("pre",{"code-path":"src/components/automation/CronJobFormDialog.tsx:275:19",className:"max-h-48 overflow-auto rounded-md bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] p-3 text-xs font-mono text-[var(--dg-text-secondary)] whitespace-pre-wrap break-all",children:r.content||"(空脚本)"})]})]}):t.jsxs("div",{"code-path":"src/components/automation/CronJobFormDialog.tsx:282:13",children:[t.jsx(J,{"code-path":"src/components/automation/CronJobFormDialog.tsx:283:15",className:"text-[var(--dg-text-primary)]",children:"执行命令"}),t.jsx(Q,{"code-path":"src/components/automation/CronJobFormDialog.tsx:284:15",value:a.content,onChange:e=>l({...a,content:e.target.value}),placeholder:"/scripts/backup.sh arg1 arg2",rows:4,className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] mt-1 font-mono"})]})]}),t.jsxs(xt,{"code-path":"src/components/automation/CronJobFormDialog.tsx:294:9",children:[t.jsx(p,{"code-path":"src/components/automation/CronJobFormDialog.tsx:295:11",variant:"outline",onClick:()=>g(!1),className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",children:"取消"}),t.jsx(p,{"code-path":"src/components/automation/CronJobFormDialog.tsx:298:11",className:"bg-blue-600 hover:bg-blue-700",onClick:k,disabled:H,children:H?"保存中...":s?"保存修改":"创建任务"})]})]})})}function St({open:i,onOpenChange:g}){const[s,D]=n.useState([]),[a,l]=n.useState(!1),[h,v]=n.useState(null);return n.useEffect(()=>{if(!i)return;(async()=>{try{l(!0);const m=await bt.getExecutions({task_type:"cron",page_size:50});D(m.list||[])}catch(m){console.error("Failed to load executions:",m)}finally{l(!1)}})()},[i]),t.jsx(K,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:51:5",open:i,onOpenChange:g,children:t.jsxs(U,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:52:7",className:"max-w-4xl bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] max-h-[85vh] overflow-y-auto",children:[t.jsxs(W,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:53:9",children:[t.jsx(Y,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:54:11",children:"执行历史"}),t.jsx(Z,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:55:11",className:"text-[var(--dg-text-secondary)]",children:"定时任务执行记录与输出日志"})]}),t.jsx("div",{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:57:9",className:"mt-4",children:a?t.jsx("div",{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:59:13",className:"flex items-center justify-center py-8",children:t.jsx(L,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:60:15",className:"h-6 w-6 text-[var(--dg-text-secondary)] animate-spin"})}):s.length===0?t.jsxs("div",{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:63:13",className:"flex flex-col items-center justify-center py-12 text-[var(--dg-text-secondary)]",children:[t.jsx(ot,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:64:15",className:"h-10 w-10 mb-3 opacity-40"}),t.jsx("p",{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:65:15",className:"text-sm",children:"暂无执行记录"})]}):t.jsxs(yt,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:68:13",children:[t.jsx(Ct,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:69:15",children:t.jsxs(I,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:70:17",className:"border-[var(--dg-border)]",children:[t.jsx(E,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:71:19",className:"text-[var(--dg-text-secondary)]",children:"任务"}),t.jsx(E,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:72:19",className:"text-[var(--dg-text-secondary)]",children:"状态"}),t.jsx(E,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:73:19",className:"text-[var(--dg-text-secondary)]",children:"耗时"}),t.jsx(E,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:74:19",className:"text-[var(--dg-text-secondary)]",children:"执行时间"}),t.jsx(E,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:75:19",className:"text-[var(--dg-text-secondary)]",children:"输出"})]})}),t.jsx(jt,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:78:15",children:s.map(r=>t.jsxs(n.Fragment,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:80:19",children:[t.jsxs(I,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:81:21",className:"border-[var(--dg-border)] cursor-pointer hover:bg-[var(--dg-bg-hover)]/50",onClick:()=>v(h===r.id?null:r.id),children:[t.jsx(f,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:82:23",className:"text-[var(--dg-text-primary)]",children:r.task_name}),t.jsx(f,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:83:23",children:et(r.status)}),t.jsx(f,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:84:23",className:"text-[var(--dg-text-secondary)]",children:r.duration?`${r.duration}ms`:"--"}),t.jsx(f,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:85:23",className:"text-[var(--dg-text-secondary)]",children:r.started_at?new Date(r.started_at).toLocaleString():"--"}),t.jsx(f,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:88:23",className:"text-[var(--dg-text-secondary)]",children:r.output?t.jsxs("span",{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:90:27",className:"text-blue-400 text-xs flex items-center gap-1",children:[t.jsx(tt,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:91:29",className:"h-3 w-3"}),h===r.id?"收起":"查看"]}):"--"})]}),h===r.id&&r.output&&t.jsx(I,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:100:23",className:"border-[var(--dg-border)]",children:t.jsx(f,{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:101:25",colSpan:5,className:"bg-[var(--dg-bg-tertiary)] p-0",children:t.jsx("pre",{"code-path":"src/components/automation/ExecutionHistoryDialog.tsx:102:27",className:"p-4 text-xs text-[var(--dg-text-primary)] font-mono whitespace-pre-wrap max-h-64 overflow-y-auto",children:r.output})})},`${r.id}-out`)]},r.id))})]})})]})})}function Ut(){const[i,g]=n.useState(""),[s,D]=n.useState([]),[a,l]=n.useState(!0),[h,v]=n.useState(!1),[r,m]=n.useState(!1),[H,M]=n.useState(!1),[F,_]=n.useState(null),[P,k]=n.useState(null),[e,x]=n.useState([]),j=pt(),at=()=>{k(null),m(!0)},st=o=>{k(o),m(!0)},u=n.useCallback(async()=>{v(!0);try{const o=await y.getJobs();D(o.list||[])}catch(o){console.error("Failed to load cron jobs:",o),d.error("加载失败")}finally{v(!1),l(!1)}},[]);n.useEffect(()=>{u()},[u]);const b=s.filter(o=>(o.name||"").toLowerCase().includes(i.toLowerCase())||(o.description||"").toLowerCase().includes(i.toLowerCase())),rt=async o=>{try{await y.toggleJob(o),d.success("状态已切换"),u()}catch(c){console.error("Failed to toggle job:",c),d.error("操作失败")}},nt=async o=>{_(o);try{const c=await y.executeJob(o);(c?.status||"success")==="success"?d.success("执行成功",{description:`耗时 ${c?.duration||0}ms`}):d.error("执行失败",{description:(c?.output||"").slice(0,100)}),u()}catch(c){console.error("Failed to execute job:",c),d.error("执行失败")}finally{_(null)}},ct=async o=>{if(await j({title:"删除定时任务",description:`确定删除「${o.name}」吗?此操作不可恢复。`,variant:"destructive"}))try{await y.deleteJob(o.id),d.success("任务已删除"),u()}catch(T){console.error("Failed to delete job:",T),d.error("删除失败")}},it=o=>{x(c=>c.includes(o)?c.filter(T=>T!==o):[...c,o])},dt=()=>{e.length===b.length&&b.length>0?x([]):x(b.map(o=>o.id))},lt=async()=>{if(!(e.length===0||!await j({title:"批量删除定时任务",description:`确定删除选中的 ${e.length} 个任务吗?此操作不可恢复。`,confirmText:"批量删除",variant:"destructive"})))try{await y.batchDelete(e),d.success(`已删除 ${e.length} 个任务`),x([]),u()}catch(c){console.error("Failed to batch delete jobs:",c),d.error("批量删除失败")}};return t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:164:5",className:"space-y-6",children:[t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:166:7",className:"flex items-center justify-between",children:[t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:167:9",children:[t.jsx("h1",{"code-path":"src/components/automation/CronJobManager.tsx:168:11",className:"text-2xl font-bold text-[var(--dg-text-primary)]",children:"定时任务"}),t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:169:11",className:"text-sm text-[var(--dg-text-secondary)] mt-1",children:"Cron 任务管理与执行"})]}),t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:171:9",className:"flex items-center gap-2",children:[t.jsxs(p,{"code-path":"src/components/automation/CronJobManager.tsx:172:11",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",onClick:()=>M(!0),children:[t.jsx(ot,{"code-path":"src/components/automation/CronJobManager.tsx:177:13",className:"h-4 w-4 mr-2"}),"执行历史"]}),t.jsxs(p,{"code-path":"src/components/automation/CronJobManager.tsx:180:11",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",onClick:()=>u(),disabled:h,children:[t.jsx(Nt,{"code-path":"src/components/automation/CronJobManager.tsx:186:13",className:`h-4 w-4 mr-2 ${h?"animate-spin":""}`}),"刷新"]}),t.jsxs(p,{"code-path":"src/components/automation/CronJobManager.tsx:189:11",className:"bg-blue-600 hover:bg-blue-700",onClick:at,children:[t.jsx(Jt,{"code-path":"src/components/automation/CronJobManager.tsx:190:13",className:"h-4 w-4 mr-2"}),"新建任务"]})]})]}),t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:197:7",className:"grid grid-cols-4 gap-4",children:[t.jsx(w,{"code-path":"src/components/automation/CronJobManager.tsx:198:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/components/automation/CronJobManager.tsx:199:11",className:"p-4",children:[t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:200:13",className:"text-[var(--dg-text-secondary)] text-sm",children:"任务总数"}),t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:201:13",className:"text-2xl font-bold text-[var(--dg-text-primary)]",children:s.length})]})}),t.jsx(w,{"code-path":"src/components/automation/CronJobManager.tsx:204:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/components/automation/CronJobManager.tsx:205:11",className:"p-4",children:[t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:206:13",className:"text-[var(--dg-text-secondary)] text-sm",children:"已启用"}),t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:207:13",className:"text-2xl font-bold text-emerald-400",children:s.filter(o=>o.enabled).length})]})}),t.jsx(w,{"code-path":"src/components/automation/CronJobManager.tsx:212:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/components/automation/CronJobManager.tsx:213:11",className:"p-4",children:[t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:214:13",className:"text-[var(--dg-text-secondary)] text-sm",children:"累计成功"}),t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:215:13",className:"text-2xl font-bold text-emerald-400",children:s.reduce((o,c)=>o+(c.success_count||0),0)})]})}),t.jsx(w,{"code-path":"src/components/automation/CronJobManager.tsx:220:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/components/automation/CronJobManager.tsx:221:11",className:"p-4",children:[t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:222:13",className:"text-[var(--dg-text-secondary)] text-sm",children:"累计失败"}),t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:223:13",className:"text-2xl font-bold text-red-400",children:s.reduce((o,c)=>o+(c.fail_count||0),0)})]})})]}),t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:231:7",className:"flex items-center justify-between flex-wrap gap-4",children:[t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:232:9",className:"flex items-center gap-3 flex-wrap",children:[t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:233:11",className:"relative flex-1 max-w-md",children:[t.jsx(ht,{"code-path":"src/components/automation/CronJobManager.tsx:234:13",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[var(--dg-text-secondary)]"}),t.jsx($,{"code-path":"src/components/automation/CronJobManager.tsx:235:13",placeholder:"搜索任务...",value:i,onChange:o=>g(o.target.value),className:"pl-10 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),b.length>0&&t.jsxs("label",{"code-path":"src/components/automation/CronJobManager.tsx:243:13",className:"flex items-center gap-2 text-sm text-[var(--dg-text-secondary)] cursor-pointer select-none",children:[t.jsx(B,{"code-path":"src/components/automation/CronJobManager.tsx:244:15",checked:e.length===b.length&&b.length>0,onCheckedChange:dt,className:"border-[var(--dg-border)]"}),"全选"]})]}),e.length>0&&t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:256:11",className:"flex items-center gap-2",children:[t.jsxs("span",{"code-path":"src/components/automation/CronJobManager.tsx:257:13",className:"text-sm text-[var(--dg-text-secondary)]",children:["已选择 ",e.length," 项"]}),t.jsxs(p,{"code-path":"src/components/automation/CronJobManager.tsx:258:13",variant:"outline",size:"sm",className:"border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:lt,children:[t.jsx(q,{"code-path":"src/components/automation/CronJobManager.tsx:264:15",className:"h-4 w-4 mr-2"}),"批量删除"]})]})]}),a?t.jsx("div",{"code-path":"src/components/automation/CronJobManager.tsx:272:9",className:"flex items-center justify-center py-12",children:t.jsx(L,{"code-path":"src/components/automation/CronJobManager.tsx:273:11",className:"h-6 w-6 text-[var(--dg-text-secondary)] animate-spin"})}):b.length===0?t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:276:9",className:"flex flex-col items-center justify-center py-16 text-[var(--dg-text-secondary)]",children:[t.jsx(ft,{"code-path":"src/components/automation/CronJobManager.tsx:277:11",className:"h-12 w-12 mb-3 opacity-40"}),t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:278:11",className:"text-sm",children:"暂无定时任务"})]}):null,t.jsx("div",{"code-path":"src/components/automation/CronJobManager.tsx:283:7",className:"space-y-3",children:b.map(o=>t.jsx(w,{"code-path":"src/components/automation/CronJobManager.tsx:285:11",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsx(S,{"code-path":"src/components/automation/CronJobManager.tsx:286:13",className:"p-4",children:t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:287:15",className:"flex items-start justify-between gap-3",children:[t.jsx("div",{"code-path":"src/components/automation/CronJobManager.tsx:288:17",className:"flex items-center pt-1",children:t.jsx(B,{"code-path":"src/components/automation/CronJobManager.tsx:289:19",checked:e.includes(o.id),onCheckedChange:()=>it(o.id),className:"border-[var(--dg-border)]"})}),t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:295:17",className:"flex-1 min-w-0",children:[t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:296:19",className:"flex items-center gap-3 flex-wrap",children:[t.jsx("h3",{"code-path":"src/components/automation/CronJobManager.tsx:297:21",className:"font-medium text-[var(--dg-text-primary)]",children:o.name}),t.jsx(C,{"code-path":"src/components/automation/CronJobManager.tsx:298:21",variant:"outline",className:o.enabled?"border-emerald-500/30 text-emerald-400 bg-emerald-500/10":"border-[var(--dg-border)] text-[var(--dg-text-muted)]",children:o.enabled?"已启用":"已禁用"}),et(o.last_status),t.jsx(C,{"code-path":"src/components/automation/CronJobManager.tsx:309:21",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",children:o.type==="shell"?"Shell":o.type==="python"?"Python":"命令"})]}),t.jsx("p",{"code-path":"src/components/automation/CronJobManager.tsx:313:19",className:"text-sm text-[var(--dg-text-secondary)] mt-1",children:o.description||"—"}),t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:314:19",className:"flex items-center gap-4 mt-2 text-sm",children:[t.jsxs("span",{"code-path":"src/components/automation/CronJobManager.tsx:315:21",className:"flex items-center gap-1 text-[var(--dg-text-secondary)]",children:[t.jsx(gt,{"code-path":"src/components/automation/CronJobManager.tsx:316:23",className:"h-3 w-3"}),Ft(o.cron_expr)]}),(o.type==="shell"||o.type==="python")&&o.script?.name?t.jsxs("span",{"code-path":"src/components/automation/CronJobManager.tsx:320:23",className:"flex items-center gap-1 text-[var(--dg-text-secondary)]",children:[t.jsx(ut,{"code-path":"src/components/automation/CronJobManager.tsx:321:25",className:"h-3 w-3"}),t.jsx("span",{"code-path":"src/components/automation/CronJobManager.tsx:322:25",className:"text-xs",children:o.script.name})]}):o.content&&t.jsxs("span",{"code-path":"src/components/automation/CronJobManager.tsx:325:23",className:"flex items-center gap-1 text-[var(--dg-text-secondary)]",children:[t.jsx(tt,{"code-path":"src/components/automation/CronJobManager.tsx:326:25",className:"h-3 w-3"}),t.jsx("code",{"code-path":"src/components/automation/CronJobManager.tsx:327:25",className:"text-xs bg-[var(--dg-bg-tertiary)] px-2 py-0.5 rounded truncate max-w-xs",children:o.content})]})]}),t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:333:19",className:"flex items-center gap-4 mt-2 text-xs text-[var(--dg-text-muted)]",children:[t.jsxs("span",{"code-path":"src/components/automation/CronJobManager.tsx:334:21",children:["上次执行: ",o.last_run_at?new Date(o.last_run_at).toLocaleString():"--"]}),t.jsxs("span",{"code-path":"src/components/automation/CronJobManager.tsx:335:21",children:["成功: ",o.success_count||0," / 失败: ",o.fail_count||0]}),t.jsxs("span",{"code-path":"src/components/automation/CronJobManager.tsx:336:21",children:["累计: ",o.run_count||0," 次"]})]})]}),t.jsxs("div",{"code-path":"src/components/automation/CronJobManager.tsx:340:17",className:"flex items-center gap-2 shrink-0",children:[t.jsxs(p,{"code-path":"src/components/automation/CronJobManager.tsx:341:19",variant:"outline",size:"sm",className:"border-emerald-600 text-emerald-400 hover:bg-emerald-600/20",disabled:F===o.id,onClick:()=>nt(o.id),children:[F===o.id?t.jsx(L,{"code-path":"src/components/automation/CronJobManager.tsx:349:23",className:"h-4 w-4 mr-1 animate-spin"}):t.jsx(X,{"code-path":"src/components/automation/CronJobManager.tsx:351:23",className:"h-4 w-4 mr-1"}),"立即执行"]}),t.jsx(p,{"code-path":"src/components/automation/CronJobManager.tsx:355:19",variant:"ghost",size:"icon",className:"h-8 w-8 text-[var(--dg-text-secondary)] hover:text-blue-400",title:o.enabled?"禁用":"启用",onClick:()=>rt(o.id),children:o.enabled?t.jsx(Dt,{"code-path":"src/components/automation/CronJobManager.tsx:362:36",className:"h-4 w-4"}):t.jsx(X,{"code-path":"src/components/automation/CronJobManager.tsx:362:68",className:"h-4 w-4"})}),t.jsx(p,{"code-path":"src/components/automation/CronJobManager.tsx:364:19",variant:"ghost",size:"icon",className:"h-8 w-8 text-[var(--dg-text-secondary)] hover:text-blue-400",title:"编辑",onClick:()=>st(o),children:t.jsx(Mt,{"code-path":"src/components/automation/CronJobManager.tsx:371:21",className:"h-4 w-4"})}),t.jsx(p,{"code-path":"src/components/automation/CronJobManager.tsx:373:19",variant:"ghost",size:"icon",className:"h-8 w-8 text-[var(--dg-text-secondary)] hover:text-red-400",title:"删除",onClick:()=>ct(o),children:t.jsx(q,{"code-path":"src/components/automation/CronJobManager.tsx:380:21",className:"h-4 w-4"})})]})]})})},o.id))}),t.jsx(wt,{"code-path":"src/components/automation/CronJobManager.tsx:390:7",open:r,onOpenChange:m,editJob:P,onSuccess:u}),t.jsx(St,{"code-path":"src/components/automation/CronJobManager.tsx:398:7",open:H,onOpenChange:M})]})}export{Ut as CronJobManager}; diff --git a/backend/static/assets/Dashboard-iCzLAtNG.js b/backend/static/assets/Dashboard-iCzLAtNG.js new file mode 100644 index 0000000..e3a1f4e --- /dev/null +++ b/backend/static/assets/Dashboard-iCzLAtNG.js @@ -0,0 +1,4 @@ +import{g as kt,j as t,X as m,ab as U,_ as x,aU as rt,r as A,o as ot,A as wt,G as Rt,k as le,B as se,a2 as nt,T as ct,t as Be,a7 as Ke,q as Ae,s as Se,x as At,J as St}from"./index-DfyorCky.js";import{d as pe}from"./dashboard-BjQPIG2G.js";import{s as Ot}from"./server-CjDPBaTN.js";import{k as _t}from"./kubernetes-J8O09fK7.js";import{C as I,a as F,b as z,c as V,d as q}from"./card-C55cvSHg.js";import{T as Pt}from"./trending-up-CdusV6gc.js";import{T as Et}from"./trending-down-BGTWG_dA.js";import{M as Tt}from"./minus-UVrx3jLc.js";import{B as $}from"./badge-xNW8x0G1.js";import{H as Lt}from"./hard-drive-BbPmnARR.js";import{b as C,r as dt,s as $t,t as it,v as It,n as Z,w as Ie,x as B,L,y as lt,z as Fe,E as ht,D as Ft,c as Mt,e as ae,o as Y,S as Bt,A as Kt,F as Ut,d as Ue,j as zt,i as Q,l as Vt,u as qt,G as Ht,H as ue,I as Wt,a as pt,J as Gt,K as me,M as ze,g as Zt,N as Xt,R as Oe,C as mt,X as xt,Y as ut,T as _e,B as Jt}from"./generateCategoricalChart-6v9BPbG2.js";import{A as Yt,a as ke}from"./AreaChart-B2zlWfdX.js";import{B as Qt}from"./BarChart-DlFprovY.js";import{M as ea}from"./memory-stick-QMV-0CnU.js";import{A as he}from"./arrow-right-DyIltvNZ.js";import{C as ta}from"./circle-DOZr6_68.js";const aa=[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]],sa=kt("dollar-sign",aa),Ve={blue:{bg:"bg-[var(--dg-blue)]/10",icon:"text-[var(--dg-blue)]",glow:"shadow-[var(--dg-blue)]/10"},emerald:{bg:"bg-[var(--dg-green)]/10",icon:"text-[var(--dg-green)]",glow:"shadow-[var(--dg-green)]/10"},amber:{bg:"bg-[var(--dg-yellow)]/10",icon:"text-[var(--dg-yellow)]",glow:"shadow-[var(--dg-yellow)]/10"},rose:{bg:"bg-[var(--dg-red)]/10",icon:"text-[var(--dg-red)]",glow:"shadow-[var(--dg-red)]/10"},purple:{bg:"bg-[var(--dg-purple)]/10",icon:"text-[var(--dg-purple)]",glow:"shadow-[var(--dg-purple)]/10"},cyan:{bg:"bg-[var(--dg-cyan)]/10",icon:"text-[var(--dg-cyan)]",glow:"shadow-[var(--dg-cyan)]/10"},orange:{bg:"bg-[var(--dg-orange)]/10",icon:"text-[var(--dg-orange)]",glow:"shadow-[var(--dg-orange)]/10"}};function xe({title:a,value:s,description:r,icon:e,trend:o,trendValue:n,color:c,onClick:d,loading:l=!1}){const i=Ve[c]||Ve.blue;if(l)return t.jsx(I,{"code-path":"src/components/dashboard/DashboardStats.tsx:53:7",className:"dg-card overflow-hidden",children:t.jsxs(F,{"code-path":"src/components/dashboard/DashboardStats.tsx:54:9",className:"p-6 space-y-4",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardStats.tsx:55:11",className:"flex items-start justify-between",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardStats.tsx:56:13",className:"space-y-3 flex-1",children:[t.jsx("div",{"code-path":"src/components/dashboard/DashboardStats.tsx:57:15",className:"dg-skeleton h-4 w-24 rounded"}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardStats.tsx:58:15",className:"dg-skeleton h-8 w-16 rounded"})]}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardStats.tsx:60:13",className:"dg-skeleton h-10 w-10 rounded-lg"})]}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardStats.tsx:62:11",className:"dg-skeleton h-3 w-32 rounded"})]})});const p=o==="up"?Pt:o==="down"?Et:Tt,u=o==="up"?"text-[var(--dg-green)]":o==="down"?"text-[var(--dg-red)]":"text-[var(--dg-text-muted)]";return t.jsx(I,{"code-path":"src/components/dashboard/DashboardStats.tsx:76:5",className:m("dg-card dg-card-hover cursor-pointer overflow-hidden",d&&"cursor-pointer"),onClick:d,children:t.jsx(F,{"code-path":"src/components/dashboard/DashboardStats.tsx:83:7",className:"p-6",children:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardStats.tsx:84:9",className:"flex items-start justify-between gap-4",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardStats.tsx:85:11",className:"space-y-3 min-w-0 flex-1",children:[t.jsx("p",{"code-path":"src/components/dashboard/DashboardStats.tsx:86:13",className:"text-sm font-medium text-[var(--dg-text-secondary)] truncate",children:a}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardStats.tsx:89:13",className:"flex items-baseline gap-2 flex-wrap",children:[t.jsx("h3",{"code-path":"src/components/dashboard/DashboardStats.tsx:90:15",className:"text-2xl font-bold text-[var(--dg-text-primary)] tracking-tight",children:s}),o&&n&&t.jsxs("span",{"code-path":"src/components/dashboard/DashboardStats.tsx:94:17",className:m("flex items-center text-xs font-semibold gap-0.5",u),children:[t.jsx(p,{"code-path":"src/components/dashboard/DashboardStats.tsx:95:19",className:"h-3.5 w-3.5"}),n]})]}),r&&t.jsx("p",{"code-path":"src/components/dashboard/DashboardStats.tsx:101:15",className:"text-xs text-[var(--dg-text-muted)]",children:r})]}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardStats.tsx:104:11",className:m("p-3 rounded-xl flex-shrink-0",i.bg,i.icon),children:t.jsx(e,{"code-path":"src/components/dashboard/DashboardStats.tsx:111:13",className:"h-5 w-5"})})]})})})}var ra=["points","className","baseLinePoints","connectNulls"];function ee(){return ee=Object.assign?Object.assign.bind():function(a){for(var s=1;s=0)&&Object.prototype.propertyIsEnumerable.call(a,e)&&(r[e]=a[e])}return r}function na(a,s){if(a==null)return{};var r={};for(var e in a)if(Object.prototype.hasOwnProperty.call(a,e)){if(s.indexOf(e)>=0)continue;r[e]=a[e]}return r}function qe(a){return la(a)||ia(a)||da(a)||ca()}function ca(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function da(a,s){if(a){if(typeof a=="string")return Pe(a,s);var r=Object.prototype.toString.call(a).slice(8,-1);if(r==="Object"&&a.constructor&&(r=a.constructor.name),r==="Map"||r==="Set")return Array.from(a);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Pe(a,s)}}function ia(a){if(typeof Symbol<"u"&&a[Symbol.iterator]!=null||a["@@iterator"]!=null)return Array.from(a)}function la(a){if(Array.isArray(a))return Pe(a)}function Pe(a,s){(s==null||s>a.length)&&(s=a.length);for(var r=0,e=new Array(s);r0&&arguments[0]!==void 0?arguments[0]:[],r=[[]];return s.forEach(function(e){He(e)?r[r.length-1].push(e):r[r.length-1].length>0&&r.push([])}),He(s[0])&&r[r.length-1].push(s[0]),r[r.length-1].length<=0&&(r=r.slice(0,-1)),r},de=function(s,r){var e=ha(s);r&&(e=[e.reduce(function(n,c){return[].concat(qe(n),qe(c))},[])]);var o=e.map(function(n){return n.reduce(function(c,d,l){return"".concat(c).concat(l===0?"M":"L").concat(d.x,",").concat(d.y)},"")}).join("");return e.length===1?"".concat(o,"Z"):o},pa=function(s,r,e){var o=de(s,e);return"".concat(o.slice(-1)==="Z"?o.slice(0,-1):o,"L").concat(de(r.reverse(),e).slice(1))},ma=function(s){var r=s.points,e=s.className,o=s.baseLinePoints,n=s.connectNulls,c=oa(s,ra);if(!r||!r.length)return null;var d=U("recharts-polygon",e);if(o&&o.length){var l=c.stroke&&c.stroke!=="none",i=pa(r,o,n);return x.createElement("g",{className:d},x.createElement("path",ee({},C(c,!0),{fill:i.slice(-1)==="Z"?c.fill:"none",stroke:"none",d:i})),l?x.createElement("path",ee({},C(c,!0),{fill:"none",d:de(r,n)})):null,l?x.createElement("path",ee({},C(c,!0),{fill:"none",d:de(o,n)})):null)}var p=de(r,n);return x.createElement("path",ee({},C(c,!0),{fill:p.slice(-1)==="Z"?c.fill:"none",className:d,d:p}))},we,We;function xa(){if(We)return we;We=1;var a=dt(),s=$t(),r=it();function e(o,n){return o&&o.length?a(o,r(n,2),s):void 0}return we=e,we}var ua=xa();const ba=rt(ua);var Re,Ge;function fa(){if(Ge)return Re;Ge=1;var a=dt(),s=it(),r=It();function e(o,n){return o&&o.length?a(o,s(n,2),r):void 0}return Re=e,Re}var ga=fa();const va=rt(ga);var ya=["cx","cy","angle","ticks","axisLine"],ja=["ticks","tick","angle","tickFormatter","stroke"];function re(a){"@babel/helpers - typeof";return re=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},re(a)}function ie(){return ie=Object.assign?Object.assign.bind():function(a){for(var s=1;s=0)&&Object.prototype.propertyIsEnumerable.call(a,e)&&(r[e]=a[e])}return r}function Da(a,s){if(a==null)return{};var r={};for(var e in a)if(Object.prototype.hasOwnProperty.call(a,e)){if(s.indexOf(e)>=0)continue;r[e]=a[e]}return r}function Na(a,s){if(!(a instanceof s))throw new TypeError("Cannot call a class as a function")}function Je(a,s){for(var r=0;ret?c=o==="outer"?"start":"end":n<-et?c=o==="outer"?"end":"start":c="middle",c}},{key:"renderAxisLine",value:function(){var e=this.props,o=e.cx,n=e.cy,c=e.radius,d=e.axisLine,l=e.axisLineType,i=G(G({},C(this.props,!1)),{},{fill:"none"},C(d,!1));if(l==="circle")return x.createElement(Ft,X({className:"recharts-polar-angle-axis-line"},i,{cx:o,cy:n,r:c}));var p=this.props.ticks,u=p.map(function(b){return B(o,n,c,b.coordinate)});return x.createElement(ma,X({className:"recharts-polar-angle-axis-line"},i,{points:u}))}},{key:"renderTicks",value:function(){var e=this,o=this.props,n=o.ticks,c=o.tick,d=o.tickLine,l=o.tickFormatter,i=o.stroke,p=C(this.props,!1),u=C(c,!1),b=G(G({},p),{},{fill:"none"},C(d,!1)),D=n.map(function(f,h){var v=e.getTickLineCoord(f),y=e.getTickTextAnchor(f),j=G(G(G({textAnchor:y},p),{},{stroke:"none",fill:i},u),{},{index:h,payload:f,x:v.x2,y:v.y2});return x.createElement(L,X({className:U("recharts-polar-angle-axis-tick",lt(c)),key:"tick-".concat(f.coordinate)},Fe(e.props,f,h)),d&&x.createElement("line",X({className:"recharts-polar-angle-axis-tick-line"},b,v)),c&&s.renderTickItem(c,j,l?l(f.value,h):f.value))});return x.createElement(L,{className:"recharts-polar-angle-axis-ticks"},D)}},{key:"render",value:function(){var e=this.props,o=e.ticks,n=e.radius,c=e.axisLine;return n<=0||!o||!o.length?null:x.createElement(L,{className:U("recharts-polar-angle-axis",this.props.className)},c&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(e,o,n){var c;return x.isValidElement(e)?c=x.cloneElement(e,o):Z(e)?c=e(o):c=x.createElement(Ie,X({},o,{className:"recharts-polar-angle-axis-tick-value"}),n),c}}])})(A.PureComponent);Ne(Ce,"displayName","PolarAngleAxis");Ne(Ce,"axisType","angleAxis");Ne(Ce,"defaultProps",{type:"category",angleAxisId:0,scale:"auto",cx:0,cy:0,orientation:"outer",axisLine:!0,tickLine:!0,tickSize:8,tick:!0,hide:!1,allowDuplicatedCategory:!0});var be;function ne(a){"@babel/helpers - typeof";return ne=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(s){return typeof s}:function(s){return s&&typeof Symbol=="function"&&s.constructor===Symbol&&s!==Symbol.prototype?"symbol":typeof s},ne(a)}function te(){return te=Object.assign?Object.assign.bind():function(a){for(var s=1;s0?Ut(k,"paddingAngle",0):0;if(S){var M=Ue(S.endAngle-S.startAngle,k.endAngle-k.startAngle),N=g(g({},k),{},{startAngle:j+_,endAngle:j+M(h)+_});v.push(N),j=N.endAngle}else{var O=k.endAngle,P=k.startAngle,J=Ue(0,O-P),H=J(h),T=g(g({},k),{},{startAngle:j+_,endAngle:j+H+_});v.push(T),j=T.endAngle}}),x.createElement(L,null,e.renderSectorsStatically(v))})}},{key:"attachKeyboardHandlers",value:function(e){var o=this;e.onkeydown=function(n){if(!n.altKey)switch(n.key){case"ArrowLeft":{var c=++o.state.sectorToFocus%o.sectorRefs.length;o.sectorRefs[c].focus(),o.setState({sectorToFocus:c});break}case"ArrowRight":{var d=--o.state.sectorToFocus<0?o.sectorRefs.length-1:o.state.sectorToFocus%o.sectorRefs.length;o.sectorRefs[d].focus(),o.setState({sectorToFocus:d});break}case"Escape":{o.sectorRefs[o.state.sectorToFocus].blur(),o.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var e=this.props,o=e.sectors,n=e.isAnimationActive,c=this.state.prevSectors;return n&&o&&o.length&&(!c||!zt(c,o))?this.renderSectorsWithAnimation():this.renderSectorsStatically(o)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var e=this,o=this.props,n=o.hide,c=o.sectors,d=o.className,l=o.label,i=o.cx,p=o.cy,u=o.innerRadius,b=o.outerRadius,D=o.isAnimationActive,f=this.state.isAnimationFinished;if(n||!c||!c.length||!Q(i)||!Q(p)||!Q(u)||!Q(b))return null;var h=U("recharts-pie",d);return x.createElement(L,{tabIndex:this.props.rootTabIndex,className:h,ref:function(y){e.pieRef=y}},this.renderSectors(),l&&this.renderLabels(c),ht.renderCallByParent(this.props,null,!1),(!D||f)&&Vt.renderCallByParent(this.props,c,!1))}}],[{key:"getDerivedStateFromProps",value:function(e,o){return o.prevIsAnimationActive!==e.isAnimationActive?{prevIsAnimationActive:e.isAnimationActive,prevAnimationId:e.animationId,curSectors:e.sectors,prevSectors:[],isAnimationFinished:!0}:e.isAnimationActive&&e.animationId!==o.prevAnimationId?{prevAnimationId:e.animationId,curSectors:e.sectors,prevSectors:o.curSectors,isAnimationFinished:!0}:e.sectors!==o.curSectors?{curSectors:e.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(e,o){return e>o?"start":e=360?j:j-1)*l,w=v-j*D-k,S=o.reduce(function(N,O){var P=Y(O,y,0);return N+(Q(P)?P:0)},0),_;if(S>0){var M;_=o.map(function(N,O){var P=Y(N,y,0),J=Y(N,p,O),H=(Q(P)?P:0)/S,T;O?T=M.endAngle+ue(h)*l*(P!==0?1:0):T=c;var ce=T+ue(h)*((P!==0?D:0)+H*w),R=(T+ce)/2,Me=(f.innerRadius+f.outerRadius)/2,Nt=[{name:J,value:P,payload:N,dataKey:y,type:b}],Ct=B(f.cx,f.cy,Me,R);return M=g(g(g({percent:H,cornerRadius:n,name:J,tooltipPayload:Nt,midAngle:R,middleRadius:Me,tooltipPosition:Ct},N),f),{},{value:Y(N,y),startAngle:T,endAngle:ce,payload:N,paddingAngle:ue(h)*l}),M})}return g(g({},f),{},{sectors:_,data:o})});var qa=Zt({chartName:"PieChart",GraphicalChild:K,validateTooltipEventTypes:["item"],defaultTooltipEventType:"item",legendContent:"children",axisComponents:[{axisType:"angleAxis",AxisComp:Ce},{axisType:"radiusAxis",AxisComp:De}],formatAxisMap:Xt,defaultProps:{layout:"centric",startAngle:0,endAngle:360,cx:"50%",cy:"50%",innerRadius:0,outerRadius:"80%"}});const Ha={阿里云:"#ff6a00",aliyun:"#ff6a00",AWS:"#ff9900",aws:"#ff9900",腾讯云:"#006eff",tencent:"#006eff",华为云:"#ff0000",huawei:"#ff0000",Azure:"#0078d4",azure:"#0078d4"},st=["#ff6a00","#ff9900","#006eff","#ff0000","#0078d4","#10b981","#a855f7","#ec4899"];function Dt(a){if(!a||a.length<2)return{pct:0,label:"暂无数据",direction:"neutral"};const s=Number(a[a.length-1].cost??0),r=Number(a[a.length-2].cost??0);if(r===0)return{pct:0,label:s>0?"新增费用":"持平",direction:"neutral"};const e=(s-r)/r*100,o=e>.05?"up":e<-.05?"down":"neutral",n=`${e>0?"+":""}${e.toFixed(1)}% 较上月`;return{pct:e,label:n,direction:o}}function Wa(a,s,r,e=24){const o=[];for(let n=e-1;n>=0;n--){const c=new Date(Date.now()-n*60*60*1e3);o.push({time:`${c.getHours().toString().padStart(2,"0")}:00`,cpu:Number(Math.max(0,Math.min(100,a+(Math.random()-.5)*15)).toFixed(1)),memory:Number(Math.max(0,Math.min(100,s+(Math.random()-.5)*10)).toFixed(1)),disk:Number(Math.max(0,Math.min(100,r+(Math.random()-.5)*5)).toFixed(1))})}return o}function Ga(a,s){if(!a||a.length===0)return[];const r={};for(const e of a){const o=e.timestamp;if(!o)continue;const c=`${new Date(o).getHours().toString().padStart(2,"0")}:00`;r[c]||(r[c]={}),e.name==="cpu"&&(r[c].cpu=Number(e.value)||0),e.name==="memory"&&(r[c].memory=Number(e.value)||0)}return Object.entries(r).sort((e,o)=>e[0].localeCompare(o[0])).map(([e,o])=>({time:e,cpu:Number((o.cpu??0).toFixed(1)),memory:Number((o.memory??0).toFixed(1)),disk:Number(s.toFixed(1))}))}function $e({active:a,payload:s,label:r}){return!a||!s?null:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:94:5",className:"chart-tooltip px-3 py-2",children:[t.jsx("p",{"code-path":"src/components/dashboard/DashboardCharts.tsx:95:7",className:"text-xs font-medium mb-1.5",style:{color:"var(--dg-text-secondary)"},children:r}),s.map((e,o)=>t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:97:9",className:"flex items-center gap-2 text-xs",children:[t.jsx("span",{"code-path":"src/components/dashboard/DashboardCharts.tsx:98:11",className:"w-2 h-2 rounded-full",style:{backgroundColor:e.color}}),t.jsxs("span",{"code-path":"src/components/dashboard/DashboardCharts.tsx:99:11",style:{color:"var(--dg-text-muted)"},children:[e.name,":"]}),t.jsx("span",{"code-path":"src/components/dashboard/DashboardCharts.tsx:100:11",className:"font-medium",style:{color:"var(--dg-text-primary)"},children:typeof e.value=="number"?`${e.value}%`:e.value})]},o))]})}function Za({costStats:a}){const s=a?.cloud_costs??[],r=a?.month_trend??[],e=s.map((d,l)=>({name:d.cloud,value:d.cost,color:Ha[d.cloud]||st[l%st.length]})),o=r.map(d=>({month:d.month,cost:d.cost})),n=a?.total_cost??e.reduce((d,l)=>d+l.value,0),c=Dt(r);return t.jsxs(I,{"code-path":"src/components/dashboard/DashboardCharts.tsx:123:5",className:"dg-card dg-card-hover",children:[t.jsx(z,{"code-path":"src/components/dashboard/DashboardCharts.tsx:124:7",className:"pb-2",children:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:125:9",className:"flex items-center justify-between",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:126:11",children:[t.jsx(V,{"code-path":"src/components/dashboard/DashboardCharts.tsx:127:13",className:"text-[var(--dg-text-primary)]",children:"云成本概览"}),t.jsx(q,{"code-path":"src/components/dashboard/DashboardCharts.tsx:128:13",className:"text-[var(--dg-text-muted)]",children:"本月各云平台费用支出"})]}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:130:11",className:"text-right",children:[t.jsxs("p",{"code-path":"src/components/dashboard/DashboardCharts.tsx:131:13",className:"text-2xl font-bold text-[var(--dg-text-primary)] tracking-tight",children:["¥",Number(n).toLocaleString()]}),t.jsx("p",{"code-path":"src/components/dashboard/DashboardCharts.tsx:134:13",className:m("text-xs font-medium mt-0.5",c.direction==="up"?"text-[var(--dg-green)]":c.direction==="down"?"text-[var(--dg-red)]":"text-[var(--dg-text-muted)]"),children:c.label})]})]})}),t.jsxs(F,{"code-path":"src/components/dashboard/DashboardCharts.tsx:145:7",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:146:9",className:"grid grid-cols-2 gap-4",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:147:11",children:[t.jsx("p",{"code-path":"src/components/dashboard/DashboardCharts.tsx:148:13",className:"text-sm text-[var(--dg-text-secondary)] mb-2",children:"费用分布"}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:149:13",className:"h-[180px]",children:t.jsx(Oe,{"code-path":"src/components/dashboard/DashboardCharts.tsx:150:15",width:"100%",height:"100%",children:t.jsxs(qa,{"code-path":"src/components/dashboard/DashboardCharts.tsx:151:17",children:[t.jsx(K,{"code-path":"src/components/dashboard/DashboardCharts.tsx:152:19",data:e,cx:"50%",cy:"50%",innerRadius:40,outerRadius:70,paddingAngle:2,dataKey:"value",stroke:"none",children:e.map((d,l)=>t.jsx(pt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:163:23",fill:d.color},`cell-${l}`))}),t.jsx(_e,{"code-path":"src/components/dashboard/DashboardCharts.tsx:166:19",content:t.jsx($e,{"code-path":"src/components/dashboard/DashboardCharts.tsx:166:37"})})]})})})]}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:171:11",children:[t.jsx("p",{"code-path":"src/components/dashboard/DashboardCharts.tsx:172:13",className:"text-sm text-[var(--dg-text-secondary)] mb-2",children:"月度趋势"}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:173:13",className:"h-[180px]",children:t.jsx(Oe,{"code-path":"src/components/dashboard/DashboardCharts.tsx:174:15",width:"100%",height:"100%",children:t.jsxs(Qt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:175:17",data:o,margin:{top:5,right:5,left:0,bottom:5},children:[t.jsx(mt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:176:19",strokeDasharray:"3 3",className:"chart-grid-stroke",stroke:"var(--chart-grid)"}),t.jsx(xt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:177:19",dataKey:"month",stroke:"var(--chart-axis)",fontSize:10,tickLine:!1,axisLine:!1}),t.jsx(ut,{"code-path":"src/components/dashboard/DashboardCharts.tsx:178:19",stroke:"var(--chart-axis)",fontSize:10,tickLine:!1,axisLine:!1}),t.jsx(_e,{"code-path":"src/components/dashboard/DashboardCharts.tsx:179:19",content:t.jsx($e,{"code-path":"src/components/dashboard/DashboardCharts.tsx:179:37"})}),t.jsx(Jt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:180:19",dataKey:"cost",fill:"var(--dg-blue)",radius:[4,4,0,0]})]})})})]})]}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:186:9",className:"mt-4 space-y-2",children:e.map(d=>t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:188:13",className:"flex items-center justify-between",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:189:15",className:"flex items-center gap-2",children:[t.jsx("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:190:17",className:"w-3 h-3 rounded-full",style:{backgroundColor:d.color}}),t.jsx("span",{"code-path":"src/components/dashboard/DashboardCharts.tsx:191:17",className:"text-sm text-[var(--dg-text-secondary)]",children:d.name})]}),t.jsxs("span",{"code-path":"src/components/dashboard/DashboardCharts.tsx:193:15",className:"text-sm font-semibold text-[var(--dg-text-primary)]",children:["¥",Number(d.value).toLocaleString()]})]},d.name))})]})]})}function Xa({topUsage:a}){const s=(a?.cpu??[]).slice(0,5),r=(a?.memory??[]).slice(0,5),e=(a?.disk??[]).slice(0,5),o=(n,c,d,l,i)=>t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:215:5",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:216:7",className:"flex items-center gap-2 mb-3",children:[l,t.jsx("span",{"code-path":"src/components/dashboard/DashboardCharts.tsx:218:9",className:"text-sm font-semibold text-[var(--dg-text-secondary)]",children:i})]}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:220:7",className:"space-y-2.5",children:n.map((p,u)=>{const b=Number(p.usage??0);return t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:224:13",className:"flex items-center gap-2.5",children:[t.jsx("span",{"code-path":"src/components/dashboard/DashboardCharts.tsx:225:15",className:"text-xs font-mono text-[var(--dg-text-muted)] w-5 text-center",children:u+1}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:228:15",className:"flex-1 min-w-0",children:[t.jsx("p",{"code-path":"src/components/dashboard/DashboardCharts.tsx:229:17",className:"text-xs text-[var(--dg-text-secondary)] truncate font-medium",children:p.hostname}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:230:17",className:"flex items-center gap-2 mt-1",children:[t.jsx("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:231:19",className:"flex-1 h-1.5 bg-[var(--dg-bg-tertiary)] rounded-full overflow-hidden",children:t.jsx("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:232:21",className:m("h-full rounded-full transition-all duration-500",b>80?"bg-[var(--dg-red)]":b>60?"bg-[var(--dg-yellow)]":d),style:{width:`${Math.min(b,100)}%`}})}),t.jsxs("span",{"code-path":"src/components/dashboard/DashboardCharts.tsx:240:19",className:m("text-xs font-mono font-medium w-12 text-right",b>80?"text-[var(--dg-red)]":b>60?"text-[var(--dg-yellow)]":"text-[var(--dg-text-muted)]"),children:[b.toFixed(1),"%"]})]})]})]},p.id??u)})})]});return t.jsxs(I,{"code-path":"src/components/dashboard/DashboardCharts.tsx:256:5",className:"dg-card dg-card-hover",children:[t.jsx(z,{"code-path":"src/components/dashboard/DashboardCharts.tsx:257:7",className:"pb-2",children:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:258:9",children:[t.jsx(V,{"code-path":"src/components/dashboard/DashboardCharts.tsx:259:11",className:"text-[var(--dg-text-primary)]",children:"Top5 资源使用"}),t.jsx(q,{"code-path":"src/components/dashboard/DashboardCharts.tsx:260:11",className:"text-[var(--dg-text-muted)]",children:"CPU、内存、磁盘使用率最高"})]})}),t.jsx(F,{"code-path":"src/components/dashboard/DashboardCharts.tsx:263:7",children:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:264:9",className:"grid grid-cols-3 gap-4",children:[o(s,"blue","bg-[var(--dg-blue)]",t.jsx(ot,{"code-path":"src/components/dashboard/DashboardCharts.tsx:265:69",className:"h-4 w-4 text-[var(--dg-blue)]"}),"CPU"),o(r,"emerald","bg-[var(--dg-green)]",t.jsx(ea,{"code-path":"src/components/dashboard/DashboardCharts.tsx:266:76",className:"h-4 w-4 text-[var(--dg-green)]"}),"内存"),o(e,"purple","bg-[var(--dg-purple)]",t.jsx(Rt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:267:74",className:"h-4 w-4 text-[var(--dg-purple)]"}),"磁盘")]})})]})}function Ja({avgCpu:a,avgMemory:s,avgDisk:r,metrics:e}){const o=Ga(e??[],r),n=o.length>0?o:Wa(a,s,r,24);return t.jsxs(I,{"code-path":"src/components/dashboard/DashboardCharts.tsx:289:5",className:"dg-card",children:[t.jsx(z,{"code-path":"src/components/dashboard/DashboardCharts.tsx:290:7",className:"pb-2",children:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:291:9",className:"flex items-center justify-between flex-wrap gap-3",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:292:11",children:[t.jsx(V,{"code-path":"src/components/dashboard/DashboardCharts.tsx:293:13",className:"text-[var(--dg-text-primary)]",children:"资源使用率趋势"}),t.jsx(q,{"code-path":"src/components/dashboard/DashboardCharts.tsx:294:13",className:"text-[var(--dg-text-muted)]",children:"过去24小时系统资源使用情况"})]}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:296:11",className:"flex items-center gap-2",children:[t.jsxs($,{"code-path":"src/components/dashboard/DashboardCharts.tsx:297:13",variant:"outline",className:"dg-badge-blue border",children:[t.jsx(ot,{"code-path":"src/components/dashboard/DashboardCharts.tsx:298:15",className:"h-3 w-3 mr-1"}),"CPU"]}),t.jsxs($,{"code-path":"src/components/dashboard/DashboardCharts.tsx:301:13",variant:"outline",className:"dg-badge-green border",children:[t.jsx(wt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:302:15",className:"h-3 w-3 mr-1"}),"内存"]}),t.jsxs($,{"code-path":"src/components/dashboard/DashboardCharts.tsx:305:13",variant:"outline",className:"dg-badge-purple border",children:[t.jsx(Lt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:306:15",className:"h-3 w-3 mr-1"}),"磁盘"]})]})]})}),t.jsx(F,{"code-path":"src/components/dashboard/DashboardCharts.tsx:312:7",children:t.jsx("div",{"code-path":"src/components/dashboard/DashboardCharts.tsx:313:9",className:"h-[280px]",children:t.jsx(Oe,{"code-path":"src/components/dashboard/DashboardCharts.tsx:314:11",width:"100%",height:"100%",children:t.jsxs(Yt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:315:13",data:n,margin:{top:10,right:10,left:0,bottom:0},children:[t.jsxs("defs",{"code-path":"src/components/dashboard/DashboardCharts.tsx:316:15",children:[t.jsxs("linearGradient",{"code-path":"src/components/dashboard/DashboardCharts.tsx:317:17",id:"colorCpu",x1:"0",y1:"0",x2:"0",y2:"1",children:[t.jsx("stop",{"code-path":"src/components/dashboard/DashboardCharts.tsx:318:19",offset:"5%",stopColor:"var(--dg-blue)",stopOpacity:.3}),t.jsx("stop",{"code-path":"src/components/dashboard/DashboardCharts.tsx:319:19",offset:"95%",stopColor:"var(--dg-blue)",stopOpacity:0})]}),t.jsxs("linearGradient",{"code-path":"src/components/dashboard/DashboardCharts.tsx:321:17",id:"colorMemory",x1:"0",y1:"0",x2:"0",y2:"1",children:[t.jsx("stop",{"code-path":"src/components/dashboard/DashboardCharts.tsx:322:19",offset:"5%",stopColor:"var(--dg-green)",stopOpacity:.3}),t.jsx("stop",{"code-path":"src/components/dashboard/DashboardCharts.tsx:323:19",offset:"95%",stopColor:"var(--dg-green)",stopOpacity:0})]}),t.jsxs("linearGradient",{"code-path":"src/components/dashboard/DashboardCharts.tsx:325:17",id:"colorDisk",x1:"0",y1:"0",x2:"0",y2:"1",children:[t.jsx("stop",{"code-path":"src/components/dashboard/DashboardCharts.tsx:326:19",offset:"5%",stopColor:"var(--dg-purple)",stopOpacity:.3}),t.jsx("stop",{"code-path":"src/components/dashboard/DashboardCharts.tsx:327:19",offset:"95%",stopColor:"var(--dg-purple)",stopOpacity:0})]})]}),t.jsx(mt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:330:15",strokeDasharray:"3 3",stroke:"var(--chart-grid)"}),t.jsx(xt,{"code-path":"src/components/dashboard/DashboardCharts.tsx:331:15",dataKey:"time",stroke:"var(--chart-axis)",fontSize:12,tickLine:!1,axisLine:!1}),t.jsx(ut,{"code-path":"src/components/dashboard/DashboardCharts.tsx:332:15",stroke:"var(--chart-axis)",fontSize:12,tickLine:!1,axisLine:!1,unit:"%"}),t.jsx(_e,{"code-path":"src/components/dashboard/DashboardCharts.tsx:333:15",content:t.jsx($e,{"code-path":"src/components/dashboard/DashboardCharts.tsx:333:33"})}),t.jsx(ke,{"code-path":"src/components/dashboard/DashboardCharts.tsx:334:15",type:"monotone",dataKey:"cpu",stroke:"var(--dg-blue)",fillOpacity:1,fill:"url(#colorCpu)",strokeWidth:2,name:"CPU"}),t.jsx(ke,{"code-path":"src/components/dashboard/DashboardCharts.tsx:335:15",type:"monotone",dataKey:"memory",stroke:"var(--dg-green)",fillOpacity:1,fill:"url(#colorMemory)",strokeWidth:2,name:"内存"}),t.jsx(ke,{"code-path":"src/components/dashboard/DashboardCharts.tsx:336:15",type:"monotone",dataKey:"disk",stroke:"var(--dg-purple)",fillOpacity:1,fill:"url(#colorDisk)",strokeWidth:2,name:"磁盘"})]})})})})]})}function Ya({severity:a}){return t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:31:5",className:m("w-2 h-2 rounded-full flex-shrink-0 mt-1.5",a==="critical"&&"bg-[var(--dg-red)]",a==="warning"&&"bg-[var(--dg-yellow)]",a==="info"&&"bg-[var(--dg-blue)]")})}function Qa({severity:a}){return t.jsx($,{"code-path":"src/components/dashboard/DashboardRecent.tsx:45:5",variant:"outline",className:m("text-xs font-medium",a==="critical"&&"dg-badge-red border",a==="warning"&&"dg-badge-yellow border",a==="info"&&"dg-badge-blue border"),children:a==="critical"?"严重":a==="warning"?"警告":"提示"})}function es({alerts:a}){const s=le(),r=a.filter(e=>e.status==="firing").slice(0,8);return t.jsxs(I,{"code-path":"src/components/dashboard/DashboardRecent.tsx:64:5",className:"dg-card dg-card-hover",children:[t.jsx(z,{"code-path":"src/components/dashboard/DashboardRecent.tsx:65:7",className:"pb-2",children:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:66:9",className:"flex items-center justify-between",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:67:11",children:[t.jsx(V,{"code-path":"src/components/dashboard/DashboardRecent.tsx:68:13",className:"text-[var(--dg-text-primary)]",children:"告警消息"}),t.jsx(q,{"code-path":"src/components/dashboard/DashboardRecent.tsx:69:13",className:"text-[var(--dg-text-muted)]",children:"最近触发的告警事件"})]}),t.jsxs(se,{"code-path":"src/components/dashboard/DashboardRecent.tsx:71:11",variant:"ghost",size:"sm",className:"dg-btn-ghost text-xs",onClick:()=>s("/alerts"),children:["查看全部",t.jsx(he,{"code-path":"src/components/dashboard/DashboardRecent.tsx:78:13",className:"h-3.5 w-3.5 ml-1"})]})]})}),t.jsx(F,{"code-path":"src/components/dashboard/DashboardRecent.tsx:82:7",children:t.jsx(nt,{"code-path":"src/components/dashboard/DashboardRecent.tsx:83:9",className:"h-[320px] scrollbar-thin",children:r.length===0?t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:85:13",className:"flex flex-col items-center justify-center py-12 text-[var(--dg-text-muted)]",children:[t.jsx(ct,{"code-path":"src/components/dashboard/DashboardRecent.tsx:86:15",className:"h-10 w-10 mb-3 opacity-30"}),t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:87:15",className:"text-sm",children:"暂无告警事件"}),t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:88:15",className:"text-xs mt-1 opacity-60",children:"所有系统运行正常"})]}):t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:91:13",className:"space-y-1.5 pr-2",children:r.map(e=>t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:93:17",className:"flex items-start gap-3 p-3 rounded-lg bg-[var(--dg-bg-tertiary)]/50 hover:bg-[var(--dg-bg-hover)] transition-all duration-200 cursor-pointer group",onClick:()=>s("/alert-center"),children:[t.jsx(Ya,{"code-path":"src/components/dashboard/DashboardRecent.tsx:98:19",severity:e.severity||"info"}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:99:19",className:"flex-1 min-w-0",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:100:21",className:"flex items-center gap-2 flex-wrap",children:[t.jsx("span",{"code-path":"src/components/dashboard/DashboardRecent.tsx:101:23",className:"text-sm font-medium text-[var(--dg-text-primary)] truncate",children:e.rule_name}),t.jsx(Qa,{"code-path":"src/components/dashboard/DashboardRecent.tsx:104:23",severity:e.severity||"info"})]}),t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:106:21",className:"text-xs text-[var(--dg-text-muted)] mt-1",children:e.target}),t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:107:21",className:"text-xs text-[var(--dg-text-muted)]/70 line-clamp-1",children:e.message})]}),t.jsx("span",{"code-path":"src/components/dashboard/DashboardRecent.tsx:109:19",className:"text-[11px] text-[var(--dg-text-muted)]/50 whitespace-nowrap flex-shrink-0",children:e.created_at?new Date(e.created_at).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}):""})]},e.id))})})})]})}function ts({expCerts:a}){const s=(a??[]).map(o=>({...o,daysUntilExpiry:o.days_until_expiry??Math.ceil((new Date(o.expire_date).getTime()-Date.now())/864e5)})).sort((o,n)=>o.daysUntilExpiry-n.daysUntilExpiry),r=s.filter(o=>o.daysUntilExpiry<30).length,e=s.filter(o=>o.daysUntilExpiry>=30&&o.daysUntilExpiry<60).length;return t.jsxs(I,{"code-path":"src/components/dashboard/DashboardRecent.tsx:134:5",className:"dg-card dg-card-hover",children:[t.jsx(z,{"code-path":"src/components/dashboard/DashboardRecent.tsx:135:7",className:"pb-2",children:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:136:9",className:"flex items-center justify-between flex-wrap gap-2",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:137:11",children:[t.jsx(V,{"code-path":"src/components/dashboard/DashboardRecent.tsx:138:13",className:"text-[var(--dg-text-primary)]",children:"证书到期提醒"}),t.jsx(q,{"code-path":"src/components/dashboard/DashboardRecent.tsx:139:13",className:"text-[var(--dg-text-muted)]",children:"SSL证书到期时间监控"})]}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:141:11",className:"flex items-center gap-2",children:[r>0&&t.jsxs($,{"code-path":"src/components/dashboard/DashboardRecent.tsx:143:15",className:"dg-badge-red border",children:[t.jsx(ct,{"code-path":"src/components/dashboard/DashboardRecent.tsx:144:17",className:"h-3 w-3 mr-1"}),r," 即将过期"]}),e>0&&t.jsxs($,{"code-path":"src/components/dashboard/DashboardRecent.tsx:149:15",className:"dg-badge-yellow border",children:[e," 30天内过期"]})]})]})}),t.jsx(F,{"code-path":"src/components/dashboard/DashboardRecent.tsx:156:7",children:t.jsx(nt,{"code-path":"src/components/dashboard/DashboardRecent.tsx:157:9",className:"h-[280px] scrollbar-thin",children:s.length===0?t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:159:13",className:"flex flex-col items-center justify-center py-10 text-[var(--dg-text-muted)]",children:[t.jsx(Be,{"code-path":"src/components/dashboard/DashboardRecent.tsx:160:15",className:"h-10 w-10 mb-3 opacity-30"}),t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:161:15",className:"text-sm",children:"暂无证书数据"})]}):t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:164:13",className:"space-y-1.5 pr-2",children:s.map(o=>t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:166:17",className:"flex items-center justify-between p-3 rounded-lg bg-[var(--dg-bg-tertiary)]/50 hover:bg-[var(--dg-bg-hover)] transition-all duration-200",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:170:19",className:"flex items-center gap-3 min-w-0",children:[t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:171:21",className:m("w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0",o.daysUntilExpiry<30?"bg-[var(--dg-red)]/10":o.daysUntilExpiry<60?"bg-[var(--dg-yellow)]/10":"bg-[var(--dg-green)]/10"),children:t.jsx(Be,{"code-path":"src/components/dashboard/DashboardRecent.tsx:179:23",className:m("h-4 w-4",o.daysUntilExpiry<30?"text-[var(--dg-red)]":o.daysUntilExpiry<60?"text-[var(--dg-yellow)]":"text-[var(--dg-green)]")})}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:186:21",className:"min-w-0",children:[t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:187:23",className:"text-sm font-medium text-[var(--dg-text-primary)] truncate",children:o.name}),t.jsxs("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:188:23",className:"text-xs text-[var(--dg-text-muted)]",children:["到期: ",o.expire_date?.substring(0,10)]})]})]}),t.jsx($,{"code-path":"src/components/dashboard/DashboardRecent.tsx:191:19",variant:"outline",className:m("text-xs flex-shrink-0",o.daysUntilExpiry<30?"dg-badge-red border":o.daysUntilExpiry<60?"dg-badge-yellow border":"dg-badge-green border"),children:o.daysUntilExpiry<0?"已过期":`${o.daysUntilExpiry} 天`})]},o.id))})})})]})}function as({releases:a}){const s=le(),r=a?.slice(0,5)??[];return t.jsxs(I,{"code-path":"src/components/dashboard/DashboardRecent.tsx:217:5",className:"dg-card dg-card-hover",children:[t.jsx(z,{"code-path":"src/components/dashboard/DashboardRecent.tsx:218:7",className:"pb-2",children:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:219:9",className:"flex items-center justify-between",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:220:11",children:[t.jsx(V,{"code-path":"src/components/dashboard/DashboardRecent.tsx:221:13",className:"text-[var(--dg-text-primary)]",children:"发布历史"}),t.jsx(q,{"code-path":"src/components/dashboard/DashboardRecent.tsx:222:13",className:"text-[var(--dg-text-muted)]",children:"今日应用发布记录"})]}),t.jsxs(se,{"code-path":"src/components/dashboard/DashboardRecent.tsx:224:11",variant:"ghost",size:"sm",className:"dg-btn-ghost text-xs",onClick:()=>s("/pipelines"),children:["查看全部",t.jsx(he,{"code-path":"src/components/dashboard/DashboardRecent.tsx:231:13",className:"h-3.5 w-3.5 ml-1"})]})]})}),t.jsx(F,{"code-path":"src/components/dashboard/DashboardRecent.tsx:235:7",children:r.length===0?t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:237:11",className:"flex flex-col items-center justify-center py-10 text-[var(--dg-text-muted)]",children:[t.jsx(Ke,{"code-path":"src/components/dashboard/DashboardRecent.tsx:238:13",className:"h-10 w-10 mb-3 opacity-30"}),t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:239:13",className:"text-sm",children:"暂无发布记录"})]}):t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:242:11",className:"space-y-2",children:r.map(e=>t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:244:15",className:"flex items-center gap-3 p-3 rounded-lg bg-[var(--dg-bg-tertiary)]/50 hover:bg-[var(--dg-bg-hover)] transition-all duration-200",children:[t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:248:17",className:m("w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0",e.status==="success"?"bg-[var(--dg-green)]/10":e.status==="failed"?"bg-[var(--dg-red)]/10":e.status==="deploying"?"bg-[var(--dg-blue)]/10":"bg-[var(--dg-yellow)]/10"),children:t.jsx(Ke,{"code-path":"src/components/dashboard/DashboardRecent.tsx:257:19",className:m("h-4 w-4",e.status==="success"?"text-[var(--dg-green)]":e.status==="failed"?"text-[var(--dg-red)]":e.status==="deploying"?"text-[var(--dg-blue)]":"text-[var(--dg-yellow)]")})}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:265:17",className:"flex-1 min-w-0",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:266:19",className:"flex items-center gap-2",children:[t.jsx("span",{"code-path":"src/components/dashboard/DashboardRecent.tsx:267:21",className:"text-sm font-medium text-[var(--dg-text-primary)] truncate",children:e.app_name}),t.jsx($,{"code-path":"src/components/dashboard/DashboardRecent.tsx:268:21",variant:"outline",className:"text-xs border-[var(--dg-border)] text-[var(--dg-text-muted)] flex-shrink-0",children:e.version})]}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:272:19",className:"flex items-center gap-2 mt-0.5",children:[t.jsx("span",{"code-path":"src/components/dashboard/DashboardRecent.tsx:273:21",className:"text-xs text-[var(--dg-text-muted)]",children:e.environment}),t.jsx("span",{"code-path":"src/components/dashboard/DashboardRecent.tsx:274:21",className:"text-xs text-[var(--dg-border)]",children:"·"}),t.jsx("span",{"code-path":"src/components/dashboard/DashboardRecent.tsx:275:21",className:"text-xs text-[var(--dg-text-muted)] truncate",children:e.commit_id})]})]}),t.jsx($,{"code-path":"src/components/dashboard/DashboardRecent.tsx:278:17",variant:"outline",className:m("text-xs flex-shrink-0",e.status==="success"?"dg-badge-green border":e.status==="failed"?"dg-badge-red border":e.status==="deploying"?"dg-badge-blue border":"dg-badge-yellow border"),children:e.status==="success"?"成功":e.status==="failed"?"失败":e.status==="deploying"?"发布中":e.status==="rolled_back"?"已回滚":"构建中"})]},e.id))})})]})}function ss({servers:a}){const s=le(),r=a.filter(n=>n.status==="running").length,e=a.filter(n=>n.status==="stopped").length,o=a.filter(n=>n.status==="maintenance").length;return t.jsxs(I,{"code-path":"src/components/dashboard/DashboardRecent.tsx:309:5",className:"dg-card dg-card-hover",children:[t.jsx(z,{"code-path":"src/components/dashboard/DashboardRecent.tsx:310:7",className:"pb-2",children:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:311:9",className:"flex items-center justify-between",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:312:11",children:[t.jsx(V,{"code-path":"src/components/dashboard/DashboardRecent.tsx:313:13",className:"text-[var(--dg-text-primary)]",children:"服务器状态"}),t.jsx(q,{"code-path":"src/components/dashboard/DashboardRecent.tsx:314:13",className:"text-[var(--dg-text-muted)]",children:"服务器运行状态分布"})]}),t.jsxs(se,{"code-path":"src/components/dashboard/DashboardRecent.tsx:316:11",variant:"ghost",size:"sm",className:"dg-btn-ghost text-xs",onClick:()=>s("/servers"),children:["查看全部",t.jsx(he,{"code-path":"src/components/dashboard/DashboardRecent.tsx:323:13",className:"h-3.5 w-3.5 ml-1"})]})]})}),t.jsxs(F,{"code-path":"src/components/dashboard/DashboardRecent.tsx:327:7",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:329:9",className:"grid grid-cols-3 gap-3 mb-4",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:330:11",className:"text-center p-3 rounded-xl bg-[var(--dg-green)]/8 border border-[var(--dg-green)]/15",children:[t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:331:13",className:"text-2xl font-bold text-[var(--dg-green)]",children:r}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:332:13",className:"text-xs text-[var(--dg-text-muted)] mt-1",children:"运行中"})]}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:334:11",className:"text-center p-3 rounded-xl bg-[var(--dg-yellow)]/8 border border-[var(--dg-yellow)]/15",children:[t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:335:13",className:"text-2xl font-bold text-[var(--dg-yellow)]",children:o}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:336:13",className:"text-xs text-[var(--dg-text-muted)] mt-1",children:"维护中"})]}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:338:11",className:"text-center p-3 rounded-xl bg-[var(--dg-text-muted)]/8 border border-[var(--dg-border)]",children:[t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:339:13",className:"text-2xl font-bold text-[var(--dg-text-muted)]",children:e}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:340:13",className:"text-xs text-[var(--dg-text-muted)] mt-1",children:"已停止"})]})]}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:345:9",className:"space-y-1.5",children:[a.slice(0,4).map(n=>t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:347:13",className:"flex items-center gap-3 p-2.5 rounded-lg bg-[var(--dg-bg-tertiary)]/50 hover:bg-[var(--dg-bg-hover)] transition-all duration-200",children:[t.jsx(ta,{"code-path":"src/components/dashboard/DashboardRecent.tsx:351:15",className:m("h-2.5 w-2.5 flex-shrink-0 fill-current",n.status==="running"?"text-[var(--dg-green)]":n.status==="maintenance"?"text-[var(--dg-yellow)]":"text-[var(--dg-text-muted)]")}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:359:15",className:"flex-1 min-w-0",children:[t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:360:17",className:"text-sm text-[var(--dg-text-primary)] truncate",children:n.hostname}),t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:361:17",className:"text-xs text-[var(--dg-text-muted)]",children:n.ip})]}),t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:363:15",className:"text-right flex-shrink-0",children:[t.jsxs("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:364:17",className:"text-xs text-[var(--dg-text-muted)]",children:["CPU ",t.jsxs("span",{"code-path":"src/components/dashboard/DashboardRecent.tsx:365:23",className:"text-[var(--dg-text-secondary)] font-medium",children:[Number(n.cpu_usage??0).toFixed(1),"%"]})]}),t.jsxs("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:367:17",className:"text-xs text-[var(--dg-text-muted)]",children:["内存 ",t.jsxs("span",{"code-path":"src/components/dashboard/DashboardRecent.tsx:368:22",className:"text-[var(--dg-text-secondary)] font-medium",children:[Number(n.memory_usage??0).toFixed(1),"%"]})]})]})]},n.id)),a.length===0&&t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:374:13",className:"flex flex-col items-center justify-center py-6 text-[var(--dg-text-muted)]",children:[t.jsx(Ae,{"code-path":"src/components/dashboard/DashboardRecent.tsx:375:15",className:"h-8 w-8 mb-2 opacity-30"}),t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:376:15",className:"text-sm",children:"暂无服务器"})]})]})]})]})}function rs({clusters:a}){const s=le();return t.jsxs(I,{"code-path":"src/components/dashboard/DashboardRecent.tsx:389:5",className:"dg-card dg-card-hover",children:[t.jsx(z,{"code-path":"src/components/dashboard/DashboardRecent.tsx:390:7",className:"pb-2",children:t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:391:9",className:"flex items-center justify-between",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:392:11",children:[t.jsx(V,{"code-path":"src/components/dashboard/DashboardRecent.tsx:393:13",className:"text-[var(--dg-text-primary)]",children:"Kubernetes 集群"}),t.jsx(q,{"code-path":"src/components/dashboard/DashboardRecent.tsx:394:13",className:"text-[var(--dg-text-muted)]",children:"Kubernetes集群健康状态"})]}),t.jsxs(se,{"code-path":"src/components/dashboard/DashboardRecent.tsx:396:11",variant:"ghost",size:"sm",className:"dg-btn-ghost text-xs",onClick:()=>s("/kubernetes"),children:["查看全部",t.jsx(he,{"code-path":"src/components/dashboard/DashboardRecent.tsx:403:13",className:"h-3.5 w-3.5 ml-1"})]})]})}),t.jsx(F,{"code-path":"src/components/dashboard/DashboardRecent.tsx:407:7",children:a.length===0?t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:409:11",className:"flex flex-col items-center justify-center py-10 text-[var(--dg-text-muted)]",children:[t.jsx(Se,{"code-path":"src/components/dashboard/DashboardRecent.tsx:410:13",className:"h-10 w-10 mb-3 opacity-30"}),t.jsx("p",{"code-path":"src/components/dashboard/DashboardRecent.tsx:411:13",className:"text-sm",children:"暂无集群数据"})]}):t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:414:11",className:"space-y-3",children:a.map(r=>{const e=Number(r.cpu_usage??0),o=Number(r.memory_usage??0);return t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:419:17",className:"p-3.5 rounded-xl bg-[var(--dg-bg-tertiary)]/50 hover:bg-[var(--dg-bg-hover)] transition-all duration-200 cursor-pointer",onClick:()=>s(`/kubernetes/${r.code||r.id}`),children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:424:19",className:"flex items-center justify-between mb-3",children:[t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:425:21",className:"flex items-center gap-2.5",children:[t.jsx(Se,{"code-path":"src/components/dashboard/DashboardRecent.tsx:426:23",className:"h-4.5 w-4.5 text-[var(--dg-blue)]"}),t.jsx("span",{"code-path":"src/components/dashboard/DashboardRecent.tsx:427:23",className:"text-sm font-semibold text-[var(--dg-text-primary)]",children:r.name})]}),t.jsx($,{"code-path":"src/components/dashboard/DashboardRecent.tsx:429:21",variant:"outline",className:m("text-xs",r.status==="healthy"?"dg-badge-green border":r.status==="warning"?"dg-badge-yellow border":"dg-badge-red border"),children:r.status==="healthy"?"健康":r.status==="warning"?"警告":"异常"})]}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:441:19",className:"grid grid-cols-4 gap-2 text-center",children:[{label:"节点",value:r.node_count??0},{label:"Pod",value:r.pod_count??0},{label:"CPU",value:`${e.toFixed(1)}%`},{label:"内存",value:`${o.toFixed(1)}%`}].map(n=>t.jsxs("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:448:23",className:"p-1.5 rounded-lg bg-[var(--dg-bg-primary)]/50",children:[t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:449:25",className:"text-sm font-semibold text-[var(--dg-text-primary)]",children:n.value}),t.jsx("div",{"code-path":"src/components/dashboard/DashboardRecent.tsx:450:25",className:"text-[10px] text-[var(--dg-text-muted)] mt-0.5",children:n.label})]},n.label))})]},r.id)})})})]})}function fe({variant:a="card",className:s}){const r="dg-skeleton";return a==="stat"?t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:22:7",className:m("dg-card p-6 space-y-4",s),children:[t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:23:9",className:"flex items-start justify-between",children:[t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:24:11",className:"space-y-3 flex-1",children:[t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:25:13",className:m("h-4 w-24 rounded",r)}),t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:26:13",className:m("h-8 w-16 rounded",r)})]}),t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:28:11",className:m("h-10 w-10 rounded-lg",r)})]}),t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:30:9",className:m("h-3 w-32 rounded",r)})]}):a==="chart"?t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:37:7",className:m("dg-card p-6 space-y-4",s),children:[t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:38:9",className:"space-y-2",children:[t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:39:11",className:m("h-5 w-32 rounded",r)}),t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:40:11",className:m("h-3 w-48 rounded",r)})]}),t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:42:9",className:m("h-[200px] rounded-lg",r)})]}):a==="table"?t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:49:7",className:m("dg-card overflow-hidden",s),children:[t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:51:9",className:"flex items-center gap-4 p-4 border-b border-[var(--dg-border)]",children:[t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:52:11",className:m("h-4 w-8 rounded",r)}),Array.from({length:6}).map((e,o)=>t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:54:13",className:m("h-4 flex-1 rounded",r)},o))]}),Array.from({length:5}).map((e,o)=>t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:59:11",className:"flex items-center gap-4 p-4 border-b border-[var(--dg-border)] last:border-0",children:[t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:60:13",className:m("h-4 w-8 rounded",r)}),Array.from({length:6}).map((n,c)=>t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:62:15",className:m("h-4 flex-1 rounded",r)},c))]},o))]}):t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:72:5",className:m("dg-card p-6 space-y-4",s),children:[t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:73:7",className:"space-y-2",children:[t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:74:9",className:m("h-5 w-40 rounded",r)}),t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:75:9",className:m("h-3 w-56 rounded",r)})]}),t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:77:7",className:"space-y-3",children:Array.from({length:4}).map((e,o)=>t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:79:11",className:"flex items-center gap-3",children:[t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:80:13",className:m("h-8 w-8 rounded-lg",r)}),t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:81:13",className:"flex-1 space-y-2",children:[t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:82:15",className:m("h-3 w-full rounded",r)}),t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:83:15",className:m("h-3 w-2/3 rounded",r)})]})]},o))})]})}function os({count:a=4}){return t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:97:5",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:Array.from({length:a}).map((s,r)=>t.jsx(fe,{"code-path":"src/components/layout/SkeletonCard.tsx:99:9",variant:"stat"},r))})}function ns(){return t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:110:5",className:"space-y-6",children:[t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:112:7",className:"flex items-center justify-between",children:[t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:113:9",className:"space-y-2",children:[t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:114:11",className:"dg-skeleton h-7 w-24 rounded"}),t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:115:11",className:"dg-skeleton h-4 w-48 rounded"})]}),t.jsx("div",{"code-path":"src/components/layout/SkeletonCard.tsx:117:9",className:"dg-skeleton h-9 w-20 rounded-lg"})]}),t.jsx(os,{"code-path":"src/components/layout/SkeletonCard.tsx:121:7",count:4}),t.jsx(fe,{"code-path":"src/components/layout/SkeletonCard.tsx:124:7",variant:"chart"}),t.jsxs("div",{"code-path":"src/components/layout/SkeletonCard.tsx:127:7",className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[t.jsx(fe,{"code-path":"src/components/layout/SkeletonCard.tsx:128:9",variant:"list"}),t.jsx(fe,{"code-path":"src/components/layout/SkeletonCard.tsx:129:9",variant:"list"})]})]})}function Ns(){const a=le(),[s,r]=A.useState(!0),[e,o]=A.useState(!1),[n,c]=A.useState(null),[d,l]=A.useState([]),[i,p]=A.useState([]),[u,b]=A.useState([]),[D,f]=A.useState([]),[h,v]=A.useState([]),[y,j]=A.useState([]),k=A.useCallback(async()=>{o(!0);try{const[O,P,J,H,T,ce]=await Promise.all([pe.getStats().catch(R=>(console.error("Failed to fetch dashboard stats:",R),null)),Ot.getServers({page:1,page_size:100}).catch(R=>(console.error("Failed to fetch servers:",R),null)),_t.getClusters().catch(R=>(console.error("Failed to fetch k8s clusters:",R),null)),pe.getAlerts(10).catch(R=>(console.error("Failed to fetch dashboard alerts:",R),null)),pe.getReleases(5).catch(R=>(console.error("Failed to fetch dashboard releases:",R),null)),pe.getMetrics(6).catch(R=>(console.error("Failed to fetch metrics:",R),[]))]);c(O),l(P?.list??[]),p(J?.list??[]),b(Array.isArray(H)?H:[]),f(Array.isArray(T)?T:[]),v(O?.expiring_certs??[]),j(Array.isArray(ce)?ce:[])}catch(O){console.error("Failed to load dashboard data:",O)}finally{o(!1),r(!1)}},[]);if(A.useEffect(()=>{k();const O=setInterval(k,5e3);return()=>clearInterval(O)},[k]),s)return t.jsx(ns,{"code-path":"src/components/dashboard/Dashboard.tsx:94:12"});const w=n?.server_stats,S=n?.kubernetes_stats,_=n?.alert_stats,M=n?.cost_stats,N=Dt(M?.month_trend);return t.jsxs("div",{"code-path":"src/components/dashboard/Dashboard.tsx:104:5",className:"dg-page",children:[t.jsxs("div",{"code-path":"src/components/dashboard/Dashboard.tsx:106:7",className:"dg-page-header",children:[t.jsxs("div",{"code-path":"src/components/dashboard/Dashboard.tsx:107:9",children:[t.jsx("h1",{"code-path":"src/components/dashboard/Dashboard.tsx:108:11",className:"dg-page-title",children:"仪表盘"}),t.jsxs("p",{"code-path":"src/components/dashboard/Dashboard.tsx:109:11",className:"dg-page-subtitle",children:["实时监控和运维概览 · 最后更新: ",new Date().toLocaleTimeString("zh-CN")]})]}),t.jsxs("div",{"code-path":"src/components/dashboard/Dashboard.tsx:111:9",className:"dg-page-actions",children:[t.jsxs(se,{"code-path":"src/components/dashboard/Dashboard.tsx:112:11",variant:"outline",className:"dg-btn-secondary",onClick:k,disabled:e,children:[t.jsx(At,{"code-path":"src/components/dashboard/Dashboard.tsx:118:13",className:m("h-4 w-4",e&&"animate-spin")}),e?"刷新中":"刷新"]}),t.jsxs(se,{"code-path":"src/components/dashboard/Dashboard.tsx:121:11",className:"dg-btn-primary",onClick:()=>a("/servers"),children:[t.jsx(Ae,{"code-path":"src/components/dashboard/Dashboard.tsx:125:13",className:"h-4 w-4"}),"服务器",t.jsx(he,{"code-path":"src/components/dashboard/Dashboard.tsx:127:13",className:"h-3.5 w-3.5"})]})]})]}),t.jsxs("div",{"code-path":"src/components/dashboard/Dashboard.tsx:133:7",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[t.jsx("div",{"code-path":"src/components/dashboard/Dashboard.tsx:134:9",className:"animate-fade-in-delay-1",children:t.jsx(xe,{"code-path":"src/components/dashboard/Dashboard.tsx:135:11",title:"服务器总数",value:w?.total??0,description:`${w?.running??0} 台运行中`,icon:Ae,trend:Number(w?.error??0)>0?"down":"neutral",trendValue:Number(w?.error??0)>0?`${w?.error} 台异常`:"运行正常",color:"blue",onClick:()=>a("/servers")})}),t.jsx("div",{"code-path":"src/components/dashboard/Dashboard.tsx:146:9",className:"animate-fade-in-delay-2",children:t.jsx(xe,{"code-path":"src/components/dashboard/Dashboard.tsx:147:11",title:"Kubernetes 集群",value:S?.total??0,description:`${S?.healthy??0} 个健康`,icon:Se,trend:"neutral",trendValue:"稳定",color:"purple",onClick:()=>a("/kubernetes")})}),t.jsx("div",{"code-path":"src/components/dashboard/Dashboard.tsx:158:9",className:"animate-fade-in-delay-3",children:t.jsx(xe,{"code-path":"src/components/dashboard/Dashboard.tsx:159:11",title:"待处理告警",value:_?.firing??0,description:`${_?.critical??0} 个严重`,icon:St,trend:Number(_?.today_count??0)>0?"up":"down",trendValue:`本周 ${_?.week_count??0} 条`,color:"rose",onClick:()=>a("/alert-center")})}),t.jsx("div",{"code-path":"src/components/dashboard/Dashboard.tsx:170:9",className:"animate-fade-in-delay-4",children:t.jsx(xe,{"code-path":"src/components/dashboard/Dashboard.tsx:171:11",title:"本月云成本",value:`¥${Number(M?.month_cost??0).toLocaleString()}`,description:N.label,icon:sa,trend:N.direction,trendValue:`${N.pct>0?"+":""}${N.pct.toFixed(1)}%`,color:"orange",onClick:()=>a("/cloud-billing")})})]}),t.jsx("div",{"code-path":"src/components/dashboard/Dashboard.tsx:185:7",className:"animate-fade-in-delay-2",children:t.jsx(Ja,{"code-path":"src/components/dashboard/Dashboard.tsx:186:9",avgCpu:Number(w?.avg_cpu??0),avgMemory:Number(w?.avg_memory??0),avgDisk:Number(w?.avg_disk??0),metrics:y})}),t.jsxs("div",{"code-path":"src/components/dashboard/Dashboard.tsx:195:7",className:"grid grid-cols-1 lg:grid-cols-2 gap-6 animate-fade-in-delay-3",children:[t.jsx(Za,{"code-path":"src/components/dashboard/Dashboard.tsx:196:9",costStats:M}),t.jsx(Xa,{"code-path":"src/components/dashboard/Dashboard.tsx:197:9",topUsage:n?.top_resource_usage})]}),t.jsxs("div",{"code-path":"src/components/dashboard/Dashboard.tsx:201:7",className:"grid grid-cols-1 lg:grid-cols-2 gap-6 animate-fade-in-delay-3",children:[t.jsx(es,{"code-path":"src/components/dashboard/Dashboard.tsx:202:9",alerts:u}),t.jsx(ts,{"code-path":"src/components/dashboard/Dashboard.tsx:203:9",expCerts:h})]}),t.jsxs("div",{"code-path":"src/components/dashboard/Dashboard.tsx:207:7",className:"grid grid-cols-1 lg:grid-cols-3 gap-6 animate-fade-in-delay-4",children:[t.jsx(as,{"code-path":"src/components/dashboard/Dashboard.tsx:208:9",releases:D}),t.jsx(ss,{"code-path":"src/components/dashboard/Dashboard.tsx:209:9",servers:d}),t.jsx(rs,{"code-path":"src/components/dashboard/Dashboard.tsx:210:9",clusters:i})]})]})}export{Ns as Dashboard}; diff --git a/backend/static/assets/DatasourcePage-brk0z6d8.js b/backend/static/assets/DatasourcePage-brk0z6d8.js new file mode 100644 index 0000000..690db2b --- /dev/null +++ b/backend/static/assets/DatasourcePage-brk0z6d8.js @@ -0,0 +1 @@ +import{g as he,a as le,r,j as e,B as i,G as L,P as Ce,D as xe,b as pe,c as ge,d as be,e as De,I as u,O as je,t as ve,a4 as F,a5 as ke,T as Se,x as te,E as Me,a3 as Te,f as Ne}from"./index-DfyorCky.js";import{T as Ae,a as ze,b as de,c as me}from"./tabs-CIh_yD4s.js";import{B as v}from"./badge-xNW8x0G1.js";import{C as re,b as Le,c as Fe,a as oe}from"./card-C55cvSHg.js";import{L as c}from"./label-BK0h2apY.js";import{S as l}from"./switch-CGiGgOnh.js";import{S as Y,a as ee,b as ae,c as se,d as A,C as I}from"./select-D5qUzdAs.js";import{t as o}from"./index-a3ybMjbR.js";import{p as k,z}from"./monitor-BAaBXIsC.js";import{R as ce}from"./refresh-cw-DUB_tAG-.js";import{P as H}from"./plus-CUG-9kpu.js";import{S as fe}from"./square-pen-BxUFAe0F.js";import{T as _e}from"./trash-2-Dx32pOzT.js";import{W as Ie}from"./wrench-KfbhOOJm.js";import{C as Pe}from"./circle-x-DK79Dhg2.js";import{C as qe}from"./circle-check-DWcXrx2k.js";import"./index-CWVNW_qu.js";const Ee=[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M17 8a1 1 0 0 1 1 1v4a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1z",key:"1xoxul"}],["path",{d:"M9 8V2",key:"14iosj"}]],ne=he("plug",Ee);const Oe=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]],$=he("star",Oe),ie={name:"",url:"",access:"server",http_method:"POST",basic_auth:!1,basic_auth_user:"",basic_auth_pass:"",with_credentials:!1,tls_client_auth:!1,with_ca_cert:!1,ca_cert:"",skip_tls_verify:!1,custom_headers_json:"",enable_alerting:!0,alertmanager_ds:"",scrape_interval:15,query_timeout:60,disable_metrics_lookup:!1,custom_query_params:"",is_default:!1};function Re(){const x=le(),[h,p]=r.useState([]),[B,V]=r.useState(!0),[U,g]=r.useState(!1),[b,q]=r.useState(null),[s,_]=r.useState({...ie}),[P,D]=r.useState([]),[y,E]=r.useState(!1),[,O]=r.useState(!1),[S,R]=r.useState(!1),[T,w]=r.useState(!1),[M,N]=r.useState(!1),[j,Z]=r.useState(null),m=r.useCallback(async()=>{try{const a=await k.list();p(a?.data||a||[])}catch{o.error("获取数据源列表失败")}finally{V(!1)}},[]);r.useEffect(()=>{m()},[m]);const G=()=>{q(null),_({...ie}),D([]),Z(null),E(!1),O(!1),R(!1),w(!1),g(!0)},W=a=>{q(a.id),_({name:a.name,url:a.url,access:a.access||"server",http_method:a.http_method||"POST",basic_auth:a.basic_auth||!1,basic_auth_user:a.basic_auth_user||"",basic_auth_pass:a.basic_auth_pass||"",with_credentials:a.with_credentials||!1,tls_client_auth:a.tls_client_auth||!1,with_ca_cert:a.with_ca_cert||!1,ca_cert:a.ca_cert||"",skip_tls_verify:a.skip_tls_verify||!1,custom_headers_json:a.custom_headers||"",enable_alerting:a.enable_alerting!==!1,alertmanager_ds:a.alertmanager_ds||"",scrape_interval:a.scrape_interval||15,query_timeout:a.query_timeout||60,disable_metrics_lookup:a.disable_metrics_lookup||!1,custom_query_params:a.custom_query_params||"",is_default:a.is_default||!1});try{const d=JSON.parse(a.custom_headers||"[]");D(Array.isArray(d)?d:[])}catch{D([])}Z(null),g(!0)},n=(a,d)=>{_(f=>({...f,[a]:d}))},J=()=>{D(a=>[...a,{header:"",value:""}])},t=a=>{D(d=>d.filter((f,X)=>X!==a))},C=(a,d,f)=>{D(X=>{const K=[...X];return K[a]={...K[a],[d]:f},K})},Q=async()=>{if(!s.name.trim()){o.error("请输入数据源名称");return}if(!s.url.trim()){o.error("请输入 Prometheus URL");return}const a={name:s.name.trim(),url:s.url.trim(),access:s.access,http_method:s.http_method,basic_auth:s.basic_auth,basic_auth_user:s.basic_auth_user,basic_auth_pass:s.basic_auth_pass,with_credentials:s.with_credentials,tls_client_auth:s.tls_client_auth,with_ca_cert:s.with_ca_cert,ca_cert:s.ca_cert,skip_tls_verify:s.skip_tls_verify,custom_headers:JSON.stringify(P),enable_alerting:s.enable_alerting,alertmanager_ds:s.alertmanager_ds,scrape_interval:s.scrape_interval,query_timeout:s.query_timeout,disable_metrics_lookup:s.disable_metrics_lookup,custom_query_params:s.custom_query_params,is_default:s.is_default};try{b?(await k.update(b,a),o.success("数据源更新成功")):(await k.create(a),o.success("数据源创建成功")),g(!1),m()}catch(d){o.error(d?.message||"操作失败")}},ye=async a=>{if(await x({title:"删除数据源",description:`确定删除数据源「${a.name}」吗?此操作不可撤销。`,variant:"destructive"}))try{await k.delete(a.id),o.success("已删除"),m()}catch{o.error("删除失败")}},we=async a=>{try{await k.setDefault(a.id),o.success(`已将「${a.name}」设为默认数据源`),m()}catch{o.error("设置失败")}},Ze=async()=>{if(!s.url.trim()){o.error("请先输入 URL");return}N(!0),Z(null);try{const a=await k.testConnection({url:s.url.trim(),basic_auth:s.basic_auth,basic_auth_user:s.basic_auth_user,basic_auth_pass:s.basic_auth_pass,skip_tls_verify:s.skip_tls_verify}),d=a?.data||a;Z(d)}catch(a){Z({success:!1,message:a?.message||"测试失败"})}finally{N(!1)}};return B?e.jsx("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:298:7",className:"flex items-center justify-center h-96",children:e.jsx(ce,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:299:9",className:"animate-spin w-8 h-8 text-[var(--dg-text-secondary)]"})}):e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:305:5",className:"p-6 space-y-6 max-w-7xl mx-auto",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:307:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:308:9",children:[e.jsx("h1",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:309:11",className:"text-2xl font-bold text-[var(--dg-text-primary)]",children:"数据源管理"}),e.jsx("p",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:310:11",className:"text-sm text-[var(--dg-text-secondary)] mt-1",children:"Prometheus 数据源配置,用于指标监控与监控大屏"})]}),e.jsxs(i,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:314:9",onClick:G,className:"gap-2",children:[e.jsx(H,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:315:11",className:"w-4 h-4"}),"添加数据源"]})]}),e.jsxs(re,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:321:7",className:"border-[var(--dg-border)] bg-[var(--dg-bg-secondary)]",children:[e.jsx(Le,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:322:9",className:"pb-2",children:e.jsxs(Fe,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:323:11",className:"text-base flex items-center gap-2",children:[e.jsx(L,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:324:13",className:"w-4 h-4 text-blue-400"}),"已配置的数据源",e.jsx(v,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:326:13",variant:"secondary",className:"ml-2",children:h.length})]})}),e.jsx(oe,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:329:9",className:"p-0",children:h.length===0?e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:331:13",className:"py-12 text-center text-[var(--dg-text-secondary)]",children:[e.jsx(L,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:332:15",className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:333:15",className:"text-sm",children:"暂无数据源"}),e.jsx("p",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:334:15",className:"text-xs mt-1",children:"点击「添加数据源」开始配置"})]}):e.jsx("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:337:13",className:"overflow-x-auto",children:e.jsxs("table",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:338:15",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:339:17",className:"border-b border-[var(--dg-border)]",children:e.jsxs("tr",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:340:19",className:"text-xs text-[var(--dg-text-secondary)]",children:[e.jsx("th",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:341:21",className:"text-left py-3 px-4 font-medium",children:"名称"}),e.jsx("th",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:342:21",className:"text-left py-3 px-4 font-medium",children:"URL"}),e.jsx("th",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:343:21",className:"text-left py-3 px-4 font-medium w-20",children:"默认"}),e.jsx("th",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:344:21",className:"text-left py-3 px-4 font-medium w-16",children:"状态"}),e.jsx("th",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:345:21",className:"text-right py-3 px-4 font-medium w-36",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:348:17",children:h.map(a=>e.jsxs("tr",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:350:21",className:"border-b border-[var(--dg-border)]/50 hover:bg-[var(--dg-bg-tertiary)]/50 transition-colors",children:[e.jsx("td",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:354:23",className:"py-3 px-4",children:e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:355:25",className:"flex items-center gap-2",children:[e.jsx("img",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:356:27",src:"https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/prometheus.png",alt:"Prometheus",className:"w-5 h-5 rounded",onError:d=>{d.target.style.display="none"}}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:362:27",children:[e.jsx("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:363:29",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:a.name}),a.basic_auth&&e.jsx(Ce,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:364:47",className:"w-3 h-3 inline ml-1.5 text-amber-400"})]})]})}),e.jsx("td",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:368:23",className:"py-3 px-4",children:e.jsx("code",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:369:25",className:"text-xs text-blue-300 bg-slate-800/50 px-2 py-0.5 rounded max-w-[320px] block truncate",title:a.url,children:a.url})}),e.jsx("td",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:374:23",className:"py-3 px-4",children:a.is_default?e.jsxs(v,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:376:27",variant:"default",className:"bg-amber-500/15 text-amber-400 border-amber-500/30 text-xs",children:[e.jsx($,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:377:29",className:"w-3 h-3 mr-1"})," 默认"]}):e.jsx("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:380:27",className:"text-xs text-[var(--dg-text-secondary)]",children:"--"})}),e.jsx("td",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:383:23",className:"py-3 px-4",children:a.status===1?e.jsx(v,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:385:27",variant:"default",className:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30 text-xs",children:"启用"}):e.jsx(v,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:389:27",variant:"secondary",className:"text-xs",children:"禁用"})}),e.jsx("td",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:392:23",className:"py-3 px-4",children:e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:393:25",className:"flex items-center justify-end gap-1",children:[e.jsx(i,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:394:27",variant:"ghost",size:"sm",className:"h-8 px-2",onClick:()=>He(a),title:"测试连接",children:e.jsx(ne,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:400:29",className:"w-3.5 h-3.5"})}),!a.is_default&&e.jsx(i,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:403:29",variant:"ghost",size:"sm",className:"h-8 px-2 text-amber-400 hover:text-amber-300",onClick:()=>we(a),title:"设为默认",children:e.jsx($,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:409:31",className:"w-3.5 h-3.5"})}),e.jsx(i,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:412:27",variant:"ghost",size:"sm",className:"h-8 px-2",onClick:()=>W(a),children:e.jsx(fe,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:417:29",className:"w-3.5 h-3.5"})}),e.jsx(i,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:419:27",variant:"ghost",size:"sm",className:"h-8 px-2 text-red-400 hover:text-red-300",onClick:()=>ye(a),children:e.jsx(_e,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:424:29",className:"w-3.5 h-3.5"})})]})})]},a.id))})]})})})]}),e.jsx(xe,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:438:7",open:U,onOpenChange:g,children:e.jsxs(pe,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:439:9",className:"max-w-2xl max-h-[90vh] overflow-y-auto bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:[e.jsxs(ge,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:440:11",children:[e.jsxs(be,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:441:13",className:"flex items-center gap-2 text-lg",children:[e.jsx(L,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:442:15",className:"w-5 h-5 text-orange-400"}),b?"编辑数据源":"添加数据源"]}),e.jsx(De,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:445:13",children:"Prometheus 数据源配置 · 参考 Grafana 数据源管理"})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:450:11",className:"space-y-5 py-2",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:452:13",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:453:15",className:"space-y-2",children:[e.jsxs(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:454:17",htmlFor:"ds-name",className:"text-sm",children:["Name ",e.jsx("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:454:67",className:"text-red-400",children:"*"})]}),e.jsx(u,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:455:17",id:"ds-name",placeholder:"Prometheus 数据源名称",value:s.name,onChange:a=>n("name",a.target.value),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]"})]}),e.jsx("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:463:15",className:"flex items-end pb-2",children:e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:464:17",className:"flex items-center gap-3",children:[e.jsx(l,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:465:19",id:"ds-default",checked:s.is_default,onCheckedChange:a=>n("is_default",a)}),e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:470:19",htmlFor:"ds-default",className:"text-sm cursor-pointer",children:"Default"})]})})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:476:13",className:"space-y-3 bg-[var(--dg-bg-tertiary)]/50 rounded-lg p-4 border border-[var(--dg-border)]/50",children:[e.jsxs("h4",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:477:15",className:"text-sm font-medium flex items-center gap-2 text-[var(--dg-text-primary)]",children:[e.jsx(je,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:478:17",className:"w-4 h-4"})," HTTP"]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:480:15",className:"space-y-2",children:[e.jsxs(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:481:17",htmlFor:"ds-url",className:"text-sm",children:["URL ",e.jsx("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:481:65",className:"text-red-400",children:"*"})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:482:17",className:"flex gap-2",children:[e.jsxs(Y,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:483:19",value:s.access,onValueChange:a=>n("access",a),children:[e.jsx(ee,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:484:21",className:"w-32 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm",children:e.jsx(ae,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:485:23"})}),e.jsxs(se,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:487:21",children:[e.jsx(A,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:488:23",value:"server",children:"Server"}),e.jsx(A,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:489:23",value:"browser",children:"Browser"})]})]}),e.jsx(u,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:492:19",id:"ds-url",placeholder:"http://localhost:9090",value:s.url,onChange:a=>n("url",a.target.value),className:"flex-1 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] font-mono text-sm"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:501:15",className:"text-xs text-[var(--dg-text-secondary)]",children:["Access: ",e.jsx("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:502:25",className:"text-[var(--dg-text-primary)]",children:s.access==="server"?"Server (default)":"Browser"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:507:13",className:"border border-[var(--dg-border)]/50 rounded-lg overflow-hidden",children:[e.jsxs("button",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:508:15",type:"button",className:"w-full flex items-center justify-between px-4 py-3 bg-[var(--dg-bg-tertiary)]/30 hover:bg-[var(--dg-bg-tertiary)]/60 transition-colors",onClick:()=>E(!y),children:[e.jsxs("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:513:17",className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ve,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:514:19",className:"w-4 h-4"})," Auth"]}),y?e.jsx(I,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:516:29",className:"w-4 h-4"}):e.jsx(F,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:516:65",className:"w-4 h-4"})]}),y&&e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:519:17",className:"p-4 space-y-4 border-t border-[var(--dg-border)]/50",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:521:19",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:522:21",className:"flex items-center gap-3",children:[e.jsx(l,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:523:23",id:"ds-basic-auth",checked:s.basic_auth,onCheckedChange:a=>n("basic_auth",a)}),e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:528:23",htmlFor:"ds-basic-auth",className:"text-sm cursor-pointer",children:"Basic auth"})]}),s.basic_auth&&e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:531:23",className:"grid grid-cols-2 gap-3 ml-9",children:[e.jsx(u,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:532:25",placeholder:"用户名",value:s.basic_auth_user,onChange:a=>n("basic_auth_user",a.target.value),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm"}),e.jsx(u,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:538:25",type:"password",placeholder:"密码",value:s.basic_auth_pass,onChange:a=>n("basic_auth_pass",a.target.value),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:550:19",className:"flex items-center gap-3",children:[e.jsx(l,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:551:21",id:"ds-with-creds",checked:s.with_credentials,onCheckedChange:a=>n("with_credentials",a)}),e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:556:21",htmlFor:"ds-with-creds",className:"text-sm cursor-pointer",children:"With Credentials"})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:560:19",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:561:21",className:"flex items-center gap-3",children:[e.jsx(l,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:562:23",id:"ds-tls-auth",checked:s.tls_client_auth,onCheckedChange:a=>n("tls_client_auth",a)}),e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:567:23",htmlFor:"ds-tls-auth",className:"text-sm cursor-pointer",children:"TLS Client Auth"})]}),s.tls_client_auth&&e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:570:23",className:"ml-9 space-y-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:571:25",className:"flex items-center gap-3",children:[e.jsx(l,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:572:27",id:"ds-ca-cert",checked:s.with_ca_cert,onCheckedChange:a=>n("with_ca_cert",a)}),e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:577:27",htmlFor:"ds-ca-cert",className:"text-sm cursor-pointer",children:"With CA Cert"})]}),s.with_ca_cert&&e.jsx("textarea",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:580:27",placeholder:"PEM 格式的 CA 证书内容...",value:s.ca_cert,onChange:a=>n("ca_cert",a.target.value),rows:4,className:"w-full bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-md p-3 text-xs font-mono text-[var(--dg-text-primary)] resize-y"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:593:19",className:"flex items-center gap-3",children:[e.jsx(l,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:594:21",id:"ds-skip-tls",checked:s.skip_tls_verify,onCheckedChange:a=>n("skip_tls_verify",a)}),e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:599:21",htmlFor:"ds-skip-tls",className:"text-sm cursor-pointer",children:"Skip TLS Verify"})]}),e.jsx("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:603:19",className:"text-xs text-[var(--dg-text-secondary)] italic",children:"Forward OAuth Identity"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:611:13",className:"space-y-3 bg-[var(--dg-bg-tertiary)]/30 rounded-lg p-4 border border-[var(--dg-border)]/50",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:612:15",className:"flex items-center justify-between",children:[e.jsxs("h4",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:613:17",className:"text-sm font-medium flex items-center gap-2 text-[var(--dg-text-primary)]",children:[e.jsx(Ie,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:614:19",className:"w-4 h-4"})," Custom HTTP Headers"]}),e.jsxs(i,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:616:17",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:J,children:[e.jsx(H,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:617:19",className:"w-3 h-3 mr-1"})," Add header"]})]}),P.length===0?e.jsx("p",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:621:17",className:"text-xs text-[var(--dg-text-secondary)] italic",children:"暂无自定义 Header"}):e.jsx("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:623:17",className:"space-y-2",children:P.map((a,d)=>e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:625:21",className:"flex items-center gap-2",children:[e.jsx(u,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:626:23",placeholder:"Header",value:a.header,onChange:f=>C(d,"header",f.target.value),className:"flex-1 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm h-8"}),e.jsx(u,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:632:23",placeholder:"Value",value:a.value,onChange:f=>C(d,"value",f.target.value),className:"flex-1 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm h-8"}),e.jsx(i,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:638:23",variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-red-400 hover:text-red-300",onClick:()=>t(d),children:e.jsx(ke,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:642:25",className:"w-3.5 h-3.5"})})]},d))})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:651:13",className:"border border-[var(--dg-border)]/50 rounded-lg overflow-hidden",children:[e.jsxs("button",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:652:15",type:"button",className:"w-full flex items-center justify-between px-4 py-3 bg-[var(--dg-bg-tertiary)]/30 hover:bg-[var(--dg-bg-tertiary)]/60 transition-colors",onClick:()=>R(!S),children:[e.jsxs("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:657:17",className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Se,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:658:19",className:"w-4 h-4"})," Alerting"]}),S?e.jsx(I,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:660:33",className:"w-4 h-4"}):e.jsx(F,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:660:69",className:"w-4 h-4"})]}),S&&e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:663:17",className:"p-4 space-y-4 border-t border-[var(--dg-border)]/50",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:664:19",className:"flex items-center gap-3",children:[e.jsx(l,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:665:21",id:"ds-enable-alerting",checked:s.enable_alerting,onCheckedChange:a=>n("enable_alerting",a)}),e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:670:21",htmlFor:"ds-enable-alerting",className:"text-sm cursor-pointer",children:"Manage alerts via Alerting UI"})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:674:19",className:"space-y-2",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:675:21",className:"text-sm text-[var(--dg-text-secondary)]",children:"Alertmanager data source"}),e.jsxs(Y,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:676:21",value:s.alertmanager_ds,onValueChange:a=>n("alertmanager_ds",a),children:[e.jsx(ee,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:677:23",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm",children:e.jsx(ae,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:678:25",placeholder:"Choose"})}),e.jsxs(se,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:680:23",children:[e.jsx(A,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:681:25",value:"__none",children:"无"}),h.filter(a=>a.id!==b).map(a=>e.jsx(A,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:683:27",value:String(a.id),children:a.name},a.id))]})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:693:13",className:"grid grid-cols-2 gap-4 bg-[var(--dg-bg-tertiary)]/30 rounded-lg p-4 border border-[var(--dg-border)]/50",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:694:15",className:"space-y-2",children:[e.jsxs(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:695:17",className:"text-sm flex items-center gap-1.5",children:[e.jsx(te,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:696:19",className:"w-3.5 h-3.5"})," Scrape interval"]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:698:17",className:"flex items-center gap-2",children:[e.jsx(u,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:699:19",type:"number",min:1,value:s.scrape_interval,onChange:a=>n("scrape_interval",Number(a.target.value)),className:"w-20 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm text-center"}),e.jsx("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:706:19",className:"text-xs text-[var(--dg-text-secondary)]",children:"秒"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:709:15",className:"space-y-2",children:[e.jsxs(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:710:17",className:"text-sm flex items-center gap-1.5",children:[e.jsx(te,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:711:19",className:"w-3.5 h-3.5"})," Query timeout"]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:713:17",className:"flex items-center gap-2",children:[e.jsx(u,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:714:19",type:"number",min:1,value:s.query_timeout,onChange:a=>n("query_timeout",Number(a.target.value)),className:"w-20 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm text-center"}),e.jsx("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:721:19",className:"text-xs text-[var(--dg-text-secondary)]",children:"秒"})]})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:727:13",className:"space-y-2",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:728:15",className:"text-sm",children:"HTTP Method"}),e.jsxs(Y,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:729:15",value:s.http_method,onValueChange:a=>n("http_method",a),children:[e.jsx(ee,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:730:17",className:"w-32 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm",children:e.jsx(ae,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:731:19"})}),e.jsxs(se,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:733:17",children:[e.jsx(A,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:734:19",value:"POST",children:"POST"}),e.jsx(A,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:735:19",value:"GET",children:"GET"})]})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:741:13",className:"border border-[var(--dg-border)]/50 rounded-lg overflow-hidden",children:[e.jsxs("button",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:742:15",type:"button",className:"w-full flex items-center justify-between px-4 py-3 bg-[var(--dg-bg-tertiary)]/30 hover:bg-[var(--dg-bg-tertiary)]/60 transition-colors",onClick:()=>w(!T),children:[e.jsxs("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:747:17",className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Me,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:748:19",className:"w-4 h-4"})," Misc"]}),T?e.jsx(I,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:750:29",className:"w-4 h-4"}):e.jsx(F,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:750:65",className:"w-4 h-4"})]}),T&&e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:753:17",className:"p-4 space-y-4 border-t border-[var(--dg-border)]/50",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:754:19",className:"flex items-center gap-3",children:[e.jsx(l,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:755:21",id:"ds-disable-lookup",checked:s.disable_metrics_lookup,onCheckedChange:a=>n("disable_metrics_lookup",a)}),e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:760:21",htmlFor:"ds-disable-lookup",className:"text-sm cursor-pointer",children:"Disable metrics lookup"})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:764:19",className:"space-y-2",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:765:21",className:"text-sm text-[var(--dg-text-secondary)]",children:"Custom query parameters"}),e.jsx(u,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:766:21",placeholder:'例: {"timeout": "30s"}',value:s.custom_query_params,onChange:a=>n("custom_query_params",a.target.value),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-sm font-mono"})]})]})]}),j&&e.jsxs("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:779:15",className:`rounded-lg p-3 flex items-center gap-2 text-sm ${j.success?"bg-emerald-500/10 border border-emerald-500/30 text-emerald-400":"bg-red-500/10 border border-red-500/30 text-red-400"}`,children:[j.success?e.jsx(Te,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:785:21",className:"w-4 h-4 shrink-0"}):e.jsx(Pe,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:786:21",className:"w-4 h-4 shrink-0"}),e.jsx("span",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:788:17",children:j.message}),j.target_count!==void 0&&e.jsxs(v,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:790:19",variant:"secondary",className:"ml-auto text-xs",children:[j.target_count," targets"]})]})]}),e.jsxs(Ne,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:799:11",className:"flex items-center gap-2 pt-2 border-t border-[var(--dg-border)]/50",children:[e.jsxs(i,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:800:13",variant:"outline",onClick:Ze,disabled:M||!s.url.trim(),className:"gap-2",children:[M?e.jsx(ce,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:807:17",className:"w-4 h-4 animate-spin"}):e.jsx(ne,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:809:17",className:"w-4 h-4"}),"Save & test"]}),e.jsx("div",{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:813:13",className:"flex-1"}),e.jsx(i,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:814:13",variant:"ghost",onClick:()=>g(!1),children:"取消"}),e.jsx(i,{"code-path":"src/components/monitor/datasource/PrometheusDatasourceManager.tsx:817:13",onClick:Q,children:b?"更新":"保存"})]})]})})]})}async function He(x){try{const h=await k.testConnection({url:x.url,basic_auth:x.basic_auth,basic_auth_user:x.basic_auth_user,basic_auth_pass:x.basic_auth_pass,skip_tls_verify:x.skip_tls_verify}),p=h?.data||h;p?.success?o.success(`连接成功 · ${p.target_count||0} targets`):o.error(p?.message||"连接失败")}catch(h){o.error(h?.message||"测试失败")}}const ue={name:"",url:"",username:"",password:"",trends_after:0,trends_range:0,trends_cache_ttl:3600,trends_timeout:30,direct_db:!1,disable_acknowledges:!1,disable_data_alignment:!1,is_default:!1};function $e(){const x=le(),[h,p]=r.useState([]),[B,V]=r.useState(!0),[U,g]=r.useState(!1),[b,q]=r.useState(null),[s,_]=r.useState({...ue}),[P,D]=r.useState(!1),[y,E]=r.useState(!1),[O,S]=r.useState(!1),[R,T]=r.useState(!1),[w,M]=r.useState(null),N=r.useCallback(async()=>{try{const t=await z.list();p(t?.data||t||[])}catch{o.error("获取数据源列表失败")}finally{V(!1)}},[]);r.useEffect(()=>{N()},[N]);const j=()=>{q(null),_({...ue}),M(null),D(!1),E(!1),S(!1),g(!0)},Z=t=>{q(t.id),_({name:t.name,url:t.url,username:t.username||"",password:t.password||"",trends_after:t.trends_after||0,trends_range:t.trends_range||0,trends_cache_ttl:t.trends_cache_ttl||3600,trends_timeout:t.trends_timeout||30,direct_db:t.direct_db||!1,disable_acknowledges:t.disable_acknowledges||!1,disable_data_alignment:t.disable_data_alignment||!1,is_default:t.is_default||!1}),M(null),g(!0)},m=(t,C)=>{_(Q=>({...Q,[t]:C}))},G=async()=>{if(!s.name.trim()){o.error("请输入数据源名称");return}if(!s.url.trim()){o.error("请输入 Zabbix API URL");return}if(!s.username.trim()){o.error("请输入用户名");return}if(!s.password.trim()){o.error("请输入密码");return}try{b?(await z.update(b,s),o.success("数据源已更新")):(await z.create(s),o.success("数据源已创建")),g(!1),N()}catch(t){o.error(t?.message||"操作失败")}},W=async t=>{if(await x({title:"删除数据源",description:`确定删除「${t.name}」?`,variant:"destructive"}))try{await z.delete(t.id),o.success("已删除"),N()}catch{o.error("删除失败")}},n=async t=>{try{await z.setDefault(t.id),o.success(`已将「${t.name}」设为默认`),N()}catch{o.error("设置失败")}},J=async()=>{if(!s.url.trim()||!s.username.trim()){o.error("请填写 URL 和用户名");return}T(!0),M(null);try{const t=await z.testConnection({url:s.url.trim(),username:s.username.trim(),password:s.password||""}),C=t?.data||t;M(C)}catch(t){M({success:!1,message:t?.message||"测试失败"})}finally{T(!1)}};return B?e.jsx("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:183:7",className:"flex items-center justify-center h-96",children:e.jsx(ce,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:184:9",className:"animate-spin w-8 h-8 text-[var(--dg-text-secondary)]"})}):e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:190:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:191:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:192:9",children:[e.jsxs("h2",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:193:11",className:"text-lg font-semibold text-[var(--dg-text-primary)] flex items-center gap-2",children:[e.jsx("img",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:194:13",src:"https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/zabbix.png",className:"w-5 h-5 rounded",onError:t=>{t.target.style.display="none"}}),"Zabbix 数据源"]}),e.jsx("p",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:201:11",className:"text-xs text-[var(--dg-text-muted)]",children:"配置 Zabbix API 连接,获取主机监控数据"})]}),e.jsxs(i,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:203:9",onClick:j,size:"sm",children:[e.jsx(H,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:204:11",className:"w-4 h-4 mr-1"}),"添加"]})]}),h.length===0?e.jsx(re,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:209:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(oe,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:210:11",className:"py-12 text-center text-[var(--dg-text-muted)]",children:[e.jsx(L,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:211:13",className:"w-12 h-12 mx-auto mb-3 opacity-30"}),e.jsx("p",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:212:13",className:"text-sm",children:"暂无 Zabbix 数据源"}),e.jsxs(i,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:213:13",size:"sm",className:"mt-4",onClick:j,children:[e.jsx(H,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:214:15",className:"w-4 h-4 mr-1"}),"添加数据源"]})]})}):e.jsx("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:219:9",className:"grid gap-3",children:h.map(t=>e.jsx(re,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:221:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] hover:border-orange-500/30 transition-colors",children:e.jsx(oe,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:222:15",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:223:17",className:"flex items-start justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:224:19",className:"flex-1 min-w-0",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:225:21",className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:226:23",className:`w-2 h-2 rounded-full ${t.status===1?"bg-emerald-400":"bg-slate-500"}`}),e.jsx("span",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:227:23",className:"font-medium text-[var(--dg-text-primary)]",children:t.name}),t.is_default&&e.jsxs(v,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:228:41",className:"bg-amber-500/20 text-amber-400 text-[10px]",children:[e.jsx($,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:228:103",className:"w-3 h-3 mr-0.5"}),"默认"]}),t.status===1?e.jsx(v,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:230:27",className:"bg-emerald-500/20 text-emerald-400 text-[10px]",children:"启用"}):e.jsx(v,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:231:27",className:"bg-slate-500/20 text-slate-400 text-[10px]",children:"禁用"})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:233:21",className:"text-xs text-[var(--dg-text-muted)] space-x-3",children:[e.jsx("code",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:234:23",className:"text-orange-300",children:t.url}),e.jsxs("span",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:235:23",children:["用户: ",t.username]}),t.direct_db&&e.jsx(v,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:236:40",variant:"outline",className:"text-[10px]",children:"直连DB"})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:239:19",className:"flex items-center gap-1",children:[!t.is_default&&e.jsxs(i,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:241:23",variant:"ghost",size:"sm",className:"h-7 text-xs text-amber-400",onClick:()=>n(t),children:[e.jsx($,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:242:25",className:"w-3 h-3 mr-0.5"}),"默认"]}),e.jsxs(i,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:245:21",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>Z(t),children:[e.jsx(fe,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:246:23",className:"w-3 h-3 mr-0.5"}),"编辑"]}),e.jsx(i,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:248:21",variant:"ghost",size:"sm",className:"h-7 text-xs text-red-400",onClick:()=>W(t),children:e.jsx(_e,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:249:23",className:"w-3 h-3"})})]})]})})},t.id))}),e.jsx(xe,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:260:7",open:U,onOpenChange:g,children:e.jsxs(pe,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:261:9",className:"max-w-xl max-h-[85vh] overflow-y-auto bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:[e.jsxs(ge,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:262:11",children:[e.jsxs(be,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:263:13",className:"text-[var(--dg-text-primary)] flex items-center gap-2",children:[e.jsx(L,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:264:15",className:"h-5 w-5 text-orange-400"}),b?"编辑 Zabbix 数据源":"新建 Zabbix 数据源"]}),e.jsx(De,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:267:13",children:"配置 Zabbix API 连接,用于主机监控与告警数据获取"})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:272:11",className:"space-y-4 py-2",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:274:13",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:275:15",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:276:17",className:"text-xs text-[var(--dg-text-secondary)]",children:"名称 *"}),e.jsx(u,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:277:17",className:"mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]",placeholder:"如:生产 Zabbix",value:s.name,onChange:t=>m("name",t.target.value)})]}),e.jsx("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:280:15",className:"flex items-end pb-1",children:e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:281:17",className:"flex items-center gap-2",children:[e.jsx(l,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:282:19",checked:s.is_default,onCheckedChange:t=>m("is_default",t)}),e.jsx(c,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:283:19",className:"text-xs cursor-pointer",children:"设为默认"})]})})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:289:13",className:"border border-[var(--dg-border)] rounded-lg p-3 space-y-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:290:15",className:"flex items-center gap-2 text-sm text-[var(--dg-text-primary)]",children:[e.jsx(je,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:291:17",className:"w-4 h-4"})," HTTP"]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:293:15",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:294:17",className:"text-xs text-[var(--dg-text-secondary)]",children:"URL *"}),e.jsx(u,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:295:17",className:"mt-1 h-9 text-sm font-mono bg-[var(--dg-bg-primary)]",placeholder:"http://zabbix.example.com/api_jsonrpc.php",value:s.url,onChange:t=>m("url",t.target.value)})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:302:13",className:"border border-[var(--dg-border)] rounded-lg overflow-hidden",children:[e.jsxs("button",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:303:15",className:"w-full flex items-center justify-between px-3 py-2.5 text-sm hover:bg-[var(--dg-bg-tertiary)]",onClick:()=>D(!P),children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:305:17",className:"flex items-center gap-2",children:[e.jsx(ve,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:306:19",className:"w-4 h-4"}),e.jsx("span",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:307:19",children:"Zabbix API 认证"})]}),P?e.jsx(I,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:309:29",className:"w-4 h-4"}):e.jsx(F,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:309:65",className:"w-4 h-4"})]}),P&&e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:312:17",className:"px-3 pb-3 space-y-3",children:[e.jsx(u,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:313:19",className:"h-9 text-sm bg-[var(--dg-bg-primary)]",placeholder:"用户名 *",value:s.username,onChange:t=>m("username",t.target.value)}),e.jsx(u,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:315:19",className:"h-9 text-sm bg-[var(--dg-bg-primary)]",type:"password",placeholder:"密码 *",value:s.password,onChange:t=>m("password",t.target.value)})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:322:13",className:"border border-[var(--dg-border)] rounded-lg overflow-hidden",children:[e.jsxs("button",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:323:15",className:"w-full flex items-center justify-between px-3 py-2.5 text-sm hover:bg-[var(--dg-bg-tertiary)]",onClick:()=>E(!y),children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:325:17",className:"flex items-center gap-2",children:[e.jsx(te,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:326:19",className:"w-4 h-4"}),e.jsx("span",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:327:19",children:"Trends 设置"})]}),y?e.jsx(I,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:329:31",className:"w-4 h-4"}):e.jsx(F,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:329:67",className:"w-4 h-4"})]}),y&&e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:332:17",className:"px-3 pb-3 space-y-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:333:19",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:334:21",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:335:23",className:"text-xs text-[var(--dg-text-secondary)]",children:"After (天)"}),e.jsx(u,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:336:23",className:"mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]",type:"number",min:0,value:s.trends_after,onChange:t=>m("trends_after",parseInt(t.target.value)||0)})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:339:21",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:340:23",className:"text-xs text-[var(--dg-text-secondary)]",children:"Range (秒)"}),e.jsx(u,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:341:23",className:"mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]",type:"number",min:0,value:s.trends_range,onChange:t=>m("trends_range",parseInt(t.target.value)||0)})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:345:19",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:346:21",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:347:23",className:"text-xs text-[var(--dg-text-secondary)]",children:"Cache TTL (秒)"}),e.jsx(u,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:348:23",className:"mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]",type:"number",min:0,value:s.trends_cache_ttl,onChange:t=>m("trends_cache_ttl",parseInt(t.target.value)||3600)})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:351:21",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:352:23",className:"text-xs text-[var(--dg-text-secondary)]",children:"Timeout (秒)"}),e.jsx(u,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:353:23",className:"mt-1 h-9 text-sm bg-[var(--dg-bg-primary)]",type:"number",min:1,value:s.trends_timeout,onChange:t=>m("trends_timeout",parseInt(t.target.value)||30)})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:362:13",className:"border border-[var(--dg-border)] rounded-lg overflow-hidden",children:[e.jsxs("button",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:363:15",className:"w-full flex items-center justify-between px-3 py-2.5 text-sm hover:bg-[var(--dg-bg-tertiary)]",onClick:()=>S(!O),children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:365:17",className:"flex items-center gap-2",children:[e.jsx(Me,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:366:19",className:"w-4 h-4"}),e.jsx("span",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:367:19",children:"其他设置"})]}),O?e.jsx(I,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:369:30",className:"w-4 h-4"}):e.jsx(F,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:369:66",className:"w-4 h-4"})]}),O&&e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:372:17",className:"px-3 pb-3 space-y-3",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:373:19",className:"flex items-center justify-between",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:374:21",className:"text-xs",children:"Direct DB Connection"}),e.jsx(l,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:375:21",checked:s.direct_db,onCheckedChange:t=>m("direct_db",t)})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:377:19",className:"flex items-center justify-between",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:378:21",className:"text-xs",children:"只读用户禁用确认"}),e.jsx(l,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:379:21",checked:s.disable_acknowledges,onCheckedChange:t=>m("disable_acknowledges",t)})]}),e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:381:19",className:"flex items-center justify-between",children:[e.jsx(c,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:382:21",className:"text-xs",children:"禁用数据对齐"}),e.jsx(l,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:383:21",checked:s.disable_data_alignment,onCheckedChange:t=>m("disable_data_alignment",t)})]})]})]}),w&&e.jsxs("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:391:15",className:`flex items-center gap-2 p-2.5 rounded text-sm ${w.success?"bg-emerald-500/10 text-emerald-400":"bg-red-500/10 text-red-400"}`,children:[w.success?e.jsx(qe,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:394:39",className:"h-4 w-4"}):e.jsx(Pe,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:394:78",className:"h-4 w-4"}),w.message]})]}),e.jsxs(Ne,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:400:11",className:"gap-2",children:[e.jsxs(i,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:401:13",variant:"outline",size:"sm",onClick:J,disabled:R,children:[e.jsx(ne,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:402:15",className:`w-4 h-4 mr-1 ${R?"animate-pulse":""}`}),"测试连接"]}),e.jsx("div",{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:405:13",className:"flex-1"}),e.jsx(i,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:406:13",variant:"ghost",size:"sm",onClick:()=>g(!1),children:"取消"}),e.jsx(i,{"code-path":"src/components/monitor/datasource/ZabbixDatasourceManager.tsx:407:13",size:"sm",onClick:G,children:"保存"})]})]})})]})}function na(){const[x,h]=r.useState("prometheus");return e.jsxs("div",{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:12:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:13:7",className:"flex items-center gap-2",children:[e.jsx(L,{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:14:9",className:"h-5 w-5 text-blue-400"}),e.jsx("h1",{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:15:9",className:"text-xl font-bold text-[var(--dg-text-primary)]",children:"数据源管理"})]}),e.jsxs(Ae,{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:18:7",value:x,onValueChange:h,children:[e.jsxs(ze,{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:19:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:[e.jsxs(de,{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:20:11",value:"prometheus",className:"data-[state=active]:bg-orange-500/10 data-[state=active]:text-orange-400",children:[e.jsx("img",{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:21:13",src:"https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/prometheus.png",className:"w-4 h-4 rounded mr-1.5",onError:p=>{p.target.style.display="none"}}),"Prometheus"]}),e.jsxs(de,{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:28:11",value:"zabbix",className:"data-[state=active]:bg-orange-500/10 data-[state=active]:text-orange-400",children:[e.jsx("img",{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:29:13",src:"https://cdn.jsdelivr.net/gh/walkxcode/dashboard-icons@master/png/zabbix.png",className:"w-4 h-4 rounded mr-1.5",onError:p=>{p.target.style.display="none"}}),"Zabbix"]})]}),e.jsx(me,{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:38:9",value:"prometheus",className:"mt-4",children:e.jsx(Re,{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:39:11"})}),e.jsx(me,{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:41:9",value:"zabbix",className:"mt-4",children:e.jsx($e,{"code-path":"src/components/monitor/datasource/DatasourcePage.tsx:42:11"})})]})]})}export{na as default}; diff --git a/backend/static/assets/DeployCredentials-XbkP4xDn.js b/backend/static/assets/DeployCredentials-XbkP4xDn.js new file mode 100644 index 0000000..faef104 --- /dev/null +++ b/backend/static/assets/DeployCredentials-XbkP4xDn.js @@ -0,0 +1 @@ +import{g as te,r as o,j as e,D as A,b as H,c as M,d as W,O as Y,v as Z,I as z,P as oe,f as ae,B as d,h as ne,L as F,a3 as le,x as ce,a4 as de,e as re,a as pe,a0 as ie}from"./index-DfyorCky.js";import{B as w}from"./badge-xNW8x0G1.js";import{T as xe,a as me,b as $,c as B}from"./tabs-CIh_yD4s.js";import{L as _}from"./label-BK0h2apY.js";import{S as K,a as X,b as q,c as J,d as E}from"./select-D5qUzdAs.js";import{t as r}from"./index-a3ybMjbR.js";import{d as i}from"./deploy-B3Sg3N1U.js";import{P as G}from"./plus-CUG-9kpu.js";import{R as ee}from"./refresh-cw-DUB_tAG-.js";import{C as ye}from"./circle-x-DK79Dhg2.js";import{D as I}from"./download-DoZfYs2h.js";import{W as he}from"./wrench-KfbhOOJm.js";import{P}from"./pencil-BqUotcjf.js";import{T as U}from"./trash-2-Dx32pOzT.js";import"./index-CWVNW_qu.js";const ge=[["path",{d:"M14 17H5",key:"gfn3mx"}],["path",{d:"M19 7h-9",key:"6i9tg"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]],Ce=te("settings-2",ge);function be({open:S,onOpenChange:b,type:L,editId:n,repos:h,registries:j,onSave:m}){const c=L==="repo",[g,u]=o.useState(""),[C,f]=o.useState(""),[p,v]=o.useState(""),[y,N]=o.useState(""),[D,T]=o.useState(""),[s,l]=o.useState([]),[x,V]=o.useState(!1),t=s.filter(a=>c?!0:a.secret_type==="docker"),k=async()=>{try{const a=await ne.get("/credentials?page_size=100");l(a?.list||[])}catch{}};o.useEffect(()=>{if(k(),n)if(c){const a=h.find(R=>R.id===n);a&&(u(a.name),f(""),v(a.url),T(a.credential_id||""))}else{const a=j.find(R=>R.id===n);a&&(u(a.name),f(""),v(a.registry_url),N(a.namespace||""),T(a.credential_id||""))}else u(""),f(""),v(""),N(""),T("")},[n,S,c]);const O=async()=>{if(!g.trim()||!p.trim()){r.error("请填写名称和地址");return}V(!0);try{const a=D?Number(D):null,R=c?{name:g.trim(),description:C.trim(),url:p.trim(),credential_id:a}:{name:g.trim(),description:C.trim(),registry_url:p.trim(),namespace:y.trim(),credential_id:a};n?(c?await i.updateRepo(n,R):await i.updateRegistry(n,R),r.success("已更新")):(c?await i.createRepo(R):await i.createRegistry(R),r.success("已创建")),b(!1),m()}catch{r.error("保存失败")}finally{V(!1)}},se=c?Y:Z;return e.jsx(A,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:97:5",open:S,onOpenChange:b,children:e.jsxs(H,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:98:7",className:"sm:max-w-[480px] bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:[e.jsx(M,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:99:9",children:e.jsxs(W,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:100:11",className:"text-[var(--dg-text-primary)] flex items-center gap-2",children:[e.jsx(se,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:101:13",className:"h-5 w-5 text-[var(--dg-blue)]"}),n?"编辑":"新增",c?" Git 仓库":" 镜像仓库"]})}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialFormDialog.tsx:105:9",className:"space-y-4 py-2",children:[e.jsxs("div",{"code-path":"src/components/deploy/CredentialFormDialog.tsx:106:11",className:"space-y-1",children:[e.jsx(_,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:106:38",children:"名称 *"}),e.jsx(z,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:107:13",value:g,onChange:a=>u(a.target.value),placeholder:c?"如:GitLab CE":"如:Harbor",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialFormDialog.tsx:108:11",className:"space-y-1",children:[e.jsx(_,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:108:38",children:c?"仓库 URL *":"Registry URL *"}),e.jsx(z,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:109:13",value:p,onChange:a=>v(a.target.value),placeholder:c?"http://10.10.10.72:9000/group/repo.git":"http://10.10.10.72",className:"font-mono text-sm bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),!c&&e.jsxs("div",{"code-path":"src/components/deploy/CredentialFormDialog.tsx:110:23",className:"space-y-1",children:[e.jsx(_,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:110:50",children:"默认命名空间"}),e.jsx(z,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:111:13",value:y,onChange:a=>N(a.target.value),placeholder:"如:aiops",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/components/deploy/CredentialFormDialog.tsx:114:11",className:"space-y-1",children:[e.jsxs(_,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:115:13",children:["关联凭证 ",e.jsx("span",{"code-path":"src/components/deploy/CredentialFormDialog.tsx:115:25",className:"text-xs text-[var(--dg-text-secondary)] opacity-70",children:"(认证由凭据管理统一配置)"})]}),e.jsxs(K,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:116:13",value:String(D),onValueChange:a=>T(a==="__none"?"":a),children:[e.jsx(X,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:117:15",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(q,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:118:17",placeholder:c?"选择凭据(API/密码等)":"选择 Docker 密码凭据"})}),e.jsxs(J,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:120:15",children:[e.jsx(E,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:121:17",value:"__none",children:"不关联凭证"}),t.map(a=>e.jsx(E,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:123:19",value:String(a.id),children:e.jsxs("span",{"code-path":"src/components/deploy/CredentialFormDialog.tsx:124:21",className:"flex items-center gap-1.5",children:[e.jsx(oe,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:125:23",className:"h-3 w-3 opacity-60"}),a.name," ",a.summary&&e.jsxs("span",{"code-path":"src/components/deploy/CredentialFormDialog.tsx:126:46",className:"text-[10px] opacity-50",children:["(",a.summary,")"]})]})},a.id))]})]}),t.length===0&&e.jsxs("p",{"code-path":"src/components/deploy/CredentialFormDialog.tsx:133:15",className:"text-xs text-amber-400 flex items-center gap-1 mt-1",children:[e.jsx(G,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:134:17",className:"h-3 w-3"}),"暂无",c?"":"Docker 密码","类型凭证,请在凭证配置页面新增"]})]})]}),e.jsxs(ae,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:140:9",children:[e.jsx(d,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:141:11",variant:"outline",onClick:()=>b(!1),children:"取消"}),e.jsx(d,{"code-path":"src/components/deploy/CredentialFormDialog.tsx:142:11",onClick:O,disabled:x,children:x?"保存中...":"保存"})]})]})})}const je={build:"构建",deploy:"部署",automation:"自动化",other:"其他"},Q={build:"bg-amber-500/20 text-amber-400 border-amber-500/30",deploy:"bg-cyan-500/20 text-cyan-400 border-cyan-500/30",automation:"bg-purple-500/20 text-purple-400 border-purple-500/30",other:"bg-slate-500/20 text-slate-400 border-slate-500/30"},ue=["jdk","nodejs","maven"];function fe(){const[S,b]=o.useState([]),[L,n]=o.useState(!1),[h,j]=o.useState(null),[m,c]=o.useState(null),[g,u]=o.useState(""),[C,f]=o.useState(null),p=async()=>{n(!0);try{const s=await i.getTools();b(s?.list||[])}catch{r.error("获取工具配置失败")}finally{n(!1)}};o.useEffect(()=>{p()},[]);const v=async s=>{try{const x=(await i.getToolVersions(s.id))?.versions||[];if(x.length===0){y(s);return}c({tool:s,versions:x}),u(s.default_version||x[0]?.version||"")}catch{y(s)}},y=async(s,l)=>{j(s.id);try{const x=l||s.default_version;await i.installTool(s.id,x),r.success(`${s.display_name}${x?` (${x})`:""} 安装已触发`),c(null),setTimeout(async()=>{try{await i.checkTool(s.id),p()}catch{}j(null)},3e3)}catch{r.error("触发安装失败"),j(null)}},N=async s=>{try{const l=await i.checkTool(s.id);r.success(l?.available?`${s.display_name} 可用`:`${s.display_name} 不可用`),p()}catch{r.error("检测失败")}},D=async(s,l)=>{try{await i.updateTool(s.id,{install_method:l}),r.success("已更新"),p()}catch{r.error("更新失败")}},T=async s=>{f(s.id);const l=Date.now();try{const x=await i.getToolVersions(s.id),V=((Date.now()-l)/1e3).toFixed(1);x?.versions?.length>0?r.success(`${s.display_name} 镜像可访问 (${V}s)`):r(`${s.display_name} 无法获取版本列表`,{description:"请检查网络连接"})}catch{r.error(`${s.display_name} 网络不可达`)}f(null)};return e.jsxs("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:137:5",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:138:7",className:"flex items-center justify-between",children:[e.jsx("p",{"code-path":"src/components/deploy/ToolConfigTab.tsx:139:9",className:"text-xs text-[var(--dg-text-secondary)]",children:"管理 DevOps 工具的安装策略:预装在镜像中、首次使用自动下载(懒加载)、或禁用不安装"}),e.jsxs(d,{"code-path":"src/components/deploy/ToolConfigTab.tsx:142:9",variant:"outline",size:"sm",onClick:p,children:[e.jsx(ee,{"code-path":"src/components/deploy/ToolConfigTab.tsx:143:11",className:"w-3.5 h-3.5 mr-1"}),"刷新"]})]}),L?e.jsxs("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:148:9",className:"text-center py-12 text-[var(--dg-text-secondary)]",children:[e.jsx(F,{"code-path":"src/components/deploy/ToolConfigTab.tsx:149:11",className:"w-5 h-5 animate-spin mx-auto mb-2"}),"加载中..."]}):S.length===0?e.jsx("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:152:9",className:"text-center py-12 text-[var(--dg-text-secondary)]",children:"暂无工具配置,请检查后端种子数据"}):e.jsx("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:156:9",className:"rounded-md border border-[var(--dg-border)] overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/deploy/ToolConfigTab.tsx:157:11",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/deploy/ToolConfigTab.tsx:158:13",className:"bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]",children:e.jsxs("tr",{"code-path":"src/components/deploy/ToolConfigTab.tsx:159:15",children:[e.jsx("th",{"code-path":"src/components/deploy/ToolConfigTab.tsx:160:17",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"工具"}),e.jsx("th",{"code-path":"src/components/deploy/ToolConfigTab.tsx:161:17",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden sm:table-cell",children:"分类"}),e.jsx("th",{"code-path":"src/components/deploy/ToolConfigTab.tsx:162:17",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"安装方式"}),e.jsx("th",{"code-path":"src/components/deploy/ToolConfigTab.tsx:163:17",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"状态"}),e.jsx("th",{"code-path":"src/components/deploy/ToolConfigTab.tsx:164:17",className:"px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/deploy/ToolConfigTab.tsx:167:13",children:S.map(s=>{const l=ue.includes(s.name);return e.jsxs("tr",{"code-path":"src/components/deploy/ToolConfigTab.tsx:171:19",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50",children:[e.jsxs("td",{"code-path":"src/components/deploy/ToolConfigTab.tsx:172:21",className:"px-3 py-2",children:[e.jsx("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:173:23",className:"font-medium text-[var(--dg-text-primary)]",children:s.display_name}),e.jsx("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:174:23",className:"text-xs text-[var(--dg-text-secondary)] font-mono",children:s.name}),s.description&&e.jsx("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:176:25",className:"text-[10px] text-[var(--dg-text-muted)] mt-0.5 max-w-[220px] leading-tight",children:s.description}),s.installed_version&&s.status==="installed"&&e.jsxs("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:179:25",className:"text-xs text-emerald-400 font-mono mt-0.5",children:["v",s.installed_version]}),s.error_msg&&e.jsx("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:182:25",className:"text-xs text-red-400 mt-0.5 max-w-[200px] truncate",title:s.error_msg,children:s.error_msg})]}),e.jsx("td",{"code-path":"src/components/deploy/ToolConfigTab.tsx:185:21",className:"px-3 py-2 hidden sm:table-cell",children:e.jsx(w,{"code-path":"src/components/deploy/ToolConfigTab.tsx:186:23",className:`text-xs ${Q[s.category]||Q.other}`,children:je[s.category]||s.category})}),e.jsx("td",{"code-path":"src/components/deploy/ToolConfigTab.tsx:190:21",className:"px-3 py-2",children:e.jsxs(K,{"code-path":"src/components/deploy/ToolConfigTab.tsx:191:23",value:s.install_method,onValueChange:x=>D(s,x),children:[e.jsx(X,{"code-path":"src/components/deploy/ToolConfigTab.tsx:195:25",className:"h-7 w-[90px] text-xs",children:e.jsx(q,{"code-path":"src/components/deploy/ToolConfigTab.tsx:196:27"})}),e.jsxs(J,{"code-path":"src/components/deploy/ToolConfigTab.tsx:198:25",children:[e.jsx(E,{"code-path":"src/components/deploy/ToolConfigTab.tsx:199:27",value:"preinstall",children:"预装"}),e.jsx(E,{"code-path":"src/components/deploy/ToolConfigTab.tsx:200:27",value:"lazy",children:"懒加载"}),e.jsx(E,{"code-path":"src/components/deploy/ToolConfigTab.tsx:201:27",value:"disabled",children:"禁用"})]})]})}),e.jsx("td",{"code-path":"src/components/deploy/ToolConfigTab.tsx:205:21",className:"px-3 py-2",children:s.status==="installed"?e.jsxs(w,{"code-path":"src/components/deploy/ToolConfigTab.tsx:207:25",className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-xs gap-1",children:[e.jsx(le,{"code-path":"src/components/deploy/ToolConfigTab.tsx:208:27",className:"w-3 h-3"}),"已安装"]}):s.status==="installing"?e.jsxs(w,{"code-path":"src/components/deploy/ToolConfigTab.tsx:211:25",className:"bg-amber-500/20 text-amber-400 border-amber-500/30 text-xs gap-1",children:[e.jsx(F,{"code-path":"src/components/deploy/ToolConfigTab.tsx:212:27",className:"w-3 h-3 animate-spin"}),"安装中"]}):s.status==="failed"?e.jsxs(w,{"code-path":"src/components/deploy/ToolConfigTab.tsx:215:25",className:"bg-red-500/20 text-red-400 border-red-500/30 text-xs gap-1",children:[e.jsx(ye,{"code-path":"src/components/deploy/ToolConfigTab.tsx:216:27",className:"w-3 h-3"}),"失败"]}):e.jsxs(w,{"code-path":"src/components/deploy/ToolConfigTab.tsx:219:25",className:"bg-slate-500/20 text-slate-400 border-slate-500/30 text-xs gap-1",children:[e.jsx(ce,{"code-path":"src/components/deploy/ToolConfigTab.tsx:220:27",className:"w-3 h-3"}),"未安装"]})}),e.jsx("td",{"code-path":"src/components/deploy/ToolConfigTab.tsx:224:21",className:"px-3 py-2 text-right",children:e.jsxs("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:225:23",className:"flex justify-end gap-1",children:[s.install_method==="lazy"&&s.status!=="installed"&&(l?e.jsxs(d,{"code-path":"src/components/deploy/ToolConfigTab.tsx:228:29",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>v(s),disabled:h===s.id,children:[h===s.id?e.jsx(F,{"code-path":"src/components/deploy/ToolConfigTab.tsx:234:33",className:"w-3 h-3 animate-spin mr-1"}):e.jsx(I,{"code-path":"src/components/deploy/ToolConfigTab.tsx:236:33",className:"w-3 h-3 mr-1"}),"安装"]}):e.jsxs(d,{"code-path":"src/components/deploy/ToolConfigTab.tsx:241:29",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>y(s),disabled:h===s.id,children:[h===s.id?e.jsx(F,{"code-path":"src/components/deploy/ToolConfigTab.tsx:247:33",className:"w-3 h-3 animate-spin mr-1"}):e.jsx(I,{"code-path":"src/components/deploy/ToolConfigTab.tsx:249:33",className:"w-3 h-3 mr-1"}),"安装"]})),s.install_method==="lazy"&&e.jsxs(d,{"code-path":"src/components/deploy/ToolConfigTab.tsx:256:27",variant:"ghost",size:"sm",className:"h-7 text-xs text-[var(--dg-text-secondary)]",onClick:()=>T(s),disabled:C===s.id,children:[C===s.id?e.jsx(F,{"code-path":"src/components/deploy/ToolConfigTab.tsx:262:31",className:"w-3 h-3 animate-spin mr-1"}):e.jsx(de,{"code-path":"src/components/deploy/ToolConfigTab.tsx:264:31",className:"w-3 h-3 mr-1"}),"测试"]}),e.jsx(d,{"code-path":"src/components/deploy/ToolConfigTab.tsx:269:25",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>N(s),title:"检测",children:e.jsx(Ce,{"code-path":"src/components/deploy/ToolConfigTab.tsx:270:27",className:"w-3.5 h-3.5"})})]})})]},s.id)})})]})}),e.jsx(A,{"code-path":"src/components/deploy/ToolConfigTab.tsx:283:7",open:!!m,onOpenChange:()=>c(null),children:e.jsxs(H,{"code-path":"src/components/deploy/ToolConfigTab.tsx:284:9",className:"max-w-sm",children:[e.jsxs(M,{"code-path":"src/components/deploy/ToolConfigTab.tsx:285:11",children:[e.jsx(W,{"code-path":"src/components/deploy/ToolConfigTab.tsx:286:13",children:"选择安装版本"}),e.jsxs(re,{"code-path":"src/components/deploy/ToolConfigTab.tsx:287:13",children:[m?.tool.display_name," — 请选择要安装的版本"]})]}),e.jsxs("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:291:11",className:"space-y-4 py-2",children:[e.jsx("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:292:13",className:"space-y-2",children:m?.versions.map((s,l)=>e.jsxs("button",{"code-path":"src/components/deploy/ToolConfigTab.tsx:294:17",onClick:()=>u(s.version),className:`w-full flex items-center justify-between px-3 py-2.5 rounded-lg text-sm border transition-all ${g===s.version?"border-indigo-400/50 bg-indigo-400/10 text-[var(--dg-text-primary)]":"border-[var(--dg-border)] bg-[var(--dg-bg-secondary)] text-[var(--dg-text-secondary)] hover:border-[var(--dg-text-secondary)]/30"}`,children:[e.jsx("span",{"code-path":"src/components/deploy/ToolConfigTab.tsx:303:19",children:s.label}),e.jsx("span",{"code-path":"src/components/deploy/ToolConfigTab.tsx:304:19",className:"text-xs font-mono text-[var(--dg-text-muted)]",children:s.version})]},s.version))}),e.jsxs("div",{"code-path":"src/components/deploy/ToolConfigTab.tsx:308:13",className:"flex justify-end gap-2 pt-2 border-t border-[var(--dg-border)]",children:[e.jsx(d,{"code-path":"src/components/deploy/ToolConfigTab.tsx:309:15",variant:"outline",size:"sm",onClick:()=>c(null),children:"取消"}),e.jsxs(d,{"code-path":"src/components/deploy/ToolConfigTab.tsx:310:15",size:"sm",onClick:()=>m&&y(m.tool,g),disabled:!g||h===m?.tool.id,children:[h===m?.tool.id?e.jsx(F,{"code-path":"src/components/deploy/ToolConfigTab.tsx:316:19",className:"w-3.5 h-3.5 animate-spin mr-1"}):e.jsx(I,{"code-path":"src/components/deploy/ToolConfigTab.tsx:318:19",className:"w-3.5 h-3.5 mr-1"}),"安装"]})]})]})]})})]})}function ve({open:S,onClose:b,onSaved:L,editData:n}){const[h,j]=o.useState(""),[m,c]=o.useState(""),[g,u]=o.useState("development"),[C,f]=o.useState("#3B82F6"),[p,v]=o.useState(""),[y,N]=o.useState(50),[D,T]=o.useState(!1);o.useEffect(()=>{n?(j(n.name),c(n.display_name),u(n.type),f(n.color),v(n.description||""),N(n.sort_order)):(j(""),c(""),u("development"),f("#3B82F6"),v(""),N(50))},[n,S]);const s=async()=>{if(!h.trim()||!m.trim()){r.error("请填写名称");return}T(!0);try{n?await i.updateEnvironment(n.id,{name:h,display_name:m,type:g,color:C,sort_order:y,description:p}):await i.createEnvironment({name:h,display_name:m,type:g,color:C,sort_order:y,description:p}),r.success(n?"已更新":"已创建"),L(),b()}catch{r.error("操作失败")}finally{T(!1)}};return e.jsx(A,{"code-path":"src/components/deploy/DeployCredentials.tsx:67:5",open:S,onOpenChange:b,children:e.jsxs(H,{"code-path":"src/components/deploy/DeployCredentials.tsx:68:7",children:[e.jsx(M,{"code-path":"src/components/deploy/DeployCredentials.tsx:69:9",children:e.jsx(W,{"code-path":"src/components/deploy/DeployCredentials.tsx:69:23",children:n?"编辑环境":"新增环境"})}),e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:70:9",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:71:11",className:"space-y-1",children:[e.jsx(_,{"code-path":"src/components/deploy/DeployCredentials.tsx:71:38",children:"环境标识"}),e.jsx(z,{"code-path":"src/components/deploy/DeployCredentials.tsx:71:57",value:h,onChange:l=>j(l.target.value),placeholder:"production"})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:72:11",className:"space-y-1",children:[e.jsx(_,{"code-path":"src/components/deploy/DeployCredentials.tsx:72:38",children:"显示名称"}),e.jsx(z,{"code-path":"src/components/deploy/DeployCredentials.tsx:72:57",value:m,onChange:l=>c(l.target.value),placeholder:"生产环境"})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:73:11",className:"space-y-1",children:[e.jsx(_,{"code-path":"src/components/deploy/DeployCredentials.tsx:73:38",children:"环境类型"}),e.jsxs(K,{"code-path":"src/components/deploy/DeployCredentials.tsx:74:13",value:g,onValueChange:u,children:[e.jsx(X,{"code-path":"src/components/deploy/DeployCredentials.tsx:75:15",children:e.jsx(q,{"code-path":"src/components/deploy/DeployCredentials.tsx:75:30"})}),e.jsxs(J,{"code-path":"src/components/deploy/DeployCredentials.tsx:76:15",children:[e.jsx(E,{"code-path":"src/components/deploy/DeployCredentials.tsx:77:17",value:"production",children:"生产环境"}),e.jsx(E,{"code-path":"src/components/deploy/DeployCredentials.tsx:78:17",value:"staging",children:"预发布"}),e.jsx(E,{"code-path":"src/components/deploy/DeployCredentials.tsx:79:17",value:"testing",children:"测试环境"}),e.jsx(E,{"code-path":"src/components/deploy/DeployCredentials.tsx:80:17",value:"development",children:"开发环境"})]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:84:11",className:"space-y-1",children:[e.jsx(_,{"code-path":"src/components/deploy/DeployCredentials.tsx:84:38",children:"标志颜色"}),e.jsx(z,{"code-path":"src/components/deploy/DeployCredentials.tsx:84:57",value:C,onChange:l=>f(l.target.value),type:"color",className:"w-16 h-9 p-1"})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:85:11",className:"space-y-1",children:[e.jsx(_,{"code-path":"src/components/deploy/DeployCredentials.tsx:85:38",children:"排序序号"}),e.jsx(z,{"code-path":"src/components/deploy/DeployCredentials.tsx:85:57",value:y,onChange:l=>N(Number(l.target.value)),type:"number"})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:86:11",className:"space-y-1",children:[e.jsx(_,{"code-path":"src/components/deploy/DeployCredentials.tsx:86:38",children:"描述"}),e.jsx(z,{"code-path":"src/components/deploy/DeployCredentials.tsx:86:55",value:p,onChange:l=>v(l.target.value),placeholder:"可选"})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:88:9",className:"flex justify-end gap-2 mt-4",children:[e.jsx(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:89:11",variant:"outline",onClick:b,children:"取消"}),e.jsx(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:90:11",onClick:s,disabled:D,children:D?"...":n?"保存":"创建"})]})]})})}function Be(){const S=pe(),[b,L]=o.useState([]),[n,h]=o.useState([]),[j,m]=o.useState([]),[c,g]=o.useState(!1),[u,C]=o.useState(!1),[f,p]=o.useState("repo"),[v,y]=o.useState(null),[N,D]=o.useState(!1),[T,s]=o.useState(null),l=async()=>{g(!0);try{const[t,k,O]=await Promise.all([i.getRepos(),i.getRegistries(),i.getEnvironments()]);L(t?.list||[]),h(k?.list||[]),m(O?.list||[])}catch{r.error("获取数据失败")}finally{g(!1)}};o.useEffect(()=>{l()},[]);const x=async(t,k)=>{if(await S({title:"删除",description:`确定删除「${k.name||k.display_name}」?`,confirmText:"删除",variant:"destructive"}))try{t==="repo"?await i.deleteRepo(k.id):t==="registry"?await i.deleteRegistry(k.id):await i.deleteEnvironment(k.id),r.success("已删除"),l()}catch{r.error("删除失败")}},V={production:"生产",staging:"预发布",testing:"测试",development:"开发"};return e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:137:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:138:7",className:"flex items-center justify-between",children:[e.jsx("h2",{"code-path":"src/components/deploy/DeployCredentials.tsx:139:9",className:"text-lg font-semibold text-[var(--dg-text-primary)]",children:"发布配置管理"}),e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:140:9",className:"flex items-center gap-2",children:[e.jsxs(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:141:11",variant:"outline",size:"sm",onClick:l,children:[e.jsx(ee,{"code-path":"src/components/deploy/DeployCredentials.tsx:141:66",className:"w-4 h-4 mr-1"}),"刷新"]}),e.jsxs(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:142:11",size:"sm",onClick:()=>{p("repo"),y(null),C(!0)},children:[e.jsx(G,{"code-path":"src/components/deploy/DeployCredentials.tsx:143:13",className:"w-4 h-4 mr-1"}),"新增 Git 仓库"]}),e.jsxs(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:145:11",size:"sm",variant:"secondary",onClick:()=>{p("registry"),y(null),C(!0)},children:[e.jsx(G,{"code-path":"src/components/deploy/DeployCredentials.tsx:146:13",className:"w-4 h-4 mr-1"}),"新增镜像仓库"]})]})]}),e.jsxs(xe,{"code-path":"src/components/deploy/DeployCredentials.tsx:151:7",defaultValue:"repos",children:[e.jsxs(me,{"code-path":"src/components/deploy/DeployCredentials.tsx:152:9",children:[e.jsxs($,{"code-path":"src/components/deploy/DeployCredentials.tsx:153:11",value:"repos",className:"gap-1",children:[e.jsx(ie,{"code-path":"src/components/deploy/DeployCredentials.tsx:153:56",className:"w-4 h-4"}),"Git 仓库 (",b.length,")"]}),e.jsxs($,{"code-path":"src/components/deploy/DeployCredentials.tsx:154:11",value:"registries",className:"gap-1",children:[e.jsx(Z,{"code-path":"src/components/deploy/DeployCredentials.tsx:154:61",className:"w-4 h-4"}),"镜像仓库 (",n.length,")"]}),e.jsxs($,{"code-path":"src/components/deploy/DeployCredentials.tsx:155:11",value:"environments",className:"gap-1",children:[e.jsx(Y,{"code-path":"src/components/deploy/DeployCredentials.tsx:155:63",className:"w-4 h-4"}),"环境管理 (",j.length,")"]}),e.jsxs($,{"code-path":"src/components/deploy/DeployCredentials.tsx:156:11",value:"tools",className:"gap-1",children:[e.jsx(he,{"code-path":"src/components/deploy/DeployCredentials.tsx:156:56",className:"w-4 h-4"}),"工具配置"]})]}),e.jsx(B,{"code-path":"src/components/deploy/DeployCredentials.tsx:159:9",value:"repos",className:"mt-3",children:c?e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:160:22",className:"text-center py-8 text-[var(--dg-text-secondary)]",children:[e.jsx(F,{"code-path":"src/components/deploy/DeployCredentials.tsx:160:88",className:"w-5 h-5 animate-spin mx-auto mb-2"}),"加载中..."]}):b.length===0?e.jsx("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:161:34",className:"text-center py-8 text-[var(--dg-text-secondary)]",children:"暂无 Git 仓库认证配置"}):e.jsx("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:163:13",className:"rounded-md border border-[var(--dg-border)] overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/deploy/DeployCredentials.tsx:164:15",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/deploy/DeployCredentials.tsx:165:17",className:"bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]",children:e.jsxs("tr",{"code-path":"src/components/deploy/DeployCredentials.tsx:166:19",children:[e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:167:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"名称"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:168:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden md:table-cell",children:"仓库 URL"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:169:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"认证方式"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:170:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"状态"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:171:21",className:"px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/deploy/DeployCredentials.tsx:174:17",children:b.map(t=>e.jsxs("tr",{"code-path":"src/components/deploy/DeployCredentials.tsx:176:21",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50",children:[e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:177:23",className:"px-3 py-2 font-medium text-[var(--dg-text-primary)]",children:t.name}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:178:23",className:"px-3 py-2 text-[var(--dg-text-secondary)] hidden md:table-cell font-mono text-xs max-w-[300px] truncate",children:t.url}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:179:23",className:"px-3 py-2",children:e.jsx(w,{"code-path":"src/components/deploy/DeployCredentials.tsx:179:49",variant:"outline",className:"text-xs",children:t.auth_type})}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:180:23",className:"px-3 py-2",children:e.jsx(w,{"code-path":"src/components/deploy/DeployCredentials.tsx:181:25",className:t.enabled?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-slate-500/20 text-slate-400 border-slate-500/30",children:t.enabled?"启用":"禁用"})}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:183:23",className:"px-3 py-2 text-right",children:e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:184:25",className:"flex justify-end gap-1",children:[e.jsx(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:185:27",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{p("repo"),y(t.id),C(!0)},children:e.jsx(P,{"code-path":"src/components/deploy/DeployCredentials.tsx:185:165",className:"w-3.5 h-3.5"})}),e.jsx(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:186:27",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-500",onClick:()=>x("repo",t),children:e.jsx(U,{"code-path":"src/components/deploy/DeployCredentials.tsx:186:136",className:"w-3.5 h-3.5"})})]})})]},t.id))})]})})}),e.jsx(B,{"code-path":"src/components/deploy/DeployCredentials.tsx:197:9",value:"registries",className:"mt-3",children:c?e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:198:22",className:"text-center py-8 text-[var(--dg-text-secondary)]",children:[e.jsx(F,{"code-path":"src/components/deploy/DeployCredentials.tsx:198:88",className:"w-5 h-5 animate-spin mx-auto mb-2"}),"加载中..."]}):n.length===0?e.jsx("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:199:39",className:"text-center py-8 text-[var(--dg-text-secondary)]",children:"暂无镜像仓库认证配置"}):e.jsx("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:201:13",className:"rounded-md border border-[var(--dg-border)] overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/deploy/DeployCredentials.tsx:202:15",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/deploy/DeployCredentials.tsx:203:17",className:"bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]",children:e.jsxs("tr",{"code-path":"src/components/deploy/DeployCredentials.tsx:204:19",children:[e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:205:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"名称"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:206:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden md:table-cell",children:"Registry URL"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:207:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] hidden sm:table-cell",children:"命名空间"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:208:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"认证"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:209:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"状态"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:210:21",className:"px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/deploy/DeployCredentials.tsx:213:17",children:n.map(t=>e.jsxs("tr",{"code-path":"src/components/deploy/DeployCredentials.tsx:215:21",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50",children:[e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:216:23",className:"px-3 py-2 font-medium text-[var(--dg-text-primary)]",children:t.name}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:217:23",className:"px-3 py-2 text-[var(--dg-text-secondary)] hidden md:table-cell font-mono text-xs max-w-[250px] truncate",children:t.registry_url}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:218:23",className:"px-3 py-2 text-[var(--dg-text-secondary)] hidden sm:table-cell",children:t.namespace||"-"}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:219:23",className:"px-3 py-2",children:e.jsx(w,{"code-path":"src/components/deploy/DeployCredentials.tsx:219:49",variant:"outline",className:"text-xs",children:t.auth_type})}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:220:23",className:"px-3 py-2",children:e.jsx(w,{"code-path":"src/components/deploy/DeployCredentials.tsx:221:25",className:t.enabled?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-slate-500/20 text-slate-400 border-slate-500/30",children:t.enabled?"启用":"禁用"})}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:223:23",className:"px-3 py-2 text-right",children:e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:224:25",className:"flex justify-end gap-1",children:[e.jsx(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:225:27",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{p("registry"),y(t.id),C(!0)},children:e.jsx(P,{"code-path":"src/components/deploy/DeployCredentials.tsx:225:169",className:"w-3.5 h-3.5"})}),e.jsx(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:226:27",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-500",onClick:()=>x("registry",t),children:e.jsx(U,{"code-path":"src/components/deploy/DeployCredentials.tsx:226:140",className:"w-3.5 h-3.5"})})]})})]},t.id))})]})})}),e.jsxs(B,{"code-path":"src/components/deploy/DeployCredentials.tsx:238:9",value:"environments",className:"mt-3",children:[e.jsx("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:239:11",className:"flex items-center justify-end mb-3",children:e.jsxs(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:240:13",size:"sm",onClick:()=>{s(null),D(!0)},children:[e.jsx(G,{"code-path":"src/components/deploy/DeployCredentials.tsx:241:15",className:"w-4 h-4 mr-1"}),"新增环境"]})}),c?e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:244:22",className:"text-center py-8 text-[var(--dg-text-secondary)]",children:[e.jsx(F,{"code-path":"src/components/deploy/DeployCredentials.tsx:244:88",className:"w-5 h-5 animate-spin mx-auto mb-2"}),"加载中..."]}):j.length===0?e.jsx("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:245:41",className:"text-center py-8 text-[var(--dg-text-secondary)]",children:'暂无环境配置,点击"新增环境"创建'}):e.jsx("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:247:13",className:"rounded-md border border-[var(--dg-border)] overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/deploy/DeployCredentials.tsx:248:15",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/deploy/DeployCredentials.tsx:249:17",className:"bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]",children:e.jsxs("tr",{"code-path":"src/components/deploy/DeployCredentials.tsx:250:19",children:[e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:251:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"环境标识"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:252:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"显示名称"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:253:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"类型"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:254:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"颜色"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:255:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"排序"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:256:21",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)]",children:"状态"}),e.jsx("th",{"code-path":"src/components/deploy/DeployCredentials.tsx:257:21",className:"px-3 py-2 text-right font-medium text-[var(--dg-text-secondary)]",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/deploy/DeployCredentials.tsx:260:17",children:j.map(t=>e.jsxs("tr",{"code-path":"src/components/deploy/DeployCredentials.tsx:262:21",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50",children:[e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:263:23",className:"px-3 py-2 font-mono text-xs font-medium text-[var(--dg-text-primary)]",children:t.name}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:264:23",className:"px-3 py-2 text-[var(--dg-text-primary)]",children:e.jsxs("span",{"code-path":"src/components/deploy/DeployCredentials.tsx:265:25",className:"flex items-center gap-1.5",children:[e.jsx("span",{"code-path":"src/components/deploy/DeployCredentials.tsx:266:27",className:"w-2.5 h-2.5 rounded-full inline-block",style:{backgroundColor:t.color}}),t.display_name]})}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:270:23",className:"px-3 py-2",children:e.jsx(w,{"code-path":"src/components/deploy/DeployCredentials.tsx:270:49",variant:"secondary",className:"text-xs",children:V[t.type]||t.type})}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:271:23",className:"px-3 py-2",children:e.jsx("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:271:49",className:"w-6 h-6 rounded border",style:{backgroundColor:t.color}})}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:272:23",className:"px-3 py-2 text-[var(--dg-text-secondary)]",children:t.sort_order}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:273:23",className:"px-3 py-2",children:e.jsx(w,{"code-path":"src/components/deploy/DeployCredentials.tsx:274:25",className:t.enabled?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-slate-500/20 text-slate-400 border-slate-500/30",children:t.enabled?"启用":"禁用"})}),e.jsx("td",{"code-path":"src/components/deploy/DeployCredentials.tsx:276:23",className:"px-3 py-2 text-right",children:e.jsxs("div",{"code-path":"src/components/deploy/DeployCredentials.tsx:277:25",className:"flex justify-end gap-1",children:[e.jsx(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:278:27",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>{s(t),D(!0)},children:e.jsx(P,{"code-path":"src/components/deploy/DeployCredentials.tsx:278:144",className:"w-3.5 h-3.5"})}),e.jsx(d,{"code-path":"src/components/deploy/DeployCredentials.tsx:279:27",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-500",onClick:()=>x("env",t),children:e.jsx(U,{"code-path":"src/components/deploy/DeployCredentials.tsx:279:137",className:"w-3.5 h-3.5"})})]})})]},t.id))})]})})]}),e.jsx(B,{"code-path":"src/components/deploy/DeployCredentials.tsx:291:9",value:"tools",className:"mt-3",children:e.jsx(fe,{"code-path":"src/components/deploy/DeployCredentials.tsx:292:11"})})]}),e.jsx(be,{"code-path":"src/components/deploy/DeployCredentials.tsx:296:7",open:u,onOpenChange:C,type:f,editId:v,repos:b,registries:n,onSave:l}),e.jsx(ve,{"code-path":"src/components/deploy/DeployCredentials.tsx:301:7",open:N,onClose:()=>D(!1),onSaved:l,editData:T})]})}export{Be as default}; diff --git a/backend/static/assets/DeployRBAC-QV1xM1Jn.js b/backend/static/assets/DeployRBAC-QV1xM1Jn.js new file mode 100644 index 0000000..2ff3a5f --- /dev/null +++ b/backend/static/assets/DeployRBAC-QV1xM1Jn.js @@ -0,0 +1 @@ +import{g as Ne,r as o,a as ve,j as e,L as M,t as ae,B as a,a0 as D,I as h,a9 as fe,a5 as le,aa as we,u as be}from"./index-DfyorCky.js";import{C as g,a as N}from"./card-C55cvSHg.js";import{B as x}from"./badge-xNW8x0G1.js";import{S as v,a as f,b as w,c as b,d as r}from"./select-D5qUzdAs.js";import{L as i}from"./label-BK0h2apY.js";import{t as c}from"./index-a3ybMjbR.js";import{d as m,p as Se}from"./deploy-B3Sg3N1U.js";import{P as pe}from"./plus-CUG-9kpu.js";import{S as ne}from"./save-DoGGjfwC.js";import{T as ke}from"./trash-2-Dx32pOzT.js";import{U as de}from"./user-plus-BwUWtcQl.js";import"./index-CWVNW_qu.js";const Ie=[["path",{d:"M17 3v10",key:"15fgeh"}],["path",{d:"m12.67 5.5 8.66 5",key:"1gpheq"}],["path",{d:"m12.67 10.5 8.66-5",key:"1dkfa6"}],["path",{d:"M9 17a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2z",key:"swwfx4"}]],re=Ne("regex",Ie);function He(){const[p,me]=o.useState([]),[xe,T]=o.useState(!0),[S,A]=o.useState(!1),[y,ie]=o.useState([]),[n,k]=o.useState(null),[F,ye]=o.useState([]),[I,_]=o.useState([]),[l,he]=o.useState(""),[j,q]=o.useState(""),[G,H]=o.useState(!1),[J,z]=o.useState(!1),[P,X]=o.useState(""),[E,K]=o.useState(""),[C,O]=o.useState(""),[Q,W]=o.useState("editor"),[Y,Z]=o.useState(""),[Ce,U]=o.useState(null),[L,ee]=o.useState(""),[se,te]=o.useState(""),Re=ve(),R=async()=>{T(!0);try{const[s,t,d]=await Promise.all([m.getItemRoles(),Se.getPipelines({page_size:200}),be.getUsers({page_size:500})]);me(Array.isArray(s)?s:s?.list||s?.data||[]),ie(Array.isArray(t)?t:t?.list||t?.data||[]);const u=Array.isArray(d)?d:d?.list||d?.data||[];ye(u)}catch{}finally{T(!1)}};o.useEffect(()=>{R()},[]);const $=async()=>{if(!l){_([]);return}try{const s=await m.getUserItemRoles(Number(l));_(Array.isArray(s)?s:s?.data||s?.list||[])}catch{_([])}};o.useEffect(()=>{$()},[l]);const B=o.useMemo(()=>{const s={};return p.forEach(t=>{try{const d=new RegExp(t.pattern);s[t.id]=y.filter(u=>d.test(u.code)).map(u=>u.code)}catch{s[t.id]=[]}}),s},[p,y]),oe=(n?p.find(s=>s.id===n):null)?B[n]||[]:[],ue=async()=>{if(!P.trim()||!E.trim()||!C.trim()){c.error("名称、代码、正则表达式不能为空");return}A(!0);try{await m.createItemRole({name:P.trim(),code:E.trim(),pattern:C.trim(),role:Q,description:Y}),c.success("已创建"),z(!1),X(""),K(""),O(""),W("editor"),Z(""),R()}catch(s){c.error(s?.message||"创建失败")}finally{A(!1)}},Ae=async s=>{if(!L.trim()){c.error("正则不能为空");return}A(!0);try{await m.updateItemRole(s,{pattern:L,role:se}),c.success("已更新"),U(null),R()}catch(t){c.error(t?.message||"更新失败")}finally{A(!1)}},je=async s=>{if(await Re({title:"删除角色",description:`确定删除「${s.name}」?匹配 ${B[s.id]?.length||0} 条流水线`,variant:"destructive"}))try{await m.deleteItemRole(s.id),c.success("已删除"),R()}catch{c.error("删除失败")}},Be=async s=>{try{await m.updateItemRole(s.id,{status:s.status?0:1}),c.success(s.status?"已禁用":"已启用"),R()}catch{c.error("操作失败")}},De=async()=>{if(!l||!j){c.error("请选择用户和角色");return}H(!0);try{await m.assignItemRole(Number(l),{user_id:Number(l),item_role_id:Number(j)}),c.success("已分配"),q(""),$()}catch(s){c.error(s?.message||"分配失败")}finally{H(!1)}},ge=async s=>{try{await m.removeItemRole(Number(l),s),c.success("已撤销"),$()}catch{c.error("撤销失败")}},ce=s=>s==="owner"?"bg-amber-500/20 text-amber-400 border-amber-500/30":s==="editor"?"bg-blue-500/20 text-blue-400 border-blue-500/30":"bg-slate-500/20 text-slate-400 border-slate-500/30",V=F.find(s=>String(s.id)===l);return xe?e.jsx("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:167:23",className:"flex items-center justify-center py-20",children:e.jsx(M,{"code-path":"src/components/deploy/DeployRBAC.tsx:167:79",className:"w-6 h-6 animate-spin"})}):e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:170:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:172:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:173:9",children:[e.jsxs("h1",{"code-path":"src/components/deploy/DeployRBAC.tsx:174:11",className:"text-xl font-bold flex items-center gap-2 text-[var(--dg-text-primary)]",children:[e.jsx(ae,{"code-path":"src/components/deploy/DeployRBAC.tsx:175:13",className:"w-5 h-5 text-purple-500"}),"发布权限"]}),e.jsx("p",{"code-path":"src/components/deploy/DeployRBAC.tsx:177:11",className:"text-sm text-[var(--dg-text-secondary)] mt-1",children:"Jenkins-style Role Strategy — 按流水线 code 正则匹配分配角色"})]}),e.jsxs(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:181:9",onClick:()=>z(!0),disabled:J,children:[e.jsx(pe,{"code-path":"src/components/deploy/DeployRBAC.tsx:182:11",className:"w-4 h-4 mr-1"}),"新建角色"]})]}),e.jsx(g,{"code-path":"src/components/deploy/DeployRBAC.tsx:187:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(N,{"code-path":"src/components/deploy/DeployRBAC.tsx:188:9",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:189:11",className:"flex items-center gap-2 mb-3",children:[e.jsx(D,{"code-path":"src/components/deploy/DeployRBAC.tsx:190:13",className:"w-4 h-4 text-blue-500"}),e.jsx("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:191:13",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:"流水线命中预览"}),e.jsx("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:192:13",className:"text-xs text-[var(--dg-text-muted)]",children:"— 选择一个角色查看哪些流水线会被匹配"})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:194:11",className:"flex gap-2 mb-3 flex-wrap",children:[e.jsxs(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:195:13",variant:n===null?"secondary":"ghost",size:"sm",onClick:()=>k(null),children:["全部 (",y.length,")"]}),p.map(s=>e.jsxs(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:197:15",variant:n===s.id?"secondary":"ghost",size:"sm",onClick:()=>k(s.id),className:s.status===0?"opacity-40":"",children:[s.name," (",B[s.id]?.length||0,")"]},s.id))]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:203:11",className:"flex flex-wrap gap-1.5 max-h-32 overflow-y-auto",children:[n===null?y.map(s=>e.jsxs(x,{"code-path":"src/components/deploy/DeployRBAC.tsx:205:36",variant:"secondary",className:"text-xs",children:[e.jsx(D,{"code-path":"src/components/deploy/DeployRBAC.tsx:205:94",className:"w-3 h-3 mr-0.5"}),s.code]},s.id)):y.map(s=>{const t=oe.includes(s.code);return e.jsxs(x,{"code-path":"src/components/deploy/DeployRBAC.tsx:209:21",variant:t?"default":"secondary",className:`text-xs ${t?"bg-purple-500/20 text-purple-300 border-purple-500/30":"opacity-30"}`,children:[e.jsx(D,{"code-path":"src/components/deploy/DeployRBAC.tsx:211:23",className:"w-3 h-3 mr-0.5"}),s.code]},s.id)}),n!==null&&oe.length===0&&e.jsx("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:217:15",className:"text-xs text-red-400",children:"无匹配 — 请调整正则表达式"})]})]})}),J&&e.jsx(g,{"code-path":"src/components/deploy/DeployRBAC.tsx:225:9",className:"bg-[var(--dg-bg-secondary)] border-purple-500/20",children:e.jsxs(N,{"code-path":"src/components/deploy/DeployRBAC.tsx:226:11",className:"p-4 space-y-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:227:13",className:"flex items-center justify-between",children:[e.jsxs("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:228:15",className:"text-sm font-medium text-[var(--dg-text-primary)] flex items-center gap-2",children:[e.jsx(pe,{"code-path":"src/components/deploy/DeployRBAC.tsx:228:107",className:"w-4 h-4"}),"新建 Item Role"]}),e.jsx(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:229:15",variant:"ghost",size:"sm",onClick:()=>z(!1),children:"取消"})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:231:13",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:232:15",className:"space-y-1",children:[e.jsx(i,{"code-path":"src/components/deploy/DeployRBAC.tsx:232:42",className:"text-xs",children:"名称"}),e.jsx(h,{"code-path":"src/components/deploy/DeployRBAC.tsx:232:79",value:P,onChange:s=>X(s.target.value),placeholder:"如: backend",className:"h-8 text-sm"})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:233:15",className:"space-y-1",children:[e.jsx(i,{"code-path":"src/components/deploy/DeployRBAC.tsx:233:42",className:"text-xs",children:"代码 (唯一标识)"}),e.jsx(h,{"code-path":"src/components/deploy/DeployRBAC.tsx:233:86",value:E,onChange:s=>K(s.target.value),placeholder:"如: backend",className:"h-8 text-sm font-mono"})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:235:13",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:236:15",className:"space-y-1",children:[e.jsxs(i,{"code-path":"src/components/deploy/DeployRBAC.tsx:237:17",className:"text-xs flex items-center gap-1",children:[e.jsx(re,{"code-path":"src/components/deploy/DeployRBAC.tsx:237:68",className:"w-3 h-3"}),"正则匹配 Pattern"]}),e.jsx(h,{"code-path":"src/components/deploy/DeployRBAC.tsx:238:17",value:C,onChange:s=>{O(s.target.value)},placeholder:"如: ^cex-.*",className:"h-8 text-sm font-mono"}),C&&e.jsxs("p",{"code-path":"src/components/deploy/DeployRBAC.tsx:240:19",className:"text-xs text-[var(--dg-text-muted)]",children:["实时匹配: ",(()=>{try{const s=y.filter(t=>new RegExp(C).test(t.code)).length;return s>0?`✅ 命中 ${s} 条流水线`:"⚠️ 无匹配"}catch{return"❌ 正则语法错误"}})()]})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:245:15",className:"space-y-1",children:[e.jsx(i,{"code-path":"src/components/deploy/DeployRBAC.tsx:246:17",className:"text-xs",children:"角色"}),e.jsxs(v,{"code-path":"src/components/deploy/DeployRBAC.tsx:247:17",value:Q,onValueChange:W,children:[e.jsx(f,{"code-path":"src/components/deploy/DeployRBAC.tsx:248:19",className:"h-8 text-sm",children:e.jsx(w,{"code-path":"src/components/deploy/DeployRBAC.tsx:248:58"})}),e.jsxs(b,{"code-path":"src/components/deploy/DeployRBAC.tsx:249:19",children:[e.jsx(r,{"code-path":"src/components/deploy/DeployRBAC.tsx:250:21",value:"owner",children:"拥有者 (owner)"}),e.jsx(r,{"code-path":"src/components/deploy/DeployRBAC.tsx:251:21",value:"editor",children:"编辑者 (editor)"}),e.jsx(r,{"code-path":"src/components/deploy/DeployRBAC.tsx:252:21",value:"viewer",children:"查看者 (viewer)"})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:257:13",className:"space-y-1",children:[e.jsx(i,{"code-path":"src/components/deploy/DeployRBAC.tsx:257:40",className:"text-xs",children:"描述 (可选)"}),e.jsx(h,{"code-path":"src/components/deploy/DeployRBAC.tsx:257:82",value:Y,onChange:s=>Z(s.target.value),placeholder:"简要说明此角色的用途",className:"h-8 text-sm"})]}),e.jsxs(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:258:13",onClick:ue,disabled:S,className:"w-full",children:[S?e.jsx(M,{"code-path":"src/components/deploy/DeployRBAC.tsx:259:25",className:"w-4 h-4 mr-1 animate-spin"}):e.jsx(ne,{"code-path":"src/components/deploy/DeployRBAC.tsx:259:77",className:"w-4 h-4 mr-1"}),S?"创建中...":"创建"]})]})}),p.length===0?e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:268:9",className:"text-center py-12 text-[var(--dg-text-secondary)]",children:[e.jsx(ae,{"code-path":"src/components/deploy/DeployRBAC.tsx:269:11",className:"w-10 h-10 mx-auto mb-2 opacity-20"}),e.jsx("p",{"code-path":"src/components/deploy/DeployRBAC.tsx:270:11",className:"text-sm",children:"暂无 Item Role"})]}):e.jsx("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:273:9",className:"space-y-2",children:p.map(s=>e.jsx(g,{"code-path":"src/components/deploy/DeployRBAC.tsx:275:13",className:`bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] ${s.status===0?"opacity-50":""}`,children:e.jsx(N,{"code-path":"src/components/deploy/DeployRBAC.tsx:276:15",className:"p-3",children:e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:277:17",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:278:19",className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:279:21",className:"w-9 h-9 rounded-lg bg-purple-500/20 flex items-center justify-center shrink-0",children:e.jsx(re,{"code-path":"src/components/deploy/DeployRBAC.tsx:280:23",className:"w-4 h-4 text-purple-400"})}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:282:21",className:"min-w-0",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:283:23",className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:284:25",className:"text-sm font-semibold text-[var(--dg-text-primary)]",children:s.name}),e.jsx(x,{"code-path":"src/components/deploy/DeployRBAC.tsx:285:25",className:`text-xs border ${ce(s.role)}`,children:s.role==="owner"?"拥有者":s.role==="editor"?"编辑者":"查看者"}),s.status===0&&e.jsx(x,{"code-path":"src/components/deploy/DeployRBAC.tsx:286:47",variant:"secondary",className:"text-xs text-red-400",children:"已禁用"}),e.jsxs(x,{"code-path":"src/components/deploy/DeployRBAC.tsx:287:25",variant:"secondary",className:"text-xs cursor-pointer",onClick:()=>k(n===s.id?null:s.id),children:[e.jsx(D,{"code-path":"src/components/deploy/DeployRBAC.tsx:288:27",className:"w-3 h-3 mr-0.5"}),B[s.id]?.length||0," 条"]})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:291:23",className:"text-xs text-[var(--dg-text-secondary)] mt-0.5 truncate",children:[e.jsx("code",{"code-path":"src/components/deploy/DeployRBAC.tsx:292:25",className:"font-mono text-purple-400 bg-purple-500/10 px-1 rounded",children:s.code}),e.jsx("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:293:25",className:"mx-1",children:"→"}),e.jsx("code",{"code-path":"src/components/deploy/DeployRBAC.tsx:294:25",className:"font-mono text-blue-400 bg-blue-500/10 px-1 rounded",children:s.pattern}),s.description&&e.jsx("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:295:46",className:"ml-2 opacity-60",children:s.description})]})]})]}),e.jsx("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:299:19",className:"flex items-center gap-1 shrink-0",children:Ce===s.id?e.jsxs(e.Fragment,{children:[e.jsx(h,{"code-path":"src/components/deploy/DeployRBAC.tsx:302:25",value:L,onChange:t=>ee(t.target.value),className:"h-7 w-36 text-xs font-mono",placeholder:"正则表达式"}),e.jsxs(v,{"code-path":"src/components/deploy/DeployRBAC.tsx:303:25",value:se,onValueChange:te,children:[e.jsx(f,{"code-path":"src/components/deploy/DeployRBAC.tsx:304:27",className:"h-7 w-20 text-xs",children:e.jsx(w,{"code-path":"src/components/deploy/DeployRBAC.tsx:304:71"})}),e.jsxs(b,{"code-path":"src/components/deploy/DeployRBAC.tsx:305:27",children:[e.jsx(r,{"code-path":"src/components/deploy/DeployRBAC.tsx:306:29",value:"owner",children:"拥有者"}),e.jsx(r,{"code-path":"src/components/deploy/DeployRBAC.tsx:307:29",value:"editor",children:"编辑者"}),e.jsx(r,{"code-path":"src/components/deploy/DeployRBAC.tsx:308:29",value:"viewer",children:"查看者"})]})]}),e.jsx(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:311:25",size:"icon",variant:"ghost",className:"h-7 w-7 text-green-400",onClick:()=>Ae(s.id),children:e.jsx(fe,{"code-path":"src/components/deploy/DeployRBAC.tsx:311:134",className:"w-3.5 h-3.5"})}),e.jsx(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:312:25",size:"icon",variant:"ghost",className:"h-7 w-7 text-red-400",onClick:()=>U(null),children:e.jsx(le,{"code-path":"src/components/deploy/DeployRBAC.tsx:312:127",className:"w-3.5 h-3.5"})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:316:25",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{U(s.id),ee(s.pattern),te(s.role)},children:[e.jsx(ne,{"code-path":"src/components/deploy/DeployRBAC.tsx:316:178",className:"w-3 h-3 mr-1"}),"编辑"]}),e.jsx(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:317:25",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>Be(s),children:s.status?"禁用":"启用"}),e.jsx(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:318:25",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-500",onClick:()=>je(s),children:e.jsx(ke,{"code-path":"src/components/deploy/DeployRBAC.tsx:318:129",className:"w-3.5 h-3.5"})})]})})]})})},s.id))}),e.jsx(g,{"code-path":"src/components/deploy/DeployRBAC.tsx:330:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(N,{"code-path":"src/components/deploy/DeployRBAC.tsx:331:9",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:332:11",className:"flex items-center gap-2 mb-3",children:[e.jsx(de,{"code-path":"src/components/deploy/DeployRBAC.tsx:333:13",className:"w-4 h-4 text-amber-400"}),e.jsx("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:334:13",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:"分配角色给用户"})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:336:11",className:"flex gap-3 items-end mb-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:337:13",className:"space-y-1 flex-1",children:[e.jsx(i,{"code-path":"src/components/deploy/DeployRBAC.tsx:338:15",className:"text-xs",children:"选择用户"}),e.jsxs(v,{"code-path":"src/components/deploy/DeployRBAC.tsx:339:15",value:l,onValueChange:he,children:[e.jsx(f,{"code-path":"src/components/deploy/DeployRBAC.tsx:340:17",className:"h-8 text-sm",children:e.jsx(w,{"code-path":"src/components/deploy/DeployRBAC.tsx:340:56",placeholder:"选择用户..."})}),e.jsxs(b,{"code-path":"src/components/deploy/DeployRBAC.tsx:341:17",className:"max-h-60",children:[e.jsx("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:342:19",className:"px-2 py-1.5 sticky top-0 bg-popover z-10",children:e.jsx(h,{"code-path":"src/components/deploy/DeployRBAC.tsx:342:77",placeholder:"搜索用户...",className:"h-7 text-xs"})}),F.map(s=>e.jsxs(r,{"code-path":"src/components/deploy/DeployRBAC.tsx:344:21",value:String(s.id),children:[s.real_name||s.username," (",s.username,")",I.some(t=>t.user_id===s.id)&&e.jsx("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:346:69",className:"ml-2 text-xs text-purple-400",children:"已分配"})]},s.id))]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:352:13",className:"space-y-1 w-48",children:[e.jsx(i,{"code-path":"src/components/deploy/DeployRBAC.tsx:353:15",className:"text-xs",children:"Item Role"}),e.jsxs(v,{"code-path":"src/components/deploy/DeployRBAC.tsx:354:15",value:j,onValueChange:q,children:[e.jsx(f,{"code-path":"src/components/deploy/DeployRBAC.tsx:355:17",className:"h-8 text-sm",children:e.jsx(w,{"code-path":"src/components/deploy/DeployRBAC.tsx:355:56",placeholder:"选择角色"})}),e.jsx(b,{"code-path":"src/components/deploy/DeployRBAC.tsx:356:17",children:p.filter(s=>s.status===1).map(s=>e.jsxs(r,{"code-path":"src/components/deploy/DeployRBAC.tsx:358:21",value:String(s.id),children:[s.name," (",s.role,")"]},s.id))})]})]}),e.jsxs(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:363:13",className:"h-8",onClick:De,disabled:G||!l||!j,children:[G?e.jsx(M,{"code-path":"src/components/deploy/DeployRBAC.tsx:364:32",className:"w-3.5 h-3.5 mr-1 animate-spin"}):e.jsx(de,{"code-path":"src/components/deploy/DeployRBAC.tsx:364:88",className:"w-3.5 h-3.5 mr-1"}),"分配"]})]}),V&&e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:371:13",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:372:15",className:"flex items-center gap-2 mb-2",children:[e.jsxs(x,{"code-path":"src/components/deploy/DeployRBAC.tsx:373:17",variant:"secondary",className:"text-xs",children:[e.jsx(we,{"code-path":"src/components/deploy/DeployRBAC.tsx:374:19",className:"w-3 h-3 mr-1"}),V.real_name||V.username]}),e.jsx("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:376:17",className:"text-xs text-[var(--dg-text-muted)]",children:"已分配角色:"})]}),I.length===0?e.jsx("p",{"code-path":"src/components/deploy/DeployRBAC.tsx:379:17",className:"text-xs text-[var(--dg-text-muted)] py-2",children:"该用户尚未分配任何 Item Role"}):e.jsx("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:381:17",className:"space-y-1",children:I.map(s=>{const t=s.item_role||p.find(d=>d.id===s.item_role_id);return e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:385:23",className:"flex items-center justify-between py-1.5 px-2 rounded bg-[var(--dg-bg-tertiary)] text-xs",children:[e.jsxs("div",{"code-path":"src/components/deploy/DeployRBAC.tsx:386:25",className:"flex items-center gap-2",children:[e.jsx(x,{"code-path":"src/components/deploy/DeployRBAC.tsx:387:27",className:`text-xs border ${ce(t?.role||"viewer")}`,children:t?.role==="owner"?"拥有者":t?.role==="editor"?"编辑者":"查看者"}),e.jsx("span",{"code-path":"src/components/deploy/DeployRBAC.tsx:390:27",className:"text-[var(--dg-text-primary)]",children:t?.name||`#${s.item_role_id}`}),t&&e.jsx("code",{"code-path":"src/components/deploy/DeployRBAC.tsx:392:29",className:"font-mono text-[var(--dg-text-muted)] bg-[var(--dg-bg-primary)] px-1 rounded text-xs",children:t.pattern})]}),e.jsx(a,{"code-path":"src/components/deploy/DeployRBAC.tsx:397:25",variant:"ghost",size:"icon",className:"h-6 w-6 text-red-400",onClick:()=>ge(s.id),children:e.jsx(le,{"code-path":"src/components/deploy/DeployRBAC.tsx:398:27",className:"w-3 h-3"})})]},s.id)})})]})]})})]})}export{He as default}; diff --git a/backend/static/assets/DeploymentDetailPage--48QYro1.js b/backend/static/assets/DeploymentDetailPage--48QYro1.js new file mode 100644 index 0000000..6dd1532 --- /dev/null +++ b/backend/static/assets/DeploymentDetailPage--48QYro1.js @@ -0,0 +1,20 @@ +import{g as Fe,r as m,v as ot,N as Se,A as Zt,j as e,B as u,I as v,L as xe,a4 as Qt,n as es,H as ts,x as ss,R as bs,o as ys,t as ns,V as os,G as tt,q as jt,E as vt,O as ks,M as vs,a3 as gt,a0 as xt,k as as,aT as gs,T as Mt,a7 as Ds,a5 as cs,W as Nt,i as js}from"./index-DfyorCky.js";import{C as L,a as G,b as ie,c as pe}from"./card-C55cvSHg.js";import{L as C}from"./label-BK0h2apY.js";import{B as se}from"./badge-xNW8x0G1.js";import{k as te}from"./kubernetes-J8O09fK7.js";import{u as Pe}from"./use-toast-CrSOP4cJ.js";import{S as we,f as Ye,e as Ns,b as fs,s as ht,Y as zt,P as Es,a as ws}from"./PodFileBrowser-BySN2XGN.js";import{T as Re,a as Be,b as De,c as X,d as Oe,e as Z}from"./table-5sHV4Akp.js";import{P as ae}from"./plus-CUG-9kpu.js";import{H as Cs}from"./history-D_9jPUQg.js";import{M as ft}from"./minus-UVrx3jLc.js";import{F as Et}from"./file-text-C9G5abwR.js";import{H as rs}from"./hard-drive-BbPmnARR.js";import{E as Dt}from"./external-link-CzIpMNu1.js";import{T as st}from"./textarea-NXY8u32k.js";import{S as Le,a as Ge,b as nt,c as He,d as ve}from"./select-D5qUzdAs.js";import{S as wt}from"./switch-CGiGgOnh.js";import{T as ue}from"./trash-2-Dx32pOzT.js";import{P as ls}from"./play-cdPayOtJ.js";import{S as at}from"./save-DoGGjfwC.js";import{R as ds}from"./rotate-cw-5qcj_h_q.js";import{Z as is}from"./zap-D2uWSK32.js";import{F as Ss}from"./folder-open-IMBifk-r.js";import{D as Ps}from"./disc-EsE6x5Oh.js";import{F as As,a as ut}from"./folder-DoMwqvzv.js";import{R as ct}from"./refresh-cw-DUB_tAG-.js";import{C as Vs}from"./circle-x-DK79Dhg2.js";import{A as Ws}from"./arrow-left-BDgGyrD0.js";import{P as _t}from"./pause-D_famo9P.js";import"./copy-DXW4LnkN.js";import"./sparkles-Bld4NX5y.js";import"./xterm-DSqgeKvr.js";import"./box-TTGA1p57.js";import"./minimize-2-CiCQYRfn.js";import"./upload-Ba6rlaGS.js";import"./download-DoZfYs2h.js";import"./index-CWVNW_qu.js";const Ts=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],Rs=Fe("hash",Ts);const Bs=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}]],Os=Fe("heart",Bs);const Is=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]],Ms=Fe("image",Is);const zs=[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]],_s=Fe("key-round",zs);const $s=[["path",{d:"M13.172 2a2 2 0 0 1 1.414.586l6.71 6.71a2.4 2.4 0 0 1 0 3.408l-4.592 4.592a2.4 2.4 0 0 1-3.408 0l-6.71-6.71A2 2 0 0 1 6 9.172V3a1 1 0 0 1 1-1z",key:"16rjxf"}],["path",{d:"M2 7v6.172a2 2 0 0 0 .586 1.414l6.71 6.71a2.4 2.4 0 0 0 3.191.193",key:"178nd4"}],["circle",{cx:"10.5",cy:"6.5",r:".5",fill:"currentColor",key:"12ikhr"}]],$t=Fe("tags",$s);function ps(t){const s=t.conditions||t.pod_conditions||[],o=n=>s.find(d=>(d.type||d.Type)===n),a=n=>n?.lastTransitionTime||n?.LastTransitionTime||n?.last_transition_time;return{scheduled:a(o("PodScheduled")||{}),initialized:a(o("Initialized")||{}),containersReady:a(o("ContainersReady")||{}),ready:a(o("Ready")||{}),startTime:t.start_time||t.startTime}}function Ls(t){const{clusterCode:s,namespace:o,deployment:a,pods:n,revisions:d,onRefresh:i}=t,{toast:p}=Pe(),[D,h]=m.useState("pods"),[N,I]=m.useState(null),[q,V]=m.useState(null),[R,M]=m.useState(a?.replicas||0),[z,F]=m.useState(!1),[B,U]=m.useState([]),[Y,S]=m.useState([]),[Q,O]=m.useState([]),[H,ne]=m.useState(""),[oe,r]=m.useState([]),[b,f]=m.useState([]),P=a?.ready_replicas??a?.readyReplicas??0,l=a?.replicas??0,w=P===l&&l>0;m.useEffect(()=>{D==="services"&&(ne("services"),Promise.all([te.getNamespaceServices(s,o).catch(()=>[]),te.getNamespaceIngresses(s,o).catch(()=>[])]).then(([y,J])=>{const _=A=>Array.isArray(A)?A:A?.list||A?.items||A?.data||[],$=_(y),be=_(J),K=a?.spec?.selector?.matchLabels||a?.spec?.template?.metadata?.labels||{},he=$.filter(A=>{const ce=A.spec?.selector||A.selector||{};return Object.keys(ce).length===0?!1:Object.entries(ce).every(([ge,fe])=>K[ge]===fe)}).map(A=>({name:A.name||A.metadata?.name,type:A.spec?.type||A.type||"ClusterIP",clusterIP:A.spec?.clusterIP||A.cluster_ip||"",ports:(A.spec?.ports||A.ports||[]).map(ce=>`${ce.port}${ce.targetPort?":"+ce.targetPort:""}/${ce.protocol||"TCP"}`),selector:A.spec?.selector||A.selector||{},age:A.age||""})),Ne=new Set(he.map(A=>A.name)),de=be.filter(A=>(A.spec?.rules||A.rules||[]).some(ge=>(ge.http?.paths||ge.paths||[]).some(fe=>{const g=fe.backend?.service?.name||fe.backendService||"";return Ne.has(g)}))).map(A=>({name:A.name||A.metadata?.name,className:A.spec?.ingressClassName||A.ingressClass||"-",hosts:(A.spec?.rules||A.rules||[]).map(ce=>ce.host).filter(Boolean),rules:A.spec?.rules||A.rules||[],age:A.age||""}));U(he),S(de)}).catch(()=>{}).finally(()=>ne("")))},[D,s,o,a]),m.useEffect(()=>{D==="events"&&(ne("events"),te.getEvents(s,o,void 0).then(y=>{const _=(Array.isArray(y)?y:y?.list||y?.items||y?.data||[]).filter($=>{const K=($.involvedObject||$.involved_object||{}).name||"";return K===a?.name||K.startsWith(a?.name+"-")}).map($=>({type:$.type||"Normal",reason:$.reason||"",message:$.message||"",source:$.source?.component||$.sourceComponent||"-",firstTimestamp:$.firstTimestamp||$.first_timestamp||"",lastTimestamp:$.lastTimestamp||$.last_timestamp||"",count:$.count||1}));O(_)}).catch(()=>{}).finally(()=>ne("")))},[D,s,o,a?.name]),m.useEffect(()=>{D==="scale"&&(ne("scale"),Promise.all([te.getHPAs(s,o).catch(()=>[]),Promise.resolve([])]).then(([y])=>{const _=(be=>Array.isArray(be)?be:be?.list||be?.items||be?.data||[])(y),$=a?.name||"";r(_.filter(be=>(be.scaleTargetRef?.name||be.targetRef?.name||"")===$)),f([])}).catch(()=>{}).finally(()=>ne("")))},[D,s,o,a?.name]);const T=async y=>{const J=y.revision??y.revision_number??y.number;if(confirm(`确认回滚到修订版本 #${J}?`)){V(J);try{await te.rollbackDeployment(s,o,a.name,Number(J)),p({title:"回滚已下发",description:`正在回滚到 #${J}`}),i()}catch(_){p({title:"回滚失败",description:_?.message||String(_),variant:"destructive"})}finally{V(null)}}},c=async()=>{F(!0);try{await te.scaleDeployment(s,o,a.name,R),p({title:"伸缩已提交",description:`副本数 → ${R}`}),i()}catch(y){p({title:"伸缩失败",description:y?.message||String(y),variant:"destructive"})}finally{F(!1)}},k=[{key:"pods",label:"容器组",icon:ot,count:n.length},{key:"services",label:"访问方式",icon:Se,count:B.length},{key:"events",label:"事件",icon:Zt,count:Q.length},{key:"scale",label:"容器伸缩",icon:ae},{key:"history",label:"历史版本",icon:Cs,count:d.length}];return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:225:5",className:"space-y-4",children:[e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentView.tsx:227:7",className:"dg-card",children:e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentView.tsx:228:9",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:229:11",className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3 text-sm",children:[e.jsx(Te,{"code-path":"src/components/kubernetes/DeploymentView.tsx:230:13",label:"状态",value:e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentView.tsx:231:15",style:{background:`${w?we.green:we.orange}22`,color:w?we.green:we.orange,border:`1px solid ${w?we.green:we.orange}44`},children:w?"Running":"Updating"})}),e.jsx(Te,{"code-path":"src/components/kubernetes/DeploymentView.tsx:235:13",label:"副本",value:e.jsxs("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:235:41",className:"font-mono",children:[P,"/",l]})}),e.jsx(Te,{"code-path":"src/components/kubernetes/DeploymentView.tsx:236:13",label:"策略",value:a?.strategy||"RollingUpdate"}),n[0]&&e.jsxs(e.Fragment,{children:[e.jsx(Te,{"code-path":"src/components/kubernetes/DeploymentView.tsx:239:17",label:"所在节点",value:e.jsx("button",{"code-path":"src/components/kubernetes/DeploymentView.tsx:240:19",className:"text-[var(--dg-blue)] hover:underline",onClick:()=>window.open(`/kubernetes/${s}/nodes/${n[0].node_name||n[0].node}`,"_blank"),children:n[0].node_name||n[0].node||"-"})}),e.jsx(Te,{"code-path":"src/components/kubernetes/DeploymentView.tsx:244:17",label:"容器组 IP",value:e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:244:49",className:"font-mono",children:n[0].ip||n[0].pod_ip||"-"})})]}),e.jsx(Te,{"code-path":"src/components/kubernetes/DeploymentView.tsx:247:13",label:"创建时间",value:Ye(a?.created_at||a?.creationTimestamp)})]}),n[0]&&e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:251:13",className:"mt-3 pt-3 border-t border-[var(--dg-border)]",children:e.jsx(ms,{"code-path":"src/components/kubernetes/DeploymentView.tsx:252:15",pod:n[0]})})]})}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:259:7",className:"flex items-center gap-0.5 border-b border-[var(--dg-border)] overflow-x-auto",children:[k.map(y=>e.jsxs("button",{"code-path":"src/components/kubernetes/DeploymentView.tsx:261:11",className:`flex items-center gap-1.5 px-4 py-2.5 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${D===y.key?"border-[var(--dg-blue)] text-[var(--dg-blue)]":"border-transparent text-[var(--dg-text-muted)] hover:text-[var(--dg-text-secondary)]"}`,onClick:()=>h(y.key),children:[e.jsx(y.icon,{"code-path":"src/components/kubernetes/DeploymentView.tsx:270:13",className:"h-4 w-4"}),y.label,y.key==="pods"&&e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentView.tsx:272:34",className:"ml-1 text-[10px] px-1.5 py-0 bg-[var(--dg-bg-tertiary)] text-[var(--dg-text-muted)]",children:y.count})]},y.key)),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:276:9",className:"ml-auto flex items-center gap-1 pr-2 shrink-0",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentView.tsx:277:11",variant:"ghost",size:"icon",className:"h-7 w-7 text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)]",disabled:z||R<=0,onClick:()=>M(y=>Math.max(0,y-1)),children:e.jsx(ft,{"code-path":"src/components/kubernetes/DeploymentView.tsx:280:13",className:"h-4 w-4"})}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentView.tsx:282:11",type:"number",min:0,value:R,onChange:y=>M(Math.max(0,Number(y.target.value))),className:"w-16 h-7 text-center text-sm font-bold bg-slate-800 border-slate-700 text-slate-200"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentView.tsx:287:11",variant:"ghost",size:"icon",className:"h-7 w-7 text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)]",disabled:z,onClick:()=>M(y=>y+1),children:e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentView.tsx:290:13",className:"h-4 w-4"})}),R!==l&&e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentView.tsx:293:13",size:"sm",className:"h-7 text-xs bg-[var(--dg-blue)] hover:bg-[var(--dg-blue-hover)]",disabled:z,onClick:c,children:z?e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:295:31",className:"h-3 w-3 animate-spin"}):"应用"})]})]}),D==="pods"&&e.jsx(Gs,{"code-path":"src/components/kubernetes/DeploymentView.tsx:302:26",...t,expandedPod:N,setExpandedPod:I}),D==="services"&&e.jsx(Hs,{"code-path":"src/components/kubernetes/DeploymentView.tsx:303:30",services:B,ingresses:Y,loading:H,namespace:o}),D==="events"&&e.jsx(Fs,{"code-path":"src/components/kubernetes/DeploymentView.tsx:304:28",events:Q,loading:H}),D==="scale"&&e.jsx(Ys,{"code-path":"src/components/kubernetes/DeploymentView.tsx:306:9",hpas:oe,cronHpas:b,loading:H,replicas:l}),D==="history"&&e.jsx(Js,{"code-path":"src/components/kubernetes/DeploymentView.tsx:313:29",revisions:d,rollbackLoading:q,onRollback:T})]})}function Te({label:t,value:s}){return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:321:5",children:[e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentView.tsx:322:7",className:"text-xs text-[var(--dg-text-muted)] mb-1",children:t}),e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:323:7",className:"text-sm text-[var(--dg-text-primary)]",children:s})]})}function ms({pod:t}){const s=ps(t),o=[{label:"已调度",ts:s.scheduled,color:we.blue},{label:"已初始化",ts:s.initialized,color:we.orange},{label:"容器已就绪",ts:s.containersReady,color:we.green},{label:"容器组已就绪",ts:s.ready,color:we.green}];return e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:338:5",className:"flex items-center gap-2 overflow-x-auto",children:o.map((a,n)=>{const d=o[n-1],i=Ns(d?.ts,a.ts);return e.jsxs(m.Fragment,{"code-path":"src/components/kubernetes/DeploymentView.tsx:343:11",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:344:13",className:"flex flex-col items-center min-w-[80px]",children:[e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:345:15",className:"h-2 w-2 rounded-full",style:{background:a.ts?a.color:"#334155"}}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:346:15",className:"text-[10px] mt-1 font-medium",style:{color:a.ts?a.color:"#475569"},children:a.label}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:347:15",className:"text-[9px] text-[var(--dg-text-muted)]",children:a.ts?Ye(a.ts):"-"})]}),n{const D=ps(p),h=d===p.name,N=p.node_name||p.node;return e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentView.tsx:374:11",className:"dg-card",children:e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentView.tsx:375:13",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:377:15",className:"flex items-center gap-3",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentView.tsx:378:17",variant:"ghost",size:"icon",className:"h-6 w-6 text-[var(--dg-text-muted)]",onClick:()=>i(h?null:p.name),children:h?e.jsx(Qt,{"code-path":"src/components/kubernetes/DeploymentView.tsx:379:31",className:"h-4 w-4"}):e.jsx(es,{"code-path":"src/components/kubernetes/DeploymentView.tsx:379:69",className:"h-4 w-4"})}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:381:17",className:"font-mono text-sm text-[var(--dg-text-primary)]",children:p.name}),e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentView.tsx:382:17",style:{background:`${ht(p.status)}22`,color:ht(p.status),border:`1px solid ${ht(p.status)}44`},children:p.status||"Unknown"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:385:17",className:"text-xs text-[var(--dg-text-muted)]",children:e.jsx("button",{"code-path":"src/components/kubernetes/DeploymentView.tsx:386:19",className:"text-[var(--dg-blue)] hover:underline mr-2",onClick:()=>window.open(`/kubernetes/${t}/nodes/${N}`,"_blank"),children:N||"-"})}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:390:17",className:"text-xs font-mono text-[var(--dg-text-muted)]",children:p.ip||p.pod_ip||"-"}),e.jsxs("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:391:17",className:"text-xs text-[var(--dg-text-muted)]",children:["重启 ",p.restart_count||0," 次"]}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:392:17",className:"text-xs text-[var(--dg-text-muted)]",children:Ye(D.startTime||p.created_at)}),e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:393:17",className:"flex-1"}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentView.tsx:394:17",variant:"ghost",size:"sm",className:"h-7 text-xs text-[var(--dg-blue)]",onClick:()=>o(p),children:[e.jsx(Et,{"code-path":"src/components/kubernetes/DeploymentView.tsx:395:19",className:"h-3.5 w-3.5 mr-1"}),"日志"]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentView.tsx:397:17",variant:"ghost",size:"sm",className:"h-7 text-xs text-emerald-400",onClick:()=>a(p),children:[e.jsx(ts,{"code-path":"src/components/kubernetes/DeploymentView.tsx:398:19",className:"h-3.5 w-3.5 mr-1"}),"终端"]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentView.tsx:400:17",variant:"ghost",size:"sm",className:"h-7 text-xs text-amber-400",onClick:()=>n(p),children:[e.jsx(rs,{"code-path":"src/components/kubernetes/DeploymentView.tsx:401:19",className:"h-3.5 w-3.5 mr-1"}),"文件"]})]}),h&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:406:17",className:"mt-3 pt-3 border-t border-[var(--dg-border)]",children:[e.jsx(ms,{"code-path":"src/components/kubernetes/DeploymentView.tsx:407:19",pod:p}),p.containers&&p.containers.length>0&&e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:410:21",className:"mt-3 grid grid-cols-1 md:grid-cols-2 gap-2",children:p.containers.map((I,q)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:412:25",className:"p-2 rounded bg-[var(--dg-bg-tertiary)] text-xs",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:413:27",className:"flex items-center justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:414:29",className:"font-medium text-[var(--dg-text-primary)]",children:I.name}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:415:29",className:I.ready?"text-emerald-400":"text-[var(--dg-text-muted)]",children:I.ready?"Ready":"Pending"})]}),e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:417:27",className:"text-[var(--dg-text-muted)] mt-1",children:I.image}),I.resources&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:419:29",className:"mt-1 flex gap-3",children:[e.jsxs("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:420:31",children:["CPU: ",I.resources?.requests?.cpu||"0","/",I.resources?.limits?.cpu||"-"," m"]}),e.jsxs("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:421:31",children:["内存: ",I.resources?.requests?.memory||"0","/",I.resources?.limits?.memory||"-"]})]})]},q))})]})]})},p.name)})})}function Hs({services:t,ingresses:s,loading:o}){return o==="services"?e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:441:12",className:"flex items-center justify-center py-12",children:e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:441:68",className:"h-6 w-6 animate-spin text-[var(--dg-text-muted)]"})}):e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:444:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:446:7",children:[e.jsxs("h3",{"code-path":"src/components/kubernetes/DeploymentView.tsx:447:9",className:"text-sm font-semibold text-[var(--dg-text-primary)] mb-3 flex items-center gap-2",children:[e.jsx(Se,{"code-path":"src/components/kubernetes/DeploymentView.tsx:448:11",className:"h-4 w-4 text-[var(--dg-blue)]"}),"关联 Service"]}),t.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentView.tsx:451:11",className:"text-sm text-[var(--dg-text-muted)] py-4",children:"暂无匹配的 Service(Deployment 选择器未关联任何 Service)"}):e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:453:11",className:"overflow-x-auto",children:e.jsxs(Re,{"code-path":"src/components/kubernetes/DeploymentView.tsx:454:13",children:[e.jsx(Be,{"code-path":"src/components/kubernetes/DeploymentView.tsx:455:15",children:e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:456:17",className:"border-[var(--dg-border)]",children:[e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:457:19",className:"text-[var(--dg-text-muted)]",children:"名称"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:458:19",className:"text-[var(--dg-text-muted)]",children:"类型"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:459:19",className:"text-[var(--dg-text-muted)]",children:"ClusterIP"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:460:19",className:"text-[var(--dg-text-muted)]",children:"端口"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:461:19",className:"text-[var(--dg-text-muted)]",children:"Selector"})]})}),e.jsx(Oe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:464:15",children:t.map(a=>e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:466:19",className:"border-[var(--dg-border)]",children:[e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:467:21",className:"font-medium text-[var(--dg-text-primary)]",children:a.name}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:468:21",children:e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentView.tsx:468:32",variant:"outline",className:"text-xs",children:a.type})}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:469:21",className:"font-mono text-sm text-[var(--dg-text-muted)]",children:a.clusterIP}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:470:21",className:"text-sm text-[var(--dg-text-muted)]",children:a.ports.join(", ")}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:471:21",className:"text-xs text-[var(--dg-text-muted)]",children:Object.entries(a.selector).map(([n,d])=>e.jsxs("code",{"code-path":"src/components/kubernetes/DeploymentView.tsx:473:25",className:"mr-1 bg-[var(--dg-bg-tertiary)] px-1 rounded",children:[n,"=",d]},n))})]},a.name))})]})})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:485:7",children:[e.jsxs("h3",{"code-path":"src/components/kubernetes/DeploymentView.tsx:486:9",className:"text-sm font-semibold text-[var(--dg-text-primary)] mb-3 flex items-center gap-2",children:[e.jsx(Dt,{"code-path":"src/components/kubernetes/DeploymentView.tsx:487:11",className:"h-4 w-4 text-[var(--dg-purple)]"}),"关联 Ingress"]}),s.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentView.tsx:490:11",className:"text-sm text-[var(--dg-text-muted)] py-4",children:"暂无匹配的 Ingress"}):e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:492:11",className:"overflow-x-auto",children:e.jsxs(Re,{"code-path":"src/components/kubernetes/DeploymentView.tsx:493:13",children:[e.jsx(Be,{"code-path":"src/components/kubernetes/DeploymentView.tsx:494:15",children:e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:495:17",className:"border-[var(--dg-border)]",children:[e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:496:19",className:"text-[var(--dg-text-muted)]",children:"名称"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:497:19",className:"text-[var(--dg-text-muted)]",children:"Class"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:498:19",className:"text-[var(--dg-text-muted)]",children:"Host"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:499:19",className:"text-[var(--dg-text-muted)]",children:"路径"})]})}),e.jsx(Oe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:502:15",children:s.map(a=>e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:504:19",className:"border-[var(--dg-border)]",children:[e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:505:21",className:"font-medium text-[var(--dg-text-primary)]",children:a.name}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:506:21",className:"text-sm text-[var(--dg-text-muted)]",children:a.className}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:507:21",className:"text-sm text-[var(--dg-text-muted)]",children:a.hosts.join(", ")}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:508:21",className:"text-xs text-[var(--dg-text-muted)]",children:a.rules.flatMap(n=>(n.http?.paths||n.paths||[]).map(d=>d.path||"/")).join(", ")})]},a.name))})]})})]})]})}function Fs({events:t,loading:s}){return s==="events"?e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:525:12",className:"flex items-center justify-center py-12",children:e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:525:68",className:"h-6 w-6 animate-spin text-[var(--dg-text-muted)]"})}):t.length===0?e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:528:12",className:"text-center text-[var(--dg-text-muted)] py-12",children:"暂无事件"}):e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:531:5",className:"overflow-x-auto",children:e.jsxs(Re,{"code-path":"src/components/kubernetes/DeploymentView.tsx:532:7",children:[e.jsx(Be,{"code-path":"src/components/kubernetes/DeploymentView.tsx:533:9",children:e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:534:11",className:"border-[var(--dg-border)]",children:[e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:535:13",className:"text-[var(--dg-text-muted)] w-16",children:"类型"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:536:13",className:"text-[var(--dg-text-muted)] w-24",children:"原因"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:537:13",className:"text-[var(--dg-text-muted)]",children:"消息"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:538:13",className:"text-[var(--dg-text-muted)] w-20",children:"来源"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:539:13",className:"text-[var(--dg-text-muted)] w-10",children:"次数"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:540:13",className:"text-[var(--dg-text-muted)] w-40",children:"最后时间"})]})}),e.jsx(Oe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:543:9",children:t.map((o,a)=>e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:545:13",className:"border-[var(--dg-border)]",children:[e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:546:15",children:e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentView.tsx:547:17",variant:"outline",className:o.type==="Warning"?"text-[var(--dg-yellow)] border-[var(--dg-yellow)]/30":"text-[var(--dg-text-muted)] border-[var(--dg-border)]",children:o.type})}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:551:15",className:"text-sm text-[var(--dg-text-secondary)]",children:o.reason}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:552:15",className:"text-sm text-[var(--dg-text-primary)] max-w-md truncate",title:o.message,children:o.message}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:553:15",className:"text-xs text-[var(--dg-text-muted)]",children:o.source}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:554:15",className:"text-sm text-[var(--dg-text-muted)]",children:o.count}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:555:15",className:"text-xs text-[var(--dg-text-muted)]",children:Ye(o.lastTimestamp)})]},a))})]})})}function Ys({hpas:t,cronHpas:s,loading:o,replicas:a}){return o==="scale"?e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:567:12",className:"flex items-center justify-center py-12",children:e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:567:68",className:"h-6 w-6 animate-spin text-[var(--dg-text-muted)]"})}):e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:571:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:573:7",className:"flex items-center gap-2 px-2",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:574:9",className:"text-sm text-[var(--dg-text-muted)]",children:"当前副本:"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:575:9",className:"text-sm font-bold text-[var(--dg-text-primary)]",children:a}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentView.tsx:576:9",className:"text-xs text-[var(--dg-text-muted)]",children:"(可通过 Tab 栏右侧 +/- 手动调整)"})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentView.tsx:580:7",className:"dg-card",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentView.tsx:581:9",className:"pb-2",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:581:38",className:"text-sm flex items-center gap-2",children:[e.jsx(Zt,{"code-path":"src/components/kubernetes/DeploymentView.tsx:581:93",className:"h-4 w-4 text-[var(--dg-orange)]"}),"HPA — 水平自动伸缩"]})}),e.jsx(G,{"code-path":"src/components/kubernetes/DeploymentView.tsx:582:9",children:t.length===0?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:584:13",className:"text-sm text-[var(--dg-text-muted)] py-4",children:["未关联 HPA — ",e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentView.tsx:585:25",variant:"link",className:"h-auto p-0 text-[var(--dg-blue)] text-sm",children:"创建 HPA"})]}):e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:588:13",className:"overflow-x-auto",children:e.jsxs(Re,{"code-path":"src/components/kubernetes/DeploymentView.tsx:589:15",children:[e.jsx(Be,{"code-path":"src/components/kubernetes/DeploymentView.tsx:590:17",children:e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:591:19",className:"border-[var(--dg-border)]",children:[e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:592:21",className:"text-[var(--dg-text-muted)]",children:"名称"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:593:21",className:"text-[var(--dg-text-muted)]",children:"最小/最大"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:594:21",className:"text-[var(--dg-text-muted)]",children:"指标"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:595:21",className:"text-[var(--dg-text-muted)]",children:"当前负载"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:596:21",className:"text-[var(--dg-text-muted)]",children:"状态"})]})}),e.jsx(Oe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:599:17",children:t.map((n,d)=>{const i=n.spec?.minReplicas??n.minReplicas??1,p=n.spec?.maxReplicas??n.maxReplicas??10,D=n.spec?.metrics||n.metrics||[],h=n.status?.currentReplicas??n.currentReplicas??0,q=(n.status?.conditions||n.conditions||[]).find(V=>V.type==="AbleToScale")?.status==="True";return e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:609:23",className:"border-[var(--dg-border)]",children:[e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:610:25",className:"font-medium text-[var(--dg-text-primary)]",children:n.name||n.metadata?.name}),e.jsxs(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:611:25",className:"text-sm text-[var(--dg-text-secondary)] font-mono",children:[i," → ",p]}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:612:25",className:"text-xs text-[var(--dg-text-muted)]",children:D.map((V,R)=>{const M=V.resource||V.object?.metric?.name||"",z=V.resource?.target?.averageUtilization||V.resource?.target?.averageValue||V.resource?.target?.type||"-";return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:616:36",children:[M?.name||M,": ",z,V.resource?.target?.averageUtilization?"%":""]},R)})}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:619:25",className:"text-sm font-mono text-[var(--dg-text-secondary)]",children:h}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:620:25",children:e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentView.tsx:621:27",className:q?"bg-[var(--dg-green)]/20 text-[var(--dg-green)]":"bg-[var(--dg-red)]/20 text-[var(--dg-red)]",children:q?"正常":"异常"})})]},n.name||d)})})]})})})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentView.tsx:636:7",className:"dg-card",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentView.tsx:637:9",className:"pb-2",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:637:38",className:"text-sm flex items-center gap-2",children:[e.jsx(ss,{"code-path":"src/components/kubernetes/DeploymentView.tsx:637:93",className:"h-4 w-4 text-[var(--dg-blue)]"}),"CronHPA — 定时伸缩"]})}),e.jsx(G,{"code-path":"src/components/kubernetes/DeploymentView.tsx:638:9",children:s.length===0?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:640:13",className:"text-sm text-[var(--dg-text-muted)] py-4",children:["未关联 CronHPA — ",e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentView.tsx:641:29",variant:"link",className:"h-auto p-0 text-[var(--dg-blue)] text-sm",children:"创建 CronHPA"})]}):e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:644:13",className:"overflow-x-auto",children:e.jsxs(Re,{"code-path":"src/components/kubernetes/DeploymentView.tsx:645:15",children:[e.jsx(Be,{"code-path":"src/components/kubernetes/DeploymentView.tsx:646:17",children:e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:647:19",className:"border-[var(--dg-border)]",children:[e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:648:21",className:"text-[var(--dg-text-muted)]",children:"名称"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:649:21",className:"text-[var(--dg-text-muted)]",children:"目标副本"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:650:21",className:"text-[var(--dg-text-muted)]",children:"调度规则"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:651:21",className:"text-[var(--dg-text-muted)]",children:"时区"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:652:21",className:"text-[var(--dg-text-muted)]",children:"状态"})]})}),e.jsx(Oe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:655:17",children:s.map((n,d)=>{const i=n.spec?.jobs||n.jobs||[],p=n.spec?.timezone||"UTC";return e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:660:23",className:"border-[var(--dg-border)]",children:[e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:661:25",className:"font-medium text-[var(--dg-text-primary)]",children:n.name||n.metadata?.name}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:662:25",className:"text-sm text-[var(--dg-text-secondary)]",children:i.map(D=>D.targetSize||D.targetReplicas||"?").join(", ")}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:665:25",className:"text-xs font-mono text-[var(--dg-text-muted)]",children:i.map(D=>D.schedule||"?").join(", ")}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:666:25",className:"text-xs text-[var(--dg-text-muted)]",children:p}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:667:25",children:e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentView.tsx:668:27",className:"bg-[var(--dg-green)]/20 text-[var(--dg-green)]",children:"已启用"})})]},n.name||d)})})]})})})]})]})}function Js({revisions:t,rollbackLoading:s,onRollback:o}){return t.length===0?e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:686:12",className:"text-center text-[var(--dg-text-muted)] py-12",children:"暂无历史版本"}):e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentView.tsx:689:5",className:"overflow-x-auto",children:e.jsxs(Re,{"code-path":"src/components/kubernetes/DeploymentView.tsx:690:7",children:[e.jsx(Be,{"code-path":"src/components/kubernetes/DeploymentView.tsx:691:9",children:e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:692:11",className:"border-[var(--dg-border)]",children:[e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:693:13",className:"text-[var(--dg-text-muted)] w-24",children:"Revision"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:694:13",className:"text-[var(--dg-text-muted)]",children:"镜像"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:695:13",className:"text-[var(--dg-text-muted)] w-24",children:"状态"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:696:13",className:"text-[var(--dg-text-muted)] w-40",children:"更新时间"}),e.jsx(X,{"code-path":"src/components/kubernetes/DeploymentView.tsx:697:13",className:"text-[var(--dg-text-muted)] w-24",children:"操作"})]})}),e.jsx(Oe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:700:9",children:t.map((a,n)=>{const d=a.revision??a.revision_number??a.number??n+1,i=n===0;return e.jsxs(De,{"code-path":"src/components/kubernetes/DeploymentView.tsx:705:15",className:"border-[var(--dg-border)]",children:[e.jsxs(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:706:17",className:"font-mono text-[var(--dg-text-primary)]",children:["#",d]}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:707:17",className:"text-xs font-mono text-[var(--dg-text-muted)] max-w-[300px] truncate",children:a.image||a.images?.[0]||"-"}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:708:17",children:i?e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentView.tsx:710:23",className:"bg-[var(--dg-green)]/20 text-[var(--dg-green)] border-[var(--dg-green)]/30",children:"当前"}):e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentView.tsx:711:23",variant:"outline",className:"text-[var(--dg-text-muted)]",children:"历史"})}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:713:17",className:"text-xs text-[var(--dg-text-muted)]",children:Ye(a.created_at||a.time)}),e.jsx(Z,{"code-path":"src/components/kubernetes/DeploymentView.tsx:714:17",children:e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentView.tsx:715:19",variant:"ghost",size:"sm",className:"h-7 text-amber-400",disabled:i||s!==null,onClick:()=>o(a),children:[s===d?e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentView.tsx:716:53",className:"h-3 w-3 animate-spin mr-1"}):e.jsx(bs,{"code-path":"src/components/kubernetes/DeploymentView.tsx:716:105",className:"h-3 w-3 mr-1"}),"回滚"]})})]},d)})})]})})}function Lt(t){const s=n=>{if(!n)return null;let d="none";return n.httpGet?d="httpGet":n.tcpSocket?d="tcpSocket":n.exec&&(d="exec"),{type:d,httpPath:n.httpGet?.path||"",httpPort:n.httpGet?.port??"",httpHost:n.httpGet?.host||"",tcpPort:n.tcpSocket?.port??"",execCommand:Array.isArray(n.exec?.command)?n.exec.command.join(` +`):n.exec?.command||"",initialDelaySeconds:n.initialDelaySeconds,periodSeconds:n.periodSeconds,timeoutSeconds:n.timeoutSeconds,successThreshold:n.successThreshold,failureThreshold:n.failureThreshold}},o=n=>{if(!n)return{type:"none"};let d="none";return n.exec?d="exec":n.httpGet?d="httpGet":n.tcpSocket&&(d="tcpSocket"),{type:d,execCommand:Array.isArray(n.exec?.command)?n.exec.command.join(` +`):"",httpPath:n.httpGet?.path||"",httpPort:n.httpGet?.port??"",tcpPort:n.tcpSocket?.port??""}},a=t.securityContext;return{name:t.name||"",image:t.image||"",imagePullPolicy:t.imagePullPolicy||"",command:Array.isArray(t.command)?t.command:[],args:Array.isArray(t.args)?t.args:[],workingDir:t.workingDir||"",env:(Array.isArray(t.env)?t.env:[]).map(n=>({name:n.name||"",value:n.value??""})),ports:(Array.isArray(t.ports)?t.ports:[]).map(n=>({name:n.name||"",containerPort:n.containerPort??"",protocol:n.protocol||"TCP"})),resources:{requests:t.resources?.requests||{},limits:t.resources?.limits||{}},livenessProbe:s(t.livenessProbe),readinessProbe:s(t.readinessProbe),startupProbe:s(t.startupProbe),lifecycle:t.lifecycle?{postStart:t.lifecycle.postStart?o(t.lifecycle.postStart):void 0,preStop:t.lifecycle.preStop?o(t.lifecycle.preStop):void 0}:null,securityContext:a?{runAsUser:a.runAsUser,runAsGroup:a.runAsGroup,runAsNonRoot:a.runAsNonRoot,privileged:a.privileged,readOnlyRootFilesystem:a.readOnlyRootFilesystem,allowPrivilegeEscalation:a.allowPrivilegeEscalation,capabilitiesAdd:a.capabilities?.add||[],capabilitiesDrop:a.capabilities?.drop||[]}:null,volumeMounts:(Array.isArray(t.volumeMounts)?t.volumeMounts:[]).map(n=>({name:n.name||"",mountPath:n.mountPath||"",subPath:n.subPath||"",readOnly:n.readOnly||!1}))}}function Gt(t=""){return{name:t,image:"",imagePullPolicy:"IfNotPresent",command:[],args:[],workingDir:"",env:[],ports:[],resources:{},livenessProbe:null,readinessProbe:null,startupProbe:null,lifecycle:null,securityContext:null,volumeMounts:[]}}function bt(t){if(!t||t.type==="none"||!t.type)return;const s={};if(t.type==="httpGet")s.httpGet={},t.httpPath&&(s.httpGet.path=t.httpPath),t.httpPort!==""&&t.httpPort!=null&&(s.httpGet.port=typeof t.httpPort=="number"?t.httpPort:Number(t.httpPort)),t.httpHost&&(s.httpGet.host=t.httpHost);else if(t.type==="tcpSocket")s.tcpSocket={},t.tcpPort!==""&&t.tcpPort!=null&&(s.tcpSocket.port=typeof t.tcpPort=="number"?t.tcpPort:Number(t.tcpPort));else if(t.type==="exec"){const o=(t.execCommand||"").split(` +`).map(a=>a.trim()).filter(Boolean);o.length&&(s.exec={command:o})}return t.initialDelaySeconds!=null&&(s.initialDelaySeconds=t.initialDelaySeconds),t.periodSeconds!=null&&(s.periodSeconds=t.periodSeconds),t.timeoutSeconds!=null&&(s.timeoutSeconds=t.timeoutSeconds),t.successThreshold!=null&&(s.successThreshold=t.successThreshold),t.failureThreshold!=null&&(s.failureThreshold=t.failureThreshold),Object.keys(s).length>0?s:void 0}function Ht(t){if(!(!t||t.type==="none"||!t.type)){if(t.type==="exec"){const s=(t.execCommand||"").split(` +`).map(o=>o.trim()).filter(Boolean);return s.length?{exec:{command:s}}:void 0}if(t.type==="httpGet"){const s={httpGet:{}};return t.httpPath&&(s.httpGet.path=t.httpPath),t.httpPort!==""&&t.httpPort!=null&&(s.httpGet.port=Number(t.httpPort)),s}if(t.type==="tcpSocket"){const s={tcpSocket:{}};return t.tcpPort!==""&&t.tcpPort!=null&&(s.tcpSocket.port=Number(t.tcpPort)),s}}}function Ft(t){const s={name:t.name};t.image&&(s.image=t.image),t.imagePullPolicy&&(s.imagePullPolicy=t.imagePullPolicy),t.workingDir&&(s.workingDir=t.workingDir),t.command.length>0&&(s.command=t.command),t.args.length>0&&(s.args=t.args),t.env.length>0&&(s.env=t.env.filter(h=>h.name.trim()).map(h=>{const N={name:h.name};return h.value!=null&&(N.value=h.value),N})),t.ports.length>0&&(s.ports=t.ports.filter(h=>h.containerPort!=="").map(h=>{const N={containerPort:typeof h.containerPort=="number"?h.containerPort:Number(h.containerPort)};return h.name&&(N.name=h.name),h.protocol&&(N.protocol=h.protocol),N}));const o=t.resources.requests,a=t.resources.limits,n=o&&Object.values(o).some(h=>h&&h.trim()),d=a&&Object.values(a).some(h=>h&&h.trim());(n||d)&&(s.resources={},n&&(s.resources.requests={},o.cpu?.trim()&&(s.resources.requests.cpu=o.cpu),o.memory?.trim()&&(s.resources.requests.memory=o.memory)),d&&(s.resources.limits={},a.cpu?.trim()&&(s.resources.limits.cpu=a.cpu),a.memory?.trim()&&(s.resources.limits.memory=a.memory)));const i=bt(t.livenessProbe);i&&(s.livenessProbe=i);const p=bt(t.readinessProbe);p&&(s.readinessProbe=p);const D=bt(t.startupProbe);if(D&&(s.startupProbe=D),t.lifecycle){const h={},N=Ht(t.lifecycle.postStart);N&&(h.postStart=N);const I=Ht(t.lifecycle.preStop);I&&(h.preStop=I),Object.keys(h).length>0&&(s.lifecycle=h)}if(t.securityContext){const h=t.securityContext,N={};h.runAsUser!==""&&h.runAsUser!=null&&(N.runAsUser=Number(h.runAsUser)),h.runAsGroup!==""&&h.runAsGroup!=null&&(N.runAsGroup=Number(h.runAsGroup)),h.runAsNonRoot!=null&&(N.runAsNonRoot=h.runAsNonRoot),h.privileged!=null&&(N.privileged=h.privileged),h.readOnlyRootFilesystem!=null&&(N.readOnlyRootFilesystem=h.readOnlyRootFilesystem),h.allowPrivilegeEscalation!=null&&(N.allowPrivilegeEscalation=h.allowPrivilegeEscalation);const I=(h.capabilitiesAdd||[]).filter(Boolean),q=(h.capabilitiesDrop||[]).filter(Boolean);(I.length||q.length)&&(N.capabilities={},I.length&&(N.capabilities.add=I),q.length&&(N.capabilities.drop=q)),Object.keys(N).length>0&&(s.securityContext=N)}return t.volumeMounts.length>0&&(s.volumeMounts=t.volumeMounts.filter(h=>h.name.trim()&&h.mountPath.trim()).map(h=>{const N={name:h.name,mountPath:h.mountPath};return h.subPath&&(N.subPath=h.subPath),h.readOnly&&(N.readOnly=!0),N})),s}function Yt(t){return t.join(` +`)}function Jt(t){return t.split(` +`).map(s=>s.trim()).filter(Boolean)}function qs({clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}){const{toast:i}=Pe(),[p,D]=m.useState(!1),[h,N]=m.useState(!a),[I,q]=m.useState(a||{}),[V,R]=m.useState([]),[M,z]=m.useState([]),[F,B]=m.useState([]);m.useEffect(()=>{if(!a){N(!1);return}q(a);const r=a?.spec?.template?.spec||{};R((Array.isArray(r.containers)?r.containers:[]).map(Lt)),z((Array.isArray(r.initContainers)?r.initContainers:[]).map(Lt)),B((Array.isArray(r.imagePullSecrets)?r.imagePullSecrets:[]).map(b=>b.name||"")),N(!1)},[a]);const U=(r,b)=>{R(f=>f.map((P,l)=>l===r?{...P,...b}:P))},Y=()=>{R(r=>[...r,Gt(`container-${r.length+1}`)])},S=r=>{R(b=>b.filter((f,P)=>P!==r))},Q=r=>{R(b=>{const f=JSON.parse(JSON.stringify(b[r]));f.name=`${f.name}-copy`;const P=[...b];return P.splice(r+1,0,f),P})},O=(r,b)=>{z(f=>f.map((P,l)=>l===r?{...P,...b}:P))},H=()=>{z(r=>[...r,Gt(`init-${r.length+1}`)])},ne=r=>{z(b=>b.filter((f,P)=>P!==r))},oe=async()=>{for(const r of[...M,...V]){if(!r.name.trim()){i({title:"保存失败",description:"容器名称不能为空",variant:"destructive"});return}if(!r.image.trim()){i({title:"保存失败",description:`容器 ${r.name} 的镜像不能为空`,variant:"destructive"});return}}D(!0);try{const r=JSON.parse(JSON.stringify(I));r.spec=r.spec||{},r.spec.template=r.spec.template||{},r.spec.template.spec=r.spec.template.spec||{},r.spec.template.spec.containers=V.map(Ft),r.spec.template.spec.initContainers=M.length>0?M.map(Ft):void 0,r.spec.template.spec.imagePullSecrets=F.filter(f=>f.trim()).length>0?F.filter(f=>f.trim()).map(f=>({name:f})):void 0;const b=JSON.stringify(r,null,2);await te.updateResourceYaml(t,s,"deployments",o,b),i({title:"容器配置已保存",description:`${o} 更新已提交`}),n()}catch(r){i({title:"保存失败",description:r?.message||String(r),variant:"destructive"})}finally{D(!1)}};return h?e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:400:7",className:"bg-slate-900 border-slate-800",children:e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:401:9",className:"p-12 text-center",children:[e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:402:11",className:"h-6 w-6 animate-spin mx-auto text-slate-500"}),e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:403:11",className:"text-slate-500 mt-3 text-sm",children:"加载中..."})]})}):a?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:419:5",className:"space-y-4",children:[e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:421:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:422:9",className:"pb-3",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:423:11",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(_s,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:424:13",className:"h-4 w-4 text-amber-400"}),"镜像拉取凭证 (imagePullSecrets)",e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:426:13",variant:"outline",className:"border-slate-700 text-slate-500 text-[10px]",children:"Pod 级别"})]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:429:9",className:"pt-0 space-y-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:430:11",className:"flex items-center gap-2 flex-wrap",children:[F.map((r,b)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:432:15",className:"flex items-center gap-1 bg-slate-800 rounded px-2 py-1",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:433:17",className:"text-xs text-slate-300 font-mono",children:r}),e.jsx("button",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:434:17",onClick:()=>B(f=>f.filter((P,l)=>l!==b)),className:"text-red-400 hover:text-red-300 ml-1",children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:435:68",className:"h-3 w-3"})})]},b)),F.length===0&&e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:438:47",className:"text-[11px] text-slate-600",children:"无"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:440:11",className:"flex gap-2",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:441:13",placeholder:"输入 Secret 名称后回车",className:"bg-slate-800 border-slate-700 text-slate-200 text-xs h-8",onKeyDown:r=>{if(r.key==="Enter"){const b=r.target.value.trim();b&&(B(f=>[...f,b]),r.target.value="")}}}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:448:13",size:"sm",variant:"outline",className:"h-8 border-slate-700 text-slate-300 text-xs",onClick:()=>B(r=>[...r,""]),children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:450:15",className:"h-3 w-3 mr-1"}),"新增"]})]})]})]}),e.jsx(qt,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:457:7",title:"初始化容器",description:"在主容器启动前按顺序执行的容器,用于初始化环境",icon:e.jsx(ls,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:460:15",className:"h-4 w-4 text-purple-400"}),containers:M,accentColor:"purple",onAdd:H,onRemove:ne,onUpdate:O}),e.jsx(qt,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:469:7",title:"工作容器",description:"Deployment 运行的主容器,定义应用进程及其运行时配置",icon:e.jsx(ot,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:472:15",className:"h-4 w-4 text-blue-400"}),containers:V,accentColor:"blue",onAdd:Y,onRemove:S,onUpdate:U,onDuplicate:Q}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:482:7",className:"sticky bottom-0 bg-slate-950/80 backdrop-blur border-t border-slate-800 p-3 flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:483:9",className:"text-[11px] text-slate-500",children:["共 ",e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:484:13",className:"text-slate-300 font-semibold",children:M.length})," 个初始化容器 +",e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:485:11",className:"text-slate-300 font-semibold ml-1",children:V.length})," 个工作容器"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:487:9",className:"flex gap-2",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:488:11",variant:"outline",className:"border-slate-700 text-slate-400",onClick:d,children:"取消"}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:489:11",className:"bg-blue-600 hover:bg-blue-700",disabled:p,onClick:oe,children:[p?e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:490:23",className:"h-4 w-4 animate-spin mr-1"}):e.jsx(at,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:490:75",className:"h-4 w-4 mr-1"}),"保存"]})]})]})]}):e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:410:7",className:"bg-slate-900 border-slate-800",children:e.jsx(G,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:411:9",className:"p-8 text-center text-slate-500",children:"未获取到 manifest 数据,请使用 YAML 编辑模式直接修改。"})})}function qt({title:t,description:s,icon:o,containers:a,accentColor:n,onAdd:d,onRemove:i,onUpdate:p,onDuplicate:D}){const[h,N]=m.useState(new Set([0])),I=R=>{N(M=>{const z=new Set(M);return z.has(R)?z.delete(R):z.add(R),z})},q=n==="blue"?"border-blue-500/30":"border-purple-500/30",V=n==="blue"?"bg-blue-500/5":"bg-purple-500/5";return e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:527:5",className:"bg-slate-900 border-slate-800",children:[e.jsxs(ie,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:528:7",className:"pb-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:529:9",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:530:11",className:"flex items-center gap-2",children:[o,e.jsx(pe,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:532:13",className:"text-sm text-slate-200",children:t}),e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:533:13",variant:"outline",className:"border-slate-700 text-slate-400 text-[10px]",children:a.length})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:535:11",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:d,children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:536:13",className:"h-3 w-3 mr-1"}),"新增容器"]})]}),e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:539:9",className:"text-[11px] text-slate-600",children:s})]}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:541:7",className:"pt-0 space-y-3",children:[a.length===0&&e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:543:11",className:"text-center py-6 text-slate-600 text-xs",children:"暂无容器,点击「新增容器」添加"}),a.map((R,M)=>{const z=h.has(M)||a.length===1;return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:548:13",className:`rounded-lg border ${q} overflow-hidden`,children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:550:15",className:`flex items-center justify-between px-3 py-2 ${V} cursor-pointer`,onClick:()=>I(M),children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:551:17",className:"flex items-center gap-2",children:[z?e.jsx(Qt,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:552:29",className:"h-4 w-4 text-slate-500"}):e.jsx(es,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:552:82",className:"h-4 w-4 text-slate-500"}),e.jsx(ot,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:553:19",className:`h-4 w-4 ${n==="blue"?"text-blue-400":"text-purple-400"}`}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:554:19",className:"text-sm font-mono text-slate-200 font-semibold",children:R.name||"(未命名)"}),R.image&&e.jsx("code",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:555:31",className:"text-[10px] text-slate-500 font-mono truncate max-w-[300px]",children:R.image})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:557:17",className:"flex items-center gap-1",onClick:F=>F.stopPropagation(),children:[D&&e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:559:21",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-500 hover:text-slate-300",title:"复制",onClick:()=>D(M),children:e.jsx(ds,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:561:23",className:"h-3.5 w-3.5"})}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:564:19",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-400 hover:text-red-300",title:"删除",onClick:()=>{confirm(`确认删除容器「${R.name}」?`)&&i(M)},children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:566:21",className:"h-3.5 w-3.5"})})]})]}),z&&e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:572:17",className:"p-3 space-y-4 bg-slate-950/30",children:e.jsx(Us,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:573:19",container:R,onUpdate:F=>p(M,F)})})]},M)})]})]})}function Us({container:t,onUpdate:s}){const o=t,a="flex items-center gap-1.5 text-xs font-semibold text-slate-300 mb-2";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:596:7",className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:597:9",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:598:11",className:"text-slate-400 text-xs",children:"容器名称"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:599:11",value:o.name,onChange:n=>s({name:n.target.value}),placeholder:"my-app",className:"mt-1 bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:603:9",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:604:11",className:"text-slate-400 text-xs",children:"容器镜像"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:605:11",value:o.image,onChange:n=>s({image:n.target.value}),placeholder:"nginx:1.25",className:"mt-1 bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:609:9",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:610:11",className:"text-slate-400 text-xs",children:"镜像拉取策略"}),e.jsxs(Le,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:611:11",value:o.imagePullPolicy||"__none",onValueChange:n=>s({imagePullPolicy:n==="__none"?"":n}),children:[e.jsx(Ge,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:612:13",className:"mt-1 bg-slate-800 border-slate-700 text-slate-200 text-xs h-8",children:e.jsx(nt,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:613:15"})}),e.jsxs(He,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:615:13",className:"bg-slate-900 border-slate-700",children:[e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:616:15",value:"__none",className:"text-slate-400",children:"不设置(默认 IfNotPresent)"}),e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:617:15",value:"Always",className:"text-slate-200",children:"Always"}),e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:618:15",value:"IfNotPresent",className:"text-slate-200",children:"IfNotPresent"}),e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:619:15",value:"Never",className:"text-slate-200",children:"Never"})]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:623:9",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:624:11",className:"text-slate-400 text-xs",children:"工作目录 (workingDir)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:625:11",value:o.workingDir||"",onChange:n=>s({workingDir:n.target.value}),placeholder:"/app",className:"mt-1 bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:632:7",className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:633:9",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:634:11",className:"text-slate-400 text-xs",children:"启动命令 (command) — 每行一个"}),e.jsx(st,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:635:11",value:Yt(o.command),placeholder:`/bin/sh +-c`,onChange:n=>s({command:Jt(n.target.value)}),className:"mt-1 bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs min-h-[60px]"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:639:9",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:640:11",className:"text-slate-400 text-xs",children:"启动参数 (args) — 每行一个"}),e.jsx(st,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:641:11",value:Yt(o.args),placeholder:`--config=/etc/app.yaml +--debug`,onChange:n=>s({args:Jt(n.target.value)}),className:"mt-1 bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs min-h-[60px]"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:648:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:649:9",className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:650:11",className:a,children:[e.jsx(ts,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:650:39",className:"h-3.5 w-3.5 text-cyan-400"})," 环境变量"]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:651:11",size:"sm",variant:"outline",className:"h-6 border-slate-700 text-slate-300 text-[11px]",onClick:()=>s({env:[...o.env,{name:"",value:""}]}),children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:653:13",className:"h-3 w-3 mr-1"}),"新增"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:656:9",className:"space-y-1.5",children:[o.env.map((n,d)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:658:13",className:"grid grid-cols-[1fr_1.4fr_auto] gap-2",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:659:15",value:n.name,placeholder:"KEY",onChange:i=>{const p=[...o.env];p[d]={...n,name:i.target.value},s({env:p})},className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:662:15",value:n.value||"",placeholder:"value",onChange:i=>{const p=[...o.env];p[d]={...n,value:i.target.value},s({env:p})},className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:665:15",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-400",onClick:()=>s({env:o.env.filter((i,p)=>p!==d)}),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:667:17",className:"h-3.5 w-3.5"})})]},d)),o.env.length===0&&e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:671:34",className:"text-[11px] text-slate-600",children:"无环境变量"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:676:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:677:9",className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:678:11",className:a,children:[e.jsx(Se,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:678:39",className:"h-3.5 w-3.5 text-indigo-400"})," 端口"]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:679:11",size:"sm",variant:"outline",className:"h-6 border-slate-700 text-slate-300 text-[11px]",onClick:()=>s({ports:[...o.ports,{name:"",containerPort:"",protocol:"TCP"}]}),children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:681:13",className:"h-3 w-3 mr-1"}),"新增"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:684:9",className:"space-y-1.5",children:[o.ports.map((n,d)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:686:13",className:"grid grid-cols-[1fr_1fr_100px_auto] gap-2",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:687:15",value:n.name||"",placeholder:"http",onChange:i=>{const p=[...o.ports];p[d]={...n,name:i.target.value},s({ports:p})},className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:690:15",type:"number",value:n.containerPort,placeholder:"8080",onChange:i=>{const p=[...o.ports];p[d]={...n,containerPort:i.target.value},s({ports:p})},className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsxs(Le,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:693:15",value:n.protocol||"TCP",onValueChange:i=>{const p=[...o.ports];p[d]={...n,protocol:i},s({ports:p})},children:[e.jsx(Ge,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:694:17",className:"bg-slate-800 border-slate-700 text-slate-200 text-xs h-8",children:e.jsx(nt,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:695:19"})}),e.jsxs(He,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:697:17",className:"bg-slate-900 border-slate-700",children:[e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:698:19",value:"TCP",className:"text-slate-200",children:"TCP"}),e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:699:19",value:"UDP",className:"text-slate-200",children:"UDP"}),e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:700:19",value:"SCTP",className:"text-slate-200",children:"SCTP"})]})]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:703:15",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-400",onClick:()=>s({ports:o.ports.filter((i,p)=>p!==d)}),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:705:17",className:"h-3.5 w-3.5"})})]},d)),o.ports.length===0&&e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:709:36",className:"text-[11px] text-slate-600",children:"无端口暴露"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:714:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:715:9",className:a,children:[e.jsx(ys,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:715:37",className:"h-3.5 w-3.5 text-amber-400"})," 资源 (requests / limits)"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:716:9",className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:717:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:718:13",className:"text-[11px] text-slate-500",children:"CPU 请求"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:719:13",value:o.resources.requests?.cpu||"",placeholder:"100m",onChange:n=>s({resources:{...o.resources,requests:{...o.resources.requests,cpu:n.target.value}}}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:723:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:724:13",className:"text-[11px] text-slate-500",children:"CPU 上限"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:725:13",value:o.resources.limits?.cpu||"",placeholder:"500m",onChange:n=>s({resources:{...o.resources,limits:{...o.resources.limits,cpu:n.target.value}}}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:729:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:730:13",className:"text-[11px] text-slate-500",children:"内存请求"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:731:13",value:o.resources.requests?.memory||"",placeholder:"128Mi",onChange:n=>s({resources:{...o.resources,requests:{...o.resources.requests,memory:n.target.value}}}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:735:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:736:13",className:"text-[11px] text-slate-500",children:"内存上限"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:737:13",value:o.resources.limits?.memory||"",placeholder:"512Mi",onChange:n=>s({resources:{...o.resources,limits:{...o.resources.limits,memory:n.target.value}}}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:745:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:746:9",className:a,children:[e.jsx(Os,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:746:37",className:"h-3.5 w-3.5 text-rose-400"})," 健康检查 (Probes)"]}),e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:747:9",className:"space-y-2",children:["livenessProbe","readinessProbe","startupProbe"].map(n=>e.jsx(Ks,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:749:13",label:{livenessProbe:"存活探针 (liveness)",readinessProbe:"就绪探针 (readiness)",startupProbe:"启动探针 (startup)"}[n],probe:o[n],onChange:d=>s({[n]:d})},n))})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:759:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:760:9",className:a,children:[e.jsx(is,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:760:37",className:"h-3.5 w-3.5 text-yellow-400"})," 生命周期回调 (Lifecycle)"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:761:9",className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsx(Ut,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:762:11",label:"启动后 (postStart)",handler:o.lifecycle?.postStart,onChange:n=>s({lifecycle:{...o.lifecycle,postStart:n}})}),e.jsx(Ut,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:764:11",label:"终止前 (preStop)",handler:o.lifecycle?.preStop,onChange:n=>s({lifecycle:{...o.lifecycle,preStop:n}})})]}),!o.lifecycle&&e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:768:11",size:"sm",variant:"outline",className:"h-6 border-slate-700 text-slate-300 text-[11px] mt-1",onClick:()=>s({lifecycle:{postStart:{type:"none"},preStop:{type:"none"}}}),children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:770:13",className:"h-3 w-3 mr-1"}),"启用生命周期回调"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:776:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:777:9",className:a,children:[e.jsx(ns,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:777:37",className:"h-3.5 w-3.5 text-emerald-400"})," 安全上下文 (SecurityContext)"]}),o.securityContext?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:779:11",className:"space-y-2 border border-slate-800 rounded-md p-3 bg-slate-950/30",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:780:13",className:"grid grid-cols-2 md:grid-cols-3 gap-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:781:15",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:782:17",className:"text-[11px] text-slate-500",children:"runAsUser"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:783:17",type:"number",value:o.securityContext.runAsUser??"",placeholder:"1000",onChange:n=>s({securityContext:{...o.securityContext,runAsUser:n.target.value===""?void 0:Number(n.target.value)}}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:787:15",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:788:17",className:"text-[11px] text-slate-500",children:"runAsGroup"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:789:17",type:"number",value:o.securityContext.runAsGroup??"",placeholder:"1000",onChange:n=>s({securityContext:{...o.securityContext,runAsGroup:n.target.value===""?void 0:Number(n.target.value)}}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:793:15",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:794:17",className:"text-[11px] text-slate-500",children:"Capabilities Add (逗号分隔)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:795:17",value:(o.securityContext.capabilitiesAdd||[]).join(","),placeholder:"NET_ADMIN",onChange:n=>s({securityContext:{...o.securityContext,capabilitiesAdd:n.target.value.split(",").map(d=>d.trim()).filter(Boolean)}}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:799:15",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:800:17",className:"text-[11px] text-slate-500",children:"Capabilities Drop (逗号分隔)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:801:17",value:(o.securityContext.capabilitiesDrop||[]).join(","),placeholder:"ALL",onChange:n=>s({securityContext:{...o.securityContext,capabilitiesDrop:n.target.value.split(",").map(d=>d.trim()).filter(Boolean)}}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:806:13",className:"flex items-center gap-4 flex-wrap",children:[e.jsx(Qe,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:807:15",label:"runAsNonRoot",value:!!o.securityContext.runAsNonRoot,onChange:n=>s({securityContext:{...o.securityContext,runAsNonRoot:n}})}),e.jsx(Qe,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:809:15",label:"privileged",value:!!o.securityContext.privileged,onChange:n=>s({securityContext:{...o.securityContext,privileged:n}})}),e.jsx(Qe,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:811:15",label:"readOnlyRootFilesystem",value:!!o.securityContext.readOnlyRootFilesystem,onChange:n=>s({securityContext:{...o.securityContext,readOnlyRootFilesystem:n}})}),e.jsx(Qe,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:813:15",label:"allowPrivilegeEscalation",value:o.securityContext.allowPrivilegeEscalation??!1,onChange:n=>s({securityContext:{...o.securityContext,allowPrivilegeEscalation:n}})})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:816:13",size:"sm",variant:"ghost",className:"h-6 text-red-400 text-[11px]",onClick:()=>s({securityContext:null}),children:[e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:818:15",className:"h-3 w-3 mr-1"}),"移除安全上下文"]})]}):e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:822:11",size:"sm",variant:"outline",className:"h-6 border-slate-700 text-slate-300 text-[11px]",onClick:()=>s({securityContext:{runAsNonRoot:!1,privileged:!1}}),children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:824:13",className:"h-3 w-3 mr-1"}),"启用安全上下文"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:830:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:831:9",className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:832:11",className:a,children:[e.jsx(Ss,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:832:39",className:"h-3.5 w-3.5 text-teal-400"})," 卷挂载 (VolumeMounts)"]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:833:11",size:"sm",variant:"outline",className:"h-6 border-slate-700 text-slate-300 text-[11px]",onClick:()=>s({volumeMounts:[...o.volumeMounts,{name:"",mountPath:"",subPath:"",readOnly:!1}]}),children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:835:13",className:"h-3 w-3 mr-1"}),"新增"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:838:9",className:"space-y-1.5",children:[o.volumeMounts.map((n,d)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:840:13",className:"grid grid-cols-[1fr_1fr_1fr_60px_auto] gap-2 items-center",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:841:15",value:n.name,placeholder:"volume 名称",onChange:i=>{const p=[...o.volumeMounts];p[d]={...n,name:i.target.value},s({volumeMounts:p})},className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:844:15",value:n.mountPath,placeholder:"/data",onChange:i=>{const p=[...o.volumeMounts];p[d]={...n,mountPath:i.target.value},s({volumeMounts:p})},className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:847:15",value:n.subPath||"",placeholder:"subPath (可选)",onChange:i=>{const p=[...o.volumeMounts];p[d]={...n,subPath:i.target.value},s({volumeMounts:p})},className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:850:15",className:"flex items-center gap-1 text-[10px] text-slate-500 cursor-pointer",children:[e.jsx(wt,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:851:17",checked:!!n.readOnly,onCheckedChange:i=>{const p=[...o.volumeMounts];p[d]={...n,readOnly:i},s({volumeMounts:p})}}),"RO"]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:855:15",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-400",onClick:()=>s({volumeMounts:o.volumeMounts.filter((i,p)=>p!==d)}),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:857:17",className:"h-3.5 w-3.5"})})]},d)),o.volumeMounts.length===0&&e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:861:43",className:"text-[11px] text-slate-600",children:"无卷挂载"})]})]})]})}function Ks({label:t,probe:s,onChange:o}){const a=!!s,n=s||{type:"httpGet"},d=i=>o({...n,...i});return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:881:5",className:"border border-slate-800 rounded-md p-2.5 bg-slate-950/30",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:882:7",className:"flex items-center justify-between mb-2",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:883:9",className:"text-xs text-slate-300 font-medium",children:t}),e.jsx(wt,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:884:9",checked:a,onCheckedChange:i=>o(i?{type:"httpGet",httpPath:"/",httpPort:8080,initialDelaySeconds:10,periodSeconds:10}:null)})]}),a&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:889:11",className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:890:13",className:"text-[10px] text-slate-500 w-8",children:"类型"}),e.jsxs(Le,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:891:13",value:n.type||"httpGet",onValueChange:i=>d({type:i}),children:[e.jsx(Ge,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:892:15",className:"bg-slate-800 border-slate-700 text-slate-200 text-xs h-7 flex-1",children:e.jsx(nt,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:893:17"})}),e.jsxs(He,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:895:15",className:"bg-slate-900 border-slate-700",children:[e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:896:17",value:"httpGet",className:"text-slate-200",children:"HTTP GET"}),e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:897:17",value:"tcpSocket",className:"text-slate-200",children:"TCP Socket"}),e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:898:17",value:"exec",className:"text-slate-200",children:"Exec 命令"})]})]})]}),n.type==="httpGet"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:903:13",className:"grid grid-cols-3 gap-2 mb-2",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:904:15",value:n.httpPath||"",placeholder:"/healthz",onChange:i=>d({httpPath:i.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:907:15",type:"number",value:n.httpPort??"",placeholder:"8080",onChange:i=>d({httpPort:i.target.value===""?void 0:Number(i.target.value)}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:910:15",value:n.httpHost||"",placeholder:"host (可选)",onChange:i=>d({httpHost:i.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"})]}),n.type==="tcpSocket"&&e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:916:13",className:"mb-2",children:e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:917:15",type:"number",value:n.tcpPort??"",placeholder:"端口",onChange:i=>d({tcpPort:i.target.value===""?void 0:Number(i.target.value)}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"})}),n.type==="exec"&&e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:923:13",className:"mb-2",children:e.jsx(st,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:924:15",value:n.execCommand||"",placeholder:"每行一个命令片段,如:\\ncat\\n/tmp/healthy",onChange:i=>d({execCommand:i.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs min-h-[50px]"})}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:929:11",className:"grid grid-cols-5 gap-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:930:13",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:931:15",className:"text-[10px] text-slate-500",children:"延迟(s)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:932:15",type:"number",value:n.initialDelaySeconds??"",placeholder:"10",onChange:i=>d({initialDelaySeconds:i.target.value===""?void 0:Number(i.target.value)}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:936:13",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:937:15",className:"text-[10px] text-slate-500",children:"间隔(s)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:938:15",type:"number",value:n.periodSeconds??"",placeholder:"10",onChange:i=>d({periodSeconds:i.target.value===""?void 0:Number(i.target.value)}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:942:13",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:943:15",className:"text-[10px] text-slate-500",children:"超时(s)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:944:15",type:"number",value:n.timeoutSeconds??"",placeholder:"1",onChange:i=>d({timeoutSeconds:i.target.value===""?void 0:Number(i.target.value)}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:948:13",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:949:15",className:"text-[10px] text-slate-500",children:"成功"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:950:15",type:"number",value:n.successThreshold??"",placeholder:"1",onChange:i=>d({successThreshold:i.target.value===""?void 0:Number(i.target.value)}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:954:13",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:955:15",className:"text-[10px] text-slate-500",children:"失败"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:956:15",type:"number",value:n.failureThreshold??"",placeholder:"3",onChange:i=>d({failureThreshold:i.target.value===""?void 0:Number(i.target.value)}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"})]})]})]})]})}function Ut({label:t,handler:s,onChange:o}){const a=s||{type:"none"},n=!a.type||a.type==="none"?"__none":a.type;return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:978:5",className:"border border-slate-800 rounded-md p-2.5 bg-slate-950/30",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:979:7",className:"text-xs text-slate-300 font-medium block mb-2",children:t}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:980:7",className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:981:9",className:"text-[10px] text-slate-500 w-8",children:"类型"}),e.jsxs(Le,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:982:9",value:n,onValueChange:d=>o({...a,type:d==="__none"?"none":d}),children:[e.jsx(Ge,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:983:11",className:"bg-slate-800 border-slate-700 text-slate-200 text-xs h-7 flex-1",children:e.jsx(nt,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:984:13"})}),e.jsxs(He,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:986:11",className:"bg-slate-900 border-slate-700",children:[e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:987:13",value:"__none",className:"text-slate-400",children:"不设置"}),e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:988:13",value:"exec",className:"text-slate-200",children:"Exec 命令"}),e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:989:13",value:"httpGet",className:"text-slate-200",children:"HTTP GET"}),e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:990:13",value:"tcpSocket",className:"text-slate-200",children:"TCP Socket"})]})]})]}),a.type==="exec"&&e.jsx(st,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:995:9",value:a.execCommand||"",placeholder:"每行一个命令片段",onChange:d=>o({...a,execCommand:d.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs min-h-[50px]"}),a.type==="httpGet"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:1000:9",className:"grid grid-cols-2 gap-2",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:1001:11",value:a.httpPath||"",placeholder:"/shutdown",onChange:d=>o({...a,httpPath:d.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:1004:11",type:"number",value:a.httpPort??"",placeholder:"8080",onChange:d=>o({...a,httpPort:d.target.value===""?void 0:Number(d.target.value)}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"})]}),a.type==="tcpSocket"&&e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:1010:9",type:"number",value:a.tcpPort??"",placeholder:"端口",onChange:d=>o({...a,tcpPort:d.target.value===""?void 0:Number(d.target.value)}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-7"})]})}function Qe({label:t,value:s,onChange:o}){return e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:1026:5",className:"flex items-center gap-1.5 cursor-pointer",children:[e.jsx(wt,{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:1027:7",checked:s,onCheckedChange:o}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditContainers.tsx:1028:7",className:"text-[11px] text-slate-400 font-mono",children:t})]})}function yt(t){return!t||typeof t!="object"?[]:Object.entries(t).map(([s,o])=>({key:s,value:String(o)}))}function kt(t){const s={};for(const{key:o,value:a}of t){const n=o.trim();n&&(s[n]=a)}return s}function Xs({clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}){const{toast:i}=Pe(),[p,D]=m.useState(!1),[h,N]=m.useState(!a),[I,q]=m.useState(a||{}),[V,R]=m.useState(1),[M,z]=m.useState([]),[F,B]=m.useState([]),[U,Y]=m.useState([]);m.useEffect(()=>{const l=a;if(!l){N(!1);return}q(l),R(l?.spec?.replicas??1),z(yt(l?.metadata?.labels)),B(yt(l?.metadata?.annotations)),Y(yt(l?.spec?.selector?.matchLabels)),N(!1)},[a]);const S=(l,w)=>{z(T=>T.map((c,k)=>k===l?{...c,...w}:c))},Q=()=>z(l=>[...l,{key:"",value:""}]),O=l=>z(w=>w.filter((T,c)=>c!==l)),H=(l,w)=>{B(T=>T.map((c,k)=>k===l?{...c,...w}:c))},ne=()=>B(l=>[...l,{key:"",value:""}]),oe=l=>B(w=>w.filter((T,c)=>c!==l)),r=(l,w)=>{Y(T=>T.map((c,k)=>k===l?{...c,...w}:c))},b=()=>Y(l=>[...l,{key:"",value:""}]),f=l=>Y(w=>w.filter((T,c)=>c!==l)),P=async()=>{D(!0);try{const l=JSON.parse(JSON.stringify(I));l.spec=l.spec||{},l.spec.replicas=V;const w=kt(M);l.metadata=l.metadata||{},l.metadata.labels=Object.keys(w).length>0?w:void 0;const T=kt(F);l.metadata.annotations=Object.keys(T).length>0?T:void 0;const c=kt(U);Object.keys(c).length>0&&(l.spec.selector=l.spec.selector||{},l.spec.selector.matchLabels=c,l.spec.template=l.spec.template||{},l.spec.template.metadata=l.spec.template.metadata||{},l.spec.template.metadata.labels={...l.spec.template.metadata.labels,...c});const k=JSON.stringify(l,null,2);await te.updateResourceYaml(t,s,"deployments",o,k),i({title:"基本信息已保存",description:`${o} 更新已提交`}),n()}catch(l){i({title:"保存失败",description:l?.message||String(l),variant:"destructive"})}finally{D(!1)}};return h?e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:123:7",className:"bg-slate-900 border-slate-800",children:e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:124:9",className:"p-12 text-center",children:[e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:125:11",className:"h-6 w-6 animate-spin mx-auto text-slate-500"}),e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:126:11",className:"text-slate-500 mt-3 text-sm",children:"加载中..."})]})}):a?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:143:5",className:"space-y-4",children:[e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:145:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:146:9",className:"pb-3",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:147:11",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(Rs,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:148:13",className:"h-4 w-4 text-blue-400"}),"副本数 (Replicas)"]})}),e.jsx(G,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:152:9",className:"pt-0",children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:153:11",className:"flex items-center gap-3",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:154:13",type:"number",min:0,value:V,onChange:l=>R(Math.max(0,Number(l.target.value)||0)),className:"w-32 bg-slate-800 border-slate-700 text-slate-200"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:161:13",className:"text-xs text-slate-500",children:"期望运行的 Pod 实例数量"})]})})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:167:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:168:9",className:"pb-3",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:169:11",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(os,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:170:13",className:"h-4 w-4 text-slate-500"}),"基本标识(只读)"]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:174:9",className:"pt-0 grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:175:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:176:13",className:"text-slate-400 text-xs",children:"名称 (name)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:177:13",value:o,readOnly:!0,className:"mt-1 bg-slate-950 border-slate-800 text-slate-500 font-mono text-sm cursor-not-allowed"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:180:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:181:13",className:"text-slate-400 text-xs",children:"命名空间 (namespace)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:182:13",value:s,readOnly:!0,className:"mt-1 bg-slate-950 border-slate-800 text-slate-500 font-mono text-sm cursor-not-allowed"})]})]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:189:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:190:9",className:"pb-3",children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:191:11",className:"flex items-center justify-between",children:[e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:192:13",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx($t,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:193:15",className:"h-4 w-4 text-emerald-400"}),"标签 (Labels)",e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:195:15",variant:"outline",className:"border-slate-700 text-slate-500 text-[10px]",children:M.length})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:197:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:Q,children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:198:15",className:"h-3 w-3 mr-1"}),"新增"]})]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:202:9",className:"pt-0 space-y-1.5",children:[M.length===0&&e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:203:35",className:"text-[11px] text-slate-600",children:"无标签"}),M.map((l,w)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:205:13",className:"grid grid-cols-[1fr_1.4fr_auto] gap-2",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:206:15",value:l.key,placeholder:"app",onChange:T=>S(w,{key:T.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:209:15",value:l.value,placeholder:"nginx",onChange:T=>S(w,{value:T.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:212:15",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-400 hover:text-red-300",onClick:()=>O(w),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:213:48",className:"h-3.5 w-3.5"})})]},w))]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:220:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:221:9",className:"pb-3",children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:222:11",className:"flex items-center justify-between",children:[e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:223:13",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx($t,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:224:15",className:"h-4 w-4 text-amber-400"}),"选择器 (Selector)",e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:226:15",variant:"outline",className:"border-amber-700/50 text-amber-500 text-[10px]",children:"⚠️ 需与模板标签一致"})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:228:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:b,children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:229:15",className:"h-3 w-3 mr-1"}),"新增"]})]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:233:9",className:"pt-0 space-y-1.5",children:[e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:234:11",className:"text-[11px] text-amber-500/70 mb-1",children:"Selector 决定哪些 Pod 归属此 Deployment。修改时必须确保与 Pod Template Labels 匹配,否则 Deployment 将无法管理 Pod。"}),U.length===0&&e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:235:43",className:"text-[11px] text-slate-600",children:"无选择器"}),U.map((l,w)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:237:13",className:"grid grid-cols-[1fr_1.4fr_auto] gap-2",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:238:15",value:l.key,placeholder:"app",onChange:T=>r(w,{key:T.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:241:15",value:l.value,placeholder:"nginx",onChange:T=>r(w,{value:T.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:244:15",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-400 hover:text-red-300",onClick:()=>f(w),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:245:51",className:"h-3.5 w-3.5"})})]},w))]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:252:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:253:9",className:"pb-3",children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:254:11",className:"flex items-center justify-between",children:[e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:255:13",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(Et,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:256:15",className:"h-4 w-4 text-purple-400"}),"注解 (Annotations)",e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:258:15",variant:"outline",className:"border-slate-700 text-slate-500 text-[10px]",children:F.length})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:260:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:ne,children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:261:15",className:"h-3 w-3 mr-1"}),"新增"]})]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:265:9",className:"pt-0 space-y-1.5",children:[F.length===0&&e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:266:40",className:"text-[11px] text-slate-600",children:"无注解"}),F.map((l,w)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:268:13",className:"grid grid-cols-[1fr_1.4fr_auto] gap-2",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:269:15",value:l.key,placeholder:"deployment.kubernetes.io/revision",onChange:T=>H(w,{key:T.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:272:15",value:l.value,placeholder:"1",onChange:T=>H(w,{value:T.target.value}),className:"bg-slate-800 border-slate-700 text-slate-200 font-mono text-xs h-8"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:275:15",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-400 hover:text-red-300",onClick:()=>oe(w),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:276:53",className:"h-3.5 w-3.5"})})]},w))]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:283:7",className:"sticky bottom-0 bg-slate-950/80 backdrop-blur border-t border-slate-800 p-3 flex items-center justify-between",children:[e.jsxs("p",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:284:9",className:"text-[11px] text-slate-500",children:["保存将通过 ",e.jsx("code",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:285:17",className:"text-slate-400",children:"PUT application/yaml"})," 提交(自动剥离 status/managedFields 等只读字段)"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:287:9",className:"flex gap-2",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:288:11",variant:"outline",className:"border-slate-700 text-slate-400",onClick:d,children:"取消"}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:289:11",className:"bg-blue-600 hover:bg-blue-700",disabled:p,onClick:P,children:[p?e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:290:23",className:"h-4 w-4 animate-spin mr-1"}):e.jsx(at,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:290:75",className:"h-4 w-4 mr-1"}),"保存"]})]})]})]}):e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:134:7",className:"bg-slate-900 border-slate-800",children:e.jsx(G,{"code-path":"src/components/kubernetes/DeploymentEditBasic.tsx:135:9",className:"p-8 text-center text-slate-500",children:"未获取到 manifest 数据,请使用 YAML 编辑模式直接修改。"})})}const Kt=[{key:"persistentVolumeClaim",label:"存储卷声明",icon:tt,color:"text-emerald-400",desc:"PVC"},{key:"emptyDir",label:"临时目录",icon:Ps,color:"text-slate-400",desc:"EmptyDir"},{key:"hostPath",label:"HostPath",icon:rs,color:"text-amber-400",desc:"主机路径"},{key:"nfs",label:"NFS",icon:jt,color:"text-purple-400",desc:"网络存储"},{key:"configMap",label:"配置字典",icon:As,color:"text-blue-400",desc:"ConfigMap"},{key:"secret",label:"密文",icon:os,color:"text-rose-400",desc:"Secret"}];function Zs(t){if(!t||typeof t!="object")return{name:"",type:"emptyDir"};const s=t.name||"";return t.emptyDir?{name:s,type:"emptyDir",medium:t.emptyDir.medium||"",sizeLimit:t.emptyDir.sizeLimit||""}:t.hostPath?{name:s,type:"hostPath",path:t.hostPath.path||"",pathType:t.hostPath.type||"Directory"}:t.configMap?{name:s,type:"configMap",configMapName:t.configMap.name||"",cmItems:t.configMap.items?JSON.stringify(t.configMap.items):""}:t.secret?{name:s,type:"secret",secretName:t.secret.secretName||"",secItems:t.secret.items?JSON.stringify(t.secret.items):""}:t.persistentVolumeClaim?{name:s,type:"persistentVolumeClaim",pvcName:t.persistentVolumeClaim.claimName||"",pvcReadOnly:!!t.persistentVolumeClaim.readOnly}:t.nfs?{name:s,type:"nfs",nfsServer:t.nfs.server||"",nfsPath:t.nfs.path||"",nfsReadOnly:!!t.nfs.readOnly}:{name:s,type:"emptyDir"}}function Qs(t){const s={name:t.name.trim()};if(!s.name)return null;switch(t.type){case"emptyDir":{const o={};t.medium&&(o.medium=t.medium),t.sizeLimit&&(o.sizeLimit=t.sizeLimit),s.emptyDir=o;break}case"hostPath":s.hostPath={path:t.path||"",type:t.pathType||"Directory"};break;case"configMap":{if(s.configMap={name:t.configMapName||""},t.cmItems)try{s.configMap.items=JSON.parse(t.cmItems)}catch{}break}case"secret":{if(s.secret={secretName:t.secretName||""},t.secItems)try{s.secret.items=JSON.parse(t.secItems)}catch{}break}case"persistentVolumeClaim":s.persistentVolumeClaim={claimName:t.pvcName||"",...t.pvcReadOnly?{readOnly:!0}:{}};break;case"nfs":s.nfs={server:t.nfsServer||"",path:t.nfsPath||"",...t.nfsReadOnly?{readOnly:!0}:{}};break}return s}function en({clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}){const{toast:i}=Pe(),[p,D]=m.useState(!1),[h,N]=m.useState(!a),[I,q]=m.useState(a||{}),[V,R]=m.useState([]),[M,z]=m.useState([]),[F,B]=m.useState([]);m.useEffect(()=>{const r=a;if(!r){N(!1);return}q(r);const b=r?.spec?.template?.spec||{},f=Array.isArray(b.volumes)?b.volumes:[];R(f.map(Zs));const P=[...b.containers||[],...b.initContainers||[]],l=P.map(T=>T.name||"(unnamed)");B(l);const w=[];for(const T of P){const c=T.name||"(unnamed)",k=Array.isArray(T.volumeMounts)?T.volumeMounts:[];for(const y of k)w.push({containerName:c,volumeName:y.name||"",mountPath:y.mountPath||"",subPath:y.subPath||"",readOnly:!!y.readOnly})}z(w),N(!1)},[a]);const U=()=>R(r=>[...r,{name:"",type:"emptyDir"}]),Y=r=>{const b=V[r]?.name;R(f=>f.filter((P,l)=>l!==r)),b&&z(f=>f.filter(P=>P.volumeName!==b))},S=(r,b)=>R(f=>f.map((P,l)=>l===r?{...P,...b}:P)),Q=()=>z(r=>[...r,{containerName:F[0]||"",volumeName:"",mountPath:"",subPath:"",readOnly:!1}]),O=r=>z(b=>b.filter((f,P)=>P!==r)),H=(r,b)=>z(f=>f.map((P,l)=>l===r?{...P,...b}:P)),ne=async()=>{D(!0);try{const r=JSON.parse(JSON.stringify(I));r.spec=r.spec||{},r.spec.template=r.spec.template||{},r.spec.template.spec=r.spec.template.spec||{};const b=r.spec.template.spec,f=V.map(Qs).filter(Boolean);f.length>0?b.volumes=f:delete b.volumes;const P=[...b.containers||[],...b.initContainers||[]];for(const w of P){const T=w.name||"(unnamed)",c=M.filter(k=>k.containerName===T&&k.volumeName&&k.mountPath).map(k=>{const y={name:k.volumeName,mountPath:k.mountPath,readOnly:k.readOnly};return k.subPath&&(y.subPath=k.subPath),y});c.length>0?w.volumeMounts=c:delete w.volumeMounts}b.containers=P.filter(w=>!(b.initContainers||[]).includes(w)),b.initContainers=b.initContainers||[];const l=JSON.stringify(r,null,2);await te.updateResourceYaml(t,s,"deployments",o,l),i({title:"存储配置已保存",description:`${o} 更新已提交`}),n()}catch(r){i({title:"保存失败",description:r?.message||String(r),variant:"destructive"})}finally{D(!1)}};if(h)return e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:193:7",className:"bg-slate-900 border-slate-800",children:e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:194:9",className:"p-12 text-center",children:[e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:195:11",className:"h-6 w-6 animate-spin mx-auto text-slate-500"}),e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:196:11",className:"text-slate-500 mt-3 text-sm",children:"加载中..."})]})});if(!a)return e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:204:7",className:"bg-slate-900 border-slate-800",children:e.jsx(G,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:205:9",className:"p-8 text-center text-slate-500",children:"未获取到 manifest 数据,请使用 YAML 编辑模式直接修改。"})});const oe=V.map(r=>r.name).filter(Boolean);return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:215:5",className:"space-y-4",children:[e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:217:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:218:9",className:"pb-3",children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:219:11",className:"flex items-center justify-between",children:[e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:220:13",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(tt,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:221:15",className:"h-4 w-4 text-emerald-400"}),"定义数据卷",e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:222:15",variant:"outline",className:"border-slate-700 text-slate-400",children:V.length})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:224:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:U,children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:225:15",className:"h-3 w-3 mr-1"}),"添加数据卷"]})]})}),e.jsx(G,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:229:9",className:"pt-0 space-y-3",children:V.length===0?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:231:13",className:"text-center py-8 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg",children:[e.jsx(tt,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:232:15",className:"h-8 w-8 mx-auto mb-2 text-slate-700"}),"未配置数据卷"]}):V.map((r,b)=>{const f=Kt.find(l=>l.key===r.type),P=f?.icon||ut;return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:239:15",className:"bg-slate-950/50 border border-slate-800 rounded-lg p-3 space-y-2.5",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:241:17",className:"flex items-center gap-2",children:[e.jsx(P,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:242:19",className:`h-4 w-4 ${f?.color||"text-slate-400"}`}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:243:19",className:"text-[10px] text-slate-500 w-16 shrink-0",children:"数据卷名称"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:244:19",value:r.name,onChange:l=>S(b,{name:l.target.value}),placeholder:"volume-name",className:"h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsxs(Le,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:247:19",value:r.type,onValueChange:l=>S(b,{type:l}),children:[e.jsx(Ge,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:248:21",className:"h-7 w-[120px] bg-slate-800 border-slate-700 text-xs text-slate-300",children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:249:23",className:"flex items-center gap-1.5",children:[e.jsx(P,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:250:25",className:"h-3 w-3"}),f?.label||r.type]})}),e.jsx(He,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:253:21",children:Kt.map(l=>{const w=l.icon;return e.jsx(ve,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:257:27",value:l.key,children:e.jsxs("span",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:258:29",className:"flex items-center gap-1.5 text-xs",children:[e.jsx(w,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:259:31",className:"h-3 w-3"}),l.label]})},l.key)})})]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:266:19",size:"icon",variant:"ghost",className:"h-7 w-7 text-red-400",onClick:()=>Y(b),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:267:21",className:"h-3.5 w-3.5"})})]}),r.type==="persistentVolumeClaim"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:273:19",className:"flex items-center gap-2 pl-[88px]",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:274:21",value:r.pvcName||"",onChange:l=>S(b,{pvcName:l.target.value}),placeholder:"PVC 名称",className:"h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:276:21",className:"flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer whitespace-nowrap",children:[e.jsx("input",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:277:23",type:"checkbox",checked:!!r.pvcReadOnly,onChange:l=>S(b,{pvcReadOnly:l.target.checked}),className:"accent-blue-500"}),"只读"]})]}),r.type==="emptyDir"&&e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:285:19",className:"flex items-center gap-2 pl-[88px]",children:e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:286:21",value:r.sizeLimit||"",onChange:l=>S(b,{sizeLimit:l.target.value}),placeholder:"sizeLimit (如 512Mi, 可为空)",className:"h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"})}),r.type==="hostPath"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:293:19",className:"flex items-center gap-2 pl-[88px]",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:294:21",value:r.path||"",onChange:l=>S(b,{path:l.target.value}),placeholder:"主机路径 /data/app",className:"h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:297:21",value:r.pathType||"Directory",onChange:l=>S(b,{pathType:l.target.value}),className:"h-7 w-28 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5",children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:299:23",value:"Directory",children:"Directory"}),e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:300:23",value:"File",children:"File"}),e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:301:23",value:"",children:"(默认)"})]})]}),r.type==="nfs"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:307:19",className:"flex items-center gap-2 pl-[88px]",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:308:21",value:r.nfsServer||"",onChange:l=>S(b,{nfsServer:l.target.value}),placeholder:"NFS Server IP",className:"h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:311:21",className:"text-slate-600 text-xs",children:":"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:312:21",value:r.nfsPath||"",onChange:l=>S(b,{nfsPath:l.target.value}),placeholder:"/export/path",className:"h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:315:21",className:"flex items-center gap-1.5 text-xs text-slate-400 cursor-pointer whitespace-nowrap",children:[e.jsx("input",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:316:23",type:"checkbox",checked:!!r.nfsReadOnly,onChange:l=>S(b,{nfsReadOnly:l.target.checked}),className:"accent-blue-500"}),"只读"]})]}),r.type==="configMap"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:324:19",className:"flex items-center gap-2 pl-[88px]",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:325:21",className:"text-[10px] text-slate-500 whitespace-nowrap",children:"ConfigMap"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:326:21",value:r.configMapName||"",onChange:l=>S(b,{configMapName:l.target.value}),placeholder:"ConfigMap 名称",className:"h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:329:21",value:r.cmItems||"",onChange:l=>S(b,{cmItems:l.target.value}),placeholder:"KeyToPath (可为空)",className:"h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"})]}),r.type==="secret"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:336:19",className:"flex items-center gap-2 pl-[88px]",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:337:21",className:"text-[10px] text-slate-500 whitespace-nowrap",children:"密文"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:338:21",value:r.secretName||"",onChange:l=>S(b,{secretName:l.target.value}),placeholder:"Secret 名称",className:"h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:341:21",value:r.secItems||"",onChange:l=>S(b,{secItems:l.target.value}),placeholder:"KeyToPath (可为空)",className:"h-7 w-40 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"})]})]},b)})})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:353:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:354:9",className:"pb-3",children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:355:11",className:"flex items-center justify-between",children:[e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:356:13",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(ut,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:357:15",className:"h-4 w-4 text-blue-400"}),"将数据卷挂载到容器",e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:358:15",variant:"outline",className:"border-slate-700 text-slate-400",children:M.length})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:360:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:Q,disabled:oe.length===0||F.length===0,children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:362:15",className:"h-3 w-3 mr-1"}),"添加挂载"]})]})}),e.jsx(G,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:366:9",className:"pt-0 space-y-2",children:M.length===0?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:368:13",className:"text-center py-8 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg",children:[e.jsx(ut,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:369:15",className:"h-8 w-8 mx-auto mb-2 text-slate-700"}),oe.length===0?"请先定义数据卷":"未配置挂载点"]}):M.map((r,b)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:373:13",className:"flex items-center gap-2 bg-slate-950/50 border border-slate-800 rounded-lg p-2.5",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:375:15",className:"text-[10px] text-slate-500 whitespace-nowrap",children:"容器:"}),e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:376:15",value:r.containerName,onChange:f=>H(b,{containerName:f.target.value}),className:"h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 min-w-[120px]",children:[F.length===0&&e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:378:45",value:"",children:"(无容器)"}),F.map(f=>e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:379:39",value:f,children:f},f))]}),e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:382:15",value:r.volumeName,onChange:f=>H(b,{volumeName:f.target.value}),className:"h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 min-w-[100px]",children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:384:17",value:"",children:"选择数据卷"}),oe.map(f=>e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:385:40",value:f,children:f},f))]}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:388:15",value:r.mountPath,onChange:f=>H(b,{mountPath:f.target.value}),placeholder:"挂载路径 /app/data",className:"h-7 flex-1 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:392:15",className:"flex items-center gap-1 bg-slate-800 rounded-lg p-0.5 border border-slate-700",children:[e.jsx("button",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:393:17",onClick:()=>H(b,{readOnly:!1}),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all ${r.readOnly?"text-slate-500":"bg-blue-500/20 text-blue-300"}`,children:"读写"}),e.jsx("button",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:397:17",onClick:()=>H(b,{readOnly:!0}),className:`px-2 py-0.5 rounded text-[10px] font-medium transition-all ${r.readOnly?"bg-amber-500/20 text-amber-300":"text-slate-500"}`,children:"只读"})]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:402:15",size:"icon",variant:"ghost",className:"h-7 w-7 text-red-400",onClick:()=>O(b),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:403:17",className:"h-3.5 w-3.5"})})]},b))})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:411:7",className:"flex justify-end gap-2 pt-2",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:412:9",variant:"outline",className:"border-slate-700 text-slate-400",onClick:d,children:"取消"}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:413:9",className:"bg-blue-600 hover:bg-blue-700",disabled:p,onClick:ne,children:[p?e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:414:21",className:"h-4 w-4 animate-spin mr-1"}):e.jsx(at,{"code-path":"src/components/kubernetes/DeploymentEditStorage.tsx:414:73",className:"h-4 w-4 mr-1"}),"保存"]})]})]})}function tn({clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}){const{toast:i}=Pe(),[p,D]=m.useState(!1),[h,N]=m.useState(!a),[I,q]=m.useState(a||{}),[V,R]=m.useState("RollingUpdate"),[M,z]=m.useState("25%"),[F,B]=m.useState("25%"),[U,Y]=m.useState("10"),[S,Q]=m.useState("600"),[O,H]=m.useState("nodeSelector"),[ne,oe]=m.useState(""),[r,b]=m.useState([]),[f,P]=m.useState(!1),[l,w]=m.useState([]),[T,c]=m.useState({}),[k,y]=m.useState([]),[J,_]=m.useState("ClusterFirst"),[$,be]=m.useState("Always"),[K,he]=m.useState("default-scheduler"),[Ne,de]=m.useState("30"),[A,ce]=m.useState(""),[ge,fe]=m.useState(""),[g,ye]=m.useState(""),[je,Ae]=m.useState(""),[We,rt]=m.useState(!1),[Je,lt]=m.useState(!1),[qe,Ce]=m.useState(!1),[Ct,St]=m.useState(!1),[Pt,At]=m.useState(!1),[dt,Ie]=m.useState([]),[Vt,Wt]=m.useState(""),[Tt,Rt]=m.useState(""),[it,Me]=m.useState([]);m.useEffect(()=>{const x=a;if(!x){N(!1);return}q(x);const j=x?.spec||{},E=j?.template?.spec||{},ee=j.strategy||{};R(ee.type||"RollingUpdate");const re=ee.rollingUpdate||{};z(String(re.maxSurge??"25%")),B(String(re.maxUnavailable??"25%")),Y(j.revisionHistoryLimit!=null?String(j.revisionHistoryLimit):"10"),Q(j.progressDeadlineSeconds!=null?String(j.progressDeadlineSeconds):"600");const ke=E.nodeSelector||{},ze=Object.entries(ke).map(([le,_e])=>({key:le,value:String(_e)}));w(ze),oe(E.nodeName||""),E.nodeName?H("nodeName"):E.affinity?.nodeAffinity?H("nodeAffinity"):ze.length>0&&H("nodeSelector"),t&&(P(!0),te.getClusterNodes(t).then(le=>{const It=(Array.isArray(le)?le:le?.items||le?.list||[]).map(Xe=>{const Ve=Xe.metadata||{},Ze=Xe.status||{},hs=(Array.isArray(Ze.addresses)?Ze.addresses:[]).find(us=>us.type==="InternalIP")?.address||"";return{name:Ve.name||"",ip:hs,labels:Ve.labels||{}}});b(It);const $e={};for(const Xe of It)for(const[Ve,Ze]of Object.entries(Xe.labels)){const mt=String(Ze);$e[Ve]||($e[Ve]=[]),$e[Ve].includes(mt)||$e[Ve].push(mt)}c($e)}).catch(()=>{}).finally(()=>P(!1)));const Ke=Array.isArray(E.tolerations)?E.tolerations:[];y(Ke.map(le=>({key:le.key||"",operator:le.operator||"Equal",value:le.value||"",effect:le.effect||"",tolerationSeconds:le.tolerationSeconds!=null?String(le.tolerationSeconds):""}))),_(E.dnsPolicy||"ClusterFirst"),be(E.restartPolicy||"Always"),he(E.schedulerName||"default-scheduler"),de(E.terminationGracePeriodSeconds!=null?String(E.terminationGracePeriodSeconds):"30"),ce(E.serviceAccountName||"");const Ee=E.securityContext||{};fe(Ee.fsGroup!=null?String(Ee.fsGroup):""),ye(Ee.runAsUser!=null?String(Ee.runAsUser):""),Ae(Ee.runAsGroup!=null?String(Ee.runAsGroup):""),rt(!!Ee.runAsNonRoot),lt(!!E.hostNetwork),Ce(!!E.hostIPC),St(!!E.hostPID),At(!!E.shareProcessNamespace);const pt=Array.isArray(E.hostAliases)?E.hostAliases:[];Ie(pt.map(le=>({ip:le.ip||"",hostnames:Array.isArray(le.hostnames)?le.hostnames.join(", "):""})));const W=E.dnsConfig||{};Wt(Array.isArray(W.nameservers)?W.nameservers.join(` +`):""),Rt(Array.isArray(W.searches)?W.searches.join(` +`):"");const me=Array.isArray(W.options)?W.options:[];Me(me.map(le=>({name:le.name||"",value:le.value||""}))),N(!1)},[a]);const Bt=()=>w(x=>[...x,{key:"",value:""}]),Ot=x=>w(j=>j.filter((E,ee)=>ee!==x)),Ue=(x,j)=>w(E=>E.map((ee,re)=>re===x?{...ee,...j}:ee)),xs=async()=>{D(!0);try{const x=JSON.parse(JSON.stringify(I));x.spec=x.spec||{},x.spec.template=x.spec.template||{},x.spec.template.spec=x.spec.template.spec||{};const j=x.spec.template.spec;if(x.spec.strategy={type:V},V==="RollingUpdate"&&(x.spec.strategy.rollingUpdate={maxSurge:M,maxUnavailable:F}),U&&(x.spec.revisionHistoryLimit=Number(U)),S&&(x.spec.progressDeadlineSeconds=Number(S)),O==="nodeName"&&ne.trim())j.nodeName=ne.trim(),delete j.nodeSelector,j.affinity&&delete j.affinity.nodeAffinity;else if(O==="nodeSelector"){const W={};for(const{key:me,value:le}of l){const _e=me.trim();_e&&(W[_e]=le)}Object.keys(W).length>0?j.nodeSelector=W:delete j.nodeSelector,j.nodeName&&delete j.nodeName,j.affinity&&delete j.affinity.nodeAffinity}else if(O==="nodeAffinity"){const W=l.filter(me=>me.key.trim()).map(me=>({key:me.key.trim(),operator:"In",values:[me.value]}));W.length>0?(j.affinity=j.affinity||{},j.affinity.nodeAffinity={requiredDuringSchedulingIgnoredDuringExecution:{nodeSelectorTerms:[{matchExpressions:W}]}}):j.affinity&&delete j.affinity.nodeAffinity,delete j.nodeSelector,j.nodeName&&delete j.nodeName}const E=k.filter(W=>W.key||W.operator==="Exists").map(W=>{const me={};return W.key&&(me.key=W.key),W.operator&&(me.operator=W.operator),W.value&&W.operator!=="Exists"&&(me.value=W.value),W.effect&&(me.effect=W.effect),W.tolerationSeconds&&W.effect==="NoExecute"&&(me.tolerationSeconds=Number(W.tolerationSeconds)),me});E.length>0?j.tolerations=E:delete j.tolerations,J&&(j.dnsPolicy=J),$&&(j.restartPolicy=$),K&&(j.schedulerName=K),Ne&&(j.terminationGracePeriodSeconds=Number(Ne)),A&&(j.serviceAccountName=A);const ee={};ge&&(ee.fsGroup=Number(ge)),g&&(ee.runAsUser=Number(g)),je&&(ee.runAsGroup=Number(je)),We&&(ee.runAsNonRoot=!0),Object.keys(ee).length>0?j.securityContext=ee:delete j.securityContext,Je?j.hostNetwork=!0:delete j.hostNetwork,qe?j.hostIPC=!0:delete j.hostIPC,Ct?j.hostPID=!0:delete j.hostPID,Pt?j.shareProcessNamespace=!0:delete j.shareProcessNamespace;const re=dt.filter(W=>W.ip.trim()).map(W=>({ip:W.ip.trim(),hostnames:W.hostnames.split(/[,\s]+/).map(me=>me.trim()).filter(Boolean)})).filter(W=>W.hostnames.length>0);re.length>0?j.hostAliases=re:delete j.hostAliases;const ke={},ze=Vt.split(` +`).map(W=>W.trim()).filter(Boolean);ze.length>0&&(ke.nameservers=ze);const Ke=Tt.split(` +`).map(W=>W.trim()).filter(Boolean);Ke.length>0&&(ke.searches=Ke);const Ee=it.filter(W=>W.name.trim()).map(W=>{const me={name:W.name.trim()};return W.value.trim()&&(me.value=W.value.trim()),me});Ee.length>0&&(ke.options=Ee),Object.keys(ke).length>0?j.dnsConfig=ke:delete j.dnsConfig;const pt=JSON.stringify(x,null,2);await te.updateResourceYaml(t,s,"deployments",o,pt),i({title:"高级设置已保存",description:`${o} 更新已提交`}),n()}catch(x){i({title:"保存失败",description:x?.message||String(x),variant:"destructive"})}finally{D(!1)}};return h?e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:328:7",className:"bg-slate-900 border-slate-800",children:e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:329:9",className:"p-12 text-center",children:[e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:330:11",className:"h-6 w-6 animate-spin mx-auto text-slate-500"}),e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:331:11",className:"text-slate-500 mt-3 text-sm",children:"加载中..."})]})}):a?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:348:5",className:"space-y-4",children:[e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:350:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:351:9",className:"pb-3",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:352:11",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(ct,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:353:13",className:"h-4 w-4 text-blue-400"}),"更新策略 (Strategy)"]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:356:9",className:"pt-0 space-y-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:357:11",className:"flex items-center gap-4",children:[e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:358:13",className:"flex items-center gap-1.5 text-xs text-slate-300 cursor-pointer",children:[e.jsx("input",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:359:15",type:"radio",checked:V==="RollingUpdate",onChange:()=>R("RollingUpdate"),className:"accent-blue-500"}),"RollingUpdate(滚动更新)"]}),e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:363:13",className:"flex items-center gap-1.5 text-xs text-slate-300 cursor-pointer",children:[e.jsx("input",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:364:15",type:"radio",checked:V==="Recreate",onChange:()=>R("Recreate"),className:"accent-blue-500"}),"Recreate(重建)"]})]}),V==="RollingUpdate"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:370:13",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:371:15",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:372:17",className:"text-slate-500 text-xs",children:"maxSurge(整数或百分比,超出期望副本数)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:373:17",value:M,onChange:x=>z(x.target.value),placeholder:"25%",className:"h-8 mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:376:15",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:377:17",className:"text-slate-500 text-xs",children:"maxUnavailable(整数或百分比,不可用上限)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:378:17",value:F,onChange:x=>B(x.target.value),placeholder:"25%",className:"h-8 mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]})]})]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:387:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:388:9",className:"pb-3",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:389:11",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(ss,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:390:13",className:"h-4 w-4 text-amber-400"}),"历史版本 & 进度"]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:393:9",className:"pt-0 grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:394:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:395:13",className:"text-slate-500 text-xs",children:"revisionHistoryLimit(保留 RS 历史)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:396:13",type:"number",value:U,onChange:x=>Y(x.target.value),className:"h-8 mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:399:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:400:13",className:"text-slate-500 text-xs",children:"progressDeadlineSeconds(升级超时秒数)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:401:13",type:"number",value:S,onChange:x=>Q(x.target.value),className:"h-8 mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]})]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:408:7",className:"bg-slate-900 border-slate-800",children:[e.jsxs(ie,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:409:9",className:"pb-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:410:11",className:"flex items-center justify-between",children:[e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:411:13",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(jt,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:412:15",className:"h-4 w-4 text-emerald-400"}),"调度 (Scheduling)"]}),e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:414:13",className:"flex items-center gap-1 bg-slate-800 rounded-lg p-0.5 border border-slate-700",children:[{key:"nodeName",label:"节点名称",desc:"指定节点"},{key:"nodeSelector",label:"标签选择器",desc:"key=value"},{key:"nodeAffinity",label:"节点亲和性",desc:"高级规则"}].map(x=>e.jsx("button",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:420:17",onClick:()=>H(x.key),className:`px-2.5 py-1 rounded text-[10px] font-medium transition-all ${O===x.key?"bg-emerald-500/20 text-emerald-300 shadow-sm":"text-slate-400 hover:text-slate-300"}`,children:x.label},x.key))})]}),e.jsxs("p",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:431:11",className:"text-xs text-slate-500 mt-1",children:[O==="nodeName"&&"Pod 将直接调度到指定节点",O==="nodeSelector"&&"Pod 将调度到匹配标签的节点",O==="nodeAffinity"&&"通过亲和性规则控制 Pod 调度到指定节点"]})]}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:437:9",className:"pt-0",children:[O==="nodeName"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:440:13",className:"space-y-2",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:441:15",className:"text-slate-400 text-xs",children:"请选择节点"}),f?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:443:17",className:"flex items-center gap-1 text-slate-500 text-xs",children:[e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:443:81",className:"h-3 w-3 animate-spin"}),"加载节点列表..."]}):e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:445:17",value:ne,onChange:x=>oe(x.target.value),className:"h-8 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2",children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:447:19",value:"",children:"(不指定)"}),r.map(x=>e.jsxs("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:449:21",value:x.name,children:[x.name," ",x.ip?`(${x.ip})`:""]},x.name))]}),ne&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:454:17",className:"text-[10px] text-slate-500",children:["已选择: ",e.jsx("code",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:455:24",className:"bg-slate-800 px-1 py-0.5 rounded text-emerald-400",children:ne})]})]}),O==="nodeSelector"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:463:13",className:"space-y-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:464:15",className:"flex items-center justify-between",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:465:17",className:"text-slate-400 text-xs",children:"请选择标签"}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:466:17",size:"sm",variant:"ghost",className:"h-6 text-xs text-slate-400",onClick:Bt,children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:467:19",className:"h-3 w-3 mr-1"}),"添加"]})]}),l.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:471:17",className:"text-xs text-slate-600 italic",children:"未配置标签选择器"}):l.map((x,j)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:473:17",className:"flex items-center gap-2",children:[e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:475:19",value:x.key,onChange:E=>Ue(j,{key:E.target.value,value:""}),className:"flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5",children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:477:21",value:"",children:"选择标签"}),Object.entries(T).map(([E,ee])=>e.jsxs("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:479:23",value:E,children:[E," (",ee.length,")"]},E))]}),e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:483:19",value:x.value,onChange:E=>Ue(j,{value:E.target.value}),className:"flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5",disabled:!x.key,children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:486:21",value:"",children:"选择值"}),(T[x.key]||[]).map(E=>e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:488:23",value:E,children:E},E))]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:491:19",size:"icon",variant:"ghost",className:"h-6 w-6 text-red-400",onClick:()=>Ot(j),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:492:21",className:"h-3 w-3"})})]},j))]}),O==="nodeAffinity"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:501:13",className:"space-y-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:502:15",className:"flex items-center justify-between",children:[e.jsxs(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:503:17",className:"text-slate-400 text-xs",children:["请选择标签 ",e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:504:25",className:"text-slate-600",children:"(生成 requiredDuringScheduling 规则)"})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:506:17",size:"sm",variant:"ghost",className:"h-6 text-xs text-slate-400",onClick:Bt,children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:507:19",className:"h-3 w-3 mr-1"}),"添加"]})]}),l.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:511:17",className:"text-xs text-slate-600 italic",children:"未配置亲和性规则"}):l.map((x,j)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:513:17",className:"flex items-center gap-2",children:[e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:514:19",value:x.key,onChange:E=>Ue(j,{key:E.target.value,value:""}),className:"flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5",children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:516:21",value:"",children:"选择标签"}),Object.entries(T).map(([E,ee])=>e.jsxs("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:518:23",value:E,children:[E," (",ee.length,")"]},E))]}),e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:521:19",value:x.value,onChange:E=>Ue(j,{value:E.target.value}),className:"flex-1 h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5",disabled:!x.key,children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:524:21",value:"",children:"选择值"}),(T[x.key]||[]).map(E=>e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:526:23",value:E,children:E},E))]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:529:19",size:"icon",variant:"ghost",className:"h-6 w-6 text-red-400",onClick:()=>Ot(j),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:530:21",className:"h-3 w-3"})})]},j))]})]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:540:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:541:9",className:"pb-3",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:542:11",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(vt,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:543:13",className:"h-4 w-4 text-slate-400"}),"Pod 级别"]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:546:9",className:"pt-0 grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:547:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:548:13",className:"text-slate-500 text-xs",children:"dnsPolicy"}),e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:549:13",value:J,onChange:x=>_(x.target.value),className:"h-8 mt-1 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2",children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:551:15",value:"ClusterFirst",children:"ClusterFirst"}),e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:552:15",value:"ClusterFirstWithHostNet",children:"ClusterFirstWithHostNet"}),e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:553:15",value:"Default",children:"Default"}),e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:554:15",value:"None",children:"None"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:557:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:558:13",className:"text-slate-500 text-xs",children:"restartPolicy"}),e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:559:13",value:$,onChange:x=>be(x.target.value),className:"h-8 mt-1 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2",children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:561:15",value:"Always",children:"Always"}),e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:562:15",value:"OnFailure",children:"OnFailure"}),e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:563:15",value:"Never",children:"Never"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:566:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:567:13",className:"text-slate-500 text-xs",children:"schedulerName"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:568:13",value:K,onChange:x=>he(x.target.value),className:"h-8 mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:571:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:572:13",className:"text-slate-500 text-xs",children:"terminationGracePeriodSeconds"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:573:13",type:"number",value:Ne,onChange:x=>de(x.target.value),className:"h-8 mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:576:11",className:"col-span-2",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:577:13",className:"text-slate-500 text-xs",children:"serviceAccountName"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:578:13",value:A,onChange:x=>ce(x.target.value),placeholder:"default",className:"h-8 mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]})]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:585:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:586:9",className:"pb-3",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:587:11",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(ns,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:588:13",className:"h-4 w-4 text-rose-400"}),"Pod 安全上下文 (securityContext)"]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:591:9",className:"pt-0 grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:592:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:593:13",className:"text-slate-500 text-xs",children:"fsGroup"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:594:13",type:"number",value:ge,onChange:x=>fe(x.target.value),placeholder:"1000",className:"h-8 mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:597:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:598:13",className:"text-slate-500 text-xs",children:"runAsUser"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:599:13",type:"number",value:g,onChange:x=>ye(x.target.value),placeholder:"1000",className:"h-8 mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:602:11",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:603:13",className:"text-slate-500 text-xs",children:"runAsGroup"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:604:13",type:"number",value:je,onChange:x=>Ae(x.target.value),placeholder:"1000",className:"h-8 mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]}),e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:607:11",className:"flex items-end pb-1",children:e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:608:13",className:"flex items-center gap-2 text-xs text-slate-400 cursor-pointer",children:[e.jsx("input",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:609:15",type:"checkbox",checked:We,onChange:x=>rt(x.target.checked),className:"accent-blue-500"}),"runAsNonRoot"]})})]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:618:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:619:9",className:"pb-3",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:620:11",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(Se,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:621:13",className:"h-4 w-4 text-cyan-400"}),"主机设置 (Host Namespace)"]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:624:9",className:"pt-0 grid grid-cols-2 gap-3",children:[e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:625:11",className:"flex items-center gap-2 text-xs text-slate-300 cursor-pointer",children:[e.jsx("input",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:626:13",type:"checkbox",checked:Je,onChange:x=>lt(x.target.checked),className:"accent-blue-500"}),"hostNetwork(共享主机网络命名空间)"]}),e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:630:11",className:"flex items-center gap-2 text-xs text-slate-300 cursor-pointer",children:[e.jsx("input",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:631:13",type:"checkbox",checked:qe,onChange:x=>Ce(x.target.checked),className:"accent-blue-500"}),"hostIPC(共享主机 IPC 命名空间)"]}),e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:635:11",className:"flex items-center gap-2 text-xs text-slate-300 cursor-pointer",children:[e.jsx("input",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:636:13",type:"checkbox",checked:Ct,onChange:x=>St(x.target.checked),className:"accent-blue-500"}),"hostPID(共享主机 PID 命名空间)"]}),e.jsxs("label",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:640:11",className:"flex items-center gap-2 text-xs text-slate-300 cursor-pointer",children:[e.jsx("input",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:641:13",type:"checkbox",checked:Pt,onChange:x=>At(x.target.checked),className:"accent-blue-500"}),"shareProcessNamespace(共享进程命名空间)"]})]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:649:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:650:9",className:"pb-3",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:651:11",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(ks,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:652:13",className:"h-4 w-4 text-indigo-400"}),"DNS 配置 (dnsConfig)"]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:655:9",className:"pt-0 space-y-3",children:[e.jsxs("p",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:656:11",className:"text-[11px] text-slate-500",children:["提示:dnsConfig 通常与 ",e.jsx("code",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:657:30",className:"text-slate-400",children:"dnsPolicy: None"})," 搭配使用。每行一个值。"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:659:11",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:660:13",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:661:15",className:"text-slate-500 text-xs",children:"nameservers(每行一个 IP)"}),e.jsx("textarea",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:662:15",value:Vt,onChange:x=>Wt(x.target.value),placeholder:`8.8.8.8 +114.114.114.114`,rows:3,className:"w-full mt-1 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 font-mono p-2 resize-y"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:667:13",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:668:15",className:"text-slate-500 text-xs",children:"searches(搜索域,每行一个)"}),e.jsx("textarea",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:669:15",value:Tt,onChange:x=>Rt(x.target.value),placeholder:`svc.cluster.local +cluster.local`,rows:3,className:"w-full mt-1 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 font-mono p-2 resize-y"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:675:11",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:676:13",className:"flex items-center justify-between mb-1",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:677:15",className:"text-slate-400 text-xs",children:"options(DNS 选项)"}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:678:15",size:"sm",variant:"ghost",className:"h-6 text-xs text-slate-400",onClick:()=>Me(x=>[...x,{name:"",value:""}]),children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:680:17",className:"h-3 w-3 mr-1"}),"添加"]})]}),it.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:684:15",className:"text-xs text-slate-600 italic",children:"未配置"}):it.map((x,j)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:686:15",className:"flex items-center gap-2 mb-1.5",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:687:17",value:x.name,onChange:E=>Me(ee=>ee.map((re,ke)=>ke===j?{...re,name:E.target.value}:re)),placeholder:"ndots",className:"flex-1 h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:689:17",className:"text-slate-600",children:":"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:690:17",value:x.value,onChange:E=>Me(ee=>ee.map((re,ke)=>ke===j?{...re,value:E.target.value}:re)),placeholder:"5(可留空)",className:"flex-1 h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:692:17",size:"icon",variant:"ghost",className:"h-6 w-6 text-red-400",onClick:()=>Me(E=>E.filter((ee,re)=>re!==j)),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:694:19",className:"h-3 w-3"})})]},j))]})]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:703:7",className:"bg-slate-900 border-slate-800",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:704:9",className:"pb-3",children:e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:705:11",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(vs,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:706:13",className:"h-4 w-4 text-amber-400"}),"主机别名 (hostAliases)"]})}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:709:9",className:"pt-0 space-y-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:710:11",className:"flex items-center justify-between mb-1",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:711:13",className:"text-slate-400 text-xs",children:"IP → 主机名映射(注入 Pod 的 /etc/hosts)"}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:712:13",size:"sm",variant:"ghost",className:"h-6 text-xs text-slate-400",onClick:()=>Ie(x=>[...x,{ip:"",hostnames:""}]),children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:714:15",className:"h-3 w-3 mr-1"}),"添加"]})]}),dt.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:718:13",className:"text-xs text-slate-600 italic",children:"未配置"}):dt.map((x,j)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:720:13",className:"flex items-center gap-2",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:721:15",value:x.ip,onChange:E=>Ie(ee=>ee.map((re,ke)=>ke===j?{...re,ip:E.target.value}:re)),placeholder:"10.10.10.72",className:"w-40 h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:723:15",className:"text-slate-600",children:"→"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:724:15",value:x.hostnames,onChange:E=>Ie(ee=>ee.map((re,ke)=>ke===j?{...re,hostnames:E.target.value}:re)),placeholder:"gitlab.local, registry.local",className:"flex-1 h-7 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:726:15",size:"icon",variant:"ghost",className:"h-6 w-6 text-red-400",onClick:()=>Ie(E=>E.filter((ee,re)=>re!==j)),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:728:17",className:"h-3 w-3"})})]},j))]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:736:7",className:"flex justify-end gap-2 pt-2",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:737:9",variant:"outline",className:"border-slate-700 text-slate-400",onClick:d,children:"取消"}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:738:9",className:"bg-blue-600 hover:bg-blue-700",disabled:p,onClick:xs,children:[p?e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:739:21",className:"h-4 w-4 animate-spin mr-1"}):e.jsx(at,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:739:73",className:"h-4 w-4 mr-1"}),"保存"]})]})]}):e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:339:7",className:"bg-slate-900 border-slate-800",children:e.jsx(G,{"code-path":"src/components/kubernetes/DeploymentEditAdvanced.tsx:340:9",className:"p-8 text-center text-slate-500",children:"未获取到 manifest 数据,请使用 YAML 编辑模式直接修改。"})})}const sn=[{label:"HTTP",protocol:"TCP",port:8080,targetPort:8080,name:"http"},{label:"WebSocket",protocol:"TCP",port:8001,targetPort:8002,name:"ws"},{label:"gRPC",protocol:"TCP",port:8002,targetPort:8002,name:"grpc"}],Xt=t=>Array.isArray(t)?t:t?.list||t?.items||t?.data||[];function nn({clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}){const{toast:i}=Pe(),[p,D]=m.useState(!0),[h,N]=m.useState([]),[I,q]=m.useState([]),[V,R]=m.useState({}),[M,z]=m.useState(null),[F,B]=m.useState(null),[U,Y]=m.useState({name:"",type:"ClusterIP",ports:[{name:"http",port:"8080",targetPort:"8080",protocol:"TCP",nodePort:""}]}),[S,Q]=m.useState({name:"",className:"nginx",host:"",path:"/",pathType:"Prefix",svcPort:"80"}),O=c=>{Y(k=>({...k,ports:[...k.ports,c?{name:c.name,port:String(c.port),targetPort:String(c.targetPort),protocol:c.protocol,nodePort:""}:{name:"",port:"",targetPort:"",protocol:"TCP",nodePort:""}]}))},H=(c,k,y)=>{Y(J=>({...J,ports:J.ports.map((_,$)=>$===c?{..._,[k]:y}:_)}))},ne=c=>{U.ports.length<=1||Y(k=>({...k,ports:k.ports.filter((y,J)=>J!==c)}))},oe=m.useCallback(async()=>{D(!0);try{const c=a?.spec?.selector?.matchLabels||a?.selector||{};R(c);const[k,y]=await Promise.all([te.getNamespaceServices(t,s).catch(()=>[]),te.getNamespaceIngresses(t,s).catch(()=>[])]),J=Xt(k),_=Xt(y),$=J.map(K=>{const he=K.spec||{},Ne=Array.isArray(he.ports)?he.ports.map(de=>({port:de.port,targetPort:de.targetPort,protocol:de.protocol||"TCP",nodePort:de.nodePort,name:de.name})):Array.isArray(K.portList)?K.portList.map(de=>({port:de.port,targetPort:de.targetPort,protocol:de.protocol||"TCP",nodePort:de.nodePort,name:de.name})):[];return{name:K.name||K.metadata?.name||"",type:he.type||K.type||"ClusterIP",clusterIP:he.clusterIP||K.cluster_ip||"",externalIP:Array.isArray(he.externalIPs)?he.externalIPs.join(","):"",ports:Ne,selector:he.selector||K.selector||{},age:K.age||K.created_at||"",raw:K}}),be=_.map(K=>{const he=K.spec||{},de=(Array.isArray(he.rules)?he.rules:Array.isArray(K.rules)?K.rules:[]).map(A=>({host:A.host||"",paths:(A.http?.paths||A.paths||[]).map(ce=>({path:ce.path||"/",backend:{service:ce.backend?.service?.name||ce.backendService||"",port:ce.backend?.service?.port?.number||ce.backend?.service?.port?.name||ce.backendPort||""}}))}));return{name:K.name||K.metadata?.name||"",className:he.ingressClassName||K.ingressClass||"",hosts:de.map(A=>A.host).filter(Boolean),rules:de,raw:K}});N($),q(be)}catch(c){console.error("M9 load error:",c)}finally{D(!1)}},[t,s,a]);m.useEffect(()=>{oe()},[oe]);const r=c=>Object.keys(c).length===0?!1:Object.entries(c).every(([k,y])=>V[k]===y),b=h.filter(c=>r(c.selector)),f=new Set(b.map(c=>c.name)),P=I.filter(c=>c.rules.some(k=>k.paths.some(y=>f.has(y.backend.service)))),l=async()=>{const c=U.name.trim()||`${o}-svc`,k=U.ports.map(_=>{const $={name:_.name||"http",port:Number(_.port)||80,targetPort:/^\d+$/.test(String(_.targetPort))?Number(_.targetPort):_.targetPort,protocol:_.protocol||"TCP"};return U.type==="NodePort"&&_.nodePort&&($.nodePort=Number(_.nodePort)),$}),y={apiVersion:"v1",kind:"Service",metadata:{name:c,namespace:s,labels:{app:o}},spec:{type:U.type,selector:V,ports:k}},J=JSON.stringify(y,null,2);try{await te.updateResourceYaml(t,s,"services",c,J),i({title:"Service 已创建",description:c}),B(null),oe()}catch(_){i({title:"创建失败",description:_?.message||String(_),variant:"destructive"})}},w=async()=>{const c=S.name.trim()||`${o}-ingress`,k=b[0]?.name||`${o}-svc`,y=Number(S.svcPort)||80,J={apiVersion:"networking.k8s.io/v1",kind:"Ingress",metadata:{name:c,namespace:s,labels:{app:o}},spec:{ingressClassName:S.className||void 0,rules:[{host:S.host||void 0,http:{paths:[{path:S.path||"/",pathType:S.pathType||"Prefix",backend:{service:{name:k,port:{number:y}}}}]}}]}};S.className||delete J.spec.ingressClassName;const _=JSON.stringify(J,null,2);try{await te.updateResourceYaml(t,s,"ingresses",c,_),i({title:"Ingress 已创建",description:c}),B(null),oe()}catch($){i({title:"创建失败",description:$?.message||String($),variant:"destructive"})}},T=async(c,k)=>{if(window.confirm(`确认删除 ${c==="service"?"Service":"Ingress"} 「${k}」?此操作不可撤销。`))try{const y=c==="service"?"services":"ingresses";await te.deleteResourceYaml(t,s,y,k),i({title:"已删除",description:`${c==="service"?"Service":"Ingress"} ${k} 已删除`}),oe()}catch(y){i({title:"删除失败",description:y?.message||String(y),variant:"destructive"})}};return p?e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:281:7",className:"bg-slate-900 border-slate-800",children:e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:282:9",className:"p-12 text-center",children:[e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:283:11",className:"h-6 w-6 animate-spin mx-auto text-slate-500"}),e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:284:11",className:"text-slate-500 mt-3 text-sm",children:"加载中..."})]})}):e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:291:5",className:"space-y-4",children:[e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:293:7",className:"bg-slate-900/50 border-slate-800",children:e.jsx(G,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:294:9",className:"p-3",children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:295:11",className:"flex items-center gap-2 text-xs text-slate-400",children:[e.jsx(Se,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:296:13",className:"h-3.5 w-3.5 text-blue-400"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:297:13",children:"选择器:"}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:298:13",className:"flex flex-wrap gap-1",children:[Object.entries(V).map(([c,k])=>e.jsxs("code",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:300:17",className:"bg-slate-800 px-1.5 py-0.5 rounded text-slate-300 text-[11px]",children:[c,"=",k]},c)),Object.keys(V).length===0&&e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:303:17",className:"text-slate-600 italic",children:"(无 selector)"})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:306:13",size:"sm",variant:"ghost",className:"h-6 ml-auto text-xs text-slate-400",onClick:oe,children:[e.jsx(ct,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:307:15",className:"h-3 w-3 mr-1"}),"刷新"]})]})})}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:314:7",className:"bg-slate-900 border-slate-800",children:[e.jsxs(ie,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:315:9",className:"pb-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:316:11",className:"flex items-center justify-between",children:[e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:317:13",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(Se,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:318:15",className:"h-4 w-4 text-blue-400"}),"Services",e.jsxs(se,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:320:15",variant:"outline",className:"border-slate-700 text-slate-400",children:[b.length," 个关联"]})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:322:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:()=>{Y({name:`${o}-svc`,type:"ClusterIP",ports:[{name:"http",port:"8080",targetPort:"8080",protocol:"TCP",nodePort:""}]}),B("service")},children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:327:15",className:"h-3 w-3 mr-1"}),"创建 Service"]})]}),e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:330:11",className:"text-xs text-slate-500 mt-1",children:"仅显示 selector 匹配此 Deployment 的关联 Service"})]}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:332:9",className:"pt-0",children:[b.length===0&&F!=="service"?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:334:13",className:"text-center py-6 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg",children:[e.jsx(Se,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:335:15",className:"h-8 w-8 mx-auto mb-2 text-slate-700"}),"当前命名空间暂无关联 Service"]}):e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:339:13",className:"space-y-2",children:b.map(c=>{const k=r(c.selector);return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:343:19",className:`rounded-lg border p-3 ${k?"border-blue-700/50 bg-blue-950/20":"border-slate-800 bg-slate-950/30"}`,children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:344:21",className:"flex items-center gap-2 flex-wrap",children:[k?e.jsx(gt,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:345:34",className:"h-4 w-4 text-blue-400"}):e.jsx(Se,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:345:86",className:"h-4 w-4 text-slate-500"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:346:23",className:"text-sm font-semibold text-slate-200",children:c.name}),e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:347:23",variant:"outline",className:"border-slate-700 text-slate-400 text-[10px]",children:c.type}),k&&e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:348:35",className:"bg-blue-500/20 text-blue-300 border-blue-500/30 text-[10px]",children:"关联"}),e.jsx("code",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:349:23",className:"text-[11px] text-slate-500 ml-auto",children:c.clusterIP}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:350:23",size:"sm",variant:"ghost",className:"h-6 text-xs text-slate-400",onClick:()=>z({kind:"service",name:c.name}),children:[e.jsx(Dt,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:352:25",className:"h-3 w-3 mr-1"}),"YAML"]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:354:23",size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-red-400 hover:text-red-300",title:"删除 Service",onClick:()=>T("service",c.name),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:356:25",className:"h-3 w-3"})})]}),e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:360:21",className:"mt-2 flex flex-wrap gap-1.5 text-[11px]",children:c.ports.map((y,J)=>e.jsxs("code",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:362:25",className:"bg-slate-800/60 px-1.5 py-0.5 rounded text-slate-300",children:[y.name&&e.jsxs("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:363:38",className:"text-slate-500",children:[y.name,": "]}),y.port,"→",y.targetPort,y.nodePort?`/NodePort:${y.nodePort}`:"","/",y.protocol]},J))}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:369:21",className:"mt-1 flex flex-wrap gap-1 text-[10px]",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:370:23",className:"text-slate-600",children:"selector:"}),Object.entries(c.selector).map(([y,J])=>e.jsxs("code",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:372:25",className:"text-slate-500",children:[y,"=",J]},y))]})]},c.name)})}),F==="service"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:383:13",className:"mt-3 border border-blue-800/50 rounded-lg p-3 bg-blue-950/20 space-y-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:384:15",className:"text-xs font-semibold text-blue-300 flex items-center gap-1.5",children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:385:17",className:"h-3 w-3"}),"创建新 Service"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:389:15",className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:390:17",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:391:19",className:"text-slate-500 text-[11px]",children:"名称"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:392:19",value:U.name,onChange:c=>Y(k=>({...k,name:c.target.value})),placeholder:`${o}-svc`,className:"h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:396:17",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:397:19",className:"text-slate-500 text-[11px]",children:"类型"}),e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:398:19",value:U.type,onChange:c=>Y(k=>({...k,type:c.target.value})),className:"h-7 mt-0.5 w-full bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2",children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:400:21",value:"ClusterIP",children:"ClusterIP"}),e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:401:21",value:"NodePort",children:"NodePort"})]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:407:15",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:408:17",className:"text-slate-500 text-[11px] mb-1 block",children:"快速添加常用端口"}),e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:409:17",className:"flex gap-1.5",children:sn.map(c=>e.jsxs("button",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:411:21",onClick:()=>O(c),className:`flex items-center gap-1 px-2 py-1 rounded text-[10px] font-medium + bg-slate-800 border border-slate-700 text-slate-300 hover:border-blue-500/50 hover:text-blue-300 transition-colors`,children:[e.jsx(is,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:414:23",className:"h-2.5 w-2.5"}),c.label,e.jsxs("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:416:23",className:"text-slate-500 text-[9px]",children:[c.protocol," ",c.port,":",c.targetPort]})]},c.name))})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:423:15",className:"space-y-2",children:[e.jsxs(C,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:424:17",className:"text-slate-500 text-[11px]",children:["端口配置 ",e.jsxs("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:425:24",className:"text-slate-600",children:["(",U.ports.length," 个端口)"]})]}),U.ports.map((c,k)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:428:19",className:"flex items-center gap-1.5 p-2 rounded bg-slate-800/50 border border-slate-700/50",children:[e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:430:21",value:c.name,onChange:y=>H(k,"name",y.target.value),placeholder:"http",className:"h-7 w-[72px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsxs("select",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:434:21",value:c.protocol,onChange:y=>H(k,"protocol",y.target.value),className:"h-7 bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-1.5 w-16",children:[e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:436:23",value:"TCP",children:"TCP"}),e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:437:23",value:"UDP",children:"UDP"})]}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:440:21",value:c.port,onChange:y=>H(k,"port",y.target.value),type:"number",placeholder:"port",className:"h-7 w-[72px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:443:21",className:"text-slate-600 text-[10px]",children:"→"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:444:21",value:c.targetPort,onChange:y=>H(k,"targetPort",y.target.value),type:"number",placeholder:"targetPort",className:"h-7 w-[72px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),U.type==="NodePort"&&e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:449:23",value:c.nodePort,onChange:y=>H(k,"nodePort",y.target.value),type:"number",placeholder:"30000-32767",className:"h-7 w-[80px] bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:454:21",size:"icon",variant:"ghost",className:"h-6 w-6 text-slate-500 hover:text-red-400",onClick:()=>ne(k),disabled:U.ports.length<=1,children:e.jsx(ft,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:456:23",className:"h-3 w-3"})})]},k)),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:461:17",size:"sm",variant:"outline",className:"h-7 w-full border-dashed border-slate-700 text-slate-400 text-xs",onClick:()=>O(),children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:463:19",className:"h-3 w-3 mr-1"}),"添加自定义端口"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:468:15",className:"text-[10px] text-slate-500 border-t border-slate-700/50 pt-2",children:[e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:469:17",className:"text-slate-600",children:"selector (自动检测): "}),Object.keys(V).length>0?Object.entries(V).map(([c,k])=>e.jsxs("code",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:472:21",className:"bg-slate-800 px-1 py-0.5 rounded text-slate-400 ml-1",children:[c,"=",k]},c)):e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:475:19",className:"text-slate-600 italic",children:"未检测到"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:479:15",className:"flex justify-end gap-2 pt-1",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:480:17",size:"sm",variant:"ghost",className:"h-7 text-xs text-slate-400",onClick:()=>B(null),children:"取消"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:481:17",size:"sm",className:"h-7 bg-blue-600 hover:bg-blue-700 text-xs",onClick:l,children:"创建"})]})]})]})]}),e.jsxs(L,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:489:7",className:"bg-slate-900 border-slate-800",children:[e.jsxs(ie,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:490:9",className:"pb-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:491:11",className:"flex items-center justify-between",children:[e.jsxs(pe,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:492:13",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(xt,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:493:15",className:"h-4 w-4 text-purple-400"}),"Ingresses (应用路由)",e.jsxs(se,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:495:15",variant:"outline",className:"border-slate-700 text-slate-400",children:[P.length,"/",I.length]})]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:497:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:()=>{Q(c=>({...c,name:`${o}-ingress`,svcPort:String(b[0]?.ports[0]?.port||80)})),B("ingress")},children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:502:15",className:"h-3 w-3 mr-1"}),"创建 Ingress"]})]}),e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:505:11",className:"text-xs text-slate-500 mt-1",children:"backend 指向关联 Service 的 Ingress 自动高亮"})]}),e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:507:9",className:"pt-0",children:[I.length===0?e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:509:13",className:"text-center py-6 text-slate-500 text-sm border border-dashed border-slate-800 rounded-lg",children:[e.jsx(xt,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:510:15",className:"h-8 w-8 mx-auto mb-2 text-slate-700"}),"当前命名空间暂无 Ingress"]}):e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:514:13",className:"space-y-2",children:I.map(c=>{const k=P.includes(c);return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:518:19",className:`rounded-lg border p-3 ${k?"border-purple-700/50 bg-purple-950/20":"border-slate-800 bg-slate-950/30"}`,children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:519:21",className:"flex items-center gap-2 flex-wrap",children:[k?e.jsx(gt,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:520:34",className:"h-4 w-4 text-purple-400"}):e.jsx(xt,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:520:88",className:"h-4 w-4 text-slate-500"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:521:23",className:"text-sm font-semibold text-slate-200",children:c.name}),e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:522:23",variant:"outline",className:"border-slate-700 text-slate-400 text-[10px]",children:c.className}),k&&e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:523:35",className:"bg-purple-500/20 text-purple-300 border-purple-500/30 text-[10px]",children:"关联"}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:524:23",size:"sm",variant:"ghost",className:"h-6 text-xs text-slate-400 ml-auto",onClick:()=>z({kind:"ingress",name:c.name}),children:[e.jsx(Dt,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:526:25",className:"h-3 w-3 mr-1"}),"YAML"]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:528:23",size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-red-400 hover:text-red-300",title:"删除 Ingress",onClick:()=>T("ingress",c.name),children:e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:530:25",className:"h-3 w-3"})})]}),e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:534:21",className:"mt-2 space-y-1 text-[11px]",children:c.rules.map((y,J)=>e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:536:25",className:"flex items-start gap-1.5",children:[e.jsx(jt,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:537:27",className:"h-3 w-3 text-slate-500 mt-0.5"}),e.jsx("code",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:538:27",className:"text-slate-300",children:y.host||"*"}),y.paths.map((_,$)=>e.jsxs("code",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:540:29",className:"bg-slate-800/60 px-1.5 py-0.5 rounded text-slate-400",children:[_.path," → ",_.backend?.service,":",_.backend?.port]},$))]},J))})]},c.name)})}),F==="ingress"&&e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:555:13",className:"mt-3 border border-purple-800/50 rounded-lg p-3 bg-purple-950/20 space-y-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:556:15",className:"text-xs font-semibold text-purple-300 flex items-center gap-1.5",children:[e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:557:17",className:"h-3 w-3"}),"创建新 Ingress"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:559:15",className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:560:17",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:561:19",className:"text-slate-500 text-[11px]",children:"名称"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:562:19",value:S.name,onChange:c=>Q(k=>({...k,name:c.target.value})),placeholder:`${o}-ingress`,className:"h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:566:17",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:567:19",className:"text-slate-500 text-[11px]",children:"ingressClassName"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:568:19",value:S.className,onChange:c=>Q(k=>({...k,className:c.target.value})),placeholder:"nginx",className:"h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:572:17",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:573:19",className:"text-slate-500 text-[11px]",children:"host (域名)"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:574:19",value:S.host,onChange:c=>Q(k=>({...k,host:c.target.value})),placeholder:"app.example.com",className:"h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:578:17",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:579:19",className:"text-slate-500 text-[11px]",children:"path"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:580:19",value:S.path,onChange:c=>Q(k=>({...k,path:c.target.value})),placeholder:"/",className:"h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:584:17",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:585:19",className:"text-slate-500 text-[11px]",children:"Service 端口"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:586:19",type:"number",value:S.svcPort,onChange:c=>Q(k=>({...k,svcPort:c.target.value})),className:"h-7 mt-0.5 bg-slate-800 border-slate-700 text-slate-300 text-xs font-mono"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:590:15",className:"flex justify-end gap-2 pt-1",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:591:17",size:"sm",variant:"ghost",className:"h-7 text-xs text-slate-400",onClick:()=>B(null),children:"取消"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:592:17",size:"sm",className:"h-7 bg-purple-600 hover:bg-purple-700 text-xs",onClick:w,children:"创建"})]})]})]})]}),M&&e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:601:9",className:"hidden"}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:605:7",className:"flex justify-end gap-2 pt-2",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:606:9",size:"sm",variant:"ghost",className:"h-7 text-xs text-slate-400",onClick:d,children:"完成"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentEditService.tsx:607:9",size:"sm",className:"h-7 bg-slate-600 text-xs",onClick:n,children:"保存并关闭"})]})]})}function on({clusterCode:t,namespace:s,deploymentName:o,mode:a,onBack:n,onModeChange:d}){const i=as(),{toast:p}=Pe(),[D,h]=m.useState(null),[N,I]=m.useState(null),[q,V]=m.useState([]),[R,M]=m.useState([]),[z,F]=m.useState([]),[B,U]=m.useState(!0),[Y,S]=m.useState(""),[Q,O]=m.useState(null),[H,ne]=m.useState(""),[oe,r]=m.useState(0),[b,f]=m.useState(null),[P,l]=m.useState(null),w=D?.cluster_id||D?.clusterId||t,T=g=>Array.isArray(g)?g:g?.list||g?.items||g?.data||[],c=m.useCallback(async()=>{U(!0);try{const[g,ye,je,Ae]=await Promise.all([te.getDeployment(t,s,o).catch(()=>null),te.getNamespacePods(t,s).catch(()=>[]),te.getReplicaSets(t,s).catch(()=>[]),te.getDeploymentRevisions(t,s,o).catch(()=>[])]),We=g||(Array.isArray(g)?g[0]:null);h(We),r(We?.replicas||0),ne(We?.image||"");const Je=T(ye).filter(Ce=>Ce.namespace===s&&(Ce.name||"").startsWith(o));V(Je);const qe=T(je).filter(Ce=>Ce.namespace===s&&(Ce.owner_deployment===o||(Ce.name||"").startsWith(o)));M(qe),F(T(Ae))}catch(g){console.error("加载详情失败:",g)}finally{U(!1)}},[t,s,o]),k=m.useCallback(async()=>{try{const g=await te.getResourceYaml(t,s,"deployments",o);let ye=null;try{ye=JSON.parse(g)}catch{try{ye=(await gs(()=>import("./js-yaml-37NdyH6G.js"),[],import.meta.url)).load(g)}catch{ye=null}}I(ye||D)}catch(g){console.warn("加载 manifest 失败(编辑功能降级):",g),I(D)}},[t,s,o,D]);m.useEffect(()=>{c()},[c]),m.useEffect(()=>{a==="edit"&&!N&&k()},[a,N,k]);const y=async()=>{S("scale");try{await te.scaleDeployment(t,s,o,oe),p({title:"伸缩成功",description:`副本数已设置为 ${oe}`}),O(null),c()}catch(g){p({title:"操作失败",description:g?.message||String(g),variant:"destructive"})}finally{S("")}},J=async()=>{if(confirm(`确认滚动重启 Deployment "${o}"?`)){S("restart");try{await te.restartDeployment(t,s,o),p({title:"重启指令已下发",description:"Deployment 正在滚动重启"}),setTimeout(c,1500)}catch(g){p({title:"重启失败",description:g?.message||String(g),variant:"destructive"})}finally{S("")}}},_=async()=>{const g=!!D?.paused,ye=g?"恢复":"暂停";if(confirm(`确认${ye} Deployment "${o}" 的滚动更新?`)){S(g?"resume":"pause");try{g?await te.resumeDeployment(t,s,o):await te.pauseDeployment(t,s,o),p({title:`${ye}成功`,description:`Deployment 滚动更新已${ye}`}),setTimeout(c,1e3)}catch(je){p({title:`${ye}失败`,description:je?.message||String(je),variant:"destructive"})}finally{S("")}}},$=()=>{O({kind:"cicd"})},be=async()=>{if(H.trim()){S("image");try{await te.updateDeploymentImage(t,s,o,H),p({title:"镜像更新成功",description:`正在滚动更新为 ${H}`}),O(null),c()}catch(g){p({title:"更新失败",description:g?.message||String(g),variant:"destructive"})}finally{S("")}}},K=async()=>{S("delete");try{const g=Nt.getState().token||"",je=`/api/v1/kubernetes/${t}/namespace/${s}/deployments/${o}`,Ae=await fetch(je,{method:"DELETE",headers:{Authorization:`Bearer ${g}`}});if(!Ae.ok)throw new Error(`HTTP ${Ae.status}`);p({title:"删除成功",description:`${o} 已删除`}),O(null),setTimeout(()=>i(`/kubernetes/${t}/namespace/${s}/deployments`),800)}catch(g){p({title:"删除失败",description:g?.message||String(g),variant:"destructive"})}finally{S("")}},he=g=>O({kind:"podLogs",pod:g.name}),Ne=g=>O({kind:"podYaml",pod:g.name}),de=g=>{f(g.name)},A=g=>{l(g.name)};if(B)return e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:260:7",className:"bg-slate-900 border-slate-800",children:e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:261:9",className:"p-12 text-center",children:[e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:262:11",className:"h-6 w-6 animate-spin mx-auto text-slate-500"}),e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:263:11",className:"text-slate-500 mt-3",children:"加载中..."})]})});if(!D)return e.jsx(L,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:271:7",className:"bg-slate-900 border-slate-800",children:e.jsxs(G,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:272:9",className:"p-12 text-center",children:[e.jsx(Vs,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:273:11",className:"h-8 w-8 mx-auto text-red-400"}),e.jsxs("p",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:274:11",className:"text-slate-400 mt-3",children:["未找到 Deployment: ",o]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:275:11",variant:"outline",className:"mt-4",onClick:n,children:"返回"})]})});const ce=D.ready_replicas||D.readyReplicas||0,ge=D.replicas||0,fe=ce===ge&&ge>0;return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:287:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:289:7",className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:290:9",className:"flex items-center gap-3 min-w-0",children:[e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:291:11",variant:"ghost",size:"sm",className:"text-slate-400",onClick:n,children:[e.jsx(Ws,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:292:13",className:"h-4 w-4 mr-1"}),"返回"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:294:11",className:"min-w-0",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:295:13",className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h1",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:296:15",className:"text-xl font-bold text-slate-100 truncate",children:o}),e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:297:15",variant:"outline",className:"border-slate-700 text-slate-400",children:s}),e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:298:15",variant:"outline",className:"border-slate-700 text-slate-400",children:"Deployment"}),e.jsxs(se,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:299:15",className:fe?"bg-emerald-500/20 text-emerald-400 border-emerald-500/30":"bg-amber-500/20 text-amber-400 border-amber-500/30",children:[fe?e.jsx(gt,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:304:30",className:"h-3 w-3 mr-1"}):e.jsx(Mt,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:304:73",className:"h-3 w-3 mr-1"}),ce,"/",ge]}),D?.paused&&e.jsxs(se,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:308:17",className:"bg-orange-500/20 text-orange-400 border-orange-500/30",children:[e.jsx(_t,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:309:19",className:"h-3 w-3 mr-1"}),"已暂停更新"]})]}),e.jsxs("p",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:313:13",className:"text-xs text-slate-500 mt-0.5 truncate",children:["镜像: ",e.jsx("code",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:314:19",className:"text-slate-400",children:D.image||"-"})]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:319:9",className:"flex items-center gap-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:321:11",className:"inline-flex rounded-md border border-slate-700 overflow-hidden",children:[e.jsx("button",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:322:13",className:`px-3 py-1.5 text-xs font-medium transition-colors ${a==="view"?"bg-slate-700 text-slate-100":"bg-transparent text-slate-400 hover:text-slate-200"}`,onClick:()=>d("view"),children:"查看"}),e.jsx("button",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:328:13",className:`px-3 py-1.5 text-xs font-medium transition-colors ${a==="edit"?"bg-blue-600 text-white":"bg-transparent text-slate-400 hover:text-slate-200"}`,onClick:()=>d("edit"),children:"编辑"}),e.jsx("button",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:334:13",className:`px-3 py-1.5 text-xs font-medium transition-colors ${a==="yaml"?"bg-emerald-600 text-white":"bg-transparent text-slate-400 hover:text-slate-200"}`,onClick:()=>d("yaml"),children:"YAML"})]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:342:11",variant:"outline",size:"sm",className:"border-slate-700 text-slate-400",onClick:c,title:"刷新",children:e.jsx(ct,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:343:13",className:"h-4 w-4"})}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:347:11",className:"flex items-center gap-1.5",children:[e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:348:13",variant:"outline",size:"sm",className:"border-slate-700 text-slate-300",onClick:()=>O({kind:"image"}),children:[e.jsx(Ms,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:349:15",className:"h-3.5 w-3.5 mr-1"}),"调整镜像"]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:351:13",variant:"outline",size:"sm",className:"border-slate-700 text-slate-300",onClick:J,children:[e.jsx(ds,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:352:15",className:"h-3.5 w-3.5 mr-1"}),"重启"]}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:354:13",variant:"outline",size:"sm",className:"border-slate-700 text-slate-300",disabled:!!Y,onClick:_,children:D?.paused?e.jsxs(e.Fragment,{children:[e.jsx(ls,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:361:21",className:"h-3.5 w-3.5 mr-1 text-green-400"}),"恢复"]}):e.jsxs(e.Fragment,{children:[e.jsx(_t,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:362:21",className:"h-3.5 w-3.5 mr-1 text-orange-400"}),"暂停"]})}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:365:13",variant:"outline",size:"sm",className:"border-slate-700 text-slate-300",onClick:$,children:[e.jsx(Ds,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:366:15",className:"h-3.5 w-3.5 mr-1 text-purple-400"}),"CI/CD"]}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:368:13",variant:"outline",size:"sm",className:"border-slate-700 text-red-400 hover:bg-red-500/10",onClick:()=>O({kind:"delete"}),children:[e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:369:15",className:"h-3.5 w-3.5 mr-1"}),"删除"]})]})]})]}),a==="view"?e.jsx(Ls,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:377:9",clusterCode:t,namespace:s,deployment:D,pods:q,replicaSets:R,revisions:z,onRefresh:c,onShowPodLogs:he,onShowPodTerminal:de,onShowPodYaml:Ne,onShowPodFileBrowser:A}):a==="yaml"?e.jsx(zt,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:392:9",clusterCode:t,namespace:s,resource:"deployments",name:o,cleanBeforeEdit:!0,inline:!0,onSaved:c,onClose:()=>d("view")}):e.jsx(an,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:404:9",clusterCode:t,namespace:s,deploymentName:o,manifest:N,onSaved:()=>{k(),c(),d("view")},onCancel:()=>d("view")}),Q?.kind==="yaml"&&e.jsx(zt,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:416:9",clusterCode:t,namespace:s,resource:"deployments",name:o,cleanBeforeEdit:!0,onClose:()=>O(null),onSaved:c}),Q?.kind==="image"&&e.jsx(et,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:429:9",title:"调整镜像版本",onClose:()=>O(null),children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:430:11",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:431:13",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:432:15",className:"text-slate-400 text-sm",children:"当前镜像"}),e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:433:15",className:"text-xs text-slate-500 font-mono mt-1 bg-slate-800 rounded px-3 py-2",children:D.image||"-"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:435:13",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:436:15",className:"text-slate-400 text-sm",children:"新镜像地址"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:437:15",value:H,onChange:g=>ne(g.target.value),placeholder:"harbor.example.com/app:v2.0",className:"mt-1 bg-slate-800 border-slate-700 text-slate-200 text-sm font-mono"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:441:13",className:"flex justify-end gap-2 pt-2",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:442:15",variant:"outline",className:"border-slate-700 text-slate-400",onClick:()=>O(null),children:"取消"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:443:15",className:"bg-blue-600 hover:bg-blue-700",disabled:Y==="image"||!H.trim(),onClick:be,children:Y==="image"?e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:444:46",className:"h-4 w-4 animate-spin"}):"更新镜像"})]})]})}),Q?.kind==="scale"&&e.jsx(et,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:453:9",title:"伸缩 (Scale)",onClose:()=>O(null),children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:454:11",className:"space-y-3",children:[e.jsxs("p",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:455:13",className:"text-xs text-slate-500",children:["当前副本: ",D.replicas||0]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:456:13",className:"flex items-center justify-center gap-3 py-3",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:457:15",variant:"outline",size:"icon",className:"border-slate-700 text-slate-300",disabled:Y==="scale"||oe<=0,onClick:()=>r(g=>Math.max(0,g-1)),children:e.jsx(ft,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:460:17",className:"h-4 w-4"})}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:462:15",type:"number",min:0,value:oe,onChange:g=>r(Math.max(0,Number(g.target.value))),className:"w-24 text-center text-lg font-bold bg-slate-800 border-slate-700 text-slate-200"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:465:15",variant:"outline",size:"icon",className:"border-slate-700 text-slate-300",disabled:Y==="scale",onClick:()=>r(g=>g+1),children:e.jsx(ae,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:468:17",className:"h-4 w-4"})})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:471:13",className:"flex justify-end gap-2 pt-2",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:472:15",variant:"outline",className:"border-slate-700 text-slate-400",onClick:()=>O(null),children:"取消"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:473:15",className:"bg-blue-600 hover:bg-blue-700",disabled:Y==="scale",onClick:y,children:Y==="scale"?e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:474:46",className:"h-4 w-4 animate-spin"}):"确认"})]})]})}),Q?.kind==="delete"&&e.jsx(et,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:483:9",title:"删除 Deployment",onClose:()=>O(null),children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:484:11",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:485:13",className:"flex items-center gap-2 text-red-400",children:[e.jsx(Mt,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:486:15",className:"h-5 w-5"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:487:15",className:"font-semibold",children:"此操作不可撤销"})]}),e.jsxs("p",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:489:13",className:"text-sm text-slate-400",children:["确认删除 Deployment ",e.jsxs("code",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:490:31",className:"text-slate-200 font-mono",children:[s,"/",o]}),"? 其管理的所有 Pod 将被一并回收。"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:493:13",className:"flex justify-end gap-2 pt-2",children:[e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:494:15",variant:"outline",className:"border-slate-700 text-slate-400",onClick:()=>O(null),children:"取消"}),e.jsxs(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:495:15",variant:"destructive",disabled:Y==="delete",onClick:K,children:[Y==="delete"?e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:496:47",className:"h-4 w-4 animate-spin mr-1"}):e.jsx(ue,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:496:99",className:"h-4 w-4 mr-1"}),"确认删除"]})]})]})}),Q?.kind==="cicd"&&e.jsx(et,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:506:9",title:"CI/CD Webhook",onClose:()=>O(null),children:e.jsx(cn,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:507:11",clusterCode:t,namespace:s,deploymentName:o})}),Q?.kind==="podLogs"&&e.jsx(rn,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:513:9",clusterCode:t,namespace:s,podName:Q.pod,containers:(q.find(g=>g.name===Q.pod)?.containers||[]).map(g=>g.name).filter(Boolean),onClose:()=>O(null)}),e.jsx(Es,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:523:7",open:!!b,onOpenChange:g=>{g||f(null)},clusterId:w,namespace:s,podName:b||"",containers:(q.find(g=>g.name===b)?.containers||[]).map(g=>g.name).filter(Boolean)}),e.jsx(ws,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:532:7",open:!!P,onOpenChange:g=>{g||l(null)},clusterCode:t,namespace:s,podName:P||"",containers:(q.find(g=>g.name===P)?.containers||[]).map(g=>g.name).filter(Boolean)})]})}function an({clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}){const[i,p]=m.useState("basic"),D=[{key:"basic",label:"基本信息",icon:vt,available:!0},{key:"containers",label:"容器信息",icon:ot,available:!0},{key:"storage",label:"存储挂载",icon:tt,available:!0},{key:"advanced",label:"高级设置",icon:vt,available:!0},{key:"service",label:"服务/应用路由",icon:Se,available:!0}];return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:565:5",className:"space-y-4",children:[e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:567:7",className:"flex items-center gap-1 border-b border-slate-800 pb-px overflow-x-auto",children:D.map(h=>{const N=i===h.key,I=h.icon;return e.jsxs("button",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:572:13",disabled:!h.available,onClick:()=>h.available&&p(h.key),className:`flex items-center gap-1.5 px-3 py-2 text-xs font-medium border-b-2 transition-colors whitespace-nowrap + ${N?"border-blue-500 text-blue-400":h.available?"border-transparent text-slate-400 hover:text-slate-200":"border-transparent text-slate-600 cursor-not-allowed"}`,children:[e.jsx(I,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:584:15",className:"h-3.5 w-3.5"}),h.label,h.badge&&e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:587:17",className:`text-[9px] px-1 py-0.5 rounded ${N?"bg-blue-500/20 text-blue-300":"bg-slate-800 text-slate-600"}`,children:h.badge})]},h.key)})}),i==="basic"?e.jsx(Xs,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:598:9",clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}):i==="containers"?e.jsx(qs,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:608:9",clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}):i==="storage"?e.jsx(en,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:618:9",clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}):i==="advanced"?e.jsx(tn,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:628:9",clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}):i==="service"?e.jsx(nn,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:638:9",clusterCode:t,namespace:s,deploymentName:o,manifest:a,onSaved:n,onCancel:d}):null]})}function cn({clusterCode:t,namespace:s,deploymentName:o}){const{toast:a}=Pe(),n=Nt(D=>D.token)||localStorage.getItem("token")||"",d=`${window.location.origin}/api/v1/clusters/${t}/namespaces/${s}/deployments/${o}/update-image`,i=`curl -X POST '${d}' \\ + -H 'Authorization: Bearer ${n?n.substring(0,16)+"...":"YOUR_TOKEN"}' \\ + -H 'Content-Type: application/json' \\ + -d '{"image": "harbor.example.com/app:v1.0", "container": "your-container-name"}'`,p=D=>{navigator.clipboard.writeText(D).then(()=>a({title:"已复制"})).catch(()=>{})};return e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:666:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:667:7",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:668:9",className:"text-slate-400 text-sm",children:"Webhook URL"}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:669:9",className:"flex items-center gap-2 mt-1",children:[e.jsx("code",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:670:11",className:"flex-1 text-xs text-slate-300 bg-slate-800 rounded px-3 py-2 break-all font-mono",children:d}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:671:11",variant:"outline",size:"sm",className:"border-slate-700 text-slate-400 shrink-0",onClick:()=>p(d),children:"复制"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:674:7",children:[e.jsx(C,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:675:9",className:"text-slate-400 text-sm",children:"curl 示例"}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:676:9",className:"relative mt-1",children:[e.jsx("pre",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:677:11",className:"text-xs text-slate-300 bg-slate-800 rounded p-3 overflow-x-auto font-mono whitespace-pre-wrap",children:i}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:678:11",variant:"outline",size:"sm",className:"absolute top-2 right-2 border-slate-700 text-slate-400",onClick:()=>p(i),children:"复制"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:681:7",className:"text-xs text-slate-500 space-y-1",children:[e.jsx("p",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:682:9",children:"• 使用 Bearer Token 认证(JWT 登录令牌)"}),e.jsxs("p",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:683:9",children:["• ",e.jsx("code",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:683:14",className:"text-slate-400",children:"image"})," 必填,指定新镜像地址"]}),e.jsxs("p",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:684:9",children:["• ",e.jsx("code",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:684:14",className:"text-slate-400",children:"container"})," 可选,不填则更新第一个容器"]})]})]})}function et({title:t,children:s,onClose:o}){return e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:693:5",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:o,children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:694:7",className:"bg-slate-900 border border-slate-700 rounded-xl p-6 w-[460px] max-w-[90vw] shadow-2xl",onClick:a=>a.stopPropagation(),children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:695:9",className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:696:11",className:"text-base font-bold text-slate-100",children:t}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:697:11",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400",onClick:o,children:e.jsx(cs,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:697:100",className:"h-4 w-4"})})]}),s]})})}function rn({clusterCode:t,namespace:s,podName:o,containers:a,onClose:n}){const{toast:d}=Pe(),[i,p]=m.useState(""),[D,h]=m.useState(200),[N,I]=m.useState(a[0]||""),[q,V]=m.useState(!1),[R,M]=m.useState(!1),z=async()=>{V(!0);try{const B=await te.getPodLogs(t,s,o,D,N||void 0);p(B?.data?.logs||B?.logs||B||"无日志")}catch{p("获取日志失败")}finally{V(!1)}};m.useEffect(()=>{z()},[N,D]);const F=async()=>{M(!0);const B=Nt.getState().token||"",U="",Y=N?`&container=${encodeURIComponent(N)}`:"",S=`${U}/api/v1/kubernetes/${t}/namespace/${s}/pods/${o}/logs?tail=${D}&stream=true${Y}`;try{const O=(await fetch(S,{headers:{Authorization:`Bearer ${B}`}})).body?.getReader();if(!O)return;const H=new TextDecoder;let ne="";for(;;){const{done:oe,value:r}=await O.read();if(oe)break;ne+=H.decode(r,{stream:!0}),p(ne)}}catch{d({title:"流式日志连接中断",variant:"destructive"})}finally{M(!1)}};return e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:752:5",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:n,children:e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:753:7",className:"bg-slate-900 border border-slate-700 rounded-xl w-[90vw] max-w-4xl max-h-[80vh] flex flex-col",onClick:B=>B.stopPropagation(),children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:754:9",className:"flex items-center justify-between p-3 border-b border-slate-700",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:755:11",className:"flex items-center gap-2",children:[e.jsx(Et,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:756:13",className:"h-4 w-4 text-blue-400"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:757:13",className:"text-sm font-semibold text-slate-200",children:o}),N&&e.jsx(se,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:758:27",variant:"outline",className:"border-slate-700 text-slate-400 text-[10px]",children:N})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:760:11",className:"flex items-center gap-2",children:[a.length>0&&e.jsx("select",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:762:15",value:N,onChange:B=>I(B.target.value),className:"bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2 py-1",children:a.map(B=>e.jsx("option",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:764:38",value:B,children:B},B))}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:767:13",className:"text-[11px] text-slate-500",children:"最近"}),e.jsx(v,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:768:13",type:"number",value:D,onChange:B=>h(Number(B.target.value)||200),className:"w-16 h-7 bg-slate-800 border-slate-700 text-slate-200 text-xs"}),e.jsx("span",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:770:13",className:"text-[11px] text-slate-500",children:"行"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:771:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:z,disabled:q,children:q?e.jsx(xe,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:772:26",className:"h-3 w-3 animate-spin"}):e.jsx(ct,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:772:73",className:"h-3 w-3"})}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:774:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-emerald-400 text-xs",onClick:F,disabled:R,children:R?"流中...":"实时流"}),e.jsx(u,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:777:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400",onClick:n,children:e.jsx(cs,{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:777:102",className:"h-4 w-4"})})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:780:9",className:"flex-1 overflow-auto p-3",children:e.jsx("pre",{"code-path":"src/components/kubernetes/DeploymentWorkload.tsx:781:11",className:"bg-slate-950 rounded p-3 text-xs text-slate-300 font-mono whitespace-pre-wrap max-h-[60vh] overflow-auto",children:i||"无日志内容"})})]})})}function Yn(){const t=js(),s=as(),o=t.clusterCode||"",a=t.namespace||"",n=t.name||"",d=t.mode==="edit"||t.mode==="yaml"?t.mode:"view",i=p=>{p!==d&&s(`/kubernetes/${o}/namespace/${a}/workload/${p}/Deployment/${n}`,{replace:!0})};return e.jsx(on,{"code-path":"src/components/kubernetes/DeploymentDetailPage.tsx:38:5",clusterCode:o,namespace:a,deploymentName:n,mode:d,onBack:()=>s(-1),onModeChange:i})}export{Yn as default}; diff --git a/backend/static/assets/DomainManager-CIA5bu9u.js b/backend/static/assets/DomainManager-CIA5bu9u.js new file mode 100644 index 0000000..0897bb4 --- /dev/null +++ b/backend/static/assets/DomainManager-CIA5bu9u.js @@ -0,0 +1 @@ +import{g as X,r as o,j as e,B as x,O as v,x as O,S as q,I as i,D as J,b as K,c as V,d as W,e as Y,f as Z,L as ee}from"./index-DfyorCky.js";import{L as m}from"./label-BK0h2apY.js";import{C as r,a as l}from"./card-C55cvSHg.js";import{B as D}from"./badge-xNW8x0G1.js";import{c as j}from"./cloud-Dzoer-2i.js";import{R as P}from"./refresh-cw-DUB_tAG-.js";import{P as I}from"./plus-CUG-9kpu.js";import{C as M}from"./circle-check-DWcXrx2k.js";import{C as B}from"./circle-x-DK79Dhg2.js";import{T as se}from"./trash-2-Dx32pOzT.js";const ae=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]],F=X("pen",ae);function xe(){const[p,f]=o.useState([]),[y,_]=o.useState(!0),[N,T]=o.useState(""),[b,z]=o.useState("all"),[R,h]=o.useState(!1),[w,C]=o.useState(!1),[d,S]=o.useState(null),[a,t]=o.useState({name:"",registrar:"",status:"active",expire_date:"",dns_provider:"",record_count:"",ssl_enabled:!1,ssl_expire_date:""}),$=()=>{S(null),t({name:"",registrar:"",status:"active",expire_date:"",dns_provider:"",record_count:"",ssl_enabled:!1,ssl_expire_date:""})},Q=()=>{$(),h(!0)},U=s=>{S(s);const c=n=>n?n.substring(0,10):"";t({name:s.name||"",registrar:s.registrar||"",status:s.status||"active",expire_date:c(s.expire_date||""),dns_provider:s.dns_provider||s.dnsProvider||"",record_count:String(s.record_count??s.recordCount??""),ssl_enabled:s.ssl_enabled??s.sslEnabled??!1,ssl_expire_date:c(s.ssl_expire_date||"")}),h(!0)},A=async()=>{if(a.name.trim())try{C(!0);const s={name:a.name.trim(),registrar:a.registrar.trim(),status:a.status,expire_date:a.expire_date,dns_provider:a.dns_provider.trim(),record_count:Number(a.record_count)||0,ssl_enabled:a.ssl_enabled,ssl_expire_date:a.ssl_expire_date};d?await j.updateDomain(d.id,s):await j.createDomain(s),h(!1),g()}catch(s){console.error(d?"更新域名失败:":"创建域名失败:",s)}finally{C(!1)}},g=async()=>{try{_(!0);const s=await j.getDomains();f(s?.list||[])}catch(s){console.error("加载域名列表失败:",s),f([])}finally{_(!1)}};o.useEffect(()=>{g()},[]);const G=async s=>{try{await j.deleteDomain(s),g()}catch(c){console.error("删除域名失败:",c)}},L=p.filter(s=>{const c=(s.name||"").toLowerCase().includes(N.toLowerCase())||(s.registrar||"").toLowerCase().includes(N.toLowerCase()),n=b==="all"||s.status===b;return c&&n}),u={total:p.length,active:p.filter(s=>s.status==="active").length,expired:p.filter(s=>s.status==="expired").length,pending:p.filter(s=>s.status==="pending").length,sslEnabled:p.filter(s=>s.ssl_enabled||s.sslEnabled).length},H=s=>s?Math.ceil((new Date(s).getTime()-Date.now())/(1e3*60*60*24)):1/0;return e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:162:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:164:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:165:9",children:[e.jsx("h1",{"code-path":"src/components/cloud/DomainManager.tsx:166:11",className:"text-2xl font-bold text-slate-100",children:"域名管理"}),e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:167:11",className:"text-slate-400 mt-1",children:"管理域名注册信息和DNS解析记录"})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:169:9",className:"flex items-center gap-2",children:[e.jsxs(x,{"code-path":"src/components/cloud/DomainManager.tsx:170:11",variant:"outline",onClick:g,className:"border-slate-700 text-slate-300",children:[e.jsx(P,{"code-path":"src/components/cloud/DomainManager.tsx:171:13",className:`h-4 w-4 mr-2 ${y?"animate-spin":""}`}),"刷新"]}),e.jsxs(x,{"code-path":"src/components/cloud/DomainManager.tsx:174:11",className:"bg-blue-600 hover:bg-blue-700",onClick:Q,children:[e.jsx(I,{"code-path":"src/components/cloud/DomainManager.tsx:175:13",className:"h-4 w-4 mr-2"}),"添加域名"]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:182:7",className:"grid grid-cols-5 gap-4",children:[e.jsx(r,{"code-path":"src/components/cloud/DomainManager.tsx:183:9",className:"bg-slate-800 border-slate-700",children:e.jsx(l,{"code-path":"src/components/cloud/DomainManager.tsx:184:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:185:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:186:15",children:[e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:187:17",className:"text-slate-400 text-sm",children:"域名总数"}),e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:188:17",className:"text-2xl font-bold text-slate-100 mt-1",children:u.total})]}),e.jsx("div",{"code-path":"src/components/cloud/DomainManager.tsx:190:15",className:"w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center",children:e.jsx(v,{"code-path":"src/components/cloud/DomainManager.tsx:191:17",className:"h-5 w-5 text-blue-400"})})]})})}),e.jsx(r,{"code-path":"src/components/cloud/DomainManager.tsx:196:9",className:"bg-slate-800 border-slate-700",children:e.jsx(l,{"code-path":"src/components/cloud/DomainManager.tsx:197:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:198:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:199:15",children:[e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:200:17",className:"text-slate-400 text-sm",children:"正常"}),e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:201:17",className:"text-2xl font-bold text-green-400 mt-1",children:u.active})]}),e.jsx("div",{"code-path":"src/components/cloud/DomainManager.tsx:203:15",className:"w-10 h-10 rounded-lg bg-green-500/20 flex items-center justify-center",children:e.jsx(M,{"code-path":"src/components/cloud/DomainManager.tsx:204:17",className:"h-5 w-5 text-green-400"})})]})})}),e.jsx(r,{"code-path":"src/components/cloud/DomainManager.tsx:209:9",className:"bg-slate-800 border-slate-700",children:e.jsx(l,{"code-path":"src/components/cloud/DomainManager.tsx:210:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:211:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:212:15",children:[e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:213:17",className:"text-slate-400 text-sm",children:"已过期"}),e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:214:17",className:"text-2xl font-bold text-red-400 mt-1",children:u.expired})]}),e.jsx("div",{"code-path":"src/components/cloud/DomainManager.tsx:216:15",className:"w-10 h-10 rounded-lg bg-red-500/20 flex items-center justify-center",children:e.jsx(B,{"code-path":"src/components/cloud/DomainManager.tsx:217:17",className:"h-5 w-5 text-red-400"})})]})})}),e.jsx(r,{"code-path":"src/components/cloud/DomainManager.tsx:222:9",className:"bg-slate-800 border-slate-700",children:e.jsx(l,{"code-path":"src/components/cloud/DomainManager.tsx:223:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:224:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:225:15",children:[e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:226:17",className:"text-slate-400 text-sm",children:"待审核"}),e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:227:17",className:"text-2xl font-bold text-yellow-400 mt-1",children:u.pending})]}),e.jsx("div",{"code-path":"src/components/cloud/DomainManager.tsx:229:15",className:"w-10 h-10 rounded-lg bg-yellow-500/20 flex items-center justify-center",children:e.jsx(O,{"code-path":"src/components/cloud/DomainManager.tsx:230:17",className:"h-5 w-5 text-yellow-400"})})]})})}),e.jsx(r,{"code-path":"src/components/cloud/DomainManager.tsx:235:9",className:"bg-slate-800 border-slate-700",children:e.jsx(l,{"code-path":"src/components/cloud/DomainManager.tsx:236:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:237:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:238:15",children:[e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:239:17",className:"text-slate-400 text-sm",children:"SSL证书"}),e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:240:17",className:"text-2xl font-bold text-cyan-400 mt-1",children:u.sslEnabled})]}),e.jsx("div",{"code-path":"src/components/cloud/DomainManager.tsx:242:15",className:"w-10 h-10 rounded-lg bg-cyan-500/20 flex items-center justify-center",children:e.jsx(M,{"code-path":"src/components/cloud/DomainManager.tsx:243:17",className:"h-5 w-5 text-cyan-400"})})]})})})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:251:7",className:"flex items-center gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:252:9",className:"relative flex-1 max-w-md",children:[e.jsx(q,{"code-path":"src/components/cloud/DomainManager.tsx:253:11",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(i,{"code-path":"src/components/cloud/DomainManager.tsx:254:11",placeholder:"搜索域名...",value:N,onChange:s=>T(s.target.value),className:"pl-10 bg-slate-800 border-slate-700 text-slate-100"})]}),e.jsxs("select",{"code-path":"src/components/cloud/DomainManager.tsx:261:9",value:b,onChange:s=>z(s.target.value),className:"px-3 py-2 bg-slate-800 border border-slate-700 rounded-md text-slate-100 text-sm",children:[e.jsx("option",{"code-path":"src/components/cloud/DomainManager.tsx:266:11",value:"all",children:"全部状态"}),e.jsx("option",{"code-path":"src/components/cloud/DomainManager.tsx:267:11",value:"active",children:"正常"}),e.jsx("option",{"code-path":"src/components/cloud/DomainManager.tsx:268:11",value:"expired",children:"已过期"}),e.jsx("option",{"code-path":"src/components/cloud/DomainManager.tsx:269:11",value:"pending",children:"待审核"})]})]}),y?e.jsx(r,{"code-path":"src/components/cloud/DomainManager.tsx:275:9",className:"bg-slate-800 border-slate-700",children:e.jsxs(l,{"code-path":"src/components/cloud/DomainManager.tsx:276:11",className:"p-12 text-center text-slate-500",children:[e.jsx(P,{"code-path":"src/components/cloud/DomainManager.tsx:277:13",className:"h-6 w-6 animate-spin mx-auto mb-3"}),"加载中..."]})}):L.length===0?e.jsx(r,{"code-path":"src/components/cloud/DomainManager.tsx:282:9",className:"bg-slate-800 border-slate-700",children:e.jsx(l,{"code-path":"src/components/cloud/DomainManager.tsx:283:11",className:"p-12 text-center text-slate-500",children:"暂无域名数据"})}):e.jsx("div",{"code-path":"src/components/cloud/DomainManager.tsx:286:9",className:"space-y-3",children:L.map(s=>{const c=s.ssl_enabled||s.sslEnabled,n=s.expire_date||s.expireDate||"",E=s.ssl_expire_date||s.sslExpireDate||"",k=H(n);return e.jsx(r,{"code-path":"src/components/cloud/DomainManager.tsx:293:15",className:"bg-slate-800 border-slate-700",children:e.jsx(l,{"code-path":"src/components/cloud/DomainManager.tsx:294:17",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:295:19",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:296:21",className:"flex items-center gap-4",children:[e.jsx("div",{"code-path":"src/components/cloud/DomainManager.tsx:297:23",className:"w-10 h-10 rounded-lg bg-gradient-to-br from-blue-500 to-cyan-500 flex items-center justify-center",children:e.jsx(v,{"code-path":"src/components/cloud/DomainManager.tsx:298:25",className:"h-5 w-5 text-white"})}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:300:23",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:301:25",className:"flex items-center gap-2",children:[e.jsx("h3",{"code-path":"src/components/cloud/DomainManager.tsx:302:27",className:"font-medium text-slate-100 text-lg",children:s.name}),s.status==="active"&&e.jsxs(D,{"code-path":"src/components/cloud/DomainManager.tsx:304:29",className:"bg-green-500/20 text-green-400 border-0",children:[e.jsx(M,{"code-path":"src/components/cloud/DomainManager.tsx:305:31",className:"h-3 w-3 mr-1"}),"正常"]}),s.status==="expired"&&e.jsxs(D,{"code-path":"src/components/cloud/DomainManager.tsx:310:29",className:"bg-red-500/20 text-red-400 border-0",children:[e.jsx(B,{"code-path":"src/components/cloud/DomainManager.tsx:311:31",className:"h-3 w-3 mr-1"}),"已过期"]}),s.status==="pending"&&e.jsxs(D,{"code-path":"src/components/cloud/DomainManager.tsx:316:29",className:"bg-yellow-500/20 text-yellow-400 border-0",children:[e.jsx(O,{"code-path":"src/components/cloud/DomainManager.tsx:317:31",className:"h-3 w-3 mr-1"}),"待审核"]}),c&&e.jsxs(D,{"code-path":"src/components/cloud/DomainManager.tsx:322:29",className:"bg-cyan-500/20 text-cyan-400 border-0",children:[e.jsx(M,{"code-path":"src/components/cloud/DomainManager.tsx:323:31",className:"h-3 w-3 mr-1"}),"SSL"]})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:328:25",className:"flex items-center gap-4 mt-1 text-sm text-slate-400",children:[e.jsxs("span",{"code-path":"src/components/cloud/DomainManager.tsx:329:27",children:["注册商: ",s.registrar||"-"]}),e.jsxs("span",{"code-path":"src/components/cloud/DomainManager.tsx:330:27",children:["DNS: ",s.dns_provider||s.dnsProvider||"-"]}),e.jsxs("span",{"code-path":"src/components/cloud/DomainManager.tsx:331:27",children:["解析记录: ",s.record_count??s.recordCount??0,"条"]})]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:335:21",className:"flex items-center gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:336:23",className:"text-right",children:[e.jsx("p",{"code-path":"src/components/cloud/DomainManager.tsx:337:25",className:"text-sm text-slate-400",children:"到期时间"}),e.jsxs("p",{"code-path":"src/components/cloud/DomainManager.tsx:338:25",className:`text-sm font-medium ${k<30?"text-red-400":"text-slate-200"}`,children:[n?n.substring(0,10):"-",n&&` (${k}天)`,c&&E&&e.jsxs("span",{"code-path":"src/components/cloud/DomainManager.tsx:341:29",className:"text-slate-500",children:[" · SSL: ",E.substring(0,10)]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:345:23",className:"flex items-center gap-1",children:[e.jsx(x,{"code-path":"src/components/cloud/DomainManager.tsx:346:25",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-blue-400",onClick:()=>U(s),children:e.jsx(F,{"code-path":"src/components/cloud/DomainManager.tsx:352:27",className:"h-4 w-4"})}),e.jsx(x,{"code-path":"src/components/cloud/DomainManager.tsx:354:25",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-red-400",onClick:()=>G(s.id),children:e.jsx(se,{"code-path":"src/components/cloud/DomainManager.tsx:360:27",className:"h-4 w-4"})})]})]})]})})},s.id)})}),e.jsx(J,{"code-path":"src/components/cloud/DomainManager.tsx:373:7",open:R,onOpenChange:h,children:e.jsxs(K,{"code-path":"src/components/cloud/DomainManager.tsx:374:9",className:"bg-slate-800 border-slate-700 text-slate-100 max-w-lg",children:[e.jsxs(V,{"code-path":"src/components/cloud/DomainManager.tsx:375:11",children:[e.jsxs(W,{"code-path":"src/components/cloud/DomainManager.tsx:376:13",className:"text-slate-100 flex items-center gap-2",children:[e.jsx(v,{"code-path":"src/components/cloud/DomainManager.tsx:377:15",className:"h-5 w-5 text-blue-400"}),d?"编辑域名":"添加域名"]}),e.jsx(Y,{"code-path":"src/components/cloud/DomainManager.tsx:380:13",className:"text-slate-400",children:d?"修改域名注册信息、DNS 配置和 SSL 证书状态":"录入域名信息,包括注册商、DNS 服务商和到期时间"})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:385:11",className:"space-y-4 py-2",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:386:13",className:"space-y-2",children:[e.jsx(m,{"code-path":"src/components/cloud/DomainManager.tsx:387:15",className:"text-slate-300",children:"域名 *"}),e.jsx(i,{"code-path":"src/components/cloud/DomainManager.tsx:388:15",placeholder:"example.com",value:a.name,onChange:s=>t({...a,name:s.target.value}),className:"bg-slate-900 border-slate-700 text-slate-100"})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:396:13",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:397:15",className:"space-y-2",children:[e.jsx(m,{"code-path":"src/components/cloud/DomainManager.tsx:398:17",className:"text-slate-300",children:"注册商"}),e.jsx(i,{"code-path":"src/components/cloud/DomainManager.tsx:399:17",placeholder:"阿里云 / Cloudflare ...",value:a.registrar,onChange:s=>t({...a,registrar:s.target.value}),className:"bg-slate-900 border-slate-700 text-slate-100"})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:406:15",className:"space-y-2",children:[e.jsx(m,{"code-path":"src/components/cloud/DomainManager.tsx:407:17",className:"text-slate-300",children:"状态"}),e.jsxs("select",{"code-path":"src/components/cloud/DomainManager.tsx:408:17",value:a.status,onChange:s=>t({...a,status:s.target.value}),className:"w-full px-3 py-2 bg-slate-900 border border-slate-700 rounded-md text-slate-100 text-sm",children:[e.jsx("option",{"code-path":"src/components/cloud/DomainManager.tsx:413:19",value:"active",children:"正常"}),e.jsx("option",{"code-path":"src/components/cloud/DomainManager.tsx:414:19",value:"expired",children:"已过期"}),e.jsx("option",{"code-path":"src/components/cloud/DomainManager.tsx:415:19",value:"pending",children:"待审核"})]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:420:13",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:421:15",className:"space-y-2",children:[e.jsx(m,{"code-path":"src/components/cloud/DomainManager.tsx:422:17",className:"text-slate-300",children:"到期时间"}),e.jsx(i,{"code-path":"src/components/cloud/DomainManager.tsx:423:17",type:"date",value:a.expire_date,onChange:s=>t({...a,expire_date:s.target.value}),className:"bg-slate-900 border-slate-700 text-slate-100"})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:430:15",className:"space-y-2",children:[e.jsx(m,{"code-path":"src/components/cloud/DomainManager.tsx:431:17",className:"text-slate-300",children:"DNS 服务商"}),e.jsx(i,{"code-path":"src/components/cloud/DomainManager.tsx:432:17",placeholder:"Cloudflare / DNSPod ...",value:a.dns_provider,onChange:s=>t({...a,dns_provider:s.target.value}),className:"bg-slate-900 border-slate-700 text-slate-100"})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:441:13",className:"space-y-2",children:[e.jsx(m,{"code-path":"src/components/cloud/DomainManager.tsx:442:15",className:"text-slate-300",children:"解析记录数"}),e.jsx(i,{"code-path":"src/components/cloud/DomainManager.tsx:443:15",type:"number",placeholder:"0",value:a.record_count,onChange:s=>t({...a,record_count:s.target.value}),className:"bg-slate-900 border-slate-700 text-slate-100"})]}),e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:452:13",className:"grid grid-cols-2 gap-4 items-end",children:[e.jsxs("div",{"code-path":"src/components/cloud/DomainManager.tsx:453:15",className:"space-y-2",children:[e.jsx(m,{"code-path":"src/components/cloud/DomainManager.tsx:454:17",className:"text-slate-300",children:"SSL 证书到期"}),e.jsx(i,{"code-path":"src/components/cloud/DomainManager.tsx:455:17",type:"date",value:a.ssl_expire_date,onChange:s=>t({...a,ssl_expire_date:s.target.value}),disabled:!a.ssl_enabled,className:"bg-slate-900 border-slate-700 text-slate-100 disabled:opacity-40"})]}),e.jsxs("label",{"code-path":"src/components/cloud/DomainManager.tsx:463:15",className:"flex items-center gap-2 cursor-pointer pb-2",children:[e.jsx("input",{"code-path":"src/components/cloud/DomainManager.tsx:464:17",type:"checkbox",checked:a.ssl_enabled,onChange:s=>t({...a,ssl_enabled:s.target.checked}),className:"h-4 w-4 rounded border-slate-600 bg-slate-900 accent-cyan-500"}),e.jsx("span",{"code-path":"src/components/cloud/DomainManager.tsx:470:17",className:"text-slate-300 text-sm",children:"启用 SSL"})]})]})]}),e.jsxs(Z,{"code-path":"src/components/cloud/DomainManager.tsx:475:11",children:[e.jsx(x,{"code-path":"src/components/cloud/DomainManager.tsx:476:13",variant:"outline",onClick:()=>h(!1),className:"border-slate-700 text-slate-300",children:"取消"}),e.jsxs(x,{"code-path":"src/components/cloud/DomainManager.tsx:479:13",className:"bg-blue-600 hover:bg-blue-700",disabled:!a.name.trim()||w,onClick:A,children:[w?e.jsx(ee,{"code-path":"src/components/cloud/DomainManager.tsx:484:29",className:"h-4 w-4 mr-2 animate-spin"}):d?e.jsx(F,{"code-path":"src/components/cloud/DomainManager.tsx:484:97",className:"h-4 w-4 mr-2"}):e.jsx(I,{"code-path":"src/components/cloud/DomainManager.tsx:484:134",className:"h-4 w-4 mr-2"}),d?"保存修改":"创建域名"]})]})]})})]})}export{xe as DomainManager}; diff --git a/backend/static/assets/EventsPage-Dbw7LuoJ.js b/backend/static/assets/EventsPage-Dbw7LuoJ.js new file mode 100644 index 0000000..837dcd1 --- /dev/null +++ b/backend/static/assets/EventsPage-Dbw7LuoJ.js @@ -0,0 +1 @@ +import{i as he,k as ue,r as n,j as e,m as G,n as J,J as be,B as ge,A as ve,T as E,w as Q,q as ke}from"./index-DfyorCky.js";import{C as x,a as p}from"./card-C55cvSHg.js";import{B as g}from"./badge-xNW8x0G1.js";import{S as N,a as f,b as y,c as w,d as o}from"./select-D5qUzdAs.js";import{T as Ee,a as je,b as L,c as h,d as Pe,e as d}from"./table-5sHV4Akp.js";import{k as S}from"./kubernetes-J8O09fK7.js";import{R as Ne}from"./refresh-cw-DUB_tAG-.js";import{L as Z}from"./layers-FW4KKJMi.js";import{R as W,C as D,X as K,Y as M,T as V,B as O,a as ee}from"./generateCategoricalChart-6v9BPbG2.js";import{B as H}from"./BarChart-DlFprovY.js";import"./index-CWVNW_qu.js";const se=["#EF4444","#F59E0B","#3B82F6","#8B5CF6","#EC4899","#14B8A6","#F97316","#6366F1","#84CC16","#06B6D4"];function $e(){const{clusterCode:te}=he(),I=ue(),[C,U]=n.useState(!1),[m,X]=n.useState([]),[ne,ae]=n.useState([]),[ce,re]=n.useState([]),[i,oe]=n.useState("all"),[j,le]=n.useState("all"),[T,xe]=n.useState("0"),[c,Y]=n.useState(te||""),[r,q]=n.useState(null),[u,B]=n.useState(""),[b,R]=n.useState(""),[pe,de]=n.useState(null);n.useEffect(()=>{S.getClusters().then(s=>{const t=s?.list||[];if(ae(t),!c&&t.length>0){const a=t[0].code||String(t[0].id);Y(a),I(`/kubernetes/${a}/events`,{replace:!0})}}).catch(()=>{})},[]),n.useEffect(()=>{c&&S.getNamespaces(c).then(s=>{re(Array.isArray(s)?s:s?.list||s?.data||[])}).catch(()=>{})},[c]);const _=n.useCallback(async()=>{if(c){U(!0);try{const s=i==="all"?void 0:i,t=j==="all"?void 0:j,a=await S.getEvents(c,s,t);X(Array.isArray(a)?a:a?.list||[])}catch{X([])}finally{U(!1)}}},[c,i,j]),A=n.useCallback(async()=>{if(c)try{const s=i==="all"?void 0:i,t=parseInt(T)||void 0,a=await S.getEventsSummary(c,s,t);q(a||null)}catch{q(null)}},[c,i,T]);n.useEffect(()=>{_()},[_]),n.useEffect(()=>{A()},[A]);const v=n.useMemo(()=>{let s=m;return u&&(s=s.filter(t=>t.reason===u)),b&&(s=s.filter(t=>(t.object||"").startsWith(b+"/"))),s},[m,u,b]),me=n.useMemo(()=>m.filter(s=>s.type==="Warning").length,[m]),ie=n.useMemo(()=>m.filter(s=>s.type==="Normal").length,[m]),k=n.useMemo(()=>(r?.by_reason||[]).map(t=>({name:t.reason||"Unknown",count:t.count})),[r]),z=n.useMemo(()=>(r?.by_namespace||[]).map(t=>({name:t.namespace||"",count:t.count})),[r]),$=n.useMemo(()=>(r?.by_kind||[]).map(t=>({name:t.kind||"Unknown",count:t.count})),[r]),F=s=>s?s.replace("T"," ").substring(0,19):"-",P=s=>{if(!s)return"";const t=Date.now()-new Date(s).getTime();if(t<0)return"";const a=Math.floor(t/6e4);if(a<1)return"刚刚";if(a<60)return`${a}分钟前`;const l=Math.floor(a/60);return l<24?`${l}小时前`:`${Math.floor(l/24)}天前`};return e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:134:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:136:7",className:"flex items-center gap-2 text-sm text-slate-500",children:[e.jsx(G,{"code-path":"src/components/kubernetes/EventsPage.tsx:137:9",to:"/kubernetes",className:"hover:text-slate-300",children:"集群"}),c&&e.jsxs(e.Fragment,{children:[e.jsx(J,{"code-path":"src/components/kubernetes/EventsPage.tsx:138:29",className:"h-3 w-3"}),e.jsx(G,{"code-path":"src/components/kubernetes/EventsPage.tsx:138:65",to:`/kubernetes/${c}`,className:"hover:text-slate-300",children:c})]}),e.jsx(J,{"code-path":"src/components/kubernetes/EventsPage.tsx:139:9",className:"h-3 w-3"}),e.jsx("span",{"code-path":"src/components/kubernetes/EventsPage.tsx:139:45",className:"text-slate-300",children:"事件"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:143:7",className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/EventsPage.tsx:144:9",className:"text-lg font-semibold text-slate-100 flex items-center gap-2",children:[e.jsx(be,{"code-path":"src/components/kubernetes/EventsPage.tsx:145:11",className:"h-5 w-5 text-yellow-400"}),"事件中心"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:147:9",className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(N,{"code-path":"src/components/kubernetes/EventsPage.tsx:148:11",value:c,onValueChange:s=>{Y(s),I(`/kubernetes/${s}/events`)},children:[e.jsx(f,{"code-path":"src/components/kubernetes/EventsPage.tsx:149:13",className:"w-40 h-8 text-xs bg-slate-800 border-slate-700",children:e.jsx(y,{"code-path":"src/components/kubernetes/EventsPage.tsx:149:87"})}),e.jsx(w,{"code-path":"src/components/kubernetes/EventsPage.tsx:150:13",className:"bg-slate-800 border-slate-700",children:ne.map(s=>e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:151:42",value:s.code||String(s.id),className:"text-xs",children:s.name||s.code},s.id))})]}),e.jsxs(N,{"code-path":"src/components/kubernetes/EventsPage.tsx:154:11",value:i,onValueChange:s=>{oe(s),B(""),R("")},children:[e.jsx(f,{"code-path":"src/components/kubernetes/EventsPage.tsx:155:13",className:"w-36 h-8 text-xs bg-slate-800 border-slate-700",children:e.jsx(y,{"code-path":"src/components/kubernetes/EventsPage.tsx:155:87",placeholder:"命名空间"})}),e.jsxs(w,{"code-path":"src/components/kubernetes/EventsPage.tsx:156:13",className:"bg-slate-800 border-slate-700",children:[e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:157:15",value:"all",className:"text-xs",children:"所有命名空间"}),ce.map(s=>e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:158:36",value:s,className:"text-xs",children:s},s))]})]}),e.jsxs(N,{"code-path":"src/components/kubernetes/EventsPage.tsx:161:11",value:T,onValueChange:s=>xe(s),children:[e.jsx(f,{"code-path":"src/components/kubernetes/EventsPage.tsx:162:13",className:"w-32 h-8 text-xs bg-slate-800 border-slate-700",children:e.jsx(y,{"code-path":"src/components/kubernetes/EventsPage.tsx:162:87"})}),e.jsxs(w,{"code-path":"src/components/kubernetes/EventsPage.tsx:163:13",className:"bg-slate-800 border-slate-700",children:[e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:164:15",value:"0",className:"text-xs",children:"全部时间"}),e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:165:15",value:"1",className:"text-xs",children:"近 1 小时"}),e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:166:15",value:"6",className:"text-xs",children:"近 6 小时"}),e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:167:15",value:"24",className:"text-xs",children:"近 24 小时"}),e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:168:15",value:"168",className:"text-xs",children:"近 7 天"})]})]}),e.jsxs(ge,{"code-path":"src/components/kubernetes/EventsPage.tsx:171:11",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300 text-xs",onClick:()=>{_(),A()},disabled:C,children:[e.jsx(Ne,{"code-path":"src/components/kubernetes/EventsPage.tsx:172:13",className:`h-3 w-3 mr-1 ${C?"animate-spin":""}`}),"刷新"]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:178:7",className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(x,{"code-path":"src/components/kubernetes/EventsPage.tsx:179:9",className:"bg-slate-900 border-slate-800",children:e.jsx(p,{"code-path":"src/components/kubernetes/EventsPage.tsx:180:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:181:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:182:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:183:17",className:"text-xs text-slate-500 mb-1",children:"事件总数"}),e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:184:17",className:"text-2xl font-bold text-slate-100",children:r?.total??m.length})]}),e.jsx(ve,{"code-path":"src/components/kubernetes/EventsPage.tsx:186:15",className:"h-8 w-8 text-slate-600"})]})})}),e.jsx(x,{"code-path":"src/components/kubernetes/EventsPage.tsx:190:9",className:"bg-slate-900 border-red-900/40",children:e.jsx(p,{"code-path":"src/components/kubernetes/EventsPage.tsx:191:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:192:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:193:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:194:17",className:"text-xs text-slate-500 mb-1",children:"告警事件"}),e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:195:17",className:"text-2xl font-bold text-red-400",children:r?.warning_count??me}),e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:196:17",className:"text-[10px] text-slate-600 mt-0.5",children:"Warning 累计触发次数"})]}),e.jsx(E,{"code-path":"src/components/kubernetes/EventsPage.tsx:198:15",className:"h-8 w-8 text-red-500/30"})]})})}),e.jsx(x,{"code-path":"src/components/kubernetes/EventsPage.tsx:202:9",className:"bg-slate-900 border-emerald-900/40",children:e.jsx(p,{"code-path":"src/components/kubernetes/EventsPage.tsx:203:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:204:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:205:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:206:17",className:"text-xs text-slate-500 mb-1",children:"正常事件"}),e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:207:17",className:"text-2xl font-bold text-emerald-400",children:r?.normal_count??ie})]}),e.jsx(Q,{"code-path":"src/components/kubernetes/EventsPage.tsx:209:15",className:"h-8 w-8 text-emerald-500/30"})]})})}),e.jsx(x,{"code-path":"src/components/kubernetes/EventsPage.tsx:213:9",className:"bg-slate-900 border-slate-800",children:e.jsx(p,{"code-path":"src/components/kubernetes/EventsPage.tsx:214:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:215:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:216:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:217:17",className:"text-xs text-slate-500 mb-1",children:"告警类型数"}),e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:218:17",className:"text-2xl font-bold text-amber-400",children:k.length}),e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:219:17",className:"text-[10px] text-slate-600 mt-0.5",children:"不同 Reason 数量"})]}),e.jsx(Z,{"code-path":"src/components/kubernetes/EventsPage.tsx:221:15",className:"h-8 w-8 text-amber-500/30"})]})})})]}),(u||b)&&e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:229:9",className:"flex items-center gap-2",children:[e.jsx("span",{"code-path":"src/components/kubernetes/EventsPage.tsx:230:11",className:"text-xs text-slate-500",children:"已选过滤:"}),u&&e.jsxs(g,{"code-path":"src/components/kubernetes/EventsPage.tsx:232:13",className:"bg-amber-500/20 text-amber-300 border-amber-500/30 cursor-pointer text-xs",onClick:()=>B(""),children:["原因: ",u," ✕"]}),b&&e.jsxs(g,{"code-path":"src/components/kubernetes/EventsPage.tsx:237:13",className:"bg-blue-500/20 text-blue-300 border-blue-500/30 cursor-pointer text-xs",onClick:()=>R(""),children:["类型: ",b," ✕"]})]}),k.length>0&&e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:246:9",className:"grid grid-cols-1 lg:grid-cols-3 gap-4",children:[e.jsx(x,{"code-path":"src/components/kubernetes/EventsPage.tsx:248:11",className:"bg-slate-900 border-slate-800",children:e.jsxs(p,{"code-path":"src/components/kubernetes/EventsPage.tsx:249:13",className:"p-4",children:[e.jsxs("h3",{"code-path":"src/components/kubernetes/EventsPage.tsx:250:15",className:"text-sm font-medium text-slate-300 mb-3 flex items-center gap-1.5",children:[e.jsx(E,{"code-path":"src/components/kubernetes/EventsPage.tsx:251:17",className:"h-4 w-4 text-amber-400"}),"告警原因 Top ",k.length]}),e.jsx(W,{"code-path":"src/components/kubernetes/EventsPage.tsx:253:15",width:"100%",height:220,children:e.jsxs(H,{"code-path":"src/components/kubernetes/EventsPage.tsx:254:17",data:k,layout:"vertical",margin:{left:10,right:10,top:0,bottom:0},children:[e.jsx(D,{"code-path":"src/components/kubernetes/EventsPage.tsx:255:19",strokeDasharray:"3 3",stroke:"#1e293b",horizontal:!1}),e.jsx(K,{"code-path":"src/components/kubernetes/EventsPage.tsx:256:19",type:"number",tick:{fill:"#64748b",fontSize:10},axisLine:{stroke:"#334155"}}),e.jsx(M,{"code-path":"src/components/kubernetes/EventsPage.tsx:257:19",type:"category",dataKey:"name",tick:{fill:"#94a3b8",fontSize:10},width:100,axisLine:{stroke:"#334155"}}),e.jsx(V,{"code-path":"src/components/kubernetes/EventsPage.tsx:258:19",contentStyle:{background:"#1e293b",border:"1px solid #334155",borderRadius:"6px",fontSize:"12px"},labelStyle:{color:"#e2e8f0"}}),e.jsx(O,{"code-path":"src/components/kubernetes/EventsPage.tsx:262:19",dataKey:"count",radius:[0,4,4,0],cursor:"pointer",onClick:s=>B(t=>t===s?.name?"":s?.name),children:k.map((s,t)=>e.jsx(ee,{"code-path":"src/components/kubernetes/EventsPage.tsx:264:23",fill:se[t%se.length]},t))})]})}),e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:269:15",className:"text-[10px] text-slate-600 text-center mt-1",children:"点击柱状图过滤事件列表"})]})}),z.length>0&&e.jsx(x,{"code-path":"src/components/kubernetes/EventsPage.tsx:275:13",className:"bg-slate-900 border-slate-800",children:e.jsxs(p,{"code-path":"src/components/kubernetes/EventsPage.tsx:276:15",className:"p-4",children:[e.jsxs("h3",{"code-path":"src/components/kubernetes/EventsPage.tsx:277:17",className:"text-sm font-medium text-slate-300 mb-3 flex items-center gap-1.5",children:[e.jsx(ke,{"code-path":"src/components/kubernetes/EventsPage.tsx:278:19",className:"h-4 w-4 text-blue-400"}),"命名空间分布 Top ",z.length]}),e.jsx(W,{"code-path":"src/components/kubernetes/EventsPage.tsx:280:17",width:"100%",height:220,children:e.jsxs(H,{"code-path":"src/components/kubernetes/EventsPage.tsx:281:19",data:z,layout:"vertical",margin:{left:10,right:10,top:0,bottom:0},children:[e.jsx(D,{"code-path":"src/components/kubernetes/EventsPage.tsx:282:21",strokeDasharray:"3 3",stroke:"#1e293b",horizontal:!1}),e.jsx(K,{"code-path":"src/components/kubernetes/EventsPage.tsx:283:21",type:"number",tick:{fill:"#64748b",fontSize:10},axisLine:{stroke:"#334155"}}),e.jsx(M,{"code-path":"src/components/kubernetes/EventsPage.tsx:284:21",type:"category",dataKey:"name",tick:{fill:"#94a3b8",fontSize:10},width:80,axisLine:{stroke:"#334155"}}),e.jsx(V,{"code-path":"src/components/kubernetes/EventsPage.tsx:285:21",contentStyle:{background:"#1e293b",border:"1px solid #334155",borderRadius:"6px",fontSize:"12px"},labelStyle:{color:"#e2e8f0"}}),e.jsx(O,{"code-path":"src/components/kubernetes/EventsPage.tsx:289:21",dataKey:"count",radius:[0,4,4,0],fill:"#3B82F6",fillOpacity:.7})]})})]})}),$.length>0&&e.jsx(x,{"code-path":"src/components/kubernetes/EventsPage.tsx:298:13",className:"bg-slate-900 border-slate-800",children:e.jsxs(p,{"code-path":"src/components/kubernetes/EventsPage.tsx:299:15",className:"p-4",children:[e.jsxs("h3",{"code-path":"src/components/kubernetes/EventsPage.tsx:300:17",className:"text-sm font-medium text-slate-300 mb-3 flex items-center gap-1.5",children:[e.jsx(Z,{"code-path":"src/components/kubernetes/EventsPage.tsx:301:19",className:"h-4 w-4 text-purple-400"}),"资源类型分布"]}),e.jsx(W,{"code-path":"src/components/kubernetes/EventsPage.tsx:303:17",width:"100%",height:220,children:e.jsxs(H,{"code-path":"src/components/kubernetes/EventsPage.tsx:304:19",data:$,layout:"vertical",margin:{left:10,right:10,top:0,bottom:0},children:[e.jsx(D,{"code-path":"src/components/kubernetes/EventsPage.tsx:305:21",strokeDasharray:"3 3",stroke:"#1e293b",horizontal:!1}),e.jsx(K,{"code-path":"src/components/kubernetes/EventsPage.tsx:306:21",type:"number",tick:{fill:"#64748b",fontSize:10},axisLine:{stroke:"#334155"}}),e.jsx(M,{"code-path":"src/components/kubernetes/EventsPage.tsx:307:21",type:"category",dataKey:"name",tick:{fill:"#94a3b8",fontSize:10},width:80,axisLine:{stroke:"#334155"}}),e.jsx(V,{"code-path":"src/components/kubernetes/EventsPage.tsx:308:21",contentStyle:{background:"#1e293b",border:"1px solid #334155",borderRadius:"6px",fontSize:"12px"},labelStyle:{color:"#e2e8f0"}}),e.jsx(O,{"code-path":"src/components/kubernetes/EventsPage.tsx:312:21",dataKey:"count",radius:[0,4,4,0],cursor:"pointer",onClick:s=>R(t=>t===s?.name?"":s?.name),children:$.map((s,t)=>e.jsx(ee,{"code-path":"src/components/kubernetes/EventsPage.tsx:314:25",fill:["#8B5CF6","#6366F1","#EC4899","#14B8A6"][t%4],fillOpacity:.7},t))})]})}),e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:319:17",className:"text-[10px] text-slate-600 text-center mt-1",children:"点击柱状图过滤事件列表"})]})})]}),r?.recent_warnings?.length>0&&e.jsx(x,{"code-path":"src/components/kubernetes/EventsPage.tsx:328:9",className:"bg-red-950/20 border-red-900/30",children:e.jsxs(p,{"code-path":"src/components/kubernetes/EventsPage.tsx:329:11",className:"p-4",children:[e.jsxs("h3",{"code-path":"src/components/kubernetes/EventsPage.tsx:330:13",className:"text-sm font-medium text-red-300 mb-3 flex items-center gap-1.5",children:[e.jsx(E,{"code-path":"src/components/kubernetes/EventsPage.tsx:331:15",className:"h-4 w-4"}),"最新告警事件 (",r.recent_warnings.length,")"]}),e.jsx("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:333:13",className:"space-y-1.5",children:r.recent_warnings.map((s,t)=>e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:335:17",className:"flex items-start gap-2 text-xs py-1.5 px-2 rounded bg-slate-900/40 hover:bg-slate-800/40 transition-colors",children:[e.jsx(E,{"code-path":"src/components/kubernetes/EventsPage.tsx:336:19",className:"h-3.5 w-3.5 text-red-400 mt-0.5 shrink-0"}),e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:337:19",className:"flex-1 min-w-0",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:338:21",className:"flex items-center gap-2 flex-wrap",children:[e.jsx(g,{"code-path":"src/components/kubernetes/EventsPage.tsx:339:23",variant:"outline",className:"text-[10px] h-4 px-1 border-red-500/30 text-red-400",children:s.reason}),e.jsx("span",{"code-path":"src/components/kubernetes/EventsPage.tsx:340:23",className:"text-slate-500 font-mono text-[11px]",children:s.object}),e.jsx("span",{"code-path":"src/components/kubernetes/EventsPage.tsx:341:23",className:"text-slate-600 text-[10px]",children:s.namespace}),e.jsxs("span",{"code-path":"src/components/kubernetes/EventsPage.tsx:342:23",className:"text-slate-600 text-[10px]",children:["×",s.count]}),e.jsx("span",{"code-path":"src/components/kubernetes/EventsPage.tsx:343:23",className:"text-slate-600 text-[10px] ml-auto",children:P(s.last_time)})]}),e.jsx("p",{"code-path":"src/components/kubernetes/EventsPage.tsx:345:21",className:"text-slate-400 mt-0.5 truncate",title:s.message,children:s.message})]})]},t))})]})}),e.jsx(x,{"code-path":"src/components/kubernetes/EventsPage.tsx:355:7",className:"bg-slate-900 border-slate-800",children:e.jsxs(p,{"code-path":"src/components/kubernetes/EventsPage.tsx:356:9",className:"p-0",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:357:11",className:"flex items-center justify-between px-4 py-2 border-b border-slate-800",children:[e.jsxs("span",{"code-path":"src/components/kubernetes/EventsPage.tsx:358:13",className:"text-sm text-slate-400",children:["事件列表 (",v.length,")"]}),e.jsxs(N,{"code-path":"src/components/kubernetes/EventsPage.tsx:359:13",value:j,onValueChange:le,children:[e.jsx(f,{"code-path":"src/components/kubernetes/EventsPage.tsx:360:15",className:"w-28 h-7 text-xs bg-slate-800 border-slate-700",children:e.jsx(y,{"code-path":"src/components/kubernetes/EventsPage.tsx:360:89"})}),e.jsxs(w,{"code-path":"src/components/kubernetes/EventsPage.tsx:361:15",className:"bg-slate-800 border-slate-700",children:[e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:362:17",value:"all",className:"text-xs",children:"所有类型"}),e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:363:17",value:"Warning",className:"text-xs",children:"⚠ Warning"}),e.jsx(o,{"code-path":"src/components/kubernetes/EventsPage.tsx:364:17",value:"Normal",className:"text-xs",children:"ℹ Normal"})]})]})]}),e.jsxs(Ee,{"code-path":"src/components/kubernetes/EventsPage.tsx:368:11",children:[e.jsx(je,{"code-path":"src/components/kubernetes/EventsPage.tsx:369:13",children:e.jsxs(L,{"code-path":"src/components/kubernetes/EventsPage.tsx:369:26",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(h,{"code-path":"src/components/kubernetes/EventsPage.tsx:370:15",className:"text-slate-400 w-16",children:"类型"}),e.jsx(h,{"code-path":"src/components/kubernetes/EventsPage.tsx:371:15",className:"text-slate-400 w-24",children:"原因"}),e.jsx(h,{"code-path":"src/components/kubernetes/EventsPage.tsx:372:15",className:"text-slate-400",children:"对象"}),e.jsx(h,{"code-path":"src/components/kubernetes/EventsPage.tsx:373:15",className:"text-slate-400",children:"消息"}),e.jsx(h,{"code-path":"src/components/kubernetes/EventsPage.tsx:374:15",className:"text-slate-400 w-12",children:"次数"}),e.jsx(h,{"code-path":"src/components/kubernetes/EventsPage.tsx:375:15",className:"text-slate-400 w-20",children:"命名空间"}),e.jsx(h,{"code-path":"src/components/kubernetes/EventsPage.tsx:376:15",className:"text-slate-400 w-40",children:"最后时间"})]})}),e.jsx(Pe,{"code-path":"src/components/kubernetes/EventsPage.tsx:378:13",children:v.length===0?e.jsx(L,{"code-path":"src/components/kubernetes/EventsPage.tsx:380:17",children:e.jsx(d,{"code-path":"src/components/kubernetes/EventsPage.tsx:380:27",colSpan:7,className:"text-center text-slate-500 py-8",children:C?e.jsx("span",{"code-path":"src/components/kubernetes/EventsPage.tsx:381:30",className:"animate-spin inline-block",children:"⏳"}):"暂无事件"})}):v.slice(0,200).map((s,t)=>{const a=`${s.name}-${t}`,l=pe===a;return e.jsxs(L,{"code-path":"src/components/kubernetes/EventsPage.tsx:387:19",className:`border-slate-800 cursor-pointer ${s.type==="Warning"?"hover:bg-red-950/10":"hover:bg-slate-800/30"} ${l?"bg-slate-800/20":""}`,onClick:()=>de(l?null:a),children:[e.jsx(d,{"code-path":"src/components/kubernetes/EventsPage.tsx:392:21",children:s.type==="Warning"?e.jsxs(g,{"code-path":"src/components/kubernetes/EventsPage.tsx:394:25",className:"bg-red-500/20 text-red-400 border-red-500/30 text-xs",children:[e.jsx(E,{"code-path":"src/components/kubernetes/EventsPage.tsx:394:97",className:"h-3 w-3 mr-0.5 inline"}),"W"]}):e.jsxs(g,{"code-path":"src/components/kubernetes/EventsPage.tsx:396:25",className:"bg-blue-500/20 text-blue-400 border-blue-500/30 text-xs",children:[e.jsx(Q,{"code-path":"src/components/kubernetes/EventsPage.tsx:396:100",className:"h-3 w-3 mr-0.5 inline"}),"N"]})}),e.jsx(d,{"code-path":"src/components/kubernetes/EventsPage.tsx:399:21",className:"text-xs text-slate-300 font-medium",children:e.jsx("span",{"code-path":"src/components/kubernetes/EventsPage.tsx:400:23",className:s.type==="Warning"?"text-amber-400":"text-slate-400",children:s.reason||"-"})}),e.jsx(d,{"code-path":"src/components/kubernetes/EventsPage.tsx:402:21",className:"text-xs text-slate-500 font-mono",children:s.object||"-"}),e.jsxs(d,{"code-path":"src/components/kubernetes/EventsPage.tsx:403:21",className:"text-xs text-slate-400 max-w-[400px]",children:[e.jsx("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:404:23",className:`truncate ${l?"whitespace-normal":""}`,title:l?void 0:s.message,children:s.message||"-"}),l&&e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:408:25",className:"mt-1 pt-1 border-t border-slate-800 text-[10px] text-slate-600 space-y-0.5",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:409:27",children:["首次出现: ",F(s.first_time)," (",P(s.first_time),")"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:410:27",children:["最后出现: ",F(s.last_time)," (",P(s.last_time),")"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:411:27",children:["事件名称: ",s.name]})]})]}),e.jsx(d,{"code-path":"src/components/kubernetes/EventsPage.tsx:415:21",className:"text-sm text-slate-400 text-center",children:s.count>1?e.jsx(g,{"code-path":"src/components/kubernetes/EventsPage.tsx:416:38",variant:"outline",className:"text-[10px] h-4 px-1",children:s.count}):e.jsx("span",{"code-path":"src/components/kubernetes/EventsPage.tsx:416:116",className:"text-slate-600",children:"1"})}),e.jsx(d,{"code-path":"src/components/kubernetes/EventsPage.tsx:418:21",className:"text-xs text-slate-500",children:s.namespace||"-"}),e.jsxs(d,{"code-path":"src/components/kubernetes/EventsPage.tsx:419:21",className:"text-xs text-slate-500",children:[e.jsx("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:420:23",children:F(s.last_time)}),e.jsx("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:421:23",className:"text-[10px] text-slate-600",children:P(s.last_time)})]})]},a)})})]}),v.length>200&&e.jsxs("div",{"code-path":"src/components/kubernetes/EventsPage.tsx:429:13",className:"text-center py-2 text-xs text-slate-600 border-t border-slate-800",children:["仅显示前 200 条,共 ",v.length," 条事件"]})]})})]})}export{$e as default}; diff --git a/backend/static/assets/GrafanaDashboard-BoB6WmDi.js b/backend/static/assets/GrafanaDashboard-BoB6WmDi.js new file mode 100644 index 0000000..a24eadc --- /dev/null +++ b/backend/static/assets/GrafanaDashboard-BoB6WmDi.js @@ -0,0 +1,3 @@ +import{g as ya,j as a,r as o,h as oa,A as J,B as D,L as aa,T as Na,q as Q,v as Ya,o as ka,W as Wa,D as ra,b as na,c as da,d as ca,e as _a,H as pa,a9 as Qa,t as Xa,I as X,E as as,aq as $a,a as ss,k as es,a7 as ts,w as os,f as va,K as Za,G as Ta}from"./index-DfyorCky.js";import{B as E}from"./badge-xNW8x0G1.js";import{C as z,b as Ga,c as wa,a as k}from"./card-C55cvSHg.js";import{S as ba,a as ua,b as ga,c as fa,d as O}from"./select-D5qUzdAs.js";import{L}from"./label-BK0h2apY.js";import{t as u}from"./index-a3ybMjbR.js";import{s as Fa}from"./server-CjDPBaTN.js";import{z as rs,p as ns,d as ja}from"./monitor-BAaBXIsC.js";import{a as Aa}from"./agent-DqqIRCQX.js";import{T as ds}from"./trending-up-CdusV6gc.js";import{R as ha}from"./refresh-cw-DUB_tAG-.js";import{W as Ma}from"./wifi-FqsslTyA.js";import{A as Ia}from"./arrow-up-down-DnvTt5VG.js";import{T as Ba,a as Oa,b as R,c as K}from"./tabs-CIh_yD4s.js";import{Z as ta}from"./zap-D2uWSK32.js";import{C as cs}from"./copy-DXW4LnkN.js";import{D as hs}from"./download-DoZfYs2h.js";import{P as ms}from"./play-cdPayOtJ.js";import{C as Da}from"./checkbox-CH0bpj6b.js";import{M as is,a as ls}from"./minimize-2-CiCQYRfn.js";import{P as Sa}from"./package-open-CUXo2Tda.js";import{T as xs}from"./trash-2-Dx32pOzT.js";import{E as Ea}from"./external-link-CzIpMNu1.js";import{P as Ca}from"./plus-CUG-9kpu.js";import"./index-CWVNW_qu.js";const ps=[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]],Ua=ya("arrow-down",ps);const bs=[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]],Ha=ya("arrow-up",bs);const us=[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]],gs=ya("wifi-off",us);function fs(s){return s?Array.isArray(s)?s:Array.isArray(s.list)?s.list:Array.isArray(s.items)?s.items:Array.isArray(s.data)?s.data:[]:[]}function js(s){const e=[];for(let c=0;c<24;c++)e.push({time:new Date(Date.now()-(24-c)*36e5).toLocaleTimeString(),value:Math.random()*100});return e}function Ds({panel:s}){const r=js();switch(s.type){case"stat":return a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:24:9",className:"flex flex-col items-center justify-center h-full",children:[a.jsx("span",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:25:11",className:"text-4xl font-bold text-blue-500",children:Math.floor(Math.random()*1e3)}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:26:11",className:"text-sm text-muted-foreground mt-2",children:s.options?.unit||"requests/s"}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:27:11",className:"flex items-center gap-1 mt-2 text-green-500 text-sm",children:[a.jsx(ds,{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:28:13",className:"w-4 h-4"}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:29:13",children:"+12.5%"})]})]});case"gauge":return a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:35:9",className:"flex flex-col items-center justify-center h-full",children:[a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:36:11",className:"relative w-24 h-24",children:[a.jsxs("svg",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:37:13",className:"w-full h-full",viewBox:"0 0 100 100",children:[a.jsx("circle",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:38:15",cx:"50",cy:"50",r:"40",fill:"none",stroke:"#e5e7eb",strokeWidth:"10"}),a.jsx("circle",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:39:15",cx:"50",cy:"50",r:"40",fill:"none",stroke:"#3b82f6",strokeWidth:"10",strokeDasharray:`${Math.random()*251} 251`,transform:"rotate(-90 50 50)"})]}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:50:13",className:"absolute inset-0 flex items-center justify-center",children:a.jsxs("span",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:51:15",className:"text-xl font-bold",children:[Math.floor(Math.random()*100),"%"]})})]}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:54:11",className:"text-sm text-muted-foreground mt-2",children:"CPU使用率"})]});default:return a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:60:9",className:"h-full flex flex-col",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:61:11",className:"flex-1 flex items-end gap-1 px-2",children:r.map((e,c)=>a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:63:15",className:"flex-1 bg-blue-500 rounded-t",style:{height:`${e.value}%`,opacity:.3+c/r.length*.7}},c))}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:70:11",className:"flex justify-between text-xs text-muted-foreground px-2 pt-2",children:[a.jsx("span",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:71:13",children:r[0].time}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/GrafanaPanelContent.tsx:72:13",children:r[r.length-1].time})]})]})}}const Ns=({dsUrl:s,dsUsername:r,dsPassword:e})=>{const[c,i]=o.useState(!1),[x,b]=o.useState(!1),[g,N]=o.useState([]),[w,m]=o.useState(""),[P,y]=o.useState(""),[W,v]=o.useState("cpu_usage"),[h,A]=o.useState("desc");o.useEffect(()=>{s&&r&&e&&$(s,r,e)},[s,r,e]);const $=async(n,l,S)=>{b(!0),y("");try{const j=await oa.post("/zabbix/connect",{url:n,username:l,password:S});N(j.hosts||[]),m(j.version||""),i(!0)}catch(j){i(!1),y(j.message||"连接失败")}finally{b(!1)}},F=()=>{s&&r&&e&&$(s,r,e)},M=n=>{W===n?A(l=>l==="asc"?"desc":"asc"):(v(n),A("desc"))},I=[...g].sort((n,l)=>{const S=n[W]??"",j=l[W]??"";return typeof S=="number"?h==="asc"?S-j:j-S:h==="asc"?String(S).localeCompare(String(j)):String(j).localeCompare(String(S))}),T=({f:n})=>W!==n?a.jsx(Ia,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:68:33",className:"w-3 h-3 text-slate-500"}):h==="asc"?a.jsx(Ha,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:69:32",className:"w-3 h-3 text-blue-400"}):a.jsx(Ua,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:69:80",className:"w-3 h-3 text-blue-400"}),p=(n,l)=>a.jsxs("div",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:73:5",className:"flex items-center gap-2 min-w-[90px]",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:74:7",className:"flex-1 h-2.5 rounded-full bg-[var(--dg-bg-tertiary)] overflow-hidden",children:a.jsx("div",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:75:9",className:`h-full rounded-full transition-all duration-500 ${n>=80?"bg-orange-500":"bg-blue-500"}`,style:{width:`${Math.min(n,100)}%`}})}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:77:7",className:`w-14 text-right text-xs font-mono tabular-nums ${n>=80?"text-orange-400":""}`,children:l})]}),f=n=>!n||n===0?"—":n>1e9?`${(n/1e9).toFixed(1)} GB/s`:n>1e6?`${(n/1e6).toFixed(1)} MB/s`:n>1e3?`${(n/1e3).toFixed(1)} KB/s`:`${n.toFixed(1)} B/s`;return!c&&!x&&!P?null:a.jsxs(z,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:92:5",className:"bg-[var(--dg-bg-secondary)] border-blue-500/20",children:[a.jsx(Ga,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:93:7",className:"py-3 px-4 pb-2",children:a.jsxs("div",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:94:9",className:"flex items-center gap-2",children:[a.jsx(J,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:95:11",className:"h-4 w-4 text-blue-400"}),a.jsx(wa,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:96:11",className:"text-sm font-medium",children:"Zabbix 主机监控"}),w&&a.jsxs(E,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:97:23",className:"text-[10px] bg-blue-500/10 text-blue-400",children:["v",w]}),c&&a.jsxs("span",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:98:25",className:"text-[10px] text-[var(--dg-text-muted)] ml-2",children:[g.length," 台"]}),c&&a.jsx("div",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:99:25",className:"ml-auto flex gap-1",children:a.jsxs(D,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:99:61",variant:"ghost",size:"sm",className:"h-6 px-2 text-[10px]",onClick:F,children:[a.jsx(ha,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:99:146",className:"w-3 h-3 mr-1"}),"刷新"]})})]})}),a.jsx(k,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:102:7",className:"px-4 pb-3 pt-0",children:x?a.jsxs("div",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:103:21",className:"text-center py-12",children:[a.jsx(aa,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:103:56",className:"h-6 w-6 mx-auto mb-2 animate-spin text-blue-400"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:103:127",className:"text-xs text-[var(--dg-text-muted)]",children:"连接中…"})]}):P?a.jsxs("div",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:104:20",className:"p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs text-red-400 flex items-start gap-2",children:[a.jsx(Na,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:104:135",className:"h-4 w-4 mt-0.5"}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:104:179",children:P})]}):g.length===0?a.jsxs("div",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:105:33",className:"text-center py-8 text-[var(--dg-text-muted)]",children:[a.jsx(Q,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:105:95",className:"h-8 w-8 mx-auto mb-2 text-slate-600"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:105:153",className:"text-sm",children:"未找到被监控的 Zabbix 主机"})]}):a.jsx("div",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:107:11",className:"overflow-x-auto rounded-lg border border-[var(--dg-border)]",children:a.jsxs("table",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:108:13",className:"w-full text-xs",children:[a.jsx("thead",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:109:15",className:"bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]",children:a.jsx("tr",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:109:96",children:[{f:"hostname",l:"主机名"},{f:"cpu_usage",l:"CPU"},{f:"memory_usage",l:"内存"},{f:"disk_usage",l:"磁盘"},{f:"load5",l:"Load5"},{f:"net_in_bps",l:"流入"},{f:"net_out_bps",l:"流出"},{f:"problem_count",l:"问题"},{f:"uptime_days",l:"运行"}].map(({f:n,l})=>a.jsx("th",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:115:19",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] cursor-pointer hover:text-[var(--dg-text-primary)] select-none whitespace-nowrap",onClick:()=>M(n),children:a.jsxs("div",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:116:21",className:"flex items-center gap-1",children:[l,a.jsx(T,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:116:65",f:n})]})},n))})}),a.jsx("tbody",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:118:15",children:I.map((n,l)=>a.jsxs("tr",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:120:19",className:"border-b border-[var(--dg-border)] last:border-0 hover:bg-[var(--dg-bg-tertiary)]/50",children:[a.jsxs("td",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:121:21",className:"px-3 py-2.5 whitespace-nowrap",children:[a.jsxs(E,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:121:67",className:`text-[10px] ${n.available==="1"?"bg-emerald-500/20 text-emerald-400":"bg-red-500/20 text-red-400"}`,children:[a.jsx(Ma,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:121:193",className:"w-3 h-3 mr-1"}),n.available==="1"?"UP":"DOWN"]})," ",a.jsx("span",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:121:272",className:"font-medium text-[var(--dg-text-primary)] ml-1",children:n.name||n.hostname})]}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:122:21",className:"px-3 py-2.5",children:p(Number(n.cpu_usage||0),`${Number(n.cpu_usage||0).toFixed(1)}%`)}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:123:21",className:"px-3 py-2.5",children:p(Number(n.memory_usage||0),`${Number(n.memory_usage||0).toFixed(1)}%`)}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:124:21",className:"px-3 py-2.5",children:p(Number(n.disk_usage||0),`${Number(n.disk_usage||0).toFixed(1)}%`)}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:125:21",className:"px-3 py-2.5 text-[var(--dg-text-secondary)]",children:n.load5>0?n.load5.toFixed(1):"—"}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:126:21",className:"px-3 py-2.5 font-mono text-[var(--dg-text-secondary)]",children:f(n.net_in_bps)}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:127:21",className:"px-3 py-2.5 font-mono text-[var(--dg-text-secondary)]",children:f(n.net_out_bps)}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:128:21",className:"px-3 py-2.5 text-center",children:a.jsx("span",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:128:61",className:`font-mono font-bold ${n.problem_count>0?n.problem_count>2?"text-red-400":"text-amber-400":"text-emerald-400"}`,children:n.problem_count>0?a.jsxs(a.Fragment,{children:[a.jsx(Na,{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:128:230",className:"w-3 h-3 inline mr-1"}),n.problem_count]}):"0"})}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/ZabbixDashboard.tsx:129:21",className:"px-3 py-2.5 text-[var(--dg-text-secondary)]",children:n.uptime_days>0?`${n.uptime_days}d`:"—"})]},n.hostid||l))})]})})})]})},V=({val:s,label:r,color:e})=>{const c=Math.min(s,100);return a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:15:5",className:"flex items-center gap-1.5 min-w-[80px]",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:16:7",className:"flex-1 h-2 rounded-full bg-[var(--dg-bg-tertiary)] overflow-hidden",children:a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:17:9",className:`h-full rounded-full ${e||"bg-purple-500"}`,style:{width:`${c}%`}})}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:19:7",className:"w-14 text-right text-[11px] font-mono text-[var(--dg-text-secondary)]",children:r})]})},vs=s=>s?s>1e9?`${(s/1e9).toFixed(1)} GB`:s>1e6?`${(s/1e6).toFixed(1)} MB`:`${(s/1e3).toFixed(1)} KB`:"—",za=s=>s?s>1e9?`${(s/1e9).toFixed(1)} GB/s`:s>1e6?`${(s/1e6).toFixed(1)} MB/s`:s>1e3?`${(s/1e3).toFixed(1)} KB/s`:`${s.toFixed(1)} B/s`:"—";function ys(s){return(s||[]).map(r=>{const e={...r.metric||{}};return r.value&&(e.value=r.value[1]),e})}const Gs=s=>a.jsx("svg",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:46:26",xmlns:"http://www.w3.org/2000/svg",width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",...s,children:a.jsx("path",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:46:211",d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"})}),ws=({d:s})=>a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:49:3",className:"space-y-4",children:[a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:50:5",className:"grid grid-cols-4 gap-3",children:[a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:51:7",className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:51:77",className:"p-3 text-center",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:51:118",className:"text-2xl font-bold text-purple-400",children:s.podCount?.[0]?.value||0}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:51:205",className:"text-[10px] text-[var(--dg-text-muted)]",children:"Pods"})]})}),a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:52:7",className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:52:77",className:"p-3 text-center",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:52:118",className:"text-2xl font-bold text-blue-400",children:s.deployCount?.[0]?.value||0}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:52:206",className:"text-[10px] text-[var(--dg-text-muted)]",children:"Deployments"})]})}),a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:53:7",className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:53:77",className:"p-3 text-center",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:53:118",className:"text-2xl font-bold text-emerald-400",children:s.nodeCount?.[0]?.value||0}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:53:207",className:"text-[10px] text-[var(--dg-text-muted)]",children:"Nodes"})]})}),a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:54:7",className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:54:77",className:"p-3 text-center",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:54:118",className:"text-2xl font-bold text-amber-400",children:s.nsPods?.length||0}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:54:198",className:"text-[10px] text-[var(--dg-text-muted)]",children:"Namespaces"})]})})]}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:56:5",className:"rounded-lg bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] p-3 max-h-60 overflow-y-auto",children:[a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:57:7",className:"text-xs font-medium mb-2 flex items-center gap-1",children:[a.jsx(ka,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:57:73",className:"w-3 h-3 text-purple-400"}),"节点 CPU / 内存利用率"]}),(s.nodeCPU||[]).map((r,e)=>{const c=(s.nodeMem||[]).find(i=>i.node===r.node);return a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:60:16",className:"flex items-center gap-3 text-[11px] mb-1.5",children:[a.jsx("span",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:60:84",className:"w-28 truncate",title:r.node,children:r.node}),a.jsx(V,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:60:146",val:Number(r.value||0),label:`${Number(r.value||0).toFixed(1)}%`}),a.jsx(V,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:60:226",val:Number(c?.value||0),label:`${Number(c?.value||0).toFixed(1)}%`,color:"bg-blue-500"})]},e)})]})]}),Ps=({d:s})=>a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:67:3",className:"overflow-x-auto rounded-lg border border-[var(--dg-border)]",children:a.jsxs("table",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:68:5",className:"w-full text-xs",children:[a.jsx("thead",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:69:7",className:"bg-[var(--dg-bg-tertiary)]",children:a.jsxs("tr",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:69:53",children:[a.jsx("th",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:69:57",className:"px-3 py-2 text-left",children:"节点"}),a.jsx("th",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:69:100",className:"px-3 py-2 text-left",children:"状态"}),a.jsx("th",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:69:143",className:"px-3 py-2 text-left",children:"CPU"}),a.jsx("th",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:69:187",className:"px-3 py-2 text-left",children:"内存"}),a.jsx("th",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:69:230",className:"px-3 py-2 text-left",children:"磁盘"}),a.jsx("th",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:69:273",className:"px-3 py-2 text-left",children:"流入"}),a.jsx("th",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:69:316",className:"px-3 py-2 text-left",children:"流出"})]})}),a.jsx("tbody",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:70:7",children:(s.nodes||[]).map((r,e)=>{const c=r.instance||r.exported_instance||"",i=(s.cpuUsage||[]).find(m=>m.instance===c),x=(s.memUsage||[]).find(m=>m.instance===c),b=(s.diskUsage||[]).find(m=>m.instance===c),g=(s.up||[]).find(m=>m.instance===c),N=(s.netRx||[]).find(m=>m.instance===c),w=(s.netTx||[]).find(m=>m.instance===c);return a.jsxs("tr",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:79:18",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50",children:[a.jsx("td",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:80:13",className:"px-3 py-2 font-medium",children:r.nodename||c}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:81:13",className:"px-3 py-2",children:a.jsx(E,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:81:39",className:`text-[10px] ${g?.value===1?"bg-emerald-500/20 text-emerald-400":"bg-red-500/20 text-red-400"}`,children:g?.value===1?"UP":"DOWN"})}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:82:13",className:"px-3 py-2",children:a.jsx(V,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:82:39",val:Number(i?.value||0),label:`${Number(i?.value||0).toFixed(1)}%`})}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:83:13",className:"px-3 py-2",children:a.jsx(V,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:83:39",val:Number(x?.value||0),label:`${Number(x?.value||0).toFixed(1)}%`,color:"bg-blue-500"})}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:84:13",className:"px-3 py-2",children:a.jsx(V,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:84:39",val:Number(b?.value||0),label:`${Number(b?.value||0).toFixed(1)}%`,color:"bg-amber-500"})}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:85:13",className:"px-3 py-2 font-mono text-[var(--dg-text-secondary)]",children:za(Number(N?.value||0))}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:86:13",className:"px-3 py-2 font-mono text-[var(--dg-text-secondary)]",children:za(Number(w?.value||0))})]},e)})})]})}),As=({d:s})=>a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:95:3",className:"space-y-4",children:[a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:96:5",className:"grid grid-cols-4 gap-3",children:[a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:97:7",className:"bg-[var(--dg-bg-primary)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:97:51",className:"p-3 text-center",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:97:92",className:"text-xl font-bold text-emerald-400",children:s.running?.[0]?.value||0}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:97:176",className:"text-[10px] text-[var(--dg-text-muted)]",children:"Running"})]})}),a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:98:7",className:"bg-[var(--dg-bg-primary)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:98:51",className:"p-3 text-center",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:98:92",className:"text-xl font-bold text-amber-400",children:s.pending?.[0]?.value||0}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:98:174",className:"text-[10px] text-[var(--dg-text-muted)]",children:"Pending"})]})})]}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:100:5",className:"rounded-lg bg-[var(--dg-bg-primary)] p-3 max-h-40 overflow-y-auto",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:100:88",className:"text-xs font-medium mb-2",children:"CPU Top 10"}),(s.cpuTop||[]).map((r,e)=>a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:100:186",className:"flex items-center gap-2 text-[11px] mb-1",children:[a.jsx("span",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:100:252",className:"w-10 text-right text-[var(--dg-text-muted)]",children:e+1}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:100:326",className:"w-32 truncate",title:r.pod,children:r.pod}),a.jsx(V,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:100:386",val:Number(r.value||0)*100,label:`${Number(r.value||0).toFixed(2)}c`,color:"bg-purple-500"})]},e))]}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:101:5",className:"rounded-lg bg-[var(--dg-bg-primary)] p-3 max-h-40 overflow-y-auto",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:101:88",className:"text-xs font-medium mb-2",children:"内存 Top 10"}),(s.memTop||[]).map((r,e)=>a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:101:185",className:"flex items-center gap-2 text-[11px] mb-1",children:[a.jsx("span",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:101:251",className:"w-10 text-right text-[var(--dg-text-muted)]",children:e+1}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:101:325",className:"w-32 truncate",title:r.pod,children:r.pod}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:101:385",className:"ml-auto",children:vs(Number(r.value||0))})]},e))]})]}),Ss=({d:s})=>{const r=Number(s.heapUsed?.[0]?.value||0),e=Number(s.uptime?.[0]?.value||0);return a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:109:5",className:"grid grid-cols-5 gap-3",children:[a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:110:7",className:"bg-[var(--dg-bg-primary)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:110:51",className:"p-3 text-center",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:110:92",className:"text-lg font-bold",children:e>86400?`${(e/86400).toFixed(1)}d`:`${(e/3600).toFixed(1)}h`}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:110:210",className:"text-[10px] text-[var(--dg-text-muted)]",children:"Uptime"})]})}),a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:111:7",className:"bg-[var(--dg-bg-primary)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:111:51",className:"p-3 text-center",children:[a.jsx(V,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:111:92",val:r,label:`${r.toFixed(1)}%`,color:r>80?"bg-orange-500":"bg-purple-500"}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:111:183",className:"text-[10px] text-[var(--dg-text-muted)] mt-1",children:"Heap"})]})}),a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:112:7",className:"bg-[var(--dg-bg-primary)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:112:51",className:"p-3 text-center",children:[a.jsx(V,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:112:92",val:Number(s.nonHeapUsed?.[0]?.value||0),label:`${Number(s.nonHeapUsed?.[0]?.value||0).toFixed(1)}%`,color:"bg-blue-500"}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:112:228",className:"text-[10px] text-[var(--dg-text-muted)] mt-1",children:"Non-Heap"})]})}),a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:113:7",className:"bg-[var(--dg-bg-primary)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:113:51",className:"p-3 text-center",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:113:92",className:"text-lg font-bold text-emerald-400",children:s.threadCount?.[0]?.value||0}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:113:180",className:"text-[10px] text-[var(--dg-text-muted)]",children:"Threads"})]})}),a.jsx(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:114:7",className:"bg-[var(--dg-bg-primary)]",children:a.jsxs(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:114:51",className:"p-3 text-center",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:114:92",className:"text-lg font-bold text-amber-400",children:Number(s.gcPause?.[0]?.value||0).toFixed(3)}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:114:193",className:"text-[10px] text-[var(--dg-text-muted)]",children:"GC Pause (s)"})]})})]})},Cs=({dsUrl:s})=>{const[r,e]=o.useState(!1),[c,i]=o.useState(!1),[x,b]=o.useState(0),[g,N]=o.useState(""),[w,m]=o.useState("kubernetes"),[P,y]=o.useState({}),[W,v]=o.useState({}),[h,A]=o.useState({}),[$,F]=o.useState({});o.useEffect(()=>{s&&M(s)},[s]);const M=async p=>{i(!0),N("");try{const f=await oa.post("/prometheus/connect",{url:p});e(!0),b(f.targets||0),I(p)}catch(f){e(!1),N(f.message||"连接失败")}finally{i(!1)}},I=async p=>{for(const f of["kubernetes","node","pod","jvm"])try{const n=await oa.post("/prometheus/dashboard",{url:p,type:f}),l={};for(const[S,j]of Object.entries(n||{}))l[S]=Array.isArray(j)?j:j?.data?.result?ys(j.data.result):j;f==="kubernetes"&&y(l),f==="node"&&v(l),f==="pod"&&A(l),f==="jvm"&&F(l)}catch{}},T=()=>{s&&M(s)};return!r&&!g?null:a.jsxs(z,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:162:5",className:"bg-[var(--dg-bg-secondary)] border-purple-500/20",children:[a.jsx(Ga,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:163:7",className:"py-3 px-4 pb-2",children:a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:164:9",className:"flex items-center gap-2",children:[a.jsx(J,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:165:11",className:"h-4 w-4 text-purple-400"}),a.jsx(wa,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:166:11",className:"text-sm font-medium",children:"Prometheus 监控"}),r&&a.jsxs(E,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:167:25",className:"text-[10px] bg-purple-500/10 text-purple-400",children:[x," targets"]}),r&&a.jsx("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:168:25",className:"ml-auto",children:a.jsxs(D,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:168:50",variant:"ghost",size:"sm",className:"h-6 px-2 text-[10px]",onClick:T,children:[a.jsx(ha,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:168:135",className:"w-3 h-3 mr-1"}),"刷新"]})})]})}),a.jsx(k,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:171:7",className:"px-4 pb-3 pt-0",children:c?a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:172:21",className:"text-center py-12",children:[a.jsx(aa,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:172:56",className:"h-6 w-6 mx-auto mb-2 animate-spin text-purple-400"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:172:129",className:"text-xs text-[var(--dg-text-muted)]",children:"连接中…"})]}):g?a.jsxs("div",{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:173:20",className:"p-3 rounded-lg bg-red-500/10 border border-red-500/20 text-xs text-red-400",children:[a.jsx(Na,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:173:112",className:"h-4 w-4 inline mr-1"}),g]}):a.jsxs(Ba,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:175:11",value:w,onValueChange:m,children:[a.jsxs(Oa,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:176:13",className:"bg-[var(--dg-bg-tertiary)] mb-3",children:[a.jsxs(R,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:177:15",value:"kubernetes",className:"text-xs",children:[a.jsx(Ya,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:177:67",className:"w-3 h-3 mr-1"}),"Kubernetes"]}),a.jsxs(R,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:178:15",value:"node",className:"text-xs",children:[a.jsx(Q,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:178:61",className:"w-3 h-3 mr-1"}),"Node"]}),a.jsxs(R,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:179:15",value:"pod",className:"text-xs",children:[a.jsx(Gs,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:179:60",className:"w-3 h-3 mr-1"}),"Pod"]}),a.jsxs(R,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:180:15",value:"jvm",className:"text-xs",children:[a.jsx(ta,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:180:60",className:"w-3 h-3 mr-1"}),"JVM"]})]}),a.jsx(K,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:182:13",value:"kubernetes",children:a.jsx(ws,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:182:45",d:P})}),a.jsx(K,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:183:13",value:"node",children:a.jsx(Ps,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:183:39",d:W})}),a.jsx(K,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:184:13",value:"pod",children:a.jsx(As,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:184:38",d:h})}),a.jsx(K,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:185:13",value:"jvm",children:a.jsx(Ss,{"code-path":"src/components/monitor/dashboard/PrometheusDashboard.tsx:185:38",d:$})})]})})]})};function zs(){return typeof window<"u"&&window.location?{origin:window.location.origin,backend:`${window.location.protocol}//${window.location.hostname}:8080`}:{origin:"http://127.0.0.1",backend:"http://127.0.0.1:8080"}}function ks({open:s,onOpenChange:r,server:e,onInstalled:c,onFailed:i}){const x=Wa(d=>d.token)||"",{origin:b,backend:g}=zs(),[N,w]=o.useState(!1),[m,P]=o.useState(!1),[y,W]=o.useState(!1),[v,h]=o.useState("auto"),[A,$]=o.useState("root"),[F,M]=o.useState(""),[I,T]=o.useState(""),[p,f]=o.useState("password"),n=e&&!e.has_auth,l=`curl -fsSL ${b}/agent/install.sh | bash -s -- --server ${g} --token ${x}`,S=()=>{const d=document.createElement("textarea");d.value=l,d.style.position="fixed",d.style.top="0",d.style.left="0",d.style.width="2em",d.style.height="2em",d.style.padding="0",d.style.border="none",d.style.outline="none",d.style.boxShadow="none",d.style.background="transparent",d.style.opacity="0",d.style.pointerEvents="none",d.style.zIndex="-1",d.style.fontSize="16px",d.contentEditable="true",d.readOnly=!0,document.body.appendChild(d),d.focus(),d.select(),d.setSelectionRange&&d.setSelectionRange(0,999999);let Z=!1;try{Z=document.execCommand("copy")}catch{}document.body.removeChild(d),Z?(w(!0),u.success("安装命令已复制到剪贴板,粘贴到目标主机执行"),setTimeout(()=>w(!1),3e3)):(u.error("自动复制失败,请在下方手动全选复制 (Ctrl+A → Ctrl+C)"),P(!0))},j=`${b}/agent/aiops-agent-linux-amd64`,ma=[{icon:hs,title:"1. 下载二进制",commands:[`curl -fsSL ${j} -o /usr/local/bin/aiops-agent`]},{icon:as,title:"2. 赋予执行权限",commands:["chmod +x /usr/local/bin/aiops-agent"]},{icon:ka,title:"3. 创建 systemd 服务",commands:["cat > /etc/systemd/system/aiops-agent.service << 'EOF'","[Unit]","Description=AIOps Agent","After=network.target","","[Service]","Type=simple",`ExecStart=/usr/local/bin/aiops-agent --server ${g} --token ${x}`,"Restart=always","RestartSec=5","","[Install]","WantedBy=multi-user.target","EOF"]},{icon:ms,title:"4. 启动并设置开机自启",commands:["systemctl daemon-reload","systemctl enable --now aiops-agent","systemctl status aiops-agent"]}],B=async()=>{if(!(!e||!x)){if(n&&!F&&!I){u.error("请填写 SSH 登录凭据(密码或密钥)");return}W(!0);try{const d=n?{username:A,password:F,ssh_key:I,auth_type:p}:void 0;(await Fa.installAgent(e.id,x,d))?.installed||!1?(u.success(`${e.hostname} Agent 安装成功`),c?.(e.id),r(!1)):(u.warning(`${e.hostname}: Agent 安装命令已执行,但服务未检测到运行`),c?.(e.id),r(!1))}catch(d){const Z=d?.message||"安装失败";u.error(`${e.hostname} ${Z}`),i?.(e.id,Z)}finally{W(!1)}}};return a.jsx(ra,{"code-path":"src/components/agent/AgentWizard.tsx:190:5",open:s,onOpenChange:r,children:a.jsxs(na,{"code-path":"src/components/agent/AgentWizard.tsx:191:7",className:"max-w-2xl bg-slate-900 border-slate-800 text-slate-100",children:[a.jsxs(da,{"code-path":"src/components/agent/AgentWizard.tsx:192:9",children:[a.jsx(ca,{"code-path":"src/components/agent/AgentWizard.tsx:193:11",className:"text-slate-100",children:e?`部署 Agent → ${e.hostname}`:"部署 Agent"}),a.jsx(_a,{"code-path":"src/components/agent/AgentWizard.tsx:196:11",className:"text-slate-400",children:e?`目标主机 ${e.hostname} (${e.ip}),选择安装方式:`:"在目标主机上执行以下命令即可完成 Agent 安装与注册"})]}),a.jsxs(Ba,{"code-path":"src/components/agent/AgentWizard.tsx:204:9",value:v,onValueChange:h,className:"w-full",children:[a.jsxs(Oa,{"code-path":"src/components/agent/AgentWizard.tsx:205:11",className:"bg-slate-800 border border-slate-700",children:[a.jsxs(R,{"code-path":"src/components/agent/AgentWizard.tsx:206:13",value:"auto",className:"data-[state=active]:bg-slate-700",children:[a.jsx(pa,{"code-path":"src/components/agent/AgentWizard.tsx:207:15",className:"h-4 w-4 mr-1.5"}),"安装Agent"]}),e&&a.jsxs(R,{"code-path":"src/components/agent/AgentWizard.tsx:211:15",value:"ssh",className:"data-[state=active]:bg-slate-700",children:[a.jsx(ta,{"code-path":"src/components/agent/AgentWizard.tsx:212:17",className:"h-4 w-4 mr-1.5"}),"SSH一键安装"]}),!e&&a.jsxs(R,{"code-path":"src/components/agent/AgentWizard.tsx:217:15",value:"ssh",className:"data-[state=active]:bg-slate-700 opacity-50 cursor-not-allowed",disabled:!0,children:[a.jsx(ta,{"code-path":"src/components/agent/AgentWizard.tsx:218:17",className:"h-4 w-4 mr-1.5"}),"SSH一键安装"]}),a.jsx(R,{"code-path":"src/components/agent/AgentWizard.tsx:222:13",value:"manual",className:"data-[state=active]:bg-slate-700",children:"手动安装"})]}),a.jsxs(K,{"code-path":"src/components/agent/AgentWizard.tsx:228:11",value:"auto",className:"mt-4 space-y-3",children:[a.jsx("p",{"code-path":"src/components/agent/AgentWizard.tsx:229:13",className:"text-sm text-slate-400",children:"在目标主机执行以下命令,Agent 将自动下载、安装并启动:"}),a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:232:13",className:"relative rounded-lg bg-slate-950 border border-slate-800 p-4",children:[a.jsx("pre",{"code-path":"src/components/agent/AgentWizard.tsx:233:15",className:"text-xs text-emerald-400 font-mono whitespace-pre-wrap break-all pr-10",children:l}),a.jsx(D,{"code-path":"src/components/agent/AgentWizard.tsx:236:15",size:"icon",variant:"ghost",onClick:S,className:"absolute top-2 right-2 h-8 w-8 text-slate-400 hover:text-slate-100 hover:bg-slate-800",title:"复制到剪贴板",children:N?a.jsx(Qa,{"code-path":"src/components/agent/AgentWizard.tsx:243:27",className:"h-4 w-4 text-emerald-400"}):a.jsx(cs,{"code-path":"src/components/agent/AgentWizard.tsx:243:76",className:"h-4 w-4"})})]}),m&&a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:249:15",className:"rounded-lg bg-amber-950/30 border border-amber-800/50 p-4",children:[a.jsx("p",{"code-path":"src/components/agent/AgentWizard.tsx:250:17",className:"text-xs text-amber-400 mb-2",children:"⚠️ 自动复制失败。请点击下方输入框全选 (Ctrl+A) 后复制 (Ctrl+C):"}),a.jsx("textarea",{"code-path":"src/components/agent/AgentWizard.tsx:253:17",readOnly:!0,value:l,className:"w-full h-24 bg-slate-950 border border-amber-800/30 text-emerald-400 font-mono text-xs p-3 rounded resize-none focus:outline-none focus:border-amber-600",onClick:d=>d.target.select()})]}),a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:261:13",className:"flex items-start gap-2 text-xs text-slate-500",children:[a.jsx(pa,{"code-path":"src/components/agent/AgentWizard.tsx:262:15",className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),a.jsxs("span",{"code-path":"src/components/agent/AgentWizard.tsx:263:15",children:["服务器地址已自动检测 — 安装脚本通过 Nginx 代理 (",b,"),Agent 直连后端 (",g,")。安装成功后将自动连接并开始上报指标。"]})]})]}),!e&&a.jsx(K,{"code-path":"src/components/agent/AgentWizard.tsx:271:13",value:"ssh",className:"mt-4 space-y-4",children:a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:272:15",className:"text-center py-12 text-slate-400",children:[a.jsx(Q,{"code-path":"src/components/agent/AgentWizard.tsx:273:17",className:"h-10 w-10 mx-auto mb-3 opacity-50"}),a.jsx("p",{"code-path":"src/components/agent/AgentWizard.tsx:274:17",className:"text-sm font-medium mb-1",children:"未选择目标主机"}),a.jsx("p",{"code-path":"src/components/agent/AgentWizard.tsx:275:17",className:"text-xs",children:"请先在主机列表中勾选一台主机,再点击「安装 Agent」打开此页面"})]})}),e&&a.jsxs(K,{"code-path":"src/components/agent/AgentWizard.tsx:281:13",value:"ssh",className:"mt-4 space-y-4",children:[a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:282:15",className:"rounded-lg bg-slate-950 border border-slate-800 p-4",children:[a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:283:17",className:"flex items-center gap-3 mb-3",children:[a.jsx(Q,{"code-path":"src/components/agent/AgentWizard.tsx:284:19",className:"h-5 w-5 text-blue-400"}),a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:285:19",children:[a.jsx("p",{"code-path":"src/components/agent/AgentWizard.tsx:286:21",className:"text-sm font-medium text-slate-200",children:e.hostname}),a.jsx("code",{"code-path":"src/components/agent/AgentWizard.tsx:287:21",className:"text-xs text-slate-400",children:e.ip})]})]}),n&&a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:293:19",className:"mb-4 p-3 rounded-lg bg-amber-950/30 border border-amber-800/40 space-y-3",children:[a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:294:21",className:"flex items-center gap-2 text-xs text-amber-300/80",children:[a.jsx(Xa,{"code-path":"src/components/agent/AgentWizard.tsx:295:23",className:"h-3.5 w-3.5"}),a.jsx("span",{"code-path":"src/components/agent/AgentWizard.tsx:296:23",children:"该服务器未配置 SSH 凭据,请填写以下信息(首次连接成功后自动保存)"})]}),a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:298:21",className:"grid grid-cols-2 gap-2",children:[a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:299:23",children:[a.jsx(L,{"code-path":"src/components/agent/AgentWizard.tsx:300:25",className:"text-xs text-slate-400",children:"用户名"}),a.jsx(X,{"code-path":"src/components/agent/AgentWizard.tsx:301:25",value:A,onChange:d=>$(d.target.value),placeholder:"root",className:"h-8 text-sm bg-slate-900 border-slate-700 text-slate-200 mt-1"})]}),a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:308:23",className:"flex items-end gap-1",children:[a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:309:25",className:"flex-1",children:[a.jsx(L,{"code-path":"src/components/agent/AgentWizard.tsx:310:27",className:"text-xs text-slate-400",children:"密码"}),a.jsx(X,{"code-path":"src/components/agent/AgentWizard.tsx:311:27",type:"password",value:F,onChange:d=>{M(d.target.value),f("password")},placeholder:"******",className:"h-8 text-sm bg-slate-900 border-slate-700 text-slate-200 mt-1"})]}),a.jsx("span",{"code-path":"src/components/agent/AgentWizard.tsx:319:25",className:"text-xs text-slate-500 px-1 pb-1",children:"或"}),a.jsx(D,{"code-path":"src/components/agent/AgentWizard.tsx:320:25",variant:"ghost",size:"sm",onClick:()=>{f("key"),M("")},className:`text-xs h-7 px-2 ${p==="key"?"text-blue-400":"text-slate-500"}`,children:"密钥"})]})]}),p==="key"&&a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:328:23",children:[a.jsx(L,{"code-path":"src/components/agent/AgentWizard.tsx:329:25",className:"text-xs text-slate-400",children:"SSH 私钥(PEM 格式)"}),a.jsx("textarea",{"code-path":"src/components/agent/AgentWizard.tsx:330:25",value:I,onChange:d=>T(d.target.value),placeholder:`-----BEGIN OPENSSH PRIVATE KEY----- +... +-----END OPENSSH PRIVATE KEY-----`,rows:3,className:"w-full mt-1 bg-slate-900 border border-slate-700 text-slate-200 font-mono text-xs p-2 rounded-md resize-none"})]})]}),a.jsx("p",{"code-path":"src/components/agent/AgentWizard.tsx:342:17",className:"text-sm text-slate-400 mb-4",children:"通过 SSH 远程连接到目标主机,自动下载并安装 Agent,完成后立即启动运行。"}),a.jsx(D,{"code-path":"src/components/agent/AgentWizard.tsx:345:17",onClick:B,disabled:y,className:"w-full bg-blue-600 hover:bg-blue-700 text-white",children:y?a.jsxs(a.Fragment,{children:[a.jsx(aa,{"code-path":"src/components/agent/AgentWizard.tsx:352:23",className:"h-4 w-4 mr-2 animate-spin"}),"SSH 连接中,正在安装..."]}):a.jsxs(a.Fragment,{children:[a.jsx(ta,{"code-path":"src/components/agent/AgentWizard.tsx:357:23",className:"h-4 w-4 mr-2"}),n?"连接并安装 Agent(凭据将自动保存)":"一键安装 Agent"]})})]}),a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:363:15",className:"flex items-start gap-2 text-xs text-slate-500",children:[a.jsx(pa,{"code-path":"src/components/agent/AgentWizard.tsx:364:17",className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),a.jsxs("span",{"code-path":"src/components/agent/AgentWizard.tsx:365:17",children:["系统将通过 SSH 连接 ",e.ip,",执行安装脚本。请确保服务器 SSH 凭据已正确配置(编辑服务器可修改密码/密钥)。"]})]})]}),a.jsxs(K,{"code-path":"src/components/agent/AgentWizard.tsx:373:11",value:"manual",className:"mt-4 space-y-4",children:[a.jsx("div",{"code-path":"src/components/agent/AgentWizard.tsx:374:13",className:"max-h-[420px] overflow-y-auto space-y-3 pr-1",children:ma.map(d=>a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:376:17",className:"rounded-lg bg-slate-950 border border-slate-800 overflow-hidden",children:[a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:377:19",className:"flex items-center gap-2 px-4 py-2.5 bg-slate-800/50",children:[a.jsx(d.icon,{"code-path":"src/components/agent/AgentWizard.tsx:378:21",className:"h-4 w-4 text-blue-400"}),a.jsx("span",{"code-path":"src/components/agent/AgentWizard.tsx:379:21",className:"text-sm font-medium text-slate-200",children:d.title})]}),a.jsx("div",{"code-path":"src/components/agent/AgentWizard.tsx:381:19",className:"p-3 space-y-1",children:d.commands.map((Z,sa)=>a.jsxs("div",{"code-path":"src/components/agent/AgentWizard.tsx:383:23",className:"flex items-start gap-2",children:[a.jsx("span",{"code-path":"src/components/agent/AgentWizard.tsx:384:25",className:"text-slate-600 font-mono text-xs select-none mt-0.5",children:"$"}),a.jsx("code",{"code-path":"src/components/agent/AgentWizard.tsx:385:25",className:"text-xs text-slate-300 font-mono whitespace-pre-wrap break-all flex-1",children:Z})]},sa))})]},d.title))}),a.jsx("p",{"code-path":"src/components/agent/AgentWizard.tsx:394:13",className:"text-xs text-slate-500",children:"完成上述步骤后,Agent 将作为 systemd 服务运行并自动上报指标。"})]})]})]})})}const Ws=[{id:"agent",label:"Agent 主机",icon:a.jsx(Q,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:52:43",className:"w-3.5 h-3.5"})},{id:"zabbix",label:"Zabbix",icon:a.jsx(J,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:53:42",className:"w-3.5 h-3.5"})},{id:"prometheus",label:"Prometheus",icon:a.jsx(J,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:54:50",className:"w-3.5 h-3.5"})},{id:"dashboard",label:"自定义",icon:a.jsx($a,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:55:42",className:"w-3.5 h-3.5"})}],_s=()=>{const s=ss(),r=es(),[e,c]=o.useState([]),[i,x]=o.useState(!0),[b,g]=o.useState("cpu_usage"),[N,w]=o.useState("desc"),[m,P]=o.useState(1),[y,W]=o.useState(10),[v,h]=o.useState(new Set),[A,$]=o.useState(!1),[F,M]=o.useState(null),[I,T]=o.useState(!1),[p,f]=o.useState("install"),[n,l]=o.useState(!1),[S,j]=o.useState(!1),[ma,B]=o.useState(new Set),[d,Z]=o.useState(!1),sa=async()=>{if(await s({title:"批量卸载 Agent",description:`确定卸载选中的 ${ea.length} 台主机的 AIOps Agent?卸载将在后台异步执行。`,confirmText:"卸载",variant:"destructive"})){Z(!0),B(new Set(ea));try{await Aa.batchUninstall(ea),u.success(`已提交:批量卸载 ${ea.length} 台主机的 Agent,后台执行中,30秒后自动刷新`),h(new Set),setTimeout(()=>{q(),B(new Set)},3e4)}catch{u.error("提交失败"),B(new Set)}finally{Z(!1)}}},Pa=Math.max(1,Math.ceil(e.length/y)),q=async()=>{try{c(fs(await oa.get("/agent/latest")))}catch{}finally{x(!1)}};o.useEffect(()=>{q();const t=setInterval(q,3e4);return()=>clearInterval(t)},[]);const La=t=>{b===t?w(C=>C==="asc"?"desc":"asc"):(g(t),w("desc"))},Ra=[...e].sort((t,C)=>{let G=t[b]??"",_=C[b]??"";return b==="agent_status"&&(G=t.agent_status||"",_=C.agent_status||""),typeof G=="number"?N==="asc"?G-_:_-G:N==="asc"?String(G).localeCompare(String(_)):String(_).localeCompare(String(G))}).slice((m-1)*y,m*y),Ka=({f:t})=>b!==t?a.jsx(Ia,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:107:54",className:"w-3 h-3 text-slate-500"}):N==="asc"?a.jsx(Ha,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:107:122",className:"w-3 h-3 text-emerald-400"}):a.jsx(Ua,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:107:173",className:"w-3 h-3 text-emerald-400"}),ia=(t,C)=>a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:109:5",className:"flex items-center gap-2 min-w-[90px]",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:109:59",className:"flex-1 h-2.5 rounded-full bg-[var(--dg-bg-tertiary)] overflow-hidden",children:a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:109:145",className:`h-full rounded-full transition-all duration-500 ${t>=80?"bg-orange-500":"bg-emerald-500"}`,style:{width:`${Math.min(t,100)}%`}})}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:109:310",className:`w-14 text-right text-xs font-mono tabular-nums ${t>=80?"text-orange-400":""}`,children:C})]}),Va=v.size===e.length&&e.length>0,la=v.size>0,ea=[...v].map(Number).filter(t=>!isNaN(t)),Y=o.useMemo(()=>e.filter(t=>v.has(String(t.server_id))),[e,v]),U=o.useMemo(()=>Y.filter(t=>t.agent_status!=="online"),[Y]),H=o.useMemo(()=>Y.filter(t=>t.agent_status==="online"),[Y]),qa=()=>{l(!1),U.length>0&&H.length===0?f("install"):U.length===0&&H.length>0?f("upgrade"):f("install"),T(!0)},Ja=async()=>{if(!n){u.error("请先确认并勾选「我已知悉」");return}j(!0);const t=Wa.getState().token,C=Y.map(G=>G.server_id);B(new Set(C));try{if(p==="install"){if(!t){u.error("未登录");return}const G=U.map(xa=>xa.server_id);if(G.length===0){u.warning("所选主机均已安装 Agent,无需安装");return}const _=await Fa.batchInstallAgent(G,t);u.success(`已提交:批量安装 ${_?.total??G.length} 台主机的 Agent,后台执行中,30秒后自动刷新`),h(new Set),setTimeout(()=>{q(),B(new Set)},3e4)}else{const G=H.map(xa=>xa.server_id);if(G.length===0){u.warning("所选主机中没有在线 Agent,无法升级");return}const _=await Aa.batchUpgrade(G);u.success(_?.message||`已提交:批量升级 ${G.length} 台主机的 Agent,后台执行中,30秒后自动刷新`),h(new Set),setTimeout(()=>{q(),B(new Set)},3e4)}T(!1)}catch{u.error("提交失败"),B(new Set)}finally{j(!1)}};return i?a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:164:23",className:"text-center py-20 text-[var(--dg-text-muted)]",children:[a.jsx(J,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:164:86",className:"h-6 w-6 mx-auto mb-2 animate-spin"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:164:144",className:"text-xs",children:"加载中…"})]}):e.length?a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:167:5",children:[a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:169:7",className:"flex items-center gap-2 mb-3 flex-wrap",children:[la&&a.jsxs("span",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:170:20",className:"text-xs text-[var(--dg-text-secondary)]",children:["已选 ",v.size," 项"]}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:171:9",className:"flex-1"}),a.jsxs(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:172:9",size:"sm",variant:"outline",className:"h-7 text-xs gap-1",onClick:()=>{const t=la?e.find(C=>v.has(String(C.server_id))):null;M(t?{id:t.server_id,hostname:t.hostname,ip:t.ip,has_auth:t.has_auth}:null),$(!0)},children:[a.jsx(ts,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:177:11",className:"w-3 h-3"}),"安装 Agent"]}),la&&a.jsxs(a.Fragment,{children:[a.jsxs(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:181:13",size:"sm",variant:"outline",className:"h-7 text-xs gap-1 border-blue-500/30 text-blue-400 hover:bg-blue-500/10",onClick:qa,children:[a.jsx(Sa,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:182:15",className:"w-3 h-3"}),"批量部署 (",v.size,")"]}),a.jsxs(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:184:13",size:"sm",variant:"outline",className:"h-7 text-xs gap-1 border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:sa,disabled:d,children:[a.jsx(xs,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:185:15",className:"w-3 h-3"}),"批量卸载 (",v.size,")"]})]}),a.jsxs(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:189:9",size:"sm",variant:"ghost",className:"h-7 text-xs gap-1",onClick:q,children:[a.jsx(ha,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:189:89",className:"w-3 h-3"}),"刷新"]})]}),a.jsx(ks,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:192:7",open:A,onOpenChange:$,server:F,onInstalled:()=>{u.success("Agent 安装成功"),$(!1),q()},onFailed:()=>u.error("安装失败")}),a.jsx(ra,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:197:7",open:I,onOpenChange:t=>{t||(T(!1),l(!1))},children:a.jsxs(na,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:198:9",className:"max-w-2xl max-h-[85vh] overflow-auto bg-slate-900 border-slate-700 text-slate-100",children:[a.jsxs(da,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:199:11",children:[a.jsxs(ca,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:200:13",className:"flex items-center gap-2 text-base",children:[a.jsx(Sa,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:201:15",className:"w-5 h-5 text-blue-400"}),"批量部署 Agent"]}),a.jsxs(_a,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:204:13",className:"text-slate-400 text-xs",children:["选中 ",Y.length," 台主机(需安装: ",U.length,",待升级: ",H.length,")"]})]}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:209:11",className:"space-y-4",children:[a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:211:13",className:"flex items-center gap-2 p-1 rounded-lg bg-slate-800 border border-slate-700 w-fit",children:["install","upgrade"].map(t=>a.jsx("button",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:213:17",disabled:t==="install"?U.length===0:H.length===0,onClick:()=>f(t),className:`px-4 py-1.5 rounded text-xs font-medium transition-colors disabled:opacity-30 disabled:cursor-not-allowed ${p===t?"bg-blue-600 text-white shadow-sm":"text-slate-400 hover:text-slate-200"}`,children:t==="install"?`⚡ 安装 (${U.length})`:`🔄 升级到最新版 (${H.length})`},t))}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:227:13",className:"rounded-md border border-slate-700 overflow-hidden",children:a.jsxs("table",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:228:15",className:"w-full text-xs",children:[a.jsx("thead",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:229:17",className:"bg-slate-800",children:a.jsxs("tr",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:230:19",children:[a.jsx("th",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:231:21",className:"px-3 py-2 text-left font-medium text-slate-400",children:"主机名"}),a.jsx("th",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:232:21",className:"px-3 py-2 text-left font-medium text-slate-400",children:"IP"}),a.jsx("th",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:233:21",className:"px-3 py-2 text-left font-medium text-slate-400",children:"状态"}),a.jsx("th",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:234:21",className:"px-3 py-2 text-left font-medium text-slate-400",children:"当前版本"}),a.jsx("th",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:235:21",className:"px-3 py-2 text-left font-medium text-slate-400",children:"操作"})]})}),a.jsx("tbody",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:238:17",children:(p==="install"?U:H).map(t=>a.jsxs("tr",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:240:21",className:"border-t border-slate-800 hover:bg-slate-800/50",children:[a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:241:23",className:"px-3 py-2 font-medium text-slate-200",children:t.hostname}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:242:23",className:"px-3 py-2 font-mono text-slate-400",children:t.ip}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:243:23",className:"px-3 py-2",children:t.agent_status==="online"?a.jsx(E,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:245:29",className:"text-[10px] bg-emerald-500/20 text-emerald-400",children:"在线"}):a.jsx(E,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:246:29",className:"text-[10px] bg-slate-500/20 text-slate-400",children:t.agent_status==="not_installed"?"未安装":t.agent_status||"离线"})}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:250:23",className:"px-3 py-2 font-mono text-slate-400",children:t.agent_version||"—"}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:251:23",className:"px-3 py-2",children:a.jsx("span",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:252:25",className:"text-blue-400 text-[11px]",children:p==="install"?"即将安装":"即将升级"})})]},t.server_id))})]})}),a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:263:13",className:"rounded-md border border-amber-500/30 bg-amber-500/5 p-3 space-y-2",children:a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:264:15",className:"flex items-start gap-2",children:[a.jsx(os,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:265:17",className:"w-4 h-4 text-amber-400 mt-0.5 shrink-0"}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:266:17",children:[a.jsxs("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:267:19",className:"text-xs font-medium text-amber-300 mb-1",children:[p==="install"?"本次安装":"本次升级",",主机监控探针将部署 AIOps Agent。AIOps Agent 是 AIOps 平台推出的新一代数据采集器,提供主机监控指标采集和可观测数据采集能力。"]}),a.jsxs("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:270:19",className:"text-[11px] text-amber-400/80 leading-relaxed",children:[p==="upgrade"&&"升级前请注意以下事项:",p==="install"&&"安装前请注意以下事项:"]}),a.jsxs("ul",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:274:19",className:"mt-1 space-y-0.5 text-[11px] text-slate-400 list-disc list-inside",children:[p==="upgrade"&&a.jsxs(a.Fragment,{children:[a.jsx("li",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:277:25",children:"如果您的机器已经安装旧版 Agent,升级操作将停止旧版并替换为最新版本。"}),a.jsx("li",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:278:25",children:"如果您的机器之前安装过 Agent 但已卸载,遗留有相关采集配置,本次升级可能导致配置重新生效。升级前请确保存量废弃配置已经移除。"}),a.jsx("li",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:279:25",children:"如果您的机器采用自定义安装的 Agent(非 AIOps 提供的一键安装脚本),请不要直接使用批量升级。"}),a.jsx("li",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:280:25",children:"批量升级前,请务必先单机灰度升级,确保升级成功且不影响业务后再操作。"})]}),p==="install"&&a.jsxs(a.Fragment,{children:[a.jsx("li",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:285:25",children:"安装将自动检测目标主机架构(amd64/arm64),下载对应版本的 Agent 二进制并启动服务。"}),a.jsx("li",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:286:25",children:"请确保目标主机的 SSH 端口(默认 22)可访问,且已关联有效的 SSH 凭据。"}),a.jsx("li",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:287:25",children:"安装过程约 30-60 秒,期间目标主机 CPU 负载会短暂升高。"}),a.jsx("li",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:288:25",children:"若安装失败,请检查目标主机的防火墙规则和 SSH 服务状态后重试。"})]}),a.jsx("li",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:291:21",children:"操作不可回滚,请在操作前确认已备份关键配置。"}),a.jsx("li",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:292:21",children:"操作将在后台异步执行,您可以在「任务执行记录」中查看详细进度。"})]})]})]})}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:299:13",className:"flex items-center gap-2",children:[a.jsx(Da,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:300:15",id:"batch-ack",checked:n,onCheckedChange:t=>l(!!t)}),a.jsx("label",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:301:15",htmlFor:"batch-ack",className:"text-xs text-slate-300 cursor-pointer select-none",children:"我已知悉以上风险和注意事项"})]})]}),a.jsxs(va,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:305:11",className:"gap-2",children:[a.jsx(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:306:13",variant:"outline",className:"border-slate-700 text-slate-300 h-8 text-xs",onClick:()=>{T(!1),l(!1)},children:"取消"}),a.jsxs(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:309:13",className:"bg-blue-600 hover:bg-blue-700 text-white h-8 text-xs gap-1",disabled:S||!n||(p==="install"?U.length===0:H.length===0),onClick:Ja,children:[S&&a.jsx(aa,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:314:35",className:"w-3 h-3 animate-spin"}),p==="install"?"确认安装":"确认升级"]})]})]})}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:321:7",className:"overflow-x-auto rounded-lg border border-[var(--dg-border)]",children:[a.jsxs("table",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:322:9",className:"w-full text-xs",children:[a.jsx("thead",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:323:11",className:"bg-[var(--dg-bg-tertiary)] border-b",children:a.jsxs("tr",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:323:66",children:[a.jsx("th",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:324:13",className:"px-2 py-2 w-8",children:a.jsx(Da,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:325:15",checked:Va,onCheckedChange:t=>h(t?new Set(e.map(C=>String(C.server_id))):new Set)})}),["hostname","agent_version","agent_status","cpu_usage","mem_usage","disk_usage","region","ip"].map(t=>a.jsx("th",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:328:15",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] cursor-pointer hover:text-[var(--dg-text-primary)] select-none whitespace-nowrap",onClick:()=>La(t),children:a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:329:17",className:"flex items-center gap-1",children:[{hostname:"主机名",agent_version:"Agent版本",agent_status:"状态",cpu_usage:"CPU",mem_usage:"内存",disk_usage:"磁盘",region:"区域",ip:"IP"}[t],a.jsx(Ka,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:329:188",f:t})]})},t)),a.jsx("th",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:332:13",className:"px-3 py-2 text-left font-medium text-[var(--dg-text-secondary)] whitespace-nowrap",children:"操作"})]})}),a.jsx("tbody",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:333:11",children:Ra.map((t,C)=>a.jsxs("tr",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:335:15",className:"border-b border-[var(--dg-border)] last:border-0 hover:bg-[var(--dg-bg-tertiary)]/50",children:[a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:336:17",className:"px-2 py-2.5",children:a.jsx(Da,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:337:19",checked:v.has(String(t.server_id)),onCheckedChange:G=>{const _=new Set(v);G?_.add(String(t.server_id)):_.delete(String(t.server_id)),h(_)}})}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:343:17",className:"px-3 py-2.5 font-medium text-[var(--dg-text-primary)]",children:t.hostname}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:344:17",className:"px-3 py-2.5 font-mono text-[var(--dg-text-secondary)]",children:ma.has(t.server_id)?a.jsxs("span",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:346:21",className:"inline-flex items-center gap-1 text-blue-400",children:[a.jsx(aa,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:347:23",className:"w-3 h-3 animate-spin"}),a.jsx("span",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:348:23",className:"text-[10px]",children:"部署中"})]}):t.agent_version||"—"}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:354:17",className:"px-3 py-2.5",children:t.agent_status==="online"?a.jsxs(E,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:354:72",className:"text-[10px] bg-emerald-500/20 text-emerald-400",children:[a.jsx(Ma,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:354:138",className:"w-3 h-3 mr-1"}),"在线"]}):t.agent_status==="not_installed"?a.jsx(E,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:354:214",className:"text-[10px] bg-amber-500/20 text-amber-400",children:"未安装"}):a.jsxs(E,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:354:288",className:"text-[10px] bg-slate-500/10 text-slate-400",children:[a.jsx(gs,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:354:350",className:"w-3 h-3 mr-1"}),"离线"]})}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:355:17",className:"px-3 py-2.5",children:ia(Number(t.cpu_usage||0),`${Number(t.cpu_usage||0).toFixed(1)}%`)}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:356:17",className:"px-3 py-2.5",children:ia(Number(t.mem_usage||0),`${Number(t.mem_usage||0).toFixed(1)}%`)}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:357:17",className:"px-3 py-2.5",children:ia(Number(t.disk_usage||0),`${Number(t.disk_usage||0).toFixed(1)}%`)}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:358:17",className:"px-3 py-2.5 text-[var(--dg-text-secondary)]",children:t.region||"—"}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:359:17",className:"px-3 py-2.5 font-mono text-[var(--dg-text-secondary)]",children:t.ip||"—"}),a.jsx("td",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:360:17",className:"px-3 py-2.5",children:a.jsxs(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:361:19",variant:"ghost",size:"sm",className:"h-7 text-xs text-blue-400 hover:text-blue-300 hover:bg-blue-500/10 px-2",onClick:()=>r(`/host-monitor?host=${encodeURIComponent(t.hostname)}`),children:[a.jsx(Za,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:363:21",className:"w-3.5 h-3.5 mr-1"}),"图表"]})})]},t.hostname+C))})]}),e.length>y&&a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:371:11",className:"flex items-center justify-between px-3 py-2 bg-[var(--dg-bg-tertiary)] border-t border-[var(--dg-border)] text-xs",children:[a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:372:13",className:"flex items-center gap-2 text-[var(--dg-text-muted)]",children:[a.jsxs("span",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:373:15",children:["共 ",e.length," 条"]}),a.jsxs("select",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:374:15",className:"bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] rounded px-2 py-0.5 text-xs",value:y,onChange:t=>{W(Number(t.target.value)),P(1)},children:[a.jsx("option",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:375:17",value:10,children:"10/页"}),a.jsx("option",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:376:17",value:20,children:"20/页"}),a.jsx("option",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:377:17",value:30,children:"30/页"})]})]}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:380:13",className:"flex items-center gap-1",children:[a.jsx("button",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:381:15",className:"px-2 py-0.5 rounded hover:bg-[var(--dg-bg-primary)] disabled:opacity-30",disabled:m<=1,onClick:()=>P(t=>t-1),children:"上一页"}),a.jsxs("span",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:382:15",className:"px-2 text-[var(--dg-text-primary)]",children:[m," / ",Pa]}),a.jsx("button",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:383:15",className:"px-2 py-0.5 rounded hover:bg-[var(--dg-bg-primary)] disabled:opacity-30",disabled:m>=Pa,onClick:()=>P(t=>t+1),children:"下一页"})]})]})]})]}):a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:165:29",className:"text-center py-20 text-[var(--dg-text-muted)]",children:[a.jsx(Q,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:165:92",className:"h-8 w-8 mx-auto mb-2"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:165:135",className:"text-sm",children:"暂无服务器资产"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:165:169",className:"text-xs mt-1",children:"请先在「服务器管理」中添加主机,然后在此安装 Agent"})]})},$s=()=>{const[s,r]=o.useState(null),[e,c]=o.useState(!0);return o.useEffect(()=>{rs.list().then(i=>{const x=i?.data||i||[];r(x.find(b=>b.is_default)||x[0]||null)}).catch(()=>{}).finally(()=>c(!1))},[]),e?a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:402:23",className:"text-center py-20 text-[var(--dg-text-muted)]",children:[a.jsx(J,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:402:86",className:"h-6 w-6 mx-auto mb-2 animate-spin"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:402:144",className:"text-xs",children:"加载数据源…"})]}):s?a.jsx(Ns,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:404:10",dsUrl:s.url,dsUsername:s.username,dsPassword:s.password}):a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:403:19",className:"text-center py-20 text-[var(--dg-text-muted)]",children:[a.jsx(Ta,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:403:82",className:"h-8 w-8 mx-auto mb-2"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:403:127",className:"text-sm",children:"未配置 Zabbix 数据源"}),a.jsxs("a",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:403:168",href:"/datasources",className:"text-xs text-blue-400 hover:underline inline-flex items-center gap-1",children:["前往配置 ",a.jsx(Ea,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:403:277",className:"w-3 h-3"})]})]})},Zs=()=>{const[s,r]=o.useState(null),[e,c]=o.useState(!0);return o.useEffect(()=>{ns.list().then(i=>{const x=i?.data||i||[];r(x.find(b=>b.is_default)||x[0]||null)}).catch(()=>{}).finally(()=>c(!1))},[]),e?a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:416:23",className:"text-center py-20 text-[var(--dg-text-muted)]",children:[a.jsx(J,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:416:86",className:"h-6 w-6 mx-auto mb-2 animate-spin"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:416:144",className:"text-xs",children:"加载数据源…"})]}):s?a.jsx(Cs,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:418:10",dsUrl:s.url}):a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:417:19",className:"text-center py-20 text-[var(--dg-text-muted)]",children:[a.jsx(Ta,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:417:82",className:"h-8 w-8 mx-auto mb-2"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:417:127",className:"text-sm",children:"未配置 Prometheus 数据源"}),a.jsxs("a",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:417:172",href:"/datasources",className:"text-xs text-blue-400 hover:underline inline-flex items-center gap-1",children:["前往配置 ",a.jsx(Ea,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:417:281",className:"w-3 h-3"})]})]})},Ts=()=>{const[s,r]=o.useState([]),[e,c]=o.useState(null),[i,x]=o.useState(!1),[b,g]=o.useState(!1),[N,w]=o.useState({name:"",description:"",datasource:"prometheus",datasourceUrl:""}),[m,P]=o.useState({title:"",type:"graph",query:"",width:6,height:4}),y=async()=>{try{const A=(await ja.getDashboards()).data||[];r(A),A.length>0&&!e&&c(A[0])}catch{}};o.useEffect(()=>{y()},[]);const W=async()=>{if(!N.name){u.error("请输入名称");return}try{await ja.createDashboard({...N,panels:[]}),u.success("创建成功"),x(!1),w({name:"",description:"",datasource:"prometheus",datasourceUrl:""}),y()}catch{u.error("创建失败")}},v=async()=>{if(!(!m.title||!m.query||!e))try{const h={id:Date.now().toString(),...m,datasource:e.datasource,x:0,y:0,options:{legend:!0,tooltip:!0,refreshInterval:30}};await ja.updateDashboard(e.id,{...e,panels:[...e.panels,h]}),u.success("面板添加成功"),g(!1),P({title:"",type:"graph",query:"",width:6,height:4}),y()}catch{u.error("添加失败")}};return a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:452:5",className:"space-y-4",children:[a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:453:7",className:"flex items-center gap-2",children:[a.jsxs(ba,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:454:9",value:e?.id,onValueChange:h=>{const A=s.find($=>$.id===h);A&&c(A)},children:[a.jsx(ua,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:455:11",className:"w-[240px] h-8 text-xs",children:a.jsx(ga,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:455:60",placeholder:"选择仪表盘"})}),a.jsx(fa,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:456:11",children:s.map(h=>a.jsxs(O,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:456:47",value:h.id,children:[h.name,h.isDefault?" (默认)":""]},h.id))})]}),a.jsxs(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:458:9",variant:"outline",size:"sm",className:"h-8 text-[10px]",onClick:y,children:[a.jsx(ha,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:458:89",className:"w-3 h-3 mr-1"}),"刷新"]}),e&&a.jsxs(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:459:20",variant:"outline",size:"sm",className:"h-8 text-[10px]",onClick:()=>g(!0),children:[a.jsx(Ca,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:459:117",className:"w-3 h-3 mr-1"}),"添加面板"]}),a.jsxs(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:460:9",variant:"outline",size:"sm",className:"h-8 text-[10px]",onClick:()=>x(!0),children:[a.jsx(Ca,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:460:109",className:"w-3 h-3 mr-1"}),"新建"]})]}),e?e.panels.length===0?a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:465:11",className:"text-center py-16 text-[var(--dg-text-muted)]",children:[a.jsx(Za,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:465:74",className:"w-10 h-10 mx-auto mb-2 opacity-50"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:465:133",className:"text-xs",children:"暂无面板"})]}):a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:467:11",className:"grid grid-cols-12 gap-3",children:e.panels.map(h=>a.jsxs(z,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:469:15",style:{gridColumn:`span ${h.width}`,minHeight:`${h.height*80}px`},children:[a.jsx(Ga,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:470:17",className:"py-2 px-3",children:a.jsx(wa,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:470:51",className:"text-[11px] font-medium",children:h.title})}),a.jsx(k,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:471:17",className:"p-3 pt-0",children:a.jsx(Ds,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:471:51",panel:h})})]},h.id))}):a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:477:9",className:"text-center py-16 text-[var(--dg-text-muted)]",children:[a.jsx($a,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:477:72",className:"w-10 h-10 mx-auto mb-2 opacity-50"}),a.jsx("p",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:477:129",className:"text-xs",children:"暂无仪表盘"})]}),a.jsx(ra,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:480:7",open:i,onOpenChange:x,children:a.jsxs(na,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:480:62",children:[a.jsx(da,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:480:77",children:a.jsx(ca,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:480:91",children:"新建仪表盘"})}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:481:9",className:"space-y-3",children:[a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:481:36",children:[a.jsx(L,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:481:41",children:"名称"}),a.jsx(X,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:481:58",value:N.name,onChange:h=>w({...N,name:h.target.value})})]}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:482:11",children:[a.jsx(L,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:482:16",children:"数据源"}),a.jsxs(ba,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:482:34",value:N.datasource,onValueChange:h=>w({...N,datasource:h}),children:[a.jsx(ua,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:482:124",children:a.jsx(ga,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:482:139"})}),a.jsxs(fa,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:482:170",children:[a.jsx(O,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:482:185",value:"prometheus",children:"Prometheus"}),a.jsx(O,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:482:239",value:"zabbix",children:"Zabbix"}),a.jsx(O,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:482:285",value:"skywalking",children:"SkyWalking"}),a.jsx(O,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:482:339",value:"custom",children:"自定义"})]})]})]})]}),a.jsxs(va,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:483:9",children:[a.jsx(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:483:23",variant:"outline",onClick:()=>x(!1),children:"取消"}),a.jsx(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:483:97",onClick:W,children:"创建"})]})]})}),a.jsx(ra,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:485:7",open:b,onOpenChange:g,children:a.jsxs(na,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:485:56",children:[a.jsx(da,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:485:71",children:a.jsx(ca,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:485:85",children:"添加面板"})}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:486:9",className:"space-y-3",children:[a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:486:36",children:[a.jsx(L,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:486:41",children:"标题"}),a.jsx(X,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:486:58",value:m.title,onChange:h=>P({...m,title:h.target.value})})]}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:487:11",children:[a.jsx(L,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:487:16",children:"类型"}),a.jsxs(ba,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:487:33",value:m.type,onValueChange:h=>P({...m,type:h}),children:[a.jsx(ua,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:487:111",children:a.jsx(ga,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:487:126"})}),a.jsxs(fa,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:487:157",children:[a.jsx(O,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:487:172",value:"graph",children:"折线图"}),a.jsx(O,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:487:214",value:"stat",children:"数值"}),a.jsx(O,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:487:254",value:"gauge",children:"仪表盘"}),a.jsx(O,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:487:296",value:"table",children:"表格"})]})]})]}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:488:11",children:[a.jsx(L,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:488:16",children:"查询"}),a.jsx(X,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:488:33",value:m.query,onChange:h=>P({...m,query:h.target.value})})]})]}),a.jsxs(va,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:489:9",children:[a.jsx(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:489:23",variant:"outline",onClick:()=>g(!1),children:"取消"}),a.jsx(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:489:94",onClick:v,children:"添加"})]})]})})]})},he=()=>{const[s,r]=o.useState("agent"),[e,c]=o.useState(!1);return a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:500:5",className:`space-y-4 ${e?"fixed inset-0 z-50 bg-background p-4 overflow-auto":""}`,children:[a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:503:7",className:"flex items-center gap-1 p-1 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]",children:[Ws.map(i=>a.jsxs("button",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:505:11",onClick:()=>r(i.id),className:`flex items-center gap-1.5 px-4 py-2 rounded-md text-xs font-medium transition-colors ${s===i.id?"bg-[var(--dg-bg-primary)] text-[var(--dg-text-primary)] shadow-sm":"text-[var(--dg-text-muted)] hover:text-[var(--dg-text-secondary)]"}`,children:[i.icon,i.label]},i.id)),a.jsx("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:518:9",className:"ml-auto",children:a.jsx(D,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:519:11",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>c(!e),children:e?a.jsx(is,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:520:27",className:"w-3.5 h-3.5"}):a.jsx(ls,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:520:67",className:"w-3.5 h-3.5"})})})]}),a.jsxs("div",{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:526:7",className:"min-h-[50vh]",children:[s==="agent"&&a.jsx(_s,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:527:29"}),s==="zabbix"&&a.jsx($s,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:528:30"}),s==="prometheus"&&a.jsx(Zs,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:529:34"}),s==="dashboard"&&a.jsx(Ts,{"code-path":"src/components/monitor/dashboard/GrafanaDashboard.tsx:530:33"})]})]})};export{he as default}; diff --git a/backend/static/assets/HostMonitor-C63FMElJ.js b/backend/static/assets/HostMonitor-C63FMElJ.js new file mode 100644 index 0000000..a227469 --- /dev/null +++ b/backend/static/assets/HostMonitor-C63FMElJ.js @@ -0,0 +1 @@ +import{g as os,ap as gs,r as n,j as t,L as ms,q as Y,B as A,aq as us,N as dt,w as bs,o as Ms,x as at,A as Wt,a3 as Hs,D as Kt,b as qt,c as Ut,d as Vt,e as Xt,f as Jt}from"./index-DfyorCky.js";import{a as R}from"./agent-DqqIRCQX.js";import{C,a as S}from"./card-C55cvSHg.js";import{S as Qt,a as Yt,b as Zt,c as ts,d as rt}from"./select-D5qUzdAs.js";import{T as js,a as vs,b as fs,c as G}from"./tabs-CIh_yD4s.js";import{B as Z}from"./badge-xNW8x0G1.js";import{H as W}from"./hard-drive-BbPmnARR.js";import{D as mt}from"./disc-EsE6x5Oh.js";import{C as ut}from"./circle-x-DK79Dhg2.js";import{R as Mt,C as Ht,X as jt,Y as vt,T as ft,q as as}from"./generateCategoricalChart-6v9BPbG2.js";import{A as Nt,a as nt}from"./AreaChart-B2zlWfdX.js";import{R as ss}from"./refresh-cw-DUB_tAG-.js";import{P as Ns}from"./plus-CUG-9kpu.js";import{S as _s}from"./square-pen-BxUFAe0F.js";import{T as ys}from"./trash-2-Dx32pOzT.js";import"./index-CWVNW_qu.js";const ws=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5",key:"mvr1a0"}],["path",{d:"M3.22 13H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27",key:"auskq0"}]],ks=os("heart-pulse",ws);const Cs=[["path",{d:"M3 5h.01",key:"18ugdj"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 19h.01",key:"noohij"}],["path",{d:"M8 5h13",key:"1pao27"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 19h13",key:"m83p4d"}]],es=os("list",Cs),bt=[{label:"1小时",hours:1,window:60,buckets:60},{label:"6小时",hours:6,window:300,buckets:72},{label:"12小时",hours:12,window:600,buckets:72},{label:"1天",hours:24,window:1800,buckets:96},{label:"3天",hours:72,window:3600,buckets:72},{label:"7天",hours:168,window:10800,buckets:56},{label:"14天",hours:336,window:21600,buckets:48}];function u(r,T,O){if(!r||r.length===0)return[];const F=Math.max(1,Math.ceil(r.length/O)),d=[];for(let j=0;jit+K,0)/y.length,f=Math.max(...y),z=Math.min(...y),i=w[Math.floor(w.length/2)]||0;d.push({time:new Date(i*1e3).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"}),timestamp:i,avg:Number(v.toFixed(2)),max:Number(f.toFixed(2)),min:Number(z.toFixed(2)),count:y.length})}return d.slice(-O)}function M(r){if(!r)return{};if(typeof r=="object")return r;try{return JSON.parse(r)}catch{return{}}}function ct(r){return r>=1024*1024*1024?`${(r/1024/1024/1024).toFixed(1)} GB/s`:r>=1024*1024?`${(r/1024/1024).toFixed(1)} MB/s`:r>=1024?`${(r/1024).toFixed(1)} KB/s`:`${r.toFixed(1)} B/s`}function qs(){const[r]=gs(),T=r.get("host")||"",[O,F]=n.useState([]),[d,j]=n.useState(T),[y,w]=n.useState(!0),[P,v]=n.useState("basic"),[f,z]=n.useState(1),[i,it]=n.useState("avg"),[K,_t]=n.useState([]),[o,yt]=n.useState(null),[b,rs]=n.useState(null),[wt,tt]=n.useState([]),[cs,q]=n.useState(!1),[U,kt]=n.useState(null),[a,N]=n.useState({name:"",hostname:"",probe_type:"http_get",http_url:"",http_method:"GET",http_expect_code:200,http_expect_body:"",tcp_host:"",tcp_port:3306,exec_command:"",timeout:10,interval:60,description:""}),V=n.useCallback(()=>{d&&R.getHealthProbes({hostname:d}).then(s=>{Array.isArray(s)?tt(s):s?.list?tt(s.list):tt([])}).catch(()=>tt([]))},[d]),[k,xt]=n.useState("whitelist"),[X,Ct]=n.useState([]),[ds,st]=n.useState(!1),[St,Tt]=n.useState(!1),pt=n.useCallback(()=>{d&&R.getPortPolicy(d).then(s=>{s?.data&&(xt(s.data.port_filter_mode||"blacklist"),Ct(s.data.port_whitelist||[]))}).catch(()=>{})},[d]);n.useEffect(()=>{pt()},[pt]);const ns=async()=>{if(d){Tt(!0);try{await R.savePortPolicy(d,{port_filter_mode:k,port_whitelist:X}),st(!1)}catch{}finally{Tt(!1)}}};n.useEffect(()=>{V()},[V]);const h=bt.find(s=>s.hours===f)||bt[0];n.useEffect(()=>{R.getLatest().then(s=>{const e=Array.isArray(s)?s:s?.data||s?.list||[];if(F(e),e.length>0&&!d){const l=T?e.find(E=>E.hostname===T):null;j(l?.hostname||e[0]?.hostname||"")}const c=e.find(l=>l.hostname===(d||T));c&&(yt(c),rs(c))}).catch(()=>{}).finally(()=>w(!1))},[d]),n.useEffect(()=>{d&&R.getHistory(d,f).then(s=>{const e=Array.isArray(s)?s:s?.data||s?.list||[];if(_t(e),e.length>0){const c=e[e.length-1];yt(l=>({...l,...c}))}}).catch(()=>_t([])).finally(()=>w(!1))},[d,f]);const g=n.useMemo(()=>{const s=[],e=[],c=[],l=[],E=[],et=[],B=[],$t=[],At=[],Ft=[],It=[],Dt=[],Et=[],Bt=[],Ot=[],Rt=[],zt=[],Gt=[],Lt=[],ht=[],m=[];for(const x of K){const is=x.report_time?new Date(x.report_time).getTime()/1e3:x.created_at?new Date(x.created_at).getTime()/1e3:0;m.push(is),s.push(x.cpu_usage||0),Bt.push(x.cpu_iowait||0),e.push(x.mem_usage||0),Ot.push(x.mem_available||0),c.push(x.load1||0),l.push(x.disk_usage||0);const ot=M(x.disk_info);if(Array.isArray(ot)&&ot.length>0){const ls=ot.find(hs=>hs.mount==="/")||ot[0];ht.push(ls?.inode_usage_pct||0)}else ht.push(0);const $=M(x.net_info);E.push($.tcp_established||0),et.push($.tcp_time_wait||0),B.push($.tcp_close_wait||0),zt.push(($.tcp_established||0)+($.tcp_time_wait||0)+($.tcp_close_wait||0)),$t.push($.net_rx_bps||0),At.push($.net_tx_bps||0),Gt.push($.net_rx_errors||0),Lt.push($.net_tx_errors||0);const gt=M(x.disk_io_info);Ft.push(gt.read_bps||0),It.push(gt.write_bps||0),Rt.push(gt.util||0);const xs=M(x.swap_info);Dt.push(xs?.usage_percent||0);const ps=M(x.fd_info);Et.push(ps?.usage_pct||0)}return{cpu:u(s,m,h.buckets),mem:u(e,m,h.buckets),load1:u(c,m,h.buckets),disk:u(l,m,h.buckets),tcpEst:u(E,m,h.buckets),tcpTW:u(et,m,h.buckets),tcpCW:u(B,m,h.buckets),rx:u($t.map(x=>x/1024),m,h.buckets),tx:u(At.map(x=>x/1024),m,h.buckets),ioRead:u(Ft.map(x=>x/1024),m,h.buckets),ioWrite:u(It.map(x=>x/1024),m,h.buckets),swap:u(Dt,m,h.buckets),fd:u(Et,m,h.buckets),iowait:u(Bt,m,h.buckets),memAvail:u(Ot,m,h.buckets),ioUtil:u(Rt,m,h.buckets),connTotal:u(zt,m,h.buckets),rxErr:u(Gt,m,h.buckets),txErr:u(Lt,m,h.buckets),inode:u(ht,m,h.buckets)}},[K,h]),p=M(o?.net_info),J=Array.isArray(o?.port_info)?o.port_info:Array.isArray(M(o?.port_info))?M(o?.port_info):[],L=M(o?.disk_io_info),Pt=M(o?.swap_info),lt=Array.isArray(M(o?.process_top_info))?M(o?.process_top_info):[],I=M(o?.fd_info),_=M(o?.cs_info),Q=M(o?.heartbeat_info),D=(s,e="--")=>o?s==="cpu"?o.cpu_usage!=null?`${o.cpu_usage.toFixed(1)}%`:e:s==="mem"?o.mem_usage!=null?`${o.mem_usage.toFixed(1)}%`:e:s==="disk"?o.disk_usage!=null?`${o.disk_usage.toFixed(1)}%`:e:s==="load1"?o.load1!=null?String(o.load1):e:s==="tcp"?p.tcp_established!=null?String(p.tcp_established):e:s==="tw"?p.tcp_time_wait!=null?String(p.tcp_time_wait):e:s==="rx"?p.net_rx_bps!=null?`${(p.net_rx_bps/1024).toFixed(1)} KB/s`:e:s==="tx"?p.net_tx_bps!=null?`${(p.net_tx_bps/1024).toFixed(1)} KB/s`:e:s==="ioR"?L.read_bps!=null?`${ct(L.read_bps)}`:e:s==="ioW"?L.write_bps!=null?`${ct(L.write_bps)}`:e:s==="swap"?Pt?.usage_percent!=null?`${Pt.usage_percent.toFixed(1)}%`:e:s==="fd"&&I?.usage_pct!=null?`${I.usage_pct.toFixed(1)}%`:e:e;return y&&!K.length?t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:278:12",className:"flex items-center justify-center h-64",children:t.jsx(ms,{"code-path":"src/pages/HostMonitor.tsx:278:67",className:"h-8 w-8 animate-spin text-slate-500"})}):t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:282:5",className:"space-y-3",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:284:7",className:"flex items-center justify-between flex-wrap gap-2",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:285:9",className:"flex items-center gap-2",children:[t.jsx(Y,{"code-path":"src/pages/HostMonitor.tsx:286:11",className:"h-4 w-4 text-blue-400"}),t.jsxs(Qt,{"code-path":"src/pages/HostMonitor.tsx:287:11",value:d,onValueChange:j,children:[t.jsx(Yt,{"code-path":"src/pages/HostMonitor.tsx:288:13",className:"w-52 h-8 text-xs bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsx(Zt,{"code-path":"src/pages/HostMonitor.tsx:289:15",placeholder:"选择主机..."})}),t.jsx(ts,{"code-path":"src/pages/HostMonitor.tsx:291:13",className:"bg-slate-800 border-slate-700 text-slate-200",children:O.map(s=>t.jsx(rt,{"code-path":"src/pages/HostMonitor.tsx:293:17",value:s.hostname,children:s.hostname},s.hostname))})]}),b&&t.jsxs("span",{"code-path":"src/pages/HostMonitor.tsx:298:13",className:"text-xs text-[var(--dg-text-muted)] ml-2",children:[b.os||"",b.cpu_cores?` | ${b.cpu_cores} 核`:"",b.mem_total?` | ${b.mem_total.toFixed(0)}GB`:""]})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:303:9",className:"flex items-center gap-2",children:[t.jsxs(Qt,{"code-path":"src/pages/HostMonitor.tsx:304:11",value:i,onValueChange:s=>it(s),children:[t.jsx(Yt,{"code-path":"src/pages/HostMonitor.tsx:305:13",className:"w-24 h-7 text-xs bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsx(Zt,{"code-path":"src/pages/HostMonitor.tsx:306:15"})}),t.jsxs(ts,{"code-path":"src/pages/HostMonitor.tsx:308:13",className:"bg-slate-800 border-slate-700 text-slate-200",children:[t.jsx(rt,{"code-path":"src/pages/HostMonitor.tsx:309:15",value:"avg",children:"平均值"}),t.jsx(rt,{"code-path":"src/pages/HostMonitor.tsx:310:15",value:"max",children:"最大值"}),t.jsx(rt,{"code-path":"src/pages/HostMonitor.tsx:311:15",value:"min",children:"最小值"})]})]}),t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:314:11",className:"flex items-center gap-1",children:bt.map(s=>t.jsx(A,{"code-path":"src/pages/HostMonitor.tsx:316:15",variant:f===s.hours?"default":"outline",size:"sm",className:"h-7 text-xs px-2.5",onClick:()=>z(s.hours),children:s.label},s.hours))})]})]}),t.jsxs(js,{"code-path":"src/pages/HostMonitor.tsx:324:7",value:P,onValueChange:v,children:[t.jsx(vs,{"code-path":"src/pages/HostMonitor.tsx:325:9",className:"h-8 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] gap-0 overflow-x-auto",children:[{id:"basic",label:"基础监控",icon:t.jsx(us,{"code-path":"src/pages/HostMonitor.tsx:327:49",className:"w-3 h-3"})},{id:"disk",label:"磁盘监控",icon:t.jsx(W,{"code-path":"src/pages/HostMonitor.tsx:328:48",className:"w-3 h-3"})},{id:"network",label:"网络监控",icon:t.jsx(dt,{"code-path":"src/pages/HostMonitor.tsx:329:51",className:"w-3 h-3"})},{id:"ports",label:"端口监控",icon:t.jsx(Y,{"code-path":"src/pages/HostMonitor.tsx:330:49",className:"w-3 h-3"})},{id:"process",label:"进程监控",icon:t.jsx(es,{"code-path":"src/pages/HostMonitor.tsx:331:51",className:"w-3 h-3"})},{id:"system",label:"系统信息",icon:t.jsx(bs,{"code-path":"src/pages/HostMonitor.tsx:332:50",className:"w-3 h-3"})},{id:"health_probes",label:"健康探针",icon:t.jsx(ks,{"code-path":"src/pages/HostMonitor.tsx:333:57",className:"w-3 h-3"})}].map(s=>t.jsxs(fs,{"code-path":"src/pages/HostMonitor.tsx:335:13",value:s.id,className:"text-[11px] h-7 gap-1 data-[state=active]:bg-[var(--dg-bg-primary)]",children:[s.icon,s.label]},s.id))}),t.jsxs(G,{"code-path":"src/pages/HostMonitor.tsx:342:9",value:"basic",className:"mt-3 grid grid-cols-1 md:grid-cols-3 gap-3",children:[t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:343:11",title:"CPU 使用率(%)",value:D("cpu"),icon:t.jsx(Ms,{"code-path":"src/pages/HostMonitor.tsx:343:79",className:"h-4 w-4 text-blue-400"}),data:g.cpu,color:"#3b82f6",unit:"%",domain:[0,100],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:345:11",title:"CPU IO等待(%)",value:o?.cpu_iowait!=null?`${o.cpu_iowait.toFixed(1)}%`:"--",icon:t.jsx(at,{"code-path":"src/pages/HostMonitor.tsx:345:133",className:"h-4 w-4 text-orange-400"}),data:g.iowait,color:"#f97316",unit:"%",domain:[0,100],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:347:11",title:"内存使用率(%)",value:D("mem"),icon:t.jsx(Y,{"code-path":"src/pages/HostMonitor.tsx:347:77",className:"h-4 w-4 text-emerald-400"}),data:g.mem,color:"#10b981",unit:"%",domain:[0,100],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:349:11",title:"可用内存(GB)",value:o?.mem_available!=null?`${o.mem_available.toFixed(1)}GB`:"--",icon:t.jsx(Y,{"code-path":"src/pages/HostMonitor.tsx:349:137",className:"h-4 w-4 text-emerald-400"}),data:g.memAvail,color:"#34d399",unit:"GB",domain:[0,"auto"],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:351:11",title:"Swap 使用率(%)",value:D("swap"),icon:t.jsx(W,{"code-path":"src/pages/HostMonitor.tsx:351:81",className:"h-4 w-4 text-red-400"}),data:g.swap,color:"#ef4444",unit:"%",domain:[0,100],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:353:11",title:"系统负载(1m)",value:D("load1"),icon:t.jsx(Wt,{"code-path":"src/pages/HostMonitor.tsx:353:79",className:"h-4 w-4 text-purple-400"}),data:g.load1,color:"#8b5cf6",unit:"",domain:[0,"auto"],aggType:i})]}),t.jsx(G,{"code-path":"src/pages/HostMonitor.tsx:358:9",value:"disk",className:"mt-3 space-y-3",children:t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:359:11",className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:360:13",title:"磁盘使用率(%)",value:D("disk"),icon:t.jsx(W,{"code-path":"src/pages/HostMonitor.tsx:360:80",className:"h-4 w-4 text-orange-400"}),data:g.disk,color:"#f97316",unit:"%",domain:[0,100],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:362:13",title:"Inode 使用率(%)",value:(()=>{const s=Array.isArray(M(o?.disk_info))?M(o?.disk_info):[],e=s.find(c=>c.mount==="/")||s[0];return e?.inode_usage_pct!=null?`${e.inode_usage_pct.toFixed(1)}%`:"--"})(),icon:t.jsx(W,{"code-path":"src/pages/HostMonitor.tsx:366:25",className:"h-4 w-4 text-purple-400"}),data:g.inode,color:"#8b5cf6",unit:"%",domain:[0,100],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:368:13",title:"磁盘读取(KB/s)",value:D("ioR"),icon:t.jsx(mt,{"code-path":"src/pages/HostMonitor.tsx:368:81",className:"h-4 w-4 text-blue-400"}),data:g.ioRead,color:"#3b82f6",unit:"KB/s",domain:[0,"auto"],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:370:13",title:"磁盘写入(KB/s)",value:D("ioW"),icon:t.jsx(mt,{"code-path":"src/pages/HostMonitor.tsx:370:81",className:"h-4 w-4 text-emerald-400"}),data:g.ioWrite,color:"#10b981",unit:"KB/s",domain:[0,"auto"],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:372:13",title:"磁盘IO繁忙度(%)",value:L?.util!=null?`${L.util.toFixed(1)}%`:"--",icon:t.jsx(mt,{"code-path":"src/pages/HostMonitor.tsx:372:130",className:"h-4 w-4 text-red-400"}),data:g.ioUtil,color:"#ef4444",unit:"%",domain:[0,100],aggType:i})]})}),t.jsxs(G,{"code-path":"src/pages/HostMonitor.tsx:378:9",value:"network",className:"mt-3 space-y-3",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:379:11",className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:380:13",title:"TCP EST",value:D("tcp"),icon:t.jsx(dt,{"code-path":"src/pages/HostMonitor.tsx:380:78",className:"h-4 w-4 text-purple-400"}),data:g.tcpEst,color:"#8b5cf6",unit:"个",domain:[0,"auto"],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:382:13",title:"TCP TIME_WAIT",value:D("tw"),icon:t.jsx(at,{"code-path":"src/pages/HostMonitor.tsx:382:83",className:"h-4 w-4 text-amber-400"}),data:g.tcpTW,color:"#f59e0b",unit:"个",domain:[0,"auto"],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:384:13",title:"TCP CLOSE_WAIT",value:p?.tcp_close_wait!=null?String(p.tcp_close_wait):"--",icon:t.jsx(at,{"code-path":"src/pages/HostMonitor.tsx:384:139",className:"h-4 w-4 text-red-400"}),data:g.tcpCW,color:"#ef4444",unit:"个",domain:[0,"auto"],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:386:13",title:"TCP 总连接",value:p?String((p.tcp_established||0)+(p.tcp_time_wait||0)+(p.tcp_close_wait||0)):"--",icon:t.jsx(dt,{"code-path":"src/pages/HostMonitor.tsx:386:169",className:"h-4 w-4 text-cyan-400"}),data:g.connTotal,color:"#22d3ee",unit:"个",domain:[0,"auto"],aggType:i})]}),t.jsx(Ss,{"code-path":"src/pages/HostMonitor.tsx:390:11",title:"网卡带宽吞吐",currentRx:p?.net_rx_bps!=null?ct(p.net_rx_bps):"--",currentTx:p?.net_tx_bps!=null?ct(p.net_tx_bps):"--",rxData:g.rx,txData:g.tx,aggType:i,unit:"KB/s"}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:397:11",className:"grid grid-cols-1 md:grid-cols-2 gap-3 mt-3",children:[t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:398:13",title:"网卡接收错误",value:p?.net_rx_errors!=null?String(p.net_rx_errors):"--",icon:t.jsx(ut,{"code-path":"src/pages/HostMonitor.tsx:398:129",className:"h-4 w-4 text-red-400"}),data:g.rxErr,color:"#ef4444",unit:"个",domain:[0,"auto"],aggType:i}),t.jsx(H,{"code-path":"src/pages/HostMonitor.tsx:400:13",title:"网卡发送错误",value:p?.net_tx_errors!=null?String(p.net_tx_errors):"--",icon:t.jsx(ut,{"code-path":"src/pages/HostMonitor.tsx:400:129",className:"h-4 w-4 text-orange-400"}),data:g.txErr,color:"#f97316",unit:"个",domain:[0,"auto"],aggType:i})]})]}),t.jsx(G,{"code-path":"src/pages/HostMonitor.tsx:406:9",value:"ports",className:"mt-3 space-y-3",children:t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:407:11",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/pages/HostMonitor.tsx:408:13",className:"p-4",children:[t.jsxs("h3",{"code-path":"src/pages/HostMonitor.tsx:409:15",className:"text-xs font-medium text-[var(--dg-text-primary)] mb-3 flex items-center gap-2",children:[t.jsx(Y,{"code-path":"src/pages/HostMonitor.tsx:410:17",className:"h-4 w-4 text-emerald-400"}),"监听端口 ",J.length,t.jsxs("span",{"code-path":"src/pages/HostMonitor.tsx:411:17",className:"ml-auto flex items-center gap-2",children:[k==="blacklist"&&X.length>0&&t.jsxs(Z,{"code-path":"src/pages/HostMonitor.tsx:413:21",variant:"outline",className:"text-[10px] text-amber-400 border-amber-500/30",children:["黑名单: ",X.join(",")]}),k==="whitelist"&&t.jsx(Z,{"code-path":"src/pages/HostMonitor.tsx:418:21",variant:"outline",className:"text-[10px] text-blue-400 border-blue-500/30",children:"白名单模式"}),t.jsx(A,{"code-path":"src/pages/HostMonitor.tsx:422:19",variant:"outline",size:"sm",className:"h-6 text-[10px] px-2",onClick:()=>{pt(),st(!0)},children:"策略配置"})]})]}),J.length===0?t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:429:17",className:"text-center py-6 text-xs text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-lg",children:"暂无端口数据"}):t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:433:17",className:"overflow-x-auto",children:t.jsxs("table",{"code-path":"src/pages/HostMonitor.tsx:434:19",className:"w-full text-xs",children:[t.jsx("thead",{"code-path":"src/pages/HostMonitor.tsx:435:21",children:t.jsxs("tr",{"code-path":"src/pages/HostMonitor.tsx:436:23",className:"text-[var(--dg-text-muted)] border-b border-[var(--dg-border)]",children:[t.jsx("th",{"code-path":"src/pages/HostMonitor.tsx:437:25",className:"py-1.5 text-left font-medium",children:"端口"}),t.jsx("th",{"code-path":"src/pages/HostMonitor.tsx:438:25",className:"py-1.5 text-left font-medium",children:"协议"}),t.jsx("th",{"code-path":"src/pages/HostMonitor.tsx:439:25",className:"py-1.5 text-left font-medium",children:"进程"}),t.jsx("th",{"code-path":"src/pages/HostMonitor.tsx:440:25",className:"py-1.5 text-right font-medium",children:"状态"})]})}),t.jsx("tbody",{"code-path":"src/pages/HostMonitor.tsx:443:21",children:J.map((s,e)=>t.jsxs("tr",{"code-path":"src/pages/HostMonitor.tsx:445:25",className:"border-b border-[var(--dg-border)]/30 hover:bg-slate-800/30 transition-colors",children:[t.jsx("td",{"code-path":"src/pages/HostMonitor.tsx:446:27",className:"py-1.5 font-mono text-[var(--dg-text-primary)]",children:s.port}),t.jsx("td",{"code-path":"src/pages/HostMonitor.tsx:447:27",className:"py-1.5",children:t.jsx(Z,{"code-path":"src/pages/HostMonitor.tsx:448:29",variant:"outline",className:"text-[10px] font-mono",children:s.protocol||"tcp"})}),t.jsx("td",{"code-path":"src/pages/HostMonitor.tsx:452:27",className:"py-1.5 font-mono text-[var(--dg-text-muted)]",children:s.process||"—"}),t.jsx("td",{"code-path":"src/pages/HostMonitor.tsx:453:27",className:"py-1.5 text-right",children:t.jsx(Z,{"code-path":"src/pages/HostMonitor.tsx:454:29",variant:"default",className:"text-[10px] bg-emerald-500/20 text-emerald-400 border-emerald-500/30",children:"LISTEN"})})]},e))})]})})]})})}),t.jsxs(G,{"code-path":"src/pages/HostMonitor.tsx:469:9",value:"process",className:"mt-3 space-y-3",children:[t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:471:11",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/pages/HostMonitor.tsx:472:13",className:"p-4",children:[t.jsxs("h3",{"code-path":"src/pages/HostMonitor.tsx:473:15",className:"text-xs font-medium text-[var(--dg-text-primary)] mb-3 flex items-center gap-2",children:[t.jsx(es,{"code-path":"src/pages/HostMonitor.tsx:474:17",className:"h-4 w-4 text-cyan-400"}),"进程 TOP ",lt.length]}),lt.length===0?t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:477:17",className:"text-center py-6 text-xs text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-lg",children:"Agent v2.0+ 支持,等待数据上报…"}):t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:481:17",className:"overflow-x-auto",children:t.jsxs("table",{"code-path":"src/pages/HostMonitor.tsx:482:19",className:"w-full text-xs",children:[t.jsx("thead",{"code-path":"src/pages/HostMonitor.tsx:483:21",children:t.jsxs("tr",{"code-path":"src/pages/HostMonitor.tsx:484:23",className:"text-[var(--dg-text-muted)] border-b border-[var(--dg-border)]",children:[t.jsx("th",{"code-path":"src/pages/HostMonitor.tsx:485:25",className:"py-1.5 text-left font-medium w-[40%]",children:"进程名称 / CMD"}),t.jsx("th",{"code-path":"src/pages/HostMonitor.tsx:486:25",className:"py-1.5 text-right font-medium w-[8%]",children:"PID"}),t.jsx("th",{"code-path":"src/pages/HostMonitor.tsx:487:25",className:"py-1.5 text-right font-medium w-[16%]",children:"内存使用率(%)"}),t.jsx("th",{"code-path":"src/pages/HostMonitor.tsx:488:25",className:"py-1.5 text-right font-medium w-[16%]",children:"CPU使用率(%)"}),t.jsx("th",{"code-path":"src/pages/HostMonitor.tsx:489:25",className:"py-1.5 text-right font-medium w-[20%]",children:"打开文件数"})]})}),t.jsx("tbody",{"code-path":"src/pages/HostMonitor.tsx:492:21",children:lt.map((s,e)=>{const c=s.cmdline||s.name||"?",l=s.cpu_pct!=null?Number(s.cpu_pct):null,E=s.mem_pct!=null?Number(s.mem_pct):null;return t.jsxs("tr",{"code-path":"src/pages/HostMonitor.tsx:498:27",className:"border-b border-[var(--dg-border)]/30 hover:bg-slate-800/30 transition-colors",children:[t.jsx("td",{"code-path":"src/pages/HostMonitor.tsx:499:29",className:"py-1.5 pr-2",children:t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:500:31",className:"flex items-center gap-1 group/cmd",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:501:33",className:"font-mono text-[var(--dg-text-primary)] truncate max-w-[320px] inline-block align-middle",title:c,children:c}),t.jsx("button",{"code-path":"src/pages/HostMonitor.tsx:507:33",className:"opacity-0 group-hover/cmd:opacity-100 transition-opacity p-0.5 hover:text-cyan-400 shrink-0",title:"复制命令行",onClick:async et=>{et.stopPropagation();try{await navigator.clipboard.writeText(c)}catch{const B=document.createElement("textarea");B.value=c,B.style.position="fixed",B.style.opacity="0",document.body.appendChild(B),B.select(),document.execCommand("copy"),document.body.removeChild(B)}},children:t.jsxs("svg",{"code-path":"src/pages/HostMonitor.tsx:523:35",className:"w-3 h-3",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",children:[t.jsx("rect",{"code-path":"src/pages/HostMonitor.tsx:524:37",x:"9",y:"9",width:"13",height:"13",rx:"2",ry:"2"}),t.jsx("path",{"code-path":"src/pages/HostMonitor.tsx:525:37",d:"M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"})]})})]})}),t.jsx("td",{"code-path":"src/pages/HostMonitor.tsx:530:29",className:"py-1.5 text-right font-mono text-[var(--dg-text-muted)]",children:s.pid}),t.jsx("td",{"code-path":"src/pages/HostMonitor.tsx:531:29",className:"py-1.5 text-right font-mono",children:t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:532:31",className:E!=null&&E>50?"text-rose-400":"text-cyan-400",children:E!=null?E.toFixed(2):"--"})}),t.jsx("td",{"code-path":"src/pages/HostMonitor.tsx:536:29",className:"py-1.5 text-right font-mono",children:t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:537:31",className:l!=null&&l>50?"text-rose-400":"text-[var(--dg-text-primary)]",children:l!=null?l.toFixed(2):"--"})}),t.jsx("td",{"code-path":"src/pages/HostMonitor.tsx:541:29",className:"py-1.5 text-right font-mono text-[var(--dg-text-muted)]",children:s.fd_count??"--"})]},e)})})]})})]})}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:553:11",className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:555:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/pages/HostMonitor.tsx:556:15",className:"p-4",children:[t.jsxs("h3",{"code-path":"src/pages/HostMonitor.tsx:557:17",className:"text-xs font-medium text-[var(--dg-text-primary)] mb-3 flex items-center gap-2",children:[t.jsx(W,{"code-path":"src/pages/HostMonitor.tsx:558:19",className:"h-4 w-4 text-violet-400"}),"FD 文件句柄"]}),I?.allocated!=null?t.jsxs(t.Fragment,{children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:562:21",className:"flex items-center gap-4 mb-3 text-xs",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:563:23",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:564:25",className:"text-[var(--dg-text-muted)]",children:"已分配 "}),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:565:25",className:"font-mono text-[var(--dg-text-primary)] font-semibold",children:I.allocated.toLocaleString()})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:567:23",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:568:25",className:"text-[var(--dg-text-muted)]",children:"上限 "}),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:569:25",className:"font-mono text-[var(--dg-text-primary)] font-semibold",children:I.max===-1?"无限制":I.max?.toLocaleString()||"—"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:571:23",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:572:25",className:"text-[var(--dg-text-muted)]",children:"使用率 "}),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:573:25",className:`font-mono font-semibold ${I.usage_pct>80?"text-rose-400":"text-violet-400"}`,children:I.usage_pct!=null?`${I.usage_pct.toFixed(1)}%`:"—"})]})]}),g.fd.length>0&&t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:579:23",className:"h-[120px]",children:t.jsx(Mt,{"code-path":"src/pages/HostMonitor.tsx:580:25",width:"100%",height:"100%",children:t.jsxs(Nt,{"code-path":"src/pages/HostMonitor.tsx:581:27",data:g.fd,children:[t.jsx(Ht,{"code-path":"src/pages/HostMonitor.tsx:582:29",strokeDasharray:"3 3",stroke:"var(--dg-border)"}),t.jsx(jt,{"code-path":"src/pages/HostMonitor.tsx:583:29",dataKey:"time",tick:{fontSize:10,fill:"var(--dg-text-muted)"},interval:"preserveStartEnd"}),t.jsx(vt,{"code-path":"src/pages/HostMonitor.tsx:584:29",tick:{fontSize:10,fill:"var(--dg-text-muted)"},unit:"%",domain:[0,"auto"]}),t.jsx(ft,{"code-path":"src/pages/HostMonitor.tsx:585:29",contentStyle:{background:"#1e293b",border:"1px solid #334155",borderRadius:6,fontSize:11}}),t.jsx("defs",{"code-path":"src/pages/HostMonitor.tsx:586:29",children:t.jsxs("linearGradient",{"code-path":"src/pages/HostMonitor.tsx:587:31",id:"fdGrad",x1:"0",y1:"0",x2:"0",y2:"1",children:[t.jsx("stop",{"code-path":"src/pages/HostMonitor.tsx:588:33",offset:"0%",stopColor:"#a78bfa",stopOpacity:.3}),t.jsx("stop",{"code-path":"src/pages/HostMonitor.tsx:589:33",offset:"100%",stopColor:"#a78bfa",stopOpacity:.05})]})}),t.jsx(nt,{"code-path":"src/pages/HostMonitor.tsx:592:29",type:"monotone",dataKey:i,stroke:"#a78bfa",strokeWidth:1.5,fill:"url(#fdGrad)",name:"FD使用率"})]})})})]}):t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:599:19",className:"text-center py-4 text-xs text-[var(--dg-text-muted)]",children:"等待数据…"})]})}),t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:605:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/pages/HostMonitor.tsx:606:15",className:"p-4",children:[t.jsxs("h3",{"code-path":"src/pages/HostMonitor.tsx:607:17",className:"text-xs font-medium text-[var(--dg-text-primary)] mb-3 flex items-center gap-2",children:[t.jsx(ss,{"code-path":"src/pages/HostMonitor.tsx:608:19",className:"h-4 w-4 text-emerald-400"}),"上下文切换"]}),_?.ctx_per_sec!=null?t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:611:19",className:"space-y-4",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:612:21",className:"grid grid-cols-2 gap-4",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:613:23",className:"bg-[var(--dg-bg-primary)] rounded-lg p-3 text-center",children:[t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:614:25",className:"text-[10px] text-[var(--dg-text-muted)] mb-1",children:"CTX 切换/秒"}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:615:25",className:"text-lg font-bold font-mono text-emerald-400",children:[(_.ctx_per_sec/1e6).toFixed(1),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:616:66",className:"text-xs font-normal text-[var(--dg-text-muted)] ml-0.5",children:"M"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:618:25",className:"text-[10px] text-[var(--dg-text-muted)] mt-1 font-mono",children:[_.ctx_per_sec?.toLocaleString()," 次"]})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:620:23",className:"bg-[var(--dg-bg-primary)] rounded-lg p-3 text-center",children:[t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:621:25",className:"text-[10px] text-[var(--dg-text-muted)] mb-1",children:"IRQ 中断/秒"}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:622:25",className:"text-lg font-bold font-mono text-amber-400",children:[(_.irq_per_sec/1e6).toFixed(1),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:623:66",className:"text-xs font-normal text-[var(--dg-text-muted)] ml-0.5",children:"M"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:625:25",className:"text-[10px] text-[var(--dg-text-muted)] mt-1 font-mono",children:[_.irq_per_sec?.toLocaleString()," 次"]})]})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:629:21",className:"space-y-1",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:630:23",className:"flex justify-between text-[10px]",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:631:25",className:"text-emerald-400",children:"CTX"}),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:632:25",className:"text-amber-400",children:"IRQ"})]}),t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:634:23",className:"h-2 bg-[var(--dg-bg-primary)] rounded-full overflow-hidden flex",children:_.ctx_per_sec+_.irq_per_sec>0&&t.jsxs(t.Fragment,{children:[t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:637:29",className:"h-full bg-emerald-500/60 rounded-l-full transition-all",style:{width:`${(_.ctx_per_sec/(_.ctx_per_sec+_.irq_per_sec)*100).toFixed(1)}%`}}),t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:639:29",className:"h-full bg-amber-500/60 rounded-r-full transition-all",style:{width:`${(_.irq_per_sec/(_.ctx_per_sec+_.irq_per_sec)*100).toFixed(1)}%`}})]})})]})]}):t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:647:19",className:"text-center py-4 text-xs text-[var(--dg-text-muted)]",children:"等待数据…"})]})})]})]}),t.jsxs(G,{"code-path":"src/pages/HostMonitor.tsx:655:9",value:"system",className:"mt-3 space-y-3",children:[t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:656:11",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsx(S,{"code-path":"src/pages/HostMonitor.tsx:657:13",className:"p-4",children:t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:658:15",className:"grid grid-cols-2 md:grid-cols-4 gap-x-6 gap-y-3 text-xs",children:[["主机名",b?.hostname||d],["IP 地址",b?.ip||"—"],["操作系统",b?.os||"—"],["内核版本",b?.kernel||"—"],["CPU 核心数",b?.cpu_cores||"—"],["总内存",b?.mem_total?`${b.mem_total.toFixed(0)} GB`:"—"],["已用内存",b?.mem_used?`${b.mem_used.toFixed(1)} GB`:"—"],["运行时长",b?.uptime?`${Math.floor(b.uptime/86400)}天 ${Math.floor(b.uptime%86400/3600)}时`:"—"],["Agent 版本",Q?.version||b?.agent_version||"—"],["Agent 序列号",Q?.report_seq!=null?String(Q.report_seq):"—"],["监听端口数",J.length>0?`${J.length}`:"—"],["Agent RSS",Q?.self_rss_mb?`${Q.self_rss_mb.toFixed(1)} MB`:"—"]].map(([s,e])=>t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:673:19",children:[t.jsxs("span",{"code-path":"src/pages/HostMonitor.tsx:674:21",className:"text-[var(--dg-text-muted)]",children:[s,":"]}),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:675:21",className:"text-[var(--dg-text-primary)] font-mono",children:e})]},s))})})}),o&&t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:684:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/pages/HostMonitor.tsx:685:15",className:"p-4",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:686:17",className:"flex items-center gap-2 mb-2",children:[t.jsx(Wt,{"code-path":"src/pages/HostMonitor.tsx:687:19",className:"h-4 w-4 text-[var(--dg-text-muted)]"}),t.jsx("h3",{"code-path":"src/pages/HostMonitor.tsx:688:19",className:"text-xs font-medium text-[var(--dg-text-primary)]",children:"系统负载 (Load Average)"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:690:17",className:"flex items-center gap-6 text-xs",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:691:19",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:691:24",className:"text-[var(--dg-text-muted)]",children:"1min "}),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:691:82",className:"text-sm font-bold text-slate-200",children:o.load1??"--"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:692:19",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:692:24",className:"text-[var(--dg-text-muted)]",children:"5min "}),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:692:82",className:"text-sm font-bold text-slate-200",children:o.load5??"--"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:693:19",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:693:24",className:"text-[var(--dg-text-muted)]",children:"15min "}),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:693:83",className:"text-sm font-bold text-slate-200",children:o.load15??"--"})]})]})]})}),o?.disk_info&&(()=>{const s=M(o.disk_info),e=Array.isArray(s)?s:s.partitions||[];return e.length?t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:705:15",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/pages/HostMonitor.tsx:706:17",className:"p-4",children:[t.jsxs("h3",{"code-path":"src/pages/HostMonitor.tsx:707:19",className:"text-xs font-medium text-[var(--dg-text-primary)] mb-2 flex items-center gap-2",children:[t.jsx(W,{"code-path":"src/pages/HostMonitor.tsx:707:114",className:"h-4 w-4"}),"磁盘分区"]}),t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:708:19",className:"space-y-1.5",children:e.map((c,l)=>t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:710:23",className:"flex items-center gap-2 text-xs",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:711:25",className:"text-[var(--dg-text-muted)] w-24 font-mono truncate",children:c.mount||c.mountpoint||c.device||`disk${l}`}),t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:712:25",className:"flex-1 h-1.5 bg-slate-700 rounded-full overflow-hidden",children:t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:713:27",className:"h-full rounded-full bg-blue-500",style:{width:`${Math.min(c.usage_percent||c.used_percent||0,100)}%`}})}),t.jsxs("span",{"code-path":"src/pages/HostMonitor.tsx:715:25",className:"text-[var(--dg-text-primary)] w-28 text-right tabular-nums whitespace-nowrap",children:[(c.used_gb??0).toFixed(1),"/",(c.total_gb??0).toFixed(0),"GB"]}),t.jsxs("span",{"code-path":"src/pages/HostMonitor.tsx:716:25",className:"text-blue-400 w-14 text-right tabular-nums whitespace-nowrap",children:[(c.usage_percent??c.used_percent??0).toFixed(1),"%"]})]},l))})]})}):null})()]}),t.jsxs(G,{"code-path":"src/pages/HostMonitor.tsx:727:9",value:"health_probes",className:"mt-3 space-y-3",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:728:11",className:"flex items-center justify-between",children:[t.jsx("h3",{"code-path":"src/pages/HostMonitor.tsx:729:13",className:"text-xs font-medium text-[var(--dg-text-primary)]",children:"探针列表(Agent 在目标主机本地执行探测)"}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:730:13",className:"flex gap-2",children:[t.jsxs(A,{"code-path":"src/pages/HostMonitor.tsx:731:15",size:"sm",variant:"outline",className:"h-7 text-[11px]",onClick:V,children:[t.jsx(ss,{"code-path":"src/pages/HostMonitor.tsx:732:17",className:"w-3 h-3 mr-1"}),"刷新"]}),t.jsxs(A,{"code-path":"src/pages/HostMonitor.tsx:734:15",size:"sm",className:"h-7 text-[11px] bg-blue-600 hover:bg-blue-500",onClick:()=>{kt(null),N({name:"",hostname:d,probe_type:"http_get",http_url:"",http_method:"GET",http_expect_code:200,http_expect_body:"",tcp_host:"localhost",tcp_port:3306,exec_command:"",timeout:10,interval:60,description:""}),q(!0)},children:[t.jsx(Ns,{"code-path":"src/pages/HostMonitor.tsx:743:17",className:"w-3 h-3 mr-1"}),"添加探针"]})]})]}),wt.length===0?t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:748:13",className:"bg-[var(--dg-bg-secondary)] border-dashed border-[var(--dg-border)]",children:t.jsx(S,{"code-path":"src/pages/HostMonitor.tsx:749:15",className:"p-8 text-center text-xs text-[var(--dg-text-muted)]",children:'暂无健康探针,点击"添加探针"创建'})}):t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:754:13",className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:wt.map(s=>t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:756:17",className:`bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] ${s.last_status==="down"?"border-red-700/50":""}`,children:t.jsxs(S,{"code-path":"src/pages/HostMonitor.tsx:757:19",className:"p-3",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:758:21",className:"flex items-start justify-between mb-2",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:759:23",className:"flex items-center gap-2",children:[s.last_status==="up"?t.jsx(Hs,{"code-path":"src/pages/HostMonitor.tsx:760:51",className:"w-4 h-4 text-emerald-400"}):s.last_status==="down"?t.jsx(ut,{"code-path":"src/pages/HostMonitor.tsx:761:53",className:"w-4 h-4 text-red-400"}):t.jsx(at,{"code-path":"src/pages/HostMonitor.tsx:762:26",className:"w-4 h-4 text-slate-500"}),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:763:25",className:"text-xs font-medium text-[var(--dg-text-primary)]",children:s.name}),t.jsx(Z,{"code-path":"src/pages/HostMonitor.tsx:764:25",variant:"outline",className:"text-[10px] h-5 px-1.5 capitalize",children:s.probe_type==="http_get"?"HTTP":s.probe_type==="tcp_socket"?"TCP":"Exec"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:768:23",className:"flex gap-1",children:[t.jsx(A,{"code-path":"src/pages/HostMonitor.tsx:769:25",variant:"ghost",size:"sm",className:"h-6 w-6 p-0",onClick:()=>{kt(s),N({name:s.name,hostname:s.hostname,probe_type:s.probe_type,http_url:s.http_url||"",http_method:s.http_method||"GET",http_expect_code:s.http_expect_code||200,http_expect_body:s.http_expect_body||"",tcp_host:s.tcp_host||"",tcp_port:s.tcp_port||3306,exec_command:s.exec_command||"",timeout:s.timeout||10,interval:s.interval||60,description:s.description||""}),q(!0)},children:t.jsx(_s,{"code-path":"src/pages/HostMonitor.tsx:781:27",className:"w-3 h-3"})}),t.jsx(A,{"code-path":"src/pages/HostMonitor.tsx:783:25",variant:"ghost",size:"sm",className:"h-6 w-6 p-0 text-red-400 hover:text-red-300",onClick:async()=>{confirm(`确定删除探针"${s.name}"?`)&&(await R.deleteHealthProbe(s.id),V())},children:t.jsx(ys,{"code-path":"src/pages/HostMonitor.tsx:789:27",className:"w-3 h-3"})})]})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:793:21",className:"space-y-1 text-[11px] text-[var(--dg-text-muted)]",children:[s.probe_type==="http_get"&&t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:795:25",className:"truncate",children:["URL: ",s.http_url]}),s.probe_type==="tcp_socket"&&t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:798:25",children:[s.tcp_host,":",s.tcp_port]}),s.probe_type==="exec_command"&&t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:801:25",className:"truncate font-mono",children:s.exec_command}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:803:23",className:"flex items-center gap-3",children:[t.jsxs("span",{"code-path":"src/pages/HostMonitor.tsx:804:25",children:["状态: ",t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:804:35",className:s.last_status==="up"?"text-emerald-400":s.last_status==="down"?"text-red-400":"text-slate-400",children:s.last_status?s.last_status.toUpperCase():"未检测"})]}),s.last_latency_ms>0&&t.jsxs("span",{"code-path":"src/pages/HostMonitor.tsx:807:51",children:["延迟: ",s.last_latency_ms,"ms"]}),s.fail_count>0&&t.jsxs("span",{"code-path":"src/pages/HostMonitor.tsx:808:46",className:"text-red-400",children:["连续失败: ",s.fail_count,"次"]}),s.last_checked_at&&t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:809:47",className:"text-[10px]",children:new Date(s.last_checked_at).toLocaleString("zh-CN")})]})]})]})},s.id))})]})]}),t.jsx(Kt,{"code-path":"src/pages/HostMonitor.tsx:821:7",open:cs,onOpenChange:q,children:t.jsxs(qt,{"code-path":"src/pages/HostMonitor.tsx:822:9",showOverlay:!1,className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-lg",children:[t.jsxs(Ut,{"code-path":"src/pages/HostMonitor.tsx:823:11",children:[t.jsx(Vt,{"code-path":"src/pages/HostMonitor.tsx:824:13",className:"text-[var(--dg-text-primary)]",children:U?"编辑探针":"添加探针"}),t.jsx(Xt,{"code-path":"src/pages/HostMonitor.tsx:827:13",className:"text-[var(--dg-text-secondary)]",children:U?"修改健康探针配置":"创建新的健康探针,Agent 在目标主机本地执行探测"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:831:11",className:"space-y-3 max-h-[60vh] overflow-y-auto pr-1",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:832:13",children:[t.jsxs("label",{"code-path":"src/pages/HostMonitor.tsx:833:15",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:["探针名称 ",t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:833:90",className:"text-red-400",children:"*"})]}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:834:15",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.name,onChange:s=>N({...a,name:s.target.value}),placeholder:"如:cex-agent 健康检查"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:836:13",children:[t.jsx("label",{"code-path":"src/pages/HostMonitor.tsx:837:15",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:"目标主机"}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:838:15",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.hostname,onChange:s=>N({...a,hostname:s.target.value})})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:840:13",children:[t.jsx("label",{"code-path":"src/pages/HostMonitor.tsx:841:15",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:"探针类型"}),t.jsxs("select",{"code-path":"src/pages/HostMonitor.tsx:842:15",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.probe_type,onChange:s=>N({...a,probe_type:s.target.value}),children:[t.jsx("option",{"code-path":"src/pages/HostMonitor.tsx:843:17",value:"http_get",children:"HTTP GET"}),t.jsx("option",{"code-path":"src/pages/HostMonitor.tsx:844:17",value:"tcp_socket",children:"TCP Socket"}),t.jsx("option",{"code-path":"src/pages/HostMonitor.tsx:845:17",value:"exec_command",children:"Exec Command"})]})]}),a.probe_type==="http_get"&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:851:17",children:[t.jsxs("label",{"code-path":"src/pages/HostMonitor.tsx:851:22",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:["HTTP URL ",t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:851:101",className:"text-red-400",children:"*"})]}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:852:19",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.http_url,onChange:s=>N({...a,http_url:s.target.value}),placeholder:"http://localhost:8080/health"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:853:17",className:"grid grid-cols-2 gap-2",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:854:19",children:[t.jsx("label",{"code-path":"src/pages/HostMonitor.tsx:854:24",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:"期望状态码"}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:855:21",type:"number",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.http_expect_code,onChange:s=>N({...a,http_expect_code:Number(s.target.value)})})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:856:19",children:[t.jsx("label",{"code-path":"src/pages/HostMonitor.tsx:856:24",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:"期望响应内容(可选)"}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:857:21",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.http_expect_body,onChange:s=>N({...a,http_expect_body:s.target.value})})]})]})]}),a.probe_type==="tcp_socket"&&t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:863:15",className:"grid grid-cols-2 gap-2",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:864:17",children:[t.jsx("label",{"code-path":"src/pages/HostMonitor.tsx:864:22",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:"TCP 目标地址"}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:865:19",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.tcp_host,onChange:s=>N({...a,tcp_host:s.target.value}),placeholder:"localhost"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:866:19",children:[t.jsx("label",{"code-path":"src/pages/HostMonitor.tsx:866:24",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:"TCP 端口"}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:867:19",type:"number",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.tcp_port,onChange:s=>N({...a,tcp_port:Number(s.target.value)})})]})]}),a.probe_type==="exec_command"&&t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:872:15",children:[t.jsxs("label",{"code-path":"src/pages/HostMonitor.tsx:872:20",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:["执行命令 ",t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:872:95",className:"text-red-400",children:"*"})]}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:873:17",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs font-mono text-[var(--dg-text-primary)]",value:a.exec_command,onChange:s=>N({...a,exec_command:s.target.value}),placeholder:"pgrep -x mysqld"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:876:13",className:"grid grid-cols-2 gap-2",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:877:15",children:[t.jsx("label",{"code-path":"src/pages/HostMonitor.tsx:877:20",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:"超时(秒)"}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:878:17",type:"number",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.timeout,onChange:s=>N({...a,timeout:Number(s.target.value)})})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:879:15",children:[t.jsx("label",{"code-path":"src/pages/HostMonitor.tsx:879:20",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:"间隔(秒)"}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:880:17",type:"number",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.interval,onChange:s=>N({...a,interval:Number(s.target.value)})})]})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:883:13",children:[t.jsx("label",{"code-path":"src/pages/HostMonitor.tsx:883:18",className:"text-[11px] text-[var(--dg-text-muted)] mb-1 block",children:"描述"}),t.jsx("input",{"code-path":"src/pages/HostMonitor.tsx:884:15",className:"w-full h-8 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 text-xs text-[var(--dg-text-primary)]",value:a.description,onChange:s=>N({...a,description:s.target.value})})]})]}),t.jsxs(Jt,{"code-path":"src/pages/HostMonitor.tsx:886:11",children:[t.jsx(A,{"code-path":"src/pages/HostMonitor.tsx:887:13",variant:"outline",size:"sm",className:"h-7 text-[11px]",onClick:()=>q(!1),children:"取消"}),t.jsx(A,{"code-path":"src/pages/HostMonitor.tsx:888:13",size:"sm",className:"h-7 text-[11px] bg-blue-600 hover:bg-blue-500",onClick:async()=>{if(!(!a.name||!a.hostname))try{U?await R.updateHealthProbe(U.id,a):await R.createHealthProbe(a),q(!1),V()}catch{alert("保存失败")}},disabled:!a.name||!a.hostname,children:U?"保存":"创建"})]})]})}),t.jsx(Kt,{"code-path":"src/pages/HostMonitor.tsx:907:7",open:ds,onOpenChange:st,children:t.jsxs(qt,{"code-path":"src/pages/HostMonitor.tsx:908:9",showOverlay:!1,className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-md",children:[t.jsxs(Ut,{"code-path":"src/pages/HostMonitor.tsx:909:11",children:[t.jsx(Vt,{"code-path":"src/pages/HostMonitor.tsx:910:13",className:"text-[var(--dg-text-primary)]",children:"端口监控策略"}),t.jsx(Xt,{"code-path":"src/pages/HostMonitor.tsx:911:13",className:"text-[var(--dg-text-secondary)]",children:"配置 Agent 端口上报过滤规则"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:913:11",className:"space-y-4",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:915:13",children:[t.jsx("label",{"code-path":"src/pages/HostMonitor.tsx:916:15",className:"text-[11px] text-[var(--dg-text-muted)] mb-1.5 block",children:"过滤模式"}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:917:15",className:"flex gap-2",children:[t.jsx("button",{"code-path":"src/pages/HostMonitor.tsx:918:17",className:`flex-1 h-9 rounded text-xs font-medium border transition-colors ${k==="whitelist"?"bg-blue-500/20 border-blue-500 text-blue-400":"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-muted)]"}`,onClick:()=>xt("whitelist"),children:"白名单 ─ 全量上报"}),t.jsx("button",{"code-path":"src/pages/HostMonitor.tsx:924:17",className:`flex-1 h-9 rounded text-xs font-medium border transition-colors ${k==="blacklist"?"bg-amber-500/20 border-amber-500 text-amber-400":"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-muted)]"}`,onClick:()=>xt("blacklist"),children:"黑名单 ─ 仅上报选中"})]}),t.jsx("p",{"code-path":"src/pages/HostMonitor.tsx:931:15",className:"text-[10px] text-[var(--dg-text-muted)] mt-1.5 leading-relaxed",children:k==="whitelist"?"所有发现的端口都上报,任意端口变化都会触发告警 + 恢复通知。":"仅上报选中端口的变化,其余端口变化静默忽略(不告警)。系统进程端口(sshd/rpcbind/systemd等)永远忽略。"})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:939:13",children:[t.jsxs("label",{"code-path":"src/pages/HostMonitor.tsx:940:15",className:"text-[11px] text-[var(--dg-text-muted)] mb-1.5 block",children:["端口列表 ",t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:941:22",className:"text-[var(--dg-text-muted)]",children:"(逗号分隔,如: 80,443,3306,6379)"}),k==="whitelist"&&t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:942:52",className:"text-blue-400 ml-1",children:"— 白名单模式无需配置"})]}),t.jsx("textarea",{"code-path":"src/pages/HostMonitor.tsx:944:15",className:`w-full h-20 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded px-2 py-1.5 text-xs font-mono resize-none ${k==="whitelist"?"text-[var(--dg-text-muted)] opacity-50 cursor-not-allowed":"text-[var(--dg-text-primary)]"}`,value:X.join(","),onChange:s=>{if(k==="whitelist")return;const c=s.target.value.split(",").map(l=>parseInt(l.trim())).filter(l=>!isNaN(l)&&l>0&&l<=65535);Ct(c)},placeholder:k==="whitelist"?"白名单模式下所有端口自动上报":"80,443,3306,6379",readOnly:k==="whitelist"}),t.jsxs("p",{"code-path":"src/pages/HostMonitor.tsx:958:15",className:"text-[10px] text-[var(--dg-text-muted)] mt-1",children:["已输入 ",X.length," 个端口"]})]}),t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:964:13",className:"bg-amber-500/5 border border-amber-500/20 rounded p-2.5",children:t.jsxs("p",{"code-path":"src/pages/HostMonitor.tsx:965:15",className:"text-[10px] text-amber-300/80 leading-relaxed",children:["⚠️ 无论选择哪种模式,以下系统进程端口",t.jsx("b",{"code-path":"src/pages/HostMonitor.tsx:966:37",children:"永远不上报"}),":sshd、rpcbind、master、systemd、dbus-daemon、rsyslogd 等。Agent 采集时自动跳过。"]})})]}),t.jsxs(Jt,{"code-path":"src/pages/HostMonitor.tsx:970:11",children:[t.jsx(A,{"code-path":"src/pages/HostMonitor.tsx:971:13",variant:"outline",size:"sm",className:"h-7 text-[11px]",onClick:()=>st(!1),children:"取消"}),t.jsx(A,{"code-path":"src/pages/HostMonitor.tsx:972:13",size:"sm",className:"h-7 text-[11px] bg-blue-600 hover:bg-blue-500",onClick:ns,disabled:St,children:St?"保存中…":"保存策略"})]})]})})]})}function H({title:r,value:T,icon:O,data:F,color:d,unit:j,domain:y,aggType:w}){const P=F.map(v=>({...v,value:v[w]}));return t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:992:5",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/pages/HostMonitor.tsx:993:7",className:"p-3",children:[t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:994:9",className:"flex items-center justify-between mb-1",children:t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:995:11",className:"flex items-center gap-1.5",children:[O,t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:995:60",className:"text-xs text-[var(--dg-text-primary)] font-medium truncate",children:r})]})}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:997:9",className:"mb-2",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:998:11",className:"text-xl font-bold text-[var(--dg-text-primary)] tabular-nums",children:T}),j&&t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:999:20",className:"text-xs text-[var(--dg-text-muted)] ml-1",children:j})]}),t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:1001:9",className:"h-48",children:P.length===0?t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:1003:13",className:"h-full flex items-center justify-center text-xs text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-md",children:"暂无数据"}):t.jsx(Mt,{"code-path":"src/pages/HostMonitor.tsx:1005:13",width:"100%",height:"100%",children:t.jsxs(Nt,{"code-path":"src/pages/HostMonitor.tsx:1006:15",data:P,margin:{top:2,right:2,bottom:0,left:-10},children:[t.jsx("defs",{"code-path":"src/pages/HostMonitor.tsx:1007:17",children:t.jsxs("linearGradient",{"code-path":"src/pages/HostMonitor.tsx:1008:19",id:`grad-${r}`,x1:"0",y1:"0",x2:"0",y2:"1",children:[t.jsx("stop",{"code-path":"src/pages/HostMonitor.tsx:1009:21",offset:"5%",stopColor:d,stopOpacity:.3}),t.jsx("stop",{"code-path":"src/pages/HostMonitor.tsx:1010:21",offset:"95%",stopColor:d,stopOpacity:0})]})}),t.jsx(Ht,{"code-path":"src/pages/HostMonitor.tsx:1013:17",strokeDasharray:"3 3",stroke:"#1e293b",strokeOpacity:.5}),t.jsx(jt,{"code-path":"src/pages/HostMonitor.tsx:1014:17",dataKey:"time",hide:!0}),t.jsx(vt,{"code-path":"src/pages/HostMonitor.tsx:1015:17",hide:!0,domain:y[1]==="auto"?[0,v=>v*1.1]:y}),t.jsx(ft,{"code-path":"src/pages/HostMonitor.tsx:1016:17",contentStyle:{backgroundColor:"#0f172a",border:"1px solid #1e293b",borderRadius:"4px",color:"#f8fafc",fontSize:"11px",padding:"4px 8px"},formatter:v=>[`${v.toFixed(2)} ${j}`,r.replace(/\(.+\)/,"")],labelFormatter:v=>`时间: ${v}`}),t.jsx(nt,{"code-path":"src/pages/HostMonitor.tsx:1019:17",type:"monotone",dataKey:"value",stroke:d,strokeWidth:1.5,fill:`url(#grad-${r})`}),t.jsx(as,{"code-path":"src/pages/HostMonitor.tsx:1020:17",dataKey:"time",height:24,stroke:"#334155",fill:"#0f172a",startIndex:Math.max(0,P.length-Math.min(20,P.length))})]})})})]})})}function Ss({title:r,currentRx:T,currentTx:O,rxData:F,txData:d,aggType:j,unit:y}){const w=F.map((f,z)=>({time:f.time,timestamp:f.timestamp,rx:f[j]??0,tx:d[z]?.[j]??0})),P=`grad-rx-${r.replace(/\s/g,"")}`,v=`grad-tx-${r.replace(/\s/g,"")}`;return t.jsx(C,{"code-path":"src/pages/HostMonitor.tsx:1049:5",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:t.jsxs(S,{"code-path":"src/pages/HostMonitor.tsx:1050:7",className:"p-3",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:1051:9",className:"flex items-center justify-between mb-1",children:[t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:1052:11",className:"flex items-center gap-1.5",children:[t.jsx(dt,{"code-path":"src/pages/HostMonitor.tsx:1053:13",className:"h-4 w-4 text-blue-400"}),t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:1054:13",className:"text-xs text-[var(--dg-text-primary)] font-medium",children:r})]}),t.jsxs("div",{"code-path":"src/pages/HostMonitor.tsx:1056:11",className:"flex items-center gap-3 text-xs",children:[t.jsxs("span",{"code-path":"src/pages/HostMonitor.tsx:1057:13",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:1057:19",className:"inline-block w-2.5 h-2.5 rounded-sm bg-blue-400 mr-1 align-middle"}),"接收 ",t.jsx("b",{"code-path":"src/pages/HostMonitor.tsx:1057:108",className:"text-blue-300",children:T})]}),t.jsxs("span",{"code-path":"src/pages/HostMonitor.tsx:1058:13",children:[t.jsx("span",{"code-path":"src/pages/HostMonitor.tsx:1058:19",className:"inline-block w-2.5 h-2.5 rounded-sm bg-emerald-400 mr-1 align-middle"}),"发送 ",t.jsx("b",{"code-path":"src/pages/HostMonitor.tsx:1058:111",className:"text-emerald-300",children:O})]})]})]}),t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:1061:9",className:"h-56",children:w.length===0?t.jsx("div",{"code-path":"src/pages/HostMonitor.tsx:1063:13",className:"h-full flex items-center justify-center text-xs text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-md",children:"暂无数据"}):t.jsx(Mt,{"code-path":"src/pages/HostMonitor.tsx:1065:13",width:"100%",height:"100%",children:t.jsxs(Nt,{"code-path":"src/pages/HostMonitor.tsx:1066:15",data:w,margin:{top:2,right:2,bottom:0,left:-10},children:[t.jsxs("defs",{"code-path":"src/pages/HostMonitor.tsx:1067:17",children:[t.jsxs("linearGradient",{"code-path":"src/pages/HostMonitor.tsx:1068:19",id:P,x1:"0",y1:"0",x2:"0",y2:"1",children:[t.jsx("stop",{"code-path":"src/pages/HostMonitor.tsx:1069:21",offset:"5%",stopColor:"#3b82f6",stopOpacity:.3}),t.jsx("stop",{"code-path":"src/pages/HostMonitor.tsx:1070:21",offset:"95%",stopColor:"#3b82f6",stopOpacity:0})]}),t.jsxs("linearGradient",{"code-path":"src/pages/HostMonitor.tsx:1072:19",id:v,x1:"0",y1:"0",x2:"0",y2:"1",children:[t.jsx("stop",{"code-path":"src/pages/HostMonitor.tsx:1073:21",offset:"5%",stopColor:"#10b981",stopOpacity:.3}),t.jsx("stop",{"code-path":"src/pages/HostMonitor.tsx:1074:21",offset:"95%",stopColor:"#10b981",stopOpacity:0})]})]}),t.jsx(Ht,{"code-path":"src/pages/HostMonitor.tsx:1077:17",strokeDasharray:"3 3",stroke:"#1e293b",strokeOpacity:.5}),t.jsx(jt,{"code-path":"src/pages/HostMonitor.tsx:1078:17",dataKey:"time",hide:!0}),t.jsx(vt,{"code-path":"src/pages/HostMonitor.tsx:1079:17",hide:!0,domain:[0,"auto"]}),t.jsx(ft,{"code-path":"src/pages/HostMonitor.tsx:1080:17",contentStyle:{backgroundColor:"#0f172a",border:"1px solid #1e293b",borderRadius:"4px",color:"#f8fafc",fontSize:"11px",padding:"4px 8px"},formatter:(f,z)=>[`${f.toFixed(2)} ${y}`,z==="rx"?"接收":"发送"],labelFormatter:f=>`时间: ${f}`}),t.jsx(nt,{"code-path":"src/pages/HostMonitor.tsx:1083:17",type:"monotone",dataKey:"rx",stroke:"#3b82f6",strokeWidth:1.5,fill:`url(#${P})`,name:"rx"}),t.jsx(nt,{"code-path":"src/pages/HostMonitor.tsx:1084:17",type:"monotone",dataKey:"tx",stroke:"#10b981",strokeWidth:1.5,fill:`url(#${v})`,name:"tx"}),t.jsx(as,{"code-path":"src/pages/HostMonitor.tsx:1085:17",dataKey:"time",height:24,stroke:"#334155",fill:"#0f172a",startIndex:Math.max(0,w.length-Math.min(20,w.length))})]})})})]})})}export{qs as HostMonitor}; diff --git a/backend/static/assets/KubernetesClusters-CsRHjVkA.js b/backend/static/assets/KubernetesClusters-CsRHjVkA.js new file mode 100644 index 0000000..b6e263a --- /dev/null +++ b/backend/static/assets/KubernetesClusters-CsRHjVkA.js @@ -0,0 +1,10 @@ +import{r as c,j as e,s as V,B as A,al as oe,aj as Re,af as Pe,ac as le,am as Te,ae as $,ag as Y,an as Ee,ah as X,ad as Ae,ai as Me,X as M,D as ue,b as de,c as Ie,d as ie,e as xe,I as B,f as Fe,W as Ge,H as Oe,L as Le,a5 as Be,a3 as ee,q as Ue,G as ze,S as $e,aK as We,aL as qe,aM as He,aN as Ve,aO as te,aP as O,U as Xe,E as Ye,v as Je,T as Ze}from"./index-DfyorCky.js";import{C as _,b as U,c as z,d as pe,a as R}from"./card-C55cvSHg.js";import{B as y}from"./badge-xNW8x0G1.js";import{k as w}from"./kubernetes-J8O09fK7.js";import{t as G}from"./index-a3ybMjbR.js";import{T as Qe,a as et,b as I,c as F}from"./tabs-CIh_yD4s.js";import{C as me}from"./circle-x-DK79Dhg2.js";import{R as tt,C as st,X as rt,Y as nt,T as at}from"./generateCategoricalChart-6v9BPbG2.js";import{A as ct,a as se}from"./AreaChart-B2zlWfdX.js";import{T as re}from"./textarea-NXY8u32k.js";import{L as E}from"./label-BK0h2apY.js";import{u as ot}from"./index-CWVNW_qu.js";import{C as lt}from"./circle-DOZr6_68.js";import{x as ut,a as dt}from"./xterm-DSqgeKvr.js";import{M as it,a as xt}from"./minimize-2-CiCQYRfn.js";import{R as H}from"./refresh-cw-DUB_tAG-.js";import{P as pt}from"./plus-CUG-9kpu.js";import{E as mt}from"./ellipsis-DU5enAwm.js";import{D as bt}from"./download-DoZfYs2h.js";import{T as ht}from"./trash-2-Dx32pOzT.js";function gt({cluster:n,onClose:x}){const[a,g]=c.useState([]),[s,u]=c.useState([]),[d,N]=c.useState([]),[k,C]=c.useState([]),[b,f]=c.useState([]),h=c.useMemo(()=>{if(!a||a.length===0)return{cpuPct:0,memPct:0};let t=0,i=0,m=0;for(const j of a){const D=j.cpu||0,o=j.cpu_usage_m?parseFloat(String(j.cpu_usage_m).replace("m","")):0,l=D>0?o/1e3/D*100:0,v=j.memory_mb||0,P=j.mem_usage_mi?parseFloat(String(j.mem_usage_mi).replace("Mi","").replace("Ki","")):0,q=j.mem_usage_mi?.includes?.("Ki")?P/1024:j.mem_usage_mi?.includes?.("Gi")?P*1024:P,L=v>0?q/v*100:0;(l>0||L>0)&&(t+=l,i+=L,m++)}return{cpuPct:m>0?t/m:0,memPct:m>0?i/m:0}},[a]),p=async t=>{try{const[i,m,j,D,o]=await Promise.all([w.getNodes(t).catch(()=>[]),w.getPods(t).catch(()=>[]),w.getDeployments(t).catch(()=>[]),w.getServices(t).catch(()=>[]),w.getIngresses(t).catch(()=>[])]),l=v=>Array.isArray(v)?v:v?.list||[];g(l(i)),u(l(m)),N(l(j)),C(l(D)),f(l(o))}catch(i){console.error("加载集群详情失败:",i)}};return c.useEffect(()=>{n?.id&&p(n.id)},[n?.id]),e.jsxs(_,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:81:5",className:"bg-slate-900 border-slate-800",children:[e.jsx(U,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:82:7",children:e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:83:9",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:84:11",className:"flex items-center gap-3",children:[e.jsx(V,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:85:13",className:"h-6 w-6 text-blue-400"}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:86:13",children:[e.jsx(z,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:87:15",className:"text-slate-100",children:n.name}),e.jsxs(pe,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:88:15",className:"text-slate-500",children:[n.version," · ",n.node_count||0," 节点 · 创建于"," ",n.created_at?new Date(n.created_at).toLocaleDateString():"-"]})]})]}),e.jsxs(A,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:94:11",variant:"ghost",size:"sm",className:"text-slate-400 hover:text-slate-100",onClick:x,children:[e.jsx(me,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:100:13",className:"h-4 w-4 mr-2"}),"关闭"]})]})}),e.jsx(R,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:105:7",children:e.jsxs(Qe,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:106:9",defaultValue:"overview",className:"w-full",children:[e.jsxs(et,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:107:11",className:"bg-slate-800 border border-slate-700 flex-wrap h-auto",children:[e.jsx(I,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:108:13",value:"overview",className:"data-[state=active]:bg-slate-700",children:"概览"}),e.jsxs(I,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:111:13",value:"nodes",className:"data-[state=active]:bg-slate-700",children:["节点 (",a.length,")"]}),e.jsxs(I,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:114:13",value:"pods",className:"data-[state=active]:bg-slate-700",children:["Pod (",s.length,")"]}),e.jsxs(I,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:117:13",value:"deployments",className:"data-[state=active]:bg-slate-700",children:["Deployment (",d.length,")"]}),e.jsxs(I,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:120:13",value:"services",className:"data-[state=active]:bg-slate-700",children:["Service (",k.length,")"]}),e.jsxs(I,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:123:13",value:"ingresses",className:"data-[state=active]:bg-slate-700",children:["Ingress (",b.length,")"]}),e.jsx(I,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:126:13",value:"events",className:"data-[state=active]:bg-slate-700",children:"事件"})]}),e.jsx(F,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:131:11",value:"overview",className:"mt-4 space-y-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:132:13",className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs(_,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:133:15",className:"bg-slate-800/50 border-slate-700",children:[e.jsx(U,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:134:17",className:"pb-2",children:e.jsx(z,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:135:19",className:"text-sm text-slate-400",children:"资源使用趋势"})}),e.jsxs(R,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:137:17",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:138:19",className:"h-[200px]",children:e.jsx(tt,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:139:21",width:"100%",height:"100%",children:e.jsxs(ct,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:140:23",data:[{time:"CPU",cpu:Number(h.cpuPct.toFixed(1)),memory:Number(h.memPct.toFixed(1))}],children:[e.jsxs("defs",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:143:25",children:[e.jsxs("linearGradient",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:144:27",id:"colorCpu",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:145:29",offset:"5%",stopColor:"#3b82f6",stopOpacity:.3}),e.jsx("stop",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:146:29",offset:"95%",stopColor:"#3b82f6",stopOpacity:0})]}),e.jsxs("linearGradient",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:148:27",id:"colorMemory",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:149:29",offset:"5%",stopColor:"#10b981",stopOpacity:.3}),e.jsx("stop",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:150:29",offset:"95%",stopColor:"#10b981",stopOpacity:0})]})]}),e.jsx(st,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:153:25",strokeDasharray:"3 3",stroke:"#1e293b"}),e.jsx(rt,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:154:25",dataKey:"time",stroke:"#475569",fontSize:12}),e.jsx(nt,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:155:25",stroke:"#475569",fontSize:12,domain:[0,100]}),e.jsx(at,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:156:25",contentStyle:{backgroundColor:"#0f172a",border:"1px solid #1e293b",borderRadius:"6px",color:"#f8fafc"}}),e.jsx(se,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:164:25",type:"monotone",dataKey:"cpu",stroke:"#3b82f6",fillOpacity:1,fill:"url(#colorCpu)",name:"CPU(%)"}),e.jsx(se,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:172:25",type:"monotone",dataKey:"memory",stroke:"#10b981",fillOpacity:1,fill:"url(#colorMemory)",name:"内存(%)"})]})})}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:183:19",className:"flex justify-center gap-6 mt-2 text-xs text-slate-400",children:[e.jsxs("span",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:184:21",children:["CPU: ",e.jsxs("span",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:184:32",className:"text-blue-400 font-bold",children:[h.cpuPct.toFixed(1),"%"]})]}),e.jsxs("span",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:185:21",children:["内存: ",e.jsxs("span",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:185:31",className:"text-emerald-400 font-bold",children:[h.memPct.toFixed(1),"%"]})]})]})]})]}),e.jsxs(_,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:190:15",className:"bg-slate-800/50 border-slate-700",children:[e.jsx(U,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:191:17",className:"pb-2",children:e.jsx(z,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:192:19",className:"text-sm text-slate-400",children:"资源分布"})}),e.jsx(R,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:194:17",children:e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:195:19",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:196:21",className:"text-center p-4 rounded-lg bg-slate-800",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:197:23",className:"text-3xl font-bold text-blue-400",children:n.pod_count||0}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:198:23",className:"text-sm text-slate-500 mt-1",children:"Pod"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:200:21",className:"text-center p-4 rounded-lg bg-slate-800",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:201:23",className:"text-3xl font-bold text-emerald-400",children:n.service_count||0}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:202:23",className:"text-sm text-slate-500 mt-1",children:"Service"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:204:21",className:"text-center p-4 rounded-lg bg-slate-800",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:205:23",className:"text-3xl font-bold text-purple-400",children:n.deployment_count||0}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:206:23",className:"text-sm text-slate-500 mt-1",children:"Deployment"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:208:21",className:"text-center p-4 rounded-lg bg-slate-800",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:209:23",className:"text-3xl font-bold text-amber-400",children:n.node_count||0}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:210:23",className:"text-sm text-slate-500 mt-1",children:"节点"})]})]})})]})]})}),e.jsx(F,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:218:11",value:"nodes",className:"mt-4",children:e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:219:13",className:"border rounded-lg border-slate-700 overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:220:15",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:221:17",className:"bg-slate-800",children:e.jsxs("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:222:19",children:[e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:223:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"名称"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:224:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"角色"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:225:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"状态"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:226:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"CPU"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:227:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"内存"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:228:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"Pod"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:229:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"操作系统"})]})}),e.jsx("tbody",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:232:17",className:"divide-y divide-slate-800",children:a.length===0?e.jsx("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:234:21",children:e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:235:23",colSpan:7,className:"px-4 py-8 text-center text-slate-500",children:"暂无节点数据"})}):a.map(t=>e.jsxs("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:239:21",className:"hover:bg-slate-800/50",children:[e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:240:23",className:"px-4 py-3 text-sm text-slate-200",children:t.name}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:241:23",className:"px-4 py-3",children:e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:242:25",variant:"outline",className:t.role==="master"?"border-purple-500/30 text-purple-400 bg-purple-500/10":"border-blue-500/30 text-blue-400 bg-blue-500/10",children:t.role==="master"?"Master":"Worker"})}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:253:23",className:"px-4 py-3",children:e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:254:25",variant:"outline",className:(t.status||"").toLowerCase()==="ready"?"border-emerald-500/30 text-emerald-400 bg-emerald-500/10":"border-red-500/30 text-red-400 bg-red-500/10",children:(t.status||"").toLowerCase()==="ready"?"Ready":"NotReady"})}),e.jsxs("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:265:23",className:"px-4 py-3 text-sm text-slate-300",children:[t.cpu_usage_m||"0m"," / ",t.cpu,"核"]}),e.jsxs("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:268:23",className:"px-4 py-3 text-sm text-slate-300",children:[t.mem_usage_mi||"0Mi"," / ",t.memory_mb?(t.memory_mb/1024).toFixed(0)+"GB":"-"]}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:271:23",className:"px-4 py-3 text-sm text-slate-300",children:t.max_pods??0}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:272:23",className:"px-4 py-3 text-sm text-slate-400",children:t.os})]},t.id||t.name))})]})})}),e.jsx(F,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:281:11",value:"pods",className:"mt-4",children:e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:282:13",className:"border rounded-lg border-slate-700 overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:283:15",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:284:17",className:"bg-slate-800",children:e.jsxs("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:285:19",children:[e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:286:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"名称"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:287:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"命名空间"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:288:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"状态"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:289:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"重启次数"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:290:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"CPU"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:291:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"内存"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:292:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"节点"})]})}),e.jsx("tbody",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:295:17",className:"divide-y divide-slate-800",children:s.length===0?e.jsx("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:297:21",children:e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:298:23",colSpan:7,className:"px-4 py-8 text-center text-slate-500",children:"暂无Pod数据"})}):s.map(t=>e.jsxs("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:302:21",className:"hover:bg-slate-800/50",children:[e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:303:23",className:"px-4 py-3 text-sm text-slate-200",children:t.name}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:304:23",className:"px-4 py-3",children:e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:305:25",variant:"outline",className:"border-slate-700 text-slate-400",children:t.namespace})}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:309:23",className:"px-4 py-3",children:e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:310:25",variant:"outline",className:(t.status||"").toLowerCase()==="running"?"border-emerald-500/30 text-emerald-400 bg-emerald-500/10":(t.status||"").toLowerCase()==="pending"?"border-amber-500/30 text-amber-400 bg-amber-500/10":"border-red-500/30 text-red-400 bg-red-500/10",children:t.status})}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:323:23",className:"px-4 py-3 text-sm text-slate-300",children:t.restart_count??0}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:324:23",className:"px-4 py-3 text-sm text-slate-300",children:t.cpu_usage_m||"0m"}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:325:23",className:"px-4 py-3 text-sm text-slate-300",children:t.mem_usage_mi||"0Mi"}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:326:23",className:"px-4 py-3 text-sm text-slate-400",children:t.node_name})]},t.id||t.name))})]})})}),e.jsx(F,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:335:11",value:"deployments",className:"mt-4",children:e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:336:13",className:"border rounded-lg border-slate-700 overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:337:15",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:338:17",className:"bg-slate-800",children:e.jsxs("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:339:19",children:[e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:340:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"名称"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:341:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"命名空间"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:342:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"副本数"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:343:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"可用副本"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:344:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"镜像"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:345:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"创建时间"})]})}),e.jsx("tbody",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:348:17",className:"divide-y divide-slate-800",children:d.length===0?e.jsx("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:350:21",children:e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:351:23",colSpan:6,className:"px-4 py-8 text-center text-slate-500",children:"暂无Deployment数据"})}):d.map(t=>e.jsxs("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:355:21",className:"hover:bg-slate-800/50",children:[e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:356:23",className:"px-4 py-3 text-sm text-slate-200",children:t.name}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:357:23",className:"px-4 py-3",children:e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:358:25",variant:"outline",className:"border-slate-700 text-slate-400",children:t.namespace})}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:362:23",className:"px-4 py-3 text-sm text-slate-300",children:t.replicas}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:363:23",className:"px-4 py-3",children:e.jsxs("span",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:364:25",className:`text-sm ${(t.available_replicas??t.availableReplicas)===t.replicas?"text-emerald-400":"text-amber-400"}`,children:[t.available_replicas??t.availableReplicas," / ",t.replicas]})}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:368:23",className:"px-4 py-3 text-sm text-slate-400 truncate max-w-[200px]",children:t.image}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:369:23",className:"px-4 py-3 text-sm text-slate-400",children:t.created_at||t.createdAt})]},t.id||t.name))})]})})}),e.jsx(F,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:378:11",value:"services",className:"mt-4",children:e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:379:13",className:"border rounded-lg border-slate-700 overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:380:15",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:381:17",className:"bg-slate-800",children:e.jsxs("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:382:19",children:[e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:383:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"名称"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:384:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"命名空间"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:385:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"类型"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:386:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"ClusterIP"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:387:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"端口"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:388:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"Selector"})]})}),e.jsx("tbody",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:391:17",className:"divide-y divide-slate-800",children:k.length===0?e.jsx("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:393:21",children:e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:394:23",colSpan:6,className:"px-4 py-8 text-center text-slate-500",children:"暂无Service数据"})}):k.map(t=>e.jsxs("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:398:21",className:"hover:bg-slate-800/50",children:[e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:399:23",className:"px-4 py-3 text-sm text-slate-200",children:t.name}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:400:23",className:"px-4 py-3",children:e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:401:25",variant:"outline",className:"border-slate-700 text-slate-400",children:t.namespace})}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:405:23",className:"px-4 py-3",children:e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:406:25",variant:"outline",className:t.type==="ClusterIP"?"border-blue-500/30 text-blue-400 bg-blue-500/10":t.type==="NodePort"?"border-purple-500/30 text-purple-400 bg-purple-500/10":"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:t.type})}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:419:23",className:"px-4 py-3 text-sm text-slate-300",children:t.cluster_ip??t.clusterIP}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:420:23",className:"px-4 py-3 text-sm text-slate-300",children:t.ports}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:421:23",className:"px-4 py-3 text-sm text-slate-400",children:t.selector})]},t.id||t.name))})]})})}),e.jsx(F,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:430:11",value:"ingresses",className:"mt-4",children:e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:431:13",className:"border rounded-lg border-slate-700 overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:432:15",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:433:17",className:"bg-slate-800",children:e.jsxs("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:434:19",children:[e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:435:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"名称"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:436:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"命名空间"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:437:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"Hosts"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:438:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"后端服务"}),e.jsx("th",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:439:21",className:"px-4 py-3 text-left text-xs font-medium text-slate-400",children:"TLS"})]})}),e.jsx("tbody",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:442:17",className:"divide-y divide-slate-800",children:b.length===0?e.jsx("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:444:21",children:e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:445:23",colSpan:5,className:"px-4 py-8 text-center text-slate-500",children:"暂无Ingress数据"})}):b.map(t=>e.jsxs("tr",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:449:21",className:"hover:bg-slate-800/50",children:[e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:450:23",className:"px-4 py-3 text-sm text-slate-200",children:t.name}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:451:23",className:"px-4 py-3",children:e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:452:25",variant:"outline",className:"border-slate-700 text-slate-400",children:t.namespace})}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:456:23",className:"px-4 py-3 text-sm text-slate-300",children:t.hosts}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:457:23",className:"px-4 py-3 text-sm text-slate-300",children:t.backend}),e.jsx("td",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:458:23",className:"px-4 py-3",children:e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:459:25",variant:"outline",className:t.tls?"border-emerald-500/30 text-emerald-400 bg-emerald-500/10":"border-slate-700 text-slate-400",children:t.tls?"已启用":"未启用"})})]},t.id||t.name))})]})})}),e.jsx(F,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:478:11",value:"events",className:"mt-4",children:e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:479:13",className:"space-y-2",children:[{type:"Normal",reason:"Started",message:"Started container nginx",time:"2分钟前"},{type:"Normal",reason:"Created",message:"Created pod nginx-deployment-xxx",time:"5分钟前"},{type:"Warning",reason:"FailedScheduling",message:"0/3 nodes are available",time:"10分钟前"},{type:"Normal",reason:"Pulling",message:'Pulling image "nginx:latest"',time:"15分钟前"},{type:"Normal",reason:"Pulled",message:"Successfully pulled image",time:"12分钟前"}].map((t,i)=>e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:487:17",className:"flex items-center gap-3 p-3 rounded-lg bg-slate-800/50",children:[e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:491:19",variant:"outline",className:t.type==="Normal"?"border-emerald-500/30 text-emerald-400 bg-emerald-500/10":"border-amber-500/30 text-amber-400 bg-amber-500/10",children:t.type}),e.jsx("span",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:501:19",className:"text-sm font-medium text-slate-300 min-w-[120px]",children:t.reason}),e.jsx("span",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:502:19",className:"text-sm text-slate-400 flex-1",children:t.message}),e.jsx("span",{"code-path":"src/components/kubernetes/KubernetesClusterDetail.tsx:503:19",className:"text-xs text-slate-500",children:t.time})]},i))})})]})})]})}var J="Radio",[Ct,be]=le(J),[kt,ft]=Ct(J),he=c.forwardRef((n,x)=>{const{__scopeRadio:a,name:g,checked:s=!1,required:u,disabled:d,value:N="on",onCheck:k,form:C,...b}=n,[f,h]=c.useState(null),p=Y(x,m=>h(m)),t=c.useRef(!1),i=f?C||!!f.closest("form"):!0;return e.jsxs(kt,{scope:a,checked:s,disabled:d,children:[e.jsx($.button,{type:"button",role:"radio","aria-checked":s,"data-state":fe(s),"data-disabled":d?"":void 0,disabled:d,value:N,...b,ref:p,onClick:X(n.onClick,m=>{s||k?.(),i&&(t.current=m.isPropagationStopped(),t.current||m.stopPropagation())})}),i&&e.jsx(ke,{control:f,bubbles:!t.current,name:g,value:N,checked:s,required:u,disabled:d,form:C,style:{transform:"translateX(-100%)"}})]})});he.displayName=J;var ge="RadioIndicator",Ce=c.forwardRef((n,x)=>{const{__scopeRadio:a,forceMount:g,...s}=n,u=ft(ge,a);return e.jsx(Ae,{present:g||u.checked,children:e.jsx($.span,{"data-state":fe(u.checked),"data-disabled":u.disabled?"":void 0,...s,ref:x})})});Ce.displayName=ge;var jt="RadioBubbleInput",ke=c.forwardRef(({__scopeRadio:n,control:x,checked:a,bubbles:g=!0,...s},u)=>{const d=c.useRef(null),N=Y(d,u),k=ot(a),C=Me(x);return c.useEffect(()=>{const b=d.current;if(!b)return;const f=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(f,"checked").set;if(k!==a&&p){const t=new Event("click",{bubbles:g});p.call(b,a),b.dispatchEvent(t)}},[k,a,g]),e.jsx($.input,{type:"radio","aria-hidden":!0,defaultChecked:a,...s,tabIndex:-1,ref:N,style:{...s.style,...C,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});ke.displayName=jt;function fe(n){return n?"checked":"unchecked"}var Kt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],W="RadioGroup",[Nt]=le(W,[oe,be]),je=oe(),Ke=be(),[vt,Dt]=Nt(W),Ne=c.forwardRef((n,x)=>{const{__scopeRadioGroup:a,name:g,defaultValue:s,value:u,required:d=!1,disabled:N=!1,orientation:k,dir:C,loop:b=!0,onValueChange:f,...h}=n,p=je(a),t=Re(C),[i,m]=Pe({prop:u,defaultProp:s??null,onChange:f,caller:W});return e.jsx(vt,{scope:a,name:g,required:d,disabled:N,value:i,onValueChange:m,children:e.jsx(Te,{asChild:!0,...p,orientation:k,dir:t,loop:b,children:e.jsx($.div,{role:"radiogroup","aria-required":d,"aria-orientation":k,"data-disabled":N?"":void 0,dir:t,...h,ref:x})})})});Ne.displayName=W;var ve="RadioGroupItem",De=c.forwardRef((n,x)=>{const{__scopeRadioGroup:a,disabled:g,...s}=n,u=Dt(ve,a),d=u.disabled||g,N=je(a),k=Ke(a),C=c.useRef(null),b=Y(x,C),f=u.value===s.value,h=c.useRef(!1);return c.useEffect(()=>{const p=i=>{Kt.includes(i.key)&&(h.current=!0)},t=()=>h.current=!1;return document.addEventListener("keydown",p),document.addEventListener("keyup",t),()=>{document.removeEventListener("keydown",p),document.removeEventListener("keyup",t)}},[]),e.jsx(Ee,{asChild:!0,...N,focusable:!d,active:f,children:e.jsx(he,{disabled:d,required:u.required,checked:f,...k,...s,name:u.name,ref:b,onCheck:()=>u.onValueChange(s.value),onKeyDown:X(p=>{p.key==="Enter"&&p.preventDefault()}),onFocus:X(s.onFocus,()=>{h.current&&C.current?.click()})})})});De.displayName=ve;var yt="RadioGroupIndicator",ye=c.forwardRef((n,x)=>{const{__scopeRadioGroup:a,...g}=n,s=Ke(a);return e.jsx(Ce,{...s,...g,ref:x})});ye.displayName=yt;var wt=Ne,St=De,_t=ye;function Rt({className:n,...x}){return e.jsx(wt,{"code-path":"src/components/ui/radio-group.tsx:14:5","data-slot":"radio-group",className:M("grid gap-3",n),...x})}function ne({className:n,...x}){return e.jsx(St,{"code-path":"src/components/ui/radio-group.tsx:27:5","data-slot":"radio-group-item",className:M("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",n),...x,children:e.jsx(_t,{"code-path":"src/components/ui/radio-group.tsx:35:7","data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:e.jsx(lt,{"code-path":"src/components/ui/radio-group.tsx:39:9",className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}const ae=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?$/,ce={name:"",version:"",description:"",config_type:1,api_server:"",token:"",kube_config:""};function Pt({open:n,onOpenChange:x,editingCluster:a,onSaved:g}){const[s,u]=c.useState({...ce}),[d,N]=c.useState(!1),[k,C]=c.useState(!1),[b,f]=c.useState(!1),[h,p]=c.useState("");c.useEffect(()=>{n&&(a&&a.id?w.getClusterDetail(a.id).then(o=>{const l=o||{};C(!!l.has_token),f(!!l.has_kube_config),u({name:l.name||"",version:l.version||"",description:l.description||"",config_type:Number(l.config_type??1),api_server:l.api_server||"",token:"",kube_config:""}),p("")}).catch(()=>{u({name:a.name||"",version:a.version||"",description:a.description||"",config_type:Number(a.config_type??1),api_server:a.api_server||"",token:"",kube_config:""}),p("")}):(C(!1),f(!1),u({...ce}),p("")))},[n,a]);const t=o=>{u({...s,name:o}),o.trim()?ae.test(o)?p(""):p("只允许英文、数字和连字符(-),首尾不能是连字符"):p("")},i=o=>{const l=o.match(/^\s*server:\s*(\S+)\s*$/m);return l?l[1]:""},m=o=>{const l=i(o);u(v=>({...v,kube_config:o,api_server:l||v.api_server}))},j=async()=>{if(!s.name.trim()||!ae.test(s.name.trim())){G.error("请输入有效的集群名称(英文/数字/连字符)");return}try{N(!0);const o={name:s.name.trim(),code:s.name.trim(),version:s.version,description:s.description,config_type:s.config_type,api_server:s.api_server,token:s.config_type===0?s.token:"",kube_config:s.config_type===1?s.kube_config:""};a?await w.updateCluster(a.id,o):await w.createCluster(o),x(!1),g()}catch(o){console.error("保存集群失败:",o)}finally{N(!1)}},D=d||!s.name.trim()||!!h;return e.jsx(ue,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:143:5",open:n,onOpenChange:x,children:e.jsxs(de,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:144:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-2xl",children:[e.jsxs(Ie,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:145:9",children:[e.jsx(ie,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:146:11",className:"text-[var(--dg-text-primary)]",children:a?"编辑集群":"添加集群"}),e.jsx(xe,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:149:11",className:"text-[var(--dg-text-secondary)]",children:a?"修改集群接入配置":"配置新的 Kubernetes 集群接入信息"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:153:9",className:"space-y-4 py-2 max-h-[60vh] overflow-y-auto pr-1",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:154:11",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:155:13",className:"space-y-2",children:[e.jsx(E,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:156:15",className:"text-[var(--dg-text-secondary)]",children:"集群名称"}),e.jsx(B,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:157:15",value:s.name,onChange:o=>t(o.target.value),placeholder:"如: prod-cluster",className:`bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] ${h?"border-red-500":""}`}),h&&e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:163:29",className:"text-xs text-red-400",children:h}),e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:164:15",className:"text-xs text-[var(--dg-text-muted)]",children:"只允许英文、数字和连字符(-),首尾不能是连字符。名称将作为集群唯一标识。"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:168:13",className:"space-y-2",children:[e.jsx(E,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:169:15",className:"text-[var(--dg-text-secondary)]",children:"版本(可选)"}),e.jsx(B,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:170:15",value:s.version,onChange:o=>u({...s,version:o.target.value}),placeholder:"如: 1.28.0",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:179:11",className:"space-y-2",children:[e.jsx(E,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:180:13",className:"text-[var(--dg-text-secondary)]",children:"描述"}),e.jsx(B,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:181:13",value:s.description,onChange:o=>u({...s,description:o.target.value}),placeholder:"集群用途描述",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:189:11",className:"space-y-2",children:[e.jsx(E,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:190:13",className:"text-[var(--dg-text-secondary)]",children:"接入方式"}),e.jsxs(Rt,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:191:13",value:String(s.config_type),onValueChange:o=>u({...s,config_type:Number(o)}),className:"flex gap-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:196:15",className:"flex items-center gap-2 px-3 py-2 rounded-md border border-[var(--dg-border)] cursor-pointer hover:bg-[var(--dg-bg-hover)]",children:[e.jsx(ne,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:197:17",value:"0",id:"ct-0"}),e.jsx(E,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:198:17",htmlFor:"ct-0",className:"cursor-pointer text-[var(--dg-text-primary)] font-normal",children:"Token"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:200:15",className:"flex items-center gap-2 px-3 py-2 rounded-md border border-[var(--dg-border)] cursor-pointer hover:bg-[var(--dg-bg-hover)]",children:[e.jsx(ne,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:201:17",value:"1",id:"ct-1"}),e.jsx(E,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:202:17",htmlFor:"ct-1",className:"cursor-pointer text-[var(--dg-text-primary)] font-normal",children:"Kubeconfig"})]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:207:11",className:"space-y-2",children:[e.jsx(E,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:208:13",className:"text-[var(--dg-text-secondary)]",children:"API Server"}),e.jsx(B,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:209:13",value:s.api_server,onChange:o=>u({...s,api_server:o.target.value}),placeholder:"https://10.0.0.1:6443",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]}),s.config_type===0?e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:218:13",className:"space-y-2",children:[e.jsxs(E,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:219:15",className:"text-[var(--dg-text-secondary)]",children:["Token ",k&&e.jsx("span",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:220:36",className:"text-emerald-400 text-xs ml-1",children:"✓ 已配置(留空不修改)"})]}),e.jsx(re,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:222:15",value:s.token,onChange:o=>u({...s,token:o.target.value}),placeholder:k?"已配置,输入新值覆盖...":"粘贴 Service Account Token...",rows:4,className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-xs"})]}):e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:231:13",className:"space-y-2",children:[e.jsxs(E,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:232:15",className:"text-[var(--dg-text-secondary)]",children:["Kubeconfig ",b&&e.jsx("span",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:233:46",className:"text-emerald-400 text-xs ml-1",children:"✓ 已配置(留空不修改)"})]}),e.jsx(re,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:235:15",value:s.kube_config,onChange:o=>m(o.target.value),placeholder:b?"已配置,输入新值覆盖...":`apiVersion: v1 +kind: Config +clusters: +- cluster: + server: https://10.0.0.1:6443 + ...`,rows:10,className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-xs"}),!b&&e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:243:17",className:"text-xs text-[var(--dg-text-muted)]",children:"粘贴 kubeconfig 内容后将自动解析 API Server 地址"})]})]}),e.jsxs(Fe,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:250:9",children:[e.jsx(A,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:251:11",variant:"outline",onClick:()=>{x(!1)},className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]",children:"取消"}),e.jsx(A,{"code-path":"src/components/kubernetes/KubernetesClusterDialog.tsx:258:11",onClick:j,disabled:D,className:"bg-[var(--dg-blue)] hover:opacity-90 text-white",children:d?"保存中...":a?"保存":"添加"})]})]})})}function Tt({open:n,onOpenChange:x,clusterId:a,clusterName:g}){const s=c.useRef(null),u=c.useRef(null),d=c.useRef(null),N=c.useRef(null),[k,C]=c.useState(!1),[b,f]=c.useState(!1),[h,p]=c.useState("");return c.useEffect(()=>{n||f(!1)},[n]),c.useEffect(()=>{if(!n||!a)return;const t=new ut.Terminal({cursorBlink:!0,fontSize:14,fontFamily:'Menlo, Monaco, "Courier New", monospace',allowProposedApi:!0,theme:{background:"#0f172a",foreground:"#e2e8f0",cursor:"#38bdf8",selectionBackground:"#1e40af",black:"#1e293b",red:"#ef4444",green:"#10b981",yellow:"#f59e0b",blue:"#3b82f6",magenta:"#a855f7",cyan:"#06b6d4",white:"#e2e8f0",brightBlack:"#475569",brightRed:"#f87171",brightGreen:"#34d399",brightYellow:"#fbbf24",brightBlue:"#60a5fa",brightMagenta:"#c084fc",brightCyan:"#22d3ee",brightWhite:"#f8fafc"}}),i=new dt.FitAddon;t.loadAddon(i),u.current=t,N.current=i;const j=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}`,D=Ge.getState().token||"",o=`${j.replace(/^http/,"ws").replace("/api/v1","")}/ws/kubectl?token=${encodeURIComponent(D)}&id=${a}`,l=new WebSocket(o);return d.current=l,t.onData(v=>{l.readyState===WebSocket.OPEN&&l.send(JSON.stringify({status:0,data:v}))}),l.onmessage=v=>{try{const P=JSON.parse(v.data);P.status===0&&typeof P.data=="string"&&t.write(P.data)}catch{typeof v.data=="string"&&t.write(v.data)}},l.onopen=()=>{C(!0),p(""),s.current&&(t.open(s.current),requestAnimationFrame(()=>{try{i.fit()}catch{}}),setTimeout(()=>{try{t.focus()}catch{}},150))},l.onclose=()=>{C(!1),t.write(`\r +\x1B[31m[连接已断开]\x1B[0m\r +`)},l.onerror=()=>{p("WebSocket 连接失败"),t.write(`\r +\x1B[31m[连接发生错误]\x1B[0m\r +`)},()=>{try{(l.readyState===WebSocket.OPEN||l.readyState===WebSocket.CONNECTING)&&l.close(),t.dispose()}catch{}u.current=null,d.current=null,C(!1)}},[n,a]),c.useEffect(()=>{if(!n)return;const t=s.current;if(!t)return;let i;const m=new ResizeObserver(()=>{clearTimeout(i),i=setTimeout(()=>{if(N.current&&u.current&&d.current)try{N.current.fit(),u.current.focus();const{cols:j,rows:D}=u.current;d.current.readyState===WebSocket.OPEN&&d.current.send(JSON.stringify({status:1,cols:j,rows:D}))}catch{}},60)});return m.observe(t),()=>{clearTimeout(i),m.disconnect()}},[n]),e.jsx(ue,{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:161:5",open:n,onOpenChange:x,children:e.jsxs(de,{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:162:7",showCloseButton:!1,onOpenAutoFocus:t=>t.preventDefault(),className:M("bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] p-0 gap-0","!duration-0 !transition-none",b?"!max-w-none !w-screen !h-screen !rounded-none !translate-x-0 !translate-y-0 !left-0 !top-0":""),style:b?{maxWidth:"100vw",width:"100vw",height:"100vh"}:{maxWidth:"900px",width:"90vw"},children:[e.jsxs(ie,{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:174:9",className:"sr-only",children:["kubectl — ",g]}),e.jsx(xe,{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:175:9",className:"sr-only",children:"Kubernetes 集群命令行终端"}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:178:9",className:"flex items-center justify-between px-4 py-2 border-b border-[var(--dg-border)]",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:179:11",className:"flex items-center gap-2 text-sm",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:180:13",className:M("w-2 h-2 rounded-full",k?"bg-emerald-400":h?"bg-red-400":"bg-yellow-400")}),e.jsx(Oe,{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:181:13",className:"h-4 w-4 text-blue-400"}),e.jsxs("span",{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:182:13",className:"text-[var(--dg-text-primary)] font-medium",children:["kubectl — ",g]}),!k&&!h&&e.jsx(Le,{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:183:38",className:"h-3 w-3 animate-spin text-[var(--dg-text-muted)]"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:185:11",className:"flex items-center gap-1",children:[e.jsx("button",{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:186:13",onClick:()=>f(!b),className:"p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]",children:b?e.jsx(it,{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:190:29",className:"h-4 w-4"}):e.jsx(xt,{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:190:65",className:"h-4 w-4"})}),e.jsx("button",{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:192:13",onClick:()=>x(!1),className:"p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]",children:e.jsx(Be,{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:196:15",className:"h-4 w-4"})})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/KubectlTerminal.tsx:202:9",ref:s,className:"bg-[#0f172a]",style:{height:b?"calc(100vh - 49px)":"480px"}})]})})}function Qt(){const[n,x]=c.useState([]),[a,g]=c.useState(!0),[s,u]=c.useState(null),[d,N]=c.useState(""),[k,C]=c.useState(!1),[b,f]=c.useState(null),[h,p]=c.useState(null),[t,i]=c.useState(!1),[m,j]=c.useState(null),[D,o]=c.useState(!1),l=async()=>{try{g(!0);const r=await w.getClusters();x(r?.list||[])}catch(r){console.error("加载集群列表失败:",r),x([])}finally{g(!1)}};c.useEffect(()=>{l()},[]);const[,v]=c.useState(null),P=()=>{l().then(()=>{b||setTimeout(async()=>{const K=(await w.getClusters())?.list||[];K.length>0&&L(K[K.length-1].id,!0)},500)})},q=async r=>{try{await w.deleteCluster(r),l()}catch(K){console.error("删除集群失败:",K)}},L=async(r,K)=>{try{K||G.info("正在同步集群资源...");const T=await w.syncCluster(r);K||G.success(T?.message||"同步完成"),l()}catch(T){K||G.error(T?.message||"同步失败")}},we=async()=>{if(!m)return;const r=m.code||String(m.id);try{o(!0),G.info(`正在导出 ${m.name} 所有命名空间的资源...`),await w.exportAllResources(r),G.success("导出完成,已开始下载"),j(null)}catch(K){G.error(K?.message||"导出失败")}finally{o(!1)}},Z=n.filter(r=>(r.name||"").toLowerCase().includes(d.toLowerCase())||(r.version||"").includes(d)),Se=r=>{switch(r){case"healthy":return e.jsxs(y,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:138:11",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:[e.jsx(ee,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:139:13",className:"h-3 w-3 mr-1"}),"健康"]});case"warning":return e.jsxs(y,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:145:11",variant:"outline",className:"border-amber-500/30 text-amber-400 bg-amber-500/10",children:[e.jsx(Ze,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:146:13",className:"h-3 w-3 mr-1"}),"警告"]});case"error":return e.jsxs(y,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:152:11",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10",children:[e.jsx(me,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:153:13",className:"h-3 w-3 mr-1"}),"异常"]});default:return null}},Q=s?n.find(r=>r.id===s):null;return e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:165:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:167:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:168:9",children:[e.jsx("h1",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:169:11",className:"text-2xl font-bold text-slate-100",children:"集群列表"}),e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:170:11",className:"text-sm text-slate-500 mt-1",children:"管理Kubernetes集群资源"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:172:9",className:"flex items-center gap-2",children:[e.jsxs(A,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:173:11",variant:"outline",className:"border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800",onClick:l,children:[e.jsx(H,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:178:13",className:M("h-4 w-4 mr-2",a&&"animate-spin")}),"刷新"]}),e.jsxs(A,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:181:11",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:()=>{f(null),C(!0)},children:[e.jsx(pt,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:182:13",className:"h-4 w-4 mr-2"}),"添加集群"]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:189:7",className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(_,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:190:9",className:"bg-slate-900 border-slate-800",children:e.jsx(R,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:191:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:192:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:193:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:194:17",className:"text-sm text-slate-500",children:"集群总数"}),e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:195:17",className:"text-2xl font-bold text-slate-100",children:n.length})]}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:197:15",className:"p-3 rounded-lg bg-blue-500/10 text-blue-400",children:e.jsx(V,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:198:17",className:"h-5 w-5"})})]})})}),e.jsx(_,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:203:9",className:"bg-slate-900 border-slate-800",children:e.jsx(R,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:204:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:205:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:206:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:207:17",className:"text-sm text-slate-500",children:"健康集群"}),e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:208:17",className:"text-2xl font-bold text-emerald-400",children:n.filter(r=>r.status==="healthy").length})]}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:212:15",className:"p-3 rounded-lg bg-emerald-500/10 text-emerald-400",children:e.jsx(ee,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:213:17",className:"h-5 w-5"})})]})})}),e.jsx(_,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:218:9",className:"bg-slate-900 border-slate-800",children:e.jsx(R,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:219:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:220:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:221:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:222:17",className:"text-sm text-slate-500",children:"总节点数"}),e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:223:17",className:"text-2xl font-bold text-slate-100",children:n.reduce((r,K)=>r+(K.node_count||0),0)})]}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:227:15",className:"p-3 rounded-lg bg-purple-500/10 text-purple-400",children:e.jsx(Ue,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:228:17",className:"h-5 w-5"})})]})})}),e.jsx(_,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:233:9",className:"bg-slate-900 border-slate-800",children:e.jsx(R,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:234:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:235:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:236:15",children:[e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:237:17",className:"text-sm text-slate-500",children:"总Pod数"}),e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:238:17",className:"text-2xl font-bold text-slate-100",children:n.reduce((r,K)=>r+(K.pod_count||0),0)})]}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:242:15",className:"p-3 rounded-lg bg-cyan-500/10 text-cyan-400",children:e.jsx(ze,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:243:17",className:"h-5 w-5"})})]})})})]}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:251:7",className:"flex items-center gap-3",children:e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:252:9",className:"relative w-80",children:[e.jsx($e,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:253:11",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(B,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:254:11",placeholder:"搜索集群名称或版本...",value:d,onChange:r=>N(r.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"})]})}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:264:7",className:"grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-4",children:a?e.jsx(_,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:266:11",className:"bg-slate-900 border-slate-800 col-span-full",children:e.jsxs(R,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:267:13",className:"p-12 text-center text-slate-500",children:[e.jsx(H,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:268:15",className:"h-6 w-6 animate-spin mx-auto mb-3"}),"加载中..."]})}):Z.length===0?e.jsx(_,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:273:11",className:"bg-slate-900 border-slate-800 col-span-full",children:e.jsx(R,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:274:13",className:"p-12 text-center text-slate-500",children:"暂无集群数据"})}):Z.map(r=>{const K=Number(r.cpu_usage||0),T=Number(r.memory_usage||0),_e=K>0||T>0;return e.jsxs(_,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:282:15",className:M("bg-slate-900 border-slate-800 cursor-pointer transition-all",s===r.id?"border-blue-500 ring-1 ring-blue-500/30":"hover:border-slate-700"),onClick:()=>u(r.id),children:[e.jsx(U,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:292:17",className:"pb-3",children:e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:293:19",className:"flex items-start justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:294:21",className:"flex items-center gap-3",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:295:23",className:"w-10 h-10 rounded-lg bg-blue-500/10 flex items-center justify-center",children:e.jsx(V,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:296:25",className:"h-5 w-5 text-blue-400"})}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:298:23",children:[e.jsx(z,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:299:25",className:"text-base text-slate-100",children:r.name}),e.jsx(pe,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:300:25",className:"text-slate-500",children:r.version})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:303:21",className:"flex items-center gap-1",children:[Se(r.status),e.jsxs(We,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:305:23",children:[e.jsx(qe,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:306:25",asChild:!0,children:e.jsx(A,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:307:27",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-slate-100",onClick:S=>S.stopPropagation(),children:e.jsx(mt,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:313:29",className:"h-4 w-4"})})}),e.jsxs(He,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:316:25",align:"end",className:"w-48 bg-slate-800 border-slate-700",children:[e.jsx(Ve,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:317:27",className:"text-slate-300",children:"操作"}),e.jsx(te,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:318:27",className:"bg-slate-700"}),e.jsxs(O,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:319:27",className:"text-slate-300 focus:bg-slate-700 focus:text-slate-100",children:[e.jsx(Xe,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:320:29",className:"h-4 w-4 mr-2"}),"查看详情"]}),e.jsxs(O,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:323:27",className:"text-slate-300 focus:bg-slate-700 focus:text-slate-100",onClick:S=>{S.stopPropagation(),f(r),C(!0)},children:[e.jsx(Ye,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:331:29",className:"h-4 w-4 mr-2"}),"配置"]}),e.jsxs(O,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:334:27",className:"text-cyan-400 focus:bg-slate-700 focus:text-cyan-300",onClick:S=>{S.stopPropagation(),L(r.id)},children:[e.jsx(H,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:341:29",className:"h-4 w-4 mr-2"}),"同步"]}),e.jsxs(O,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:344:27",className:"text-emerald-400 focus:bg-slate-700 focus:text-emerald-300",onClick:S=>{S.stopPropagation(),p({id:r.id,name:r.name}),i(!0)},children:[e.jsx(Je,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:352:29",className:"h-4 w-4 mr-2"}),"kubectl"]}),e.jsxs(O,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:355:27",className:"text-blue-400 focus:bg-slate-700 focus:text-blue-300",onClick:S=>{S.stopPropagation(),j(r)},children:[e.jsx(bt,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:362:29",className:"h-4 w-4 mr-2"}),"导出资源"]}),e.jsx(te,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:365:27",className:"bg-slate-700"}),e.jsxs(O,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:366:27",className:"text-red-400 focus:bg-slate-700 focus:text-red-400",onClick:S=>{S.stopPropagation(),q(r.id)},children:[e.jsx(ht,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:373:29",className:"h-4 w-4 mr-2"}),"删除"]})]})]})]})]})}),e.jsxs(R,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:381:17",className:"pt-0",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:382:19",className:"grid grid-cols-4 gap-2 mb-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:383:21",className:"text-center p-2 rounded-lg bg-slate-800/50",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:384:23",className:"text-lg font-semibold text-slate-200",children:r.node_count||0}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:385:23",className:"text-xs text-slate-500",children:"节点"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:387:21",className:"text-center p-2 rounded-lg bg-slate-800/50",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:388:23",className:"text-lg font-semibold text-slate-200",children:r.pod_count||0}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:389:23",className:"text-xs text-slate-500",children:"Pod"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:391:21",className:"text-center p-2 rounded-lg bg-slate-800/50",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:392:23",className:"text-lg font-semibold text-slate-200",children:r.service_count||0}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:393:23",className:"text-xs text-slate-500",children:"Service"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:395:21",className:"text-center p-2 rounded-lg bg-slate-800/50",children:[e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:396:23",className:"text-lg font-semibold text-slate-200",children:r.deployment_count||0}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:397:23",className:"text-xs text-slate-500",children:"Deployment"})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:400:19",className:"space-y-2",children:_e?e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:403:25",className:"flex items-center gap-2",children:[e.jsx("span",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:404:27",className:"text-xs text-slate-500 w-10",children:"CPU"}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:405:27",className:"flex-1 h-1.5 bg-slate-800 rounded-full overflow-hidden",children:e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:406:29",className:M("h-full rounded-full",K>80?"bg-red-400":K>60?"bg-amber-400":"bg-emerald-400"),style:{width:`${Math.min(K,100)}%`}})}),e.jsxs("span",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:414:27",className:"text-xs text-slate-400 w-10 text-right",children:[K.toFixed(1),"%"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:416:25",className:"flex items-center gap-2",children:[e.jsx("span",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:417:27",className:"text-xs text-slate-500 w-10",children:"内存"}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:418:27",className:"flex-1 h-1.5 bg-slate-800 rounded-full overflow-hidden",children:e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:419:29",className:M("h-full rounded-full",T>80?"bg-red-400":T>60?"bg-amber-400":"bg-emerald-400"),style:{width:`${Math.min(T,100)}%`}})}),e.jsxs("span",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:427:27",className:"text-xs text-slate-400 w-10 text-right",children:[T.toFixed(1),"%"]})]})]}):e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:431:23",className:"text-xs text-slate-600 text-center",children:["已接入 ",r.node_count||0," 节点 · ",r.pod_count||0," Pod · 资源使用率待采集"]})})]})]},r.id)})}),Q&&e.jsx(gt,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:443:9",cluster:Q,onClose:()=>u(null)}),e.jsx(Pt,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:447:7",open:k,onOpenChange:C,editingCluster:b,onSaved:P}),h&&e.jsx(Tt,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:456:9",open:t,onOpenChange:r=>{i(r),r||p(null)},clusterId:h.id,clusterName:h.name}),m&&e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:469:9",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:()=>j(null),children:e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:470:11",className:"bg-slate-900 border border-slate-700 rounded-lg p-5 w-96 shadow-xl",onClick:r=>r.stopPropagation(),children:[e.jsx("h3",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:471:13",className:"text-base font-semibold text-slate-100 mb-1",children:"导出集群资源"}),e.jsxs("p",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:472:13",className:"text-xs text-slate-400 mb-4",children:["导出 ",m.name," 所有命名空间的 Deployment、Service、Ingress、ConfigMap、Secret 为 tar.gz"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:475:13",className:"flex justify-end gap-2",children:[e.jsx(A,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:476:15",variant:"outline",className:"border-slate-700 text-slate-300",onClick:()=>j(null),children:"取消"}),e.jsx(A,{"code-path":"src/components/kubernetes/KubernetesClusters.tsx:477:15",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:we,disabled:D,children:D?"导出中...":"确认导出"})]})]})})]})}export{Qt as KubernetesClusters}; diff --git a/backend/static/assets/KubernetesNodes-DNrQwI__.js b/backend/static/assets/KubernetesNodes-DNrQwI__.js new file mode 100644 index 0000000..8975e55 --- /dev/null +++ b/backend/static/assets/KubernetesNodes-DNrQwI__.js @@ -0,0 +1 @@ +import{r as t,j as e,B as A,L as y,S as P,I as V,q as W}from"./index-DfyorCky.js";import{C,a as S}from"./card-C55cvSHg.js";import{B as x}from"./badge-xNW8x0G1.js";import{S as $,a as B,b as R,c as T,d as u}from"./select-D5qUzdAs.js";import{T as H,a as U,b,c as o,d as q,e as r}from"./table-5sHV4Akp.js";import{k as M}from"./kubernetes-J8O09fK7.js";import{R as z}from"./refresh-cw-DUB_tAG-.js";import"./index-CWVNW_qu.js";function ee(){const[L,i]=t.useState([]),[c,N]=t.useState(""),[a,k]=t.useState([]),[p,j]=t.useState(!1),[K,_]=t.useState(""),[m,E]=t.useState("all"),g=t.useCallback(async()=>{try{const n=(await M.getClusters())?.list||[];i(n),n.length>0&&!c&&N(String(n[0].id))}catch{i([])}},[]);t.useEffect(()=>{g()},[g]);const h=t.useCallback(async()=>{if(c){j(!0);try{const s=await M.getNodes(c);k(Array.isArray(s)?s:s?.list||[])}catch{k([])}finally{j(!1)}}},[c]);t.useEffect(()=>{h()},[h]);const f=a.filter(s=>(s.name||"").toLowerCase().includes(K.toLowerCase())&&(m==="all"||s.role===m)),F=s=>s==="master"?e.jsx(x,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:52:9",className:"bg-blue-500/20 text-blue-400 border-blue-500/30",children:"Master"}):e.jsx(x,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:53:9",className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",children:"Worker"}),I=s=>s==="Ready"?e.jsx(x,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:57:9",className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",children:s}):e.jsx(x,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:58:9",variant:"destructive",children:s||"Unknown"});return e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:61:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:62:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:63:9",children:[e.jsx("h1",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:64:11",className:"text-2xl font-bold text-slate-100",children:"节点管理"}),e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:65:11",className:"text-sm text-slate-500 mt-1",children:"Kubernetes 集群工作节点状态与资源"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:67:9",className:"flex items-center gap-2",children:[e.jsxs($,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:68:11",value:c,onValueChange:N,children:[e.jsx(B,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:69:13",className:"w-48 h-9 bg-slate-800/50 border-slate-700 text-slate-200",children:e.jsx(R,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:70:15",placeholder:"选择集群"})}),e.jsx(T,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:72:13",className:"bg-slate-800 border-slate-700",children:L.map(s=>e.jsx(u,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:74:17",value:String(s.id),children:s.name},s.id))})]}),e.jsx(A,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:78:11",variant:"outline",size:"icon",className:"h-9 w-9 border-slate-700 text-slate-400",onClick:h,disabled:p,children:p?e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:79:24",className:"h-4 w-4 animate-spin"}):e.jsx(z,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:79:71",className:"h-4 w-4"})})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:84:7",className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"总节点",value:a.length,color:"text-blue-400"},{label:"Master",value:a.filter(s=>s.role==="master").length,color:"text-purple-400"},{label:"Worker",value:a.filter(s=>s.role==="worker").length,color:"text-emerald-400"},{label:"就绪",value:a.filter(s=>s.status==="Ready").length,color:"text-cyan-400"}].map(s=>e.jsx(C,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:91:11",className:"bg-slate-900 border-slate-800",children:e.jsxs(S,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:92:13",className:"p-4",children:[e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:93:15",className:"text-sm text-slate-500",children:s.label}),e.jsx("p",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:94:15",className:`text-2xl font-bold ${s.color}`,children:s.value})]})},s.label))}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:100:7",className:"flex items-center gap-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:101:9",className:"relative w-56",children:[e.jsx(P,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:102:11",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(V,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:103:11",placeholder:"搜索节点...",value:K,onChange:s=>_(s.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200"})]}),e.jsxs($,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:105:9",value:m,onValueChange:E,children:[e.jsx(B,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:106:11",className:"w-32 h-9 bg-slate-800/50 border-slate-700 text-slate-200",children:e.jsx(R,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:107:13"})}),e.jsxs(T,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:109:11",className:"bg-slate-800 border-slate-700",children:[e.jsx(u,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:110:13",value:"all",children:"全部角色"}),e.jsx(u,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:111:13",value:"master",children:"Master"}),e.jsx(u,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:112:13",value:"worker",children:"Worker"})]})]})]}),e.jsx(C,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:117:7",className:"bg-slate-900 border-slate-800",children:e.jsx(S,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:118:9",className:"p-0",children:e.jsxs(H,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:119:11",children:[e.jsx(U,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:120:13",children:e.jsxs(b,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:121:15",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(o,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:122:17",className:"text-slate-400",children:"节点名称"}),e.jsx(o,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:123:17",className:"text-slate-400",children:"IP"}),e.jsx(o,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:124:17",className:"text-slate-400",children:"角色"}),e.jsx(o,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:125:17",className:"text-slate-400",children:"状态"}),e.jsx(o,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:126:17",className:"text-slate-400",children:"配置"}),e.jsx(o,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:127:17",className:"text-slate-400",children:"使用率"}),e.jsx(o,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:128:17",className:"text-slate-400",children:"Pods"}),e.jsx(o,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:129:17",className:"text-slate-400",children:"Kubelet"})]})}),e.jsx(q,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:132:13",children:p?e.jsx(b,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:134:17",children:e.jsxs(r,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:134:27",colSpan:8,className:"text-center text-slate-500 py-12",children:[e.jsx(y,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:134:95",className:"h-5 w-5 animate-spin mx-auto mb-2"}),"加载中..."]})}):f.length===0?e.jsx(b,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:136:17",children:e.jsxs(r,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:136:27",colSpan:8,className:"text-center text-slate-500 py-12",children:[e.jsx(W,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:136:95",className:"h-8 w-8 mx-auto mb-2 opacity-50"}),c?"暂无节点数据":"请选择集群"]})}):f.map(s=>e.jsxs(b,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:139:19",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(r,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:140:21",className:"font-medium text-slate-200",children:s.name}),e.jsx(r,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:141:21",children:e.jsx("code",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:141:32",className:"text-sm text-slate-300 bg-slate-800 px-1.5 py-0.5 rounded",children:s.ip||"-"})}),e.jsx(r,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:142:21",children:F(s.role)}),e.jsx(r,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:143:21",children:I(s.status)}),e.jsxs(r,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:144:21",className:"text-sm text-slate-400",children:[s.cpu?`${s.cpu}核`:"-"," / ",s.memory?`${Math.round(s.memory/1024)}GB`:"-"]}),e.jsx(r,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:147:21",children:(()=>{const n=s.cpu_usage||0,d=s.memory_usage||0,v=l=>l>=85?"bg-red-500":l>=60?"bg-yellow-500":"bg-emerald-500",w=l=>l>=85?"text-red-400":l>=60?"text-yellow-400":"text-emerald-400";return e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:154:27",className:"flex flex-col gap-1 min-w-[120px]",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:155:29",className:"flex items-center gap-2",children:[e.jsx("span",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:156:31",className:"text-xs text-slate-500 w-7",children:"CPU"}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:157:31",className:"flex-1 h-1.5 rounded-full bg-slate-700/50 overflow-hidden",children:e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:158:33",className:`h-full rounded-full ${v(n)}`,style:{width:`${Math.min(n,100)}%`}})}),e.jsxs("span",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:160:31",className:`text-xs w-9 text-right ${w(n)}`,children:[n.toFixed(0),"%"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:162:29",className:"flex items-center gap-2",children:[e.jsx("span",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:163:31",className:"text-xs text-slate-500 w-7",children:"Mem"}),e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:164:31",className:"flex-1 h-1.5 rounded-full bg-slate-700/50 overflow-hidden",children:e.jsx("div",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:165:33",className:`h-full rounded-full ${v(d)}`,style:{width:`${Math.min(d,100)}%`}})}),e.jsxs("span",{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:167:31",className:`text-xs w-9 text-right ${w(d)}`,children:[d.toFixed(0),"%"]})]})]})})()}),e.jsxs(r,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:173:21",className:"text-sm text-slate-400",children:[s.pod_count||0," / ",s.max_pods||"-"]}),e.jsx(r,{"code-path":"src/components/kubernetes/KubernetesNodes.tsx:174:21",className:"text-xs text-slate-500",children:s.kubelet_version||"-"})]},s.id))})]})})})]})}export{ee as KubernetesNodes}; diff --git a/backend/static/assets/MetricsExplorer-CQYGy4Dt.js b/backend/static/assets/MetricsExplorer-CQYGy4Dt.js new file mode 100644 index 0000000..7c624ce --- /dev/null +++ b/backend/static/assets/MetricsExplorer-CQYGy4Dt.js @@ -0,0 +1 @@ +import{r as l,h as u,j as e,S as I,I as z,B as P,K as B,A as y,G as F,N as K,o as V}from"./index-DfyorCky.js";import{C as b,a as M}from"./card-C55cvSHg.js";import{S as q,a as G,b as H,c as Q,d as U}from"./select-D5qUzdAs.js";import{F as W}from"./funnel-D2FHr15I.js";import{P as J}from"./plus-CUG-9kpu.js";import{H as v}from"./hard-drive-BbPmnARR.js";import"./index-CWVNW_qu.js";const N={cpu:{label:"CPU",icon:e.jsx(V,{"code-path":"src/pages/MetricsExplorer.tsx:34:30",className:"h-4 w-4"})},memory:{label:"内存",icon:e.jsx(v,{"code-path":"src/pages/MetricsExplorer.tsx:35:32",className:"h-4 w-4"})},disk:{label:"磁盘",icon:e.jsx(v,{"code-path":"src/pages/MetricsExplorer.tsx:36:30",className:"h-4 w-4"})},network:{label:"网络",icon:e.jsx(K,{"code-path":"src/pages/MetricsExplorer.tsx:37:33",className:"h-4 w-4"})},middleware:{label:"中间件",icon:e.jsx(F,{"code-path":"src/pages/MetricsExplorer.tsx:38:37",className:"h-4 w-4"})},device:{label:"设备",icon:e.jsx(y,{"code-path":"src/pages/MetricsExplorer.tsx:39:32",className:"h-4 w-4"})}};function ae(){const[n,w]=l.useState([]),[j,S]=l.useState([]),[x,C]=l.useState(""),[o,E]=l.useState([]),[k,f]=l.useState([]),[O,T]=l.useState(!0),[m,_]=l.useState(""),L=l.useCallback(async()=>{try{const s=await u.get("/metrics/targets?page_size=200");w(s?.list||[])}catch{}finally{T(!1)}},[]),R=l.useCallback(async()=>{try{const s=await u.get("/metrics/names");S(s||[])}catch{}},[]);l.useEffect(()=>{L(),R()},[]),l.useEffect(()=>{if(!x||o.length===0||!n.find(c=>String(c.id)===x))return;const t=Math.floor(Date.now()/1e3),r=t-3600;Promise.all(o.map(c=>u.get("/metrics/query",{target_id:x,metric_name:c,from:String(r),to:String(t),limit:200}).then(a=>Array.isArray(a)?a:[]).catch(()=>[]))).then(c=>{f(c.flat())})},[x,o,n]);const $=m?j.filter(s=>s.toLowerCase().includes(m.toLowerCase())):j,g=n.find(s=>String(s.id)===x),A=$.reduce((s,t)=>{const r=t.split("_")[0]||"other";return s[r]||(s[r]=[]),s[r].push(t),s},{}),d={};k.forEach(s=>{d[s.timestamp]||(d[s.timestamp]={}),d[s.timestamp][s.metric_name]=s.value});const p=Object.keys(d).map(Number).sort((s,t)=>s-t),D=Math.max(1,...Object.values(d).flatMap(s=>Object.values(s))),h=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#ec4899","#06b6d4","#f97316"];return e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:118:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:120:7",className:"flex items-center gap-4 flex-wrap",children:[e.jsxs(q,{"code-path":"src/pages/MetricsExplorer.tsx:121:9",value:x,onValueChange:C,children:[e.jsx(G,{"code-path":"src/pages/MetricsExplorer.tsx:122:11",className:"w-64 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(H,{"code-path":"src/pages/MetricsExplorer.tsx:123:13",placeholder:O?"加载中...":"选择监控目标..."})}),e.jsx(Q,{"code-path":"src/pages/MetricsExplorer.tsx:125:11",className:"bg-slate-800 border-slate-700 text-slate-200 max-h-80",children:n.map(s=>e.jsx(U,{"code-path":"src/pages/MetricsExplorer.tsx:127:15",value:String(s.id),children:e.jsxs("span",{"code-path":"src/pages/MetricsExplorer.tsx:128:17",className:"flex items-center gap-2",children:[e.jsx("span",{"code-path":"src/pages/MetricsExplorer.tsx:129:19",className:`inline-block w-1.5 h-1.5 rounded-full ${s.status==="online"?"bg-emerald-400":"bg-slate-500"}`}),s.name," (",s.ip||s.type,")"]})},s.id))})]}),e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:137:9",className:"relative flex-1 max-w-sm",children:[e.jsx(I,{"code-path":"src/pages/MetricsExplorer.tsx:138:11",className:"absolute left-2.5 top-2 h-4 w-4 text-slate-500"}),e.jsx(z,{"code-path":"src/pages/MetricsExplorer.tsx:139:11",className:"pl-8 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9",placeholder:"搜索指标...",value:m,onChange:s=>_(s.target.value)})]}),e.jsx(P,{"code-path":"src/pages/MetricsExplorer.tsx:146:9",variant:"ghost",size:"sm",onClick:()=>{E([]),f([])},children:"清除"})]}),x?e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:159:9",className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsx(b,{"code-path":"src/pages/MetricsExplorer.tsx:161:11",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] lg:col-span-1",children:e.jsxs(M,{"code-path":"src/pages/MetricsExplorer.tsx:162:13",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:163:15",className:"flex items-center gap-2 mb-3",children:[e.jsx(B,{"code-path":"src/pages/MetricsExplorer.tsx:164:17",className:"h-4 w-4 text-[var(--dg-text-muted)]"}),e.jsx("h3",{"code-path":"src/pages/MetricsExplorer.tsx:165:17",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:"指标列表"}),e.jsxs("span",{"code-path":"src/pages/MetricsExplorer.tsx:166:17",className:"text-xs text-[var(--dg-text-muted)] ml-auto",children:[o.length," 已选"]})]}),e.jsx("div",{"code-path":"src/pages/MetricsExplorer.tsx:168:15",className:"space-y-4 max-h-[60vh] overflow-y-auto",children:Object.entries(A).map(([s,t])=>e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:170:19",children:[e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:171:21",className:"flex items-center gap-1.5 mb-1.5 text-xs text-[var(--dg-text-muted)]",children:[N[s]?.icon,e.jsx("span",{"code-path":"src/pages/MetricsExplorer.tsx:173:23",children:N[s]?.label||s})]}),e.jsx("div",{"code-path":"src/pages/MetricsExplorer.tsx:175:21",className:"space-y-0.5",children:t.map(r=>{const c=o.includes(r);return e.jsxs("label",{"code-path":"src/pages/MetricsExplorer.tsx:179:27",className:`flex items-center gap-2 px-2 py-1 rounded cursor-pointer text-xs transition-colors ${c?"bg-blue-500/10 text-blue-300":"text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)]"}`,children:[e.jsx("input",{"code-path":"src/pages/MetricsExplorer.tsx:180:29",type:"checkbox",className:"rounded border-slate-600 bg-slate-800 accent-blue-500",checked:c,onChange:()=>{E(a=>c?a.filter(i=>i!==r):[...a,r])}}),e.jsx("span",{"code-path":"src/pages/MetricsExplorer.tsx:190:29",className:"truncate",children:r})]},r)})})]},s))})]})}),e.jsx(b,{"code-path":"src/pages/MetricsExplorer.tsx:202:11",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] lg:col-span-2",children:e.jsxs(M,{"code-path":"src/pages/MetricsExplorer.tsx:203:13",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:204:15",className:"flex items-center gap-2 mb-3",children:[e.jsx(y,{"code-path":"src/pages/MetricsExplorer.tsx:205:17",className:"h-4 w-4 text-[var(--dg-text-muted)]"}),e.jsxs("h3",{"code-path":"src/pages/MetricsExplorer.tsx:206:17",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:[g?.name||""," — 最近 1 小时"]})]}),o.length===0?e.jsx("div",{"code-path":"src/pages/MetricsExplorer.tsx:211:17",className:"h-64 flex items-center justify-center text-sm text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-lg",children:e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:212:19",className:"text-center",children:[e.jsx(J,{"code-path":"src/pages/MetricsExplorer.tsx:213:21",className:"h-8 w-8 text-slate-600 mx-auto mb-2"}),"请从左侧勾选指标"]})}):p.length===0?e.jsx("div",{"code-path":"src/pages/MetricsExplorer.tsx:218:17",className:"h-64 flex items-center justify-center text-sm text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-lg",children:"暂无数据"}):e.jsx("div",{"code-path":"src/pages/MetricsExplorer.tsx:222:17",className:"h-80 overflow-x-auto",children:e.jsxs("svg",{"code-path":"src/pages/MetricsExplorer.tsx:223:19",viewBox:`0 0 ${Math.max(p.length*4,400)} 300`,className:"w-full h-full min-w-[400px]",children:[[0,25,50,75,100].map(s=>e.jsx("line",{"code-path":"src/pages/MetricsExplorer.tsx:226:23",x1:"0",y1:300-s/100*260,x2:Math.max(p.length*4,400),y2:300-s/100*260,stroke:"#1e293b",strokeDasharray:"3 3"},s)),o.map((s,t)=>{const r=p.map((a,i)=>({x:i*4+2,y:300-(d[a][s]??0)/D*260})).filter(a=>d[p[Math.round((a.x-2)/4)]]?.[s]!=null);if(r.length<2)return null;const c=r.map((a,i)=>`${i===0?"M":"L"}${a.x} ${a.y}`).join(" ");return e.jsx("g",{"code-path":"src/pages/MetricsExplorer.tsx:236:25",children:e.jsx("path",{"code-path":"src/pages/MetricsExplorer.tsx:237:27",d:c,fill:"none",stroke:h[t%h.length],strokeWidth:"1.5"})},s)}),p.filter((s,t)=>t%15===0).map((s,t)=>e.jsx("text",{"code-path":"src/pages/MetricsExplorer.tsx:243:23",x:t*60+2,y:"295",fill:"#475569",fontSize:"9",children:new Date(s*1e3).toLocaleTimeString("zh-CN",{hour:"2-digit",minute:"2-digit"})},s))]})}),o.length>0&&e.jsx("div",{"code-path":"src/pages/MetricsExplorer.tsx:252:17",className:"flex flex-wrap gap-3 mt-3",children:o.map((s,t)=>e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:254:21",className:"flex items-center gap-1.5 text-xs text-[var(--dg-text-secondary)]",children:[e.jsx("span",{"code-path":"src/pages/MetricsExplorer.tsx:255:23",className:"w-2.5 h-2.5 rounded-full",style:{backgroundColor:h[t%h.length]}}),s]},s))})]})})]}):e.jsx(b,{"code-path":"src/pages/MetricsExplorer.tsx:152:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/MetricsExplorer.tsx:153:11",className:"p-12 text-center",children:[e.jsx(W,{"code-path":"src/pages/MetricsExplorer.tsx:154:13",className:"h-12 w-12 text-slate-600 mx-auto mb-4"}),e.jsx("p",{"code-path":"src/pages/MetricsExplorer.tsx:155:13",className:"text-[var(--dg-text-muted)]",children:"请先选择监控目标,然后勾选要查看的指标"})]})}),g&&Object.keys(g.latest_metrics||{}).length>0&&e.jsx("div",{"code-path":"src/pages/MetricsExplorer.tsx:268:9",className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3",children:Object.entries(g.latest_metrics).map(([s,t])=>e.jsxs("div",{"code-path":"src/pages/MetricsExplorer.tsx:270:13",className:"bg-[var(--dg-bg-secondary)] rounded-lg p-3 border border-[var(--dg-border)] text-center",children:[e.jsx("p",{"code-path":"src/pages/MetricsExplorer.tsx:271:15",className:"text-[10px] text-[var(--dg-text-muted)] truncate",children:s}),e.jsx("p",{"code-path":"src/pages/MetricsExplorer.tsx:272:15",className:"text-lg font-bold text-[var(--dg-text-primary)]",children:typeof t=="number"?t.toFixed(1):"--"})]},s))})]})}export{ae as MetricsExplorer,ae as default}; diff --git a/backend/static/assets/MonitorCenter-Cdfxw79h.js b/backend/static/assets/MonitorCenter-Cdfxw79h.js new file mode 100644 index 0000000..f6a38f6 --- /dev/null +++ b/backend/static/assets/MonitorCenter-Cdfxw79h.js @@ -0,0 +1 @@ +import{g as X,r as i,h as L,j as e,L as O,A as R,G as B,q as K,D as W,y as Ne,B as w,b as Y,c as Z,d as J,e as ee,I as y,f as te,a as ve,O as I,x as je,o as be,X as Se}from"./index-DfyorCky.js";import{HostMonitor as ye}from"./HostMonitor-C63FMElJ.js";import{C as h,a as M}from"./card-C55cvSHg.js";import{B as u}from"./badge-xNW8x0G1.js";import{C as fe}from"./circle-DOZr6_68.js";import{L as j}from"./label-BK0h2apY.js";import{S as se,a as ae,b as re,c as oe,d as A}from"./select-D5qUzdAs.js";import{T as ce,a as de,b as $,c as l,d as ie,e as p}from"./table-5sHV4Akp.js";import{H as we}from"./hard-drive-BbPmnARR.js";import{P as ne}from"./plus-CUG-9kpu.js";import{T as xe}from"./trash-2-Dx32pOzT.js";import{S as Pe}from"./switch-CGiGgOnh.js";import{t as C}from"./index-a3ybMjbR.js";import{s as F}from"./monitor-BAaBXIsC.js";import{A as Ce}from"./arrow-up-down-DnvTt5VG.js";import{R as _e}from"./refresh-cw-DUB_tAG-.js";import{C as Te}from"./circle-x-DK79Dhg2.js";import{C as ke}from"./circle-check-DWcXrx2k.js";import"./agent-DqqIRCQX.js";import"./tabs-CIh_yD4s.js";import"./disc-EsE6x5Oh.js";import"./generateCategoricalChart-6v9BPbG2.js";import"./AreaChart-B2zlWfdX.js";import"./square-pen-BxUFAe0F.js";import"./index-CWVNW_qu.js";const De=[["path",{d:"M16.247 7.761a6 6 0 0 1 0 8.478",key:"1fwjs5"}],["path",{d:"M19.075 4.933a10 10 0 0 1 0 14.134",key:"ehdyv1"}],["path",{d:"M4.925 19.067a10 10 0 0 1 0-14.134",key:"1q22gi"}],["path",{d:"M7.753 16.239a6 6 0 0 1 0-8.478",key:"r2q7qm"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],le=X("radio",De);const qe=[["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6.01 18H6",key:"19vcac"}],["path",{d:"M10.01 18H10",key:"uamcmx"}],["path",{d:"M15 10v4",key:"qjz1xs"}],["path",{d:"M17.84 7.17a4 4 0 0 0-5.66 0",key:"1rif40"}],["path",{d:"M20.66 4.34a8 8 0 0 0-11.31 0",key:"6a5xfq"}]],U=X("router",qe);function Fe(t){return t==null||t===0?"--":t>1e9?`${(t/1e9).toFixed(1)} GB`:t>1e6?`${(t/1e6).toFixed(1)} MB`:t>1e3?`${(t/1e3).toFixed(1)} KB`:`${t} B`}function E(t){return t==null||Number.isNaN(t)?"--":`${(t*100).toFixed(1)}%`}function D(t,n=0){return t==null||Number.isNaN(t)?"--":t.toFixed(n)}function Le(t){switch(t){case"online":return"text-emerald-400";case"warning":return"text-amber-400";case"error":return"text-red-400";default:return"text-slate-500"}}function Ie(t){switch(t){case"online":return"bg-emerald-400";case"warning":return"bg-amber-400";case"error":return"bg-red-400";default:return"bg-slate-500"}}function $e(){const[t,n]=i.useState([]),[d,N]=i.useState(!0),[v,_]=i.useState(""),T=i.useCallback(async()=>{try{N(!0),_("");const r=await L.get("/metrics/targets",{type:"middleware",page_size:200});n(r?.list||[])}catch(r){_(r.message||"加载失败"),n([])}finally{N(!1)}},[]);i.useEffect(()=>{T()},[]);const b=t.filter(r=>r.type==="redis"||r.name?.toLowerCase().includes("redis")),o=t.filter(r=>r.type==="mysql"||r.name?.toLowerCase().includes("mysql")),x=b.find(r=>r.status==="online")||b[0],c=x?.latest_metrics||{},m=o.find(r=>r.status==="online")||o[0],S=m?.latest_metrics||{};return e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:96:5",className:"space-y-6",children:[d&&e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:98:9",className:"flex items-center justify-center py-12",children:[e.jsx(O,{"code-path":"src/pages/MiddlewareMonitor.tsx:99:11",className:"h-6 w-6 animate-spin text-slate-500 mr-2"}),e.jsx("span",{"code-path":"src/pages/MiddlewareMonitor.tsx:100:11",className:"text-sm text-[var(--dg-text-muted)]",children:"正在加载中间件指标..."})]}),v&&!d&&e.jsx(h,{"code-path":"src/pages/MiddlewareMonitor.tsx:105:9",className:"bg-[var(--dg-bg-secondary)] border-red-500/30",children:e.jsxs(M,{"code-path":"src/pages/MiddlewareMonitor.tsx:106:11",className:"p-6 text-center",children:[e.jsx(R,{"code-path":"src/pages/MiddlewareMonitor.tsx:107:13",className:"h-8 w-8 text-red-400 mx-auto mb-2"}),e.jsx("p",{"code-path":"src/pages/MiddlewareMonitor.tsx:108:13",className:"text-sm text-red-400",children:v}),e.jsx("p",{"code-path":"src/pages/MiddlewareMonitor.tsx:109:13",className:"text-xs text-[var(--dg-text-muted)] mt-2",children:"请确认后端服务可用且已配置中间件采集"})]})}),!d&&!v&&t.length===0&&e.jsx(h,{"code-path":"src/pages/MiddlewareMonitor.tsx:115:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/MiddlewareMonitor.tsx:116:11",className:"p-12 text-center",children:[e.jsx(B,{"code-path":"src/pages/MiddlewareMonitor.tsx:117:13",className:"h-12 w-12 text-slate-600 mx-auto mb-4"}),e.jsx("p",{"code-path":"src/pages/MiddlewareMonitor.tsx:118:13",className:"text-sm text-[var(--dg-text-muted)]",children:"暂无中间件监控目标"}),e.jsx("p",{"code-path":"src/pages/MiddlewareMonitor.tsx:119:13",className:"text-xs text-[var(--dg-text-muted)] mt-2",children:"需在 Agent 配置 Redis / MySQL 连接信息后启用采集"})]})}),e.jsx(h,{"code-path":"src/pages/MiddlewareMonitor.tsx:125:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/MiddlewareMonitor.tsx:126:9",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:127:11",className:"flex items-center gap-2 mb-4",children:[e.jsx(B,{"code-path":"src/pages/MiddlewareMonitor.tsx:128:13",className:"h-4 w-4 text-red-400"}),e.jsx("h3",{"code-path":"src/pages/MiddlewareMonitor.tsx:129:13",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:"Redis 监控"}),x&&e.jsxs(u,{"code-path":"src/pages/MiddlewareMonitor.tsx:131:15",variant:"outline",className:"ml-auto text-[10px] border-[var(--dg-border)] text-[var(--dg-text-muted)]",children:[x.name," (",x.ip,")"]})]}),x?e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:139:13",className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(f,{"code-path":"src/pages/MiddlewareMonitor.tsx:140:15",label:"连接数",value:D(c.redis_connected_clients)}),e.jsx(f,{"code-path":"src/pages/MiddlewareMonitor.tsx:144:15",label:"内存",value:Fe(c.redis_used_memory)}),e.jsx(f,{"code-path":"src/pages/MiddlewareMonitor.tsx:148:15",label:"命中率",value:E(c.redis_hit_rate)}),e.jsx(f,{"code-path":"src/pages/MiddlewareMonitor.tsx:152:15",label:"QPS",value:D(c.redis_qps,0)})]}):e.jsx("p",{"code-path":"src/pages/MiddlewareMonitor.tsx:137:13",className:"text-sm text-[var(--dg-text-muted)] mb-4",children:"需在 Agent 配置 Redis 连接地址和密码后启用采集。"})]})}),e.jsx(h,{"code-path":"src/pages/MiddlewareMonitor.tsx:162:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/MiddlewareMonitor.tsx:163:9",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:164:11",className:"flex items-center gap-2 mb-4",children:[e.jsx(K,{"code-path":"src/pages/MiddlewareMonitor.tsx:165:13",className:"h-4 w-4 text-blue-400"}),e.jsx("h3",{"code-path":"src/pages/MiddlewareMonitor.tsx:166:13",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:"MySQL 监控"}),m&&e.jsxs(u,{"code-path":"src/pages/MiddlewareMonitor.tsx:168:15",variant:"outline",className:"ml-auto text-[10px] border-[var(--dg-border)] text-[var(--dg-text-muted)]",children:[m.name," (",m.ip,")"]})]}),m?e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:176:13",className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(f,{"code-path":"src/pages/MiddlewareMonitor.tsx:177:15",label:"连接数",value:D(S.mysql_connections)}),e.jsx(f,{"code-path":"src/pages/MiddlewareMonitor.tsx:181:15",label:"QPS",value:D(S.mysql_qps,1)}),e.jsx(f,{"code-path":"src/pages/MiddlewareMonitor.tsx:185:15",label:"慢查询",value:D(S.mysql_slow_queries)}),e.jsx(f,{"code-path":"src/pages/MiddlewareMonitor.tsx:189:15",label:"缓冲池命中率",value:E(S.mysql_buffer_hit_rate)})]}):e.jsx("p",{"code-path":"src/pages/MiddlewareMonitor.tsx:174:13",className:"text-sm text-[var(--dg-text-muted)] mb-4",children:"需在 Agent 配置 MySQL 连接地址、用户名和密码后启用采集。"})]})}),t.length>0&&e.jsx(h,{"code-path":"src/pages/MiddlewareMonitor.tsx:200:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/MiddlewareMonitor.tsx:201:11",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:202:13",className:"flex items-center gap-2 mb-4",children:[e.jsx(R,{"code-path":"src/pages/MiddlewareMonitor.tsx:203:15",className:"h-4 w-4 text-[var(--dg-text-muted)]"}),e.jsxs("h3",{"code-path":"src/pages/MiddlewareMonitor.tsx:204:15",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:["中间件实例(",t.length,")"]})]}),e.jsx("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:208:13",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:t.map(r=>e.jsx(He,{"code-path":"src/pages/MiddlewareMonitor.tsx:210:17",target:r},r.id))})]})}),t.filter(r=>!b.includes(r)&&!o.includes(r)).length>0&&e.jsx("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:219:9",className:"space-y-4",children:t.filter(r=>!b.includes(r)&&!o.includes(r)).map(r=>e.jsx(h,{"code-path":"src/pages/MiddlewareMonitor.tsx:223:15",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/MiddlewareMonitor.tsx:224:17",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:225:19",className:"flex items-center gap-2 mb-3",children:[e.jsx(fe,{"code-path":"src/pages/MiddlewareMonitor.tsx:226:21",className:`h-3 w-3 ${Le(r.status)}`}),e.jsx("h3",{"code-path":"src/pages/MiddlewareMonitor.tsx:227:21",className:"text-sm font-medium text-[var(--dg-text-primary)] capitalize",children:r.type}),e.jsxs(u,{"code-path":"src/pages/MiddlewareMonitor.tsx:228:21",variant:"outline",className:"text-[10px] border-[var(--dg-border)] text-[var(--dg-text-muted)]",children:[r.name," (",r.ip,")"]})]}),Object.keys(r.latest_metrics||{}).length>0?e.jsx("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:233:21",className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Object.entries(r.latest_metrics).map(([g,k])=>e.jsx(f,{"code-path":"src/pages/MiddlewareMonitor.tsx:235:25",label:g,value:D(k,1)},g))}):e.jsx("p",{"code-path":"src/pages/MiddlewareMonitor.tsx:239:21",className:"text-xs text-[var(--dg-text-muted)]",children:"暂无指标数据"})]})},r.id))})]})}function f({label:t,value:n}){return e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:253:5",className:"bg-[var(--dg-bg-tertiary)] rounded-lg p-3 text-center",children:[e.jsx("p",{"code-path":"src/pages/MiddlewareMonitor.tsx:254:7",className:"text-xs text-[var(--dg-text-muted)]",children:t}),e.jsx("p",{"code-path":"src/pages/MiddlewareMonitor.tsx:255:7",className:"text-lg font-bold text-[var(--dg-text-primary)]",children:n})]})}function He({target:t}){const n=t.latest_metrics||{},d=Object.keys(n).length;return e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:266:5",className:"bg-[var(--dg-bg-tertiary)] rounded-lg p-3 border border-[var(--dg-border)] hover:border-[var(--dg-border)]/80 transition-colors",children:[e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:267:7",className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:268:9",className:"flex items-center gap-2 min-w-0",children:[e.jsx("span",{"code-path":"src/pages/MiddlewareMonitor.tsx:269:11",className:`inline-block w-2 h-2 rounded-full ${Ie(t.status)}`}),e.jsx("span",{"code-path":"src/pages/MiddlewareMonitor.tsx:270:11",className:"text-sm font-medium text-[var(--dg-text-primary)] truncate",children:t.name})]}),e.jsx(u,{"code-path":"src/pages/MiddlewareMonitor.tsx:272:9",variant:"outline",className:`text-[10px] capitalize ${t.status==="online"?"border-emerald-400/50 text-emerald-400":"border-[var(--dg-border)] text-[var(--dg-text-muted)]"}`,children:t.status})]}),e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:279:7",className:"text-xs text-[var(--dg-text-muted)] mb-2",children:[t.ip," · ",t.type]}),d>0?e.jsxs("div",{"code-path":"src/pages/MiddlewareMonitor.tsx:283:9",className:"flex flex-wrap gap-1.5",children:[Object.entries(n).slice(0,4).map(([N,v])=>e.jsxs("span",{"code-path":"src/pages/MiddlewareMonitor.tsx:285:13",className:"inline-flex items-center gap-1 text-[10px] bg-[var(--dg-bg-primary)] rounded px-1.5 py-0.5 text-[var(--dg-text-secondary)]",children:[e.jsx("span",{"code-path":"src/pages/MiddlewareMonitor.tsx:286:15",className:"text-[var(--dg-text-muted)]",children:N}),e.jsx("span",{"code-path":"src/pages/MiddlewareMonitor.tsx:287:15",className:"font-mono font-medium text-[var(--dg-text-primary)]",children:typeof v=="number"?v.toFixed(1):v})]},N)),d>4&&e.jsxs("span",{"code-path":"src/pages/MiddlewareMonitor.tsx:293:13",className:"text-[10px] text-[var(--dg-text-muted)]",children:["+",d-4," 项"]})]}):e.jsx("p",{"code-path":"src/pages/MiddlewareMonitor.tsx:297:9",className:"text-[10px] text-[var(--dg-text-muted)]",children:"暂无指标"})]})}const G={name:"",ip:"",port:161,snmp_version:"v2c",community:"public",template_id:""};function Oe(){const[t,n]=i.useState({total:0,online:0,abnormal:0}),[d,N]=i.useState([]),[v,_]=i.useState(!0),[T,b]=i.useState(!1),[o,x]=i.useState({...G}),[c,m]=i.useState(!1),S=i.useCallback(async()=>{try{const a=await L.get("/snmp/stats");n(a)}catch{}},[]),r=i.useCallback(async()=>{try{const a=await L.get("/snmp/devices");N(a.list??[])}catch{N([])}finally{_(!1)}},[]),g=i.useCallback(()=>{S(),r()},[S,r]);i.useEffect(()=>{g()},[g]);const k=async()=>{if(!(!o.name.trim()||!o.ip.trim())){m(!0);try{await L.post("/snmp/devices",{name:o.name.trim(),ip:o.ip.trim(),port:Number(o.port),snmp_version:o.snmp_version,community:o.community.trim(),template_id:o.template_id?Number(o.template_id):0}),b(!1),x({...G}),g()}catch{}finally{m(!1)}}},H=async a=>{try{await L.delete(`/snmp/devices/${a}`),g()}catch{}},P=a=>a==="online"?e.jsx(u,{"code-path":"src/pages/SNMPMonitor.tsx:146:14",className:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",children:"在线"}):a==="abnormal"?e.jsx(u,{"code-path":"src/pages/SNMPMonitor.tsx:149:14",className:"bg-red-500/15 text-red-400 border-red-500/30",children:"异常"}):e.jsx(u,{"code-path":"src/pages/SNMPMonitor.tsx:151:12",className:"bg-slate-500/15 text-slate-400 border-slate-500/30",children:"离线"});return e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:156:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:158:7",className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(h,{"code-path":"src/pages/SNMPMonitor.tsx:159:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/SNMPMonitor.tsx:160:11",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:161:13",className:"flex items-center gap-2 mb-3",children:[e.jsx(U,{"code-path":"src/pages/SNMPMonitor.tsx:162:15",className:"h-4 w-4 text-cyan-400"}),e.jsx("h3",{"code-path":"src/pages/SNMPMonitor.tsx:163:15",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:"网络设备"})]}),e.jsx("p",{"code-path":"src/pages/SNMPMonitor.tsx:165:13",className:"text-xs text-[var(--dg-text-muted)] mb-3",children:"交换机 / 路由器 / 防火墙"}),e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:166:13",className:"space-y-2",children:[e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:167:15",className:"flex justify-between text-sm",children:[e.jsx("span",{"code-path":"src/pages/SNMPMonitor.tsx:168:17",className:"text-[var(--dg-text-muted)]",children:"设备总数"}),e.jsx("span",{"code-path":"src/pages/SNMPMonitor.tsx:169:17",className:"text-[var(--dg-text-primary)] font-mono",children:t.total})]}),e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:171:15",className:"flex justify-between text-sm",children:[e.jsx("span",{"code-path":"src/pages/SNMPMonitor.tsx:172:17",className:"text-[var(--dg-text-muted)]",children:"在线"}),e.jsx("span",{"code-path":"src/pages/SNMPMonitor.tsx:173:17",className:"text-emerald-400 font-mono",children:t.online})]})]})]})}),e.jsx(h,{"code-path":"src/pages/SNMPMonitor.tsx:179:9",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/SNMPMonitor.tsx:180:11",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:181:13",className:"flex items-center gap-2 mb-3",children:[e.jsx(we,{"code-path":"src/pages/SNMPMonitor.tsx:182:15",className:"h-4 w-4 text-purple-400"}),e.jsx("h3",{"code-path":"src/pages/SNMPMonitor.tsx:183:15",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:"服务器硬件"})]}),e.jsx("p",{"code-path":"src/pages/SNMPMonitor.tsx:185:13",className:"text-xs text-[var(--dg-text-muted)] mb-3",children:"iLO / iDRAC / IPMI"}),e.jsx("div",{"code-path":"src/pages/SNMPMonitor.tsx:186:13",className:"space-y-2",children:e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:187:15",className:"flex justify-between text-sm",children:[e.jsx("span",{"code-path":"src/pages/SNMPMonitor.tsx:188:17",className:"text-[var(--dg-text-muted)]",children:"异常"}),e.jsx("span",{"code-path":"src/pages/SNMPMonitor.tsx:189:17",className:"text-red-400 font-mono",children:t.abnormal})]})})]})})]}),e.jsx(h,{"code-path":"src/pages/SNMPMonitor.tsx:197:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/SNMPMonitor.tsx:198:9",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:199:11",className:"flex items-center gap-2 mb-3",children:[e.jsx(le,{"code-path":"src/pages/SNMPMonitor.tsx:200:13",className:"h-4 w-4 text-[var(--dg-text-muted)]"}),e.jsx("h3",{"code-path":"src/pages/SNMPMonitor.tsx:201:13",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:"OID 监控模板"})]}),e.jsx("p",{"code-path":"src/pages/SNMPMonitor.tsx:203:11",className:"text-sm text-[var(--dg-text-muted)]",children:"支持 Zabbix 兼容的 SNMP OID 模板(XML 格式),内置思科/H3C/华为交换机模板、服务器硬件监控模板。"}),e.jsx("div",{"code-path":"src/pages/SNMPMonitor.tsx:206:11",className:"mt-3 grid grid-cols-2 md:grid-cols-4 gap-2 text-xs text-[var(--dg-text-secondary)]",children:["思科交换机","H3C S5000","华为交换机","iLO/Dell"].map(a=>e.jsx("div",{"code-path":"src/pages/SNMPMonitor.tsx:208:15",className:"bg-[var(--dg-bg-tertiary)] rounded px-2 py-1 text-center border border-[var(--dg-border)]",children:a},a))})]})}),e.jsx(h,{"code-path":"src/pages/SNMPMonitor.tsx:220:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/SNMPMonitor.tsx:221:9",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:222:11",className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:223:13",className:"flex items-center gap-2",children:[e.jsx(U,{"code-path":"src/pages/SNMPMonitor.tsx:224:15",className:"h-4 w-4 text-cyan-400"}),e.jsxs("h3",{"code-path":"src/pages/SNMPMonitor.tsx:225:15",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:["SNMP 设备列表",!v&&e.jsxs("span",{"code-path":"src/pages/SNMPMonitor.tsx:228:19",className:"ml-2 text-xs text-[var(--dg-text-muted)] font-normal",children:["(",d.length," 台)"]})]})]}),e.jsxs(W,{"code-path":"src/pages/SNMPMonitor.tsx:236:13",open:T,onOpenChange:b,children:[e.jsx(Ne,{"code-path":"src/pages/SNMPMonitor.tsx:237:15",asChild:!0,children:e.jsxs(w,{"code-path":"src/pages/SNMPMonitor.tsx:238:17",size:"sm",className:"bg-cyan-500/10 text-cyan-400 hover:bg-cyan-500/20 border border-cyan-500/30",children:[e.jsx(ne,{"code-path":"src/pages/SNMPMonitor.tsx:239:19",className:"h-4 w-4"}),"添加设备"]})}),e.jsxs(Y,{"code-path":"src/pages/SNMPMonitor.tsx:243:15",className:"bg-slate-900 border-[var(--dg-border)] text-[var(--dg-text-primary)] sm:max-w-md",children:[e.jsxs(Z,{"code-path":"src/pages/SNMPMonitor.tsx:244:17",children:[e.jsx(J,{"code-path":"src/pages/SNMPMonitor.tsx:245:19",className:"text-[var(--dg-text-primary)]",children:"添加 SNMP 设备"}),e.jsx(ee,{"code-path":"src/pages/SNMPMonitor.tsx:246:19",className:"text-[var(--dg-text-muted)]",children:"输入设备信息以开始 SNMP 监控采集。"})]}),e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:251:17",className:"grid gap-4 py-2",children:[e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:253:19",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SNMPMonitor.tsx:254:21",htmlFor:"snmp-name",className:"text-[var(--dg-text-muted)]",children:"设备名称"}),e.jsx(y,{"code-path":"src/pages/SNMPMonitor.tsx:257:21",id:"snmp-name",placeholder:"例如: 核心交换机",value:o.name,onChange:a=>x({...o,name:a.target.value}),className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:267:19",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SNMPMonitor.tsx:268:21",htmlFor:"snmp-ip",className:"text-[var(--dg-text-muted)]",children:"IP 地址"}),e.jsx(y,{"code-path":"src/pages/SNMPMonitor.tsx:271:21",id:"snmp-ip",placeholder:"例如: 192.168.1.1",value:o.ip,onChange:a=>x({...o,ip:a.target.value}),className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:281:19",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SNMPMonitor.tsx:282:21",htmlFor:"snmp-port",className:"text-[var(--dg-text-muted)]",children:"SNMP 端口"}),e.jsx(y,{"code-path":"src/pages/SNMPMonitor.tsx:285:21",id:"snmp-port",type:"number",placeholder:"161",value:o.port,onChange:a=>x({...o,port:Number(a.target.value)||161}),className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:296:19",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SNMPMonitor.tsx:297:21",htmlFor:"snmp-version",className:"text-[var(--dg-text-muted)]",children:"SNMP 版本"}),e.jsxs(se,{"code-path":"src/pages/SNMPMonitor.tsx:300:21",value:o.snmp_version,onValueChange:a=>x({...o,snmp_version:a}),children:[e.jsx(ae,{"code-path":"src/pages/SNMPMonitor.tsx:304:23",id:"snmp-version",className:"w-full bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(re,{"code-path":"src/pages/SNMPMonitor.tsx:308:25"})}),e.jsxs(oe,{"code-path":"src/pages/SNMPMonitor.tsx:310:23",className:"bg-slate-800 border-slate-700 text-slate-200",children:[e.jsx(A,{"code-path":"src/pages/SNMPMonitor.tsx:311:25",value:"v2c",children:"v2c"}),e.jsx(A,{"code-path":"src/pages/SNMPMonitor.tsx:312:25",value:"v3",children:"v3"})]})]})]}),e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:318:19",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SNMPMonitor.tsx:319:21",htmlFor:"snmp-community",className:"text-[var(--dg-text-muted)]",children:"Community"}),e.jsx(y,{"code-path":"src/pages/SNMPMonitor.tsx:322:21",id:"snmp-community",placeholder:"public",value:o.community,onChange:a=>x({...o,community:a.target.value}),className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/pages/SNMPMonitor.tsx:332:19",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SNMPMonitor.tsx:333:21",htmlFor:"snmp-template",className:"text-[var(--dg-text-muted)]",children:"模板 ID"}),e.jsx(y,{"code-path":"src/pages/SNMPMonitor.tsx:336:21",id:"snmp-template",type:"number",placeholder:"模板 ID",value:o.template_id,onChange:a=>x({...o,template_id:a.target.value}),className:"bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]})]}),e.jsxs(te,{"code-path":"src/pages/SNMPMonitor.tsx:347:17",children:[e.jsx(w,{"code-path":"src/pages/SNMPMonitor.tsx:348:19",variant:"outline",onClick:()=>b(!1),className:"border-[var(--dg-border)] text-[var(--dg-text-muted)] hover:bg-slate-800",children:"取消"}),e.jsx(w,{"code-path":"src/pages/SNMPMonitor.tsx:355:19",onClick:k,disabled:c||!o.name.trim()||!o.ip.trim(),className:"bg-cyan-500/10 text-cyan-400 hover:bg-cyan-500/20 border border-cyan-500/30",children:c?"添加中...":"确认添加"})]})]})]})]}),v?e.jsx("div",{"code-path":"src/pages/SNMPMonitor.tsx:369:13",className:"py-12 text-center text-sm text-[var(--dg-text-muted)]",children:"加载中..."}):d.length===0?e.jsx("div",{"code-path":"src/pages/SNMPMonitor.tsx:371:13",className:"py-12 text-center text-sm text-[var(--dg-text-muted)] border border-dashed border-[var(--dg-border)] rounded-lg",children:"暂无 SNMP 设备,点击「添加设备」开始监控"}):e.jsxs(ce,{"code-path":"src/pages/SNMPMonitor.tsx:375:13",children:[e.jsx(de,{"code-path":"src/pages/SNMPMonitor.tsx:376:15",children:e.jsxs($,{"code-path":"src/pages/SNMPMonitor.tsx:377:17",className:"border-[var(--dg-border)] hover:bg-transparent",children:[e.jsx(l,{"code-path":"src/pages/SNMPMonitor.tsx:378:19",className:"text-[var(--dg-text-muted)]",children:"名称"}),e.jsx(l,{"code-path":"src/pages/SNMPMonitor.tsx:379:19",className:"text-[var(--dg-text-muted)]",children:"IP 地址"}),e.jsx(l,{"code-path":"src/pages/SNMPMonitor.tsx:380:19",className:"text-[var(--dg-text-muted)]",children:"端口"}),e.jsx(l,{"code-path":"src/pages/SNMPMonitor.tsx:381:19",className:"text-[var(--dg-text-muted)]",children:"版本"}),e.jsx(l,{"code-path":"src/pages/SNMPMonitor.tsx:382:19",className:"text-[var(--dg-text-muted)]",children:"Community"}),e.jsx(l,{"code-path":"src/pages/SNMPMonitor.tsx:383:19",className:"text-[var(--dg-text-muted)]",children:"模板 ID"}),e.jsx(l,{"code-path":"src/pages/SNMPMonitor.tsx:384:19",className:"text-[var(--dg-text-muted)]",children:"状态"}),e.jsx(l,{"code-path":"src/pages/SNMPMonitor.tsx:385:19",className:"text-[var(--dg-text-muted)] w-16",children:"操作"})]})}),e.jsx(ie,{"code-path":"src/pages/SNMPMonitor.tsx:388:15",children:d.map(a=>e.jsxs($,{"code-path":"src/pages/SNMPMonitor.tsx:390:19",className:"border-[var(--dg-border)]",children:[e.jsx(p,{"code-path":"src/pages/SNMPMonitor.tsx:391:21",className:"text-[var(--dg-text-primary)] font-medium",children:a.name}),e.jsx(p,{"code-path":"src/pages/SNMPMonitor.tsx:394:21",className:"text-[var(--dg-text-muted)] font-mono text-xs",children:a.ip}),e.jsx(p,{"code-path":"src/pages/SNMPMonitor.tsx:397:21",className:"text-[var(--dg-text-muted)]",children:a.port}),e.jsx(p,{"code-path":"src/pages/SNMPMonitor.tsx:398:21",children:e.jsx(u,{"code-path":"src/pages/SNMPMonitor.tsx:399:23",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-muted)]",children:a.snmp_version})}),e.jsx(p,{"code-path":"src/pages/SNMPMonitor.tsx:403:21",className:"text-[var(--dg-text-muted)] font-mono text-xs",children:a.community}),e.jsx(p,{"code-path":"src/pages/SNMPMonitor.tsx:406:21",className:"text-[var(--dg-text-muted)]",children:a.template_id||"--"}),e.jsx(p,{"code-path":"src/pages/SNMPMonitor.tsx:407:21",children:P(a.status)}),e.jsx(p,{"code-path":"src/pages/SNMPMonitor.tsx:408:21",children:e.jsx(w,{"code-path":"src/pages/SNMPMonitor.tsx:409:23",variant:"ghost",size:"icon-sm",onClick:()=>H(a.id),className:"text-slate-500 hover:text-red-400 hover:bg-red-500/10",title:"删除设备",children:e.jsx(xe,{"code-path":"src/pages/SNMPMonitor.tsx:416:25",className:"h-4 w-4"})})})]},a.id))})]})]})})]})}const Re=[{icon:I,name:"HTTP",color:"text-blue-400",desc:"HTTP URL 状态码 & 响应时间"},{icon:I,name:"HTTPS",color:"text-emerald-400",desc:"HTTPS SSL 证书 & 响应时间"},{icon:K,name:"TCP",color:"text-orange-400",desc:"TCP 端口连通性检测"},{icon:I,name:"DNS",color:"text-cyan-400",desc:"域名解析延迟 & 结果验证"},{icon:Ce,name:"PING",color:"text-purple-400",desc:"ICMP 连通性 & 延迟"}],Be=["HTTP","HTTPS","TCP","DNS","PING"],Q={name:"",url:"",type:"HTTP",frequency_sec:60,timeout_sec:10,expected_status_code:200};function Ae(t){switch(t){case"up":return e.jsx(ke,{"code-path":"src/pages/SiteMonitor.tsx:106:14",className:"h-4 w-4 text-emerald-400"});case"down":return e.jsx(Te,{"code-path":"src/pages/SiteMonitor.tsx:108:14",className:"h-4 w-4 text-red-400"});default:return e.jsx(je,{"code-path":"src/pages/SiteMonitor.tsx:110:14",className:"h-4 w-4 text-gray-400"})}}function ze(t){switch(t){case"up":return e.jsx(u,{"code-path":"src/pages/SiteMonitor.tsx:117:14",className:"bg-emerald-500/15 text-emerald-400 border-emerald-500/30",children:"正常"});case"down":return e.jsx(u,{"code-path":"src/pages/SiteMonitor.tsx:119:14",className:"bg-red-500/15 text-red-400 border-red-500/30",children:"异常"});default:return e.jsx(u,{"code-path":"src/pages/SiteMonitor.tsx:121:14",className:"bg-gray-500/15 text-gray-400 border-gray-500/30",children:"未知"})}}function Ue(t){return t==null||t===0?"--":t<1e3?`${t.toFixed(0)}ms`:`${(t/1e3).toFixed(2)}s`}function Ee(t){if(!t)return"--";const n=new Date(t),d=N=>String(N).padStart(2,"0");return`${d(n.getMonth()+1)}-${d(n.getDate())} ${d(n.getHours())}:${d(n.getMinutes())}`}function Ge(){const[t,n]=i.useState(null),[d,N]=i.useState([]),[v,_]=i.useState(!0),[T,b]=i.useState(!1),[o,x]=i.useState(!1),[c,m]=i.useState({...Q}),[S,r]=i.useState(!1),[g,k]=i.useState(null),H=ve(),P=i.useCallback(async()=>{try{const s=await F.getStats();n(s)}catch{}},[]),a=i.useCallback(async()=>{b(!0);try{const s=await F.getTasks();N(s?.list||[])}catch{}finally{b(!1),_(!1)}},[]);i.useEffect(()=>{P(),a()},[P,a]);const z=g?d.filter(s=>s.type?.toUpperCase()===g.toUpperCase()):d,pe=()=>{m({...Q}),x(!0)},me=async()=>{if(!c.name.trim()||!c.url.trim()){C.error("名称和 URL 不能为空");return}r(!0);try{await F.createTask({name:c.name.trim(),url:c.url.trim(),type:c.type.toLowerCase(),frequency_sec:Number(c.frequency_sec)||60,timeout_sec:Number(c.timeout_sec)||10,expected_status_code:Number(c.expected_status_code)||200}),C.success("拨测任务已创建"),x(!1),a(),P()}catch(s){C.error(s.message||"创建失败")}finally{r(!1)}},ge=async s=>{if(await H({title:"删除拨测任务",description:`确定删除「${s.name}」吗?此操作不可恢复。`,variant:"destructive"}))try{await F.deleteTask(s.id),C.success("任务已删除"),a(),P()}catch(ue){C.error(ue.message||"删除失败")}},he=async s=>{try{await F.toggleTask(s.id,!s.enabled),C.success(s.enabled?"已停用":"已启用"),a(),P()}catch(q){C.error(q.message||"操作失败")}},Me=t?.availability!=null?`${(t.availability*100).toFixed(1)}%`:"--";return v?e.jsx("div",{"code-path":"src/pages/SiteMonitor.tsx:249:7",className:"flex items-center justify-center py-20",children:e.jsx(O,{"code-path":"src/pages/SiteMonitor.tsx:250:9",className:"h-8 w-8 animate-spin text-[var(--dg-text-muted)]"})}):e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:256:5",className:"space-y-6",children:[e.jsx("div",{"code-path":"src/pages/SiteMonitor.tsx:258:7",className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-3",children:Re.map(s=>{const q=g===s.name;return e.jsx(h,{"code-path":"src/pages/SiteMonitor.tsx:262:13",onClick:()=>k(q?null:s.name),className:`bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] transition-colors cursor-pointer ${q?"border-[var(--dg-blue)]/60 ring-1 ring-[var(--dg-blue)]/30":"hover:border-[var(--dg-blue)]/30"}`,children:e.jsxs(M,{"code-path":"src/pages/SiteMonitor.tsx:269:15",className:"p-3 text-center",children:[e.jsx(s.icon,{"code-path":"src/pages/SiteMonitor.tsx:270:17",className:`h-5 w-5 mx-auto mb-1.5 ${s.color}`}),e.jsx("p",{"code-path":"src/pages/SiteMonitor.tsx:271:17",className:"text-xs font-medium text-[var(--dg-text-primary)]",children:s.name}),e.jsx("p",{"code-path":"src/pages/SiteMonitor.tsx:272:17",className:"text-[10px] text-[var(--dg-text-muted)] mt-0.5",children:s.desc})]})},s.name)})}),e.jsx(h,{"code-path":"src/pages/SiteMonitor.tsx:280:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/SiteMonitor.tsx:281:9",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:282:11",className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:283:13",className:"flex items-center gap-2",children:[e.jsx(I,{"code-path":"src/pages/SiteMonitor.tsx:284:15",className:"h-4 w-4 text-[var(--dg-text-muted)]"}),e.jsx("h3",{"code-path":"src/pages/SiteMonitor.tsx:285:15",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:"拨测任务概览"})]}),e.jsxs(w,{"code-path":"src/pages/SiteMonitor.tsx:287:13",size:"sm",variant:"ghost",className:"h-7 text-xs text-[var(--dg-text-muted)] hover:text-[var(--dg-text-primary)]",onClick:()=>{P(),a()},disabled:T,children:[e.jsx(_e,{"code-path":"src/pages/SiteMonitor.tsx:294:15",className:`h-3.5 w-3.5 ${T?"animate-spin":""}`}),"刷新"]})]}),e.jsx("div",{"code-path":"src/pages/SiteMonitor.tsx:298:11",className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"总任务数",value:t?.total_tasks??"--"},{label:"已启用",value:t?.enabled_tasks??"--"},{label:"正常",value:t?.up_count??"--",color:"text-emerald-400"},{label:"异常",value:t?.down_count??"--",color:"text-red-400"},{label:"可用率",value:Me,color:"text-blue-400"}].map(s=>e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:306:15",className:"bg-[var(--dg-bg-tertiary)] rounded-lg p-3 text-center",children:[e.jsx("p",{"code-path":"src/pages/SiteMonitor.tsx:307:17",className:"text-xs text-[var(--dg-text-muted)]",children:s.label}),e.jsx("p",{"code-path":"src/pages/SiteMonitor.tsx:308:17",className:`text-lg font-bold ${s.color||"text-[var(--dg-text-primary)]"}`,children:s.value})]},s.label))})]})}),e.jsx(h,{"code-path":"src/pages/SiteMonitor.tsx:318:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(M,{"code-path":"src/pages/SiteMonitor.tsx:319:9",className:"p-4",children:[e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:320:11",className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:321:13",className:"flex items-center gap-2",children:[e.jsx(R,{"code-path":"src/pages/SiteMonitor.tsx:322:15",className:"h-4 w-4 text-[var(--dg-text-muted)]"}),e.jsxs("h3",{"code-path":"src/pages/SiteMonitor.tsx:323:15",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:["拨测任务列表",g&&e.jsxs(u,{"code-path":"src/pages/SiteMonitor.tsx:326:19",variant:"outline",className:"ml-2 text-[10px] cursor-pointer border-[var(--dg-blue)]/40 text-[var(--dg-blue)] h-5",onClick:()=>k(null),children:[g," ×"]})]})]}),e.jsxs(w,{"code-path":"src/pages/SiteMonitor.tsx:336:13",size:"sm",className:"h-8 gap-1.5",onClick:pe,children:[e.jsx(ne,{"code-path":"src/pages/SiteMonitor.tsx:341:15",className:"h-3.5 w-3.5"}),"添加任务"]})]}),z.length===0?e.jsx("div",{"code-path":"src/pages/SiteMonitor.tsx:347:13",className:"text-center py-12 text-sm text-[var(--dg-text-muted)]",children:d.length===0?"暂无拨测任务,点击「添加任务」创建第一个":"当前筛选条件下无任务"}):e.jsx("div",{"code-path":"src/pages/SiteMonitor.tsx:353:13",className:"overflow-x-auto",children:e.jsxs(ce,{"code-path":"src/pages/SiteMonitor.tsx:354:15",children:[e.jsx(de,{"code-path":"src/pages/SiteMonitor.tsx:355:17",children:e.jsxs($,{"code-path":"src/pages/SiteMonitor.tsx:356:19",className:"border-[var(--dg-border)] hover:bg-transparent",children:[e.jsx(l,{"code-path":"src/pages/SiteMonitor.tsx:357:21",className:"text-xs text-[var(--dg-text-muted)]",children:"名称"}),e.jsx(l,{"code-path":"src/pages/SiteMonitor.tsx:358:21",className:"text-xs text-[var(--dg-text-muted)]",children:"URL"}),e.jsx(l,{"code-path":"src/pages/SiteMonitor.tsx:359:21",className:"text-xs text-[var(--dg-text-muted)]",children:"类型"}),e.jsx(l,{"code-path":"src/pages/SiteMonitor.tsx:360:21",className:"text-xs text-[var(--dg-text-muted)]",children:"间隔"}),e.jsx(l,{"code-path":"src/pages/SiteMonitor.tsx:361:21",className:"text-xs text-[var(--dg-text-muted)]",children:"状态"}),e.jsx(l,{"code-path":"src/pages/SiteMonitor.tsx:362:21",className:"text-xs text-[var(--dg-text-muted)]",children:"延迟"}),e.jsx(l,{"code-path":"src/pages/SiteMonitor.tsx:363:21",className:"text-xs text-[var(--dg-text-muted)]",children:"上次检测"}),e.jsx(l,{"code-path":"src/pages/SiteMonitor.tsx:364:21",className:"text-xs text-[var(--dg-text-muted)]",children:"启用"}),e.jsx(l,{"code-path":"src/pages/SiteMonitor.tsx:365:21",className:"text-xs text-[var(--dg-text-muted)]",children:"操作"})]})}),e.jsx(ie,{"code-path":"src/pages/SiteMonitor.tsx:368:17",children:z.map(s=>e.jsxs($,{"code-path":"src/pages/SiteMonitor.tsx:370:21",className:"border-[var(--dg-border)]",children:[e.jsx(p,{"code-path":"src/pages/SiteMonitor.tsx:371:23",className:"text-sm text-[var(--dg-text-primary)] font-medium",children:s.name}),e.jsx(p,{"code-path":"src/pages/SiteMonitor.tsx:374:23",className:"text-sm text-[var(--dg-text-muted)] max-w-[200px] truncate",children:s.url}),e.jsx(p,{"code-path":"src/pages/SiteMonitor.tsx:377:23",children:e.jsx(u,{"code-path":"src/pages/SiteMonitor.tsx:378:25",variant:"outline",className:"text-[11px] border-[var(--dg-border)]",children:s.type?.toUpperCase()})}),e.jsxs(p,{"code-path":"src/pages/SiteMonitor.tsx:382:23",className:"text-sm text-[var(--dg-text-muted)]",children:[s.frequency_sec,"s"]}),e.jsx(p,{"code-path":"src/pages/SiteMonitor.tsx:385:23",children:e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:386:25",className:"flex items-center gap-1.5",children:[Ae(s.last_status),e.jsx("span",{"code-path":"src/pages/SiteMonitor.tsx:388:27",className:"text-sm text-[var(--dg-text-muted)]",children:ze(s.last_status)})]})}),e.jsx(p,{"code-path":"src/pages/SiteMonitor.tsx:393:23",className:"text-sm text-[var(--dg-text-muted)]",children:Ue(s.last_response_time_ms)}),e.jsx(p,{"code-path":"src/pages/SiteMonitor.tsx:396:23",className:"text-sm text-[var(--dg-text-muted)]",children:Ee(s.last_checked_at)}),e.jsx(p,{"code-path":"src/pages/SiteMonitor.tsx:399:23",children:e.jsx(Pe,{"code-path":"src/pages/SiteMonitor.tsx:400:25",checked:s.enabled,onCheckedChange:()=>he(s)})}),e.jsx(p,{"code-path":"src/pages/SiteMonitor.tsx:405:23",children:e.jsx(w,{"code-path":"src/pages/SiteMonitor.tsx:406:25",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-400 hover:text-red-300 hover:bg-red-500/10",onClick:()=>ge(s),children:e.jsx(xe,{"code-path":"src/pages/SiteMonitor.tsx:412:27",className:"h-4 w-4"})})})]},s.id))})]})})]})}),e.jsx(W,{"code-path":"src/pages/SiteMonitor.tsx:425:7",open:o,onOpenChange:x,children:e.jsxs(Y,{"code-path":"src/pages/SiteMonitor.tsx:426:9",className:"sm:max-w-md bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:[e.jsxs(Z,{"code-path":"src/pages/SiteMonitor.tsx:427:11",children:[e.jsx(J,{"code-path":"src/pages/SiteMonitor.tsx:428:13",children:"添加拨测任务"}),e.jsx(ee,{"code-path":"src/pages/SiteMonitor.tsx:429:13",className:"text-[var(--dg-text-muted)]",children:"配置站点探活任务,系统将按指定频率自动检测"})]}),e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:434:11",className:"grid gap-4 py-2",children:[e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:436:13",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SiteMonitor.tsx:437:15",htmlFor:"task-name",className:"text-[var(--dg-text-primary)]",children:"任务名称"}),e.jsx(y,{"code-path":"src/pages/SiteMonitor.tsx:438:15",id:"task-name",placeholder:"例如:官网首页检测",value:c.name,onChange:s=>m({...c,name:s.target.value})})]}),e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:447:13",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SiteMonitor.tsx:448:15",htmlFor:"task-url",className:"text-[var(--dg-text-primary)]",children:"目标 URL"}),e.jsx(y,{"code-path":"src/pages/SiteMonitor.tsx:449:15",id:"task-url",placeholder:"例如:https://example.com 或 192.168.1.1",value:c.url,onChange:s=>m({...c,url:s.target.value})})]}),e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:458:13",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SiteMonitor.tsx:459:15",className:"text-[var(--dg-text-primary)]",children:"协议类型"}),e.jsxs(se,{"code-path":"src/pages/SiteMonitor.tsx:460:15",value:c.type,onValueChange:s=>m({...c,type:s}),children:[e.jsx(ae,{"code-path":"src/pages/SiteMonitor.tsx:464:17",children:e.jsx(re,{"code-path":"src/pages/SiteMonitor.tsx:465:19"})}),e.jsx(oe,{"code-path":"src/pages/SiteMonitor.tsx:467:17",children:Be.map(s=>e.jsx(A,{"code-path":"src/pages/SiteMonitor.tsx:469:21",value:s,children:s},s))})]})]}),e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:476:13",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:477:15",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SiteMonitor.tsx:478:17",htmlFor:"freq",className:"text-[var(--dg-text-primary)]",children:"检测间隔 (秒)"}),e.jsx(y,{"code-path":"src/pages/SiteMonitor.tsx:481:17",id:"freq",type:"number",min:10,max:86400,value:c.frequency_sec,onChange:s=>m({...c,frequency_sec:Number(s.target.value)||60})})]}),e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:492:15",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SiteMonitor.tsx:493:17",htmlFor:"timeout",className:"text-[var(--dg-text-primary)]",children:"超时 (秒)"}),e.jsx(y,{"code-path":"src/pages/SiteMonitor.tsx:496:17",id:"timeout",type:"number",min:1,max:300,value:c.timeout_sec,onChange:s=>m({...c,timeout_sec:Number(s.target.value)||10})})]})]}),(c.type==="HTTP"||c.type==="HTTPS")&&e.jsxs("div",{"code-path":"src/pages/SiteMonitor.tsx:511:15",className:"grid gap-1.5",children:[e.jsx(j,{"code-path":"src/pages/SiteMonitor.tsx:512:17",htmlFor:"status-code",className:"text-[var(--dg-text-primary)]",children:"期望状态码"}),e.jsx(y,{"code-path":"src/pages/SiteMonitor.tsx:515:17",id:"status-code",type:"number",min:100,max:599,value:c.expected_status_code,onChange:s=>m({...c,expected_status_code:Number(s.target.value)||200})})]})]}),e.jsxs(te,{"code-path":"src/pages/SiteMonitor.tsx:529:11",children:[e.jsx(w,{"code-path":"src/pages/SiteMonitor.tsx:530:13",variant:"outline",onClick:()=>x(!1),disabled:S,children:"取消"}),e.jsxs(w,{"code-path":"src/pages/SiteMonitor.tsx:533:13",onClick:me,disabled:S,children:[S&&e.jsx(O,{"code-path":"src/pages/SiteMonitor.tsx:534:26",className:"h-4 w-4 animate-spin mr-1"}),"创建任务"]})]})]})})]})}const V=[{id:"host",name:"主机监控",icon:be,description:"CPU / 内存 / 磁盘 / 网络 / 磁盘IO"},{id:"middleware",name:"中间件监控",icon:B,description:"Redis / MySQL 指标采集"},{id:"snmp",name:"SNMP 监控",icon:le,description:"网络设备 / 服务器硬件 (OID 模板)"},{id:"site",name:"站点拨测",icon:I,description:"HTTP / PING / DNS / TCP / WS 拨测"}];function ut(){const[t,n]=i.useState("host");return e.jsxs("div",{"code-path":"src/pages/MonitorCenter.tsx:30:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/pages/MonitorCenter.tsx:31:7",children:[e.jsx("h1",{"code-path":"src/pages/MonitorCenter.tsx:32:9",className:"text-2xl font-bold text-[var(--dg-text-primary)]",children:"监控中心"}),e.jsx("p",{"code-path":"src/pages/MonitorCenter.tsx:33:9",className:"text-sm text-[var(--dg-text-muted)] mt-1",children:"全面的基础设施与应用监控"})]}),e.jsx("div",{"code-path":"src/pages/MonitorCenter.tsx:37:7",className:"flex gap-1 bg-[var(--dg-bg-secondary)] p-1 rounded-lg border border-[var(--dg-border)]",children:V.map(d=>e.jsxs("button",{"code-path":"src/pages/MonitorCenter.tsx:39:11",onClick:()=>n(d.id),className:Se("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-md text-sm font-medium transition-all",t===d.id?"bg-[var(--dg-bg-tertiary)] text-[var(--dg-text-primary)] shadow-sm":"text-[var(--dg-text-muted)] hover:text-[var(--dg-text-secondary)]"),children:[e.jsx(d.icon,{"code-path":"src/pages/MonitorCenter.tsx:49:13",className:"h-4 w-4"}),e.jsx("span",{"code-path":"src/pages/MonitorCenter.tsx:50:13",className:"hidden sm:inline",children:d.name})]},d.id))}),e.jsx("p",{"code-path":"src/pages/MonitorCenter.tsx:56:7",className:"text-sm text-[var(--dg-text-muted)] -mt-4",children:V.find(d=>d.id===t)?.description}),e.jsxs("div",{"code-path":"src/pages/MonitorCenter.tsx:61:7",className:"min-h-[400px]",children:[t==="host"&&e.jsx(ye,{"code-path":"src/pages/MonitorCenter.tsx:62:34"}),t==="middleware"&&e.jsx($e,{"code-path":"src/pages/MonitorCenter.tsx:63:40"}),t==="snmp"&&e.jsx(Oe,{"code-path":"src/pages/MonitorCenter.tsx:64:34"}),t==="site"&&e.jsx(Ge,{"code-path":"src/pages/MonitorCenter.tsx:65:34"})]})]})}export{ut as MonitorCenter}; diff --git a/backend/static/assets/NamespaceManagementPage-Do5kDmHW.js b/backend/static/assets/NamespaceManagementPage-Do5kDmHW.js new file mode 100644 index 0000000..e18d947 --- /dev/null +++ b/backend/static/assets/NamespaceManagementPage-Do5kDmHW.js @@ -0,0 +1 @@ +import{i as X,k as Z,r as n,j as e,m as A,n as O,p as j,B as m,L as i,D as L,y as ee,b as E,c as B,d as R,I as q,f as H,v as ae,A as se,N as te,t as $,T as z}from"./index-DfyorCky.js";import{C as p,a as l}from"./card-C55cvSHg.js";import{B as I}from"./badge-xNW8x0G1.js";import{L as ne}from"./label-BK0h2apY.js";import{T as ce,a as re,b as N,c,d as me,e as s}from"./table-5sHV4Akp.js";import{k as P}from"./kubernetes-J8O09fK7.js";import{R as oe}from"./refresh-cw-DUB_tAG-.js";import{P as pe}from"./plus-CUG-9kpu.js";import{C as le}from"./circle-check-DWcXrx2k.js";import{T as xe}from"./trash-2-Dx32pOzT.js";const de=new Set(["kube-system","kube-public","kube-node-lease","default","devops"]);function fe(){const{clusterCode:t}=X(),Q=Z(),[o,M]=n.useState([]),[u,f]=n.useState(!1),[b,F]=n.useState(""),[J,k]=n.useState(!1),[d,y]=n.useState(""),[v,w]=n.useState(!1),[g,h]=n.useState(null),[C,S]=n.useState(!1),x=n.useCallback(async()=>{if(t){f(!0);try{const a=await P.getNamespacesDetail(t);M(Array.isArray(a)?a:[])}catch{M([])}finally{f(!1)}}},[t]);n.useEffect(()=>{x()},[x]);const D=async()=>{if(!(!t||!d.trim())){w(!0);try{await P.createNamespace(t,d.trim()),y(""),k(!1),await x()}catch(a){alert(a?.message||"创建失败")}finally{w(!1)}}},K=async()=>{if(!(!t||!g)){S(!0);try{await P.deleteNamespace(t,g),h(null),await x()}catch(a){alert(a?.message||"删除失败")}finally{S(!1)}}},T=o.filter(a=>!b||a.name.toLowerCase().includes(b.toLowerCase())),Y=o.reduce((a,r)=>a+(r.resource_counts?.deployments||0),0),G=o.reduce((a,r)=>a+(r.resource_counts?.pods||0),0),U=o.reduce((a,r)=>a+(r.resource_counts?.services||0),0),V=o.filter(a=>a.has_resource_quota).length;return e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:108:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:110:7",className:"flex items-center gap-2 text-sm text-slate-500",children:[e.jsx(A,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:111:9",to:"/kubernetes",className:"hover:text-slate-300 transition-colors",children:"集群"}),e.jsx(O,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:112:9",className:"h-3 w-3"}),e.jsx(A,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:113:9",to:`/kubernetes/${t}`,className:"hover:text-slate-300 transition-colors",children:t}),e.jsx(O,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:114:9",className:"h-3 w-3"}),e.jsx("span",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:115:9",className:"text-slate-300",children:"命名空间管理"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:119:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:120:9",children:[e.jsxs("h1",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:121:11",className:"text-2xl font-bold text-slate-100 flex items-center gap-2",children:[e.jsx(j,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:122:13",className:"h-6 w-6 text-emerald-400"}),"命名空间管理"]}),e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:125:11",className:"text-sm text-slate-500 mt-1",children:"命名空间资源配额与生命周期管理"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:127:9",className:"flex items-center gap-2",children:[e.jsx(m,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:128:11",variant:"outline",size:"icon",className:"h-9 w-9 border-slate-700 text-slate-400",onClick:x,disabled:u,children:u?e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:130:24",className:"h-4 w-4 animate-spin"}):e.jsx(oe,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:130:71",className:"h-4 w-4"})}),e.jsxs(L,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:132:11",open:J,onOpenChange:k,children:[e.jsx(ee,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:133:13",asChild:!0,children:e.jsxs(m,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:134:15",className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(pe,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:135:17",className:"h-4 w-4 mr-1"}),"创建命名空间"]})}),e.jsxs(E,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:138:13",children:[e.jsx(B,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:139:15",children:e.jsx(R,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:140:17",children:"创建命名空间"})}),e.jsx("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:142:15",className:"space-y-4 py-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:143:17",className:"space-y-2",children:[e.jsx(ne,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:144:19",children:"命名空间名称"}),e.jsx(q,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:145:19",value:d,onChange:a=>y(a.target.value),placeholder:"例如: my-app",onKeyDown:a=>a.key==="Enter"&&D()}),e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:151:19",className:"text-xs text-slate-500",children:"名称需符合 DNS-1123 标准(小写字母/数字/连字符)"})]})}),e.jsxs(H,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:156:15",children:[e.jsx(m,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:157:17",variant:"outline",onClick:()=>k(!1),children:"取消"}),e.jsxs(m,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:158:17",onClick:D,disabled:v||!d.trim(),children:[v?e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:159:31",className:"h-4 w-4 animate-spin mr-1"}):null,"创建"]})]})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:169:7",className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(p,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:170:9",className:"bg-slate-900 border-slate-800",children:e.jsxs(l,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:171:11",className:"p-4 flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:172:13",children:[e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:172:18",className:"text-xs text-slate-500",children:"命名空间"}),e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:172:64",className:"text-xl font-bold text-emerald-400",children:o.length})]}),e.jsx(j,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:173:13",className:"h-6 w-6 opacity-30 text-emerald-400"})]})}),e.jsx(p,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:176:9",className:"bg-slate-900 border-slate-800",children:e.jsxs(l,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:177:11",className:"p-4 flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:178:13",children:[e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:178:18",className:"text-xs text-slate-500",children:"Deployments"}),e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:178:71",className:"text-xl font-bold text-blue-400",children:Y})]}),e.jsx(ae,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:179:13",className:"h-6 w-6 opacity-30 text-blue-400"})]})}),e.jsx(p,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:182:9",className:"bg-slate-900 border-slate-800",children:e.jsxs(l,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:183:11",className:"p-4 flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:184:13",children:[e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:184:18",className:"text-xs text-slate-500",children:"Pods"}),e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:184:64",className:"text-xl font-bold text-purple-400",children:G})]}),e.jsx(se,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:185:13",className:"h-6 w-6 opacity-30 text-purple-400"})]})}),e.jsx(p,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:188:9",className:"bg-slate-900 border-slate-800",children:e.jsxs(l,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:189:11",className:"p-4 flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:190:13",children:[e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:190:18",className:"text-xs text-slate-500",children:"Services"}),e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:190:68",className:"text-xl font-bold text-cyan-400",children:U})]}),e.jsx(te,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:191:13",className:"h-6 w-6 opacity-30 text-cyan-400"})]})}),e.jsx(p,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:194:9",className:"bg-slate-900 border-slate-800",children:e.jsxs(l,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:195:11",className:"p-4 flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:196:13",children:[e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:196:18",className:"text-xs text-slate-500",children:"配额限制"}),e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:196:64",className:"text-xl font-bold text-amber-400",children:V})]}),e.jsx($,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:197:13",className:"h-6 w-6 opacity-30 text-amber-400"})]})})]}),e.jsx("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:203:7",className:"flex items-center gap-3",children:e.jsx(q,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:204:9",value:b,onChange:a=>F(a.target.value),placeholder:"搜索命名空间...",className:"max-w-xs bg-slate-900 border-slate-700"})}),e.jsx(p,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:213:7",className:"bg-slate-900 border-slate-800",children:e.jsx(l,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:214:9",className:"p-0",children:e.jsxs(ce,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:215:11",children:[e.jsx(re,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:216:13",children:e.jsxs(N,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:217:15",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(c,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:218:17",className:"text-slate-400",children:"名称"}),e.jsx(c,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:219:17",className:"text-slate-400",children:"状态"}),e.jsx(c,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:220:17",className:"text-slate-400",children:"年龄"}),e.jsx(c,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:221:17",className:"text-slate-400 text-center",children:"Deploy"}),e.jsx(c,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:222:17",className:"text-slate-400 text-center",children:"Pods"}),e.jsx(c,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:223:17",className:"text-slate-400 text-center",children:"Svc"}),e.jsx(c,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:224:17",className:"text-slate-400 text-center",children:"配额"}),e.jsx(c,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:225:17",className:"text-slate-400",children:"标签"}),e.jsx(c,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:226:17",className:"text-slate-400 text-center",children:"操作"})]})}),e.jsx(me,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:229:13",children:u?e.jsx(N,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:231:17",children:e.jsxs(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:231:27",colSpan:9,className:"text-center text-slate-500 py-12",children:[e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:232:19",className:"h-5 w-5 animate-spin mx-auto mb-2"}),"加载中..."]})}):T.length===0?e.jsx(N,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:235:17",children:e.jsxs(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:235:27",colSpan:9,className:"text-center text-slate-500 py-12",children:[e.jsx(j,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:236:19",className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"暂无命名空间"]})}):T.map(a=>{const r=de.has(a.name);return e.jsxs(N,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:242:21",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:243:23",className:"font-medium",children:e.jsx("button",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:244:25",className:"text-blue-400 hover:text-blue-300 hover:underline text-left",onClick:()=>Q(`/kubernetes/${t}/namespace/${a.name}`),children:a.name})}),e.jsx(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:251:23",children:e.jsxs(I,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:252:25",className:a.status==="Active"?"bg-emerald-500/20 text-emerald-400":"bg-red-500/20 text-red-400",children:[a.status==="Active"?e.jsx(le,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:253:53",className:"h-3 w-3 mr-1"}):e.jsx(z,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:253:97",className:"h-3 w-3 mr-1"}),a.status]})}),e.jsx(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:257:23",className:"text-sm text-slate-400",children:a.age}),e.jsx(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:258:23",className:"text-center text-sm text-slate-300",children:a.resource_counts?.deployments??0}),e.jsx(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:259:23",className:"text-center text-sm text-slate-300",children:a.resource_counts?.pods??0}),e.jsx(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:260:23",className:"text-center text-sm text-slate-300",children:a.resource_counts?.services??0}),e.jsx(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:261:23",className:"text-center",children:a.has_resource_quota?e.jsxs(I,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:263:27",className:"bg-amber-500/20 text-amber-400",title:JSON.stringify(a.resource_quotas?.[0]?.status),children:[e.jsx($,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:264:29",className:"h-3 w-3 mr-1"}),"有"]}):e.jsx("span",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:267:27",className:"text-xs text-slate-600",children:"-"})}),e.jsx(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:270:23",className:"text-xs",children:a.labels&&Object.keys(a.labels).length>0?e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:272:27",className:"flex flex-wrap gap-1 max-w-[200px]",children:[Object.entries(a.labels).slice(0,3).map(([_,W])=>e.jsxs("span",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:274:31",className:"px-1.5 py-0.5 bg-slate-800 rounded text-slate-400",children:[_,"=",W]},_)),Object.keys(a.labels).length>3&&e.jsxs("span",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:277:31",className:"text-slate-600",children:["+",Object.keys(a.labels).length-3]})]}):e.jsx("span",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:281:27",className:"text-slate-600",children:"-"})}),e.jsx(s,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:284:23",className:"text-center",children:r?e.jsx("span",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:286:27",className:"text-xs text-slate-600",children:"系统"}):e.jsx(m,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:288:27",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-400 hover:text-red-300 hover:bg-red-500/10",onClick:()=>h(a.name),title:"删除命名空间",children:e.jsx(xe,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:294:29",className:"h-3.5 w-3.5"})})})]},a.name)})})]})})}),e.jsx(L,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:308:7",open:!!g,onOpenChange:a=>!a&&h(null),children:e.jsxs(E,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:309:9",children:[e.jsx(B,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:310:11",children:e.jsxs(R,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:311:13",className:"text-red-400 flex items-center gap-2",children:[e.jsx(z,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:312:15",className:"h-5 w-5"}),"删除命名空间"]})}),e.jsx("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:315:11",className:"space-y-3 py-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:316:13",className:"bg-red-500/10 border border-red-500/30 rounded-lg p-3",children:[e.jsxs("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:317:15",className:"text-sm text-red-300",children:["⚠️ 即将删除命名空间 ",e.jsx("span",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:318:29",className:"font-bold",children:g})," 及其中所有资源。"]}),e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:320:15",className:"text-xs text-red-400/70 mt-1",children:"此操作不可逆,所有 Deployment/Pod/Service/ConfigMap 等资源将被永久删除。"})]})}),e.jsxs(H,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:325:11",children:[e.jsx(m,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:326:13",variant:"outline",onClick:()=>h(null),children:"取消"}),e.jsxs(m,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:327:13",variant:"destructive",onClick:K,disabled:C,children:[C?e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceManagementPage.tsx:328:27",className:"h-4 w-4 animate-spin mr-1"}):null,"确认删除"]})]})]})})]})}export{fe as default}; diff --git a/backend/static/assets/NamespaceOverviewPage-qjFlj_lA.js b/backend/static/assets/NamespaceOverviewPage-qjFlj_lA.js new file mode 100644 index 0000000..27763a3 --- /dev/null +++ b/backend/static/assets/NamespaceOverviewPage-qjFlj_lA.js @@ -0,0 +1 @@ +import{i as g,r,j as s,m as l,n as i,s as h,p as b,v as N,x as f,N as u,t as w,A as k}from"./index-DfyorCky.js";import{k as n}from"./kubernetes-J8O09fK7.js";import{F as P}from"./file-text-C9G5abwR.js";const j=[{type:"deployments",label:"Deployments",icon:b,desc:"工作负载副本管理"},{type:"pods",label:"Pods",icon:N,desc:"容器实例运行状态"},{type:"cronjobs",label:"CronJobs",icon:f,desc:"定时任务管理"},{type:"services",label:"Services",icon:u,desc:"服务发现与负载均衡"},{type:"ingresses",label:"Ingresses",icon:u,desc:"外部流量路由规则"},{type:"configmaps",label:"ConfigMaps",icon:P,desc:"配置字典"},{type:"secrets",label:"Secrets",icon:w,desc:"密钥与凭证"},{type:"hpas",label:"HPAs",icon:k,desc:"水平自动伸缩策略"}];function S(){const{clusterCode:t,namespace:a}=g(),[x,p]=r.useState({}),[v,m]=r.useState(!1),d=r.useCallback(async()=>{if(!(!t||!a)){m(!0);try{const e=await Promise.allSettled([n.getNamespaceDeployments(t,a),n.getNamespacePods(t,a),n.getNamespaceServices(t,a),n.getNamespaceIngresses(t,a),n.getNamespaceConfigMaps(t,a),n.getNamespaceSecrets(t,a),n.getHPAs(t,a),n.getCronJobs(t,a)]),c=o=>Array.isArray(o)?o:o?.list||o?.data||[];p({deployments:c(e[0].status==="fulfilled"?e[0].value:[]).length,pods:c(e[1].status==="fulfilled"?e[1].value:[]).length,services:c(e[2].status==="fulfilled"?e[2].value:[]).length,ingresses:c(e[3].status==="fulfilled"?e[3].value:[]).length,configmaps:c(e[4].status==="fulfilled"?e[4].value:[]).length,secrets:c(e[5].status==="fulfilled"?e[5].value:[]).length,hpas:c(e[6].status==="fulfilled"?e[6].value:[]).length,cronjobs:c(e[7].status==="fulfilled"?e[7].value:[]).length})}catch{p({})}finally{m(!1)}}},[t,a]);return r.useEffect(()=>{d()},[d]),s.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:65:5",className:"space-y-4",children:[s.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:67:7",className:"flex items-center gap-2 text-sm text-slate-500",children:[s.jsx(l,{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:68:9",to:"/kubernetes",className:"hover:text-slate-300 transition-colors",children:"集群"}),s.jsx(i,{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:69:9",className:"h-3 w-3"}),s.jsx(l,{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:70:9",to:`/kubernetes/${t}`,className:"hover:text-slate-300 transition-colors",children:t}),s.jsx(i,{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:71:9",className:"h-3 w-3"}),s.jsx("span",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:72:9",className:"text-slate-300",children:a})]}),s.jsx("div",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:76:7",className:"flex items-center justify-between",children:s.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:77:9",children:[s.jsxs("h1",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:78:11",className:"text-2xl font-bold text-slate-100 flex items-center gap-2",children:[s.jsx(h,{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:79:13",className:"h-6 w-6 text-blue-400"}),a]}),s.jsx("p",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:82:11",className:"text-sm text-slate-500 mt-1",children:"命名空间概览"})]})}),s.jsx("div",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:87:7",className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:j.map(e=>s.jsxs(l,{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:89:11",to:`/kubernetes/${t}/namespace/${a}/${e.type}`,className:"bg-slate-900 border border-slate-800 rounded-lg p-4 hover:border-slate-600 hover:bg-slate-800/50 transition-all group",children:[s.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:93:13",className:"flex items-center justify-between mb-2",children:[s.jsx(e.icon,{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:94:15",className:"h-5 w-5 text-slate-500 group-hover:text-blue-400 transition-colors"}),s.jsx(i,{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:95:15",className:"h-4 w-4 text-slate-600 group-hover:text-slate-400 transition-colors"})]}),s.jsx("div",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:97:13",className:"text-lg font-bold text-slate-100",children:v?"-":x[e.type]??0}),s.jsx("div",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:98:13",className:"text-sm text-slate-500",children:e.label}),s.jsx("div",{"code-path":"src/components/kubernetes/NamespaceOverviewPage.tsx:99:13",className:"text-xs text-slate-600 mt-1",children:e.desc})]},e.type))})]})}export{S as default}; diff --git a/backend/static/assets/NamespaceResourcePage-Byljvm8v.js b/backend/static/assets/NamespaceResourcePage-Byljvm8v.js new file mode 100644 index 0000000..00408d2 --- /dev/null +++ b/backend/static/assets/NamespaceResourcePage-Byljvm8v.js @@ -0,0 +1,3 @@ +import{r as g,G as xe,n as te,N as Q,t as T,j as e,B as i,a5 as he,L as A,I as P,i as be,z as ge,k as Ne,p as O,x as ne,A as le,v as de,m as se,S as ke,F as M,H as ve}from"./index-DfyorCky.js";import{C as Re,a as je}from"./card-C55cvSHg.js";import{B as E}from"./badge-xNW8x0G1.js";import{S as I,a as F,b as H,c as J,d as $}from"./select-D5qUzdAs.js";import{T as Pe,a as ye,b as C,c as fe,d as Ee,e as a}from"./table-5sHV4Akp.js";import{c as re,R as Ve,y as we,o as Ce,Y as Se,P as ze,a as _e}from"./PodFileBrowser-BySN2XGN.js";import{L as _}from"./label-BK0h2apY.js";import{T as $e}from"./textarea-NXY8u32k.js";import{u as ie}from"./use-toast-CrSOP4cJ.js";import{k as f}from"./kubernetes-J8O09fK7.js";import{F as ce}from"./file-text-C9G5abwR.js";import{S as W}from"./save-DoGGjfwC.js";import{P as G}from"./plus-CUG-9kpu.js";import{T as U}from"./trash-2-Dx32pOzT.js";import{R as Me}from"./refresh-cw-DUB_tAG-.js";import{D as oe}from"./download-DoZfYs2h.js";import{P as B}from"./pencil-BqUotcjf.js";import{H as Ye}from"./hard-drive-BbPmnARR.js";import"./index-CWVNW_qu.js";import"./copy-DXW4LnkN.js";import"./sparkles-Bld4NX5y.js";import"./xterm-DSqgeKvr.js";import"./box-TTGA1p57.js";import"./rotate-cw-5qcj_h_q.js";import"./minimize-2-CiCQYRfn.js";import"./arrow-left-BDgGyrD0.js";import"./upload-Ba6rlaGS.js";import"./folder-DoMwqvzv.js";function Te(s){try{return JSON.parse(s)}catch{}try{const t=s.split(` +`).filter(o=>!o.trim().startsWith("#"));return JSON.parse(t.join(` +`))}catch{return null}}function Ae({clusterCode:s,namespace:t,resource:o,name:d,onClose:r,onSaved:x}){const{toast:v}=ie(),[w,V]=g.useState(!0),[R,m]=g.useState(!1),[u,b]=g.useState(""),[l,h]=g.useState(null),[N,j]=g.useState("visual"),[n,k]=g.useState(""),p=g.useCallback(async()=>{V(!0);try{const S=await f.getResourceYaml(s,t,o,d),L=re(S);b(S),k(L);const ee=Te(L);h(ee),ee||(j("yaml"),v({title:"可视化编辑不可用",description:"无法解析资源结构,已切换到 YAML 编辑模式"}))}catch(S){v({title:"加载失败",description:S.message,variant:"destructive"})}finally{V(!1)}},[s,t,o,d]);g.useEffect(()=>{p()},[p]);const y=async S=>{m(!0);try{const L=q(S);await f.updateResourceYaml(s,t,o,d,L),v({title:"保存成功",description:`${o}/${d} 已更新`}),x?.(),r()}catch(L){v({title:"保存失败",description:L.message,variant:"destructive"})}finally{m(!1)}},Z=async()=>{m(!0);try{await f.updateResourceYaml(s,t,o,d,n),v({title:"YAML 已应用",description:`${o}/${d} 更新成功`}),x?.(),r()}catch(S){v({title:"保存失败",description:S.message,variant:"destructive"})}finally{m(!1)}};function q(S){return JSON.stringify(S,null,2)}const X={configmaps:{title:"ConfigMap",icon:ce,color:"text-blue-400"},secrets:{title:"Secret",icon:T,color:"text-amber-400"},services:{title:"Service",icon:Q,color:"text-cyan-400"},ingresses:{title:"Ingress",icon:te,color:"text-purple-400"},pvcs:{title:"PersistentVolumeClaim",icon:xe,color:"text-emerald-400"}},Y=X[o]||X.configmaps,D=Y.icon;return e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:114:5",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:r,children:e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:115:7",className:"bg-[var(--dg-bg-primary)] border border-[var(--dg-border)] rounded-xl w-[90vw] max-w-3xl max-h-[85vh] flex flex-col shadow-2xl",onClick:S=>S.stopPropagation(),children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:117:9",className:"flex items-center justify-between p-4 border-b border-[var(--dg-border)]",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:118:11",className:"flex items-center gap-2",children:[e.jsx(D,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:119:13",className:`h-5 w-5 ${Y.color}`}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:120:13",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:121:15",className:"text-lg font-bold text-[var(--dg-text-primary)]",children:[Y.title," 编辑器"]}),e.jsxs("p",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:122:15",className:"text-xs text-[var(--dg-text-muted)]",children:[d," · ",t," · ",s]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:125:11",className:"flex items-center gap-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:127:13",className:"flex rounded-lg border border-[var(--dg-border)] overflow-hidden",children:[e.jsx("button",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:128:15",className:`px-3 py-1.5 text-xs font-medium transition-colors ${N==="visual"?"bg-blue-600 text-white":"bg-transparent text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)]"}`,onClick:()=>l&&j("visual"),disabled:!l,children:"可视化编辑"}),e.jsx("button",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:133:15",className:`px-3 py-1.5 text-xs font-medium transition-colors ${N==="yaml"?"bg-blue-600 text-white":"bg-transparent text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)]"}`,onClick:()=>j("yaml"),children:"YAML 编辑"})]}),e.jsx(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:138:13",variant:"ghost",size:"icon",className:"h-8 w-8 text-[var(--dg-text-secondary)]",onClick:r,children:e.jsx(he,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:138:119",className:"h-4 w-4"})})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:143:9",className:"flex-1 overflow-auto p-4",children:w?e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:145:13",className:"flex items-center justify-center h-full py-20",children:e.jsx(A,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:145:76",className:"h-6 w-6 animate-spin text-[var(--dg-text-muted)]"})}):N==="yaml"?e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:147:13",className:"space-y-3",children:[e.jsx("p",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:148:15",className:"text-xs text-amber-400/80",children:"⚠️ YAML 编辑模式 — 修改后点击保存。已自动清理只读字段(status/managedFields/uid)"}),e.jsx(Ve,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:149:15",value:n,height:"550px",theme:Ce,extensions:[we()],onChange:S=>k(S),basicSetup:{lineNumbers:!0,foldGutter:!0,highlightActiveLine:!0,autocompletion:!0},style:{fontSize:"12px"}}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:158:15",className:"flex justify-end gap-2",children:[e.jsx(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:159:17",variant:"outline",size:"sm",onClick:()=>{k(re(u))},children:"重置"}),e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:160:17",size:"sm",className:"bg-blue-600 hover:bg-blue-700",onClick:Z,disabled:R,children:[R?e.jsx(A,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:161:29",className:"h-3.5 w-3.5 animate-spin mr-1"}):e.jsx(W,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:161:85",className:"h-3.5 w-3.5 mr-1"}),"保存"]})]})]}):l?e.jsxs(e.Fragment,{children:[o==="configmaps"&&e.jsx(Le,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:168:45",manifest:l,onSave:y,saving:R}),o==="secrets"&&e.jsx(Oe,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:169:42",manifest:l,onSave:y,saving:R}),o==="services"&&e.jsx(Be,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:170:43",manifest:l,onSave:y,saving:R}),o==="ingresses"&&e.jsx(De,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:171:44",manifest:l,onSave:y,saving:R}),o==="pvcs"&&e.jsx(Ie,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:172:39",manifest:l,onSave:y,saving:R}),!["configmaps","secrets","services","ingresses","pvcs"].includes(o)&&e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:174:17",className:"text-center py-12 text-[var(--dg-text-muted)]",children:[e.jsx("p",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:175:19",children:"该资源类型暂不支持可视化编辑"}),e.jsx(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:176:19",variant:"outline",size:"sm",className:"mt-4",onClick:()=>j("yaml"),children:"切换到 YAML 编辑"})]})]}):e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:181:13",className:"text-center py-12 text-[var(--dg-text-muted)]",children:[e.jsx("p",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:182:15",children:"无法解析资源结构"}),e.jsx(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:183:15",variant:"outline",size:"sm",className:"mt-4",onClick:()=>j("yaml"),children:"切换到 YAML 编辑"})]})})]})})}function Le({manifest:s,onSave:t,saving:o}){const d=s?.data||{},[r,x]=g.useState(Object.entries(d).map(([m,u])=>({key:m,value:String(u)}))),v=(m,u,b)=>{const l=[...r];l[m]={...l[m],[u]:b},x(l)},w=()=>x([...r,{key:"",value:""}]),V=m=>x(r.filter((u,b)=>b!==m)),R=()=>{const m={};r.forEach(u=>{u.key.trim()&&(m[u.key.trim()]=u.value)}),t({...s,data:m})};return e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:219:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:220:7",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:221:9",className:"text-[var(--dg-text-secondary)] text-xs",children:"名称"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:222:9",value:s?.metadata?.name||"",readOnly:!0,className:"mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:224:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:225:9",className:"flex items-center justify-between mb-2",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:226:11",className:"text-[var(--dg-text-secondary)] text-sm",children:"配置数据 (键值对)"}),e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:227:11",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:w,children:[e.jsx(G,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:227:88",className:"h-3 w-3 mr-1"}),"添加"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:229:9",className:"space-y-2 max-h-[45vh] overflow-y-auto pr-1",children:[r.map((m,u)=>e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:231:13",className:"flex items-start gap-2 p-2 rounded-lg border border-[var(--dg-border)] bg-[var(--dg-bg-secondary)]",children:[e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:232:15",value:m.key,onChange:b=>v(u,"key",b.target.value),placeholder:"键名 (如 LOG_LEVEL)",className:"flex-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx($e,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:238:15",value:m.value,onChange:b=>v(u,"value",b.target.value),placeholder:"值",className:"flex-[2] font-mono text-xs min-h-[36px] max-h-[120px] bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:244:15",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-400 hover:text-red-300 shrink-0",onClick:()=>V(u),children:e.jsx(U,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:245:17",className:"h-3.5 w-3.5"})})]},u)),r.length===0&&e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:250:13",className:"text-center py-8 text-[var(--dg-text-muted)] text-xs",children:"暂无配置数据,点击「添加」创建"})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:254:7",className:"flex justify-end gap-2 pt-2 border-t border-[var(--dg-border)]",children:e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:255:9",size:"sm",className:"bg-blue-600 hover:bg-blue-700",onClick:R,disabled:o,children:[o?e.jsx(A,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:256:21",className:"h-3.5 w-3.5 animate-spin mr-1"}):e.jsx(W,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:256:77",className:"h-3.5 w-3.5 mr-1"}),"保存配置"]})})]})}function Oe({manifest:s,onSave:t,saving:o}){const d=s?.data||{},[r,x]=g.useState(Object.entries(d).map(([m,u])=>{const b=String(u);try{const l=atob(b);return{key:m,value:l,encoded:!0}}catch{return{key:m,value:b,encoded:!1}}})),v=(m,u,b)=>{const l=[...r];l[m]={...l[m],[u]:b},x(l)},w=()=>x([...r,{key:"",value:"",encoded:!0}]),V=m=>x(r.filter((u,b)=>b!==m)),R=()=>{const m={};r.forEach(u=>{u.key.trim()&&(m[u.key.trim()]=u.encoded?btoa(u.value):u.value)}),t({...s,data:m})};return e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:304:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:305:7",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:306:9",className:"text-[var(--dg-text-secondary)] text-xs",children:"名称"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:307:9",value:s?.metadata?.name||"",readOnly:!0,className:"mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:309:7",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:310:9",className:"text-[var(--dg-text-secondary)] text-xs",children:"类型"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:311:9",value:s?.type||"Opaque",readOnly:!0,className:"mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:313:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:314:9",className:"flex items-center justify-between mb-2",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:315:11",className:"text-[var(--dg-text-secondary)] text-sm",children:"密钥数据 (已自动解码 Base64)"}),e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:316:11",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:w,children:[e.jsx(G,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:316:88",className:"h-3 w-3 mr-1"}),"添加"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:318:9",className:"space-y-2 max-h-[45vh] overflow-y-auto pr-1",children:[r.map((m,u)=>e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:320:13",className:"flex items-start gap-2 p-2 rounded-lg border border-[var(--dg-border)] bg-[var(--dg-bg-secondary)]",children:[e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:321:15",value:m.key,onChange:b=>v(u,"key",b.target.value),placeholder:"键名 (如 password)",className:"flex-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:327:15",value:m.value,onChange:b=>v(u,"value",b.target.value),placeholder:"明文值",className:"flex-[2] font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:333:15",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-400 hover:text-red-300 shrink-0",onClick:()=>V(u),children:e.jsx(U,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:334:17",className:"h-3.5 w-3.5"})})]},u)),r.length===0&&e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:339:13",className:"text-center py-8 text-[var(--dg-text-muted)] text-xs",children:"暂无密钥数据,点击「添加」创建"})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:343:7",className:"flex justify-end gap-2 pt-2 border-t border-[var(--dg-border)]",children:e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:344:9",size:"sm",className:"bg-blue-600 hover:bg-blue-700",onClick:R,disabled:o,children:[o?e.jsx(A,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:345:21",className:"h-3.5 w-3.5 animate-spin mr-1"}):e.jsx(W,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:345:77",className:"h-3.5 w-3.5 mr-1"}),"保存密钥"]})})]})}function Be({manifest:s,onSave:t,saving:o}){const d=s?.spec||{},[r,x]=g.useState(d.type||"ClusterIP"),[v,w]=g.useState((d.ports||[]).map(n=>({name:n.name||"",port:String(n.port||""),targetPort:String(n.targetPort||""),protocol:n.protocol||"TCP",nodePort:n.nodePort?String(n.nodePort):""}))),[V,R]=g.useState(Object.entries(d.selector||{}).map(([n,k])=>({key:n,value:String(k)}))),m=(n,k,p)=>{const y=[...v];y[n]={...y[n],[k]:p},w(y)},u=()=>w([...v,{name:"",port:"",targetPort:"",protocol:"TCP",nodePort:""}]),b=n=>w(v.filter((k,p)=>p!==n)),l=(n,k,p)=>{const y=[...V];y[n]={...y[n],[k]:p},R(y)},h=()=>R([...V,{key:"",value:""}]),N=n=>R(V.filter((k,p)=>p!==n)),j=()=>{const n={...d};n.type=r,n.ports=v.map(p=>{const y={port:parseInt(p.port)||80,targetPort:parseInt(p.targetPort)||parseInt(p.port)||80,protocol:p.protocol};return p.name&&(y.name=p.name),p.nodePort&&r==="NodePort"&&(y.nodePort=parseInt(p.nodePort)),y});const k={};V.forEach(p=>{p.key.trim()&&(k[p.key.trim()]=p.value)}),n.selector=k,t({...s,spec:n})};return e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:408:5",className:"space-y-5",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:409:7",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:410:9",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:411:11",className:"text-[var(--dg-text-secondary)] text-xs",children:"名称"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:412:11",value:s?.metadata?.name||"",readOnly:!0,className:"mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:414:9",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:415:11",className:"text-[var(--dg-text-secondary)] text-xs",children:"Service 类型"}),e.jsxs(I,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:416:11",value:r,onValueChange:x,children:[e.jsx(F,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:417:13",className:"mt-1 h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] text-xs",children:e.jsx(H,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:418:15"})}),e.jsxs(J,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:420:13",children:[e.jsx($,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:421:15",value:"ClusterIP",children:"ClusterIP (集群内部)"}),e.jsx($,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:422:15",value:"NodePort",children:"NodePort (节点端口)"}),e.jsx($,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:423:15",value:"LoadBalancer",children:"LoadBalancer (负载均衡)"})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:430:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:431:9",className:"flex items-center justify-between mb-2",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:432:11",className:"text-[var(--dg-text-secondary)] text-sm",children:"端口映射"}),e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:433:11",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:u,children:[e.jsx(G,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:433:89",className:"h-3 w-3 mr-1"}),"添加端口"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:435:9",className:"space-y-2",children:[v.map((n,k)=>e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:437:13",className:"grid grid-cols-[1fr_80px_80px_80px_80px_32px] gap-2 items-center",children:[e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:438:15",value:n.name,onChange:p=>m(k,"name",p.target.value),placeholder:"名称",className:"font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:439:15",value:n.port,onChange:p=>m(k,"port",p.target.value),placeholder:"端口",type:"number",className:"font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:440:15",value:n.targetPort,onChange:p=>m(k,"targetPort",p.target.value),placeholder:"目标",type:"number",className:"font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsxs(I,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:441:15",value:n.protocol,onValueChange:p=>m(k,"protocol",p),children:[e.jsx(F,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:442:17",className:"h-7 text-xs bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(H,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:442:139"})}),e.jsxs(J,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:443:17",children:[e.jsx($,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:443:32",value:"TCP",children:"TCP"}),e.jsx($,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:443:72",value:"UDP",children:"UDP"})]})]}),r==="NodePort"?e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:446:17",value:n.nodePort,onChange:p=>m(k,"nodePort",p.target.value),placeholder:"NodePort",type:"number",className:"font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}):e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:447:19"}),e.jsx(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:448:15",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-400 hover:text-red-300",onClick:()=>b(k),children:e.jsx(U,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:448:133",className:"h-3 w-3"})})]},k)),v.length===0&&e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:451:34",className:"text-center py-4 text-[var(--dg-text-muted)] text-xs",children:"暂无端口,点击「添加端口」"})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:456:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:457:9",className:"flex items-center justify-between mb-2",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:458:11",className:"text-[var(--dg-text-secondary)] text-sm",children:"选择器 (Selector)"}),e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:459:11",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:h,children:[e.jsx(G,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:459:93",className:"h-3 w-3 mr-1"}),"添加标签"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:461:9",className:"space-y-2",children:[V.map((n,k)=>e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:463:13",className:"flex items-center gap-2",children:[e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:464:15",value:n.key,onChange:p=>l(k,"key",p.target.value),placeholder:"键 (如 app)",className:"flex-1 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx("span",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:465:15",className:"text-[var(--dg-text-muted)] text-xs",children:"="}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:466:15",value:n.value,onChange:p=>l(k,"value",p.target.value),placeholder:"值 (如 nginx)",className:"flex-1 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:467:15",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-400 hover:text-red-300",onClick:()=>N(k),children:e.jsx(U,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:467:137",className:"h-3 w-3"})})]},k)),V.length===0&&e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:470:37",className:"text-center py-4 text-[var(--dg-text-muted)] text-xs",children:"暂无选择器"})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:474:7",className:"flex justify-end gap-2 pt-2 border-t border-[var(--dg-border)]",children:e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:475:9",size:"sm",className:"bg-blue-600 hover:bg-blue-700",onClick:j,disabled:o,children:[o?e.jsx(A,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:476:21",className:"h-3.5 w-3.5 animate-spin mr-1"}):e.jsx(W,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:476:77",className:"h-3.5 w-3.5 mr-1"}),"保存 Service"]})})]})}function De({manifest:s,onSave:t,saving:o}){const d=s?.spec||{},[r,x]=g.useState((d.rules||[]).map(l=>({host:l.host||"",paths:l.http?.backend?.servicePort!=null?[{path:"/",pathType:"Prefix",serviceName:l.http?.backend?.serviceName||"",servicePort:String(l.http?.backend?.servicePort||"80")}]:(l.http?.paths||[]).map(h=>({path:h.path||"/",pathType:h.pathType||"Prefix",serviceName:h.backend?.service?.name||h.backend?.serviceName||"",servicePort:String(h.backend?.service?.port?.number??h.backend?.servicePort??"80")}))}))),v=(l,h)=>{const N=[...r];N[l]={...N[l],host:h},x(N)},w=()=>x([...r,{host:"",paths:[{path:"/",pathType:"Prefix",serviceName:"",servicePort:"80"}]}]),V=l=>x(r.filter((h,N)=>N!==l)),R=(l,h,N,j)=>{const n=[...r];n[l].paths[h]={...n[l].paths[h],[N]:j},x(n)},m=l=>{const h=[...r];h[l].paths.push({path:"/",pathType:"Prefix",serviceName:"",servicePort:"80"}),x(h)},u=(l,h)=>{const N=[...r];N[l].paths=N[l].paths.filter((j,n)=>n!==h),x(N)},b=()=>{const l=r.map(h=>({host:h.host,http:{paths:h.paths.map(N=>({path:N.path,pathType:N.pathType,backend:{service:{name:N.serviceName,port:{number:parseInt(N.servicePort)||80}}}}))}}));t({...s,spec:{...d,rules:l}})};return e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:544:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:545:7",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:546:9",className:"text-[var(--dg-text-secondary)] text-xs",children:"名称"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:547:9",value:s?.metadata?.name||"",readOnly:!0,className:"mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:549:7",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:550:9",className:"flex items-center justify-between mb-2",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:551:11",className:"text-[var(--dg-text-secondary)] text-sm",children:"路由规则"}),e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:552:11",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:w,children:[e.jsx(G,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:552:89",className:"h-3 w-3 mr-1"}),"添加 Host"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:554:9",className:"space-y-3 max-h-[50vh] overflow-y-auto pr-1",children:[r.map((l,h)=>e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:556:13",className:"p-3 rounded-lg border border-[var(--dg-border)] bg-[var(--dg-bg-secondary)] space-y-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:557:15",className:"flex items-center gap-2",children:[e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:558:17",value:l.host,onChange:N=>v(h,N.target.value),placeholder:"域名 (如 api.example.com)",className:"flex-1 font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:564:17",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-400 hover:text-red-300",onClick:()=>V(h),children:e.jsx(U,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:564:136",className:"h-3 w-3"})})]}),l.paths.map((N,j)=>e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:567:17",className:"grid grid-cols-[1fr_100px_1fr_60px_28px] gap-1.5 items-center pl-4",children:[e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:568:19",value:N.path,onChange:n=>R(h,j,"path",n.target.value),placeholder:"路径 /",className:"font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsxs(I,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:569:19",value:N.pathType,onValueChange:n=>R(h,j,"pathType",n),children:[e.jsx(F,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:570:21",className:"h-7 text-xs bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(H,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:570:143"})}),e.jsxs(J,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:571:21",children:[e.jsx($,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:571:36",value:"Prefix",children:"Prefix"}),e.jsx($,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:571:82",value:"Exact",children:"Exact"})]})]}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:573:19",value:N.serviceName,onChange:n=>R(h,j,"serviceName",n.target.value),placeholder:"Service",className:"font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:574:19",value:N.servicePort,onChange:n=>R(h,j,"servicePort",n.target.value),placeholder:"端口",type:"number",className:"font-mono text-xs h-7 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:575:19",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-400 hover:text-red-300",onClick:()=>u(h,j),children:e.jsx(U,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:575:142",className:"h-3 w-3"})})]},j)),e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:578:15",variant:"ghost",size:"sm",className:"h-6 text-xs text-[var(--dg-text-muted)]",onClick:()=>m(h),children:[e.jsx(G,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:578:129",className:"h-3 w-3 mr-1"}),"添加路径"]})]},h)),r.length===0&&e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:581:34",className:"text-center py-4 text-[var(--dg-text-muted)] text-xs",children:"暂无路由规则,点击「添加 Host」"})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:584:7",className:"flex justify-end gap-2 pt-2 border-t border-[var(--dg-border)]",children:e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:585:9",size:"sm",className:"bg-blue-600 hover:bg-blue-700",onClick:b,disabled:o,children:[o?e.jsx(A,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:586:21",className:"h-3.5 w-3.5 animate-spin mr-1"}):e.jsx(W,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:586:77",className:"h-3.5 w-3.5 mr-1"}),"保存 Ingress"]})})]})}function Ie({manifest:s,onSave:t,saving:o}){const d=s?.spec||{},r=d.resources?.requests||{},[x,v]=g.useState(r.storage||"1Gi"),[w,V]=g.useState(d.accessModes?.[0]||"ReadWriteOnce"),[R,m]=g.useState(d.storageClassName||""),u=()=>{t({...s,spec:{...d,accessModes:[w],storageClassName:R||void 0,resources:{requests:{storage:x}}}})};return e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:617:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:618:7",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:619:9",className:"text-[var(--dg-text-secondary)] text-xs",children:"名称"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:620:9",value:s?.metadata?.name||"",readOnly:!0,className:"mt-1 font-mono text-xs bg-[var(--dg-bg-tertiary)]"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:622:7",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:623:9",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:624:11",className:"text-[var(--dg-text-secondary)] text-xs",children:"存储大小"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:625:11",value:x,onChange:b=>v(b.target.value),placeholder:"如 10Gi",className:"mt-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"}),e.jsx("p",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:631:11",className:"text-[10px] text-[var(--dg-text-muted)] mt-1",children:"单位:Gi (GiB), Mi (MiB), Ti (TiB)"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:633:9",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:634:11",className:"text-[var(--dg-text-secondary)] text-xs",children:"访问模式"}),e.jsxs(I,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:635:11",value:w,onValueChange:V,children:[e.jsx(F,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:636:13",className:"mt-1 h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] text-xs",children:e.jsx(H,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:637:15"})}),e.jsxs(J,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:639:13",children:[e.jsx($,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:640:15",value:"ReadWriteOnce",children:"ReadWriteOnce (单节点读写)"}),e.jsx($,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:641:15",value:"ReadOnlyMany",children:"ReadOnlyMany (多节点只读)"}),e.jsx($,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:642:15",value:"ReadWriteMany",children:"ReadWriteMany (多节点读写)"})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:647:7",children:[e.jsx(_,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:648:9",className:"text-[var(--dg-text-secondary)] text-xs",children:"StorageClass"}),e.jsx(P,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:649:9",value:R,onChange:b=>m(b.target.value),placeholder:"留空使用默认 StorageClass",className:"mt-1 font-mono text-xs h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsx("div",{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:656:7",className:"flex justify-end gap-2 pt-2 border-t border-[var(--dg-border)]",children:e.jsxs(i,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:657:9",size:"sm",className:"bg-blue-600 hover:bg-blue-700",onClick:u,disabled:o,children:[o?e.jsx(A,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:658:21",className:"h-3.5 w-3.5 animate-spin mr-1"}):e.jsx(W,{"code-path":"src/components/kubernetes/ResourceVisualEditor.tsx:658:77",className:"h-3.5 w-3.5 mr-1"}),"保存 PVC"]})})]})}const ae={deployments:{title:"Deployments",subtitle:"Deployment 工作负载运行状态",icon:O,columns:["名称","命名空间","副本","镜像","操作"],renderRow:(s,t)=>e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:42:7",className:"border-slate-800 hover:bg-slate-800/30 cursor-pointer",onClick:()=>t.onDetail?.(s),children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:43:9",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:44:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:44:20",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:45:9",children:(()=>{const o=s.ready_replicas||0,d=s.replicas||0,r=d>0?o/d*100:0,x=o===d;return e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:50:15",className:"flex items-center gap-2 min-w-[100px]",children:[e.jsx("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:51:17",className:"flex-1 h-1.5 rounded-full bg-slate-700/50 overflow-hidden",children:e.jsx("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:52:19",className:`h-full rounded-full ${x?"bg-emerald-500":"bg-yellow-500"}`,style:{width:`${r}%`}})}),e.jsxs("span",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:54:17",className:`text-xs ${x?"text-emerald-400":"text-yellow-400"}`,children:[o,"/",d]})]})})()}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:59:9",className:"text-xs text-slate-500 max-w-[200px] truncate",children:s.image||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:60:9",onClick:o=>o.stopPropagation(),children:e.jsx("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:61:11",className:"flex items-center gap-0.5",children:e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:62:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-blue-400",title:"查看YAML",onClick:()=>t.onYaml?.(s.name),children:e.jsx(M,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:63:53",className:"h-3.5 w-3.5"})})})})]},s.name)},pods:{title:"Pods",subtitle:"Pod 实例运行状态",icon:de,columns:["名称","命名空间","状态","节点","CPU","内存","重启","镜像","操作"],renderRow:(s,t)=>{const o={Running:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",Pending:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",Failed:"bg-red-500/20 text-red-400 border-red-500/30"};return e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:75:9",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:76:11",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:77:11",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:77:22",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:78:11",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:78:22",className:o[s.status]||"bg-slate-500/20 text-slate-400",children:s.status||"Unknown"})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:79:11",className:"text-sm text-slate-400",children:s.node_name||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:80:11",className:"text-sm text-cyan-400",children:s.cpu_usage_m||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:81:11",className:"text-sm text-amber-400",children:s.mem_usage_mi||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:82:11",className:s.restart_count>0?"text-yellow-400":"text-slate-500",children:s.restart_count||0}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:83:11",className:"text-xs text-slate-500 max-w-[200px] truncate",children:s.image||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:84:11",children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:85:13",className:"flex items-center gap-1",children:[e.jsxs(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:86:15",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-emerald-400 hover:text-emerald-300 hover:bg-emerald-500/10",title:"终端",onClick:()=>t.onTerminal?.(s),children:[e.jsx(ve,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:87:79",className:"h-3.5 w-3.5 mr-1"}),"终端"]}),e.jsxs(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:88:15",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-amber-400 hover:text-amber-300 hover:bg-amber-500/10",title:"文件浏览器",onClick:()=>t.onFileBrowser?.(s),children:[e.jsx(Ye,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:89:82",className:"h-3.5 w-3.5 mr-1"}),"文件浏览器"]}),e.jsxs(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:90:15",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-blue-400 hover:text-blue-300 hover:bg-blue-500/10",title:"查看YAML",onClick:()=>t.onYaml?.(s.name),children:[e.jsx(M,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:91:55",className:"h-3.5 w-3.5 mr-1"}),"YAML"]})]})})]},s.name)}},services:{title:"Services",subtitle:"Service 网络服务",icon:Q,columns:["名称","命名空间","类型","Cluster IP","端口","操作"],renderRow:(s,t)=>e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:102:7",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:103:9",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:104:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:104:20",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:105:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:105:20",className:"bg-blue-500/20 text-blue-400 border-blue-500/30",children:s.type||"-"})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:106:9",className:"text-sm text-slate-400",children:s.cluster_ip||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:107:9",className:"text-sm text-slate-400",children:s.ports||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:108:9",children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:109:11",className:"flex items-center gap-0.5",children:[e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:110:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-blue-400",title:"查看YAML",onClick:()=>t.onYaml?.(s.name),children:e.jsx(M,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:110:157",className:"h-3.5 w-3.5"})}),e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:111:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-emerald-400 hover:text-emerald-300",title:"编辑",onClick:()=>t.onEdit?.(s.name),children:e.jsx(B,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:111:158",className:"h-3.5 w-3.5"})})]})})]},s.name)},ingresses:{title:"Ingresses",subtitle:"Ingress 路由规则",icon:Q,columns:["名称","命名空间","Hosts","TLS","操作"],renderRow:(s,t)=>{const o=s.hosts||[];return e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:123:9",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:124:11",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:125:11",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:125:22",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:126:11",className:"text-sm text-slate-400 max-w-[250px] truncate",children:o.length>0?o.join(", "):"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:127:11",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:127:22",className:s.tls?"bg-emerald-500/20 text-emerald-400":"bg-slate-500/20 text-slate-400",children:s.tls?"HTTPS":"HTTP"})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:128:11",children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:129:13",className:"flex items-center gap-0.5",children:[e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:130:15",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-blue-400",title:"查看YAML",onClick:()=>t.onYaml?.(s.name),children:e.jsx(M,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:130:159",className:"h-3.5 w-3.5"})}),e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:131:15",variant:"ghost",size:"icon",className:"h-7 w-7 text-emerald-400 hover:text-emerald-300",title:"编辑",onClick:()=>t.onEdit?.(s.name),children:e.jsx(B,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:131:160",className:"h-3.5 w-3.5"})})]})})]},s.name)}},configmaps:{title:"ConfigMaps",subtitle:"配置字典",icon:ce,columns:["名称","命名空间","键数量","操作"],renderRow:(s,t)=>e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:142:7",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:143:9",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:144:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:144:20",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:145:9",className:"text-sm text-slate-400",children:s.key_count||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:146:9",children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:147:11",className:"flex items-center gap-0.5",children:[e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:148:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-blue-400",title:"查看YAML",onClick:()=>t.onYaml?.(s.name),children:e.jsx(M,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:149:53",className:"h-3.5 w-3.5"})}),e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:150:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-emerald-400 hover:text-emerald-300",title:"编辑",onClick:()=>t.onEdit?.(s.name),children:e.jsx(B,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:151:53",className:"h-3.5 w-3.5"})})]})})]},s.name)},secrets:{title:"Secrets",subtitle:"密钥管理(仅名称与类型)",icon:T,columns:["名称","命名空间","类型","操作"],renderRow:(s,t)=>e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:161:7",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:162:9",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:163:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:163:20",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:164:9",className:"text-sm text-slate-400",children:s.type||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:165:9",children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:166:11",className:"flex items-center gap-0.5",children:[e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:167:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-blue-400",title:"查看YAML",onClick:()=>t.onYaml?.(s.name),children:e.jsx(M,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:168:53",className:"h-3.5 w-3.5"})}),e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:169:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-emerald-400 hover:text-emerald-300",title:"编辑",onClick:()=>t.onEdit?.(s.name),children:e.jsx(B,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:170:53",className:"h-3.5 w-3.5"})})]})})]},s.name)},hpas:{title:"HPAs",subtitle:"水平自动伸缩",icon:le,columns:["名称","命名空间","目标","最小/最大","CPU%","Mem%"],renderRow:(s,t)=>e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:180:7",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:181:9",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:182:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:182:20",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsxs(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:183:9",className:"text-sm text-slate-400",children:[s.target_kind,"/",s.target_name]}),e.jsxs(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:184:9",className:"text-sm text-slate-400",children:[s.min_replicas,"/",s.max_replicas]}),e.jsxs(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:185:9",className:"text-sm text-slate-400",children:[s.cpu_percent??"-","%"]}),e.jsxs(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:186:9",className:"text-sm text-slate-400",children:[s.mem_percent??"-","%"]})]},s.name)},cronjobs:{title:"CronJobs",subtitle:"定时任务",icon:ne,columns:["名称","命名空间","调度","状态","上次执行"],renderRow:s=>e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:194:7",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:195:9",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:196:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:196:20",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:197:9",className:"text-sm font-mono text-slate-400",children:s.schedule||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:198:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:198:20",className:s.suspend?"bg-yellow-500/20 text-yellow-400":"bg-emerald-500/20 text-emerald-400",children:s.suspend?"已暂停":"运行中"})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:199:9",className:"text-sm text-slate-400",children:s.last_schedule||"-"})]},s.name)},pvcs:{title:"存储卷声明",subtitle:"PersistentVolumeClaim",icon:O,columns:["名称","命名空间","状态","大小","StorageClass","操作"],renderRow:(s,t)=>e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:207:7",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:208:9",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:209:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:209:20",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:210:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:210:20",className:s.phase==="Bound"?"bg-emerald-500/20 text-emerald-400":"bg-yellow-500/20 text-yellow-400",children:s.phase||"-"})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:211:9",className:"text-sm text-slate-400",children:s.size||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:212:9",className:"text-sm text-slate-400",children:s.storage_class||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:213:9",children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:214:11",className:"flex items-center gap-0.5",children:[e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:215:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-blue-400",title:"查看YAML",onClick:()=>t.onYaml?.(s.name),children:e.jsx(M,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:215:157",className:"h-3.5 w-3.5"})}),e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:216:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-emerald-400 hover:text-emerald-300",title:"编辑",onClick:()=>t.onEdit?.(s.name),children:e.jsx(B,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:216:158",className:"h-3.5 w-3.5"})})]})})]},s.name)},statefulsets:{title:"StatefulSets",subtitle:"有状态应用",icon:O,columns:["名称","命名空间","副本","就绪","镜像"],renderRow:(s,t)=>e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:226:7",className:"border-slate-800 hover:bg-slate-800/30 cursor-pointer",onClick:()=>t.onDetail?.(s),children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:227:9",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:228:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:228:20",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:229:9",className:"text-sm text-slate-400",children:s.replicas||0}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:230:9",className:"text-sm text-slate-400",children:s.ready||0}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:231:9",className:"text-xs text-slate-500 max-w-[200px] truncate",children:s.image||"-"})]},s.name)},daemonsets:{title:"DaemonSets",subtitle:"守护进程集",icon:O,columns:["名称","命名空间","期望","当前","就绪","镜像"],renderRow:(s,t)=>e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:239:7",className:"border-slate-800 hover:bg-slate-800/30 cursor-pointer",onClick:()=>t.onDetail?.(s),children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:240:9",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:241:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:241:20",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:242:9",className:"text-sm text-slate-400",children:s.desired||0}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:243:9",className:"text-sm text-slate-400",children:s.current||0}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:244:9",className:"text-sm text-slate-400",children:s.ready||0}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:245:9",className:"text-xs text-slate-500 max-w-[200px] truncate",children:s.image||"-"})]},s.name)},serviceaccounts:{title:"ServiceAccounts",subtitle:"服务账号(RBAC 身份标识)",icon:T,columns:["名称","命名空间","Secret数","镜像拉取凭证","创建时间","操作"],renderRow:(s,t)=>e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:253:7",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:254:9",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:255:9",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:255:20",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:256:9",className:"text-sm text-slate-400",children:s.secret_count??0}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:257:9",className:"text-xs text-slate-500 max-w-[200px] truncate",children:s.image_pull_secrets&&s.image_pull_secrets.length>0?s.image_pull_secrets.join(", "):"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:260:9",className:"text-xs text-slate-500",children:s.age||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:261:9",onClick:o=>o.stopPropagation(),children:e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:262:11",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-blue-400",title:"查看YAML",onClick:()=>t.onYaml?.(s.name),children:e.jsx(M,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:263:52",className:"h-3.5 w-3.5"})})})]},s.name)},roles:{title:"Roles",subtitle:"命名空间级角色权限(RBAC)",icon:T,columns:["名称","命名空间","规则数","权限范围","创建时间","操作"],renderRow:(s,t)=>{const o=s.verbs||[],d=s.resources||[],r=o.length>4?o.slice(0,4).join(", ")+` +${o.length-4}`:o.join(", "),x=d.length>4?d.slice(0,4).join(", ")+` +${d.length-4}`:d.join(", ");return e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:277:9",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:278:11",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:279:11",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:279:22",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:280:11",className:"text-sm text-slate-400",children:s.rule_count??0}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:281:11",className:"text-xs text-slate-500 max-w-[280px]",children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:282:13",className:"flex flex-col gap-0.5",children:[e.jsxs("span",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:283:15",className:"text-cyan-400 truncate",title:o.join(", "),children:["verbs: ",r||"-"]}),e.jsxs("span",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:284:15",className:"text-amber-400 truncate",title:d.join(", "),children:["resources: ",x||"-"]})]})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:287:11",className:"text-xs text-slate-500",children:s.age||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:288:11",onClick:v=>v.stopPropagation(),children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:289:13",className:"flex items-center gap-0.5",children:[e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:290:15",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-blue-400",title:"查看YAML",onClick:()=>t.onYaml?.(s.name),children:e.jsx(M,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:291:55",className:"h-3.5 w-3.5"})}),e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:292:15",variant:"ghost",size:"icon",className:"h-7 w-7 text-emerald-400 hover:text-emerald-300",title:"编辑",onClick:()=>t.onEdit?.(s.name),children:e.jsx(B,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:293:55",className:"h-3.5 w-3.5"})})]})})]},s.name)}},rolebindings:{title:"RoleBindings",subtitle:"角色绑定关系(RBAC 授权)",icon:T,columns:["名称","命名空间","角色引用","绑定主体","创建时间","操作"],renderRow:(s,t)=>{const o=s.subjects||[],d=o.length>3?o.slice(0,3).join(", ")+` +${o.length-3}`:o.join(", ");return e.jsxs(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:307:9",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:308:11",className:"font-medium text-slate-200",children:s.name}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:309:11",children:e.jsx(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:309:22",variant:"outline",className:"border-slate-700 text-slate-400",children:s.namespace})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:310:11",children:e.jsxs(E,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:311:13",className:"bg-purple-500/20 text-purple-400 border-purple-500/30",children:[s.role_ref_kind||"-","/",s.role_ref_name||"-"]})}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:315:11",className:"text-xs text-slate-500 max-w-[200px] truncate",title:o.join(", "),children:d||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:318:11",className:"text-xs text-slate-500",children:s.age||"-"}),e.jsx(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:319:11",onClick:r=>r.stopPropagation(),children:e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:320:13",className:"flex items-center gap-0.5",children:[e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:321:15",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400 hover:text-blue-400",title:"查看YAML",onClick:()=>t.onYaml?.(s.name),children:e.jsx(M,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:322:56",className:"h-3.5 w-3.5"})}),e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:323:15",variant:"ghost",size:"icon",className:"h-7 w-7 text-emerald-400 hover:text-emerald-300",title:"编辑",onClick:()=>t.onEdit?.(s.name),children:e.jsx(B,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:324:56",className:"h-3.5 w-3.5"})})]})})]},s.name)}}};function gs(){const{clusterCode:s,namespace:t}=be(),o=ge(),d=Ne();ie();const r=g.useMemo(()=>{const c=o.pathname.split("/"),z=c[c.length-1];if(z&&ae[z])return z;if(c.length>=2){const K=c[c.length-2];if(K&&ae[K])return K}return"deployments"},[o.pathname]),x=ae[r],[v,w]=g.useState([]),[V,R]=g.useState([]),[m,u]=g.useState([]),[b,l]=g.useState(!1),[h,N]=g.useState(""),[j,n]=g.useState(null),[k,p]=g.useState(null),[y,Z]=g.useState(null),[q,X]=g.useState(null);g.useEffect(()=>{f.getClusters().then(c=>{const z=c?.list||[];if(w(z),!s&&z.length>0){const K=z[0].code||String(z[0].id);d(`/kubernetes/${K}/namespace/${t||"default"}/${r}`,{replace:!0})}}).catch(()=>w([]))},[]),g.useEffect(()=>{s&&f.getNamespaces(s).then(c=>{const z=Array.isArray(c)?c:c?.list||c?.data||[];R(z),!t&&z.length>0&&d(`/kubernetes/${s}/namespace/${z[0]}/${r}`,{replace:!0})}).catch(()=>R([]))},[s]);const Y=g.useCallback(async()=>{if(!(!s||!t)){l(!0);try{let c=[];switch(r){case"deployments":c=await f.getNamespaceDeployments(s,t).catch(()=>[]);break;case"pods":c=await f.getNamespacePods(s,t).catch(()=>[]);break;case"services":c=await f.getNamespaceServices(s,t).catch(()=>[]);break;case"ingresses":c=await f.getNamespaceIngresses(s,t).catch(()=>[]);break;case"configmaps":c=await f.getNamespaceConfigMaps(s,t).catch(()=>[]);break;case"secrets":c=await f.getNamespaceSecrets(s,t).catch(()=>[]);break;case"hpas":c=await f.getHPAs(s,t).catch(()=>[]);break;case"cronjobs":c=await f.getCronJobs(s,t).catch(()=>[]);break;case"pvcs":c=await f.getPVCs(s,t).catch(()=>[]);break;case"statefulsets":c=await f.getStatefulSets(s,t).catch(()=>[]);break;case"daemonsets":c=await f.getDaemonSets(s,t).catch(()=>[]);break;case"serviceaccounts":c=await f.getServiceAccounts(s,t).catch(()=>[]);break;case"roles":c=await f.getRoles(s,t).catch(()=>[]);break;case"rolebindings":c=await f.getRoleBindings(s,t).catch(()=>[]);break}u(Array.isArray(c)?c:c?.list||c?.data||[])}catch{u([])}finally{l(!1)}}},[s,t,r]);g.useEffect(()=>{Y()},[Y]);const D=m.filter(c=>(c.name||"").toLowerCase().includes(h.toLowerCase())),S=c=>{r==="deployments"?d(`/kubernetes/${s}/namespace/${t}/workload/view/Deployment/${c.name}`):r==="statefulsets"?d(`/kubernetes/${s}/namespace/${t}/workload/view/StatefulSet/${c.name}`):r==="daemonsets"&&d(`/kubernetes/${s}/namespace/${t}/workload/view/DaemonSet/${c.name}`)},L=c=>n({resource:r,name:c}),ee=c=>{["configmaps","secrets","services","ingresses","pvcs"].includes(r)?p({resource:r,name:c}):n({resource:r,name:c,editMode:!0})},me=()=>f.exportAsCSV(`${r}-${s}-${t}.csv`,D),ue=()=>f.exportAsJSON(`${r}-${s}-${t}.json`,D),pe=g.useMemo(()=>[{type:"deployments",label:"Deployments",icon:O},{type:"statefulsets",label:"StatefulSets",icon:O},{type:"daemonsets",label:"DaemonSets",icon:O},{type:"pods",label:"Pods",icon:de},{type:"cronjobs",label:"CronJobs",icon:ne},{type:"services",label:"Services",icon:Q},{type:"ingresses",label:"Ingresses",icon:Q},{type:"configmaps",label:"ConfigMaps",icon:ce},{type:"secrets",label:"Secrets",icon:T},{type:"hpas",label:"HPAs",icon:le},{type:"pvcs",label:"存储卷",icon:O},{type:"serviceaccounts",label:"ServiceAccounts",icon:T},{type:"roles",label:"Roles",icon:T},{type:"rolebindings",label:"RoleBindings",icon:T}],[]);return x?e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:454:5",className:"space-y-4",children:[j&&e.jsx(Se,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:456:9",clusterCode:s||"",namespace:t||"",resource:j.resource,name:j.name,onClose:()=>n(null),onSaved:Y,cleanBeforeEdit:!0,autoEdit:j.editMode===!0}),k&&e.jsx(Ae,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:468:9",clusterCode:s||"",namespace:t||"",resource:k.resource,name:k.name,onClose:()=>p(null),onSaved:Y}),e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:477:7",className:"flex items-center gap-2 text-sm text-slate-500",children:[e.jsx(se,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:478:9",to:"/kubernetes",className:"hover:text-slate-300 transition-colors",children:"集群"}),s&&e.jsxs(e.Fragment,{children:[e.jsx(te,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:479:27",className:"h-3 w-3"}),e.jsx(se,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:479:63",to:`/kubernetes/${s}`,className:"hover:text-slate-300 transition-colors",children:s})]}),t&&e.jsxs(e.Fragment,{children:[e.jsx(te,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:480:25",className:"h-3 w-3"}),e.jsx(se,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:480:61",to:`/kubernetes/${s}/namespace/${t}`,className:"hover:text-slate-300 transition-colors",children:t})]}),e.jsx(te,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:481:9",className:"h-3 w-3"}),e.jsx("span",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:481:45",className:"text-slate-300",children:x.title})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:483:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:484:9",children:[e.jsx("h1",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:485:11",className:"text-2xl font-bold text-slate-100",children:x.title}),e.jsx("p",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:486:11",className:"text-sm text-slate-500 mt-1",children:x.subtitle})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:488:9",className:"flex items-center gap-2",children:[e.jsxs(I,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:489:11",value:s||"",onValueChange:c=>d(`/kubernetes/${c}/namespace/${t||"default"}/${r}`),children:[e.jsx(F,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:490:13",className:"w-48 h-9 bg-slate-800/50 border-slate-700 text-slate-200",children:e.jsx(H,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:490:97",placeholder:"选择集群"})}),e.jsx(J,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:491:13",className:"bg-slate-800 border-slate-700",children:v.map(c=>e.jsx($,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:491:91",value:c.code||String(c.id),children:c.name},c.id))})]}),e.jsxs(I,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:493:11",value:t||"",onValueChange:c=>d(`/kubernetes/${s}/namespace/${c}/${r}`),children:[e.jsx(F,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:494:13",className:"w-40 h-9 bg-slate-800/50 border-slate-700 text-slate-200",children:e.jsx(H,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:494:97",placeholder:"命名空间"})}),e.jsx(J,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:495:13",className:"bg-slate-800 border-slate-700 max-h-[300px]",children:V.map(c=>e.jsx($,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:495:108",value:c,children:c},c))})]}),e.jsx(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:497:11",variant:"outline",size:"icon",className:"h-9 w-9 border-slate-700 text-slate-400",onClick:Y,disabled:b,children:b?e.jsx(A,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:498:24",className:"h-4 w-4 animate-spin"}):e.jsx(Me,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:498:71",className:"h-4 w-4"})}),e.jsxs(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:500:11",variant:"outline",size:"sm",className:"h-9 border-slate-700 text-slate-400 text-xs",onClick:me,title:"导出CSV",children:[e.jsx(oe,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:501:13",className:"h-3 w-3 mr-1"}),"CSV"]}),e.jsxs(i,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:503:11",variant:"outline",size:"sm",className:"h-9 border-slate-700 text-slate-400 text-xs",onClick:ue,title:"导出JSON",children:[e.jsx(oe,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:504:13",className:"h-3 w-3 mr-1"}),"JSON"]})]})]}),e.jsx("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:508:7",className:"flex items-center gap-1 bg-slate-900/50 border border-slate-800 rounded-lg p-1 overflow-x-auto",children:pe.map(c=>e.jsxs(se,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:510:11",to:`/kubernetes/${s}/namespace/${t}/${c.type}`,className:`flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-md transition-colors whitespace-nowrap ${c.type===r?"bg-blue-600/20 text-blue-400":"text-slate-400 hover:text-slate-200 hover:bg-slate-800/50"}`,children:[e.jsx(c.icon,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:512:13",className:"h-3 w-3"}),c.label]},c.type))}),e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:516:7",className:"relative w-56",children:[e.jsx(ke,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:517:9",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(P,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:518:9",placeholder:"搜索...",value:h,onChange:c=>N(c.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200"})]}),e.jsx(Re,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:520:7",className:"bg-slate-900 border-slate-800",children:e.jsx(je,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:521:9",className:"p-0",children:e.jsxs(Pe,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:522:11",children:[e.jsx(ye,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:523:13",children:e.jsx(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:523:26",className:"border-slate-800 hover:bg-transparent",children:x.columns.map(c=>e.jsx(fe,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:523:115",className:"text-slate-400",children:c},c))})}),e.jsx(Ee,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:524:13",children:b?e.jsx(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:526:17",children:e.jsxs(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:526:27",colSpan:x.columns.length,className:"text-center text-slate-500 py-12",children:[e.jsx(A,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:526:115",className:"h-5 w-5 animate-spin mx-auto mb-2"}),"加载中..."]})}):D.length===0?e.jsx(C,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:528:17",children:e.jsxs(a,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:528:27",colSpan:x.columns.length,className:"text-center text-slate-500 py-12",children:[e.jsx(x.icon,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:528:115",className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"暂无 ",x.title]})}):D.map(c=>x.renderRow(c,{clusterCode:s||"",namespace:t||"",onDetail:S,onYaml:L,onEdit:ee,onTerminal:z=>Z(z),onFileBrowser:z=>X(z)}))})]})})}),e.jsx(ze,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:538:7",open:!!y,onOpenChange:c=>{c||Z(null)},clusterId:v[0]?.id||v[0]?.code||s||"",namespace:t||"",podName:y?.name||"",containers:(y?.containers||[]).map(c=>c.name).filter(Boolean)}),e.jsx(_e,{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:547:7",open:!!q,onOpenChange:c=>{c||X(null)},clusterCode:s||"",namespace:t||"",podName:q?.name||"",containers:(q?.containers||[]).map(c=>c.name).filter(Boolean)})]}):e.jsxs("div",{"code-path":"src/components/kubernetes/NamespaceResourcePage.tsx:451:23",className:"text-slate-400 p-8 text-center",children:["未知资源类型: ",r]})}export{gs as default}; diff --git a/backend/static/assets/NodeDetailPage-MBEvAdV0.js b/backend/static/assets/NodeDetailPage-MBEvAdV0.js new file mode 100644 index 0000000..82fe2e4 --- /dev/null +++ b/backend/static/assets/NodeDetailPage-MBEvAdV0.js @@ -0,0 +1 @@ +import{i as R,k as M,r as p,j as e,m as g,n as k,q,B,L as j,T as P,w as S,A as F,N as L,v as U}from"./index-DfyorCky.js";import{C as c,a as o}from"./card-C55cvSHg.js";import{B as l}from"./badge-xNW8x0G1.js";import{T as A,a as E,b as D,c as n,d as I,e as r}from"./table-5sHV4Akp.js";import{k as z}from"./kubernetes-J8O09fK7.js";import{R as H}from"./refresh-cw-DUB_tAG-.js";import{C as f}from"./circle-check-DWcXrx2k.js";function X(){const{clusterCode:d,nodeName:i}=R();M();const[s,N]=p.useState(null),[h,u]=p.useState(!1),b=p.useCallback(async()=>{if(!(!d||!i)){u(!0);try{const t=await z.getNodeDetail(d,i);N(t)}catch{N(null)}finally{u(!1)}}},[d,i]);p.useEffect(()=>{b()},[b]);const x=({label:t,used:a,total:v,unit:w,pct:C,color:$})=>{const m=Math.min(Math.max(C||0,0),100),T=m>80?"bg-red-500":m>60?"bg-amber-500":"bg-emerald-500";return e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:53:7",className:"space-y-1.5",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:54:9",className:"flex items-center justify-between text-xs",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:55:11",className:"text-slate-400",children:t}),e.jsxs("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:56:11",className:"text-slate-300 font-medium",children:[a," / ",v," ",w]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:60:9",className:"flex items-center gap-2",children:[e.jsx("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:61:11",className:"flex-1 h-2 rounded-full bg-slate-700/50 overflow-hidden",children:e.jsx("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:62:13",className:`h-full rounded-full ${T} transition-all duration-500`,style:{width:`${m}%`}})}),e.jsxs("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:64:11",className:`text-xs font-semibold min-w-[40px] text-right ${$}`,children:[m.toFixed(0),"%"]})]})]})},_=(t,a)=>a==="True"?t==="Ready"?"bg-emerald-500/20 text-emerald-400":"bg-red-500/20 text-red-400":"bg-slate-500/20 text-slate-400",y=t=>t==="NoSchedule"?"bg-red-500/20 text-red-400 border-red-500/30":t==="NoExecute"?"bg-red-600/20 text-red-300 border-red-600/30":t==="PreferNoSchedule"?"bg-amber-500/20 text-amber-400 border-amber-500/30":"bg-slate-500/20 text-slate-400 border-slate-500/30";return e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:89:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:91:7",className:"flex items-center gap-2 text-sm text-slate-500",children:[e.jsx(g,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:92:9",to:"/kubernetes",className:"hover:text-slate-300 transition-colors",children:"集群"}),e.jsx(k,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:93:9",className:"h-3 w-3"}),e.jsx(g,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:94:9",to:`/kubernetes/${d}`,className:"hover:text-slate-300 transition-colors",children:d}),e.jsx(k,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:95:9",className:"h-3 w-3"}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:96:9",className:"text-slate-300",children:i})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:100:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:101:9",className:"flex items-center gap-3",children:[e.jsx("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:102:11",className:"flex items-center justify-center w-12 h-12 rounded-xl bg-slate-800 border border-slate-700",children:e.jsx(q,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:103:13",className:"h-6 w-6 text-blue-400"})}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:105:11",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:106:13",className:"flex items-center gap-2",children:[e.jsx("h1",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:107:15",className:"text-2xl font-bold text-slate-100",children:i}),e.jsx(l,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:108:15",className:s?.role==="master"?"bg-blue-500/20 text-blue-400 border-blue-500/30":"bg-slate-500/20 text-slate-400 border-slate-500/30",children:s?.role||"worker"}),e.jsx(l,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:111:15",className:s?.status==="Ready"?"bg-emerald-500/20 text-emerald-400":"bg-red-500/20 text-red-400",children:s?.status||"Unknown"})]}),e.jsxs("p",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:115:13",className:"text-sm text-slate-500 mt-0.5",children:[s?.internal_ip&&`${s.internal_ip}`,s?.hostname&&` · ${s.hostname}`]})]})]}),e.jsx(B,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:121:9",variant:"outline",size:"icon",className:"h-9 w-9 border-slate-700 text-slate-400",onClick:b,disabled:h,children:h?e.jsx(j,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:123:22",className:"h-4 w-4 animate-spin"}):e.jsx(H,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:123:69",className:"h-4 w-4"})})]}),h&&!s?e.jsx(c,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:128:9",className:"bg-slate-900 border-slate-800",children:e.jsx(o,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:129:11",className:"py-16 flex items-center justify-center",children:e.jsx(j,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:130:13",className:"h-6 w-6 animate-spin text-slate-500"})})}):s?e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:143:11",className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(c,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:145:13",className:"bg-slate-900 border-slate-800",children:e.jsxs(o,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:146:15",className:"p-4",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:147:17",className:"text-sm font-semibold text-slate-200 mb-3 flex items-center gap-2",children:[e.jsx(S,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:148:19",className:"h-4 w-4 text-cyan-400"}),"系统信息"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:150:17",className:"space-y-2 text-xs",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:151:19",className:"flex items-center justify-between py-1.5 border-b border-slate-800/50",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:152:21",className:"text-slate-500",children:"容器运行时"}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:153:21",className:"text-slate-300 font-mono",children:s.container_runtime||"-"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:155:19",className:"flex items-center justify-between py-1.5 border-b border-slate-800/50",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:156:21",className:"text-slate-500",children:"Kubelet"}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:157:21",className:"text-slate-300 font-mono",children:s.kubelet_version||"-"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:159:19",className:"flex items-center justify-between py-1.5 border-b border-slate-800/50",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:160:21",className:"text-slate-500",children:"操作系统"}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:161:21",className:"text-slate-300",children:s.os_image||"-"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:163:19",className:"flex items-center justify-between py-1.5 border-b border-slate-800/50",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:164:21",className:"text-slate-500",children:"内核版本"}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:165:21",className:"text-slate-300 font-mono",children:s.kernel_version||"-"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:167:19",className:"flex items-center justify-between py-1.5 border-b border-slate-800/50",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:168:21",className:"text-slate-500",children:"架构"}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:169:21",className:"text-slate-300 font-mono",children:s.architecture||"-"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:171:19",className:"flex items-center justify-between py-1.5 border-b border-slate-800/50",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:172:21",className:"text-slate-500",children:"创建时间"}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:173:21",className:"text-slate-300",children:s.creation_time?new Date(s.creation_time).toLocaleString("zh-CN"):"-"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:175:19",className:"flex items-center justify-between py-1.5",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:176:21",className:"text-slate-500",children:"Pod CIDR"}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:177:21",className:"text-slate-300 font-mono",children:s.pod_cidr||"-"})]})]})]})}),e.jsx(c,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:184:13",className:"bg-slate-900 border-slate-800",children:e.jsxs(o,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:185:15",className:"p-4",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:186:17",className:"text-sm font-semibold text-slate-200 mb-3 flex items-center gap-2",children:[e.jsx(F,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:187:19",className:"h-4 w-4 text-emerald-400"}),"资源分配率"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:189:17",className:"space-y-4 mt-4",children:[e.jsx(x,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:191:19",label:"CPU 已分配",used:`${(s.cpu_request_m/1e3).toFixed(2)} 核`,total:`${s.cpu_allocatable} 核`,unit:"",pct:s.cpu_alloc_pct,color:"text-emerald-400"}),s.cpu_usage_m&&e.jsx(x,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:201:21",label:"CPU 实时使用",used:s.cpu_usage_m,total:`${s.cpu_capacity} 核`,unit:"",pct:parseFloat(s.cpu_usage_m.replace("m",""))/(s.cpu_capacity*1e3)*100,color:"text-blue-400"}),e.jsx(x,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:211:19",label:"内存已分配",used:`${s.mem_request_mi} Mi`,total:`${s.mem_allocatable_mb} Mi`,unit:"",pct:s.mem_alloc_pct,color:"text-emerald-400"}),s.mem_usage_mi&&e.jsx(x,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:221:21",label:"内存实时使用",used:s.mem_usage_mi,total:`${s.mem_capacity_mb} Mi`,unit:"",pct:parseFloat(s.mem_usage_mi.replace("Mi","").replace("Ki","").replace("Gi",""))/s.mem_capacity_mb*100,color:"text-blue-400"}),e.jsx(x,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:231:19",label:"Pod 数量",used:`${s.pod_count}`,total:`${s.pod_allocatable}`,unit:"",pct:s.pod_alloc_pct,color:"text-emerald-400"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:241:17",className:"mt-4 pt-3 border-t border-slate-800/50 space-y-1 text-[11px] text-slate-500",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:242:19",className:"flex justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:243:21",children:"CPU 容量 / 可分配"}),e.jsxs("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:244:21",className:"font-mono",children:[s.cpu_capacity," / ",s.cpu_allocatable," 核"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:246:19",className:"flex justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:247:21",children:"内存容量 / 可分配"}),e.jsxs("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:248:21",className:"font-mono",children:[s.mem_capacity_mb," / ",s.mem_allocatable_mb," Mi"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:250:19",className:"flex justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:251:21",children:"Pod 容量 / 可分配"}),e.jsxs("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:252:21",className:"font-mono",children:[s.pod_capacity," / ",s.pod_allocatable]})]})]})]})})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:260:11",className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(c,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:262:13",className:"bg-slate-900 border-slate-800",children:e.jsxs(o,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:263:15",className:"p-4",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:264:17",className:"text-sm font-semibold text-slate-200 mb-3 flex items-center gap-2",children:[e.jsx(f,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:265:19",className:"h-4 w-4 text-blue-400"}),"节点条件"]}),!s.conditions||s.conditions.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:268:19",className:"text-xs text-slate-500 py-4 text-center",children:"无条件数据"}):e.jsx("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:270:19",className:"space-y-2",children:s.conditions.map((t,a)=>e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:272:23",className:"flex items-start gap-2 text-xs py-1.5 border-b border-slate-800/30 last:border-0",children:[e.jsxs(l,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:273:25",className:_(t.type,t.status),children:[t.status==="True"?e.jsx(f,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:274:53",className:"h-3 w-3 mr-1"}):null,t.type]}),e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:277:25",className:"flex-1 min-w-0",children:[t.reason&&e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:278:43",className:"text-slate-400 block",children:t.reason}),t.message&&e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:279:44",className:"text-slate-600 text-[11px] block truncate",children:t.message})]})]},a))})]})}),e.jsx(c,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:289:13",className:"bg-slate-900 border-slate-800",children:e.jsxs(o,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:290:15",className:"p-4",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:291:17",className:"text-sm font-semibold text-slate-200 mb-3 flex items-center gap-2",children:[e.jsx(P,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:292:19",className:"h-4 w-4 text-amber-400"}),"污点 (Taints)"]}),!s.taints||s.taints.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:295:19",className:"text-xs text-slate-500 py-4 text-center",children:"无污点"}):e.jsx("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:297:19",className:"space-y-2",children:s.taints.map((t,a)=>e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:299:23",className:"flex items-center gap-2 text-xs",children:[e.jsx(l,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:300:25",className:y(t.effect),children:t.effect}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:301:25",className:"text-slate-300 font-mono",children:t.key}),t.value&&e.jsxs("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:302:37",className:"text-slate-500",children:["= ",t.value]})]},a))})]})})]}),s.labels&&s.labels.length>0&&e.jsx(c,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:313:13",className:"bg-slate-900 border-slate-800",children:e.jsxs(o,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:314:15",className:"p-4",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:315:17",className:"text-sm font-semibold text-slate-200 mb-3 flex items-center gap-2",children:[e.jsx(L,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:316:19",className:"h-4 w-4 text-slate-400"}),"标签 (",s.labels.length,")"]}),e.jsx("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:318:17",className:"flex flex-wrap gap-1.5",children:s.labels.map((t,a)=>e.jsxs("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:320:21",className:"flex items-center gap-1 bg-slate-800/50 border border-slate-700/50 rounded px-2 py-0.5 text-[11px]",children:[e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:321:23",className:"text-slate-400",children:t.key}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:322:23",className:"text-slate-600",children:":"}),e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:323:23",className:"text-slate-300",children:t.value})]},a))})]})}),e.jsx(c,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:332:11",className:"bg-slate-900 border-slate-800",children:e.jsxs(o,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:333:13",className:"p-0",children:[e.jsx("div",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:334:15",className:"px-4 py-3 border-b border-slate-800",children:e.jsxs("h2",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:335:17",className:"text-sm font-semibold text-slate-200 flex items-center gap-2",children:[e.jsx(U,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:336:19",className:"h-4 w-4 text-cyan-400"}),"节点上的 Pod",e.jsx(l,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:338:19",className:"bg-slate-700/50 text-slate-300",children:s.pods?.length||0})]})}),!s.pods||s.pods.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:342:17",className:"text-xs text-slate-500 py-8 text-center",children:"该节点上暂无 Pod"}):e.jsxs(A,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:344:17",children:[e.jsx(E,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:345:19",children:e.jsxs(D,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:346:21",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(n,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:347:23",className:"text-slate-400",children:"命名空间"}),e.jsx(n,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:348:23",className:"text-slate-400",children:"名称"}),e.jsx(n,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:349:23",className:"text-slate-400",children:"状态"}),e.jsx(n,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:350:23",className:"text-slate-400",children:"IP"}),e.jsx(n,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:351:23",className:"text-slate-400",children:"CPU 请求"}),e.jsx(n,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:352:23",className:"text-slate-400",children:"内存请求"}),e.jsx(n,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:353:23",className:"text-slate-400",children:"重启次数"})]})}),e.jsx(I,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:356:19",children:s.pods.map((t,a)=>e.jsxs(D,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:358:23",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(r,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:359:25",className:"text-sm text-slate-400",children:t.namespace}),e.jsx(r,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:360:25",className:"text-sm font-medium text-slate-200",children:t.name}),e.jsx(r,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:361:25",children:e.jsx(l,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:362:27",className:t.status==="Running"?"bg-emerald-500/20 text-emerald-400":t.status==="Pending"?"bg-amber-500/20 text-amber-400":"bg-red-500/20 text-red-400",children:t.status})}),e.jsx(r,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:368:25",className:"text-xs text-slate-400 font-mono",children:t.ip||"-"}),e.jsx(r,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:369:25",className:"text-xs text-slate-400",children:t.cpu_request_m>0?`${t.cpu_request_m}m`:"-"}),e.jsx(r,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:372:25",className:"text-xs text-slate-400",children:t.mem_request_mi>0?`${t.mem_request_mi}Mi`:"-"}),e.jsx(r,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:375:25",className:"text-xs",children:t.restart_count>0?e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:377:29",className:"text-amber-400",children:t.restart_count}):e.jsx("span",{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:379:29",className:"text-slate-600",children:"0"})})]},a))})]})]})})]}):e.jsx(c,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:134:9",className:"bg-slate-900 border-slate-800",children:e.jsxs(o,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:135:11",className:"py-16 text-center text-slate-500",children:[e.jsx(P,{"code-path":"src/components/kubernetes/NodeDetailPage.tsx:136:13",className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"无法加载节点详情"]})})]})}export{X as default}; diff --git a/backend/static/assets/PipelineEditor-DrEZIuvh.js b/backend/static/assets/PipelineEditor-DrEZIuvh.js new file mode 100644 index 0000000..482ad39 --- /dev/null +++ b/backend/static/assets/PipelineEditor-DrEZIuvh.js @@ -0,0 +1 @@ +import{g as B,i as Ke,r as i,a as Xe,j as e,L as J,a0 as V,B as p,t as Pe,a4 as Ee,n as ve,I as v,x as ue,a9 as Ye,a5 as Qe,aa as es,v as ss,F as ts,H as os,q as ns,D as cs,b as ds,c as is,d as rs}from"./index-DfyorCky.js";import{C as P,a as E}from"./card-C55cvSHg.js";import{B as j}from"./badge-xNW8x0G1.js";import{T as as,a as ps,b as k,c as C}from"./tabs-CIh_yD4s.js";import{S as $,a as R,b as O,c as I,d as h,C as ls}from"./select-D5qUzdAs.js";import{T as xs}from"./textarea-NXY8u32k.js";import{S as G}from"./switch-CGiGgOnh.js";import{L as y}from"./label-BK0h2apY.js";import{t as m}from"./index-a3ybMjbR.js";import{d as ms,p as g}from"./deploy-B3Sg3N1U.js";import{S as hs}from"./save-DoGGjfwC.js";import{P as ys}from"./play-cdPayOtJ.js";import{P as D}from"./plus-CUG-9kpu.js";import{T as S}from"./trash-2-Dx32pOzT.js";import{C as Ne}from"./circle-stop-s4wxdTEV.js";import{F as gs}from"./file-text-C9G5abwR.js";import{U as js}from"./user-plus-BwUWtcQl.js";import{Z as Ps}from"./zap-D2uWSK32.js";import{W as we}from"./wrench-KfbhOOJm.js";import"./index-CWVNW_qu.js";const Es=[["path",{d:"M14 2v6a2 2 0 0 0 .245.96l5.51 10.08A2 2 0 0 1 18 22H6a2 2 0 0 1-1.755-2.96l5.51-10.08A2 2 0 0 0 10 8V2",key:"18mbvz"}],["path",{d:"M6.453 15h11.094",key:"3shlmq"}],["path",{d:"M8.5 2h7",key:"csnxdl"}]],vs=B("flask-conical",Es);const us=[["path",{d:"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1fvzgz"}],["path",{d:"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"1kc0my"}],["path",{d:"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8",key:"10h0bg"}],["path",{d:"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"1s1gnw"}]],be=B("hand",us);const Ns=[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]],bs=B("scroll-text",Ns);const fs=[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]],fe=B("webhook",fs),ws={source:"拉取代码",build:"构建",deploy:"部署",test:"测试",custom:"自定义"},ke={GitBranch:V,Wrench:we,Server:ns,FlaskConical:vs,Zap:Ps,Terminal:os,FileCode:ts,Container:ss};function ks(){return`tsk-${Date.now()}-${Math.random().toString(36).slice(2,7)}`}function Ce(r){if(!r)return"-";if(r<60)return`${r}s`;const d=Math.floor(r/60),c=r%60;return c>0?`${d}分${c}秒`:`${d}分`}function Cs({task:r,selected:d,onSelect:c,onDelete:u}){const a=ke[r.icon]||we;return e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:75:5",onClick:c,className:`flex items-center gap-3 p-3 rounded-md border cursor-pointer transition-all group ${d?"border-blue-500 bg-blue-500/10":"border-[var(--dg-border)] hover:border-slate-400 bg-[var(--dg-bg-secondary)]"}`,children:[e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:81:7",className:`p-1.5 rounded ${d?"bg-blue-100":"bg-slate-100 dark:bg-slate-800"}`,children:e.jsx(a,{"code-path":"src/components/deploy/PipelineEditor.tsx:82:9",className:`w-4 h-4 ${d?"text-blue-600":"text-[var(--dg-text-secondary)]"}`})}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:84:7",className:"flex-1 min-w-0",children:[e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:85:9",className:"text-sm font-medium text-[var(--dg-text-primary)] truncate",children:r.name}),e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:86:9",className:"text-xs text-[var(--dg-text-secondary)]",children:r.type})]}),e.jsx(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:88:7",variant:"ghost",size:"icon",className:"h-6 w-6 opacity-0 group-hover:opacity-100",onClick:x=>{x.stopPropagation(),u()},children:e.jsx(S,{"code-path":"src/components/deploy/PipelineEditor.tsx:89:9",className:"w-3.5 h-3.5 text-red-500"})})]})}function Ss({task:r,onUpdate:d}){return r?e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:99:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:100:7",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/PipelineEditor.tsx:100:34",className:"text-xs",children:"任务名称"}),e.jsx(v,{"code-path":"src/components/deploy/PipelineEditor.tsx:100:73",value:r.name,onChange:c=>d({...r,name:c.target.value}),className:"h-8 text-sm"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:101:7",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:102:9",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/PipelineEditor.tsx:102:36",className:"text-xs",children:"类型"}),e.jsxs($,{"code-path":"src/components/deploy/PipelineEditor.tsx:103:11",value:r.type,onValueChange:c=>d({...r,type:c}),children:[e.jsx(R,{"code-path":"src/components/deploy/PipelineEditor.tsx:103:89",className:"h-8 text-sm",children:e.jsx(O,{"code-path":"src/components/deploy/PipelineEditor.tsx:103:128"})}),e.jsxs(I,{"code-path":"src/components/deploy/PipelineEditor.tsx:104:13",children:[e.jsx(h,{"code-path":"src/components/deploy/PipelineEditor.tsx:104:28",value:"build",children:"构建"}),e.jsx(h,{"code-path":"src/components/deploy/PipelineEditor.tsx:104:69",value:"deploy",children:"部署"}),e.jsx(h,{"code-path":"src/components/deploy/PipelineEditor.tsx:104:111",value:"test",children:"测试"}),e.jsx(h,{"code-path":"src/components/deploy/PipelineEditor.tsx:104:151",value:"custom",children:"自定义"})]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:106:9",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/PipelineEditor.tsx:106:36",className:"text-xs",children:"图标"}),e.jsxs($,{"code-path":"src/components/deploy/PipelineEditor.tsx:107:11",value:r.icon,onValueChange:c=>d({...r,icon:c}),children:[e.jsx(R,{"code-path":"src/components/deploy/PipelineEditor.tsx:107:89",className:"h-8 text-sm",children:e.jsx(O,{"code-path":"src/components/deploy/PipelineEditor.tsx:107:128"})}),e.jsx(I,{"code-path":"src/components/deploy/PipelineEditor.tsx:108:13",children:Object.entries(ke).map(([c])=>e.jsx(h,{"code-path":"src/components/deploy/PipelineEditor.tsx:108:69",value:c,children:c},c))})]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:111:7",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/PipelineEditor.tsx:111:34",className:"text-xs",children:"脚本类型"}),e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:112:9",className:"flex gap-2",children:["shell","python"].map(c=>e.jsx(j,{"code-path":"src/components/deploy/PipelineEditor.tsx:112:68",variant:r.script_type===c?"default":"outline",className:"cursor-pointer text-xs",onClick:()=>d({...r,script_type:c}),children:c},c))})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:114:7",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/PipelineEditor.tsx:114:34",className:"text-xs",children:"脚本内容"}),e.jsx(xs,{"code-path":"src/components/deploy/PipelineEditor.tsx:115:9",value:r.script,onChange:c=>d({...r,script:c.target.value}),className:"font-mono text-xs min-h-[200px] bg-slate-950 text-green-400",placeholder:"#!/bin/bash\\nset -e\\necho 'hello'"})]})]}):e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:97:21",className:"p-6 text-center text-[var(--dg-text-secondary)] text-sm",children:"选择一个任务开始编辑"})}function _s({open:r,onClose:d,run:c,logs:u}){return e.jsx(cs,{"code-path":"src/components/deploy/PipelineEditor.tsx:124:5",open:r,onOpenChange:d,children:e.jsxs(ds,{"code-path":"src/components/deploy/PipelineEditor.tsx:125:7",className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsx(is,{"code-path":"src/components/deploy/PipelineEditor.tsx:126:9",children:e.jsxs(rs,{"code-path":"src/components/deploy/PipelineEditor.tsx:126:23",className:"flex items-center gap-2",children:[e.jsx(bs,{"code-path":"src/components/deploy/PipelineEditor.tsx:126:72",className:"w-5 h-5"}),"执行日志 #",c?.build_number||c?.id]})}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:127:9",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:128:11",className:"flex flex-wrap gap-3 text-sm text-[var(--dg-text-secondary)]",children:[e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:129:13",children:["触发方式: ",c?.triggered_by||"manual"]}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:130:13",children:["分支: ",c?.branch||"-"]}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:131:13",children:["耗时: ",Ce(c?.duration)]}),e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:132:13",children:c?.created_at?new Date(c.created_at).toLocaleString("zh-CN"):"-"})]}),e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:134:11",className:"bg-slate-950 rounded-md p-3 max-h-[50vh] overflow-y-auto font-mono text-xs",children:u.length===0?e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:136:15",className:"text-slate-500 py-4 text-center",children:"暂无日志"}):u.map((a,x)=>e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:139:17",className:"flex gap-2 py-0.5",children:[e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:140:19",className:"text-slate-500 shrink-0",children:["[",a.time,"]"]}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:141:19",className:a.level==="error"?"text-red-400":a.level==="warn"?"text-yellow-400":a.level==="success"?"text-green-400":"text-slate-300",children:[a.level==="success"?"✓":a.level==="error"?"✗":a.level==="warn"?"!":">"," ",a.message]})]},x))})]})]})})}function Ks(){const{code:r}=Ke(),d=r||"",[c,u]=i.useState(null),[a,x]=i.useState([]),[_,T]=i.useState(null),[Se,W]=i.useState({}),[_e,Te]=i.useState("flow"),[Me,F]=i.useState(!0),[Z,K]=i.useState(!1),[H,X]=i.useState([]),[Y,ze]=i.useState([]),[U,Q]=i.useState([]),[Le,ee]=i.useState(!1),[N,M]=i.useState("manual"),[se,te]=i.useState(""),[oe,ne]=i.useState(""),[ce,de]=i.useState(""),[b,f]=i.useState([]),[z,ie]=i.useState(""),[q,re]=i.useState(""),[ae,Ae]=i.useState("editor"),[De,pe]=i.useState(!1),[Ve,$e]=i.useState(null),[Re,le]=i.useState([]),xe=Xe(),me=i.useCallback(async()=>{try{const s=await ms.getEnvironments();ze(Array.isArray(s)?s:s?.list||[])}catch{}},[]),L=i.useCallback(async()=>{ee(!0);try{const s=await g.getMembers(d);Q(Array.isArray(s)?s:s?.data||[])}catch{Q([])}finally{ee(!1)}},[d]),A=i.useCallback(async()=>{try{const s=await g.getRuns(d);X(Array.isArray(s)?s:s?.list||[])}catch{X([])}},[d]);i.useEffect(()=>{(async()=>{F(!0);try{const s=await g.getPipelineDetail(d);if(!s||!s.id){u(null),F(!1);return}u(s),M(s.trigger_mode||"manual"),te(s.watch_branches||""),ne(s.cron_expr||""),de(s.webhook_token||""),ie(s.environment_id||"");try{const n=s.variables?JSON.parse(s.variables):{};f(Object.entries(n).map(([o,t])=>[o,String(t)]))}catch{f([])}try{const n=s.stages?JSON.parse(s.stages):[],o=Array.isArray(n)?n:[];x(o);const t={};o.forEach(l=>{t[l.id]=!0}),W(t)}catch{x([])}}catch{m.error("加载失败")}finally{F(!1)}})(),me(),L(),A()},[d,me,L,A]);const he=a.flatMap(s=>s.tasks).find(s=>s.id===_)||null,Oe=s=>{x(n=>n.map(o=>({...o,tasks:o.tasks.map(t=>t.id===s.id?s:t)})))},Ie=s=>{const n={id:ks(),name:"新任务",type:"build",icon:"Wrench",config:{},script:"",script_type:"shell"};x(o=>o.map((t,l)=>l===s?{...t,tasks:[...t.tasks,n]}:t))},Be=s=>{x(n=>n.map(o=>({...o,tasks:o.tasks.filter(t=>t.id!==s)}))),_===s&&T(null)},We=()=>{const s={id:`stg-${Date.now()}`,name:"新阶段",type:"custom",tasks:[]};x(n=>[...n,s])},Fe=s=>{x(n=>n.filter((o,t)=>t!==s))},ye=(s,n)=>{const o=s+n;if(o<0||o>=a.length)return;const t=[...a];[t[s],t[o]]=[t[o],t[s]],x(t)},He=async()=>{K(!0);try{await g.updatePipeline(d,{stages:JSON.stringify(a),trigger_mode:N,watch_branches:se,cron_expr:oe,webhook_token:ce,environment_id:z?Number(z):null,variables:JSON.stringify(Object.fromEntries(b.filter(([s])=>s.trim())))}),m.success("已保存")}catch{m.error("保存失败")}finally{K(!1)}},Ue=async()=>{try{await g.triggerPipeline(d),m.success("已触发"),A()}catch{m.error("触发失败")}},qe=async s=>{if(await xe({title:"停止运行",description:"确定要停止此运行吗?",variant:"destructive"}))try{await g.stopRun(d,s),m.success("已停止"),A()}catch{m.error("停止失败")}},Je=async s=>{$e(s),pe(!0);try{const n=await g.getRunLog(d,s.id);le(n?.logs||[])}catch{le([])}},Ge=async()=>{if(!q.trim()){m.error("请输入用户名");return}try{await g.addMember(d,{username:q.trim(),role:ae}),m.success("已添加成员"),re(""),L()}catch(s){m.error(s?.message||"添加失败")}},ge=async s=>{if(await xe({title:"移除成员",description:"确定要移除此成员吗?",variant:"destructive"}))try{await g.removeMember(d,s),m.success("已移除"),L()}catch{m.error("移除失败")}},w=Y.find(s=>String(s.id)===String(z));return Me?e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:325:23",className:"flex items-center justify-center py-20",children:e.jsx(J,{"code-path":"src/components/deploy/PipelineEditor.tsx:325:79",className:"w-6 h-6 animate-spin"})}):c?e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:329:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:331:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:332:9",children:[e.jsxs("h1",{"code-path":"src/components/deploy/PipelineEditor.tsx:333:11",className:"text-xl font-bold flex items-center gap-2 text-[var(--dg-text-primary)]",children:[e.jsx(V,{"code-path":"src/components/deploy/PipelineEditor.tsx:334:13",className:"w-5 h-5 text-blue-500"}),c.name,w&&e.jsx(j,{"code-path":"src/components/deploy/PipelineEditor.tsx:336:26",style:{backgroundColor:w.color+"20",color:w.color,borderColor:w.color+"40"},className:"text-xs ml-2",children:w.display_name})]}),e.jsxs("p",{"code-path":"src/components/deploy/PipelineEditor.tsx:338:11",className:"text-sm text-[var(--dg-text-secondary)] mt-1",children:["code: ",c.code," · ",c.description]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:340:9",className:"flex items-center gap-2",children:[e.jsxs(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:341:11",variant:"outline",onClick:He,disabled:Z,children:[e.jsx(hs,{"code-path":"src/components/deploy/PipelineEditor.tsx:341:76",className:"w-4 h-4 mr-1"}),Z?"保存中...":"保存"]}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:342:11",variant:"default",onClick:Ue,children:[e.jsx(ys,{"code-path":"src/components/deploy/PipelineEditor.tsx:342:61",className:"w-4 h-4 mr-1"}),"运行"]})]})]}),e.jsx(P,{"code-path":"src/components/deploy/PipelineEditor.tsx:347:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(E,{"code-path":"src/components/deploy/PipelineEditor.tsx:348:9",className:"p-3 flex items-center gap-3",children:[e.jsx(Pe,{"code-path":"src/components/deploy/PipelineEditor.tsx:349:11",className:"w-4 h-4 text-[var(--dg-text-secondary)]"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:350:11",className:"text-sm text-[var(--dg-text-secondary)]",children:"部署环境:"}),e.jsxs($,{"code-path":"src/components/deploy/PipelineEditor.tsx:351:11",value:String(z),onValueChange:s=>ie(s==="__none"?"":s),children:[e.jsx(R,{"code-path":"src/components/deploy/PipelineEditor.tsx:352:13",className:"w-40 h-8 text-sm",children:e.jsx(O,{"code-path":"src/components/deploy/PipelineEditor.tsx:352:57",placeholder:"选择环境"})}),e.jsxs(I,{"code-path":"src/components/deploy/PipelineEditor.tsx:353:13",children:[e.jsx(h,{"code-path":"src/components/deploy/PipelineEditor.tsx:354:15",value:"__none",children:"未指定"}),Y.map(s=>e.jsx(h,{"code-path":"src/components/deploy/PipelineEditor.tsx:356:17",value:String(s.id),children:e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:357:19",className:"flex items-center gap-1.5",children:[e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:358:21",className:"w-2 h-2 rounded-full inline-block",style:{backgroundColor:s.color}}),s.display_name]})},s.id))]})]}),e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:365:11",className:"text-xs text-[var(--dg-text-secondary)] opacity-70",children:"选择后流水线执行记录会关联到对应环境"})]})}),e.jsxs(as,{"code-path":"src/components/deploy/PipelineEditor.tsx:369:7",value:_e,onValueChange:Te,children:[e.jsxs(ps,{"code-path":"src/components/deploy/PipelineEditor.tsx:370:9",children:[e.jsx(k,{"code-path":"src/components/deploy/PipelineEditor.tsx:371:11",value:"flow",children:"流程配置"}),e.jsx(k,{"code-path":"src/components/deploy/PipelineEditor.tsx:372:11",value:"triggers",children:"触发设置"}),e.jsx(k,{"code-path":"src/components/deploy/PipelineEditor.tsx:373:11",value:"variables",children:"变量"}),e.jsxs(k,{"code-path":"src/components/deploy/PipelineEditor.tsx:374:11",value:"runs",children:["发布记录 (",H.length,")"]}),e.jsxs(k,{"code-path":"src/components/deploy/PipelineEditor.tsx:375:11",value:"members",children:["成员管理 (",U.length,")"]})]}),e.jsx(C,{"code-path":"src/components/deploy/PipelineEditor.tsx:379:9",value:"flow",className:"mt-3",children:e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:380:11",className:"flex gap-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:381:13",className:"flex-1 space-y-2",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:382:15",className:"flex items-center justify-between mb-2",children:[e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:383:17",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:["流水线阶段 (",a.length,")"]}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:384:17",size:"sm",onClick:We,children:[e.jsx(D,{"code-path":"src/components/deploy/PipelineEditor.tsx:384:60",className:"w-3.5 h-3.5 mr-1"}),"添加阶段"]})]}),a.length===0?e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:387:17",className:"text-center py-12 border-2 border-dashed rounded-lg text-[var(--dg-text-secondary)]",children:"点击「添加阶段」开始"}):a.map((s,n)=>{const o=Se[s.id]!==!1;return e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:392:19",className:"space-y-1",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:393:21",className:"flex items-center gap-2 px-3 py-2 bg-[var(--dg-bg-tertiary)] rounded-t-md border border-b-0 border-[var(--dg-border)] cursor-pointer",onClick:()=>W(t=>({...t,[s.id]:!o})),children:[e.jsx(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:397:23",variant:"ghost",size:"icon",className:"h-5 w-5 p-0",onClick:t=>{t.stopPropagation(),W(l=>({...l,[s.id]:!o}))},children:o?e.jsx(Ee,{"code-path":"src/components/deploy/PipelineEditor.tsx:398:39",className:"w-3.5 h-3.5"}):e.jsx(ve,{"code-path":"src/components/deploy/PipelineEditor.tsx:398:81",className:"w-3.5 h-3.5"})}),e.jsx(v,{"code-path":"src/components/deploy/PipelineEditor.tsx:400:23",value:s.name,onChange:t=>x(l=>l.map((je,Ze)=>Ze===n?{...je,name:t.target.value}:je)),className:"h-7 text-sm font-medium border-none bg-transparent shadow-none flex-1 px-1",onClick:t=>t.stopPropagation()}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:406:23",className:"text-xs text-[var(--dg-text-secondary)]",children:[s.tasks.length," 任务"]}),e.jsx(j,{"code-path":"src/components/deploy/PipelineEditor.tsx:407:23",variant:"secondary",className:"text-xs",children:ws[s.type]||s.type}),e.jsx(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:408:23",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:t=>{t.stopPropagation(),ye(n,-1)},disabled:n===0,children:e.jsx(ls,{"code-path":"src/components/deploy/PipelineEditor.tsx:408:168",className:"w-3.5 h-3.5"})}),e.jsx(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:409:23",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:t=>{t.stopPropagation(),ye(n,1)},disabled:n===a.length-1,children:e.jsx(Ee,{"code-path":"src/components/deploy/PipelineEditor.tsx:409:183",className:"w-3.5 h-3.5"})}),e.jsx(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:410:23",variant:"ghost",size:"icon",className:"h-6 w-6 text-red-500",onClick:t=>{t.stopPropagation(),Fe(n)},children:e.jsx(S,{"code-path":"src/components/deploy/PipelineEditor.tsx:410:158",className:"w-3.5 h-3.5"})})]}),o&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:413:21",className:"border border-[var(--dg-border)] rounded-b-md p-3 space-y-2",children:[s.tasks.map(t=>e.jsx(Cs,{"code-path":"src/components/deploy/PipelineEditor.tsx:414:46",task:t,selected:_===t.id,onSelect:()=>T(_===t.id?null:t.id),onDelete:()=>Be(t.id)},t.id)),e.jsxs(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:415:23",variant:"outline",size:"sm",className:"w-full h-8 text-xs",onClick:()=>Ie(n),children:[e.jsx(D,{"code-path":"src/components/deploy/PipelineEditor.tsx:415:125",className:"w-3 h-3 mr-1"}),"添加任务"]})]}),nT(null),children:"关闭"})]}),e.jsx(Ss,{"code-path":"src/components/deploy/PipelineEditor.tsx:426:15",task:he,onUpdate:Oe,onClose:()=>T(null)})]})]})}),e.jsx(C,{"code-path":"src/components/deploy/PipelineEditor.tsx:432:9",value:"triggers",className:"mt-3",children:e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:433:11",className:"space-y-4 max-w-lg",children:[e.jsx(P,{"code-path":"src/components/deploy/PipelineEditor.tsx:434:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(E,{"code-path":"src/components/deploy/PipelineEditor.tsx:434:85",className:"pt-6 space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:435:15",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:435:66",className:"flex items-center gap-2 text-[var(--dg-text-primary)]",children:[e.jsx(V,{"code-path":"src/components/deploy/PipelineEditor.tsx:435:137",className:"w-5 h-5 text-blue-500"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:435:184",className:"font-medium",children:"Git Push 触发"})]}),e.jsx(G,{"code-path":"src/components/deploy/PipelineEditor.tsx:435:238",checked:N==="git_push",onCheckedChange:s=>M(s?"git_push":"manual")})]}),N==="git_push"&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:436:46",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/PipelineEditor.tsx:436:73",children:"监听分支"}),e.jsx(v,{"code-path":"src/components/deploy/PipelineEditor.tsx:436:92",value:se,onChange:s=>te(s.target.value),placeholder:"master, release/*",className:"h-9"})]})]})}),e.jsx(P,{"code-path":"src/components/deploy/PipelineEditor.tsx:438:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(E,{"code-path":"src/components/deploy/PipelineEditor.tsx:438:85",className:"pt-6 space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:439:15",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:439:66",className:"flex items-center gap-2 text-[var(--dg-text-primary)]",children:[e.jsx(ue,{"code-path":"src/components/deploy/PipelineEditor.tsx:439:137",className:"w-5 h-5 text-blue-500"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:439:180",className:"font-medium",children:"定时触发"})]}),e.jsx(G,{"code-path":"src/components/deploy/PipelineEditor.tsx:439:227",checked:N==="cron",onCheckedChange:s=>M(s?"cron":"manual")})]}),N==="cron"&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:440:42",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/PipelineEditor.tsx:440:69",children:"Cron 表达式"}),e.jsx(v,{"code-path":"src/components/deploy/PipelineEditor.tsx:440:92",value:oe,onChange:s=>ne(s.target.value),placeholder:"0 2 * * *",className:"h-9 font-mono"})]})]})}),e.jsx(P,{"code-path":"src/components/deploy/PipelineEditor.tsx:442:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(E,{"code-path":"src/components/deploy/PipelineEditor.tsx:442:85",className:"pt-6 space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:443:15",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:443:66",className:"flex items-center gap-2 text-[var(--dg-text-primary)]",children:[e.jsx(fe,{"code-path":"src/components/deploy/PipelineEditor.tsx:443:137",className:"w-5 h-5 text-blue-500"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:443:182",className:"font-medium",children:"Webhook 触发"})]}),e.jsx(G,{"code-path":"src/components/deploy/PipelineEditor.tsx:443:235",checked:N==="webhook",onCheckedChange:s=>M(s?"webhook":"manual")})]}),N==="webhook"&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:444:45",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/PipelineEditor.tsx:444:72",children:"Secret Token"}),e.jsx(v,{"code-path":"src/components/deploy/PipelineEditor.tsx:444:99",value:ce,onChange:s=>de(s.target.value),type:"password",placeholder:"输入签名密钥",className:"h-9"})]})]})}),e.jsx(P,{"code-path":"src/components/deploy/PipelineEditor.tsx:446:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(E,{"code-path":"src/components/deploy/PipelineEditor.tsx:446:85",className:"pt-6",children:e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:446:115",className:"flex items-center gap-2 text-[var(--dg-text-primary)]",children:[e.jsx(be,{"code-path":"src/components/deploy/PipelineEditor.tsx:446:186",className:"w-5 h-5 text-blue-500"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:446:228",className:"font-medium",children:"手动触发"}),e.jsx(j,{"code-path":"src/components/deploy/PipelineEditor.tsx:446:269",variant:"secondary",className:"text-xs",children:"默认启用"})]})})})]})}),e.jsx(C,{"code-path":"src/components/deploy/PipelineEditor.tsx:451:9",value:"variables",className:"mt-3",children:e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:452:11",className:"max-w-lg space-y-3",children:[b.map(([s,n],o)=>e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:454:15",className:"flex gap-2 items-center",children:[e.jsx(v,{"code-path":"src/components/deploy/PipelineEditor.tsx:455:17",value:s,onChange:t=>{const l=[...b];l[o][0]=t.target.value,f(l)},placeholder:"KEY",className:"h-9 w-40 font-mono text-sm"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:456:17",className:"text-[var(--dg-text-secondary)]",children:"="}),e.jsx(v,{"code-path":"src/components/deploy/PipelineEditor.tsx:457:17",value:n,onChange:t=>{const l=[...b];l[o][1]=t.target.value,f(l)},placeholder:"VALUE",className:"h-9 flex-1"}),e.jsx(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:458:17",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-500",onClick:()=>f(b.filter((t,l)=>l!==o)),children:e.jsx(S,{"code-path":"src/components/deploy/PipelineEditor.tsx:458:152",className:"w-3.5 h-3.5"})})]},o)),e.jsxs(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:461:13",variant:"outline",size:"sm",onClick:()=>f([...b,["",""]]),children:[e.jsx(D,{"code-path":"src/components/deploy/PipelineEditor.tsx:461:104",className:"w-3.5 h-3.5 mr-1"}),"添加变量"]})]})}),e.jsx(C,{"code-path":"src/components/deploy/PipelineEditor.tsx:466:9",value:"runs",className:"mt-3",children:H.length===0?e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:468:13",className:"text-center py-12 text-[var(--dg-text-secondary)]",children:"暂无执行记录"}):e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:470:13",className:"rounded-md border border-[var(--dg-border)] overflow-hidden",children:e.jsxs("table",{"code-path":"src/components/deploy/PipelineEditor.tsx:471:15",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/deploy/PipelineEditor.tsx:472:17",className:"bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]",children:e.jsxs("tr",{"code-path":"src/components/deploy/PipelineEditor.tsx:473:19",children:[e.jsx("th",{"code-path":"src/components/deploy/PipelineEditor.tsx:474:21",className:"px-3 py-2 text-left text-[var(--dg-text-secondary)]",children:"#"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineEditor.tsx:475:21",className:"px-3 py-2 text-left text-[var(--dg-text-secondary)]",children:"状态"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineEditor.tsx:476:21",className:"px-3 py-2 text-left text-[var(--dg-text-secondary)]",children:"触发方式"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineEditor.tsx:477:21",className:"px-3 py-2 text-left text-[var(--dg-text-secondary)]",children:"触发人"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineEditor.tsx:478:21",className:"px-3 py-2 text-left text-[var(--dg-text-secondary)]",children:"分支"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineEditor.tsx:479:21",className:"px-3 py-2 text-left text-[var(--dg-text-secondary)]",children:"耗时"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineEditor.tsx:480:21",className:"px-3 py-2 text-left text-[var(--dg-text-secondary)]",children:"时间"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineEditor.tsx:481:21",className:"px-3 py-2 text-right text-[var(--dg-text-secondary)]",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/deploy/PipelineEditor.tsx:484:17",children:H.map(s=>e.jsxs("tr",{"code-path":"src/components/deploy/PipelineEditor.tsx:486:21",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50",children:[e.jsxs("td",{"code-path":"src/components/deploy/PipelineEditor.tsx:487:23",className:"px-3 py-2 font-medium text-[var(--dg-text-primary)]",children:["#",s.build_number||s.id]}),e.jsx("td",{"code-path":"src/components/deploy/PipelineEditor.tsx:488:23",className:"px-3 py-2",children:s.status==="success"?e.jsxs(j,{"code-path":"src/components/deploy/PipelineEditor.tsx:489:51",className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",children:[e.jsx(Ye,{"code-path":"src/components/deploy/PipelineEditor.tsx:489:127",className:"w-3 h-3 mr-0.5"}),"成功"]}):s.status==="failed"?e.jsxs(j,{"code-path":"src/components/deploy/PipelineEditor.tsx:490:50",className:"bg-red-500/20 text-red-400 border-red-500/30",children:[e.jsx(Qe,{"code-path":"src/components/deploy/PipelineEditor.tsx:490:114",className:"w-3 h-3 mr-0.5"}),"失败"]}):s.status==="running"?e.jsxs(j,{"code-path":"src/components/deploy/PipelineEditor.tsx:491:51",className:"bg-blue-500/20 text-blue-400 border-blue-500/30",children:[e.jsx(J,{"code-path":"src/components/deploy/PipelineEditor.tsx:491:118",className:"w-3 h-3 animate-spin mr-0.5"}),"执行中"]}):s.status==="cancelled"?e.jsxs(j,{"code-path":"src/components/deploy/PipelineEditor.tsx:492:53",className:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30",children:[e.jsx(Ne,{"code-path":"src/components/deploy/PipelineEditor.tsx:492:126",className:"w-3 h-3 mr-0.5"}),"已停止"]}):e.jsx(j,{"code-path":"src/components/deploy/PipelineEditor.tsx:493:26",variant:"secondary",className:"text-[var(--dg-text-secondary)]",children:s.status})}),e.jsxs("td",{"code-path":"src/components/deploy/PipelineEditor.tsx:495:23",className:"px-3 py-2 text-[var(--dg-text-secondary)] text-xs",children:[s.trigger_mode==="manual"&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:496:57",className:"flex items-center gap-1",children:[e.jsx(be,{"code-path":"src/components/deploy/PipelineEditor.tsx:496:99",className:"w-3 h-3"}),"手动"]}),s.trigger_mode==="cron"&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:497:55",className:"flex items-center gap-1",children:[e.jsx(ue,{"code-path":"src/components/deploy/PipelineEditor.tsx:497:97",className:"w-3 h-3"}),"定时"]}),s.trigger_mode==="webhook"&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:498:58",className:"flex items-center gap-1",children:[e.jsx(fe,{"code-path":"src/components/deploy/PipelineEditor.tsx:498:100",className:"w-3 h-3"}),"Webhook"]}),s.trigger_mode==="git_push"&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:499:59",className:"flex items-center gap-1",children:[e.jsx(V,{"code-path":"src/components/deploy/PipelineEditor.tsx:499:101",className:"w-3 h-3"}),"Git Push"]}),!s.trigger_mode&&(s.triggered_by||"手动")]}),e.jsx("td",{"code-path":"src/components/deploy/PipelineEditor.tsx:502:23",className:"px-3 py-2 text-[var(--dg-text-secondary)] text-xs",children:s.triggered_by||"admin"}),e.jsx("td",{"code-path":"src/components/deploy/PipelineEditor.tsx:503:23",className:"px-3 py-2 text-[var(--dg-text-secondary)] font-mono text-xs",children:s.branch||"-"}),e.jsx("td",{"code-path":"src/components/deploy/PipelineEditor.tsx:504:23",className:"px-3 py-2 text-[var(--dg-text-secondary)]",children:Ce(s.duration)}),e.jsx("td",{"code-path":"src/components/deploy/PipelineEditor.tsx:505:23",className:"px-3 py-2 text-[var(--dg-text-secondary)] text-xs",children:s.created_at?new Date(s.created_at).toLocaleString("zh-CN"):"-"}),e.jsx("td",{"code-path":"src/components/deploy/PipelineEditor.tsx:506:23",className:"px-3 py-2 text-right",children:e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:507:25",className:"flex items-center justify-end gap-1",children:[e.jsxs(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:508:27",variant:"ghost",size:"sm",className:"h-7 text-xs text-blue-400 hover:text-blue-300",onClick:()=>Je(s),children:[e.jsx(gs,{"code-path":"src/components/deploy/PipelineEditor.tsx:508:152",className:"w-3.5 h-3.5 mr-1"}),"日志"]}),(s.status==="running"||s.status==="pending")&&e.jsxs(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:510:29",variant:"ghost",size:"sm",className:"h-7 text-xs text-red-400 hover:text-red-300",onClick:()=>qe(s.id),children:[e.jsx(Ne,{"code-path":"src/components/deploy/PipelineEditor.tsx:510:152",className:"w-3.5 h-3.5 mr-1"}),"停止"]})]})})]},s.id))})]})})}),e.jsx(C,{"code-path":"src/components/deploy/PipelineEditor.tsx:523:9",value:"members",className:"mt-3",children:e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:524:11",className:"max-w-xl space-y-4",children:[e.jsx(P,{"code-path":"src/components/deploy/PipelineEditor.tsx:526:13",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(E,{"code-path":"src/components/deploy/PipelineEditor.tsx:527:15",className:"p-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:528:17",className:"flex items-center gap-3",children:[e.jsx(js,{"code-path":"src/components/deploy/PipelineEditor.tsx:529:19",className:"w-4 h-4 text-blue-500"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:530:19",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:"添加用户"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:532:17",className:"flex items-end gap-3 mt-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:533:19",className:"flex-1 space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/PipelineEditor.tsx:534:21",className:"text-xs",children:"用户名"}),e.jsx(v,{"code-path":"src/components/deploy/PipelineEditor.tsx:535:21",value:q,onChange:s=>re(s.target.value),placeholder:"输入用户名",className:"h-9"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:537:19",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/PipelineEditor.tsx:538:21",className:"text-xs",children:"角色"}),e.jsxs($,{"code-path":"src/components/deploy/PipelineEditor.tsx:539:21",value:ae,onValueChange:Ae,children:[e.jsx(R,{"code-path":"src/components/deploy/PipelineEditor.tsx:540:23",className:"h-9 w-28",children:e.jsx(O,{"code-path":"src/components/deploy/PipelineEditor.tsx:540:59"})}),e.jsxs(I,{"code-path":"src/components/deploy/PipelineEditor.tsx:541:23",children:[e.jsx(h,{"code-path":"src/components/deploy/PipelineEditor.tsx:542:25",value:"owner",children:"拥有者"}),e.jsx(h,{"code-path":"src/components/deploy/PipelineEditor.tsx:543:25",value:"editor",children:"编辑者"}),e.jsx(h,{"code-path":"src/components/deploy/PipelineEditor.tsx:544:25",value:"viewer",children:"查看者"})]})]})]}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:548:19",onClick:Ge,className:"h-9",children:[e.jsx(D,{"code-path":"src/components/deploy/PipelineEditor.tsx:548:69",className:"w-4 h-4 mr-1"}),"添加"]})]})]})}),(()=>{const s=U.filter(o=>o.username),n=U.filter(o=>o.group_id);return e.jsxs(e.Fragment,{children:[e.jsx(P,{"code-path":"src/components/deploy/PipelineEditor.tsx:560:19",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(E,{"code-path":"src/components/deploy/PipelineEditor.tsx:561:21",className:"p-0",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:562:23",className:"px-4 py-2 text-xs font-medium text-[var(--dg-text-secondary)] border-b border-[var(--dg-border)]",children:["👤 直接用户授权 (",s.length,")"]}),Le?e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:566:25",className:"flex items-center justify-center py-6",children:e.jsx(J,{"code-path":"src/components/deploy/PipelineEditor.tsx:566:80",className:"w-5 h-5 animate-spin text-[var(--dg-text-secondary)]"})}):s.length===0?e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:568:25",className:"py-4 text-center text-[var(--dg-text-secondary)] text-xs",children:"暂无直接用户"}):e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:570:25",className:"divide-y divide-[var(--dg-border)]",children:s.map(o=>e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:572:29",className:"flex items-center justify-between px-4 py-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:573:31",className:"flex items-center gap-3",children:[e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:574:33",className:"w-8 h-8 rounded-full bg-blue-500/20 flex items-center justify-center",children:e.jsx(es,{"code-path":"src/components/deploy/PipelineEditor.tsx:574:119",className:"w-4 h-4 text-blue-400"})}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:575:33",children:[e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:576:35",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:o.username}),e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:577:35",className:"text-xs text-[var(--dg-text-secondary)]",children:o.role==="owner"?e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:577:114",className:"text-amber-400",children:"拥有者"}):o.role==="editor"?e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:577:182",className:"text-blue-400",children:"编辑者"}):e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:577:227",className:"text-slate-400",children:"查看者"})})]})]}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:580:31",variant:"ghost",size:"sm",className:"h-7 text-xs text-red-400 hover:text-red-300",onClick:()=>ge(o.id),children:[e.jsx(S,{"code-path":"src/components/deploy/PipelineEditor.tsx:580:162",className:"w-3.5 h-3.5 mr-1"}),"移除"]})]},o.id))})]})}),e.jsx(P,{"code-path":"src/components/deploy/PipelineEditor.tsx:589:19",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(E,{"code-path":"src/components/deploy/PipelineEditor.tsx:590:21",className:"p-0",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:591:23",className:"px-4 py-2 text-xs font-medium text-[var(--dg-text-secondary)] border-b border-[var(--dg-border)]",children:["👥 用户组授权 (",n.length,")"]}),n.length===0?e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:595:25",className:"py-4 text-center text-[var(--dg-text-secondary)] text-xs",children:["暂无组授权 — 在「",e.jsx("a",{"code-path":"src/components/deploy/PipelineEditor.tsx:596:37",href:"/deploy/groups",className:"text-blue-400 underline",children:"用户组管理"}),"」页面创建组后,可在此授权"]}):e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:599:25",className:"divide-y divide-[var(--dg-border)]",children:n.map(o=>e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:601:29",className:"flex items-center justify-between px-4 py-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:602:31",className:"flex items-center gap-3",children:[e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:603:33",className:"w-8 h-8 rounded-full bg-purple-500/20 flex items-center justify-center",children:e.jsx(Pe,{"code-path":"src/components/deploy/PipelineEditor.tsx:603:121",className:"w-4 h-4 text-purple-400"})}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:604:33",children:[e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:605:35",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:o.group?.name||`组 #${o.group_id}`}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:606:35",className:"text-xs text-[var(--dg-text-secondary)]",children:[o.role==="owner"?e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:606:114",className:"text-amber-400",children:"拥有者"}):o.role==="editor"?e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:606:182",className:"text-blue-400",children:"编辑者"}):e.jsx("span",{"code-path":"src/components/deploy/PipelineEditor.tsx:606:227",className:"text-slate-400",children:"查看者"})," · 组内全体成员"]})]})]}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineEditor.tsx:609:31",variant:"ghost",size:"sm",className:"h-7 text-xs text-red-400 hover:text-red-300",onClick:()=>ge(o.id),children:[e.jsx(S,{"code-path":"src/components/deploy/PipelineEditor.tsx:609:162",className:"w-3.5 h-3.5 mr-1"}),"撤销授权"]})]},o.id))})]})})]})})()]})})]}),e.jsx(_s,{"code-path":"src/components/deploy/PipelineEditor.tsx:624:7",open:De,onClose:()=>pe(!1),run:Ve,logs:Re})]}):e.jsx("div",{"code-path":"src/components/deploy/PipelineEditor.tsx:326:25",className:"text-center py-20 text-[var(--dg-text-secondary)]",children:"流水线不存在"})}export{Ks as default}; diff --git a/backend/static/assets/PipelineManager-C1vaTQ2Z.js b/backend/static/assets/PipelineManager-C1vaTQ2Z.js new file mode 100644 index 0000000..eddd5c1 --- /dev/null +++ b/backend/static/assets/PipelineManager-C1vaTQ2Z.js @@ -0,0 +1 @@ +import{g as bs,j as e,L as w,a3 as B,r as n,a as Js,k as Hs,h as fe,B as p,x as W,a0 as E,a7 as I,q as ye,v as ne,N as ue,S as Qs,I as g,O as ve,a4 as Ks,n as be,D as ds,b as ps,c as is,d as xs}from"./index-DfyorCky.js";import{C as ms,a as hs}from"./card-C55cvSHg.js";import{B as y}from"./badge-xNW8x0G1.js";import{T as Us}from"./textarea-NXY8u32k.js";import{L as d}from"./label-BK0h2apY.js";import{S as Z,a as ee,b as se,c as ae,d as v}from"./select-D5qUzdAs.js";import{d as je,p as P}from"./deploy-B3Sg3N1U.js";import{t as x}from"./index-a3ybMjbR.js";import{C as D}from"./circle-x-DK79Dhg2.js";import{P as Pe}from"./plus-CUG-9kpu.js";import{A as R}from"./arrow-right-DyIltvNZ.js";import{L as Xs}from"./layers-FW4KKJMi.js";import{S as js}from"./shield-check-Dcx486cW.js";import{C as Ys}from"./code-L62jFLTC.js";import{C as Me}from"./circle-stop-s4wxdTEV.js";import{P as Zs}from"./play-cdPayOtJ.js";import{H as ea}from"./history-D_9jPUQg.js";import{T as gs}from"./trash-2-Dx32pOzT.js";import{B as sa}from"./box-TTGA1p57.js";import{T as ys}from"./tag-0HCfq8kH.js";import{F as us}from"./file-text-C9G5abwR.js";import"./index-CWVNW_qu.js";const aa=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]],ta=bs("package",aa);const na=[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]],vs=bs("workflow",na);function oa(c){return c.toLowerCase().replace(/[^a-z0-9]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")||`pipeline-${Date.now()}`}function ca(c){switch(c){case"success":return e.jsxs(y,{"code-path":"src/components/deploy/pipeline-helpers.tsx:49:9",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:[e.jsx(B,{"code-path":"src/components/deploy/pipeline-helpers.tsx:50:11",className:"h-3 w-3 mr-1"}),"成功"]});case"failed":return e.jsxs(y,{"code-path":"src/components/deploy/pipeline-helpers.tsx:56:9",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10",children:[e.jsx(D,{"code-path":"src/components/deploy/pipeline-helpers.tsx:57:11",className:"h-3 w-3 mr-1"}),"失败"]});case"running":return e.jsxs(y,{"code-path":"src/components/deploy/pipeline-helpers.tsx:63:9",variant:"outline",className:"border-blue-500/30 text-blue-400 bg-blue-500/10 animate-pulse",children:[e.jsx(w,{"code-path":"src/components/deploy/pipeline-helpers.tsx:64:11",className:"h-3 w-3 mr-1 animate-spin"}),"运行中"]});default:return e.jsx(y,{"code-path":"src/components/deploy/pipeline-helpers.tsx:70:9",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",children:"从未运行"})}}const te=[{key:"checkout",label:"代码检出",icon:E,color:"#6366F1",order:1,needs:["repo"],desc:"从 Git 仓库拉取代码"},{key:"build",label:"构建",icon:sa,color:"#F59E0B",order:2,needs:[],desc:"编译/打包项目"},{key:"test",label:"测试",icon:B,color:"#10B981",order:3,needs:[],desc:"运行单元/集成测试"},{key:"image",label:"镜像打包",icon:ne,color:"#06B6D4",order:4,needs:["registry"],desc:"Docker 构建 & 推送"},{key:"deploy",label:"部署",icon:I,color:"#EF4444",order:5,needs:[],desc:"部署到目标环境"},{key:"verify",label:"验证",icon:js,color:"#3B82F6",order:6,needs:[],desc:"部署后健康检查"}].sort((c,b)=>c.order-b.order);function Ne(c){if(!c)return"-";if(c<60)return`${c}s`;const b=Math.floor(c/60),i=c%60;return i>0?`${b}分${i}秒`:`${b}分`}function ra(c){if(!c)return[];try{const b=typeof c=="string"?JSON.parse(c):c;return Array.isArray(b)?b:[]}catch{return[]}}function La(){const[c,b]=n.useState(""),[i,q]=n.useState([]),[J,L]=n.useState(!0),[M,k]=n.useState({}),[H,T]=n.useState({}),[N,A]=n.useState({}),[F,$]=n.useState("all"),[r,we]=n.useState({}),[Ps,z]=n.useState(!1),[Q,ke]=n.useState(""),[_,_e]=n.useState(""),[Ce,Se]=n.useState(""),[oe,Re]=n.useState(""),[Ee,Be]=n.useState("main"),[De,Le]=n.useState(""),[m,Te]=n.useState(["checkout","build","image","deploy"]),[,Ms]=n.useState(""),[,Ns]=n.useState(""),[ce,Ae]=n.useState("branch"),[Fe,$e]=n.useState("ssh"),[re,ze]=n.useState(""),[le,Oe]=n.useState(!1),[fs,ws]=n.useState([]),[ks,_s]=n.useState([]),[K,Ve]=n.useState(""),[C,Ge]=n.useState(""),[O,Ie]=n.useState("manual"),[We,qe]=n.useState(""),[Je,He]=n.useState(""),[Qe,de]=n.useState(""),[Ke,Ue]=n.useState(""),[j,S]=n.useState([]),[Xe,Ye]=n.useState(""),[Ze,Cs]=n.useState(2),[,Ss]=n.useState([]),[,Rs]=n.useState([]),[Es,Bs]=n.useState([]),[,da]=n.useState([]),[,pa]=n.useState([]),[Ds,es]=n.useState(!1),[V,Ls]=n.useState(null),[ss,as]=n.useState([]),ts=Js(),ns=Hs(),Ts=[{key:"all",label:"全部",icon:Xs,color:"#6B7280"},{key:"production",label:"生产",icon:js,color:"#EF4444"},{key:"testing",label:"测试",icon:B,color:"#F59E0B"},{key:"staging",label:"预发布",icon:ve,color:"#8B5CF6"},{key:"development",label:"开发",icon:Ys,color:"#3B82F6"}],As=n.useCallback(async()=>{try{const[s,a,t,o]=await Promise.all([je.getRepos().catch(()=>({list:[]})),je.getRegistries().catch(()=>({list:[]})),je.getEnvironments().catch(()=>({list:[]})),fe.get("/credentials",{page_size:100}).catch(()=>({list:[]}))]);Ss(Array.isArray(s?.list)?s.list:[]),Rs(Array.isArray(a?.list)?a.list:[]),Bs(Array.isArray(t?.list)?t.list:[]);const h=o?.list||[];ws(h.filter(u=>u.secret_type==="api")),_s(h.filter(u=>u.secret_type==="docker"))}catch{}},[]),G=n.useCallback(async()=>{L(!0);try{const s=await P.getPipelines();q(Array.isArray(s?.list)?s.list:[])}catch{x.error("获取流水线列表失败")}finally{L(!1)}},[]);n.useEffect(()=>{As(),G()},[]),n.useEffect(()=>{i.forEach(s=>{s.last_status==="running"&&!r[s.id]&&P.getRuns(s.id).then(a=>{const o=(a?.list||[]).find(h=>h.status==="running"||h.status==="pending");o&&we(h=>({...h,[s.id]:o}))}).catch(()=>{})})},[i]);const pe=async(s,a)=>{A(t=>({...t,[s]:!0}));try{const t=await P.getRuns(a);T(o=>({...o,[s]:t?.list||[]}))}catch{T(t=>({...t,[s]:[]}))}finally{A(t=>({...t,[s]:!1}))}},Fs=(s,a)=>{M[s]?k(t=>({...t,[s]:!1})):(pe(s,a),k(t=>({...t,[s]:!0})))},$s=async()=>{if(!Q.trim()){x.error("请输入流水线名称");return}if(m.includes("checkout")&&!oe.trim()){x.error("代码检出阶段需要填写 Git URL");return}if(m.includes("image")&&!C){x.error("镜像打包阶段需要关联 Docker 凭证");return}Oe(!0);try{const s=m.map(t=>te.find(o=>o.key===t)?.label||t),a=JSON.stringify(s.map((t,o)=>({id:`stage-${o+1}`,name:t,type:m[o]||"custom",tasks:[]})));await P.createPipeline({name:Q,code:oa(Q),job_name:_||void 0,description:Ce,source:oe,branch:Ee,dockerfile:De,type:"deploy",stages:a,deploy_mode:ce,deploy_target:Fe,environment_id:re?Number(re):null,repo_id:null,registry_id:null,git_credential_id:K?Number(K):null,registry_credential_id:C?Number(C):null,trigger_mode:O,watch_branches:We||void 0,exclude_branch:Je||void 0,cron_expr:Qe||void 0,webhook_token:Ke||void 0,variables:j.length>0?JSON.stringify(j):void 0,cache_paths:Xe||void 0,max_executors:Ze}),x.success("流水线已创建"),z(!1),zs(),G()}catch{x.error("创建失败")}finally{Oe(!1)}},zs=()=>{ke(""),_e(""),Se(""),Re(""),Be("main"),Le(""),Te(["checkout","build","image","deploy"]),Ms(""),Ns(""),Ae("branch"),$e("ssh"),ze(""),Ve(""),Ge(""),Ie("manual"),qe(""),He(""),de(""),Ue(""),S([]),Ye("")},Os=async(s,a)=>{try{await P.triggerPipeline(a),x.success("已触发"),pe(s,a),G()}catch{x.error("触发失败")}},ie=async(s,a,t)=>{if(await ts({title:"停止运行",description:"确定要停止此运行吗?",variant:"destructive"}))try{await P.stopRun(a,t),x.success("已停止"),pe(s,a),we(h=>{const u={...h};return delete u[s],u})}catch{x.error("停止失败")}},Vs=async(s,a)=>{const t=r[s];if(!t){try{const h=((await P.getRuns(a))?.list||[]).find(u=>u.status==="running"||u.status==="pending");h?await ie(s,a,h.id):x.error("未找到运行中的任务")}catch{x.error("停止失败")}return}await ie(s,a,t.id)},Gs=async(s,a)=>{Ls(a),es(!0);try{const t=await P.getRunLog(s,a.id);as(t?.logs||[])}catch{as([])}},Is=async s=>{if(await ts({title:"删除流水线",description:`确定删除「${s.name}」?`,variant:"destructive"}))try{await P.deletePipeline(s.code),x.success("已删除"),G()}catch{x.error("删除失败")}},os=i.filter(s=>{const a=(s.name||"").toLowerCase().includes(c.toLowerCase())||(s.description||"").toLowerCase().includes(c.toLowerCase()),t=F==="all"||(s.environment?.type||"")===F;return a&&t}),U={total:i.length,running:i.filter(s=>s.last_status==="running").length,success:i.filter(s=>s.last_status==="success").length,failed:i.filter(s=>s.last_status==="failed").length};return e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:285:5",className:"space-y-5",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:286:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:287:9",children:[e.jsx("h1",{"code-path":"src/components/deploy/PipelineManager.tsx:288:11",className:"text-2xl font-bold text-[var(--dg-text-primary)]",children:"流水线"}),e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:289:11",className:"text-sm text-[var(--dg-text-secondary)] mt-1",children:"CI/CD 构建 · 部署 · 发布一体化"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:291:9",className:"flex items-center gap-2",children:[e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:292:11",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",onClick:G,children:[e.jsx(W,{"code-path":"src/components/deploy/PipelineManager.tsx:293:13",className:`h-4 w-4 mr-2 ${J?"animate-spin":""}`}),"刷新"]}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:295:11",onClick:()=>z(!0),children:[e.jsx(Pe,{"code-path":"src/components/deploy/PipelineManager.tsx:295:52",className:"h-4 w-4 mr-2"}),"新建流水线"]})]})]}),e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:299:7",className:"grid grid-cols-4 gap-4",children:[{label:"流水线总数",val:U.total,icon:vs,color:"#3B82F6"},{label:"运行中",val:U.running,icon:w,color:"#3B82F6"},{label:"成功",val:U.success,icon:B,color:"#10B981"},{label:"失败",val:U.failed,icon:D,color:"#EF4444"}].map((s,a)=>e.jsx(ms,{"code-path":"src/components/deploy/PipelineManager.tsx:306:11",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(hs,{"code-path":"src/components/deploy/PipelineManager.tsx:307:13",className:"p-4 flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:308:15",children:[e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:308:20",className:"text-[var(--dg-text-secondary)] text-sm",children:s.label}),e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:308:88",className:"text-2xl font-bold text-[var(--dg-text-primary)]",children:s.val})]}),e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:309:15",className:"w-10 h-10 rounded-lg flex items-center justify-center",style:{backgroundColor:s.color+"20"},children:e.jsx(s.icon,{"code-path":"src/components/deploy/PipelineManager.tsx:309:130",className:"h-5 w-5",style:{color:s.color}})})]})},a))}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:316:7",className:"flex items-stretch gap-3 px-4 py-3 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:318:9",className:"flex-1 space-y-1.5",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:319:11",className:"flex items-center gap-1.5",children:[e.jsx(E,{"code-path":"src/components/deploy/PipelineManager.tsx:320:13",className:"h-3 w-3 text-indigo-400"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:321:13",className:"text-[10px] font-semibold text-indigo-400",children:"构建"}),e.jsx(R,{"code-path":"src/components/deploy/PipelineManager.tsx:322:13",className:"h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30"}),e.jsx(I,{"code-path":"src/components/deploy/PipelineManager.tsx:323:13",className:"h-3 w-3 text-red-400"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:324:13",className:"text-[10px] font-semibold text-red-400",children:"部署"}),e.jsx(R,{"code-path":"src/components/deploy/PipelineManager.tsx:325:13",className:"h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30"}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:326:13",className:"flex items-center gap-1 px-2 py-0.5 rounded bg-blue-400/10 border border-blue-400/20",children:[e.jsx(ye,{"code-path":"src/components/deploy/PipelineManager.tsx:327:15",className:"h-3 w-3 text-blue-400"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:328:15",className:"text-[10px] font-medium text-blue-400",children:"SSH 主机"})]})]}),e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:331:11",className:"text-[9px] text-[var(--dg-text-secondary)] opacity-40 pl-1",children:"传统主机 SCP 部署 · 无需镜像仓库"})]}),e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:334:9",className:"w-px bg-[var(--dg-border)]"}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:336:9",className:"flex-1 space-y-1.5",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:337:11",className:"flex items-center gap-1.5",children:[e.jsx(E,{"code-path":"src/components/deploy/PipelineManager.tsx:338:13",className:"h-3 w-3 text-indigo-400"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:339:13",className:"text-[10px] font-semibold text-indigo-400",children:"构建"}),e.jsx(R,{"code-path":"src/components/deploy/PipelineManager.tsx:340:13",className:"h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30"}),e.jsx(ne,{"code-path":"src/components/deploy/PipelineManager.tsx:341:13",className:"h-3 w-3 text-cyan-400"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:342:13",className:"text-[10px] font-semibold text-cyan-400",children:"镜像仓库"}),e.jsx(R,{"code-path":"src/components/deploy/PipelineManager.tsx:343:13",className:"h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30"}),e.jsx(I,{"code-path":"src/components/deploy/PipelineManager.tsx:344:13",className:"h-3 w-3 text-red-400"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:345:13",className:"text-[10px] font-semibold text-red-400",children:"部署"}),e.jsx(R,{"code-path":"src/components/deploy/PipelineManager.tsx:346:13",className:"h-2.5 w-2.5 text-[var(--dg-text-secondary)] opacity-30"}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:347:13",className:"flex items-center gap-1 px-2 py-0.5 rounded bg-emerald-400/10 border border-emerald-400/20",children:[e.jsx(ue,{"code-path":"src/components/deploy/PipelineManager.tsx:348:15",className:"h-3 w-3 text-emerald-400"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:349:15",className:"text-[10px] font-medium text-emerald-400",children:"Kubernetes"})]})]}),e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:352:11",className:"text-[9px] text-[var(--dg-text-secondary)] opacity-40 pl-1",children:"容器化部署 · 需镜像仓库推送"})]}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:354:9",className:"self-center ml-2 text-[10px] text-[var(--dg-text-secondary)] opacity-30 tracking-wide whitespace-nowrap",children:"全流程可视化"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:357:7",className:"flex items-center gap-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:358:9",className:"relative max-w-md flex-1",children:[e.jsx(Qs,{"code-path":"src/components/deploy/PipelineManager.tsx:359:11",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[var(--dg-text-secondary)]"}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:360:11",placeholder:"搜索流水线...",value:c,onChange:s=>b(s.target.value),className:"pl-10 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:363:9",className:"flex items-center gap-1 bg-[var(--dg-bg-secondary)] rounded-lg p-1 border border-[var(--dg-border)]",children:Ts.map(s=>{const a=F===s.key,t=s.icon;return e.jsxs("button",{"code-path":"src/components/deploy/PipelineManager.tsx:368:15",onClick:()=>$(s.key),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium transition-all ${a?"text-white shadow-sm":"text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"}`,style:a?{backgroundColor:s.color}:{},children:[e.jsx(t,{"code-path":"src/components/deploy/PipelineManager.tsx:372:17",className:"h-3.5 w-3.5"}),s.label]},s.key)})})]}),J?e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:380:9",className:"flex items-center justify-center py-12",children:e.jsx(w,{"code-path":"src/components/deploy/PipelineManager.tsx:380:65",className:"h-6 w-6 text-[var(--dg-text-secondary)] animate-spin"})}):os.length===0?e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:382:9",className:"text-center py-16 text-[var(--dg-text-secondary)]",children:[e.jsx(vs,{"code-path":"src/components/deploy/PipelineManager.tsx:383:11",className:"h-10 w-10 mx-auto mb-3 opacity-30"}),e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:384:11",className:"text-sm",children:"暂无流水线"}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:385:11",variant:"outline",className:"mt-4",onClick:()=>z(!0),children:[e.jsx(Pe,{"code-path":"src/components/deploy/PipelineManager.tsx:385:87",className:"h-4 w-4 mr-1"}),"创建第一个流水线"]})]}):e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:388:9",className:"space-y-3",children:os.map(s=>{const a=ra(s.stages),t=H[s.id]||[],o=M[s.id],h=N[s.id],u=s.repo,cs=s.registry;return e.jsx(ms,{"code-path":"src/components/deploy/PipelineManager.tsx:396:15",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] overflow-hidden",children:e.jsxs(hs,{"code-path":"src/components/deploy/PipelineManager.tsx:397:17",className:"p-0",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:398:19",className:"px-4 py-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:399:21",className:"flex items-start justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:400:23",className:"flex-1 min-w-0",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:401:25",className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{"code-path":"src/components/deploy/PipelineManager.tsx:402:27",className:"font-semibold text-[var(--dg-text-primary)]",children:s.name}),s.run_count>0&&e.jsxs(y,{"code-path":"src/components/deploy/PipelineManager.tsx:403:54",variant:"outline",className:"text-[11px] text-[var(--dg-text-secondary)] border-[var(--dg-border)]",children:["#",s.run_count]}),ca(s.last_status),s.environment&&e.jsx(y,{"code-path":"src/components/deploy/PipelineManager.tsx:405:52",style:{backgroundColor:s.environment.color+"20",color:s.environment.color},className:"text-xs",children:s.environment.display_name}),s.job_name&&e.jsx(y,{"code-path":"src/components/deploy/PipelineManager.tsx:406:49",variant:"secondary",className:"text-xs font-mono opacity-60",children:s.job_name})]}),e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:408:25",className:"text-xs text-[var(--dg-text-secondary)] mt-1 line-clamp-1",children:s.description||"暂无描述"}),(s.last_run_branch||s.last_commit_id||s.last_image_tag)&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:411:27",className:"flex items-center gap-1 mt-1.5 text-xs font-mono",children:[s.last_run_branch&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:413:31",className:"flex items-center gap-0.5 text-indigo-400",children:[e.jsx(E,{"code-path":"src/components/deploy/PipelineManager.tsx:414:33",className:"h-3 w-3"}),s.last_run_branch]}),s.last_run_branch&&s.last_commit_id&&e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:418:31",className:"text-[var(--dg-text-secondary)] opacity-50 text-[10px] mx-0.5",children:"+"}),s.last_commit_id&&e.jsx("code",{"code-path":"src/components/deploy/PipelineManager.tsx:421:31",className:"text-amber-400 bg-amber-400/10 px-1 py-0.5 rounded text-[11px]",children:s.last_commit_id.slice(0,8)}),(s.last_run_branch||s.last_commit_id)&&s.last_image_tag&&e.jsx(R,{"code-path":"src/components/deploy/PipelineManager.tsx:424:31",className:"h-3 w-3 text-[var(--dg-text-secondary)] opacity-40 mx-0.5"}),s.last_image_tag&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:427:31",className:"flex items-center gap-0.5 text-cyan-400",children:[e.jsx(ta,{"code-path":"src/components/deploy/PipelineManager.tsx:428:33",className:"h-3 w-3"}),e.jsx("code",{"code-path":"src/components/deploy/PipelineManager.tsx:429:33",className:"bg-cyan-400/10 px-1 py-0.5 rounded text-[11px]",children:s.last_image_tag})]}),s.last_duration>0&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:433:31",className:"flex items-center gap-0.5 ml-auto text-[var(--dg-text-secondary)] opacity-50",children:[e.jsx(W,{"code-path":"src/components/deploy/PipelineManager.tsx:434:33",className:"h-3 w-3"}),Ne(s.last_duration)]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:439:25",className:"flex items-center gap-3 mt-1.5 text-xs text-[var(--dg-text-secondary)] opacity-60",children:[e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:440:27",className:"flex items-center gap-1",children:[e.jsx(E,{"code-path":"src/components/deploy/PipelineManager.tsx:440:69",className:"h-3 w-3"}),s.deploy_mode==="tag"?"Tag发版":s.branch||"main"]}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:441:27",className:"flex items-center gap-1",children:(s.deploy_target||"ssh")==="k8s"?e.jsxs(e.Fragment,{children:[e.jsx(ue,{"code-path":"src/components/deploy/PipelineManager.tsx:441:118",className:"h-3 w-3"}),"Kubernetes"]}):e.jsxs(e.Fragment,{children:[e.jsx(ye,{"code-path":"src/components/deploy/PipelineManager.tsx:441:167",className:"h-3 w-3"}),"SSH 主机"]})}),u&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:442:36",className:"flex items-center gap-1",children:[e.jsx(ve,{"code-path":"src/components/deploy/PipelineManager.tsx:442:78",className:"h-3 w-3"}),u.name]}),cs&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:443:40",className:"flex items-center gap-1",children:[e.jsx(ne,{"code-path":"src/components/deploy/PipelineManager.tsx:443:82",className:"h-3 w-3"}),cs.name]}),s.last_run_at&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:444:52",children:[e.jsx(W,{"code-path":"src/components/deploy/PipelineManager.tsx:444:58",className:"h-3 w-3 inline mr-0.5"}),new Date(s.last_run_at).toLocaleString("zh-CN")]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:447:23",className:"flex items-center gap-1 ml-4 shrink-0",children:[s.last_status==="running"?e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:449:27",variant:"destructive",size:"sm",className:"h-8",onClick:()=>Vs(s.id,s.code),children:[e.jsx(Me,{"code-path":"src/components/deploy/PipelineManager.tsx:450:29",className:"h-3.5 w-3.5 mr-1"}),"停止"]}):e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:453:27",variant:"default",size:"sm",className:"h-8",onClick:()=>Os(s.id,s.code),children:[e.jsx(Zs,{"code-path":"src/components/deploy/PipelineManager.tsx:454:29",className:"h-3.5 w-3.5 mr-1"}),"执行"]}),e.jsx(p,{"code-path":"src/components/deploy/PipelineManager.tsx:457:25",variant:"outline",size:"sm",className:"h-8",onClick:()=>ns(`/pipelines/${s.code||s.id}`),children:"编辑"}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:458:25",variant:"outline",size:"sm",className:"h-8",onClick:()=>ns(`/pipelines/${s.code||s.id}/runs`),children:[e.jsx(ea,{"code-path":"src/components/deploy/PipelineManager.tsx:459:27",className:"h-3.5 w-3.5 mr-1"}),"记录"]}),e.jsx(p,{"code-path":"src/components/deploy/PipelineManager.tsx:460:25",variant:"ghost",size:"sm",className:"h-8",onClick:()=>Fs(s.id,s.code),children:o?e.jsx(Ks,{"code-path":"src/components/deploy/PipelineManager.tsx:461:41",className:"h-4 w-4"}):e.jsx(be,{"code-path":"src/components/deploy/PipelineManager.tsx:461:79",className:"h-4 w-4"})}),e.jsx(p,{"code-path":"src/components/deploy/PipelineManager.tsx:463:25",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-500",onClick:()=>Is(s),children:e.jsx(gs,{"code-path":"src/components/deploy/PipelineManager.tsx:463:133",className:"h-4 w-4"})})]})]}),a.length>0&&e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:467:23",className:"flex items-center mt-2.5",children:a.map((l,X)=>{const rs=te.find(Y=>Y.label===l.name);rs?.icon||ys;let f="";if(s.last_run_stages)try{const Y=typeof s.last_run_stages=="string"?JSON.parse(s.last_run_stages):s.last_run_stages;f=(Array.isArray(Y)?Y.find(ls=>ls.name===l.name||ls.type===rs?.key):null)?.status||""}catch{}const xe=f==="success"||f==="completed",me=f==="running"||f==="in_progress",he=f==="failed"||f==="error",ge=he?"#EF4444":me?"#3B82F6":xe?"#10B981":"#6B7280",Ws=he?"#EF444528":me?"#3B82F628":xe?"#10B98128":"#6B728018",qs=he?e.jsx(D,{"code-path":"src/components/deploy/PipelineManager.tsx:485:51",className:"h-3 w-3"}):me?e.jsx(w,{"code-path":"src/components/deploy/PipelineManager.tsx:485:97",className:"h-3 w-3 animate-spin"}):xe?e.jsx(B,{"code-path":"src/components/deploy/PipelineManager.tsx:485:156",className:"h-3 w-3"}):e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:485:194",className:"text-[10px] opacity-40",children:"○"});return e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:487:29",className:"flex items-center",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:488:31",className:"flex items-center gap-1.5 px-2.5 py-1.5 text-[11px] font-semibold border shadow-sm",style:{backgroundColor:Ws,borderColor:ge+"70",color:ge,borderRadius:X===0?"8px 0 0 8px":X===a.length-1?"0 8px 8px 0":"0"},children:[qs,l.name]}),Xe.jsxs("tr",{"code-path":"src/components/deploy/PipelineManager.tsx:522:31",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50",children:[e.jsxs("td",{"code-path":"src/components/deploy/PipelineManager.tsx:523:33",className:"px-4 py-2 font-medium text-[var(--dg-text-primary)]",children:["#",l.build_number||l.id]}),e.jsx("td",{"code-path":"src/components/deploy/PipelineManager.tsx:524:33",className:"px-4 py-2",children:l.status==="success"?e.jsxs(y,{"code-path":"src/components/deploy/PipelineManager.tsx:525:61",className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30 text-[11px]",children:[e.jsx(B,{"code-path":"src/components/deploy/PipelineManager.tsx:525:149",className:"h-3 w-3 mr-0.5"}),"成功"]}):l.status==="failed"?e.jsxs(y,{"code-path":"src/components/deploy/PipelineManager.tsx:526:60",className:"bg-red-500/20 text-red-400 border-red-500/30 text-[11px]",children:[e.jsx(D,{"code-path":"src/components/deploy/PipelineManager.tsx:526:136",className:"h-3 w-3 mr-0.5"}),"失败"]}):l.status==="running"?e.jsxs(y,{"code-path":"src/components/deploy/PipelineManager.tsx:527:61",className:"bg-blue-500/20 text-blue-400 border-blue-500/30 text-[11px]",children:[e.jsx(w,{"code-path":"src/components/deploy/PipelineManager.tsx:527:140",className:"h-3 w-3 animate-spin mr-0.5"}),"执行中"]}):l.status==="cancelled"?e.jsxs(y,{"code-path":"src/components/deploy/PipelineManager.tsx:528:63",className:"bg-yellow-500/20 text-yellow-400 border-yellow-500/30 text-[11px]",children:[e.jsx(Me,{"code-path":"src/components/deploy/PipelineManager.tsx:528:148",className:"h-3 w-3 mr-0.5"}),"已停止"]}):e.jsx(y,{"code-path":"src/components/deploy/PipelineManager.tsx:529:36",variant:"secondary",className:"text-[11px]",children:l.status})}),e.jsx("td",{"code-path":"src/components/deploy/PipelineManager.tsx:531:33",className:"px-4 py-2 text-[var(--dg-text-secondary)] text-xs",children:l.triggered_by||"admin"}),e.jsx("td",{"code-path":"src/components/deploy/PipelineManager.tsx:532:33",className:"px-4 py-2 text-[var(--dg-text-secondary)] text-xs",children:Ne(l.duration)}),e.jsx("td",{"code-path":"src/components/deploy/PipelineManager.tsx:533:33",className:"px-4 py-2 text-[var(--dg-text-secondary)] text-xs",children:l.created_at?new Date(l.created_at).toLocaleString("zh-CN"):"-"}),e.jsx("td",{"code-path":"src/components/deploy/PipelineManager.tsx:534:33",className:"px-4 py-2 text-right",children:e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:535:35",className:"flex items-center justify-end gap-1",children:[e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:536:37",variant:"ghost",size:"sm",className:"h-7 text-xs text-blue-400 hover:text-blue-300",onClick:()=>Gs(s.code,l),children:[e.jsx(us,{"code-path":"src/components/deploy/PipelineManager.tsx:536:177",className:"h-3.5 w-3.5 mr-1"}),"日志"]}),(l.status==="running"||l.status==="pending")&&e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:538:39",variant:"ghost",size:"sm",className:"h-7 text-xs text-red-400 hover:text-red-300",onClick:()=>ie(s.id,s.code,l.id),children:[e.jsx(Me,{"code-path":"src/components/deploy/PipelineManager.tsx:538:190",className:"h-3.5 w-3.5 mr-1"}),"停止"]})]})})]},l.id))})]})]})]})},s.id)})}),e.jsx(ds,{"code-path":"src/components/deploy/PipelineManager.tsx:557:7",open:Ps,onOpenChange:z,children:e.jsxs(ps,{"code-path":"src/components/deploy/PipelineManager.tsx:558:9",className:"max-w-2xl max-h-[85vh] overflow-y-auto bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:[e.jsx(is,{"code-path":"src/components/deploy/PipelineManager.tsx:559:11",children:e.jsxs(xs,{"code-path":"src/components/deploy/PipelineManager.tsx:559:25",className:"flex items-center gap-2",children:[e.jsx(I,{"code-path":"src/components/deploy/PipelineManager.tsx:559:74",className:"h-5 w-5"}),"新建流水线"]})}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:560:11",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:562:13",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:563:15",className:"space-y-1",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:564:17",children:["名称 ",e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:564:27",className:"text-red-400",children:"*"})]}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:565:17",value:Q,onChange:s=>ke(s.target.value),placeholder:"例如: demo-jar 后端部署",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:567:15",className:"space-y-1",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:568:17",children:["Job 名称 ",e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:568:31",className:"text-xs text-[var(--dg-text-secondary)]",children:"(Webhook URL)"})]}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:569:17",value:_,onChange:s=>_e(s.target.value),placeholder:"cex-admin-server",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9 font-mono text-sm"}),_&&e.jsxs("p",{"code-path":"src/components/deploy/PipelineManager.tsx:570:32",className:"text-[10px] text-[var(--dg-text-secondary)] opacity-60",children:["Webhook: POST .../webhook/job/",e.jsx("b",{"code-path":"src/components/deploy/PipelineManager.tsx:570:132",children:_})]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:573:13",className:"space-y-1",children:[e.jsx(d,{"code-path":"src/components/deploy/PipelineManager.tsx:573:40",children:"描述"}),e.jsx(Us,{"code-path":"src/components/deploy/PipelineManager.tsx:573:57",value:Ce,onChange:s=>Se(s.target.value),placeholder:"流水线描述...",rows:2,className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:576:13",className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:577:15",className:"space-y-1",children:[e.jsx(d,{"code-path":"src/components/deploy/PipelineManager.tsx:578:17",children:"部署模式"}),e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:579:17",className:"flex gap-1 bg-[var(--dg-bg-secondary)] rounded-lg p-1 border border-[var(--dg-border)]",children:[{key:"branch",label:"分支",icon:E},{key:"tag",label:"Tag 发版",icon:ys}].map(s=>{const a=ce===s.key;return e.jsxs("button",{"code-path":"src/components/deploy/PipelineManager.tsx:586:23",onClick:()=>Ae(s.key),className:`flex-1 flex items-center justify-center gap-1 px-2 py-1.5 rounded-md text-xs font-medium transition-all ${a?"bg-blue-500 text-white":"text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"}`,children:[e.jsx(s.icon,{"code-path":"src/components/deploy/PipelineManager.tsx:589:25",className:"h-3.5 w-3.5"}),s.label]},s.key)})})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:595:15",className:"space-y-1",children:[e.jsx(d,{"code-path":"src/components/deploy/PipelineManager.tsx:596:17",children:"部署目标"}),e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:597:17",className:"flex gap-1 bg-[var(--dg-bg-secondary)] rounded-lg p-1 border border-[var(--dg-border)]",children:[{key:"ssh",label:"SSH 主机",icon:ye},{key:"k8s",label:"Kubernetes 集群",icon:ue}].map(s=>{const a=Fe===s.key;return e.jsxs("button",{"code-path":"src/components/deploy/PipelineManager.tsx:604:23",onClick:()=>$e(s.key),className:`flex-1 flex items-center justify-center gap-1 px-2 py-1.5 rounded-md text-xs font-medium transition-all ${a?"bg-green-500 text-white":"text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"}`,children:[e.jsx(s.icon,{"code-path":"src/components/deploy/PipelineManager.tsx:607:25",className:"h-3.5 w-3.5"}),s.label]},s.key)})})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:613:15",className:"space-y-1",children:[e.jsx(d,{"code-path":"src/components/deploy/PipelineManager.tsx:614:17",children:"环境分组"}),e.jsxs(Z,{"code-path":"src/components/deploy/PipelineManager.tsx:615:17",value:String(re),onValueChange:s=>ze(s==="__none"?"":s),children:[e.jsx(ee,{"code-path":"src/components/deploy/PipelineManager.tsx:616:19",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9",children:e.jsx(se,{"code-path":"src/components/deploy/PipelineManager.tsx:616:104",placeholder:"选择环境"})}),e.jsxs(ae,{"code-path":"src/components/deploy/PipelineManager.tsx:617:19",children:[e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:618:21",value:"__none",children:"不指定"}),Es.map(s=>e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:620:23",value:String(s.id),children:e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:621:25",className:"flex items-center gap-1.5",children:[e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:622:27",className:"w-2 h-2 rounded-full inline-block",style:{backgroundColor:s.color}}),s.display_name]})},s.id))]})]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:633:13",className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:634:15",className:"space-y-1",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:635:17",children:["Git URL ",m.includes("checkout")&&e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:635:72",className:"text-red-400",children:"*"})]}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:636:17",value:oe,onChange:s=>Re(s.target.value),placeholder:"https://gitee.com/user/repo.git",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9 font-mono text-xs"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:639:15",className:"space-y-1",children:[e.jsx(d,{"code-path":"src/components/deploy/PipelineManager.tsx:640:17",children:"分支 / Tag"}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:641:17",value:Ee,onChange:s=>Be(s.target.value),placeholder:ce==="tag"?"v1.0.0":"main",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:644:15",className:"space-y-1",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:645:17",children:["Git 凭证 ",e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:645:31",className:"text-xs text-[var(--dg-text-secondary)] opacity-60",children:"(API Token)"})]}),e.jsxs(Z,{"code-path":"src/components/deploy/PipelineManager.tsx:646:17",value:String(K),onValueChange:s=>Ve(s==="__none"?"":s),children:[e.jsx(ee,{"code-path":"src/components/deploy/PipelineManager.tsx:647:19",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9",children:e.jsx(se,{"code-path":"src/components/deploy/PipelineManager.tsx:647:104",placeholder:"选择凭证"})}),e.jsxs(ae,{"code-path":"src/components/deploy/PipelineManager.tsx:648:19",children:[e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:649:21",value:"__none",children:"不关联"}),fs.map(s=>e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:651:23",value:String(s.id),children:e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:652:25",className:"flex items-center gap-1.5",children:[e.jsx(ve,{"code-path":"src/components/deploy/PipelineManager.tsx:652:69",className:"h-3 w-3 opacity-60"}),s.name," ",s.summary&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:652:132",className:"text-[10px] opacity-50",children:["(",s.summary,")"]})]})},s.id))]})]}),!K&&m.includes("checkout")&&e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:657:80",className:"text-xs text-amber-400",children:"建议关联凭证"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:659:15",className:"space-y-1",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:660:17",children:["镜像仓库凭证 ",m.includes("image")&&e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:660:68",className:"text-red-400",children:"*"})]}),e.jsxs(Z,{"code-path":"src/components/deploy/PipelineManager.tsx:661:17",value:String(C),onValueChange:s=>Ge(s==="__none"?"":s),children:[e.jsx(ee,{"code-path":"src/components/deploy/PipelineManager.tsx:662:19",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9",children:e.jsx(se,{"code-path":"src/components/deploy/PipelineManager.tsx:662:104",placeholder:"选择 Docker 凭证"})}),e.jsxs(ae,{"code-path":"src/components/deploy/PipelineManager.tsx:663:19",children:[e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:664:21",value:"__none",children:"不关联"}),ks.map(s=>e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:666:23",value:String(s.id),children:e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:667:25",className:"flex items-center gap-1.5",children:[e.jsx(ne,{"code-path":"src/components/deploy/PipelineManager.tsx:667:69",className:"h-3 w-3 opacity-60"}),s.name," ",s.summary&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:667:136",className:"text-[10px] opacity-50",children:["(",s.summary,")"]})]})},s.id))]})]}),!C&&m.includes("image")&&e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:672:82",className:"text-xs text-amber-400",children:"需要关联 Docker 凭证"})]})]}),C&&_&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:677:15",className:"p-2.5 rounded-md bg-blue-500/5 border border-blue-500/20 text-xs text-[var(--dg-text-secondary)]",children:[e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:678:17",className:"text-blue-400",children:"镜像命名:"}),e.jsxs("code",{"code-path":"src/components/deploy/PipelineManager.tsx:679:17",className:"text-[var(--dg-text-primary)]",children:["{registry}","/","{namespace}","/","{","{JOB_BASE_NAME}","}",":","{","{tag}","}"]}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:680:17",className:"ml-2 opacity-60",children:"例:"}),e.jsxs("code",{"code-path":"src/components/deploy/PipelineManager.tsx:681:17",className:"opacity-60",children:["harbor.ast1001.com/test/",_,":latest"]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:684:13",className:"space-y-1",children:[e.jsx(d,{"code-path":"src/components/deploy/PipelineManager.tsx:684:40",children:"Dockerfile 路径"}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:684:68",value:De,onChange:s=>Le(s.target.value),placeholder:"jar/Dockerfile",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-9 font-mono text-xs"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:687:13",className:"space-y-2",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:688:15",children:["发布流程 ",e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:688:27",className:"text-xs text-[var(--dg-text-secondary)] opacity-70 ml-1",children:"按顺序选择阶段"})]}),e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:689:15",className:"flex flex-wrap gap-2",children:te.map(s=>{const a=m.includes(s.key);return e.jsxs(y,{"code-path":"src/components/deploy/PipelineManager.tsx:693:21",className:`cursor-pointer transition-all text-xs px-3 py-1.5 ${a?"border-current":"border-[var(--dg-border)] opacity-50 hover:opacity-80"}`,style:a?{backgroundColor:s.color+"20",color:s.color,borderColor:s.color}:{},onClick:()=>Te(a?m.filter(t=>t!==s.key):[...m,s.key]),title:s.desc,children:[e.jsx(s.icon,{"code-path":"src/components/deploy/PipelineManager.tsx:698:23",className:"h-3 w-3 mr-1"}),s.label," ",s.needs.includes("repo")?"🔗":"",s.needs.includes("registry")?"📦":""]},s.key)})}),m.length>0&&e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:704:17",className:"flex items-center mt-2",children:m.map((s,a)=>{const t=te.find(o=>o.key===s);return e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:708:23",className:"flex items-center",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:709:25",className:"flex items-center gap-1 px-2 py-1 text-[11px] font-medium border",style:{backgroundColor:t.color+"20",borderColor:t.color+"40",color:t.color,borderRadius:a===0?"6px 0 0 6px":a===m.length-1?"0 6px 6px 0":"0"},children:[e.jsx(t.icon,{"code-path":"src/components/deploy/PipelineManager.tsx:711:27",className:"h-3 w-3"}),t.label]}),a{const a=O===s.key;return e.jsx("button",{"code-path":"src/components/deploy/PipelineManager.tsx:737:21",onClick:()=>Ie(s.key),className:`flex-1 flex flex-col items-center gap-0.5 px-2 py-2 rounded-md text-xs font-medium transition-all ${a?"bg-blue-500 text-white":"text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]"}`,title:s.desc,children:s.label},s.key)})}),O==="git_push"&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:749:17",className:"mt-3 space-y-2 p-3 rounded-md bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:750:19",className:"space-y-1",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:751:21",className:"text-xs",children:["监听分支 ",e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:751:53",className:"text-[var(--dg-text-secondary)] opacity-60",children:"(逗号分隔,支持 * 通配)"})]}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:752:21",value:We,onChange:s=>qe(s.target.value),placeholder:"release/*, main",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] h-8 font-mono text-xs"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:755:19",className:"space-y-1",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:756:21",className:"text-xs",children:["排除分支 ",e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:756:53",className:"text-[var(--dg-text-secondary)] opacity-60",children:"(不触发构建)"})]}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:757:21",value:Je,onChange:s=>He(s.target.value),placeholder:"wip/*, draft/*",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] h-8 font-mono text-xs"})]})]}),O==="cron"&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:765:17",className:"mt-3 space-y-2 p-3 rounded-md bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:766:19",className:"space-y-1",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:767:21",className:"text-xs",children:["Cron 表达式 ",e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:767:57",className:"text-[var(--dg-text-secondary)] opacity-60",children:"(标准 5 位)"})]}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:768:21",value:Qe,onChange:s=>de(s.target.value),placeholder:"0 2 * * *",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] h-8 font-mono text-xs"})]}),e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:771:19",className:"flex flex-wrap gap-1.5",children:[{expr:"*/5 * * * *",label:"每5分钟"},{expr:"0 * * * *",label:"每小时"},{expr:"0 2 * * *",label:"每天2点"},{expr:"0 0 * * 0",label:"每周日"}].map(s=>e.jsx(y,{"code-path":"src/components/deploy/PipelineManager.tsx:778:23",variant:"outline",className:"cursor-pointer text-[10px] hover:bg-blue-500/10",onClick:()=>de(s.expr),children:s.label},s.expr))})]}),O==="webhook"&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:787:17",className:"mt-3 space-y-2 p-3 rounded-md bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:788:19",className:"space-y-1",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:789:21",className:"text-xs",children:["Webhook Token ",e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:789:62",className:"text-[var(--dg-text-secondary)] opacity-60",children:"(签名验证,可选)"})]}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:790:21",value:Ke,onChange:s=>Ue(s.target.value),placeholder:"随机字符串",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] h-8 font-mono text-xs"})]}),e.jsxs("p",{"code-path":"src/components/deploy/PipelineManager.tsx:793:19",className:"text-[10px] text-[var(--dg-text-secondary)] opacity-60",children:["Webhook URL: ",e.jsxs("code",{"code-path":"src/components/deploy/PipelineManager.tsx:794:34",className:"text-[var(--dg-blue)]",children:["POST /api/v1/webhook/pipeline/","{code}"]})]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:801:13",className:"border-t border-[var(--dg-border)] pt-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:802:15",className:"flex items-center justify-between mb-2",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:803:17",children:["环境变量 ",e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:803:29",className:"text-xs text-[var(--dg-text-secondary)] opacity-60",children:["($","{VAR_NAME}"," 引用)"]})]}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:804:17",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>S([...j,{key:"",value:"",desc:""}]),children:[e.jsx(Pe,{"code-path":"src/components/deploy/PipelineManager.tsx:806:19",className:"h-3 w-3 mr-1"}),"添加变量"]})]}),j.length===0?e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:810:17",className:"text-xs text-[var(--dg-text-muted)] py-2",children:'暂无变量,点击"添加变量"新增'}):e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:812:17",className:"space-y-2",children:j.map((s,a)=>e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:814:21",className:"grid grid-cols-12 gap-2 items-start p-2 rounded-md bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]",children:[e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:815:23",value:s.key,onChange:t=>{const o=[...j];o[a]={...o[a],key:t.target.value},S(o)},placeholder:"变量名",className:"col-span-3 h-8 text-xs font-mono bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]"}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:818:23",value:s.value,onChange:t=>{const o=[...j];o[a]={...o[a],value:t.target.value},S(o)},placeholder:"变量值",className:"col-span-4 h-8 text-xs font-mono bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]"}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:821:23",value:s.desc,onChange:t=>{const o=[...j];o[a]={...o[a],desc:t.target.value},S(o)},placeholder:"说明",className:"col-span-4 h-8 text-xs bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]"}),e.jsx(p,{"code-path":"src/components/deploy/PipelineManager.tsx:824:23",variant:"ghost",size:"icon",className:"col-span-1 h-8 w-8 text-red-400",onClick:()=>S(j.filter((t,o)=>o!==a)),children:e.jsx(gs,{"code-path":"src/components/deploy/PipelineManager.tsx:826:25",className:"h-3.5 w-3.5"})})]},a))})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:835:13",className:"border-t border-[var(--dg-border)] pt-4",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:836:15",className:"mb-2 block",children:["构建缓存 ",e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:836:50",className:"text-xs text-[var(--dg-text-secondary)] opacity-60",children:"(加速后续构建)"})]}),e.jsx(g,{"code-path":"src/components/deploy/PipelineManager.tsx:837:15",value:Xe,onChange:s=>Ye(s.target.value),placeholder:"node_modules, .m2, target",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] h-8 text-xs font-mono"}),e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:839:15",className:"text-[10px] text-[var(--dg-text-secondary)] opacity-50 mt-1",children:"多个路径用逗号分隔,相同的 Key 会命中已有缓存"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:843:13",className:"border-t border-[var(--dg-border)] pt-4",children:[e.jsxs(d,{"code-path":"src/components/deploy/PipelineManager.tsx:844:15",className:"mb-2 block",children:["并发执行数 ",e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:844:51",className:"text-xs text-[var(--dg-text-secondary)] opacity-60",children:"(Number of executors)"})]}),e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:845:15",className:"flex items-center gap-2",children:e.jsxs(Z,{"code-path":"src/components/deploy/PipelineManager.tsx:846:17",value:String(Ze),onValueChange:s=>Cs(Number(s)),children:[e.jsx(ee,{"code-path":"src/components/deploy/PipelineManager.tsx:847:19",className:"w-32 h-8 text-xs bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(se,{"code-path":"src/components/deploy/PipelineManager.tsx:848:21"})}),e.jsxs(ae,{"code-path":"src/components/deploy/PipelineManager.tsx:850:19",children:[e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:851:21",value:"1",children:"1 — 串行"}),e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:852:21",value:"2",children:"2"}),e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:853:21",value:"3",children:"3"}),e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:854:21",value:"4",children:"4"}),e.jsx(v,{"code-path":"src/components/deploy/PipelineManager.tsx:855:21",value:"5",children:"5"})]})]})}),e.jsx("p",{"code-path":"src/components/deploy/PipelineManager.tsx:859:15",className:"text-[10px] text-[var(--dg-text-secondary)] opacity-50 mt-1",children:"设为 1 则按顺序串行执行,默认 2 可并发构建"})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:862:11",className:"flex justify-end gap-2 mt-4 pt-4 border-t border-[var(--dg-border)]",children:[e.jsx(p,{"code-path":"src/components/deploy/PipelineManager.tsx:863:13",variant:"outline",onClick:()=>z(!1),children:"取消"}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:864:13",onClick:$s,disabled:le,children:[le?e.jsx(w,{"code-path":"src/components/deploy/PipelineManager.tsx:865:25",className:"h-4 w-4 animate-spin mr-1"}):e.jsx(I,{"code-path":"src/components/deploy/PipelineManager.tsx:865:77",className:"h-4 w-4 mr-1"}),le?"创建中...":"创建流水线"]})]})]})}),e.jsx(ds,{"code-path":"src/components/deploy/PipelineManager.tsx:873:7",open:Ds,onOpenChange:es,children:e.jsxs(ps,{"code-path":"src/components/deploy/PipelineManager.tsx:874:9",className:"max-w-3xl max-h-[85vh] overflow-y-auto bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:[e.jsx(is,{"code-path":"src/components/deploy/PipelineManager.tsx:875:11",children:e.jsxs(xs,{"code-path":"src/components/deploy/PipelineManager.tsx:875:25",className:"flex items-center gap-2",children:[e.jsx(us,{"code-path":"src/components/deploy/PipelineManager.tsx:875:74",className:"h-5 w-5"}),"执行日志 #",V?.build_number||V?.id]})}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:876:11",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:877:13",className:"flex flex-wrap gap-3 text-sm text-[var(--dg-text-secondary)]",children:[e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:878:15",children:["触发方式: ",V?.triggered_by||"manual"]}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:879:15",children:["分支: ",V?.branch||"-"]}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:880:15",children:["耗时: ",Ne(V?.duration)]})]}),e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:882:13",className:"bg-slate-950 rounded-md p-3 max-h-[50vh] overflow-y-auto font-mono text-xs",children:ss.length===0?e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:883:36",className:"text-slate-500 py-4 text-center",children:"暂无日志"}):ss.map((s,a)=>e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:885:19",className:"flex gap-2 py-0.5",children:[e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:886:21",className:"text-slate-500 shrink-0",children:["[",s.time,"]"]}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:887:21",className:s.level==="error"?"text-red-400":s.level==="warn"?"text-yellow-400":s.level==="success"?"text-green-400":"text-slate-300",children:[s.level==="success"?"✓":s.level==="error"?"✗":s.level==="warn"?"!":">"," ",s.message]})]},a))})]})]})})]})}function la({pipeline:c,clusterId:b}){const[i,q]=n.useState(null),[J,L]=n.useState(!1),M=c.code||c.id,k=async()=>{if(M){L(!0);try{const r=await fe.get(`/pipelines/${M}/queue`);q(r?.data||r)}catch{q(null)}finally{L(!1)}}};n.useEffect(()=>{k();const r=setInterval(k,1e4);return()=>clearInterval(r)},[M]);const H=async r=>{try{await fe.delete(`/pipelines/${M}/queue/${r}`),x.success("已取消"),k()}catch{x.error("取消失败")}},T=i?.running||0,N=i?.queued||0,A=i?.queue_ids||[],F=c.max_executors||2,$=i?.pending_runs||[];return J&&!i||T===0&&N===0?null:e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:936:5",className:"px-4 py-2 space-y-2",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:938:7",className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:939:9",className:"text-[var(--dg-text-secondary)]",children:"构建执行状态"}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:940:9",className:"font-bold text-[var(--dg-text-primary)]",children:[T,"/",F]}),N>0&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:942:11",className:"text-[var(--dg-text-secondary)] ml-2",children:["构建队列 ",e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:943:18",className:"font-bold text-amber-400",children:["(",N,")"]})]})]}),N>0&&$.length>0&&e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:950:9",className:"space-y-1",children:$.map(r=>e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:952:13",className:"flex items-center justify-between bg-[var(--dg-bg-tertiary)] rounded px-3 py-1.5",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:953:15",className:"flex items-center gap-2 text-xs",children:[e.jsx(W,{"code-path":"src/components/deploy/PipelineManager.tsx:954:17",className:"h-3 w-3 text-amber-400"}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:955:17",className:"text-[var(--dg-text-secondary)] font-mono",children:["#",r.build_number||r.id]}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:956:17",className:"text-[var(--dg-text-secondary)]",children:r.branch||"-"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineManager.tsx:957:17",className:"text-[var(--dg-text-secondary)] opacity-50",children:r.triggered_by||"-"})]}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:959:15",variant:"ghost",size:"sm",className:"h-6 text-xs text-red-400 hover:text-red-300",onClick:()=>H(r.id),children:[e.jsx(D,{"code-path":"src/components/deploy/PipelineManager.tsx:960:17",className:"h-3 w-3 mr-1"}),"取消"]})]},r.id))}),N>0&&$.length===0&&A.length>0&&e.jsx("div",{"code-path":"src/components/deploy/PipelineManager.tsx:969:9",className:"space-y-1",children:A.map(r=>e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:971:13",className:"flex items-center justify-between bg-[var(--dg-bg-tertiary)] rounded px-3 py-1.5",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineManager.tsx:972:15",className:"flex items-center gap-2 text-xs",children:[e.jsx(W,{"code-path":"src/components/deploy/PipelineManager.tsx:973:17",className:"h-3 w-3 text-amber-400"}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineManager.tsx:974:17",className:"text-[var(--dg-text-muted)] font-mono",children:["Run #",r]})]}),e.jsxs(p,{"code-path":"src/components/deploy/PipelineManager.tsx:976:15",variant:"ghost",size:"sm",className:"h-6 text-xs text-red-400 hover:text-red-300",onClick:()=>H(r),children:[e.jsx(D,{"code-path":"src/components/deploy/PipelineManager.tsx:977:17",className:"h-3 w-3 mr-1"}),"取消"]})]},r))})]})}export{La as PipelineManager}; diff --git a/backend/static/assets/PipelineRunDetail-CwWLRhgo.js b/backend/static/assets/PipelineRunDetail-CwWLRhgo.js new file mode 100644 index 0000000..fc5fda4 --- /dev/null +++ b/backend/static/assets/PipelineRunDetail-CwWLRhgo.js @@ -0,0 +1,3 @@ +import{r as n,j as e,D as me,b as he,X as ue,d as ge,e as ye,a5 as be,a6 as fe,n as ee,h as C,W as De,i as je,B as E,a0 as Ne,v as ve,a7 as we,L as $,$ as Re,x as te,a8 as Pe,_ as Be}from"./index-DfyorCky.js";import{B as A}from"./badge-xNW8x0G1.js";import{C as Fe,b as ke,c as Se,a as Ce}from"./card-C55cvSHg.js";import{t as S}from"./index-a3ybMjbR.js";import{F as H}from"./folder-open-IMBifk-r.js";import{M as $e,a as _e}from"./minimize-2-CiCQYRfn.js";import{A as ze}from"./arrow-left-BDgGyrD0.js";import{F as Ee}from"./file-text-C9G5abwR.js";import{D as Ae}from"./download-DoZfYs2h.js";import{H as Z}from"./history-D_9jPUQg.js";import{T as Le}from"./trash-2-Dx32pOzT.js";import{R as Ie}from"./refresh-cw-DUB_tAG-.js";import{P as Te}from"./play-cdPayOtJ.js";import{B as Oe}from"./box-TTGA1p57.js";import{C as I}from"./circle-check-DWcXrx2k.js";import{S as Me}from"./shield-check-Dcx486cW.js";import{C as G}from"./circle-x-DK79Dhg2.js";import{S as Ue}from"./square-9TIYDO_t.js";function We(s){return s===0?"-":s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function He({open:s,onOpenChange:o,runId:u,buildNumber:r}){const[x,a]=n.useState(null),[P,B]=n.useState(!1),[N,L]=n.useState(""),[v,i]=n.useState(""),[w,_]=n.useState(!1),F=async c=>{if(u){B(!0),L("");try{const h=c?`?path=${encodeURIComponent(c)}`:"",g=await C.get(`/pipelines/runs/${u}/files${h}`);a(g),i(g?.current||"")}catch(h){L(h?.message||"加载失败"),a(null)}finally{B(!1)}}};n.useEffect(()=>{s&&u&&(i(""),F(""))},[s,u]);const b=async c=>{const h=De.getState().token||"",g=`${location.protocol}//${location.host}/api/v1/pipelines/runs/${u}/files/download?path=${encodeURIComponent(c.path)}&token=${encodeURIComponent(h)}`;window.open(g,"_blank")},R=v?v.split("/").filter(Boolean):[],T=[""].concat(R.map((c,h)=>"/"+R.slice(0,h+1).join("/")));return e.jsx(me,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:105:5",open:s,onOpenChange:o,children:e.jsxs(he,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:106:7",showCloseButton:!1,className:ue("bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] p-0 gap-0","!duration-0 !transition-none",w?"!max-w-none !w-screen !h-screen !rounded-none":""),style:w?{maxWidth:"100vw",width:"100vw",height:"100vh"}:{maxWidth:"700px",width:"85vw"},children:[e.jsxs(ge,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:117:9",className:"sr-only",children:["文件浏览器 #",r]}),e.jsx(ye,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:118:9",className:"sr-only",children:"流水线构建目录文件浏览"}),e.jsxs("div",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:121:9",className:"flex items-center justify-between px-4 py-2.5 border-b border-[var(--dg-border)] shrink-0",children:[e.jsxs("div",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:122:11",className:"flex items-center gap-2 min-w-0",children:[e.jsx(H,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:123:13",className:"h-4 w-4 text-[var(--dg-text-secondary)] shrink-0"}),e.jsxs("span",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:124:13",className:"text-[var(--dg-text-primary)] font-medium text-sm",children:["#",r," 工作区文件"]})]}),e.jsxs("div",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:128:11",className:"flex items-center gap-1",children:[e.jsx("button",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:129:13",onClick:()=>_(!w),className:"p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]",children:w?e.jsx($e,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:133:29",className:"h-4 w-4"}):e.jsx(_e,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:133:65",className:"h-4 w-4"})}),e.jsx("button",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:135:13",onClick:()=>o(!1),className:"p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]",children:e.jsx(be,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:139:15",className:"h-4 w-4"})})]})]}),e.jsx("div",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:145:9",className:"flex items-center gap-0.5 px-4 py-2 text-xs border-b border-[var(--dg-border)] bg-[var(--dg-bg-primary)] overflow-x-auto shrink-0",children:T.map((c,h)=>e.jsx("span",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:147:13",className:"flex items-center gap-0.5",children:h===0?e.jsx("button",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:149:17",onClick:()=>F(""),className:"text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] p-0.5",children:e.jsx(fe,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:153:19",className:"h-3.5 w-3.5"})}):e.jsxs(e.Fragment,{children:[e.jsx(ee,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:157:19",className:"h-3 w-3 text-[var(--dg-text-muted)] shrink-0"}),e.jsx("button",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:158:19",onClick:()=>F(c),className:"text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] truncate max-w-[120px]",children:R[h-1]})]})},c))}),e.jsxs("div",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:171:9",className:"overflow-y-auto",style:{height:w?"calc(100vh - 110px)":"420px"},children:[P&&e.jsx("div",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:173:13",className:"flex items-center justify-center h-full text-[var(--dg-text-muted)] text-sm",children:"加载中..."}),N&&e.jsx("div",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:179:13",className:"flex items-center justify-center h-full text-red-400 text-sm",children:N}),x&&!P&&e.jsxs("table",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:185:13",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:186:15",className:"sticky top-0 bg-[var(--dg-bg-primary)] border-b border-[var(--dg-border)]",children:e.jsxs("tr",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:187:17",className:"text-left text-[var(--dg-text-muted)] text-xs",children:[e.jsx("th",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:188:19",className:"py-2 pl-4 pr-2 font-medium",children:"名称"}),e.jsx("th",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:189:19",className:"py-2 px-2 font-medium w-24 text-right",children:"大小"}),e.jsx("th",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:190:19",className:"py-2 pr-4 pl-2 font-medium w-40 hidden sm:table-cell",children:"修改时间"}),e.jsx("th",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:191:19",className:"py-2 pr-4 pl-2 font-medium w-16"})]})}),e.jsxs("tbody",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:194:15",children:[v&&e.jsxs("tr",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:197:19",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)] cursor-pointer",onClick:()=>{const c=v.split("/").slice(0,-1).join("/");F(c)},children:[e.jsxs("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:204:21",className:"py-2 pl-4 pr-2 flex items-center gap-2",children:[e.jsx(ze,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:205:23",className:"h-4 w-4 text-[var(--dg-text-secondary)]"}),e.jsx("span",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:206:23",className:"text-[var(--dg-text-secondary)]",children:".."})]}),e.jsx("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:208:21",className:"py-2 px-2 text-right"}),e.jsx("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:209:21",className:"py-2 pr-4 pl-2 hidden sm:table-cell"}),e.jsx("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:210:21",className:"py-2 pr-4 pl-2"})]}),x.dirs?.map(c=>e.jsxs("tr",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:216:19",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)] cursor-pointer",onClick:()=>F(c.path),children:[e.jsxs("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:221:21",className:"py-2 pl-4 pr-2 flex items-center gap-2",children:[e.jsx(H,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:222:23",className:"h-4 w-4 text-amber-400 shrink-0"}),e.jsx("span",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:223:23",className:"text-[var(--dg-text-primary)]",children:c.name})]}),e.jsx("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:225:21",className:"py-2 px-2 text-right text-[var(--dg-text-muted)]",children:"-"}),e.jsx("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:226:21",className:"py-2 pr-4 pl-2 text-[var(--dg-text-muted)] hidden sm:table-cell",children:c.mod_time}),e.jsx("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:227:21",className:"py-2 pr-4 pl-2"})]},c.path)),x.files?.map(c=>e.jsxs("tr",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:233:19",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)]",children:[e.jsxs("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:237:21",className:"py-2 pl-4 pr-2 flex items-center gap-2",children:[e.jsx(Ee,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:238:23",className:"h-4 w-4 text-sky-400 shrink-0"}),e.jsx("span",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:239:23",className:"text-[var(--dg-text-primary)]",children:c.name})]}),e.jsx("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:241:21",className:"py-2 px-2 text-right text-[var(--dg-text-muted)]",children:We(c.size)}),e.jsx("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:242:21",className:"py-2 pr-4 pl-2 text-[var(--dg-text-muted)] hidden sm:table-cell",children:c.mod_time}),e.jsx("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:243:21",className:"py-2 pr-4 pl-2",children:e.jsx("button",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:244:23",onClick:h=>{h.stopPropagation(),b(c)},className:"p-1 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)] hover:text-white",title:"下载",children:e.jsx(Ae,{"code-path":"src/components/deploy/FileBrowserDialog.tsx:249:25",className:"h-3.5 w-3.5"})})})]},c.path)),x.dirs?.length===0&&x.files?.length===0&&!v&&e.jsx("tr",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:257:19",children:e.jsx("td",{"code-path":"src/components/deploy/FileBrowserDialog.tsx:258:21",colSpan:4,className:"py-8 text-center text-[var(--dg-text-muted)]",children:P?"加载中...":"目录为空"})})]})]})]})]})})}const j=[{key:"checkout",label:"代码检出",icon:Ne,color:"#6366F1",order:1},{key:"build",label:"构建",icon:Oe,color:"#F59E0B",order:2},{key:"test",label:"测试",icon:I,color:"#10B981",order:3},{key:"image",label:"镜像打包",icon:ve,color:"#06B6D4",order:4},{key:"deploy",label:"部署",icon:we,color:"#EF4444",order:5},{key:"verify",label:"验证",icon:Me,color:"#3B82F6",order:6}].sort((s,o)=>s.order-o.order),Ge={success:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",failed:"bg-red-500/20 text-red-400 border-red-500/30",running:"bg-blue-500/20 text-blue-400 border-blue-500/30",pending:"bg-slate-500/20 text-slate-400 border-slate-500/30",cancelled:"bg-amber-500/20 text-amber-400 border-amber-500/30"},Je={success:I,failed:G,running:$,pending:te,cancelled:Re};function Xe(s){if(!s)return"-";if(s<60)return`${s}秒`;const o=Math.floor(s/60),u=s%60;return`${o}分${u}秒`}function qe(s){return s?new Date(s).toLocaleString("zh-CN",{month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit"}):"-"}function Ke(s){if(!s)return[];try{const o=typeof s=="string"?JSON.parse(s):s;return Array.isArray(o)?o:[]}catch{return[]}}function Ve(s){const o=new Map;return s&&(Ke(s.stages).forEach(r=>{if(r.name||r.type){const x=r.type||j.find(a=>a.label===r.name)?.key;x&&o.set(x,r.status)}}),o.size===0&&s.status==="success"?j.forEach(r=>o.set(r.key,"success")):o.size===0&&s.status==="failed"?j.forEach((r,x)=>o.set(r.key,x===0?"success":"pending")):o.size===0&&s.status==="running"&&o.set("checkout","running")),o}function Qe(s,o){const u=s.find(x=>x.stage===o);if(u)return u.message;const r=j.find(x=>x.key===o);return r?`${r.label}...`:""}function gt(){const{code:s}=je(),[o,u]=n.useState(null),[r,x]=n.useState([]),[a,P]=n.useState(null),[B,N]=n.useState([]),[L,v]=n.useState(!1),[i,w]=n.useState(null),[_,F]=n.useState(10),[b,R]=n.useState(new Set),[T,c]=n.useState(!1),h=n.useRef(null),g=n.useRef(null),[se,J]=n.useState(!1),[X,oe]=n.useState(null),ne=n.useCallback(async()=>{try{const t=await C.get(`/pipelines/${s}`);u(t?.data||t)}catch{}},[s]),f=n.useCallback(async()=>{v(!0);try{const p=(await C.get(`/pipelines/${s}/runs?page_size=${_}`))?.list||[];x(p),!a&&p.length>0&&P(p[0])}catch{S.error("获取执行记录失败")}finally{v(!1)}},[s,_]);n.useEffect(()=>{ne(),f()},[]),n.useEffect(()=>{f()},[_]),n.useEffect(()=>{if(!r.some(l=>l.status==="running"))return;const p=setInterval(f,5e3);return()=>clearInterval(p)},[r,f]);const q=n.useCallback(async t=>{try{const p=await C.get(`/pipelines/runs/${t.id}/log-stream`);if(p?.logs){const l=typeof p.logs=="string"?JSON.parse(p.logs):p.logs;N(Array.isArray(l)?l:[])}else N([]);t.status==="running"&&ae(t.id)}catch{N([])}},[]),ae=t=>{g.current&&g.current.close();const p=window.location.protocol==="https:"?"wss:":"ws:",l=localStorage.getItem("token"),d=new WebSocket(`${p}//${window.location.host}/ws/pipeline/${t}/log?token=${l}`);d.onmessage=k=>{try{const m=JSON.parse(k.data);if(m.type==="init"&&m.logs){const y=typeof m.logs=="string"?JSON.parse(m.logs):m.logs;N(Array.isArray(y)?y:[])}else m.type==="done"?(d.close(),f()):m.time&&m.level&&N(y=>[...y,m])}catch{}},d.onclose=()=>{g.current=null},d.onerror=()=>{g.current=null},g.current=d};n.useEffect(()=>(a&&(q(a),w(null)),()=>{g.current&&g.current.close()}),[a,q]),n.useEffect(()=>{h.current?.scrollIntoView({behavior:"smooth"})},[B]);const le=async()=>{try{await C.post(`/pipelines/${s}/trigger`,{}),S.success("已触发"),f()}catch{S.error("触发失败")}},re=async t=>{try{await C.post(`/pipelines/${s}/runs/${t}/stop`,{}),S.success("已停止"),f()}catch{S.error("停止失败")}},ce=async()=>{if(b.size!==0){c(!0);try{await C.post(`/pipelines/${s}/runs/batch-delete`,{ids:Array.from(b)}),S.success(`已删除 ${b.size} 条记录`),R(new Set),f()}catch{S.error("批量删除失败")}finally{c(!1)}}},ie=t=>{R(p=>{const l=new Set(p);return l.has(t)?l.delete(t):l.add(t),l})},pe=()=>{b.size===r.length?R(new Set):R(new Set(r.map(t=>t.id)))},K=t=>t.triggered_by==="system"?"Cron":t.triggered_by==="git"?"Git Push":t.triggered_by||"Manual",O=Ve(a),V=i?B.filter(t=>t.stage===i):B,Q=i?Qe(B,i):"";return e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:293:5",className:"space-y-4 h-full flex flex-col",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:295:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:296:9",children:[e.jsxs("h2",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:297:11",className:"text-lg font-semibold text-[var(--dg-text-primary)]",children:[e.jsx(Z,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:298:13",className:"w-5 h-5 inline mr-2"}),"流水线详情"]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:301:11",className:"flex items-center gap-2 mt-0.5 flex-wrap",children:[o?.name&&e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:303:15",className:"text-sm font-medium text-[var(--dg-text-primary)]",children:o.name}),o?.environment&&e.jsx(A,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:308:15",className:"text-xs",style:{backgroundColor:o.environment.color+"20",color:o.environment.color},children:o.environment.display_name}),a&&e.jsxs("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:316:15",className:"text-sm text-[var(--dg-text-secondary)]",children:["发布 #",a.build_number]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:322:9",className:"flex gap-2 items-center",children:[b.size>0&&e.jsxs(E,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:324:13",variant:"destructive",size:"sm",onClick:ce,disabled:T,children:[e.jsx(Le,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:325:15",className:"w-4 h-4 mr-1"}),"删除 (",b.size,")"]}),e.jsxs("select",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:328:11",value:_,onChange:t=>F(Number(t.target.value)),className:"h-8 px-2 text-xs rounded border border-[var(--dg-border)] bg-[var(--dg-bg-secondary)] text-[var(--dg-text-primary)]",children:[e.jsx("option",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:333:13",value:10,children:"10条/页"}),e.jsx("option",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:334:13",value:20,children:"20条/页"}),e.jsx("option",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:335:13",value:30,children:"30条/页"})]}),e.jsxs(E,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:337:11",variant:"outline",size:"sm",onClick:f,children:[e.jsx(Ie,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:338:13",className:"w-4 h-4 mr-1"}),"刷新"]}),e.jsxs(E,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:340:11",size:"sm",onClick:le,children:[e.jsx(Te,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:341:13",className:"w-4 h-4 mr-1"}),"立即执行"]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:347:7",className:"flex items-center gap-0 px-4 py-3 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] overflow-x-auto",children:[j.map((t,p)=>{const l=O.get(t.key)||"",d=l==="success"||l==="completed",k=l==="running"||l==="in_progress",m=l==="failed"||l==="error",y=i===t.key;t.key;const z=O.size>0,D=m?"#EF4444":k?"#3B82F6":d?"#207060":"#6B7280",M=m?"#EF444420":k?"#3B82F620":d?"#20706020":"#6B728010",U=y?D:D+"50",W=t.icon,de=m?e.jsx(G,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:369:35",className:"h-3.5 w-3.5"}):k?e.jsx($,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:370:27",className:"h-3.5 w-3.5 animate-spin"}):d?e.jsx(I,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:371:27",className:"h-3.5 w-3.5"}):z?e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:372:25",className:"text-[10px] opacity-40",children:"○"}):e.jsx(W,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:373:15",className:"h-3.5 w-3.5 opacity-40"}),Y=p===j.length-1,xe=p===0?"8px 0 0 8px":Y?"0 8px 8px 0":"0";return e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:379:13",className:"flex items-center",children:[e.jsxs("button",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:380:15",onClick:()=>w(i===t.key?null:t.key),title:`${t.label}${l?` (${l})`:""} — 点击查看日志`,className:`flex items-center gap-1.5 px-3 py-2 text-[12px] font-semibold border shadow-sm transition-all cursor-pointer + ${y?"ring-1 ring-offset-0 scale-[1.02]":"hover:brightness-110"}`,style:{backgroundColor:M,borderColor:U,color:D,borderRadius:xe},children:[de,e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:393:17",children:t.label})]}),!Y&&e.jsx("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:396:17",className:"flex items-center justify-center w-5 h-5 -mx-px z-10",children:e.jsx(ee,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:397:19",className:"h-3.5 w-3.5",style:{color:D+"99"}})})]},t.key)}),a&&e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:404:11",className:"ml-auto text-[10px] text-[var(--dg-text-secondary)] opacity-40 shrink-0 pl-3 whitespace-nowrap",children:i?j.find(t=>t.key===i)?.label:"全阶段"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:411:7",className:"flex-1 flex flex-col min-h-0",children:[e.jsx("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:413:9",className:"rounded-md border border-[var(--dg-border)] overflow-hidden mb-4",children:L&&r.length===0?e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:415:13",className:"text-center py-12",children:[e.jsx($,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:416:15",className:"w-6 h-6 animate-spin mx-auto mb-2 text-[var(--dg-text-muted)]"}),"加载中..."]}):r.length===0?e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:420:13",className:"text-center py-12 border border-dashed border-[var(--dg-border)] rounded-lg m-4",children:[e.jsx(Z,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:421:15",className:"w-10 h-10 mx-auto mb-3 text-[var(--dg-text-muted)]"}),e.jsx("p",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:422:15",className:"text-[var(--dg-text-secondary)]",children:'暂无执行记录,点击"立即执行"触发构建'})]}):e.jsxs("table",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:425:13",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:426:15",className:"bg-[var(--dg-bg-tertiary)] border-b border-[var(--dg-border)]",children:e.jsxs("tr",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:427:17",children:[e.jsx("th",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:428:19",className:"px-2 py-2.5 w-10",children:e.jsx("input",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:429:21",type:"checkbox",checked:b.size===r.length&&r.length>0,onChange:pe,className:"rounded"})}),e.jsx("th",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:432:19",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] w-16",children:"构建"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:433:19",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] w-20",children:"状态"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:434:19",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]",children:"触发方式"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:435:19",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]",children:"用户"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:436:19",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)]",children:"耗时"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:437:19",className:"px-3 py-2.5 text-left font-medium text-[var(--dg-text-secondary)] hidden md:table-cell",children:"时间"}),e.jsx("th",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:438:19",className:"px-3 py-2.5 text-right font-medium text-[var(--dg-text-secondary)] w-32",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:441:15",children:r.map(t=>{const p=Je[t.status]||te;return e.jsxs("tr",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:445:21",className:`border-b border-[var(--dg-border)] cursor-pointer transition-colors + ${a?.id===t.id?"bg-[var(--dg-blue)]/10":"hover:bg-[var(--dg-bg-tertiary)]/50"}`,onClick:()=>{P(t)},children:[e.jsx("td",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:449:23",className:"px-2 py-2.5",onClick:l=>l.stopPropagation(),children:e.jsx("input",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:450:25",type:"checkbox",checked:b.has(t.id),onChange:()=>ie(t.id),className:"rounded"})}),e.jsxs("td",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:453:23",className:"px-3 py-2.5 font-mono font-semibold text-[var(--dg-text-primary)]",children:["#",t.build_number]}),e.jsx("td",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:456:23",className:"px-3 py-2.5",children:e.jsxs(A,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:457:25",className:`text-xs ${Ge[t.status]||""} flex items-center gap-1 w-fit`,children:[e.jsx(p,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:458:27",className:`w-3 h-3 ${t.status==="running"?"animate-spin":""}`}),t.status==="success"?"成功":t.status==="failed"?"失败":t.status==="running"?"执行中":t.status==="cancelled"?"已取消":"待执行"]})}),e.jsx("td",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:466:23",className:"px-3 py-2.5",children:e.jsx(A,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:467:25",variant:"outline",className:"text-xs",children:K(t)})}),e.jsxs("td",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:469:23",className:"px-3 py-2.5 text-[var(--dg-text-secondary)] flex items-center gap-1",children:[e.jsx(Pe,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:470:25",className:"w-3 h-3"}),t.triggered_by||"admin"]}),e.jsx("td",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:473:23",className:"px-3 py-2.5 text-[var(--dg-text-secondary)] font-mono text-xs",children:t.status==="running"?e.jsxs("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:475:27",className:"flex items-center gap-1 text-blue-400",children:[e.jsx($,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:476:29",className:"w-3 h-3 animate-spin"}),"执行中..."]}):Xe(t.duration)}),e.jsx("td",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:480:23",className:"px-3 py-2.5 text-[var(--dg-text-muted)] text-xs hidden md:table-cell",children:qe(t.created_at)}),e.jsx("td",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:483:23",className:"px-3 py-2.5 text-right",onClick:l=>l.stopPropagation(),children:e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:484:25",className:"flex justify-end gap-1",children:[e.jsx(E,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:485:27",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>P(t),children:"日志"}),e.jsxs(E,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:489:27",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{oe({id:t.id,buildNumber:t.build_number}),J(!0)},children:[e.jsx(H,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:491:29",className:"w-3.5 h-3.5 mr-1"}),"浏览"]}),t.status==="running"&&e.jsx(E,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:494:29",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-500",onClick:()=>re(t.id),children:e.jsx(Ue,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:496:31",className:"w-3.5 h-3.5"})})]})})]},t.id)})})]})}),a&&e.jsxs(Fe,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:511:11",className:"flex-1 flex flex-col min-h-0 border-[var(--dg-border)] bg-[var(--dg-bg-secondary)]",children:[e.jsxs(ke,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:512:13",className:"py-3 px-4 flex flex-row items-center justify-between border-b border-[var(--dg-border)]",children:[e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:513:15",className:"flex items-center gap-3",children:[e.jsxs(Se,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:514:17",className:"text-sm font-mono",children:[o?.name||`#${s}`," #",a.build_number]}),a.status==="running"&&e.jsxs(A,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:518:19",className:"bg-blue-500/20 text-blue-400 border-blue-500/30 text-xs",children:[e.jsx($,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:519:21",className:"w-3 h-3 animate-spin mr-1"}),"实时"]}),i&&e.jsx(A,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:523:19",className:"text-xs border-[var(--dg-border)]",variant:"outline",children:j.find(t=>t.key===i)?.label||i})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:528:15",className:"flex items-center gap-2 text-xs text-[var(--dg-text-muted)]",children:[e.jsxs("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:529:17",children:["触发: ",K(a)," (",a.triggered_by||"admin",")"]}),e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:530:17",className:"opacity-40",children:"|"}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:531:17",children:["分支: ",a.branch||"-"]}),a.commit_id&&e.jsxs(e.Fragment,{children:[e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:534:21",className:"opacity-40",children:"|"}),e.jsx("code",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:535:21",className:"bg-amber-400/10 text-amber-400 px-1 py-0.5 rounded text-[10px]",children:a.commit_id.slice(0,8)})]}),a.image_tag&&e.jsxs(e.Fragment,{children:[e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:542:21",className:"opacity-40",children:"|"}),e.jsxs("code",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:543:21",className:"bg-cyan-400/10 text-cyan-400 px-1 py-0.5 rounded text-[10px]",children:["📦 ",a.image_tag]})]})]})]}),e.jsxs(Ce,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:550:13",className:"flex-1 p-0 overflow-hidden min-h-0",children:[i&&Q&&e.jsx("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:553:17",className:"px-4 py-2 border-b border-[var(--dg-border)] bg-[var(--dg-bg-tertiary)]/30",children:e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:554:19",className:"flex items-center gap-2",children:[e.jsxs("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:555:21",className:"text-[11px] font-semibold text-[var(--dg-text-secondary)]",children:["[",j.find(t=>t.key===i)?.label||i,"]"]}),(()=>{const t=O.get(i);return t==="success"||t==="completed"?e.jsx(I,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:560:74",className:"h-3.5 w-3.5 text-emerald-400"}):t==="failed"||t==="error"?e.jsx(G,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:561:69",className:"h-3.5 w-3.5 text-red-400"}):t==="running"||t==="in_progress"?e.jsx($,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:562:76",className:"h-3.5 w-3.5 text-blue-400 animate-spin"}):null})(),e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:565:21",className:"text-xs text-[var(--dg-text-muted)] truncate font-mono",children:Q})]})}),e.jsx("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:571:15",className:"h-full overflow-y-auto bg-[#0d1117] font-mono text-xs leading-5 p-4",style:{minHeight:280},children:V.length===0&&a.status!=="running"?e.jsx("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:573:19",className:"text-center py-12 text-slate-500",children:i?"该阶段暂无日志输出":"暂无日志输出"}):e.jsxs(e.Fragment,{children:[(()=>{let t="";const p={checkout:"border-indigo-500 bg-indigo-500/10",build:"border-amber-500 bg-amber-500/10",test:"border-emerald-500 bg-emerald-500/10",image:"border-cyan-500 bg-cyan-500/10",deploy:"border-red-500 bg-red-500/10",verify:"border-blue-500 bg-blue-500/10"},l={checkout:"⬇",build:"⚙",test:"✓",image:"📦",deploy:"🚀",verify:"🛡"};return V.map((d,k)=>{const m=!i&&d.stage&&d.stage!==t;m&&(t=d.stage||"");const y=d.level==="error",z=d.level==="warn",D=d.level==="success",M=y?"border-l-2 border-red-500 bg-red-500/10":z?"border-l-2 border-amber-500 bg-amber-500/10":D?"border-l-2 border-emerald-500 bg-emerald-500/5":"",U=y?"text-red-200":z?"text-amber-200":D?"text-emerald-200":"text-slate-300",W=y?e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:605:29",className:"shrink-0 px-1.5 py-px rounded text-[10px] font-bold bg-red-600/40 text-red-200",children:"ERR"}):z?e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:607:29",className:"shrink-0 px-1.5 py-px rounded text-[10px] font-bold bg-amber-600/40 text-amber-200",children:"WARN"}):D?e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:609:29",className:"shrink-0 px-1.5 py-px rounded text-[10px] font-bold bg-emerald-600/30 text-emerald-200",children:" OK "}):e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:610:29",className:"shrink-0 px-1.5 py-px rounded text-[10px] bg-slate-600/30 text-slate-400",children:"INFO"});return e.jsxs(Be.Fragment,{children:[m&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:614:31",className:`flex items-center gap-2 my-2 py-1 px-2 border-l-4 rounded-r ${p[d.stage||""]||"border-slate-500 bg-slate-500/10"}`,children:[e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:615:33",className:"text-xs",children:l[d.stage||""]||"▸"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:616:33",className:"text-[11px] font-semibold tracking-wider text-slate-200",children:d.stage}),e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:617:33",className:"flex-1 border-t border-slate-700/50"})]}),e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:620:29",className:`flex items-start gap-2 px-2 py-0.5 -mx-1 rounded-sm ${M} ${!y&&!z&&!D?"hover:bg-white/[0.03]":""}`,children:[e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:621:31",className:"text-slate-600 shrink-0 w-14 text-right text-[10px] pt-px",children:d.time}),W,e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:623:31",className:`break-all ${U}`,children:d.message})]})]},k)})})(),a.status==="running"&&e.jsxs("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:630:23",className:"flex items-center gap-2 mt-2 py-1.5 px-3 bg-blue-500/10 border-l-4 border-blue-500 rounded-r",children:[e.jsx($,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:631:25",className:"w-3 h-3 animate-spin text-blue-400 shrink-0"}),e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:632:25",className:"text-[11px] text-blue-300 font-medium",children:"流水线执行中,实时输出..."}),e.jsxs("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:633:25",className:"flex gap-1 ml-1",children:[e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:634:27",className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"0ms"}}),e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:635:27",className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"150ms"}}),e.jsx("span",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:636:27",className:"w-1 h-1 rounded-full bg-blue-400 animate-bounce",style:{animationDelay:"300ms"}})]})]}),e.jsx("div",{"code-path":"src/components/deploy/PipelineRunDetail.tsx:640:21",ref:h})]})})]})]})]}),e.jsx(He,{"code-path":"src/components/deploy/PipelineRunDetail.tsx:650:7",open:se,onOpenChange:J,runId:X?.id??null,buildNumber:X?.buildNumber??0})]})}export{gt as default}; diff --git a/backend/static/assets/PlatformManager-DvSL1hbm.js b/backend/static/assets/PlatformManager-DvSL1hbm.js new file mode 100644 index 0000000..8677b3d --- /dev/null +++ b/backend/static/assets/PlatformManager-DvSL1hbm.js @@ -0,0 +1 @@ +import{r as t,j as e,S as K,I as d,B as m,L as k,C as L,D as E,b as I,c as T,d as B,e as O,f as V}from"./index-DfyorCky.js";import{L as r}from"./label-BK0h2apY.js";import{B as j}from"./badge-xNW8x0G1.js";import{S as P,a as M,b as v,c as b,d as o}from"./select-D5qUzdAs.js";import{p as x}from"./cloud-Dzoer-2i.js";import{P as U}from"./plus-CUG-9kpu.js";import{E as W}from"./external-link-CzIpMNu1.js";import{P as Y}from"./pencil-BqUotcjf.js";import{T as Z}from"./trash-2-Dx32pOzT.js";import{C as $}from"./circle-check-DWcXrx2k.js";import{C as ee}from"./circle-x-DK79Dhg2.js";import"./index-CWVNW_qu.js";const ae={public:"公有云",private:"私有云",hybrid:"混合云"},se={public:"text-blue-400",private:"text-purple-400",hybrid:"text-cyan-400"};function ue(){const[F,N]=t.useState([]),[Q,y]=t.useState(!0),[h,A]=t.useState(""),[u,H]=t.useState("all"),[R,l]=t.useState(!1),[n,C]=t.useState(null),[w,S]=t.useState(!1),[s,c]=t.useState({name:"",code:"",type:"public",status:"active",website:"",description:""}),p=t.useCallback(async()=>{y(!0);try{const f=(await x.list())?.list||[];N(f)}catch{N([])}finally{y(!1)}},[]);t.useEffect(()=>{p()},[p]);const D=F.filter(a=>{const f=a.name?.toLowerCase().includes(h.toLowerCase())||a.code?.toLowerCase().includes(h.toLowerCase()),J=u==="all"||a.type===u;return f&&J}),X=()=>{C(null),c({name:"",code:"",type:"public",status:"active",website:"",description:""}),l(!0)},_=a=>{C(a),c({name:a.name||"",code:a.code||"",type:a.type||"public",status:a.status||"active",website:a.website||"",description:a.description||""}),l(!0)},q=async()=>{if(!(!s.name.trim()||!s.code.trim())){S(!0);try{n?await x.update(n.id,s):await x.create(s),l(!1),p()}catch{}finally{S(!1)}}},[g,i]=t.useState(null),z=a=>i(a),G=async()=>{g!==null&&(await x.delete(g),i(null),p())};return e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:124:5",className:"p-6 space-y-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:126:7",className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:127:9",className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:128:11",className:"relative w-72",children:[e.jsx(K,{"code-path":"src/components/cloud/PlatformManager.tsx:129:13",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(d,{"code-path":"src/components/cloud/PlatformManager.tsx:130:13",placeholder:"搜索平台名称或编码...",value:h,onChange:a=>A(a.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700"})]}),e.jsxs(P,{"code-path":"src/components/cloud/PlatformManager.tsx:137:11",value:u,onValueChange:H,children:[e.jsx(M,{"code-path":"src/components/cloud/PlatformManager.tsx:138:13",className:"w-32 h-9 bg-slate-800/50 border-slate-700",children:e.jsx(v,{"code-path":"src/components/cloud/PlatformManager.tsx:139:15"})}),e.jsxs(b,{"code-path":"src/components/cloud/PlatformManager.tsx:141:13",children:[e.jsx(o,{"code-path":"src/components/cloud/PlatformManager.tsx:142:15",value:"all",children:"全部类型"}),e.jsx(o,{"code-path":"src/components/cloud/PlatformManager.tsx:143:15",value:"public",children:"公有云"}),e.jsx(o,{"code-path":"src/components/cloud/PlatformManager.tsx:144:15",value:"private",children:"私有云"}),e.jsx(o,{"code-path":"src/components/cloud/PlatformManager.tsx:145:15",value:"hybrid",children:"混合云"})]})]})]}),e.jsxs(m,{"code-path":"src/components/cloud/PlatformManager.tsx:149:9",onClick:X,className:"gap-2",children:[e.jsx(U,{"code-path":"src/components/cloud/PlatformManager.tsx:150:11",className:"h-4 w-4"}),"添加平台"]})]}),Q?e.jsx("div",{"code-path":"src/components/cloud/PlatformManager.tsx:157:9",className:"flex justify-center py-20",children:e.jsx(k,{"code-path":"src/components/cloud/PlatformManager.tsx:158:11",className:"h-6 w-6 animate-spin text-slate-500"})}):D.length===0?e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:161:9",className:"text-center py-20 text-slate-500",children:[e.jsx(L,{"code-path":"src/components/cloud/PlatformManager.tsx:162:11",className:"h-12 w-12 mx-auto mb-3 opacity-40"}),e.jsx("p",{"code-path":"src/components/cloud/PlatformManager.tsx:163:11",children:"暂无云平台数据"})]}):e.jsx("div",{"code-path":"src/components/cloud/PlatformManager.tsx:166:9",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:D.map(a=>e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:168:13",className:"bg-slate-800/30 rounded-lg p-4 hover:bg-slate-800/50 transition-colors group",children:[e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:172:15",className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:173:17",className:"flex items-center gap-3",children:[e.jsx("div",{"code-path":"src/components/cloud/PlatformManager.tsx:174:19",className:"w-10 h-10 rounded-lg bg-blue-500/20 flex items-center justify-center",children:e.jsx(L,{"code-path":"src/components/cloud/PlatformManager.tsx:175:21",className:"h-5 w-5 text-blue-400"})}),e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:177:19",children:[e.jsx("h3",{"code-path":"src/components/cloud/PlatformManager.tsx:178:21",className:"font-medium text-slate-100",children:a.name}),e.jsx("span",{"code-path":"src/components/cloud/PlatformManager.tsx:179:21",className:"text-xs text-slate-500 font-mono",children:a.code})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:182:17",className:"flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[a.website&&e.jsx("a",{"code-path":"src/components/cloud/PlatformManager.tsx:184:21",href:a.website,target:"_blank",rel:"noreferrer",className:"p-1.5 rounded hover:bg-slate-700 text-slate-400 hover:text-slate-200",children:e.jsx(W,{"code-path":"src/components/cloud/PlatformManager.tsx:185:23",className:"h-3.5 w-3.5"})}),e.jsx("button",{"code-path":"src/components/cloud/PlatformManager.tsx:188:19",onClick:()=>_(a),className:"p-1.5 rounded hover:bg-slate-700 text-slate-400 hover:text-slate-200",children:e.jsx(Y,{"code-path":"src/components/cloud/PlatformManager.tsx:189:21",className:"h-3.5 w-3.5"})}),e.jsx("button",{"code-path":"src/components/cloud/PlatformManager.tsx:191:19",onClick:()=>z(a.id),className:"p-1.5 rounded hover:bg-slate-700 text-slate-400 hover:text-red-400",children:e.jsx(Z,{"code-path":"src/components/cloud/PlatformManager.tsx:192:21",className:"h-3.5 w-3.5"})})]})]}),a.description&&e.jsx("p",{"code-path":"src/components/cloud/PlatformManager.tsx:198:17",className:"text-sm text-slate-400 mb-3 line-clamp-2",children:a.description}),e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:201:15",className:"flex items-center gap-2 flex-wrap",children:[e.jsx(j,{"code-path":"src/components/cloud/PlatformManager.tsx:202:17",variant:"outline",className:se[a.type]||"text-slate-400",children:ae[a.type]||a.type}),a.status==="active"?e.jsxs(j,{"code-path":"src/components/cloud/PlatformManager.tsx:206:19",className:"bg-emerald-500/20 text-emerald-400 gap-1",children:[e.jsx($,{"code-path":"src/components/cloud/PlatformManager.tsx:207:21",className:"h-3 w-3"})," 启用"]}):e.jsxs(j,{"code-path":"src/components/cloud/PlatformManager.tsx:210:19",className:"bg-slate-500/20 text-slate-400 gap-1",children:[e.jsx(ee,{"code-path":"src/components/cloud/PlatformManager.tsx:211:21",className:"h-3 w-3"})," 禁用"]})]})]},a.id))}),e.jsx(E,{"code-path":"src/components/cloud/PlatformManager.tsx:221:7",open:R,onOpenChange:l,children:e.jsxs(I,{"code-path":"src/components/cloud/PlatformManager.tsx:222:9",children:[e.jsxs(T,{"code-path":"src/components/cloud/PlatformManager.tsx:223:11",children:[e.jsx(B,{"code-path":"src/components/cloud/PlatformManager.tsx:224:13",children:n?"编辑云平台":"添加云平台"}),e.jsx(O,{"code-path":"src/components/cloud/PlatformManager.tsx:225:13",className:"sr-only",children:"描述"})]}),e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:227:11",className:"space-y-4 py-2",children:[e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:228:13",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:229:15",className:"space-y-1.5",children:[e.jsx(r,{"code-path":"src/components/cloud/PlatformManager.tsx:230:17",children:"平台名称 *"}),e.jsx(d,{"code-path":"src/components/cloud/PlatformManager.tsx:231:17",value:s.name,onChange:a=>c({...s,name:a.target.value}),placeholder:"如:阿里云",className:"bg-slate-800/50 border-slate-700"})]}),e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:238:15",className:"space-y-1.5",children:[e.jsx(r,{"code-path":"src/components/cloud/PlatformManager.tsx:239:17",children:"编码 *"}),e.jsx(d,{"code-path":"src/components/cloud/PlatformManager.tsx:240:17",value:s.code,onChange:a=>c({...s,code:a.target.value}),placeholder:"如:aliyun",className:"bg-slate-800/50 border-slate-700",disabled:!!n})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:249:13",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:250:15",className:"space-y-1.5",children:[e.jsx(r,{"code-path":"src/components/cloud/PlatformManager.tsx:251:17",children:"类型"}),e.jsxs(P,{"code-path":"src/components/cloud/PlatformManager.tsx:252:17",value:s.type,onValueChange:a=>c({...s,type:a}),children:[e.jsx(M,{"code-path":"src/components/cloud/PlatformManager.tsx:253:19",className:"bg-slate-800/50 border-slate-700",children:e.jsx(v,{"code-path":"src/components/cloud/PlatformManager.tsx:254:21"})}),e.jsxs(b,{"code-path":"src/components/cloud/PlatformManager.tsx:256:19",children:[e.jsx(o,{"code-path":"src/components/cloud/PlatformManager.tsx:257:21",value:"public",children:"公有云"}),e.jsx(o,{"code-path":"src/components/cloud/PlatformManager.tsx:258:21",value:"private",children:"私有云"}),e.jsx(o,{"code-path":"src/components/cloud/PlatformManager.tsx:259:21",value:"hybrid",children:"混合云"})]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:263:15",className:"space-y-1.5",children:[e.jsx(r,{"code-path":"src/components/cloud/PlatformManager.tsx:264:17",children:"状态"}),e.jsxs(P,{"code-path":"src/components/cloud/PlatformManager.tsx:265:17",value:s.status,onValueChange:a=>c({...s,status:a}),children:[e.jsx(M,{"code-path":"src/components/cloud/PlatformManager.tsx:266:19",className:"bg-slate-800/50 border-slate-700",children:e.jsx(v,{"code-path":"src/components/cloud/PlatformManager.tsx:267:21"})}),e.jsxs(b,{"code-path":"src/components/cloud/PlatformManager.tsx:269:19",children:[e.jsx(o,{"code-path":"src/components/cloud/PlatformManager.tsx:270:21",value:"active",children:"启用"}),e.jsx(o,{"code-path":"src/components/cloud/PlatformManager.tsx:271:21",value:"inactive",children:"禁用"})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:276:13",className:"space-y-1.5",children:[e.jsx(r,{"code-path":"src/components/cloud/PlatformManager.tsx:277:15",children:"官网地址"}),e.jsx(d,{"code-path":"src/components/cloud/PlatformManager.tsx:278:15",value:s.website,onChange:a=>c({...s,website:a.target.value}),placeholder:"https://...",className:"bg-slate-800/50 border-slate-700"})]}),e.jsxs("div",{"code-path":"src/components/cloud/PlatformManager.tsx:285:13",className:"space-y-1.5",children:[e.jsx(r,{"code-path":"src/components/cloud/PlatformManager.tsx:286:15",children:"描述"}),e.jsx(d,{"code-path":"src/components/cloud/PlatformManager.tsx:287:15",value:s.description,onChange:a=>c({...s,description:a.target.value}),placeholder:"平台描述...",className:"bg-slate-800/50 border-slate-700"})]})]}),e.jsxs(V,{"code-path":"src/components/cloud/PlatformManager.tsx:295:11",children:[e.jsx(m,{"code-path":"src/components/cloud/PlatformManager.tsx:296:13",variant:"ghost",onClick:()=>l(!1),children:"取消"}),e.jsxs(m,{"code-path":"src/components/cloud/PlatformManager.tsx:297:13",onClick:q,disabled:w||!s.name.trim()||!s.code.trim(),children:[w&&e.jsx(k,{"code-path":"src/components/cloud/PlatformManager.tsx:298:30",className:"h-4 w-4 mr-1 animate-spin"}),n?"保存":"创建"]})]})]})}),e.jsx(E,{"code-path":"src/components/cloud/PlatformManager.tsx:306:7",open:g!==null,onOpenChange:a=>!a&&i(null),children:e.jsxs(I,{"code-path":"src/components/cloud/PlatformManager.tsx:307:9",className:"max-w-sm",children:[e.jsxs(T,{"code-path":"src/components/cloud/PlatformManager.tsx:308:11",children:[e.jsx(B,{"code-path":"src/components/cloud/PlatformManager.tsx:309:13",children:"确认删除"}),e.jsx(O,{"code-path":"src/components/cloud/PlatformManager.tsx:310:13",className:"sr-only",children:"描述"})]}),e.jsx("p",{"code-path":"src/components/cloud/PlatformManager.tsx:312:11",className:"text-sm text-slate-400",children:"确定删除此云平台?此操作不可撤销。"}),e.jsxs(V,{"code-path":"src/components/cloud/PlatformManager.tsx:313:11",children:[e.jsx(m,{"code-path":"src/components/cloud/PlatformManager.tsx:314:13",variant:"ghost",onClick:()=>i(null),children:"取消"}),e.jsx(m,{"code-path":"src/components/cloud/PlatformManager.tsx:315:13",variant:"destructive",onClick:G,children:"删除"})]})]})})]})}export{ue as PlatformManager}; diff --git a/backend/static/assets/PodFileBrowser-BySN2XGN.js b/backend/static/assets/PodFileBrowser-BySN2XGN.js new file mode 100644 index 0000000..10904bd --- /dev/null +++ b/backend/static/assets/PodFileBrowser-BySN2XGN.js @@ -0,0 +1,25 @@ +import{r as H,j as y,B as le,a9 as gl,L as St,a5 as Zs,D as Iu,b as Wu,X as xl,d as Fu,e as Vu,H as Hu,n as zu}from"./index-DfyorCky.js";import{u as Ah}from"./use-toast-CrSOP4cJ.js";import{k as wt}from"./kubernetes-J8O09fK7.js";import{C as bl}from"./copy-DXW4LnkN.js";import{S as xs}from"./sparkles-Bld4NX5y.js";import{S as yl}from"./save-DoGGjfwC.js";import{S as kl,a as wl,b as vl,c as Sl,d as Ol}from"./select-D5qUzdAs.js";import{x as Qu,a as $u}from"./xterm-DSqgeKvr.js";import{B as ju}from"./box-TTGA1p57.js";import{R as qu}from"./rotate-cw-5qcj_h_q.js";import{M as Xu,a as Uu}from"./minimize-2-CiCQYRfn.js";import{B as Yu}from"./badge-xNW8x0G1.js";import{H as _u}from"./hard-drive-BbPmnARR.js";import{A as Ku}from"./arrow-left-BDgGyrD0.js";import{U as Gu}from"./upload-Ba6rlaGS.js";import{R as Ju}from"./refresh-cw-DUB_tAG-.js";import{a as Zu,F as ed}from"./folder-DoMwqvzv.js";import{D as td}from"./download-DoZfYs2h.js";function Tr(){return Tr=Object.assign?Object.assign.bind():function(s){for(var e=1;e|]/.test(P)}function A(N){for(i++;iP.startsWith(D)):!1}for(;i=2&&D<=4&&P.startsWith("pod-template-hash")&&P.includes(":")){i++;continue}if(D===2&&M&&n.has(M)){S(N)?i++:A(2);continue}if(D===2&&M&&r.has(M)){A(2);continue}if(f&&D>2&&M&&a.has(M)){if(S(N))i++;else{const R=P.split(":").slice(1).join(":").trim();/^[>|]/.test(R)?A(D):i++}continue}}if(u){if(D===2&&M==="template"){t.push(N),i++;continue}if(D===2&&M&&o[M]){const F=P.split(":").slice(1).join(":").trim();if(o[M].includes(F)){i++;continue}}if(D===2&&M==="nodeName"){i++;continue}if(D===2&&M==="spec"){d=!0,k=D,t.push(N),i++;continue}}if(d&&D>k){if(M==="containers"){p=!0,m=!1,t.push(N),i++;continue}if(M==="initContainers"){m=!0,p=!1,t.push(N),i++;continue}if(M==="volumes"){x=!0,t.push(N),i++;continue}if(M&&o[M]){const F=P.split(":").slice(1).join(":").trim();if(o[M].includes(F)){i++;continue}}if(M==="nodeName"){i++;continue}if(M==="serviceAccount"&&P.endsWith(":")){S(N)?i++:A(D);continue}}if((p||m)&&D>=6){if(M&&l[M]){const F=P.split(":").slice(1).join(":").trim();if(l[M].includes(F)){i++;continue}}if(M==="volumeMounts"&&(g=!0),g&&P.startsWith("- name:")){let F=[N],R=i+1,C=!1;for(;R=4&&P.startsWith("- name:")&&O(P)){const F=D;for(i++;i0&&t[t.length-1].trim()===""){i++;continue}t.push(N),i++}return t.join(` +`).replace(/\n{3,}/g,` + +`).trimEnd()+` +`}function sd(s){return s.includes("mountPath:")&&(s.includes("/var/run/secrets/kubernetes.io")||s.includes("/var/run/secrets/sa"))}const ys={green:"#10b981",orange:"#f59e0b",red:"#ef4444",blue:"#326CE5"};function Ey(s){if(!s)return"#64748b";const e=s.toLowerCase();return["running","available","ready","active","completed","succeeded"].includes(e)?ys.green:["pending","updating","progressing","containercreating"].includes(e)?ys.orange:["failed","error","crashloopbackoff","imagepullbackoff","errimageneverpull"].includes(e)?ys.red:ys.blue}function Ly(s){if(!s)return"-";const e=new Date(s);if(isNaN(e.getTime()))return s;const t=i=>String(i).padStart(2,"0");return`${e.getFullYear()}-${t(e.getMonth()+1)}-${t(e.getDate())} ${t(e.getHours())}:${t(e.getMinutes())}:${t(e.getSeconds())}`}function Ny(s,e){if(!s||!e)return null;const t=new Date(s).getTime(),i=new Date(e).getTime();return isNaN(t)||isNaN(i)||i{let s="lc,34,7n,7,7b,19,,,,2,,2,,,20,b,1c,l,g,,2t,7,2,6,2,2,,4,z,,u,r,2j,b,1m,9,9,,o,4,,9,,3,,5,17,3,3b,f,,w,1j,,,,4,8,4,,3,7,a,2,t,,1m,,,,2,4,8,,9,,a,2,q,,2,2,1l,,4,2,4,2,2,3,3,,u,2,3,,b,2,1l,,4,5,,2,4,,k,2,m,6,,,1m,,,2,,4,8,,7,3,a,2,u,,1n,,,,c,,9,,14,,3,,1l,3,5,3,,4,7,2,b,2,t,,1m,,2,,2,,3,,5,2,7,2,b,2,s,2,1l,2,,,2,4,8,,9,,a,2,t,,20,,4,,2,3,,,8,,29,,2,7,c,8,2q,,2,9,b,6,22,2,r,,,,,,1j,e,,5,,2,5,b,,10,9,,2u,4,,6,,2,2,2,p,2,4,3,g,4,d,,2,2,6,,f,,jj,3,qa,3,t,3,t,2,u,2,1s,2,,7,8,,2,b,9,,19,3,3b,2,y,,3a,3,4,2,9,,6,3,63,2,2,,1m,,,7,,,,,2,8,6,a,2,,1c,h,1r,4,1c,7,,,5,,14,9,c,2,w,4,2,2,,3,1k,,,2,3,,,3,1m,8,2,2,48,3,,d,,7,4,,6,,3,2,5i,1m,,5,ek,,5f,x,2da,3,3x,,2o,w,fe,6,2x,2,n9w,4,,a,w,2,28,2,7k,,3,,4,,p,2,5,,47,2,q,i,d,,12,8,p,b,1a,3,1c,,2,4,2,2,13,,1v,6,2,2,2,2,c,,8,,1b,,1f,,,3,2,2,5,2,,,16,2,8,,6m,,2,,4,,fn4,,kh,g,g,g,a6,2,gt,,6a,,45,5,1ae,3,,2,5,4,14,3,4,,4l,2,fx,4,ar,2,49,b,4w,,1i,f,1k,3,1d,4,2,2,1x,3,10,5,,8,1q,,c,2,1g,9,a,4,2,,2n,3,2,,,2,6,,4g,,3,8,l,2,1l,2,,,,,m,,e,7,3,5,5f,8,2,3,,,n,,29,,2,6,,,2,,,2,,2,6j,,2,4,6,2,,2,r,2,2d,8,2,,,2,2y,,,,2,6,,,2t,3,2,4,,5,77,9,,2,6t,,a,2,,,4,,40,4,2,2,4,,w,a,14,6,2,4,8,,9,6,2,3,1a,d,,2,ba,7,,6,,,2a,m,2,7,,2,,2,3e,6,3,,,2,,7,,,20,2,3,,,,9n,2,f0b,5,1n,7,t4,,1r,4,29,,f5k,2,43q,,,3,4,5,8,8,2,7,u,4,44,3,1iz,1j,4,1e,8,,e,,m,5,,f,11s,7,,h,2,7,,2,,5,79,7,c5,4,15s,7,31,7,240,5,gx7k,2o,3k,6o".split(",").map(e=>e?parseInt(e,36):1);for(let e=0,t=0;e>1;if(s=Mh[i])e=i+1;else return!0;if(e==t)return!1}}function Cl(s){return s>=127462&&s<=127487}const Al=8205;function rd(s,e,t=!0,i=!0){return(t?Ph:od)(s,e,i)}function Ph(s,e,t){if(e==s.length)return e;e&&Th(s.charCodeAt(e))&&Dh(s.charCodeAt(e-1))&&e--;let i=_n(s,e);for(e+=Ml(i);e=0&&Cl(_n(s,o));)r++,o-=2;if(r%2==0)break;e+=2}else break}return e}function od(s,e,t){for(;e>0;){let i=Ph(s,e-2,t);if(i=56320&&s<57344}function Dh(s){return s>=55296&&s<56320}function Ml(s){return s<65536?1:2}class Y{lineAt(e){if(e<0||e>this.length)throw new RangeError(`Invalid position ${e} in document of length ${this.length}`);return this.lineInner(e,!1,1,0)}line(e){if(e<1||e>this.lines)throw new RangeError(`Invalid line number ${e} in ${this.lines}-line document`);return this.lineInner(e,!0,1,0)}replace(e,t,i){[e,t]=xi(this,e,t);let n=[];return this.decompose(0,e,n,2),i.length&&i.decompose(0,i.length,n,3),this.decompose(t,this.length,n,1),tt.from(n,this.length-(t-e)+i.length)}append(e){return this.replace(this.length,this.length,e)}slice(e,t=this.length){[e,t]=xi(this,e,t);let i=[];return this.decompose(e,t,i,0),tt.from(i,t-e)}eq(e){if(e==this)return!0;if(e.length!=this.length||e.lines!=this.lines)return!1;let t=this.scanIdentical(e,1),i=this.length-this.scanIdentical(e,-1),n=new Wi(this),r=new Wi(e);for(let o=t,l=t;;){if(n.next(o),r.next(o),o=0,n.lineBreak!=r.lineBreak||n.done!=r.done||n.value!=r.value)return!1;if(l+=n.value.length,n.done||l>=i)return!0}}iter(e=1){return new Wi(this,e)}iterRange(e,t=this.length){return new Rh(this,e,t)}iterLines(e,t){let i;if(e==null)i=this.iter();else{t==null&&(t=this.lines+1);let n=this.line(e).from;i=this.iterRange(n,Math.max(n,t==this.lines+1?this.length:t<=1?0:this.line(t-1).to))}return new Bh(i)}toString(){return this.sliceString(0)}toJSON(){let e=[];return this.flatten(e),e}constructor(){}static of(e){if(e.length==0)throw new RangeError("A document must have at least one line");return e.length==1&&!e[0]?Y.empty:e.length<=32?new ne(e):tt.from(ne.split(e,[]))}}class ne extends Y{constructor(e,t=ld(e)){super(),this.text=e,this.length=t}get lines(){return this.text.length}get children(){return null}lineInner(e,t,i,n){for(let r=0;;r++){let o=this.text[r],l=n+o.length;if((t?i:l)>=e)return new ad(n,l,i,o);n=l+1,i++}}decompose(e,t,i,n){let r=e<=0&&t>=this.length?this:new ne(Pl(this.text,e,t),Math.min(t,this.length)-Math.max(0,e));if(n&1){let o=i.pop(),l=js(r.text,o.text.slice(),0,r.length);if(l.length<=32)i.push(new ne(l,o.length+r.length));else{let a=l.length>>1;i.push(new ne(l.slice(0,a)),new ne(l.slice(a)))}}else i.push(r)}replace(e,t,i){if(!(i instanceof ne))return super.replace(e,t,i);[e,t]=xi(this,e,t);let n=js(this.text,js(i.text,Pl(this.text,0,e)),t),r=this.length+i.length-(t-e);return n.length<=32?new ne(n,r):tt.from(ne.split(n,[]),r)}sliceString(e,t=this.length,i=` +`){[e,t]=xi(this,e,t);let n="";for(let r=0,o=0;r<=t&&oe&&o&&(n+=i),er&&(n+=l.slice(Math.max(0,e-r),t-r)),r=a+1}return n}flatten(e){for(let t of this.text)e.push(t)}scanIdentical(){return 0}static split(e,t){let i=[],n=-1;for(let r of e)i.push(r),n+=r.length+1,i.length==32&&(t.push(new ne(i,n)),i=[],n=-1);return n>-1&&t.push(new ne(i,n)),t}}class tt extends Y{constructor(e,t){super(),this.children=e,this.length=t,this.lines=0;for(let i of e)this.lines+=i.lines}lineInner(e,t,i,n){for(let r=0;;r++){let o=this.children[r],l=n+o.length,a=i+o.lines-1;if((t?a:l)>=e)return o.lineInner(e,t,i,n);n=l+1,i=a+1}}decompose(e,t,i,n){for(let r=0,o=0;o<=t&&r=o){let h=n&((o<=e?1:0)|(a>=t?2:0));o>=e&&a<=t&&!h?i.push(l):l.decompose(e-o,t-o,i,h)}o=a+1}}replace(e,t,i){if([e,t]=xi(this,e,t),i.lines=r&&t<=l){let a=o.replace(e-r,t-r,i),h=this.lines-o.lines+a.lines;if(a.lines>4&&a.lines>h>>6){let c=this.children.slice();return c[n]=a,new tt(c,this.length-(t-e)+i.length)}return super.replace(r,l,a)}r=l+1}return super.replace(e,t,i)}sliceString(e,t=this.length,i=` +`){[e,t]=xi(this,e,t);let n="";for(let r=0,o=0;re&&r&&(n+=i),eo&&(n+=l.sliceString(e-o,t-o,i)),o=a+1}return n}flatten(e){for(let t of this.children)t.flatten(e)}scanIdentical(e,t){if(!(e instanceof tt))return 0;let i=0,[n,r,o,l]=t>0?[0,0,this.children.length,e.children.length]:[this.children.length-1,e.children.length-1,-1,-1];for(;;n+=t,r+=t){if(n==o||r==l)return i;let a=this.children[n],h=e.children[r];if(a!=h)return i+a.scanIdentical(h,t);i+=a.length+1}}static from(e,t=e.reduce((i,n)=>i+n.length+1,-1)){let i=0;for(let d of e)i+=d.lines;if(i<32){let d=[];for(let p of e)p.flatten(d);return new ne(d,t)}let n=Math.max(32,i>>5),r=n<<1,o=n>>1,l=[],a=0,h=-1,c=[];function f(d){let p;if(d.lines>r&&d instanceof tt)for(let m of d.children)f(m);else d.lines>o&&(a>o||!a)?(u(),l.push(d)):d instanceof ne&&a&&(p=c[c.length-1])instanceof ne&&d.lines+p.lines<=32?(a+=d.lines,h+=d.length+1,c[c.length-1]=new ne(p.text.concat(d.text),p.length+1+d.length)):(a+d.lines>n&&u(),a+=d.lines,h+=d.length+1,c.push(d))}function u(){a!=0&&(l.push(c.length==1?c[0]:tt.from(c,h)),h=-1,a=c.length=0)}for(let d of e)f(d);return u(),l.length==1?l[0]:new tt(l,t)}}Y.empty=new ne([""],0);function ld(s){let e=-1;for(let t of s)e+=t.length+1;return e}function js(s,e,t=0,i=1e9){for(let n=0,r=0,o=!0;r=t&&(a>i&&(l=l.slice(0,i-n)),n0?1:(e instanceof ne?e.text.length:e.children.length)<<1]}nextInner(e,t){for(this.done=this.lineBreak=!1;;){let i=this.nodes.length-1,n=this.nodes[i],r=this.offsets[i],o=r>>1,l=n instanceof ne?n.text.length:n.children.length;if(o==(t>0?l:0)){if(i==0)return this.done=!0,this.value="",this;t>0&&this.offsets[i-1]++,this.nodes.pop(),this.offsets.pop()}else if((r&1)==(t>0?0:1)){if(this.offsets[i]+=t,e==0)return this.lineBreak=!0,this.value=` +`,this;e--}else if(n instanceof ne){let a=n.text[o+(t<0?-1:0)];if(this.offsets[i]+=t,a.length>Math.max(0,e))return this.value=e==0?a:t>0?a.slice(e):a.slice(0,a.length-e),this;e-=a.length}else{let a=n.children[o+(t<0?-1:0)];e>a.length?(e-=a.length,this.offsets[i]+=t):(t<0&&this.offsets[i]--,this.nodes.push(a),this.offsets.push(t>0?1:(a instanceof ne?a.text.length:a.children.length)<<1))}}}next(e=0){return e<0&&(this.nextInner(-e,-this.dir),e=this.value.length),this.nextInner(e,this.dir)}}class Rh{constructor(e,t,i){this.value="",this.done=!1,this.cursor=new Wi(e,t>i?-1:1),this.pos=t>i?e.length:0,this.from=Math.min(t,i),this.to=Math.max(t,i)}nextInner(e,t){if(t<0?this.pos<=this.from:this.pos>=this.to)return this.value="",this.done=!0,this;e+=Math.max(0,t<0?this.pos-this.to:this.from-this.pos);let i=t<0?this.pos-this.from:this.to-this.pos;e>i&&(e=i),i-=e;let{value:n}=this.cursor.next(e);return this.pos+=(n.length+e)*t,this.value=n.length<=i?n:t<0?n.slice(n.length-i):n.slice(0,i),this.done=!this.value,this}next(e=0){return e<0?e=Math.max(e,this.from-this.pos):e>0&&(e=Math.min(e,this.to-this.pos)),this.nextInner(e,this.cursor.dir)}get lineBreak(){return this.cursor.lineBreak&&this.value!=""}}class Bh{constructor(e){this.inner=e,this.afterBreak=!0,this.value="",this.done=!1}next(e=0){let{done:t,lineBreak:i,value:n}=this.inner.next(e);return t&&this.afterBreak?(this.value="",this.afterBreak=!1):t?(this.done=!0,this.value=""):i?this.afterBreak?this.value="":(this.afterBreak=!0,this.next()):(this.value=n,this.afterBreak=!1),this}get lineBreak(){return!1}}typeof Symbol<"u"&&(Y.prototype[Symbol.iterator]=function(){return this.iter()},Wi.prototype[Symbol.iterator]=Rh.prototype[Symbol.iterator]=Bh.prototype[Symbol.iterator]=function(){return this});class ad{constructor(e,t,i,n){this.from=e,this.to=t,this.number=i,this.text=n}get length(){return this.to-this.from}}function xi(s,e,t){return e=Math.max(0,Math.min(s.length,e)),[e,Math.max(e,Math.min(s.length,t))]}function fe(s,e,t=!0,i=!0){return rd(s,e,t,i)}function hd(s){return s>=56320&&s<57344}function cd(s){return s>=55296&&s<56320}function Ce(s,e){let t=s.charCodeAt(e);if(!cd(t)||e+1==s.length)return t;let i=s.charCodeAt(e+1);return hd(i)?(t-55296<<10)+(i-56320)+65536:t}function Ro(s){return s<=65535?String.fromCharCode(s):(s-=65536,String.fromCharCode((s>>10)+55296,(s&1023)+56320))}function it(s){return s<65536?1:2}const Rr=/\r\n?|\n/;var Se=(function(s){return s[s.Simple=0]="Simple",s[s.TrackDel=1]="TrackDel",s[s.TrackBefore=2]="TrackBefore",s[s.TrackAfter=3]="TrackAfter",s})(Se||(Se={}));class lt{constructor(e){this.sections=e}get length(){let e=0;for(let t=0;te)return r+(e-n);r+=l}else{if(i!=Se.Simple&&h>=e&&(i==Se.TrackDel&&ne||i==Se.TrackBefore&&ne))return null;if(h>e||h==e&&t<0&&!l)return e==n||t<0?r:r+a;r+=a}n=h}if(e>n)throw new RangeError(`Position ${e} is out of range for changeset of length ${n}`);return r}touchesRange(e,t=e){for(let i=0,n=0;i=0&&n<=t&&l>=e)return nt?"cover":!0;n=l}return!1}toString(){let e="";for(let t=0;t=0?":"+n:"")}return e}toJSON(){return this.sections}static fromJSON(e){if(!Array.isArray(e)||e.length%2||e.some(t=>typeof t!="number"))throw new RangeError("Invalid JSON representation of ChangeDesc");return new lt(e)}static create(e){return new lt(e)}}class ae extends lt{constructor(e,t){super(e),this.inserted=t}apply(e){if(this.length!=e.length)throw new RangeError("Applying change set to a document with the wrong length");return Br(this,(t,i,n,r,o)=>e=e.replace(n,n+(i-t),o),!1),e}mapDesc(e,t=!1){return Er(this,e,t,!0)}invert(e){let t=this.sections.slice(),i=[];for(let n=0,r=0;n=0){t[n]=l,t[n+1]=o;let a=n>>1;for(;i.length0&&Ot(i,t,r.text),r.forward(c),l+=c}let h=e[o++];for(;l>1].toJSON()))}return e}static of(e,t,i){let n=[],r=[],o=0,l=null;function a(c=!1){if(!c&&!n.length)return;ou||f<0||u>t)throw new RangeError(`Invalid change range ${f} to ${u} (in doc of length ${t})`);let p=d?typeof d=="string"?Y.of(d.split(i||Rr)):d:Y.empty,m=p.length;if(f==u&&m==0)return;fo&&xe(n,f-o,-1),xe(n,u-f,m),Ot(r,n,p),o=u}}return h(e),a(!l),l}static empty(e){return new ae(e?[e,-1]:[],[])}static fromJSON(e){if(!Array.isArray(e))throw new RangeError("Invalid JSON representation of ChangeSet");let t=[],i=[];for(let n=0;nl&&typeof o!="string"))throw new RangeError("Invalid JSON representation of ChangeSet");if(r.length==1)t.push(r[0],0);else{for(;i.length=0&&t<=0&&t==s[n+1]?s[n]+=e:n>=0&&e==0&&s[n]==0?s[n+1]+=t:i?(s[n]+=e,s[n+1]+=t):s.push(e,t)}function Ot(s,e,t){if(t.length==0)return;let i=e.length-2>>1;if(i>1])),!(t||o==s.sections.length||s.sections[o+1]<0);)l=s.sections[o++],a=s.sections[o++];e(n,h,r,c,f),n=h,r=c}}}function Er(s,e,t,i=!1){let n=[],r=i?[]:null,o=new Xi(s),l=new Xi(e);for(let a=-1;;){if(o.done&&l.len||l.done&&o.len)throw new Error("Mismatched change set lengths");if(o.ins==-1&&l.ins==-1){let h=Math.min(o.len,l.len);xe(n,h,-1),o.forward(h),l.forward(h)}else if(l.ins>=0&&(o.ins<0||a==o.i||o.off==0&&(l.len=0&&a=0){let h=0,c=o.len;for(;c;)if(l.ins==-1){let f=Math.min(c,l.len);h+=f,c-=f,l.forward(f)}else if(l.ins==0&&l.lena||o.ins>=0&&o.len>a)&&(l||i.length>h),r.forward2(a),o.forward(a)}}}}class Xi{constructor(e){this.set=e,this.i=0,this.next()}next(){let{sections:e}=this.set;this.i>1;return t>=e.length?Y.empty:e[t]}textBit(e){let{inserted:t}=this.set,i=this.i-2>>1;return i>=t.length&&!e?Y.empty:t[i].slice(this.off,e==null?void 0:this.off+e)}forward(e){e==this.len?this.next():(this.len-=e,this.off+=e)}forward2(e){this.ins==-1?this.forward(e):e==this.ins?this.next():(this.ins-=e,this.off+=e)}}class $t{constructor(e,t,i){this.from=e,this.to=t,this.flags=i}get anchor(){return this.flags&32?this.to:this.from}get head(){return this.flags&32?this.from:this.to}get empty(){return this.from==this.to}get assoc(){return this.flags&8?-1:this.flags&16?1:0}get bidiLevel(){let e=this.flags&7;return e==7?null:e}get goalColumn(){let e=this.flags>>6;return e==16777215?void 0:e}map(e,t=-1){let i,n;return this.empty?i=n=e.mapPos(this.from,t):(i=e.mapPos(this.from,1),n=e.mapPos(this.to,-1)),i==this.from&&n==this.to?this:new $t(i,n,this.flags)}extend(e,t=e,i=0){if(e<=this.anchor&&t>=this.anchor)return v.range(e,t,void 0,void 0,i);let n=Math.abs(e-this.anchor)>Math.abs(t-this.anchor)?e:t;return v.range(this.anchor,n,void 0,void 0,i)}eq(e,t=!1){return this.anchor==e.anchor&&this.head==e.head&&this.goalColumn==e.goalColumn&&(!t||!this.empty||this.assoc==e.assoc)}toJSON(){return{anchor:this.anchor,head:this.head}}static fromJSON(e){if(!e||typeof e.anchor!="number"||typeof e.head!="number")throw new RangeError("Invalid JSON representation for SelectionRange");return v.range(e.anchor,e.head)}static create(e,t,i){return new $t(e,t,i)}}class v{constructor(e,t){this.ranges=e,this.mainIndex=t}map(e,t=-1){return e.empty?this:v.create(this.ranges.map(i=>i.map(e,t)),this.mainIndex)}eq(e,t=!1){if(this.ranges.length!=e.ranges.length||this.mainIndex!=e.mainIndex)return!1;for(let i=0;ie.toJSON()),main:this.mainIndex}}static fromJSON(e){if(!e||!Array.isArray(e.ranges)||typeof e.main!="number"||e.main>=e.ranges.length)throw new RangeError("Invalid JSON representation for EditorSelection");return new v(e.ranges.map(t=>$t.fromJSON(t)),e.main)}static single(e,t=e){return new v([v.range(e,t)],0)}static create(e,t=0){if(e.length==0)throw new RangeError("A selection needs at least one range");for(let i=0,n=0;nn.from-r.from),t=e.indexOf(i);for(let n=1;nr.head?v.range(a,l):v.range(l,a))}}return new v(e,t)}}function Lh(s,e){for(let t of s.ranges)if(t.to>e)throw new RangeError("Selection points outside of document")}let Bo=0;class I{constructor(e,t,i,n,r){this.combine=e,this.compareInput=t,this.compare=i,this.isStatic=n,this.id=Bo++,this.default=e([]),this.extensions=typeof r=="function"?r(this):r}get reader(){return this}static define(e={}){return new I(e.combine||(t=>t),e.compareInput||((t,i)=>t===i),e.compare||(e.combine?(t,i)=>t===i:Eo),!!e.static,e.enables)}of(e){return new qs([],this,0,e)}compute(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new qs(e,this,1,t)}computeN(e,t){if(this.isStatic)throw new Error("Can't compute a static facet");return new qs(e,this,2,t)}from(e,t){return t||(t=i=>i),this.compute([e],i=>t(i.field(e)))}}function Eo(s,e){return s==e||s.length==e.length&&s.every((t,i)=>t===e[i])}class qs{constructor(e,t,i,n){this.dependencies=e,this.facet=t,this.type=i,this.value=n,this.id=Bo++}dynamicSlot(e){var t;let i=this.value,n=this.facet.compareInput,r=this.id,o=e[r]>>1,l=this.type==2,a=!1,h=!1,c=[];for(let f of this.dependencies)f=="doc"?a=!0:f=="selection"?h=!0:(((t=e[f.id])!==null&&t!==void 0?t:1)&1)==0&&c.push(e[f.id]);return{create(f){return f.values[o]=i(f),1},update(f,u){if(a&&u.docChanged||h&&(u.docChanged||u.selection)||Lr(f,c)){let d=i(f);if(l?!Tl(d,f.values[o],n):!n(d,f.values[o]))return f.values[o]=d,1}return 0},reconfigure:(f,u)=>{let d,p=u.config.address[r];if(p!=null){let m=tn(u,p);if(this.dependencies.every(g=>g instanceof I?u.facet(g)===f.facet(g):g instanceof ye?u.field(g,!1)==f.field(g,!1):!0)||(l?Tl(d=i(f),m,n):n(d=i(f),m)))return f.values[o]=m,0}else d=i(f);return f.values[o]=d,1}}}}function Tl(s,e,t){if(s.length!=e.length)return!1;for(let i=0;is[a.id]),n=t.map(a=>a.type),r=i.filter(a=>!(a&1)),o=s[e.id]>>1;function l(a){let h=[];for(let c=0;ci===n),e);return e.provide&&(t.provides=e.provide(t)),t}create(e){let t=e.facet(ks).find(i=>i.field==this);return(t?.create||this.createF)(e)}slot(e){let t=e[this.id]>>1;return{create:i=>(i.values[t]=this.create(i),1),update:(i,n)=>{let r=i.values[t],o=this.updateF(r,n);return this.compareF(r,o)?0:(i.values[t]=o,1)},reconfigure:(i,n)=>{let r=i.facet(ks),o=n.facet(ks),l;return(l=r.find(a=>a.field==this))&&l!=o.find(a=>a.field==this)?(i.values[t]=l.create(i),1):n.config.address[this.id]!=null?(i.values[t]=n.field(this),0):(i.values[t]=this.create(i),1)}}}init(e){return[this,ks.of({field:this,create:e})]}get extension(){return this}}const Ht={lowest:4,low:3,default:2,high:1,highest:0};function Ti(s){return e=>new Nh(e,s)}const ei={highest:Ti(Ht.highest),high:Ti(Ht.high),default:Ti(Ht.default),low:Ti(Ht.low),lowest:Ti(Ht.lowest)};class Nh{constructor(e,t){this.inner=e,this.prec=t}}class Dn{of(e){return new Nr(this,e)}reconfigure(e){return Dn.reconfigure.of({compartment:this,extension:e})}get(e){return e.config.compartments.get(this)}}class Nr{constructor(e,t){this.compartment=e,this.inner=t}}class en{constructor(e,t,i,n,r,o){for(this.base=e,this.compartments=t,this.dynamicSlots=i,this.address=n,this.staticValues=r,this.facets=o,this.statusTemplate=[];this.statusTemplate.length>1]}static resolve(e,t,i){let n=[],r=Object.create(null),o=new Map;for(let u of ud(e,t,o))u instanceof ye?n.push(u):(r[u.facet.id]||(r[u.facet.id]=[])).push(u);let l=Object.create(null),a=[],h=[];for(let u of n)l[u.id]=h.length<<1,h.push(d=>u.slot(d));let c=i?.config.facets;for(let u in r){let d=r[u],p=d[0].facet,m=c&&c[u]||[];if(d.every(g=>g.type==0))if(l[p.id]=a.length<<1|1,Eo(m,d))a.push(i.facet(p));else{let g=p.combine(d.map(x=>x.value));a.push(i&&p.compare(g,i.facet(p))?i.facet(p):g)}else{for(let g of d)g.type==0?(l[g.id]=a.length<<1|1,a.push(g.value)):(l[g.id]=h.length<<1,h.push(x=>g.dynamicSlot(x)));l[p.id]=h.length<<1,h.push(g=>fd(g,p,d))}}let f=h.map(u=>u(l));return new en(e,o,f,l,a,r)}}function ud(s,e,t){let i=[[],[],[],[],[]],n=new Map;function r(o,l){let a=n.get(o);if(a!=null){if(a<=l)return;let h=i[a].indexOf(o);h>-1&&i[a].splice(h,1),o instanceof Nr&&t.delete(o.compartment)}if(n.set(o,l),Array.isArray(o))for(let h of o)r(h,l);else if(o instanceof Nr){if(t.has(o.compartment))throw new RangeError("Duplicate use of compartment in extensions");let h=e.get(o.compartment)||o.inner;t.set(o.compartment,h),r(h,l)}else if(o instanceof Nh)r(o.inner,o.prec);else if(o instanceof ye)i[l].push(o),o.provides&&r(o.provides,l);else if(o instanceof qs)i[l].push(o),o.facet.extensions&&r(o.facet.extensions,Ht.default);else{let h=o.extension;if(!h)throw new Error(`Unrecognized extension value in extension set (${o}). This sometimes happens because multiple instances of @codemirror/state are loaded, breaking instanceof checks.`);r(h,l)}}return r(s,Ht.default),i.reduce((o,l)=>o.concat(l))}function Fi(s,e){if(e&1)return 2;let t=e>>1,i=s.status[t];if(i==4)throw new Error("Cyclic dependency between fields and/or facets");if(i&2)return i;s.status[t]=4;let n=s.computeSlot(s,s.config.dynamicSlots[t]);return s.status[t]=2|n}function tn(s,e){return e&1?s.config.staticValues[e>>1]:s.values[e>>1]}const Ih=I.define(),Ir=I.define({combine:s=>s.some(e=>e),static:!0}),Wh=I.define({combine:s=>s.length?s[0]:void 0,static:!0}),Fh=I.define(),Vh=I.define(),Hh=I.define(),zh=I.define({combine:s=>s.length?s[0]:!1});class at{constructor(e,t){this.type=e,this.value=t}static define(){return new dd}}class dd{of(e){return new at(this,e)}}class pd{constructor(e){this.map=e}of(e){return new $(this,e)}}class ${constructor(e,t){this.type=e,this.value=t}map(e){let t=this.type.map(this.value,e);return t===void 0?void 0:t==this.value?this:new $(this.type,t)}is(e){return this.type==e}static define(e={}){return new pd(e.map||(t=>t))}static mapEffects(e,t){if(!e.length)return e;let i=[];for(let n of e){let r=n.map(t);r&&i.push(r)}return i}}$.reconfigure=$.define();$.appendConfig=$.define();class he{constructor(e,t,i,n,r,o){this.startState=e,this.changes=t,this.selection=i,this.effects=n,this.annotations=r,this.scrollIntoView=o,this._doc=null,this._state=null,i&&Lh(i,t.newLength),r.some(l=>l.type==he.time)||(this.annotations=r.concat(he.time.of(Date.now())))}static create(e,t,i,n,r,o){return new he(e,t,i,n,r,o)}get newDoc(){return this._doc||(this._doc=this.changes.apply(this.startState.doc))}get newSelection(){return this.selection||this.startState.selection.map(this.changes)}get state(){return this._state||this.startState.applyTransaction(this),this._state}annotation(e){for(let t of this.annotations)if(t.type==e)return t.value}get docChanged(){return!this.changes.empty}get reconfigured(){return this.startState.config!=this.state.config}isUserEvent(e){let t=this.annotation(he.userEvent);return!!(t&&(t==e||t.length>e.length&&t.slice(0,e.length)==e&&t[e.length]=="."))}}he.time=at.define();he.userEvent=at.define();he.addToHistory=at.define();he.remote=at.define();function md(s,e){let t=[];for(let i=0,n=0;;){let r,o;if(i=s[i]))r=s[i++],o=s[i++];else if(n=0;n--){let r=i[n](s);r instanceof he?s=r:Array.isArray(r)&&r.length==1&&r[0]instanceof he?s=r[0]:s=$h(e,ci(r),!1)}return s}function xd(s){let e=s.startState,t=e.facet(Hh),i=s;for(let n=t.length-1;n>=0;n--){let r=t[n](s);r&&Object.keys(r).length&&(i=Qh(i,Wr(e,r,s.changes.newLength),!0))}return i==s?s:he.create(e,s.changes,s.selection,i.effects,i.annotations,i.scrollIntoView)}const bd=[];function ci(s){return s==null?bd:Array.isArray(s)?s:[s]}var ee=(function(s){return s[s.Word=0]="Word",s[s.Space=1]="Space",s[s.Other=2]="Other",s})(ee||(ee={}));const yd=/[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/;let Fr;try{Fr=new RegExp("[\\p{Alphabetic}\\p{Number}_]","u")}catch{}function kd(s){if(Fr)return Fr.test(s);for(let e=0;e"€"&&(t.toUpperCase()!=t.toLowerCase()||yd.test(t)))return!0}return!1}function wd(s){return e=>{if(!/\S/.test(e))return ee.Space;if(kd(e))return ee.Word;for(let t=0;t-1)return ee.Word;return ee.Other}}class U{constructor(e,t,i,n,r,o){this.config=e,this.doc=t,this.selection=i,this.values=n,this.status=e.statusTemplate.slice(),this.computeSlot=r,o&&(o._state=this);for(let l=0;ln.set(h,a)),t=null),n.set(l.value.compartment,l.value.extension)):l.is($.reconfigure)?(t=null,i=l.value):l.is($.appendConfig)&&(t=null,i=ci(i).concat(l.value));let r;t?r=e.startState.values.slice():(t=en.resolve(i,n,this),r=new U(t,this.doc,this.selection,t.dynamicSlots.map(()=>null),(a,h)=>h.reconfigure(a,this),null).values);let o=e.startState.facet(Ir)?e.newSelection:e.newSelection.asSingle();new U(t,e.newDoc,o,r,(l,a)=>a.update(l,e),e)}replaceSelection(e){return typeof e=="string"&&(e=this.toText(e)),this.changeByRange(t=>({changes:{from:t.from,to:t.to,insert:e},range:v.cursor(t.from+e.length)}))}changeByRange(e){let t=this.selection,i=e(t.ranges[0]),n=this.changes(i.changes),r=[i.range],o=ci(i.effects);for(let l=1;lo.spec.fromJSON(l,a)))}}return U.create({doc:e.doc,selection:v.fromJSON(e.selection),extensions:t.extensions?n.concat([t.extensions]):n})}static create(e={}){let t=en.resolve(e.extensions||[],new Map),i=e.doc instanceof Y?e.doc:Y.of((e.doc||"").split(t.staticFacet(U.lineSeparator)||Rr)),n=e.selection?e.selection instanceof v?e.selection:v.single(e.selection.anchor,e.selection.head):v.single(0);return Lh(n,i.length),t.staticFacet(Ir)||(n=n.asSingle()),new U(t,i,n,t.dynamicSlots.map(()=>null),(r,o)=>o.create(r),null)}get tabSize(){return this.facet(U.tabSize)}get lineBreak(){return this.facet(U.lineSeparator)||` +`}get readOnly(){return this.facet(zh)}phrase(e,...t){for(let i of this.facet(U.phrases))if(Object.prototype.hasOwnProperty.call(i,e)){e=i[e];break}return t.length&&(e=e.replace(/\$(\$|\d*)/g,(i,n)=>{if(n=="$")return"$";let r=+(n||1);return!r||r>t.length?i:t[r-1]})),e}languageDataAt(e,t,i=-1){let n=[];for(let r of this.facet(Ih))for(let o of r(this,t,i))Object.prototype.hasOwnProperty.call(o,e)&&n.push(o[e]);return n}charCategorizer(e){let t=this.languageDataAt("wordChars",e);return wd(t.length?t[0]:"")}wordAt(e){let{text:t,from:i,length:n}=this.doc.lineAt(e),r=this.charCategorizer(e),o=e-i,l=e-i;for(;o>0;){let a=fe(t,o,!1);if(r(t.slice(a,o))!=ee.Word)break;o=a}for(;ls.length?s[0]:4});U.lineSeparator=Wh;U.readOnly=zh;U.phrases=I.define({compare(s,e){let t=Object.keys(s),i=Object.keys(e);return t.length==i.length&&t.every(n=>s[n]==e[n])}});U.languageData=Ih;U.changeFilter=Fh;U.transactionFilter=Vh;U.transactionExtender=Hh;Dn.reconfigure=$.define();function ht(s,e,t={}){let i={};for(let n of s)for(let r of Object.keys(n)){let o=n[r],l=i[r];if(l===void 0)i[r]=o;else if(!(l===o||o===void 0))if(Object.hasOwnProperty.call(t,r))i[r]=t[r](l,o);else throw new Error("Config merge conflict for field "+r)}for(let n in e)i[n]===void 0&&(i[n]=e[n]);return i}class Mt{eq(e){return this==e}range(e,t=e){return Vr.create(e,t,this)}}Mt.prototype.startSide=Mt.prototype.endSide=0;Mt.prototype.point=!1;Mt.prototype.mapMode=Se.TrackDel;function Lo(s,e){return s==e||s.constructor==e.constructor&&s.eq(e)}let Vr=class jh{constructor(e,t,i){this.from=e,this.to=t,this.value=i}static create(e,t,i){return new jh(e,t,i)}};function Hr(s,e){return s.from-e.from||s.value.startSide-e.value.startSide}class No{constructor(e,t,i,n){this.from=e,this.to=t,this.value=i,this.maxPoint=n}get length(){return this.to[this.to.length-1]}findIndex(e,t,i,n=0){let r=i?this.to:this.from;for(let o=n,l=r.length;;){if(o==l)return o;let a=o+l>>1,h=r[a]-e||(i?this.value[a].endSide:this.value[a].startSide)-t;if(a==o)return h>=0?o:l;h>=0?l=a:o=a+1}}between(e,t,i,n){for(let r=this.findIndex(t,-1e9,!0),o=this.findIndex(i,1e9,!1,r);rd||u==d&&h.startSide>0&&h.endSide<=0)continue;(d-u||h.endSide-h.startSide)<0||(o<0&&(o=u),h.point&&(l=Math.max(l,d-u)),i.push(h),n.push(u-o),r.push(d-o))}return{mapped:i.length?new No(n,r,i,l):null,pos:o}}}class X{constructor(e,t,i,n){this.chunkPos=e,this.chunk=t,this.nextLayer=i,this.maxPoint=n}static create(e,t,i,n){return new X(e,t,i,n)}get length(){let e=this.chunk.length-1;return e<0?0:Math.max(this.chunkEnd(e),this.nextLayer.length)}get size(){if(this.isEmpty)return 0;let e=this.nextLayer.size;for(let t of this.chunk)e+=t.value.length;return e}chunkEnd(e){return this.chunkPos[e]+this.chunk[e].length}update(e){let{add:t=[],sort:i=!1,filterFrom:n=0,filterTo:r=this.length}=e,o=e.filter;if(t.length==0&&!o)return this;if(i&&(t=t.slice().sort(Hr)),this.isEmpty)return t.length?X.of(t):this;let l=new qh(this,null,-1).goto(0),a=0,h=[],c=new mt;for(;l.value||a=0){let f=t[a++];c.addInner(f.from,f.to,f.value)||h.push(f)}else l.rangeIndex==1&&l.chunkIndexthis.chunkEnd(l.chunkIndex)||rl.to||r=r&&e<=r+o.length&&o.between(r,e-r,t-r,i)===!1)return}this.nextLayer.between(e,t,i)}}iter(e=0){return Ui.from([this]).goto(e)}get isEmpty(){return this.nextLayer==this}static iter(e,t=0){return Ui.from(e).goto(t)}static compare(e,t,i,n,r=-1){let o=e.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=r),l=t.filter(f=>f.maxPoint>0||!f.isEmpty&&f.maxPoint>=r),a=Dl(o,l,i),h=new Di(o,a,r),c=new Di(l,a,r);i.iterGaps((f,u,d)=>Rl(h,f,c,u,d,n)),i.empty&&i.length==0&&Rl(h,0,c,0,0,n)}static eq(e,t,i=0,n){n==null&&(n=999999999);let r=e.filter(c=>!c.isEmpty&&t.indexOf(c)<0),o=t.filter(c=>!c.isEmpty&&e.indexOf(c)<0);if(r.length!=o.length)return!1;if(!r.length)return!0;let l=Dl(r,o),a=new Di(r,l,0).goto(i),h=new Di(o,l,0).goto(i);for(;;){if(a.to!=h.to||!zr(a.active,h.active)||a.point&&(!h.point||!Lo(a.point,h.point)))return!1;if(a.to>n)return!0;a.next(),h.next()}}static spans(e,t,i,n,r=-1){let o=new Di(e,null,r).goto(t),l=t,a=o.openStart;for(;;){let h=Math.min(o.to,i);if(o.point){let c=o.activeForPoint(o.to),f=o.pointFroml&&(n.span(l,h,o.active,a),a=o.openEnd(h));if(o.to>i)return a+(o.point&&o.to>i?1:0);l=o.to,o.next()}}static of(e,t=!1){let i=new mt;for(let n of e instanceof Vr?[e]:t?vd(e):e)i.add(n.from,n.to,n.value);return i.finish()}static join(e){if(!e.length)return X.empty;let t=e[e.length-1];for(let i=e.length-2;i>=0;i--)for(let n=e[i];n!=X.empty;n=n.nextLayer)t=new X(n.chunkPos,n.chunk,t,Math.max(n.maxPoint,t.maxPoint));return t}}X.empty=new X([],[],null,-1);function vd(s){if(s.length>1)for(let e=s[0],t=1;t0)return s.slice().sort(Hr);e=i}return s}X.empty.nextLayer=X.empty;class mt{finishChunk(e){this.chunks.push(new No(this.from,this.to,this.value,this.maxPoint)),this.chunkPos.push(this.chunkStart),this.chunkStart=-1,this.setMaxPoint=Math.max(this.setMaxPoint,this.maxPoint),this.maxPoint=-1,e&&(this.from=[],this.to=[],this.value=[])}constructor(){this.chunks=[],this.chunkPos=[],this.chunkStart=-1,this.last=null,this.lastFrom=-1e9,this.lastTo=-1e9,this.from=[],this.to=[],this.value=[],this.maxPoint=-1,this.setMaxPoint=-1,this.nextLayer=null}add(e,t,i){this.addInner(e,t,i)||(this.nextLayer||(this.nextLayer=new mt)).add(e,t,i)}addInner(e,t,i){let n=e-this.lastTo||i.startSide-this.last.endSide;if(n<=0&&(e-this.lastFrom||i.startSide-this.last.startSide)<0)throw new Error("Ranges must be added sorted by `from` position and `startSide`");return n<0?!1:(this.from.length==250&&this.finishChunk(!0),this.chunkStart<0&&(this.chunkStart=e),this.from.push(e-this.chunkStart),this.to.push(t-this.chunkStart),this.last=i,this.lastFrom=e,this.lastTo=t,this.value.push(i),i.point&&(this.maxPoint=Math.max(this.maxPoint,t-e)),!0)}addChunk(e,t){if((e-this.lastTo||t.value[0].startSide-this.last.endSide)<0)return!1;this.from.length&&this.finishChunk(!0),this.setMaxPoint=Math.max(this.setMaxPoint,t.maxPoint),this.chunks.push(t),this.chunkPos.push(e);let i=t.value.length-1;return this.last=t.value[i],this.lastFrom=t.from[i]+e,this.lastTo=t.to[i]+e,!0}finish(){return this.finishInner(X.empty)}finishInner(e){if(this.from.length&&this.finishChunk(!1),this.chunks.length==0)return e;let t=X.create(this.chunkPos,this.chunks,this.nextLayer?this.nextLayer.finishInner(e):e,this.setMaxPoint);return this.from=null,t}}function Dl(s,e,t){let i=new Map;for(let r of s)for(let o=0;o=this.minPoint)break}}setRangeIndex(e){if(e==this.layer.chunk[this.chunkIndex].value.length){if(this.chunkIndex++,this.skip)for(;this.chunkIndex=i&&n.push(new qh(o,t,i,r));return n.length==1?n[0]:new Ui(n)}get startSide(){return this.value?this.value.startSide:0}goto(e,t=-1e9){for(let i of this.heap)i.goto(e,t);for(let i=this.heap.length>>1;i>=0;i--)Kn(this.heap,i);return this.next(),this}forward(e,t){for(let i of this.heap)i.forward(e,t);for(let i=this.heap.length>>1;i>=0;i--)Kn(this.heap,i);(this.to-e||this.value.endSide-t)<0&&this.next()}next(){if(this.heap.length==0)this.from=this.to=1e9,this.value=null,this.rank=-1;else{let e=this.heap[0];this.from=e.from,this.to=e.to,this.value=e.value,this.rank=e.rank,e.value&&e.next(),Kn(this.heap,0)}}}function Kn(s,e){for(let t=s[e];;){let i=(e<<1)+1;if(i>=s.length)break;let n=s[i];if(i+1=0&&(n=s[i+1],i++),t.compare(n)<0)break;s[i]=t,s[e]=n,e=i}}class Di{constructor(e,t,i){this.minPoint=i,this.active=[],this.activeTo=[],this.activeRank=[],this.minActive=-1,this.point=null,this.pointFrom=0,this.pointRank=0,this.to=-1e9,this.endSide=0,this.openStart=-1,this.cursor=Ui.from(e,t,i)}goto(e,t=-1e9){return this.cursor.goto(e,t),this.active.length=this.activeTo.length=this.activeRank.length=0,this.minActive=-1,this.to=e,this.endSide=t,this.openStart=-1,this.next(),this}forward(e,t){for(;this.minActive>-1&&(this.activeTo[this.minActive]-e||this.active[this.minActive].endSide-t)<0;)this.removeActive(this.minActive);this.cursor.forward(e,t)}removeActive(e){ws(this.active,e),ws(this.activeTo,e),ws(this.activeRank,e),this.minActive=Bl(this.active,this.activeTo)}addActive(e){let t=0,{value:i,to:n,rank:r}=this.cursor;for(;t0;)t++;vs(this.active,t,i),vs(this.activeTo,t,n),vs(this.activeRank,t,r),e&&vs(e,t,this.cursor.from),this.minActive=Bl(this.active,this.activeTo)}next(){let e=this.to,t=this.point;this.point=null;let i=this.openStart<0?[]:null;for(;;){let n=this.minActive;if(n>-1&&(this.activeTo[n]-this.cursor.from||this.active[n].endSide-this.cursor.startSide)<0){if(this.activeTo[n]>e){this.to=this.activeTo[n],this.endSide=this.active[n].endSide;break}this.removeActive(n),i&&ws(i,n)}else if(this.cursor.value)if(this.cursor.from>e){this.to=this.cursor.from,this.endSide=this.cursor.startSide;break}else{let r=this.cursor.value;if(!r.point)this.addActive(i),this.cursor.next();else if(t&&this.cursor.to==this.to&&this.cursor.from=0&&i[n]=0&&!(this.activeRank[i]e||this.activeTo[i]==e&&this.active[i].endSide>=this.point.endSide)&&t.push(this.active[i]);return t.reverse()}openEnd(e){let t=0;for(let i=this.activeTo.length-1;i>=0&&this.activeTo[i]>e;i--)t++;return t}}function Rl(s,e,t,i,n,r){s.goto(e),t.goto(i);let o=i+n,l=i,a=i-e,h=!!r.boundChange;for(let c=!1;;){let f=s.to+a-t.to,u=f||s.endSide-t.endSide,d=u<0?s.to+a:t.to,p=Math.min(d,o);if(s.point||t.point?(s.point&&t.point&&Lo(s.point,t.point)&&zr(s.activeForPoint(s.to),t.activeForPoint(t.to))||r.comparePoint(l,p,s.point,t.point),c=!1):(c&&r.boundChange(l),p>l&&!zr(s.active,t.active)&&r.compareRange(l,p,s.active,t.active),h&&po)break;l=d,u<=0&&s.next(),u>=0&&t.next()}}function zr(s,e){if(s.length!=e.length)return!1;for(let t=0;t=e;i--)s[i+1]=s[i];s[e]=t}function Bl(s,e){let t=-1,i=1e9;for(let n=0;n=e)return n;if(n==s.length)break;r+=s.charCodeAt(n)==9?t-r%t:1,n=fe(s,n)}return i===!0?-1:s.length}const $r="ͼ",El=typeof Symbol>"u"?"__"+$r:Symbol.for($r),jr=typeof Symbol>"u"?"__styleSet"+Math.floor(Math.random()*1e8):Symbol("styleSet"),Ll=typeof globalThis<"u"?globalThis:typeof window<"u"?window:{};class Pt{constructor(e,t){this.rules=[];let{finish:i}=t||{};function n(o){return/^@/.test(o)?[o]:o.split(/,\s*/)}function r(o,l,a,h){let c=[],f=/^@(\w+)\b/.exec(o[0]),u=f&&f[1]=="keyframes";if(f&&l==null)return a.push(o[0]+";");for(let d in l){let p=l[d];if(/&/.test(d))r(d.split(/,\s*/).map(m=>o.map(g=>m.replace(/&/,g))).reduce((m,g)=>m.concat(g)),p,a);else if(p&&typeof p=="object"){if(!f)throw new RangeError("The value of a property ("+d+") should be a primitive value.");r(n(d),p,c,u)}else p!=null&&c.push(d.replace(/_.*/,"").replace(/[A-Z]/g,m=>"-"+m.toLowerCase())+": "+p+";")}(c.length||u)&&a.push((i&&!f&&!h?o.map(i):o).join(", ")+" {"+c.join(" ")+"}")}for(let o in e)r(n(o),e[o],this.rules)}getRules(){return this.rules.join(` +`)}static newName(){let e=Ll[El]||1;return Ll[El]=e+1,$r+e.toString(36)}static mount(e,t,i){let n=e[jr],r=i&&i.nonce;n?r&&n.setNonce(r):n=new Sd(e,r),n.mount(Array.isArray(t)?t:[t],e)}}let Nl=new Map;class Sd{constructor(e,t){let i=e.ownerDocument||e,n=i.defaultView;if(!e.head&&e.adoptedStyleSheets&&n.CSSStyleSheet){let r=Nl.get(i);if(r)return e[jr]=r;this.sheet=new n.CSSStyleSheet,Nl.set(i,this)}else this.styleTag=i.createElement("style"),t&&this.styleTag.setAttribute("nonce",t);this.modules=[],e[jr]=this}mount(e,t){let i=this.sheet,n=0,r=0;for(let o=0;o-1&&(this.modules.splice(a,1),r--,a=-1),a==-1){if(this.modules.splice(r++,0,l),i)for(let h=0;h",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},Od=typeof navigator<"u"&&/Mac/.test(navigator.platform),Cd=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var me=0;me<10;me++)Tt[48+me]=Tt[96+me]=String(me);for(var me=1;me<=24;me++)Tt[me+111]="F"+me;for(var me=65;me<=90;me++)Tt[me]=String.fromCharCode(me+32),Yi[me]=String.fromCharCode(me);for(var Gn in Tt)Yi.hasOwnProperty(Gn)||(Yi[Gn]=Tt[Gn]);function Ad(s){var e=Od&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||Cd&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",t=!e&&s.key||(s.shiftKey?Yi:Tt)[s.keyCode]||s.key||"Unidentified";return t=="Esc"&&(t="Escape"),t=="Del"&&(t="Delete"),t=="Left"&&(t="ArrowLeft"),t=="Up"&&(t="ArrowUp"),t=="Right"&&(t="ArrowRight"),t=="Down"&&(t="ArrowDown"),t}function _(){var s=arguments[0];typeof s=="string"&&(s=document.createElement(s));var e=1,t=arguments[1];if(t&&typeof t=="object"&&t.nodeType==null&&!Array.isArray(t)){for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var n=t[i];typeof n=="string"?s.setAttribute(i,n):n!=null&&(s[i]=n)}e++}for(;e2);var W={mac:Fl||/Mac/.test(ve.platform),windows:/Win/.test(ve.platform),linux:/Linux|X11/.test(ve.platform),ie:Rn,ie_version:Uh?qr.documentMode||6:Ur?+Ur[1]:Xr?+Xr[1]:0,gecko:Il,gecko_version:Il?+(/Firefox\/(\d+)/.exec(ve.userAgent)||[0,0])[1]:0,chrome:!!Jn,chrome_version:Jn?+Jn[1]:0,ios:Fl,android:/Android\b/.test(ve.userAgent),webkit:Wl,webkit_version:Wl?+(/\bAppleWebKit\/(\d+)/.exec(ve.userAgent)||[0,0])[1]:0,safari:Yr,safari_version:Yr?+(/\bVersion\/(\d+(\.\d+)?)/.exec(ve.userAgent)||[0,0])[1]:0,tabSize:qr.documentElement.style.tabSize!=null?"tab-size":"-moz-tab-size"};function Io(s,e){for(let t in s)t=="class"&&e.class?e.class+=" "+s.class:t=="style"&&e.style?e.style+=";"+s.style:e[t]=s[t];return e}const sn=Object.create(null);function Wo(s,e,t){if(s==e)return!0;s||(s=sn),e||(e=sn);let i=Object.keys(s),n=Object.keys(e);if(i.length-0!=n.length-0)return!1;for(let r of i)if(r!=t&&(n.indexOf(r)==-1||s[r]!==e[r]))return!1;return!0}function Md(s,e){for(let t=s.attributes.length-1;t>=0;t--){let i=s.attributes[t].name;e[i]==null&&s.removeAttribute(i)}for(let t in e){let i=e[t];t=="style"?s.style.cssText=i:s.getAttribute(t)!=i&&s.setAttribute(t,i)}}function Vl(s,e,t){let i=!1;if(e)for(let n in e)t&&n in t||(i=!0,n=="style"?s.style.cssText="":s.removeAttribute(n));if(t)for(let n in t)e&&e[n]==t[n]||(i=!0,n=="style"?s.style.cssText=t[n]:s.setAttribute(n,t[n]));return i}function Pd(s){let e=Object.create(null);for(let t=0;t0?3e8:-4e8:t>0?1e8:-1e8,new Kt(e,t,t,i,e.widget||null,!1)}static replace(e){let t=!!e.block,i,n;if(e.isBlockGap)i=-5e8,n=4e8;else{let{start:r,end:o}=Yh(e,t);i=(r?t?-3e8:-1:5e8)-1,n=(o?t?2e8:1:-6e8)+1}return new Kt(e,i,n,t,e.widget||null,!0)}static line(e){return new cs(e)}static set(e,t=!1){return X.of(e,t)}hasHeight(){return this.widget?this.widget.estimatedHeight>-1:!1}}z.none=X.empty;class hs extends z{constructor(e){let{start:t,end:i}=Yh(e);super(t?-1:5e8,i?1:-6e8,null,e),this.tagName=e.tagName||"span",this.attrs=e.class&&e.attributes?Io(e.attributes,{class:e.class}):e.class?{class:e.class}:e.attributes||sn}eq(e){return this==e||e instanceof hs&&this.tagName==e.tagName&&Wo(this.attrs,e.attrs)}range(e,t=e){if(e>=t)throw new RangeError("Mark decorations may not be empty");return super.range(e,t)}}hs.prototype.point=!1;class cs extends z{constructor(e){super(-2e8,-2e8,null,e)}eq(e){return e instanceof cs&&this.spec.class==e.spec.class&&Wo(this.spec.attributes,e.spec.attributes)}range(e,t=e){if(t!=e)throw new RangeError("Line decoration ranges must be zero-length");return super.range(e,t)}}cs.prototype.mapMode=Se.TrackBefore;cs.prototype.point=!0;class Kt extends z{constructor(e,t,i,n,r,o){super(t,i,r,e),this.block=n,this.isReplace=o,this.mapMode=n?t<=0?Se.TrackBefore:Se.TrackAfter:Se.TrackDel}get type(){return this.startSide!=this.endSide?ge.WidgetRange:this.startSide<=0?ge.WidgetBefore:ge.WidgetAfter}get heightRelevant(){return this.block||!!this.widget&&(this.widget.estimatedHeight>=5||this.widget.lineBreaks>0)}eq(e){return e instanceof Kt&&Td(this.widget,e.widget)&&this.block==e.block&&this.startSide==e.startSide&&this.endSide==e.endSide}range(e,t=e){if(this.isReplace&&(e>t||e==t&&this.startSide>0&&this.endSide<=0))throw new RangeError("Invalid range for replacement decoration");if(!this.isReplace&&t!=e)throw new RangeError("Widget decorations can only have zero-length ranges");return super.range(e,t)}}Kt.prototype.point=!0;function Yh(s,e=!1){let{inclusiveStart:t,inclusiveEnd:i}=s;return t==null&&(t=s.inclusive),i==null&&(i=s.inclusive),{start:t??e,end:i??e}}function Td(s,e){return s==e||!!(s&&e&&s.compare(e))}function fi(s,e,t,i=0){let n=t.length-1;n>=0&&t[n]+i>=s?t[n]=Math.max(t[n],e):t.push(s,e)}class _i extends Mt{constructor(e,t,i){super(),this.tagName=e,this.attributes=t,this.rank=i}eq(e){return e==this||e instanceof _i&&this.tagName==e.tagName&&Wo(this.attributes,e.attributes)}static create(e){return new _i(e.tagName,e.attributes||sn,e.rank==null?50:Math.max(0,Math.min(e.rank,100)))}static set(e,t=!1){return X.of(e,t)}}_i.prototype.startSide=_i.prototype.endSide=-1;function Ki(s){let e;return s.nodeType==11?e=s.getSelection?s:s.ownerDocument:e=s,e.getSelection()}function _r(s,e){return e?s==e||s.contains(e.nodeType!=1?e.parentNode:e):!1}function Vi(s,e){if(!e.anchorNode)return!1;try{return _r(s,e.anchorNode)}catch{return!1}}function Hi(s){return s.nodeType==3?Ji(s,0,s.nodeValue.length).getClientRects():s.nodeType==1?s.getClientRects():[]}function zi(s,e,t,i){return t?Hl(s,e,t,i,-1)||Hl(s,e,t,i,1):!1}function Dt(s){for(var e=0;;e++)if(s=s.previousSibling,!s)return e}function nn(s){return s.nodeType==1&&/^(DIV|P|LI|UL|OL|BLOCKQUOTE|DD|DT|H\d|SECTION|PRE)$/.test(s.nodeName)}function Hl(s,e,t,i,n){for(;;){if(s==t&&e==i)return!0;if(e==(n<0?0:gt(s))){if(s.nodeName=="DIV")return!1;let r=s.parentNode;if(!r||r.nodeType!=1)return!1;e=Dt(s)+(n<0?0:1),s=r}else if(s.nodeType==1){if(s=s.childNodes[e+(n<0?-1:0)],s.nodeType==1&&s.contentEditable=="false")return!1;e=n<0?gt(s):0}else return!1}}function gt(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function Gi(s,e){let t=e?s.left:s.right;return{left:t,right:t,top:s.top,bottom:s.bottom}}function Dd(s){let e=s.visualViewport;return e?{left:0,right:e.width,top:0,bottom:e.height}:{left:0,right:s.innerWidth,top:0,bottom:s.innerHeight}}function _h(s,e){let t=e.width/s.offsetWidth,i=e.height/s.offsetHeight;return(t>.995&&t<1.005||!isFinite(t)||Math.abs(e.width-s.offsetWidth)<1)&&(t=1),(i>.995&&i<1.005||!isFinite(i)||Math.abs(e.height-s.offsetHeight)<1)&&(i=1),{scaleX:t,scaleY:i}}function Rd(s,e,t,i,n,r,o,l){let a=s.ownerDocument,h=a.defaultView||window;for(let c=s,f=!1;c&&!f;)if(c.nodeType==1){let u,d=c==a.body,p=1,m=1;if(d)u=Dd(h);else{if(/^(fixed|sticky)$/.test(getComputedStyle(c).position)&&(f=!0),c.scrollHeight<=c.clientHeight&&c.scrollWidth<=c.clientWidth){c=c.assignedSlot||c.parentNode;continue}let k=c.getBoundingClientRect();({scaleX:p,scaleY:m}=_h(c,k)),u={left:k.left,right:k.left+c.clientWidth*p,top:k.top,bottom:k.top+c.clientHeight*m}}let g=0,x=0;if(n=="nearest")e.top0&&e.bottom>u.bottom+x&&(x=e.bottom-u.bottom+o)):e.bottom>u.bottom-o&&(x=e.bottom-u.bottom+o,t<0&&e.top-x0&&e.right>u.right+g&&(g=e.right-u.right+r)):e.right>u.right-r&&(g=e.right-u.right+r,t<0&&e.leftu.bottom||e.leftu.right)&&(e={left:Math.max(e.left,u.left),right:Math.min(e.right,u.right),top:Math.max(e.top,u.top),bottom:Math.min(e.bottom,u.bottom)}),c=c.assignedSlot||c.parentNode}else if(c.nodeType==11)c=c.host;else break}function Kh(s,e=!0){let t=s.ownerDocument,i=null,n=null;for(let r=s.parentNode;r&&!(r==t.body||(!e||i)&&n);)if(r.nodeType==1)!n&&r.scrollHeight>r.clientHeight&&(n=r),e&&!i&&r.scrollWidth>r.clientWidth&&(i=r),r=r.assignedSlot||r.parentNode;else if(r.nodeType==11)r=r.host;else break;return{x:i,y:n}}class Bd{constructor(){this.anchorNode=null,this.anchorOffset=0,this.focusNode=null,this.focusOffset=0}eq(e){return this.anchorNode==e.anchorNode&&this.anchorOffset==e.anchorOffset&&this.focusNode==e.focusNode&&this.focusOffset==e.focusOffset}setRange(e){let{anchorNode:t,focusNode:i}=e;this.set(t,Math.min(e.anchorOffset,t?gt(t):0),i,Math.min(e.focusOffset,i?gt(i):0))}set(e,t,i,n){this.anchorNode=e,this.anchorOffset=t,this.focusNode=i,this.focusOffset=n}}let Vt=null;W.safari&&W.safari_version>=26&&(Vt=!1);function Gh(s){if(s.setActive)return s.setActive();if(Vt)return s.focus(Vt);let e=[];for(let t=s;t&&(e.push(t,t.scrollTop,t.scrollLeft),t!=t.ownerDocument);t=t.parentNode);if(s.focus(Vt==null?{get preventScroll(){return Vt={preventScroll:!0},!0}}:void 0),!Vt){Vt=!1;for(let t=0;tMath.max(0,s.document.documentElement.scrollHeight-s.innerHeight-4):s.scrollTop>Math.max(1,s.scrollHeight-s.clientHeight-4)}function Zh(s,e){for(let t=s,i=e;;){if(t.nodeType==3&&i>0)return{node:t,offset:i};if(t.nodeType==1&&i>0){if(t.contentEditable=="false")return null;t=t.childNodes[i-1],i=gt(t)}else if(t.parentNode&&!nn(t))i=Dt(t),t=t.parentNode;else return null}}function ec(s,e){for(let t=s,i=e;;){if(t.nodeType==3&&i=t){if(l.level==i)return o;(r<0||(n!=0?n<0?l.fromt:e[r].level>l.level))&&(r=o)}}if(r<0)throw new RangeError("Index out of range");return r}}function sc(s,e){if(s.length!=e.length)return!1;for(let t=0;t=0;m-=3)if(Ge[m+1]==-d){let g=Ge[m+2],x=g&2?n:g&4?g&1?r:n:0;x&&(G[f]=G[Ge[m]]=x),l=m;break}}else{if(Ge.length==189)break;Ge[l++]=f,Ge[l++]=u,Ge[l++]=a}else if((p=G[f])==2||p==1){let m=p==n;a=m?0:1;for(let g=l-3;g>=0;g-=3){let x=Ge[g+2];if(x&2)break;if(m)Ge[g+2]|=2;else{if(x&4)break;Ge[g+2]|=4}}}}}function Hd(s,e,t,i){for(let n=0,r=i;n<=t.length;n++){let o=n?t[n-1].to:s,l=na;)p==g&&(p=t[--m].from,g=m?t[m-1].to:s),G[--p]=d;a=c}else r=h,a++}}}function Gr(s,e,t,i,n,r,o){let l=i%2?2:1;if(i%2==n%2)for(let a=e,h=0;aa&&o.push(new nt(a,m.from,d));let g=m.direction==Gt!=!(d%2);Jr(s,g?i+1:i,n,m.inner,m.from,m.to,o),a=m.to}p=m.to}else{if(p==t||(c?G[p]!=l:G[p]==l))break;p++}u?Gr(s,a,p,i+1,n,u,o):ae;){let c=!0,f=!1;if(!h||a>r[h-1].to){let m=G[a-1];m!=l&&(c=!1,f=m==16)}let u=!c&&l==1?[]:null,d=c?i:i+1,p=a;e:for(;;)if(h&&p==r[h-1].to){if(f)break e;let m=r[--h];if(!c)for(let g=m.from,x=h;;){if(g==e)break e;if(x&&r[x-1].to==g)g=r[--x].from;else{if(G[g-1]==l)break e;break}}if(u)u.push(m);else{m.toG.length;)G[G.length]=256;let i=[],n=e==Gt?0:1;return Jr(s,n,n,t,0,s.length,i),i}function nc(s){return[new nt(0,s,0)]}let rc="";function Qd(s,e,t,i,n){var r;let o=i.head-s.from,l=nt.find(e,o,(r=i.bidiLevel)!==null&&r!==void 0?r:-1,i.assoc),a=e[l],h=a.side(n,t);if(o==h){let u=l+=n?1:-1;if(u<0||u>=e.length)return null;a=e[l=u],o=a.side(!n,t),h=a.side(n,t)}let c=fe(s.text,o,a.forward(n,t));(ca.to)&&(c=h),rc=s.text.slice(Math.min(o,c),Math.max(o,c));let f=l==(n?e.length-1:0)?null:e[l+(n?1:-1)];return f&&c==h&&f.level+(n?0:1)s.some(e=>e)}),dc=I.define({combine:s=>s.some(e=>e)}),pc=I.define();class di{constructor(e,t,i,n,r,o=!1){this.range=e,this.y=t,this.x=i,this.yMargin=n,this.xMargin=r,this.isSnapshot=o}map(e){return e.empty?this:new di(this.range.map(e),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}clip(e){return this.range.to<=e.doc.length?this:new di(v.cursor(e.doc.length),this.y,this.x,this.yMargin,this.xMargin,this.isSnapshot)}}const Ss=$.define({map:(s,e)=>s.map(e)}),mc=$.define();function Pe(s,e,t){let i=s.facet(hc);i.length?i[0](e):window.onerror&&window.onerror(String(e),t,void 0,void 0,e)||(t?console.error(t+":",e):console.error(e))}const dt=I.define({combine:s=>s.length?s[0]:!0});let jd=0;const oi=I.define({combine(s){return s.filter((e,t)=>{for(let i=0;i{let a=[];return o&&a.push(Bn.of(h=>{let c=h.plugin(l);return c?o(c):z.none})),r&&a.push(r(l)),a})}static fromClass(e,t){return se.define((i,n)=>new e(i,n),t)}}class Zn{constructor(e){this.spec=e,this.mustUpdate=null,this.value=null}get plugin(){return this.spec&&this.spec.plugin}update(e){if(this.value){if(this.mustUpdate){let t=this.mustUpdate;if(this.mustUpdate=null,this.value.update)try{this.value.update(t)}catch(i){if(Pe(t.state,i,"CodeMirror plugin crashed"),this.value.destroy)try{this.value.destroy()}catch{}this.deactivate()}}}else if(this.spec)try{this.value=this.spec.plugin.create(e,this.spec.arg)}catch(t){Pe(e.state,t,"CodeMirror plugin crashed"),this.deactivate()}return this}destroy(e){var t;if(!((t=this.value)===null||t===void 0)&&t.destroy)try{this.value.destroy()}catch(i){Pe(e.state,i,"CodeMirror plugin crashed")}}deactivate(){this.spec=this.value=null}}const gc=I.define(),zo=I.define(),Bn=I.define(),xc=I.define(),Qo=I.define(),fs=I.define(),bc=I.define();function Ql(s,e){let t=s.state.facet(bc);if(!t.length)return t;let i=t.map(r=>r instanceof Function?r(s):r),n=[];return X.spans(i,e.from,e.to,{point(){},span(r,o,l,a){let h=r-e.from,c=o-e.from,f=n;for(let u=l.length-1;u>=0;u--,a--){let d=l[u].spec.bidiIsolate,p;if(d==null&&(d=$d(e.text,h,c)),a>0&&f.length&&(p=f[f.length-1]).to==h&&p.direction==d)p.to=c,f=p.inner;else{let m={from:h,to:c,direction:d,inner:[]};f.push(m),f=m.inner}}}}),n}const yc=I.define();function $o(s){let e=0,t=0,i=0,n=0;for(let r of s.state.facet(yc)){let o=r(s);o&&(o.left!=null&&(e=Math.max(e,o.left)),o.right!=null&&(t=Math.max(t,o.right)),o.top!=null&&(i=Math.max(i,o.top)),o.bottom!=null&&(n=Math.max(n,o.bottom)))}return{left:e,right:t,top:i,bottom:n}}const Li=I.define();class We{constructor(e,t,i,n){this.fromA=e,this.toA=t,this.fromB=i,this.toB=n}join(e){return new We(Math.min(this.fromA,e.fromA),Math.max(this.toA,e.toA),Math.min(this.fromB,e.fromB),Math.max(this.toB,e.toB))}addToSet(e){let t=e.length,i=this;for(;t>0;t--){let n=e[t-1];if(!(n.fromA>i.toA)){if(n.toAn.push(new We(r,o,l,a))),this.changedRanges=n}static create(e,t,i){return new rn(e,t,i)}get viewportChanged(){return(this.flags&4)>0}get viewportMoved(){return(this.flags&8)>0}get heightChanged(){return(this.flags&2)>0}get geometryChanged(){return this.docChanged||(this.flags&18)>0}get focusChanged(){return(this.flags&1)>0}get docChanged(){return!this.changes.empty}get selectionSet(){return this.transactions.some(e=>e.selection)}get empty(){return this.flags==0&&this.transactions.length==0}}const qd=[];class ie{constructor(e,t,i=0){this.dom=e,this.length=t,this.flags=i,this.parent=null,e.cmTile=this}get breakAfter(){return this.flags&1}get children(){return qd}isWidget(){return!1}get isHidden(){return!1}isComposite(){return!1}isLine(){return!1}isText(){return!1}isBlock(){return!1}get domAttrs(){return null}sync(e){if(this.flags|=2,this.flags&4){this.flags&=-5;let t=this.domAttrs;t&&Md(this.dom,t)}}toString(){return this.constructor.name+(this.children.length?`(${this.children})`:"")+(this.breakAfter?"#":"")}destroy(){this.parent=null}setDOM(e){this.dom=e,e.cmTile=this}get posAtStart(){return this.parent?this.parent.posBefore(this):0}get posAtEnd(){return this.posAtStart+this.length}posBefore(e,t=this.posAtStart){let i=t;for(let n of this.children){if(n==e)return i;i+=n.length+n.breakAfter}throw new RangeError("Invalid child in posBefore")}posAfter(e){return this.posBefore(e)+e.length}covers(e){return!0}coordsIn(e,t){return null}domPosFor(e,t){let i=Dt(this.dom),n=this.length?e>0:t>0;return new je(this.parent.dom,i+(n?1:0),e==0||e==this.length)}markDirty(e){this.flags&=-3,e&&(this.flags|=4),this.parent&&this.parent.flags&2&&this.parent.markDirty(!1)}get overrideDOMText(){return null}get root(){for(let e=this;e;e=e.parent)if(e instanceof Ln)return e;return null}static get(e){return e.cmTile}}class En extends ie{constructor(e){super(e,0),this._children=[]}isComposite(){return!0}get children(){return this._children}get lastChild(){return this.children.length?this.children[this.children.length-1]:null}append(e){this.children.push(e),e.parent=this}sync(e){if(this.flags&2)return;super.sync(e);let t=this.dom,i=null,n,r=e?.node==t?e:null,o=0;for(let l of this.children){if(l.sync(e),o+=l.length+l.breakAfter,n=i?i.nextSibling:t.firstChild,r&&n!=l.dom&&(r.written=!0),l.dom.parentNode==t)for(;n&&n!=l.dom;)n=$l(n);else t.insertBefore(l.dom,n);i=l.dom}for(n=i?i.nextSibling:t.firstChild,r&&n&&(r.written=!0);n;)n=$l(n);this.length=o}}function $l(s){let e=s.nextSibling;return s.parentNode.removeChild(s),e}class Ln extends En{constructor(e,t){super(t),this.view=e}owns(e){for(;e;e=e.parent)if(e==this)return!0;return!1}isBlock(){return!0}nearest(e){for(;;){if(!e)return null;let t=ie.get(e);if(t&&this.owns(t))return t;e=e.parentNode}}blockTiles(e){for(let t=[],i=this,n=0,r=0;;)if(n==i.children.length){if(!t.length)return;i=i.parent,i.breakAfter&&r++,n=t.pop()}else{let o=i.children[n++];if(o instanceof pt)t.push(n),i=o,n=0;else{let l=r+o.length,a=e(o,r);if(a!==void 0)return a;r=l+o.breakAfter}}}resolveBlock(e,t){let i,n=-1,r,o=-1;if(this.blockTiles((l,a)=>{let h=a+l.length;if(e>=a&&e<=h){if(l.isWidget()&&t>=-1&&t<=1){if(l.flags&32)return!0;l.flags&16&&(i=void 0)}(ae||e==a&&(t>1?l.length:l.covers(-1)))&&(!r||!l.isWidget()&&r.isWidget())&&(r=l,o=e-a)}}),!i&&!r)throw new Error("No tile at position "+e);return i&&t<0||!r?{tile:i,offset:n}:{tile:r,offset:o}}}class pt extends En{constructor(e,t){super(e),this.wrapper=t}isBlock(){return!0}covers(e){return this.children.length?e<0?this.children[0].covers(-1):this.lastChild.covers(1):!1}get domAttrs(){return this.wrapper.attributes}static of(e,t){let i=new pt(t||document.createElement(e.tagName),e);return t||(i.flags|=4),i}}class bi extends En{constructor(e,t){super(e),this.attrs=t}isLine(){return!0}static start(e,t,i){let n=new bi(t||document.createElement("div"),e);return(!t||!i)&&(n.flags|=4),n}get domAttrs(){return this.attrs}resolveInline(e,t,i){let n=null,r=-1,o=null,l=-1;function a(c,f){for(let u=0,d=0;u=f&&(p.isComposite()?a(p,f-d):(!o||o.isHidden&&(t>0||i&&Ud(o,p)))&&(m>f||p.flags&32)?(o=p,l=f-d):(di&&(e=i);let n=e,r=e,o=0;e==0&&t<0||e==i&&t>=0?W.chrome||W.gecko||(e?(n--,o=1):r=0)?0:l.length-1];return W.safari&&!o&&a.width==0&&(a=Array.prototype.find.call(l,h=>h.width)||a),o?Gi(a,o<0):a||null}static of(e,t){let i=new jt(t||document.createTextNode(e),e);return t||(i.flags|=2),i}}class Jt extends ie{constructor(e,t,i,n){super(e,t,n),this.widget=i}isWidget(){return!0}get isHidden(){return this.widget.isHidden}covers(e){return this.flags&48?!1:(this.flags&(e<0?64:128))>0}coordsIn(e,t){return this.coordsInWidget(e,t,!1)}coordsInWidget(e,t,i){let n=this.widget.coordsAt(this.dom,e,t);if(n)return n;if(i)return Gi(this.dom.getBoundingClientRect(),this.length?e==0:t<=0);{let r=this.dom.getClientRects(),o=null;if(!r.length)return null;let l=this.flags&16?!0:this.flags&32?!1:e>0;for(let a=l?r.length-1:0;o=r[a],!(e>0?a==0:a==r.length-1||o.top0;)if(n.isComposite())if(o){if(!e)break;i&&i.break(),e--,o=!1}else if(r==n.children.length){if(!e&&!l.length)break;i&&i.leave(n),o=!!n.breakAfter,{tile:n,index:r}=l.pop(),r++}else{let a=n.children[r],h=a.breakAfter;(t>0?a.length<=e:a.length=0;l--){let a=t.marks[l],h=n.lastChild;if(h instanceof Me&&h.mark.eq(a.mark))h.dom!=a.dom&&h.setDOM(er(a.dom)),n=h;else{if(this.cache.reused.get(a)){let f=ie.get(a.dom);f&&f.setDOM(er(a.dom))}let c=Me.of(a.mark,a.dom);n.append(c),n=c}this.cache.reused.set(a,2)}let r=ie.get(e.text);r&&this.cache.reused.set(r,2);let o=new jt(e.text,e.text.nodeValue);o.flags|=8,this.pos=e.range.toB,n.append(o)}addInlineWidget(e,t,i){let n=this.afterWidget&&e.flags&48&&(this.afterWidget.flags&48)==(e.flags&48);n||this.flushBuffer();let r=this.ensureMarks(t,i);!n&&!(e.flags&16)&&r.append(this.getBuffer(1)),r.append(e),this.pos+=e.length,this.afterWidget=e}addMark(e,t,i){this.flushBuffer(),this.ensureMarks(t,i).append(e),this.pos+=e.length,this.afterWidget=null}addBlockWidget(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}continueWidget(e){let t=this.afterWidget||this.lastBlock;t.length+=e,this.pos+=e}addLineStart(e,t){var i;e||(e=kc);let n=bi.start(e,t||((i=this.cache.find(bi))===null||i===void 0?void 0:i.dom),!!t);this.getBlockPos().append(this.lastBlock=this.curLine=n)}addLine(e){this.getBlockPos().append(e),this.pos+=e.length,this.lastBlock=e,this.endLine()}addBreak(){this.lastBlock.flags|=1,this.endLine(),this.pos++}addLineStartIfNotCovered(e){this.blockPosCovered()||this.addLineStart(e)}ensureLine(e){this.curLine||this.addLineStart(e)}ensureMarks(e,t){var i;let n=this.curLine;for(let r=e.length-1;r>=0;r--){let o=e[r],l;if(t>0&&(l=n.lastChild)&&l instanceof Me&&l.mark.eq(o))n=l,t--;else{let a=Me.of(o,(i=this.cache.find(Me,h=>h.mark.eq(o)))===null||i===void 0?void 0:i.dom);n.append(a),n=a,t=0}}return n}endLine(){if(this.curLine){this.flushBuffer();let e=this.curLine.lastChild;(!e||!jl(this.curLine,!1)||e.dom.nodeName!="BR"&&e.isWidget()&&!(W.ios&&jl(this.curLine,!0)))&&this.curLine.append(this.cache.findWidget(tr,0,32)||new Jt(tr.toDOM(),0,tr,32)),this.curLine=this.afterWidget=null}}updateBlockWrappers(){this.wrapperPos>this.pos+1e4&&(this.blockWrappers.goto(this.pos),this.wrappers.length=0);for(let e=this.wrappers.length-1;e>=0;e--)this.wrappers[e].to=this.pos){let t=e.rank*102+e.value.rank,i=new _d(e.from,e.to,e.value,t),n=this.wrappers.length;for(;n>0&&(this.wrappers[n-1].rank-i.rank||this.wrappers[n-1].to-i.to)<0;)n--;this.wrappers.splice(n,0,i)}this.wrapperPos=this.pos}getBlockPos(){var e;this.updateBlockWrappers();let t=this.root;for(let i of this.wrappers){let n=t.lastChild;if(i.fromo.wrapper.eq(i.wrapper)))===null||e===void 0?void 0:e.dom);t.append(r),t=r}}return t}blockPosCovered(){let e=this.lastBlock;return e!=null&&!e.breakAfter&&(!e.isWidget()||(e.flags&160)>0)}getBuffer(e){let t=2|(e<0?16:32),i=this.cache.find(on,void 0,1);return i&&(i.flags=t),i||new on(t)}flushBuffer(){this.afterWidget&&!(this.afterWidget.flags&32)&&(this.afterWidget.parent.append(this.getBuffer(-1)),this.afterWidget=null)}}class Gd{constructor(e){this.skipCount=0,this.text="",this.textOff=0,this.cursor=e.iter()}skip(e){this.textOff+e<=this.text.length?this.textOff+=e:(this.skipCount+=e-(this.text.length-this.textOff),this.text="",this.textOff=0)}next(e){if(this.textOff==this.text.length){let{value:n,lineBreak:r,done:o}=this.cursor.next(this.skipCount);if(this.skipCount=0,o)throw new Error("Ran out of text content when drawing inline views");this.text=n;let l=this.textOff=Math.min(e,n.length);return r?null:n.slice(0,l)}let t=Math.min(this.text.length,this.textOff+e),i=this.text.slice(this.textOff,t);return this.textOff=t,i}}const ln=[Jt,bi,jt,Me,on,pt,Ln];for(let s=0;s[]),this.index=ln.map(()=>0),this.reused=new Map}add(e){let t=e.constructor.bucket,i=this.buckets[t];i.length<6?i.push(e):i[this.index[t]=(this.index[t]+1)%6]=e}find(e,t,i=2){let n=e.bucket,r=this.buckets[n],o=this.index[n];for(let l=r.length-1;l>=0;l--){let a=(l+o)%r.length,h=r[a];if((!t||t(h))&&!this.reused.has(h))return r.splice(a,1),a{if(this.cache.add(o),o.isComposite())return!1},enter:o=>this.cache.add(o),leave:()=>{},break:()=>{}}}run(e,t){let i=t&&this.getCompositionContext(t.text);for(let n=0,r=0,o=0;;){let l=on){let h=a-n;this.preserve(h,!o,!l),n=a,r+=h}if(!l)break;t&&l.fromA<=t.range.fromA&&l.toA>=t.range.toA?(this.forward(l.fromA,t.range.fromA,t.range.fromA{if(o.isWidget())if(this.openWidget)this.builder.continueWidget(a-l);else{let h=a>0||l{o.isLine()?this.builder.addLineStart(o.attrs,this.cache.maybeReuse(o)):(this.cache.add(o),o instanceof Me&&n.unshift(o.mark)),this.openWidget=!1},leave:o=>{o.isLine()?n.length&&(n.length=r=0):o instanceof Me&&(n.shift(),r=Math.min(r,n.length))},break:()=>{this.builder.addBreak(),this.openWidget=!1}}),this.text.skip(e)}emit(e,t){let i=null,n=this.builder,r=0,o=X.spans(this.decorations,e,t,{point:(l,a,h,c,f,u)=>{if(h instanceof Kt){if(this.disallowBlockEffectsFor[u]){if(h.block)throw new RangeError("Block decorations may not be specified via plugins");if(a>this.view.state.doc.lineAt(l).to)throw new RangeError("Decorations that replace line breaks may not be specified via plugins")}if(r=c.length,f>c.length)n.continueWidget(a-l);else{let d=h.widget||(h.block?yi.block:yi.inline),p=ep(h),m=this.cache.findWidget(d,a-l,p)||Jt.of(d,this.view,a-l,p);h.block?(h.startSide>0&&n.addLineStartIfNotCovered(i),n.addBlockWidget(m)):(n.ensureLine(i),n.addInlineWidget(m,c,f))}i=null}else i=tp(i,h);a>l&&this.text.skip(a-l)},span:(l,a,h,c)=>{for(let f=l;fr,this.openMarks=o}forward(e,t,i=1){t-e<=10?this.old.advance(t-e,i,this.reuseWalker):(this.old.advance(5,-1,this.reuseWalker),this.old.advance(t-e-10,-1),this.old.advance(5,i,this.reuseWalker))}getCompositionContext(e){let t=[],i=null;for(let n=e.parentNode;;n=n.parentNode){let r=ie.get(n);if(n==this.view.contentDOM)break;r instanceof Me?t.push(r):r?.isLine()?i=r:r instanceof pt||(n.nodeName=="DIV"&&!i&&n!=this.view.contentDOM?i=new bi(n,kc):i||t.push(Me.of(new hs({tagName:n.nodeName.toLowerCase(),attributes:Pd(n)}),n)))}return{line:i,marks:t}}}function jl(s,e){let t=i=>{for(let n of i.children)if((e?n.isText():n.length)||t(n))return!0;return!1};return t(s)}function ep(s){let e=s.isReplace?(s.startSide<0?64:0)|(s.endSide>0?128:0):s.startSide>0?32:16;return s.block&&(e|=256),e}const kc={class:"cm-line"};function tp(s,e){let t=e.spec.attributes,i=e.spec.class;return!t&&!i||(s||(s={class:"cm-line"}),t&&Io(t,s),i&&(s.class+=" "+i)),s}function ip(s){let e=[];for(let t=s.parents.length;t>1;t--){let i=t==s.parents.length?s.tile:s.parents[t].tile;i instanceof Me&&e.push(i.mark)}return e}function er(s){let e=ie.get(s);return e&&e.setDOM(s.cloneNode()),s}class yi extends ct{constructor(e){super(),this.tag=e}eq(e){return e.tag==this.tag}toDOM(){return document.createElement(this.tag)}updateDOM(e){return e.nodeName.toLowerCase()==this.tag}get isHidden(){return!0}}yi.inline=new yi("span");yi.block=new yi("div");const tr=new class extends ct{toDOM(){return document.createElement("br")}get isHidden(){return!0}get editable(){return!0}};class ql{constructor(e){this.view=e,this.decorations=[],this.blockWrappers=[],this.dynamicDecorationMap=[!1],this.domChanged=null,this.hasComposition=null,this.editContextFormatting=z.none,this.lastCompositionAfterCursor=!1,this.minWidth=0,this.minWidthFrom=0,this.minWidthTo=0,this.impreciseAnchor=null,this.impreciseHead=null,this.forceSelection=!1,this.lastUpdate=Date.now(),this.updateDeco(),this.tile=new Ln(e,e.contentDOM),this.updateInner([new We(0,0,0,e.state.doc.length)],null)}update(e){var t;let i=e.changedRanges;this.minWidth>0&&i.length&&(i.every(({fromA:c,toA:f})=>fthis.minWidthTo)?(this.minWidthFrom=e.changes.mapPos(this.minWidthFrom,1),this.minWidthTo=e.changes.mapPos(this.minWidthTo,1)):this.minWidth=this.minWidthFrom=this.minWidthTo=0),this.updateEditContextFormatting(e);let n=-1;this.view.inputState.composing>=0&&!this.view.observer.editContext&&(!((t=this.domChanged)===null||t===void 0)&&t.newSel?n=this.domChanged.newSel.head:!fp(e.changes,this.hasComposition)&&!e.selectionSet&&(n=e.state.selection.main.head));let r=n>-1?np(this.view,e.changes,n):null;if(this.domChanged=null,this.hasComposition){let{from:c,to:f}=this.hasComposition;i=new We(c,f,e.changes.mapPos(c,-1),e.changes.mapPos(f,1)).addToSet(i.slice())}this.hasComposition=r?{from:r.range.fromB,to:r.range.toB}:null,(W.ie||W.chrome)&&!r&&e&&e.state.doc.lines!=e.startState.doc.lines&&(this.forceSelection=!0);let o=this.decorations,l=this.blockWrappers;this.updateDeco();let a=lp(o,this.decorations,e.changes);a.length&&(i=We.extendWithRanges(i,a));let h=hp(l,this.blockWrappers,e.changes);return h.length&&(i=We.extendWithRanges(i,h)),r&&!i.some(c=>c.fromA<=r.range.fromA&&c.toA>=r.range.toA)&&(i=r.range.addToSet(i.slice())),this.tile.flags&2&&i.length==0?!1:(this.updateInner(i,r),e.transactions.length&&(this.lastUpdate=Date.now()),!0)}updateInner(e,t){this.view.viewState.mustMeasureContent=!0;let{observer:i}=this.view;i.ignore(()=>{if(t||e.length){let o=this.tile,l=new Zd(this.view,o,this.blockWrappers,this.decorations,this.dynamicDecorationMap);t&&ie.get(t.text)&&l.cache.reused.set(ie.get(t.text),2),this.tile=l.run(e,t),eo(o,l.cache.reused)}this.tile.dom.style.height=this.view.viewState.contentHeight/this.view.scaleY+"px",this.tile.dom.style.flexBasis=this.minWidth?this.minWidth+"px":"";let r=W.chrome||W.ios?{node:i.selectionRange.focusNode,written:!1}:void 0;this.tile.sync(r),r&&(r.written||i.selectionRange.focusNode!=r.node||!this.tile.dom.contains(r.node))&&(this.forceSelection=!0),this.tile.dom.style.height=""});let n=[];if(this.view.viewport.from||this.view.viewport.to-1)&&Vi(i,this.view.observer.selectionRange)&&!(n&&i.contains(n));if(!(r||t||o))return;let l=this.forceSelection;this.forceSelection=!1;let a=this.view.state.selection.main,h,c;if(a.empty?c=h=this.inlineDOMNearPos(a.anchor,a.assoc||1):(c=this.inlineDOMNearPos(a.head,a.head==a.from?1:-1),h=this.inlineDOMNearPos(a.anchor,a.anchor==a.from?1:-1)),W.gecko&&a.empty&&!this.hasComposition&&sp(h)){let u=document.createTextNode("");this.view.observer.ignore(()=>h.node.insertBefore(u,h.node.childNodes[h.offset]||null)),h=c=new je(u,0),l=!0}let f=this.view.observer.selectionRange;(l||!f.focusNode||(!zi(h.node,h.offset,f.anchorNode,f.anchorOffset)||!zi(c.node,c.offset,f.focusNode,f.focusOffset))&&!this.suppressWidgetCursorChange(f,a))&&(this.view.observer.ignore(()=>{W.android&&W.chrome&&i.contains(f.focusNode)&&cp(f.focusNode,i)&&(i.blur(),i.focus({preventScroll:!0}));let u=Ki(this.view.root);if(u)if(a.empty){if(W.gecko){let d=rp(h.node,h.offset);if(d&&d!=3){let p=(d==1?Zh:ec)(h.node,h.offset);p&&(h=new je(p.node,p.offset))}}u.collapse(h.node,h.offset),a.bidiLevel!=null&&u.caretBidiLevel!==void 0&&(u.caretBidiLevel=a.bidiLevel)}else if(u.extend){u.collapse(h.node,h.offset);try{u.extend(c.node,c.offset)}catch{}}else{let d=document.createRange();a.anchor>a.head&&([h,c]=[c,h]),d.setEnd(c.node,c.offset),d.setStart(h.node,h.offset),u.removeAllRanges(),u.addRange(d)}o&&this.view.root.activeElement==i&&(i.blur(),n&&n.focus())}),this.view.observer.setSelectionRange(h,c)),this.impreciseAnchor=h.precise?null:new je(f.anchorNode,f.anchorOffset),this.impreciseHead=c.precise?null:new je(f.focusNode,f.focusOffset)}suppressWidgetCursorChange(e,t){return this.hasComposition&&t.empty&&zi(e.focusNode,e.focusOffset,e.anchorNode,e.anchorOffset)&&this.posFromDOM(e.focusNode,e.focusOffset)==t.head}enforceCursorAssoc(){if(this.hasComposition)return;let{view:e}=this,t=e.state.selection.main,i=Ki(e.root),{anchorNode:n,anchorOffset:r}=e.observer.selectionRange;if(!i||!t.empty||!t.assoc||!i.modify)return;let o=this.lineAt(t.head,t.assoc);if(!o)return;let l=o.posAtStart;if(t.head==l||t.head==l+o.length)return;let a=this.coordsAt(t.head,-1),h=this.coordsAt(t.head,1);if(!a||!h||a.bottom>h.top)return;let c=this.domAtPos(t.head+t.assoc,t.assoc);i.collapse(c.node,c.offset),i.modify("move",t.assoc<0?"forward":"backward","lineboundary"),e.observer.readSelectionRange();let f=e.observer.selectionRange;e.docView.posFromDOM(f.anchorNode,f.anchorOffset)!=t.from&&i.collapse(n,r)}posFromDOM(e,t){let i=this.tile.nearest(e);if(!i)return this.tile.dom.compareDocumentPosition(e)&2?0:this.view.state.doc.length;let n=i.posAtStart;if(i.isComposite()){let r;if(e==i.dom)r=i.dom.childNodes[t];else{let o=gt(e)==0?0:t==0?-1:1;for(;;){let l=e.parentNode;if(l==i.dom)break;o==0&&l.firstChild!=l.lastChild&&(e==l.firstChild?o=-1:o=1),e=l}o<0?r=e:r=e.nextSibling}if(r==i.dom.firstChild)return n;for(;r&&!ie.get(r);)r=r.nextSibling;if(!r)return n+i.length;for(let o=0,l=n;;o++){let a=i.children[o];if(a.dom==r)return l;l+=a.length+a.breakAfter}}else return i.isText()?e==i.dom?n+t:n+(t?i.length:0):n}domAtPos(e,t){let{tile:i,offset:n}=this.tile.resolveBlock(e,t);return i.isWidget()?i.domPosFor(e,t):i.domIn(n,t)}inlineDOMNearPos(e,t){let i,n=-1,r=!1,o,l=-1,a=!1;return this.tile.blockTiles((h,c)=>{if(h.isWidget()){if(h.flags&32&&c>=e)return!0;h.flags&16&&(r=!0)}else{let f=c+h.length;if(c<=e&&(i=h,n=e-c,r=f=e&&!o&&(o=h,l=e-c,a=c>e),c>e&&o)return!0}}),!i&&!o?this.domAtPos(e,t):(r&&o?i=null:a&&i&&(o=null),i&&t<0||!o?i.domIn(n,t):o.domIn(l,t))}coordsAt(e,t){let{tile:i,offset:n}=this.tile.resolveBlock(e,t);return i.isWidget()?i.widget instanceof ir?null:i.coordsInWidget(n,t,!0):i.coordsIn(n,t)}lineAt(e,t){let{tile:i}=this.tile.resolveBlock(e,t);return i.isLine()?i:null}coordsForChar(e){let{tile:t,offset:i}=this.tile.resolveBlock(e,1);if(!t.isLine())return null;function n(r,o){if(r.isComposite())for(let l of r.children){if(l.length>=o){let a=n(l,o);if(a)return a}if(o-=l.length,o<0)break}else if(r.isText()&&oMath.max(this.view.scrollDOM.clientWidth,this.minWidth)+1,l=-1,a=this.view.textDirection==J.LTR,h=0,c=(f,u,d)=>{for(let p=0;pn);p++){let m=f.children[p],g=u+m.length,x=m.dom.getBoundingClientRect(),{height:k}=x;if(d&&!p&&(h+=x.top-d.top),m instanceof pt)g>i&&c(m,u,x);else if(u>=i&&(h>0&&t.push(-h),t.push(k+h),h=0,o)){let w=m.dom.lastChild,T=w?Hi(w):[];if(T.length){let S=T[T.length-1],A=a?S.right-x.left:x.right-S.left;A>l&&(l=A,this.minWidth=r,this.minWidthFrom=u,this.minWidthTo=g)}}d&&p==f.children.length-1&&(h+=d.bottom-x.bottom),u=g+m.breakAfter}};return c(this.tile,0,null),t}textDirectionAt(e){let{tile:t}=this.tile.resolveBlock(e,1);return getComputedStyle(t.dom).direction=="rtl"?J.RTL:J.LTR}measureTextSize(){let e=this.tile.blockTiles(o=>{if(o.isLine()&&o.children.length&&o.length<=20){let l=0,a;for(let h of o.children){if(!h.isText()||/[^ -~]/.test(h.text))return;let c=Hi(h.dom);if(c.length!=1)return;l+=c[0].width,a=c[0].height}if(l)return{lineHeight:o.dom.getBoundingClientRect().height,charWidth:l/o.length,textHeight:a}}});if(e)return e;let t=document.createElement("div"),i,n,r;return t.className="cm-line",t.style.width="99999px",t.style.position="absolute",t.textContent="abc def ghi jkl mno pqr stu",this.view.observer.ignore(()=>{this.tile.dom.appendChild(t);let o=Hi(t.firstChild)[0];i=t.getBoundingClientRect().height,n=o&&o.width?o.width/27:7,r=o&&o.height?o.height:i,t.remove()}),{lineHeight:i,charWidth:n,textHeight:r}}computeBlockGapDeco(){let e=[],t=this.view.viewState;for(let i=0,n=0;;n++){let r=n==t.viewports.length?null:t.viewports[n],o=r?r.from-1:this.view.state.doc.length;if(o>i){let l=(t.lineBlockAt(o).bottom-t.lineBlockAt(i).top)/this.view.scaleY;e.push(z.replace({widget:new ir(l),block:!0,inclusive:!0,isBlockGap:!0}).range(i,o))}if(!r)break;i=r.to+1}return z.set(e)}updateDeco(){let e=1,t=this.view.state.facet(Bn).map(r=>(this.dynamicDecorationMap[e++]=typeof r=="function")?r(this.view):r),i=!1,n=this.view.state.facet(Qo).map((r,o)=>{let l=typeof r=="function";return l&&(i=!0),l?r(this.view):r});for(n.length&&(this.dynamicDecorationMap[e++]=i,t.push(X.join(n))),this.decorations=[this.editContextFormatting,...t,this.computeBlockGapDeco(),this.view.viewState.lineGapDeco];etypeof r=="function"?r(this.view):r)}scrollIntoView(e){var t;if(e.isSnapshot){let c=this.view.viewState.lineBlockAt(e.range.head);this.view.scrollDOM.scrollTop=c.top-e.yMargin,this.view.scrollDOM.scrollLeft=e.xMargin;return}for(let c of this.view.state.facet(pc))try{if(c(this.view,e.range,e))return!0}catch(f){Pe(this.view.state,f,"scroll handler")}let{range:i}=e,n=this.coordsAt(i.head,(t=i.assoc)!==null&&t!==void 0?t:i.empty?0:i.head>i.anchor?-1:1),r;if(!n)return;!i.empty&&(r=this.coordsAt(i.anchor,i.anchor>i.head?-1:1))&&(n={left:Math.min(n.left,r.left),top:Math.min(n.top,r.top),right:Math.max(n.right,r.right),bottom:Math.max(n.bottom,r.bottom)});let o=$o(this.view),l={left:n.left-o.left,top:n.top-o.top,right:n.right+o.right,bottom:n.bottom+o.bottom},{offsetWidth:a,offsetHeight:h}=this.view.scrollDOM;if(Rd(this.view.scrollDOM,l,i.head1&&(n.top>window.pageYOffset+window.visualViewport.offsetTop+window.visualViewport.height||n.bottomi.isWidget()||i.children.some(t);return t(this.tile.resolveBlock(e,1).tile)}destroy(){eo(this.tile)}}function eo(s,e){let t=e?.get(s);if(t!=1){t==null&&s.destroy();for(let i of s.children)eo(i,e)}}function sp(s){return s.node.nodeType==1&&s.node.firstChild&&(s.offset==0||s.node.childNodes[s.offset-1].contentEditable=="false")&&(s.offset==s.node.childNodes.length||s.node.childNodes[s.offset].contentEditable=="false")}function wc(s,e){let t=s.observer.selectionRange;if(!t.focusNode)return null;let i=Zh(t.focusNode,t.focusOffset),n=ec(t.focusNode,t.focusOffset),r=i||n;if(n&&i&&n.node!=i.node){let l=ie.get(n.node);if(!l||l.isText()&&l.text!=n.node.nodeValue)r=n;else if(s.docView.lastCompositionAfterCursor){let a=ie.get(i.node);!a||a.isText()&&a.text!=i.node.nodeValue||(r=n)}}if(s.docView.lastCompositionAfterCursor=r!=i,!r)return null;let o=e-r.offset;return{from:o,to:o+r.node.nodeValue.length,node:r.node}}function np(s,e,t){let i=wc(s,t);if(!i)return null;let{node:n,from:r,to:o}=i,l=n.nodeValue;if(/[\n\r]/.test(l)||s.state.doc.sliceString(i.from,i.to)!=l)return null;let a=e.invertedDesc;return{range:new We(a.mapPos(r),a.mapPos(o),r,o),text:n}}function rp(s,e){return s.nodeType!=1?0:(e&&s.childNodes[e-1].contentEditable=="false"?1:0)|(e{ie.from&&(t=!0)}),t}class ir extends ct{constructor(e){super(),this.height=e}toDOM(){let e=document.createElement("div");return e.className="cm-gap",this.updateDOM(e),e}eq(e){return e.height==this.height}updateDOM(e){return e.style.height=this.height+"px",!0}get editable(){return!0}get estimatedHeight(){return this.height}ignoreEvent(){return!1}}function up(s,e,t=1){let i=s.charCategorizer(e),n=s.doc.lineAt(e),r=e-n.from;if(n.length==0)return v.cursor(e);r==0?t=1:r==n.length&&(t=-1);let o=r,l=r;t<0?o=fe(n.text,r,!1):l=fe(n.text,r);let a=i(n.text.slice(o,l));for(;o>0;){let h=fe(n.text,o,!1);if(i(n.text.slice(h,o))!=a)break;o=h}for(;ls.defaultLineHeight*1.5){let l=s.viewState.heightOracle.textHeight,a=Math.floor((n-t.top-(s.defaultLineHeight-l)*.5)/l);r+=a*s.viewState.heightOracle.lineLength}let o=s.state.sliceDoc(t.from,t.to);return t.from+Qr(o,r,s.state.tabSize)}function to(s,e,t){let i=s.lineBlockAt(e);if(Array.isArray(i.type)){let n;for(let r of i.type){if(r.from>e)break;if(!(r.toe)return r;(!n||r.type==ge.Text&&(n.type!=r.type||(t<0?r.frome)))&&(n=r)}}return n||i}return i}function pp(s,e,t,i){let n=to(s,e.head,e.assoc||-1),r=!i||n.type!=ge.Text||!(s.lineWrapping||n.widgetLineBreaks)?null:s.coordsAtPos(e.assoc<0&&e.head>n.from?e.head-1:e.head);if(r){let o=s.dom.getBoundingClientRect(),l=s.textDirectionAt(n.from),a=s.posAtCoords({x:t==(l==J.LTR)?o.right-1:o.left+1,y:(r.top+r.bottom)/2});if(a!=null)return v.cursor(a,t?-1:1)}return v.cursor(t?n.to:n.from,t?-1:1)}function Xl(s,e,t,i){let n=s.state.doc.lineAt(e.head),r=s.bidiSpans(n),o=s.textDirectionAt(n.from);for(let l=e,a=null;;){let h=Qd(n,r,o,l,t),c=rc;if(!h){if(n.number==(t?s.state.doc.lines:1))return l;c=` +`,n=s.state.doc.line(n.number+(t?1:-1)),r=s.bidiSpans(n),h=s.visualLineSide(n,!t)}if(a){if(!a(c))return l}else{if(!i)return h;a=i(c)}l=h}}function mp(s,e,t){let i=s.state.charCategorizer(e),n=i(t);return r=>{let o=i(r);return n==ee.Space&&(n=o),n==o}}function gp(s,e,t,i){let n=e.head,r=t?1:-1;if(n==(t?s.state.doc.length:0))return v.cursor(n,e.assoc);let o=e.goalColumn,l,a=s.contentDOM.getBoundingClientRect(),h=s.coordsAtPos(n,e.assoc||((e.empty?t:e.head==e.from)?1:-1)),c=s.documentTop;if(h)o==null&&(o=h.left-a.left),l=r<0?h.top:h.bottom;else{let p=s.viewState.lineBlockAt(n);o==null&&(o=Math.min(a.right-a.left,s.defaultCharacterWidth*(n-p.from))),l=(r<0?p.top:p.bottom)+c}let f=a.left+o,u=s.viewState.heightOracle.textHeight>>1,d=i??u;for(let p=0;;p+=u){let m=l+(d+p)*r,g=io(s,{x:f,y:m},!1,r);if(t?m>a.bottom:ml:k{if(e>r&&en(s)),t.from,e.head>t.from?-1:1);return i==t.from?t:v.cursor(i,is.viewState.docHeight)return new st(s.state.doc.length,-1);if(h=s.elementAtHeight(a),i==null)break;if(h.type==ge.Text){if(i<0?h.tos.viewport.to)break;let u=s.docView.coordsAt(i<0?h.from:h.to,i>0?-1:1);if(u&&(i<0?u.top<=a+r:u.bottom>=a+r))break}let f=s.viewState.heightOracle.textHeight/2;a=i>0?h.bottom+f:h.top-f}if(s.viewport.from>=h.to||s.viewport.to<=h.from){if(t)return null;if(h.type==ge.Text){let f=dp(s,n,h,o,l);return new st(f,f==h.from?1:-1)}}if(h.type!=ge.Text)return a<(h.top+h.bottom)/2?new st(h.from,1):new st(h.to,-1);let c=s.docView.lineAt(h.from,2);return(!c||c.length!=h.length)&&(c=s.docView.lineAt(h.from,-2)),new xp(s,o,l,s.textDirectionAt(h.from)).scanTile(c,h.from)}class xp{constructor(e,t,i,n){this.view=e,this.x=t,this.y=i,this.baseDir=n,this.line=null,this.spans=null}bidiSpansAt(e){return(!this.line||this.line.from>e||this.line.to1||i.length&&(i[0].level!=this.baseDir||i[0].to+n.from>1;t:if(o.has(m)){let x=n+Math.floor(Math.random()*p);for(let k=0;k1)){if(k.bottomthis.y)(!h||h.top>k.top)&&(h=k),w=-1;else{let T=k.left>this.x?this.x-k.left:k.right(p+p+m)/3)return this.y=a.bottom-1,this.scan(e,t,!0);if(h&&h.top<(p+m+m)/3)return this.y=h.top+1,this.scan(e,t,!0)}let d=(l?this.dirAt(e[c],1):this.baseDir)==J.LTR;return{i:c,after:this.x>(u.left+u.right)/2==d}}scanText(e,t){let i=[];for(let r=0;r{let o=i[r]-t,l=i[r+1]-t;return Ji(e.dom,o,l).getClientRects()});return n.after?new st(i[n.i+1],-1):new st(i[n.i],1)}scanTile(e,t){if(!e.length)return new st(t,1);if(e.children.length==1){let l=e.children[0];if(l.isText())return this.scanText(l,t);if(l.isComposite())return this.scanTile(l,t)}let i=[t];for(let l=0,a=t;l{let a=e.children[l];return a.flags&48?null:(a.dom.nodeType==1?a.dom:Ji(a.dom,0,a.length)).getClientRects()}),r=e.children[n.i],o=i[n.i];return r.isText()?this.scanText(r,o):r.isComposite()?this.scanTile(r,o):n.after?new st(i[n.i+1],-1):new st(o,1)}}const ii="￿";class bp{constructor(e,t){this.points=e,this.view=t,this.text="",this.lineSeparator=t.state.facet(U.lineSeparator)}append(e){this.text+=e}lineBreak(){this.text+=ii}readRange(e,t){if(!e)return this;let i=e.parentNode;for(let n=e;;){this.findPointBefore(i,n);let r=this.text.length;this.readNode(n);let o=ie.get(n),l=n.nextSibling;if(l==t){o?.breakAfter&&!l&&i!=this.view.contentDOM&&this.lineBreak();break}let a=ie.get(l);(o&&a?o.breakAfter:(o?o.breakAfter:nn(n))||nn(l)&&(n.nodeName!="BR"||o?.isWidget())&&this.text.length>r)&&!kp(l,t)&&this.lineBreak(),n=l}return this.findPointBefore(i,t),this}readTextNode(e){let t=e.nodeValue;for(let i of this.points)i.node==e&&(i.pos=this.text.length+Math.min(i.offset,t.length));for(let i=0,n=this.lineSeparator?null:/\r\n?|\n/g;;){let r=-1,o=1,l;if(this.lineSeparator?(r=t.indexOf(this.lineSeparator,i),o=this.lineSeparator.length):(l=n.exec(t))&&(r=l.index,o=l[0].length),this.append(t.slice(i,r<0?t.length:r)),r<0)break;if(this.lineBreak(),o>1)for(let a of this.points)a.node==e&&a.pos>this.text.length&&(a.pos-=o-1);i=r+o}}readNode(e){let t=ie.get(e),i=t&&t.overrideDOMText;if(i!=null){this.findPointInside(e,i.length);for(let n=i.iter();!n.next().done;)n.lineBreak?this.lineBreak():this.append(n.value)}else e.nodeType==3?this.readTextNode(e):e.nodeName=="BR"?e.nextSibling&&this.lineBreak():e.nodeType==1&&this.readRange(e.firstChild,null)}findPointBefore(e,t){for(let i of this.points)i.node==e&&e.childNodes[i.offset]==t&&(i.pos=this.text.length)}findPointInside(e,t){for(let i of this.points)(e.nodeType==3?i.node==e:e.contains(i.node))&&(i.pos=this.text.length+(yp(e,i.node,i.offset)?t:0))}}function yp(s,e,t){for(;;){if(!e||t-1;let{impreciseHead:r,impreciseAnchor:o}=e.docView,l=e.state.selection;if(e.state.readOnly&&t>-1)this.newSel=null;else if(t>-1&&(this.bounds=Sc(e.docView.tile,t,i,0))){let a=r||o?[]:Sp(e),h=new bp(a,e);h.readRange(this.bounds.startDOM,this.bounds.endDOM),this.text=h.text,this.newSel=Op(a,this.bounds.from)}else{let a=e.observer.selectionRange,h=r&&r.node==a.focusNode&&r.offset==a.focusOffset||!_r(e.contentDOM,a.focusNode)?l.main.head:e.docView.posFromDOM(a.focusNode,a.focusOffset),c=o&&o.node==a.anchorNode&&o.offset==a.anchorOffset||!_r(e.contentDOM,a.anchorNode)?l.main.anchor:e.docView.posFromDOM(a.anchorNode,a.anchorOffset),f=e.viewport;if((W.ios||W.chrome)&&l.main.empty&&h!=c&&(f.from>0||f.to-1&&l.ranges.length>1)this.newSel=l.replaceRange(v.range(c,h));else if(e.lineWrapping&&c==h&&!(l.main.empty&&l.main.head==h)&&e.inputState.lastTouchTime>Date.now()-100){let u=e.coordsAtPos(h,-1),d=0;u&&(d=e.inputState.lastTouchY<=u.bottom?-1:1),this.newSel=v.create([v.cursor(h,d)])}else this.newSel=v.single(c,h)}}}function Sc(s,e,t,i){if(s.isComposite()){let n=-1,r=-1,o=-1,l=-1;for(let a=0,h=i,c=i;at)return Sc(f,e,t,h);if(u>=e&&n==-1&&(n=a,r=h),h>t&&f.dom.parentNode==s.dom){o=a,l=c;break}c=u,h=u+f.breakAfter}return{from:r,to:l<0?i+s.length:l,startDOM:(n?s.children[n-1].dom.nextSibling:null)||s.dom.firstChild,endDOM:o=0?s.children[o].dom:null}}else return s.isText()?{from:i,to:i+s.length,startDOM:s.dom,endDOM:s.dom.nextSibling}:null}function Oc(s,e){let t,{newSel:i}=e,{state:n}=s,r=n.selection.main,o=s.inputState.lastKeyTime>Date.now()-100?s.inputState.lastKeyCode:-1;if(e.bounds){let{from:l,to:a}=e.bounds,h=r.from,c=null;(o===8||W.android&&e.text.length=l&&r.to<=a&&(e.typeOver||f!=e.text)&&f.slice(0,r.from-l)==e.text.slice(0,r.from-l)&&f.slice(r.to-l)==e.text.slice(u=e.text.length-(f.length-(r.to-l)))?t={from:r.from,to:r.to,insert:Y.of(e.text.slice(r.from-l,u).split(ii))}:(d=Cc(f,e.text,h-l,c))&&(W.chrome&&o==13&&d.toB==d.from+2&&e.text.slice(d.from,d.toB)==ii+ii&&d.toB--,t={from:l+d.from,to:l+d.toA,insert:Y.of(e.text.slice(d.from,d.toB).split(ii))})}else i&&(!s.hasFocus&&n.facet(dt)||an(i,r))&&(i=null);if(!t&&!i)return!1;if((W.mac||W.android)&&t&&t.from==t.to&&t.from==r.head-1&&/^\. ?$/.test(t.insert.toString())&&s.contentDOM.getAttribute("autocorrect")=="off"?(i&&t.insert.length==2&&(i=v.single(i.main.anchor-1,i.main.head-1)),t={from:t.from,to:t.to,insert:Y.of([t.insert.toString().replace("."," ")])}):n.doc.lineAt(r.from).toDate.now()-50?t={from:r.from,to:r.to,insert:n.toText(s.inputState.insertingText)}:W.chrome&&t&&t.from==t.to&&t.from==r.head&&t.insert.toString()==` + `&&s.lineWrapping&&(i&&(i=v.single(i.main.anchor-1,i.main.head-1)),t={from:r.from,to:r.to,insert:Y.of([" "])}),t)return jo(s,t,i,o);if(i&&!an(i,r)){let l=!1,a="select";return s.inputState.lastSelectionTime>Date.now()-50&&(s.inputState.lastSelectionOrigin=="select"&&(l=!0),a=s.inputState.lastSelectionOrigin,a=="select.pointer"&&(i=vc(n.facet(fs).map(h=>h(s)),i))),s.dispatch({selection:i,scrollIntoView:l,userEvent:a}),!0}else return!1}function jo(s,e,t,i=-1){if(W.ios&&s.inputState.flushIOSKey(e))return!0;let n=s.state.selection.main;if(W.android&&(e.to==n.to&&(e.from==n.from||e.from==n.from-1&&s.state.sliceDoc(e.from,n.from)==" ")&&e.insert.length==1&&e.insert.lines==2&&ui(s.contentDOM,"Enter",13)||(e.from==n.from-1&&e.to==n.to&&e.insert.length==0||i==8&&e.insert.lengthn.head)&&ui(s.contentDOM,"Backspace",8)||e.from==n.from&&e.to==n.to+1&&e.insert.length==0&&ui(s.contentDOM,"Delete",46)))return!0;let r=e.insert.toString();s.inputState.composing>=0&&s.inputState.composing++;let o,l=()=>o||(o=vp(s,e,t));return s.state.facet(cc).some(a=>a(s,e.from,e.to,r,l))||s.dispatch(l()),!0}function vp(s,e,t){let i,n=s.state,r=n.selection.main,o=-1;if(e.from==e.to&&e.fromr.to){let a=e.fromf(s)),h,a);e.from==c&&(o=c)}if(o>-1)i={changes:e,selection:v.cursor(e.from+e.insert.length,-1)};else if(e.from>=r.from&&e.to<=r.to&&e.to-e.from>=(r.to-r.from)/3&&(!t||t.main.empty&&t.main.from==e.from+e.insert.length)&&s.inputState.composing<0){let a=r.frome.to?n.sliceDoc(e.to,r.to):"";i=n.replaceSelection(s.state.toText(a+e.insert.sliceString(0,void 0,s.state.lineBreak)+h))}else{let a=n.changes(e),h=t&&t.main.to<=a.newLength?t.main:void 0;if(n.selection.ranges.length>1&&(s.inputState.composing>=0||s.inputState.compositionPendingChange)&&e.to<=r.to+10&&e.to>=r.to-10){let c=s.state.sliceDoc(e.from,e.to),f,u=t&&wc(s,t.main.head);if(u){let p=e.insert.length-(e.to-e.from);f={from:u.from,to:u.to-p}}else f=s.state.doc.lineAt(r.head);let d=r.to-e.to;i=n.changeByRange(p=>{if(p.from==r.from&&p.to==r.to)return{changes:a,range:h||p.map(a)};let m=p.to-d,g=m-c.length;if(s.state.sliceDoc(g,m)!=c||m>=f.from&&g<=f.to)return{range:p};let x=n.changes({from:g,to:m,insert:e.insert}),k=p.to-r.to;return{changes:x,range:h?v.range(Math.max(0,h.anchor+k),Math.max(0,h.head+k)):p.map(x)}})}else i={changes:a,selection:h&&n.selection.replaceRange(h)}}let l="input.type";return(s.composing||s.inputState.compositionPendingChange&&s.inputState.compositionEndedAt>Date.now()-50)&&(s.inputState.compositionPendingChange=!1,l+=".compose",s.inputState.compositionFirstChange&&(l+=".start",s.inputState.compositionFirstChange=!1)),n.update(i,{userEvent:l,scrollIntoView:!0})}function Cc(s,e,t,i){let n=Math.min(s.length,e.length),r=0;for(;r0&&l>0&&s.charCodeAt(o-1)==e.charCodeAt(l-1);)o--,l--;if(i=="end"){let a=Math.max(0,r-Math.min(o,l));t-=o+a-r}if(o=o?r-t:0;r-=a,l=r+(l-o),o=r}else if(l=l?r-t:0;r-=a,o=r+(o-l),l=r}return{from:r,toA:o,toB:l}}function Sp(s){let e=[];if(s.root.activeElement!=s.contentDOM)return e;let{anchorNode:t,anchorOffset:i,focusNode:n,focusOffset:r}=s.observer.selectionRange;return t&&(e.push(new Ul(t,i)),(n!=t||r!=i)&&e.push(new Ul(n,r))),e}function Op(s,e){if(s.length==0)return null;let t=s[0].pos,i=s.length==2?s[1].pos:t;return t>-1&&i>-1?v.single(t+e,i+e):null}function an(s,e){return e.head==s.main.head&&e.anchor==s.main.anchor}class Cp{setSelectionOrigin(e){this.lastSelectionOrigin=e,this.lastSelectionTime=Date.now()}constructor(e){this.view=e,this.lastKeyCode=0,this.lastKeyTime=0,this.lastTouchTime=0,this.lastTouchX=0,this.lastTouchY=0,this.lastFocusTime=0,this.lastScrollTop=0,this.lastScrollLeft=0,this.lastWheelEvent=0,this.pendingIOSKey=void 0,this.tabFocusMode=-1,this.lastSelectionOrigin=null,this.lastSelectionTime=0,this.lastContextMenu=0,this.scrollHandlers=[],this.handlers=Object.create(null),this.composing=-1,this.compositionFirstChange=null,this.compositionEndedAt=0,this.compositionPendingKey=!1,this.compositionPendingChange=!1,this.insertingText="",this.insertingTextAt=0,this.mouseSelection=null,this.draggedContent=null,this.handleEvent=this.handleEvent.bind(this),this.notifiedFocused=e.hasFocus,W.safari&&e.contentDOM.addEventListener("input",()=>null),W.gecko&&Hp(e.contentDOM.ownerDocument)}handleEvent(e){!Ep(this.view,e)||this.ignoreDuringComposition(e)||e.type=="keydown"&&this.keydown(e)||(this.view.updateState!=0?Promise.resolve().then(()=>this.runHandlers(e.type,e)):this.runHandlers(e.type,e))}runHandlers(e,t){let i=this.handlers[e];if(i){for(let n of i.observers)n(this.view,t);for(let n of i.handlers){if(t.defaultPrevented)break;if(n(this.view,t)){t.preventDefault();break}}}}ensureHandlers(e){let t=Ap(e),i=this.handlers,n=this.view.contentDOM;for(let r in t)if(r!="scroll"){let o=!t[r].handlers.length,l=i[r];l&&o!=!l.handlers.length&&(n.removeEventListener(r,this.handleEvent),l=null),l||n.addEventListener(r,this.handleEvent,{passive:o})}for(let r in i)r!="scroll"&&!t[r]&&n.removeEventListener(r,this.handleEvent);this.handlers=t}keydown(e){if(this.lastKeyCode=e.keyCode,this.lastKeyTime=Date.now(),e.keyCode==9&&this.tabFocusMode>-1&&(!this.tabFocusMode||Date.now()<=this.tabFocusMode))return!0;if(this.tabFocusMode>0&&e.keyCode!=27&&Mc.indexOf(e.keyCode)<0&&(this.tabFocusMode=-1),W.android&&W.chrome&&!e.synthetic&&(e.keyCode==13||e.keyCode==8))return this.view.observer.delayAndroidKey(e.key,e.keyCode),!0;let t;return W.ios&&!e.synthetic&&!e.altKey&&!e.metaKey&&!e.shiftKey&&((t=Ac.find(i=>i.keyCode==e.keyCode))&&!e.ctrlKey||Mp.indexOf(e.key)>-1&&e.ctrlKey)?(this.pendingIOSKey=t||e,setTimeout(()=>this.flushIOSKey(),250),!0):(e.keyCode!=229&&this.view.observer.forceFlush(),!1)}flushIOSKey(e){let t=this.pendingIOSKey;return!t||t.key=="Enter"&&e&&e.from0?!0:W.safari&&!W.ios&&this.compositionPendingKey&&Date.now()-this.compositionEndedAt<100?(this.compositionPendingKey=!1,!0):!1}startMouseSelection(e){this.mouseSelection&&this.mouseSelection.destroy(),this.mouseSelection=e}update(e){this.view.observer.update(e),this.mouseSelection&&this.mouseSelection.update(e),this.draggedContent&&e.docChanged&&(this.draggedContent=this.draggedContent.map(e.changes)),e.transactions.length&&(this.lastKeyCode=this.lastSelectionTime=0)}destroy(){this.mouseSelection&&this.mouseSelection.destroy()}}function Yl(s,e){return(t,i)=>{try{return e.call(s,i,t)}catch(n){Pe(t.state,n)}}}function Ap(s){let e=Object.create(null);function t(i){return e[i]||(e[i]={observers:[],handlers:[]})}for(let i of s){let n=i.spec,r=n&&n.plugin.domEventHandlers,o=n&&n.plugin.domEventObservers;if(r)for(let l in r){let a=r[l];a&&t(l).handlers.push(Yl(i.value,a))}if(o)for(let l in o){let a=o[l];a&&t(l).observers.push(Yl(i.value,a))}}for(let i in Xe)t(i).handlers.push(Xe[i]);for(let i in De)t(i).observers.push(De[i]);return e}const Ac=[{key:"Backspace",keyCode:8,inputType:"deleteContentBackward"},{key:"Enter",keyCode:13,inputType:"insertParagraph"},{key:"Enter",keyCode:13,inputType:"insertLineBreak"},{key:"Delete",keyCode:46,inputType:"deleteContentForward"}],Mp="dthko",Mc=[16,17,18,20,91,92,224,225],Os=6;function Cs(s){return Math.max(0,s)*.7+8}function Pp(s,e){return Math.max(Math.abs(s.clientX-e.clientX),Math.abs(s.clientY-e.clientY))}class Tp{constructor(e,t,i,n){this.view=e,this.startEvent=t,this.style=i,this.mustSelect=n,this.scrollSpeed={x:0,y:0},this.scrolling=-1,this.lastEvent=t,this.scrollParents=Kh(e.contentDOM),this.atoms=e.state.facet(fs).map(o=>o(e));let r=e.contentDOM.ownerDocument;r.addEventListener("mousemove",this.move=this.move.bind(this)),r.addEventListener("mouseup",this.up=this.up.bind(this)),this.extend=t.shiftKey,this.multiple=e.state.facet(U.allowMultipleSelections)&&Dp(e,t),this.dragging=Bp(e,t)&&Dc(t)==1?null:!1}start(e){this.dragging===!1&&this.select(e)}move(e){if(e.buttons==0)return this.destroy();if(this.dragging||this.dragging==null&&Pp(this.startEvent,e)<10)return;this.select(this.lastEvent=e);let t=0,i=0,n=0,r=0,o=this.view.win.innerWidth,l=this.view.win.innerHeight;this.scrollParents.x&&({left:n,right:o}=this.scrollParents.x.getBoundingClientRect()),this.scrollParents.y&&({top:r,bottom:l}=this.scrollParents.y.getBoundingClientRect());let a=$o(this.view);e.clientX-a.left<=n+Os?t=-Cs(n-e.clientX):e.clientX+a.right>=o-Os&&(t=Cs(e.clientX-o)),e.clientY-a.top<=r+Os?i=-Cs(r-e.clientY):e.clientY+a.bottom>=l-Os&&(i=Cs(e.clientY-l)),this.setScrollSpeed(t,i)}up(e){this.dragging==null&&this.select(this.lastEvent),this.dragging||e.preventDefault(),this.destroy()}destroy(){this.setScrollSpeed(0,0);let e=this.view.contentDOM.ownerDocument;e.removeEventListener("mousemove",this.move),e.removeEventListener("mouseup",this.up),this.view.inputState.mouseSelection=this.view.inputState.draggedContent=null}setScrollSpeed(e,t){this.scrollSpeed={x:e,y:t},e||t?this.scrolling<0&&(this.scrolling=setInterval(()=>this.scroll(),50)):this.scrolling>-1&&(clearInterval(this.scrolling),this.scrolling=-1)}scroll(){let{x:e,y:t}=this.scrollSpeed;e&&this.scrollParents.x&&(this.scrollParents.x.scrollLeft+=e,e=0),t&&this.scrollParents.y&&(this.scrollParents.y.scrollTop+=t,t=0),(e||t)&&this.view.win.scrollBy(e,t),this.dragging===!1&&this.select(this.lastEvent)}select(e){let{view:t}=this,i=vc(this.atoms,this.style.get(e,this.extend,this.multiple));(this.mustSelect||!i.eq(t.state.selection,this.dragging===!1))&&this.view.dispatch({selection:i,userEvent:"select.pointer"}),this.mustSelect=!1}update(e){e.transactions.some(t=>t.isUserEvent("input.type"))?this.destroy():this.style.update(e)&&setTimeout(()=>this.select(this.lastEvent),20)}}function Dp(s,e){let t=s.state.facet(oc);return t.length?t[0](e):W.mac?e.metaKey:e.ctrlKey}function Rp(s,e){let t=s.state.facet(lc);return t.length?t[0](e):W.mac?!e.altKey:!e.ctrlKey}function Bp(s,e){let{main:t}=s.state.selection;if(t.empty)return!1;let i=Ki(s.root);if(!i||i.rangeCount==0)return!0;let n=i.getRangeAt(0).getClientRects();for(let r=0;r=e.clientX&&o.top<=e.clientY&&o.bottom>=e.clientY)return!0}return!1}function Ep(s,e){if(!e.bubbles)return!0;if(e.defaultPrevented)return!1;for(let t=e.target,i;t!=s.contentDOM;t=t.parentNode)if(!t||t.nodeType==11||(i=ie.get(t))&&i.isWidget()&&!i.isHidden&&i.widget.ignoreEvent(e))return!1;return!0}const Xe=Object.create(null),De=Object.create(null),Pc=W.ie&&W.ie_version<15||W.ios&&W.webkit_version<604;function Lp(s){let e=s.dom.parentNode;if(!e)return;let t=e.appendChild(document.createElement("textarea"));t.style.cssText="position: fixed; left: -10000px; top: 10px",t.focus(),setTimeout(()=>{s.focus(),t.remove(),Tc(s,t.value)},50)}function Nn(s,e,t){for(let i of s.facet(e))t=i(t,s);return t}function Tc(s,e){e=Nn(s.state,Vo,e);let{state:t}=s,i,n=1,r=t.toText(e),o=r.lines==t.selection.ranges.length;if(so!=null&&t.selection.ranges.every(a=>a.empty)&&so==r.toString()){let a=-1;i=t.changeByRange(h=>{let c=t.doc.lineAt(h.from);if(c.from==a)return{range:h};a=c.from;let f=t.toText((o?r.line(n++).text:e)+t.lineBreak);return{changes:{from:c.from,insert:f},range:v.cursor(h.from+f.length)}})}else o?i=t.changeByRange(a=>{let h=r.line(n++);return{changes:{from:a.from,to:a.to,insert:h.text},range:v.cursor(a.from+h.length)}}):i=t.replaceSelection(r);s.dispatch(i,{userEvent:"input.paste",scrollIntoView:!0})}De.scroll=s=>{s.inputState.lastScrollTop=s.scrollDOM.scrollTop,s.inputState.lastScrollLeft=s.scrollDOM.scrollLeft};De.wheel=De.mousewheel=s=>{s.inputState.lastWheelEvent=Date.now()};Xe.keydown=(s,e)=>(s.inputState.setSelectionOrigin("select"),e.keyCode==27&&s.inputState.tabFocusMode!=0&&(s.inputState.tabFocusMode=Date.now()+2e3),!1);De.touchstart=(s,e)=>{let t=s.inputState,i=e.targetTouches[0];t.lastTouchTime=Date.now(),i&&(t.lastTouchX=i.clientX,t.lastTouchY=i.clientY),t.setSelectionOrigin("select.pointer")};De.touchmove=s=>{s.inputState.setSelectionOrigin("select.pointer")};Xe.mousedown=(s,e)=>{if(s.observer.flush(),s.inputState.lastTouchTime>Date.now()-2e3)return!1;let t=null;for(let i of s.state.facet(ac))if(t=i(s,e),t)break;if(!t&&e.button==0&&(t=Ip(s,e)),t){let i=!s.hasFocus;s.inputState.startMouseSelection(new Tp(s,e,t,i)),i&&s.observer.ignore(()=>{Gh(s.contentDOM);let r=s.root.activeElement;r&&!r.contains(s.contentDOM)&&r.blur()});let n=s.inputState.mouseSelection;if(n)return n.start(e),n.dragging===!1}else s.inputState.setSelectionOrigin("select.pointer");return!1};function _l(s,e,t,i){if(i==1)return v.cursor(e,t);if(i==2)return up(s.state,e,t);{let n=s.docView.lineAt(e,t),r=s.state.doc.lineAt(n?n.posAtEnd:e),o=n?n.posAtStart:r.from,l=n?n.posAtEnd:r.to;return lDate.now()-400&&Math.abs(e.clientX-s.clientX)<2&&Math.abs(e.clientY-s.clientY)<2?(Gl+1)%3:1}function Ip(s,e){let t=s.posAndSideAtCoords({x:e.clientX,y:e.clientY},!1),i=Dc(e),n=s.state.selection;return{update(r){r.docChanged&&(t.pos=r.changes.mapPos(t.pos),n=n.map(r.changes))},get(r,o,l){let a=s.posAndSideAtCoords({x:r.clientX,y:r.clientY},!1),h,c=_l(s,a.pos,a.assoc,i);if(t.pos!=a.pos&&!o){let f=_l(s,t.pos,t.assoc,i),u=Math.min(f.from,c.from),d=Math.max(f.to,c.to);c=u1&&(h=Wp(n,a.pos))?h:l?n.addRange(c):v.create([c])}}}function Wp(s,e){for(let t=0;t=e)return v.create(s.ranges.slice(0,t).concat(s.ranges.slice(t+1)),s.mainIndex==t?0:s.mainIndex-(s.mainIndex>t?1:0))}return null}Xe.dragstart=(s,e)=>{let{selection:{main:t}}=s.state;if(e.target.draggable){let n=s.docView.tile.nearest(e.target);if(n&&n.isWidget()){let r=n.posAtStart,o=r+n.length;(r>=t.to||o<=t.from)&&(t=v.range(r,o))}}let{inputState:i}=s;return i.mouseSelection&&(i.mouseSelection.dragging=!0),i.draggedContent=t,e.dataTransfer&&(e.dataTransfer.setData("Text",Nn(s.state,Ho,s.state.sliceDoc(t.from,t.to))),e.dataTransfer.effectAllowed="copyMove"),!1};Xe.dragend=s=>(s.inputState.draggedContent=null,!1);function Zl(s,e,t,i){if(t=Nn(s.state,Vo,t),!t)return;let n=s.posAtCoords({x:e.clientX,y:e.clientY},!1),{draggedContent:r}=s.inputState,o=i&&r&&Rp(s,e)?{from:r.from,to:r.to}:null,l={from:n,insert:t},a=s.state.changes(o?[o,l]:l);s.focus(),s.dispatch({changes:a,selection:{anchor:a.mapPos(n,-1),head:a.mapPos(n,1)},userEvent:o?"move.drop":"input.drop"}),s.inputState.draggedContent=null}Xe.drop=(s,e)=>{if(!e.dataTransfer)return!1;if(s.state.readOnly)return!0;let t=e.dataTransfer.files;if(t&&t.length){let i=Array(t.length),n=0,r=()=>{++n==t.length&&Zl(s,e,i.filter(o=>o!=null).join(s.state.lineBreak),!1)};for(let o=0;o{/[\x00-\x08\x0e-\x1f]{2}/.test(l.result)||(i[o]=l.result),r()},l.readAsText(t[o])}return!0}else{let i=e.dataTransfer.getData("Text");if(i)return Zl(s,e,i,!0),!0}return!1};Xe.paste=(s,e)=>{if(s.state.readOnly)return!0;s.observer.flush();let t=Pc?null:e.clipboardData;return t?(Tc(s,t.getData("text/plain")||t.getData("text/uri-list")),!0):(Lp(s),!1)};function Fp(s,e){let t=s.dom.parentNode;if(!t)return;let i=t.appendChild(document.createElement("textarea"));i.style.cssText="position: fixed; left: -10000px; top: 10px",i.value=e,i.focus(),i.selectionEnd=e.length,i.selectionStart=0,setTimeout(()=>{i.remove(),s.focus()},50)}function Vp(s){let e=[],t=[],i=!1;for(let n of s.selection.ranges)n.empty||(e.push(s.sliceDoc(n.from,n.to)),t.push(n));if(!e.length){let n=-1;for(let{from:r}of s.selection.ranges){let o=s.doc.lineAt(r);o.number>n&&(e.push(o.text),t.push({from:o.from,to:Math.min(s.doc.length,o.to+1)})),n=o.number}i=!0}return{text:Nn(s,Ho,e.join(s.lineBreak)),ranges:t,linewise:i}}let so=null;Xe.copy=Xe.cut=(s,e)=>{if(!Vi(s.contentDOM,s.observer.selectionRange))return!1;let{text:t,ranges:i,linewise:n}=Vp(s.state);if(!t&&!n)return!1;so=n?t:null,e.type=="cut"&&!s.state.readOnly&&s.dispatch({changes:i,scrollIntoView:!0,userEvent:"delete.cut"});let r=Pc?null:e.clipboardData;return r?(r.clearData(),r.setData("text/plain",t),!0):(Fp(s,t),!1)};const Rc=at.define();function Bc(s,e){let t=[];for(let i of s.facet(fc)){let n=i(s,e);n&&t.push(n)}return t.length?s.update({effects:t,annotations:Rc.of(!0)}):null}function Ec(s){setTimeout(()=>{let e=s.hasFocus;if(e!=s.inputState.notifiedFocused){let t=Bc(s.state,e);t?s.dispatch(t):s.update([])}},10)}De.focus=s=>{s.inputState.lastFocusTime=Date.now(),!s.scrollDOM.scrollTop&&(s.inputState.lastScrollTop||s.inputState.lastScrollLeft)&&(s.scrollDOM.scrollTop=s.inputState.lastScrollTop,s.scrollDOM.scrollLeft=s.inputState.lastScrollLeft),Ec(s)};De.blur=s=>{s.observer.clearSelectionRange(),Ec(s)};De.compositionstart=De.compositionupdate=s=>{s.observer.editContext||(s.inputState.compositionFirstChange==null&&(s.inputState.compositionFirstChange=!0),s.inputState.composing<0&&(s.inputState.composing=0))};De.compositionend=s=>{s.observer.editContext||(s.inputState.composing=-1,s.inputState.compositionEndedAt=Date.now(),s.inputState.compositionPendingKey=!0,s.inputState.compositionPendingChange=s.observer.pendingRecords().length>0,s.inputState.compositionFirstChange=null,W.chrome&&W.android?s.observer.flushSoon():s.inputState.compositionPendingChange?Promise.resolve().then(()=>s.observer.flush()):setTimeout(()=>{s.inputState.composing<0&&s.docView.hasComposition&&s.update([])},50))};De.contextmenu=s=>{s.inputState.lastContextMenu=Date.now()};Xe.beforeinput=(s,e)=>{var t,i;if((e.inputType=="insertText"||e.inputType=="insertCompositionText")&&(s.inputState.insertingText=e.data,s.inputState.insertingTextAt=Date.now()),e.inputType=="insertReplacementText"&&s.observer.editContext){let r=(t=e.dataTransfer)===null||t===void 0?void 0:t.getData("text/plain"),o=e.getTargetRanges();if(r&&o.length){let l=o[0],a=s.posAtDOM(l.startContainer,l.startOffset),h=s.posAtDOM(l.endContainer,l.endOffset);return jo(s,{from:a,to:h,insert:s.state.toText(r)},null),!0}}let n;if(W.chrome&&W.android&&(n=Ac.find(r=>r.inputType==e.inputType))&&(s.observer.delayAndroidKey(n.key,n.keyCode),n.key=="Backspace"||n.key=="Delete")){let r=((i=window.visualViewport)===null||i===void 0?void 0:i.height)||0;setTimeout(()=>{var o;(((o=window.visualViewport)===null||o===void 0?void 0:o.height)||0)>r+10&&s.hasFocus&&(s.contentDOM.blur(),s.focus())},100)}return W.ios&&e.inputType=="deleteContentForward"&&s.observer.flushSoon(),W.safari&&e.inputType=="insertText"&&s.inputState.composing>=0&&setTimeout(()=>De.compositionend(s,e),20),!1};const ea=new Set;function Hp(s){ea.has(s)||(ea.add(s),s.addEventListener("copy",()=>{}),s.addEventListener("cut",()=>{}))}const ta=["pre-wrap","normal","pre-line","break-spaces"];let ki=!1;function ia(){ki=!1}class zp{constructor(e){this.lineWrapping=e,this.doc=Y.empty,this.heightSamples={},this.lineHeight=14,this.charWidth=7,this.textHeight=14,this.lineLength=30}heightForGap(e,t){let i=this.doc.lineAt(t).number-this.doc.lineAt(e).number+1;return this.lineWrapping&&(i+=Math.max(0,Math.ceil((t-e-i*this.lineLength*.5)/this.lineLength))),this.lineHeight*i}heightForLine(e){return this.lineWrapping?(1+Math.max(0,Math.ceil((e-this.lineLength)/Math.max(1,this.lineLength-5))))*this.lineHeight:this.lineHeight}setDoc(e){return this.doc=e,this}mustRefreshForWrapping(e){return ta.indexOf(e)>-1!=this.lineWrapping}mustRefreshForHeights(e){let t=!1;for(let i=0;i-1,a=Math.abs(t-this.lineHeight)>.3||this.lineWrapping!=l;if(this.lineWrapping=l,this.lineHeight=t,this.charWidth=i,this.textHeight=n,this.lineLength=r,a){this.heightSamples={};for(let h=0;h0}set outdated(e){this.flags=(e?2:0)|this.flags&-3}setHeight(e){this.height!=e&&(Math.abs(this.height-e)>Xs&&(ki=!0),this.height=e)}replace(e,t,i){return Oe.of(i)}decomposeLeft(e,t){t.push(this)}decomposeRight(e,t){t.push(this)}applyChanges(e,t,i,n){let r=this,o=i.doc;for(let l=n.length-1;l>=0;l--){let{fromA:a,toA:h,fromB:c,toB:f}=n[l],u=r.lineAt(a,Z.ByPosNoHeight,i.setDoc(t),0,0),d=u.to>=h?u:r.lineAt(h,Z.ByPosNoHeight,i,0,0);for(f+=d.to-h,h=d.to;l>0&&u.from<=n[l-1].toA;)a=n[l-1].fromA,c=n[l-1].fromB,l--,ar*2){let l=e[t-1];l.break?e.splice(--t,1,l.left,null,l.right):e.splice(--t,1,l.left,l.right),i+=1+l.break,n-=l.size}else if(r>n*2){let l=e[i];l.break?e.splice(i,1,l.left,null,l.right):e.splice(i,1,l.left,l.right),i+=2+l.break,r-=l.size}else break;else if(n=r&&o(this.lineAt(0,Z.ByPos,i,n,r))}setMeasuredHeight(e){let t=e.heights[e.index++];t<0?(this.spaceAbove=-t,t=e.heights[e.index++]):this.spaceAbove=0,this.setHeight(t)}updateHeight(e,t=0,i=!1,n){return n&&n.from<=t&&n.more&&this.setMeasuredHeight(n),this.outdated=!1,this}toString(){return`block(${this.length})`}}class Ne extends Lc{constructor(e,t,i){super(e,t,null),this.collapsed=0,this.widgetHeight=0,this.breaks=0,this.spaceAbove=i}mainBlock(e,t){return new $e(t,this.length,e+this.spaceAbove,this.height-this.spaceAbove,this.breaks)}replace(e,t,i){let n=i[0];return i.length==1&&(n instanceof Ne||n instanceof pe&&n.flags&4)&&Math.abs(this.length-n.length)<10?(n instanceof pe?n=new Ne(n.length,this.height,this.spaceAbove):n.height=this.height,this.outdated||(n.outdated=!1),n):Oe.of(i)}updateHeight(e,t=0,i=!1,n){return n&&n.from<=t&&n.more?this.setMeasuredHeight(n):(i||this.outdated)&&(this.spaceAbove=0,this.setHeight(Math.max(this.widgetHeight,e.heightForLine(this.length-this.collapsed))+this.breaks*e.lineHeight)),this.outdated=!1,this}toString(){return`line(${this.length}${this.collapsed?-this.collapsed:""}${this.widgetHeight?":"+this.widgetHeight:""})`}}class pe extends Oe{constructor(e){super(e,0)}heightMetrics(e,t){let i=e.doc.lineAt(t).number,n=e.doc.lineAt(t+this.length).number,r=n-i+1,o,l=0;if(e.lineWrapping){let a=Math.min(this.height,e.lineHeight*r);o=a/r,this.length>r+1&&(l=(this.height-a)/(this.length-r-1))}else o=this.height/r;return{firstLine:i,lastLine:n,perLine:o,perChar:l}}blockAt(e,t,i,n){let{firstLine:r,lastLine:o,perLine:l,perChar:a}=this.heightMetrics(t,n);if(t.lineWrapping){let h=n+(e0){let r=i[i.length-1];r instanceof pe?i[i.length-1]=new pe(r.length+n):i.push(null,new pe(n-1))}if(e>0){let r=i[0];r instanceof pe?i[0]=new pe(e+r.length):i.unshift(new pe(e-1),null)}return Oe.of(i)}decomposeLeft(e,t){t.push(new pe(e-1),null)}decomposeRight(e,t){t.push(null,new pe(this.length-e-1))}updateHeight(e,t=0,i=!1,n){let r=t+this.length;if(n&&n.from<=t+this.length&&n.more){let o=[],l=Math.max(t,n.from),a=-1;for(n.from>t&&o.push(new pe(n.from-t-1).updateHeight(e,t));l<=r&&n.more;){let c=e.doc.lineAt(l).length;o.length&&o.push(null);let f=n.heights[n.index++],u=0;f<0&&(u=-f,f=n.heights[n.index++]),a==-1?a=f:Math.abs(f-a)>=Xs&&(a=-2);let d=new Ne(c,f,u);d.outdated=!1,o.push(d),l+=c+1}l<=r&&o.push(null,new pe(r-l).updateHeight(e,l));let h=Oe.of(o);return(a<0||Math.abs(h.height-this.height)>=Xs||Math.abs(a-this.heightMetrics(e,t).perLine)>=Xs)&&(ki=!0),hn(this,h)}else(i||this.outdated)&&(this.setHeight(e.heightForGap(t,t+this.length)),this.outdated=!1);return this}toString(){return`gap(${this.length})`}}class jp extends Oe{constructor(e,t,i){super(e.length+t+i.length,e.height+i.height,t|(e.outdated||i.outdated?2:0)),this.left=e,this.right=i,this.size=e.size+i.size}get break(){return this.flags&1}blockAt(e,t,i,n){let r=i+this.left.height;return el))return h;let c=t==Z.ByPosNoHeight?Z.ByPosNoHeight:Z.ByPos;return a?h.join(this.right.lineAt(l,c,i,o,l)):this.left.lineAt(l,c,i,n,r).join(h)}forEachLine(e,t,i,n,r,o){let l=n+this.left.height,a=r+this.left.length+this.break;if(this.break)e=a&&this.right.forEachLine(e,t,i,l,a,o);else{let h=this.lineAt(a,Z.ByPos,i,n,r);e=e&&h.from<=t&&o(h),t>h.to&&this.right.forEachLine(h.to+1,t,i,l,a,o)}}replace(e,t,i){let n=this.left.length+this.break;if(tthis.left.length)return this.balanced(this.left,this.right.replace(e-n,t-n,i));let r=[];e>0&&this.decomposeLeft(e,r);let o=r.length;for(let l of i)r.push(l);if(e>0&&sa(r,o-1),t=i&&t.push(null)),e>i&&this.right.decomposeLeft(e-i,t)}decomposeRight(e,t){let i=this.left.length,n=i+this.break;if(e>=n)return this.right.decomposeRight(e-n,t);e2*t.size||t.size>2*e.size?Oe.of(this.break?[e,null,t]:[e,t]):(this.left=hn(this.left,e),this.right=hn(this.right,t),this.setHeight(e.height+t.height),this.outdated=e.outdated||t.outdated,this.size=e.size+t.size,this.length=e.length+this.break+t.length,this)}updateHeight(e,t=0,i=!1,n){let{left:r,right:o}=this,l=t+r.length+this.break,a=null;return n&&n.from<=t+r.length&&n.more?a=r=r.updateHeight(e,t,i,n):r.updateHeight(e,t,i),n&&n.from<=l+o.length&&n.more?a=o=o.updateHeight(e,l,i,n):o.updateHeight(e,l,i),a?this.balanced(r,o):(this.height=this.left.height+this.right.height,this.outdated=!1,this)}toString(){return this.left+(this.break?" ":"-")+this.right}}function sa(s,e){let t,i;s[e]==null&&(t=s[e-1])instanceof pe&&(i=s[e+1])instanceof pe&&s.splice(e-1,3,new pe(t.length+1+i.length))}const qp=5;class qo{constructor(e,t){this.pos=e,this.oracle=t,this.nodes=[],this.lineStart=-1,this.lineEnd=-1,this.covering=null,this.writtenTo=e}get isCovered(){return this.covering&&this.nodes[this.nodes.length-1]==this.covering}span(e,t){if(this.lineStart>-1){let i=Math.min(t,this.lineEnd),n=this.nodes[this.nodes.length-1];n instanceof Ne?n.length+=i-this.pos:(i>this.pos||!this.isCovered)&&this.nodes.push(new Ne(i-this.pos,-1,0)),this.writtenTo=i,t>i&&(this.nodes.push(null),this.writtenTo++,this.lineStart=-1)}this.pos=t}point(e,t,i){if(e=qp)&&this.addLineDeco(n,r,o)}else t>e&&this.span(e,t);this.lineEnd>-1&&this.lineEnd-1)return;let{from:e,to:t}=this.oracle.doc.lineAt(this.pos);this.lineStart=e,this.lineEnd=t,this.writtenToe&&this.nodes.push(new Ne(this.pos-e,-1,0)),this.writtenTo=this.pos}blankContent(e,t){let i=new pe(t-e);return this.oracle.doc.lineAt(e).to==t&&(i.flags|=4),i}ensureLine(){this.enterLine();let e=this.nodes.length?this.nodes[this.nodes.length-1]:null;if(e instanceof Ne)return e;let t=new Ne(0,-1,0);return this.nodes.push(t),t}addBlock(e){this.enterLine();let t=e.deco;t&&t.startSide>0&&!this.isCovered&&this.ensureLine(),this.nodes.push(e),this.writtenTo=this.pos=this.pos+e.length,t&&t.endSide>0&&(this.covering=e)}addLineDeco(e,t,i){let n=this.ensureLine();n.length+=i,n.collapsed+=i,n.widgetHeight=Math.max(n.widgetHeight,e),n.breaks+=t,this.writtenTo=this.pos=this.pos+i}finish(e){let t=this.nodes.length==0?null:this.nodes[this.nodes.length-1];this.lineStart>-1&&!(t instanceof Ne)&&!this.isCovered?this.nodes.push(new Ne(0,-1,0)):(this.writtenToc.clientHeight||c.scrollWidth>c.clientWidth)&&f.overflow!="visible"){let u=c.getBoundingClientRect();r=Math.max(r,u.left),o=Math.min(o,u.right),l=Math.max(l,u.top),a=Math.min(h==s.parentNode?n.innerHeight:a,u.bottom)}h=f.position=="absolute"||f.position=="fixed"?c.offsetParent:c.parentNode}else if(h.nodeType==11)h=h.host;else break;return{left:r-t.left,right:Math.max(r,o)-t.left,top:l-(t.top+e),bottom:Math.max(l,a)-(t.top+e)}}function _p(s){let e=s.getBoundingClientRect(),t=s.ownerDocument.defaultView||window;return e.left0&&e.top0}function Kp(s,e){let t=s.getBoundingClientRect();return{left:0,right:t.right-t.left,top:e,bottom:t.bottom-(t.top+e)}}class nr{constructor(e,t,i,n){this.from=e,this.to=t,this.size=i,this.displaySize=n}static same(e,t){if(e.length!=t.length)return!1;for(let i=0;itypeof n!="function"&&n.class=="cm-lineWrapping");this.heightOracle=new zp(i),this.stateDeco=oa(t),this.heightMap=Oe.empty().applyChanges(this.stateDeco,Y.empty,this.heightOracle.setDoc(t.doc),[new We(0,0,0,t.doc.length)]);for(let n=0;n<2&&(this.viewport=this.getViewport(0,null),!!this.updateForViewport());n++);this.updateViewportLines(),this.lineGaps=this.ensureLineGaps([]),this.lineGapDeco=z.set(this.lineGaps.map(n=>n.draw(this,!1))),this.scrollParent=e.scrollDOM,this.computeVisibleRanges()}updateForViewport(){let e=[this.viewport],{main:t}=this.state.selection;for(let i=0;i<=1;i++){let n=i?t.head:t.anchor;if(!e.some(({from:r,to:o})=>n>=r&&n<=o)){let{from:r,to:o}=this.lineBlockAt(n);e.push(new As(r,o))}}return this.viewports=e.sort((i,n)=>i.from-n.from),this.updateScaler()}updateScaler(){let e=this.scaler;return this.scaler=this.heightMap.height<=7e6?ra:new Xo(this.heightOracle,this.heightMap,this.viewports),e.eq(this.scaler)?0:2}updateViewportLines(){this.viewportLines=[],this.heightMap.forEachLine(this.viewport.from,this.viewport.to,this.heightOracle.setDoc(this.state.doc),0,0,e=>{this.viewportLines.push(Ni(e,this.scaler))})}update(e,t=null){this.state=e.state;let i=this.stateDeco;this.stateDeco=oa(this.state);let n=e.changedRanges,r=We.extendWithRanges(n,Xp(i,this.stateDeco,e?e.changes:ae.empty(this.state.doc.length))),o=this.heightMap.height,l=this.scrolledToBottom?null:this.scrollAnchorAt(this.scrollOffset);ia(),this.heightMap=this.heightMap.applyChanges(this.stateDeco,e.startState.doc,this.heightOracle.setDoc(this.state.doc),r),(this.heightMap.height!=o||ki)&&(e.flags|=2),l?(this.scrollAnchorPos=e.changes.mapPos(l.from,-1),this.scrollAnchorHeight=l.top):(this.scrollAnchorPos=-1,this.scrollAnchorHeight=o);let a=r.length?this.mapViewport(this.viewport,e.changes):this.viewport;(t&&(t.range.heada.to)||!this.viewportIsAppropriate(a))&&(a=this.getViewport(0,t));let h=a.from!=this.viewport.from||a.to!=this.viewport.to;this.viewport=a,e.flags|=this.updateForViewport(),(h||!e.changes.empty||e.flags&2)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(this.mapLineGaps(this.lineGaps,e.changes))),e.flags|=this.computeVisibleRanges(e.changes),t&&(this.scrollTarget=t),!this.mustEnforceCursorAssoc&&(e.selectionSet||e.focusChanged)&&e.view.lineWrapping&&e.state.selection.main.empty&&e.state.selection.main.assoc&&!e.state.facet(dc)&&(this.mustEnforceCursorAssoc=!0)}measure(){let{view:e}=this,t=e.contentDOM,i=window.getComputedStyle(t),n=this.heightOracle,r=i.whiteSpace;this.defaultTextDirection=i.direction=="rtl"?J.RTL:J.LTR;let o=this.heightOracle.mustRefreshForWrapping(r)||this.mustMeasureContent==="refresh",l=t.getBoundingClientRect(),a=o||this.mustMeasureContent||this.contentDOMHeight!=l.height;this.contentDOMHeight=l.height,this.mustMeasureContent=!1;let h=0,c=0;if(l.width&&l.height){let{scaleX:S,scaleY:A}=_h(t,l);(S>.005&&Math.abs(this.scaleX-S)>.005||A>.005&&Math.abs(this.scaleY-A)>.005)&&(this.scaleX=S,this.scaleY=A,h|=16,o=a=!0)}let f=(parseInt(i.paddingTop)||0)*this.scaleY,u=(parseInt(i.paddingBottom)||0)*this.scaleY;(this.paddingTop!=f||this.paddingBottom!=u)&&(this.paddingTop=f,this.paddingBottom=u,h|=18),this.editorWidth!=e.scrollDOM.clientWidth&&(n.lineWrapping&&(a=!0),this.editorWidth=e.scrollDOM.clientWidth,h|=16);let d=Kh(this.view.contentDOM,!1).y;d!=this.scrollParent&&(this.scrollParent=d,this.scrollAnchorHeight=-1,this.scrollOffset=0);let p=this.getScrollOffset();this.scrollOffset!=p&&(this.scrollAnchorHeight=-1,this.scrollOffset=p),this.scrolledToBottom=Jh(this.scrollParent||e.win);let m=(this.printing?Kp:Yp)(t,this.paddingTop),g=m.top-this.pixelViewport.top,x=m.bottom-this.pixelViewport.bottom;this.pixelViewport=m;let k=this.pixelViewport.bottom>this.pixelViewport.top&&this.pixelViewport.right>this.pixelViewport.left;if(k!=this.inView&&(this.inView=k,k&&(a=!0)),!this.inView&&!this.scrollTarget&&!_p(e.dom))return 0;let w=l.width;if((this.contentDOMWidth!=w||this.editorHeight!=e.scrollDOM.clientHeight)&&(this.contentDOMWidth=l.width,this.editorHeight=e.scrollDOM.clientHeight,h|=16),a){let S=e.docView.measureVisibleLineHeights(this.viewport);if(n.mustRefreshForHeights(S)&&(o=!0),o||n.lineWrapping&&Math.abs(w-this.contentDOMWidth)>n.charWidth){let{lineHeight:A,charWidth:O,textHeight:V}=e.docView.measureTextSize();o=A>0&&n.refresh(r,A,O,V,Math.max(5,w/O),S),o&&(e.docView.minWidth=0,h|=16)}g>0&&x>0?c=Math.max(g,x):g<0&&x<0&&(c=Math.min(g,x)),ia();for(let A of this.viewports){let O=A.from==this.viewport.from?S:e.docView.measureVisibleLineHeights(A);this.heightMap=(o?Oe.empty().applyChanges(this.stateDeco,Y.empty,this.heightOracle,[new We(0,0,0,e.state.doc.length)]):this.heightMap).updateHeight(n,0,o,new Qp(A.from,O))}ki&&(h|=2)}let T=!this.viewportIsAppropriate(this.viewport,c)||this.scrollTarget&&(this.scrollTarget.range.headthis.viewport.to);return T&&(h&2&&(h|=this.updateScaler()),this.viewport=this.getViewport(c,this.scrollTarget),h|=this.updateForViewport()),(h&2||T)&&this.updateViewportLines(),(this.lineGaps.length||this.viewport.to-this.viewport.from>4e3)&&this.updateLineGaps(this.ensureLineGaps(o?[]:this.lineGaps,e)),h|=this.computeVisibleRanges(),this.mustEnforceCursorAssoc&&(this.mustEnforceCursorAssoc=!1,e.docView.enforceCursorAssoc()),h}get visibleTop(){return this.scaler.fromDOM(this.pixelViewport.top)}get visibleBottom(){return this.scaler.fromDOM(this.pixelViewport.bottom)}getViewport(e,t){let i=.5-Math.max(-.5,Math.min(.5,e/1e3/2)),n=this.heightMap,r=this.heightOracle,{visibleTop:o,visibleBottom:l}=this,a=new As(n.lineAt(o-i*1e3,Z.ByHeight,r,0,0).from,n.lineAt(l+(1-i)*1e3,Z.ByHeight,r,0,0).to);if(t){let{head:h}=t.range;if(ha.to){let c=Math.min(this.editorHeight,this.pixelViewport.bottom-this.pixelViewport.top),f=n.lineAt(h,Z.ByPos,r,0,0),u;t.y=="center"?u=(f.top+f.bottom)/2-c/2:t.y=="start"||t.y=="nearest"&&h=l+Math.max(10,Math.min(i,250)))&&n>o-2*1e3&&r>1,o=n<<1;if(this.defaultTextDirection!=J.LTR&&!i)return[];let l=[],a=(c,f,u,d)=>{if(f-cc&&xx.from>=u.from&&x.to<=u.to&&Math.abs(x.from-c)x.fromk));if(!g){if(fw.from<=f&&w.to>=f)){let w=t.moveToLineBoundary(v.cursor(f),!1,!0).head;w>c&&(f=w)}let x=this.gapSize(u,c,f,d),k=i||x<2e6?x:2e6;g=new nr(c,f,x,k)}l.push(g)},h=c=>{if(c.length2e6)for(let A of e)A.from>=c.from&&A.fromc.from&&a(c.from,d,c,f),pt.draw(this,this.heightOracle.lineWrapping))))}computeVisibleRanges(e){let t=this.stateDeco;this.lineGaps.length&&(t=t.concat(this.lineGapDeco));let i=[];X.spans(t,this.viewport.from,this.viewport.to,{span(r,o){i.push({from:r,to:o})},point(){}},20);let n=0;if(i.length!=this.visibleRanges.length)n=12;else for(let r=0;r=this.viewport.from&&e<=this.viewport.to&&this.viewportLines.find(t=>t.from<=e&&t.to>=e)||Ni(this.heightMap.lineAt(e,Z.ByPos,this.heightOracle,0,0),this.scaler)}lineBlockAtHeight(e){return e>=this.viewportLines[0].top&&e<=this.viewportLines[this.viewportLines.length-1].bottom&&this.viewportLines.find(t=>t.top<=e&&t.bottom>=e)||Ni(this.heightMap.lineAt(this.scaler.fromDOM(e),Z.ByHeight,this.heightOracle,0,0),this.scaler)}getScrollOffset(){return(this.scrollParent==this.view.scrollDOM?this.scrollParent.scrollTop:(this.scrollParent?this.scrollParent.getBoundingClientRect().top:0)-this.view.contentDOM.getBoundingClientRect().top)*this.scaleY}scrollAnchorAt(e){let t=this.lineBlockAtHeight(e+8);return t.from>=this.viewport.from||this.viewportLines[0].top-e>200?t:this.viewportLines[0]}elementAtHeight(e){return Ni(this.heightMap.blockAt(this.scaler.fromDOM(e),this.heightOracle,0,0),this.scaler)}get docHeight(){return this.scaler.toDOM(this.heightMap.height)}get contentHeight(){return this.docHeight+this.paddingTop+this.paddingBottom}}class As{constructor(e,t){this.from=e,this.to=t}}function Jp(s,e,t){let i=[],n=s,r=0;return X.spans(t,s,e,{span(){},point(o,l){o>n&&(i.push({from:n,to:o}),r+=o-n),n=l}},20),n=1)return e[e.length-1].to;let i=Math.floor(s*t);for(let n=0;;n++){let{from:r,to:o}=e[n],l=o-r;if(i<=l)return r+i;i-=l}}function Ps(s,e){let t=0;for(let{from:i,to:n}of s.ranges){if(e<=n){t+=e-i;break}t+=n-i}return t/s.total}function Zp(s,e){for(let t of s)if(e(t))return t}const ra={toDOM(s){return s},fromDOM(s){return s},scale:1,eq(s){return s==this}};function oa(s){let e=s.facet(Bn).filter(i=>typeof i!="function"),t=s.facet(Qo).filter(i=>typeof i!="function");return t.length&&e.push(X.join(t)),e}class Xo{constructor(e,t,i){let n=0,r=0,o=0;this.viewports=i.map(({from:l,to:a})=>{let h=t.lineAt(l,Z.ByPos,e,0,0).top,c=t.lineAt(a,Z.ByPos,e,0,0).bottom;return n+=c-h,{from:l,to:a,top:h,bottom:c,domTop:0,domBottom:0}}),this.scale=(7e6-n)/(t.height-n);for(let l of this.viewports)l.domTop=o+(l.top-r)*this.scale,o=l.domBottom=l.domTop+(l.bottom-l.top),r=l.bottom}toDOM(e){for(let t=0,i=0,n=0;;t++){let r=tt.from==e.viewports[i].from&&t.to==e.viewports[i].to):!1}}function Ni(s,e){if(e.scale==1)return s;let t=e.toDOM(s.top),i=e.toDOM(s.bottom);return new $e(s.from,s.length,t,i-t,Array.isArray(s._content)?s._content.map(n=>Ni(n,e)):s._content)}const Ts=I.define({combine:s=>s.join(" ")}),no=I.define({combine:s=>s.indexOf(!0)>-1}),ro=Pt.newName(),Nc=Pt.newName(),Ic=Pt.newName(),Wc={"&light":"."+Nc,"&dark":"."+Ic};function oo(s,e,t){return new Pt(e,{finish(i){return/&/.test(i)?i.replace(/&\w*/,n=>{if(n=="&")return s;if(!t||!t[n])throw new RangeError(`Unsupported selector: ${n}`);return t[n]}):s+" "+i}})}const em=oo("."+ro,{"&":{position:"relative !important",boxSizing:"border-box","&.cm-focused":{outline:"1px dotted #212121"},display:"flex !important",flexDirection:"column"},".cm-scroller":{display:"flex !important",alignItems:"flex-start !important",fontFamily:"monospace",lineHeight:1.4,height:"100%",overflowX:"auto",position:"relative",zIndex:0,overflowAnchor:"none"},".cm-content":{margin:0,flexGrow:2,flexShrink:0,display:"block",whiteSpace:"pre",wordWrap:"normal",boxSizing:"border-box",minHeight:"100%",padding:"4px 0",outline:"none","&[contenteditable=true]":{WebkitUserModify:"read-write-plaintext-only"}},".cm-lineWrapping":{whiteSpace_fallback:"pre-wrap",whiteSpace:"break-spaces",wordBreak:"break-word",overflowWrap:"anywhere",flexShrink:1},"&light .cm-content":{caretColor:"black"},"&dark .cm-content":{caretColor:"white"},".cm-line":{display:"block",padding:"0 2px 0 6px"},".cm-layer":{userSelect:"none",position:"absolute",left:0,top:0,contain:"size style","& > *":{position:"absolute"}},"&light .cm-selectionBackground":{background:"#d9d9d9"},"&dark .cm-selectionBackground":{background:"#222"},"&light.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#d7d4f0"},"&dark.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground":{background:"#233"},".cm-cursorLayer":{pointerEvents:"none"},"&.cm-focused > .cm-scroller > .cm-cursorLayer":{animation:"steps(1) cm-blink 1.2s infinite"},"@keyframes cm-blink":{"0%":{},"50%":{opacity:0},"100%":{}},"@keyframes cm-blink2":{"0%":{},"50%":{opacity:0},"100%":{}},".cm-cursor, .cm-dropCursor":{borderLeft:"1.2px solid black",marginLeft:"-0.6px",pointerEvents:"none"},".cm-cursor":{display:"none"},"&dark .cm-cursor":{borderLeftColor:"#ddd"},".cm-selectionHandle":{backgroundColor:"currentColor",width:"1.5px"},".cm-selectionHandle-start::before, .cm-selectionHandle-end::before":{content:'""',backgroundColor:"inherit",borderRadius:"50%",width:"8px",height:"8px",position:"absolute",left:"-3.25px"},".cm-selectionHandle-start::before":{top:"-8px"},".cm-selectionHandle-end::before":{bottom:"-8px"},".cm-dropCursor":{position:"absolute"},"&.cm-focused > .cm-scroller > .cm-cursorLayer .cm-cursor":{display:"block"},".cm-iso":{unicodeBidi:"isolate"},".cm-announced":{position:"fixed",top:"-10000px"},"@media print":{".cm-announced":{display:"none"}},"&light .cm-activeLine":{backgroundColor:"#cceeff44"},"&dark .cm-activeLine":{backgroundColor:"#99eeff33"},"&light .cm-specialChar":{color:"red"},"&dark .cm-specialChar":{color:"#f78"},".cm-gutters":{flexShrink:0,display:"flex",height:"100%",boxSizing:"border-box",zIndex:200},".cm-gutters-before":{insetInlineStart:0},".cm-gutters-after":{insetInlineEnd:0},"&light .cm-gutters":{backgroundColor:"#f5f5f5",color:"#6c6c6c",border:"0px solid #ddd","&.cm-gutters-before":{borderRightWidth:"1px"},"&.cm-gutters-after":{borderLeftWidth:"1px"}},"&dark .cm-gutters":{backgroundColor:"#333338",color:"#ccc"},".cm-gutter":{display:"flex !important",flexDirection:"column",flexShrink:0,boxSizing:"border-box",minHeight:"100%",overflow:"hidden"},".cm-gutterElement":{boxSizing:"border-box"},".cm-lineNumbers .cm-gutterElement":{padding:"0 3px 0 5px",minWidth:"20px",textAlign:"right",whiteSpace:"nowrap"},"&light .cm-activeLineGutter":{backgroundColor:"#e2f2ff"},"&dark .cm-activeLineGutter":{backgroundColor:"#222227"},".cm-panels":{boxSizing:"border-box",position:"sticky",left:0,right:0,zIndex:300},"&light .cm-panels":{backgroundColor:"#f5f5f5",color:"black"},"&light .cm-panels-top":{borderBottom:"1px solid #ddd"},"&light .cm-panels-bottom":{borderTop:"1px solid #ddd"},"&dark .cm-panels":{backgroundColor:"#333338",color:"white"},".cm-dialog":{padding:"2px 19px 4px 6px",position:"relative","& label":{fontSize:"80%"}},".cm-dialog-close":{position:"absolute",top:"3px",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",fontSize:"14px",padding:"0"},".cm-tab":{display:"inline-block",overflow:"hidden",verticalAlign:"bottom"},".cm-widgetBuffer":{verticalAlign:"text-top",height:"1em",width:0,display:"inline"},".cm-placeholder":{color:"#888",display:"inline-block",verticalAlign:"top",userSelect:"none"},".cm-highlightSpace":{backgroundImage:"radial-gradient(circle at 50% 55%, #aaa 20%, transparent 5%)",backgroundPosition:"center"},".cm-highlightTab":{backgroundImage:`url('data:image/svg+xml,')`,backgroundSize:"auto 100%",backgroundPosition:"right 90%",backgroundRepeat:"no-repeat"},".cm-trailingSpace":{backgroundColor:"#ff332255"},".cm-button":{verticalAlign:"middle",color:"inherit",fontSize:"70%",padding:".2em 1em",borderRadius:"1px"},"&light .cm-button":{backgroundImage:"linear-gradient(#eff1f5, #d9d9df)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#b4b4b4, #d0d3d6)"}},"&dark .cm-button":{backgroundImage:"linear-gradient(#393939, #111)",border:"1px solid #888","&:active":{backgroundImage:"linear-gradient(#111, #333)"}},".cm-textfield":{verticalAlign:"middle",color:"inherit",fontSize:"70%",border:"1px solid silver",padding:".2em .5em"},"&light .cm-textfield":{backgroundColor:"white"},"&dark .cm-textfield":{border:"1px solid #555",backgroundColor:"inherit"}},Wc),tm={childList:!0,characterData:!0,subtree:!0,attributes:!0,characterDataOldValue:!0},rr=W.ie&&W.ie_version<=11;class im{constructor(e){this.view=e,this.active=!1,this.editContext=null,this.selectionRange=new Bd,this.selectionChanged=!1,this.delayedFlush=-1,this.resizeTimeout=-1,this.queue=[],this.delayedAndroidKey=null,this.flushingAndroidKey=-1,this.lastChange=0,this.scrollTargets=[],this.intersection=null,this.resizeScroll=null,this.intersecting=!1,this.gapIntersection=null,this.gaps=[],this.printQuery=null,this.parentCheck=-1,this.dom=e.contentDOM,this.observer=new MutationObserver(t=>{for(let i of t)this.queue.push(i);(W.ie&&W.ie_version<=11||W.ios&&e.composing)&&t.some(i=>i.type=="childList"&&i.removedNodes.length||i.type=="characterData"&&i.oldValue.length>i.target.nodeValue.length)?this.flushSoon():this.flush()}),window.EditContext&&W.android&&e.constructor.EDIT_CONTEXT!==!1&&!(W.chrome&&W.chrome_version<126)&&(this.editContext=new nm(e),e.state.facet(dt)&&(e.contentDOM.editContext=this.editContext.editContext)),rr&&(this.onCharData=t=>{this.queue.push({target:t.target,type:"characterData",oldValue:t.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this),this.onResize=this.onResize.bind(this),this.onPrint=this.onPrint.bind(this),this.onScroll=this.onScroll.bind(this),window.matchMedia&&(this.printQuery=window.matchMedia("print")),typeof ResizeObserver=="function"&&(this.resizeScroll=new ResizeObserver(()=>{var t;((t=this.view.docView)===null||t===void 0?void 0:t.lastUpdate){this.parentCheck<0&&(this.parentCheck=setTimeout(this.listenForScroll.bind(this),1e3)),t.length>0&&t[t.length-1].intersectionRatio>0!=this.intersecting&&(this.intersecting=!this.intersecting,this.intersecting!=this.view.inView&&this.onScrollChanged(document.createEvent("Event")))},{threshold:[0,.001]}),this.intersection.observe(this.dom),this.gapIntersection=new IntersectionObserver(t=>{t.length>0&&t[t.length-1].intersectionRatio>0&&this.onScrollChanged(document.createEvent("Event"))},{})),this.listenForScroll(),this.readSelectionRange()}onScrollChanged(e){this.view.inputState.runHandlers("scroll",e),this.intersecting&&this.view.measure()}onScroll(e){this.intersecting&&this.flush(!1),this.editContext&&this.view.requestMeasure(this.editContext.measureReq),this.onScrollChanged(e)}onResize(){this.resizeTimeout<0&&(this.resizeTimeout=setTimeout(()=>{this.resizeTimeout=-1,this.view.requestMeasure()},50))}onPrint(e){(e.type=="change"||!e.type)&&!e.matches||(this.view.viewState.printing=!0,this.view.measure(),setTimeout(()=>{this.view.viewState.printing=!1,this.view.requestMeasure()},500))}updateGaps(e){if(this.gapIntersection&&(e.length!=this.gaps.length||this.gaps.some((t,i)=>t!=e[i]))){this.gapIntersection.disconnect();for(let t of e)this.gapIntersection.observe(t);this.gaps=e}}onSelectionChange(e){let t=this.selectionChanged;if(!this.readSelectionRange()||this.delayedAndroidKey)return;let{view:i}=this,n=this.selectionRange;if(i.state.facet(dt)?i.root.activeElement!=this.dom:!Vi(this.dom,n))return;let r=n.anchorNode&&i.docView.tile.nearest(n.anchorNode);if(r&&r.isWidget()&&r.widget.ignoreEvent(e)){t||(this.selectionChanged=!1);return}(W.ie&&W.ie_version<=11||W.android&&W.chrome)&&!i.state.selection.main.empty&&n.focusNode&&zi(n.focusNode,n.focusOffset,n.anchorNode,n.anchorOffset)?this.flushSoon():this.flush(!1)}readSelectionRange(){let{view:e}=this,t=Ki(e.root);if(!t)return!1;let i=W.safari&&e.root.nodeType==11&&e.root.activeElement==this.dom&&sm(this.view,t)||t;if(!i||this.selectionRange.eq(i))return!1;let n=Vi(this.dom,i);return n&&!this.selectionChanged&&e.inputState.lastFocusTime>Date.now()-200&&e.inputState.lastTouchTime{let r=this.delayedAndroidKey;r&&(this.clearDelayedAndroidKey(),this.view.inputState.lastKeyCode=r.keyCode,this.view.inputState.lastKeyTime=Date.now(),!this.flush()&&r.force&&ui(this.dom,r.key,r.keyCode))};this.flushingAndroidKey=this.view.win.requestAnimationFrame(n)}(!this.delayedAndroidKey||e=="Enter")&&(this.delayedAndroidKey={key:e,keyCode:t,force:this.lastChange{this.delayedFlush=-1,this.flush()}))}forceFlush(){this.delayedFlush>=0&&(this.view.win.cancelAnimationFrame(this.delayedFlush),this.delayedFlush=-1),this.flush()}pendingRecords(){for(let e of this.observer.takeRecords())this.queue.push(e);return this.queue}processRecords(){let e=this.pendingRecords();e.length&&(this.queue=[]);let t=-1,i=-1,n=!1;for(let r of e){let o=this.readMutation(r);o&&(o.typeOver&&(n=!0),t==-1?{from:t,to:i}=o:(t=Math.min(o.from,t),i=Math.max(o.to,i)))}return{from:t,to:i,typeOver:n}}readChange(){let{from:e,to:t,typeOver:i}=this.processRecords(),n=this.selectionChanged&&Vi(this.dom,this.selectionRange);if(e<0&&!n)return null;e>-1&&(this.lastChange=Date.now()),this.view.inputState.lastFocusTime=0,this.selectionChanged=!1;let r=new wp(this.view,e,t,i);return this.view.docView.domChanged={newSel:r.newSel?r.newSel.main:null},r}flush(e=!0){if(this.delayedFlush>=0||this.delayedAndroidKey)return!1;e&&this.readSelectionRange();let t=this.readChange();if(!t)return this.view.requestMeasure(),!1;let i=this.view.state,n=Oc(this.view,t);return this.view.state==i&&(t.domChanged||t.newSel&&!an(this.view.state.selection,t.newSel.main))&&this.view.update([]),n}readMutation(e){let t=this.view.docView.tile.nearest(e.target);if(!t||t.isWidget())return null;if(t.markDirty(e.type=="attributes"),e.type=="childList"){let i=la(t,e.previousSibling||e.target.previousSibling,-1),n=la(t,e.nextSibling||e.target.nextSibling,1);return{from:i?t.posAfter(i):t.posAtStart,to:n?t.posBefore(n):t.posAtEnd,typeOver:!1}}else return e.type=="characterData"?{from:t.posAtStart,to:t.posAtEnd,typeOver:e.target.nodeValue==e.oldValue}:null}setWindow(e){e!=this.win&&(this.removeWindowListeners(this.win),this.win=e,this.addWindowListeners(this.win))}addWindowListeners(e){e.addEventListener("resize",this.onResize),this.printQuery?this.printQuery.addEventListener?this.printQuery.addEventListener("change",this.onPrint):this.printQuery.addListener(this.onPrint):e.addEventListener("beforeprint",this.onPrint),e.addEventListener("scroll",this.onScroll),e.document.addEventListener("selectionchange",this.onSelectionChange)}removeWindowListeners(e){e.removeEventListener("scroll",this.onScroll),e.removeEventListener("resize",this.onResize),this.printQuery?this.printQuery.removeEventListener?this.printQuery.removeEventListener("change",this.onPrint):this.printQuery.removeListener(this.onPrint):e.removeEventListener("beforeprint",this.onPrint),e.document.removeEventListener("selectionchange",this.onSelectionChange)}update(e){this.editContext&&(this.editContext.update(e),e.startState.facet(dt)!=e.state.facet(dt)&&(e.view.contentDOM.editContext=e.state.facet(dt)?this.editContext.editContext:null))}destroy(){var e,t,i;this.stop(),(e=this.intersection)===null||e===void 0||e.disconnect(),(t=this.gapIntersection)===null||t===void 0||t.disconnect(),(i=this.resizeScroll)===null||i===void 0||i.disconnect();for(let n of this.scrollTargets)n.removeEventListener("scroll",this.onScroll);this.removeWindowListeners(this.win),clearTimeout(this.parentCheck),clearTimeout(this.resizeTimeout),this.win.cancelAnimationFrame(this.delayedFlush),this.win.cancelAnimationFrame(this.flushingAndroidKey),this.editContext&&(this.view.contentDOM.editContext=null,this.editContext.destroy())}}function la(s,e,t){for(;e;){let i=ie.get(e);if(i&&i.parent==s)return i;let n=e.parentNode;e=n!=s.dom?n:t>0?e.nextSibling:e.previousSibling}return null}function aa(s,e){let t=e.startContainer,i=e.startOffset,n=e.endContainer,r=e.endOffset,o=s.docView.domAtPos(s.state.selection.main.anchor,1);return zi(o.node,o.offset,n,r)&&([t,i,n,r]=[n,r,t,i]),{anchorNode:t,anchorOffset:i,focusNode:n,focusOffset:r}}function sm(s,e){if(e.getComposedRanges){let n=e.getComposedRanges(s.root)[0];if(n)return aa(s,n)}let t=null;function i(n){n.preventDefault(),n.stopImmediatePropagation(),t=n.getTargetRanges()[0]}return s.contentDOM.addEventListener("beforeinput",i,!0),s.dom.ownerDocument.execCommand("indent"),s.contentDOM.removeEventListener("beforeinput",i,!0),t?aa(s,t):null}class nm{constructor(e){this.from=0,this.to=0,this.pendingContextChange=null,this.handlers=Object.create(null),this.composing=null,this.resetRange(e.state);let t=this.editContext=new window.EditContext({text:e.state.doc.sliceString(this.from,this.to),selectionStart:this.toContextPos(Math.max(this.from,Math.min(this.to,e.state.selection.main.anchor))),selectionEnd:this.toContextPos(e.state.selection.main.head)});this.handlers.textupdate=i=>{let n=e.state.selection.main,{anchor:r,head:o}=n,l=this.toEditorPos(i.updateRangeStart),a=this.toEditorPos(i.updateRangeEnd);e.inputState.composing>=0&&!this.composing&&(this.composing={contextBase:i.updateRangeStart,editorBase:l,drifted:!1});let h=a-l>i.text.length;l==this.from&&rthis.to&&(a=r);let c=Cc(e.state.sliceDoc(l,a),i.text,(h?n.from:n.to)-l,h?"end":null);if(!c){let u=v.single(this.toEditorPos(i.selectionStart),this.toEditorPos(i.selectionEnd));an(u,n)||e.dispatch({selection:u,userEvent:"select"});return}let f={from:c.from+l,to:c.toA+l,insert:Y.of(i.text.slice(c.from,c.toB).split(` +`))};if((W.mac||W.android)&&f.from==o-1&&/^\. ?$/.test(i.text)&&e.contentDOM.getAttribute("autocorrect")=="off"&&(f={from:l,to:a,insert:Y.of([i.text.replace("."," ")])}),this.pendingContextChange=f,!e.state.readOnly){let u=this.to-this.from+(f.to-f.from+f.insert.length);jo(e,f,v.single(this.toEditorPos(i.selectionStart,u),this.toEditorPos(i.selectionEnd,u)))}this.pendingContextChange&&(this.revertPending(e.state),this.setSelection(e.state)),f.from=0&&!/[\\p{Alphabetic}\\p{Number}_]/.test(t.text.slice(Math.max(0,i.updateRangeStart-1),Math.min(t.text.length,i.updateRangeStart+1)))&&this.handlers.compositionend(i)},this.handlers.characterboundsupdate=i=>{let n=[],r=null;for(let o=this.toEditorPos(i.rangeStart),l=this.toEditorPos(i.rangeEnd);o{let n=[];for(let r of i.getTextFormats()){let o=r.underlineStyle,l=r.underlineThickness;if(!/none/i.test(o)&&!/none/i.test(l)){let a=this.toEditorPos(r.rangeStart),h=this.toEditorPos(r.rangeEnd);if(a{e.inputState.composing<0&&(e.inputState.composing=0,e.inputState.compositionFirstChange=!0)},this.handlers.compositionend=()=>{if(e.inputState.composing=-1,e.inputState.compositionFirstChange=null,this.composing){let{drifted:i}=this.composing;this.composing=null,i&&this.reset(e.state)}};for(let i in this.handlers)t.addEventListener(i,this.handlers[i]);this.measureReq={read:i=>{this.editContext.updateControlBounds(i.contentDOM.getBoundingClientRect());let n=Ki(i.root);n&&n.rangeCount&&this.editContext.updateSelectionBounds(n.getRangeAt(0).getBoundingClientRect())}}}applyEdits(e){let t=0,i=!1,n=this.pendingContextChange;return e.changes.iterChanges((r,o,l,a,h)=>{if(i)return;let c=h.length-(o-r);if(n&&o>=n.to)if(n.from==r&&n.to==o&&n.insert.eq(h)){n=this.pendingContextChange=null,t+=c,this.to+=c;return}else n=null,this.revertPending(e.state);if(r+=t,o+=t,o<=this.from)this.from+=c,this.to+=c;else if(rthis.to||this.to-this.from+h.length>3e4){i=!0;return}this.editContext.updateText(this.toContextPos(r),this.toContextPos(o),h.toString()),this.to+=c}t+=c}),n&&!i&&this.revertPending(e.state),!i}update(e){let t=this.pendingContextChange,i=e.startState.selection.main;this.composing&&(this.composing.drifted||!e.changes.touchesRange(i.from,i.to)&&e.transactions.some(n=>!n.isUserEvent("input.type")&&n.changes.touchesRange(this.from,this.to)))?(this.composing.drifted=!0,this.composing.editorBase=e.changes.mapPos(this.composing.editorBase)):!this.applyEdits(e)||!this.rangeIsValid(e.state)?(this.pendingContextChange=null,this.reset(e.state)):(e.docChanged||e.selectionSet||t)&&this.setSelection(e.state),(e.geometryChanged||e.docChanged||e.selectionSet)&&e.view.requestMeasure(this.measureReq)}resetRange(e){let{head:t}=e.selection.main;this.from=Math.max(0,t-1e4),this.to=Math.min(e.doc.length,t+1e4)}reset(e){this.resetRange(e),this.editContext.updateText(0,this.editContext.text.length,e.doc.sliceString(this.from,this.to)),this.setSelection(e)}revertPending(e){let t=this.pendingContextChange;this.pendingContextChange=null,this.editContext.updateText(this.toContextPos(t.from),this.toContextPos(t.from+t.insert.length),e.doc.sliceString(t.from,t.to))}setSelection(e){let{main:t}=e.selection,i=this.toContextPos(Math.max(this.from,Math.min(this.to,t.anchor))),n=this.toContextPos(t.head);(this.editContext.selectionStart!=i||this.editContext.selectionEnd!=n)&&this.editContext.updateSelection(i,n)}rangeIsValid(e){let{head:t}=e.selection.main;return!(this.from>0&&t-this.from<500||this.to1e4*3)}toEditorPos(e,t=this.to-this.from){e=Math.min(e,t);let i=this.composing;return i&&i.drifted?i.editorBase+(e-i.contextBase):e+this.from}toContextPos(e){let t=this.composing;return t&&t.drifted?t.contextBase+(e-t.editorBase):e-this.from}destroy(){for(let e in this.handlers)this.editContext.removeEventListener(e,this.handlers[e])}}class L{get state(){return this.viewState.state}get viewport(){return this.viewState.viewport}get visibleRanges(){return this.viewState.visibleRanges}get inView(){return this.viewState.inView}get composing(){return!!this.inputState&&this.inputState.composing>0}get compositionStarted(){return!!this.inputState&&this.inputState.composing>=0}get root(){return this._root}get win(){return this.dom.ownerDocument.defaultView||window}constructor(e={}){var t;this.plugins=[],this.pluginMap=new Map,this.editorAttrs={},this.contentAttrs={},this.bidiCache=[],this.destroyed=!1,this.updateState=2,this.measureScheduled=-1,this.measureRequests=[],this.contentDOM=document.createElement("div"),this.scrollDOM=document.createElement("div"),this.scrollDOM.tabIndex=-1,this.scrollDOM.className="cm-scroller",this.scrollDOM.appendChild(this.contentDOM),this.announceDOM=document.createElement("div"),this.announceDOM.className="cm-announced",this.announceDOM.setAttribute("aria-live","polite"),this.dom=document.createElement("div"),this.dom.appendChild(this.announceDOM),this.dom.appendChild(this.scrollDOM),e.parent&&e.parent.appendChild(this.dom);let{dispatch:i}=e;this.dispatchTransactions=e.dispatchTransactions||i&&(n=>n.forEach(r=>i(r,this)))||(n=>this.update(n)),this.dispatch=this.dispatch.bind(this),this._root=e.root||Ed(e.parent)||document,this.viewState=new na(this,e.state||U.create(e)),e.scrollTo&&e.scrollTo.is(Ss)&&(this.viewState.scrollTarget=e.scrollTo.value.clip(this.viewState.state)),this.plugins=this.state.facet(oi).map(n=>new Zn(n));for(let n of this.plugins)n.update(this);this.observer=new im(this),this.inputState=new Cp(this),this.inputState.ensureHandlers(this.plugins),this.docView=new ql(this),this.mountStyles(),this.updateAttrs(),this.updateState=0,this.requestMeasure(),!((t=document.fonts)===null||t===void 0)&&t.ready&&document.fonts.ready.then(()=>{this.viewState.mustMeasureContent="refresh",this.requestMeasure()})}dispatch(...e){let t=e.length==1&&e[0]instanceof he?e:e.length==1&&Array.isArray(e[0])?e[0]:[this.state.update(...e)];this.dispatchTransactions(t,this)}update(e){if(this.updateState!=0)throw new Error("Calls to EditorView.update are not allowed while an update is in progress");let t=!1,i=!1,n,r=this.state;for(let u of e){if(u.startState!=r)throw new RangeError("Trying to update state with a transaction that doesn't start from the previous state.");r=u.state}if(this.destroyed){this.viewState.state=r;return}let o=this.hasFocus,l=0,a=null;e.some(u=>u.annotation(Rc))?(this.inputState.notifiedFocused=o,l=1):o!=this.inputState.notifiedFocused&&(this.inputState.notifiedFocused=o,a=Bc(r,o),a||(l=1));let h=this.observer.delayedAndroidKey,c=null;if(h?(this.observer.clearDelayedAndroidKey(),c=this.observer.readChange(),(c&&!this.state.doc.eq(r.doc)||!this.state.selection.eq(r.selection))&&(c=null)):this.observer.clear(),r.facet(U.phrases)!=this.state.facet(U.phrases))return this.setState(r);n=rn.create(this,r,e),n.flags|=l;let f=this.viewState.scrollTarget;try{this.updateState=2;for(let u of e){if(f&&(f=f.map(u.changes)),u.scrollIntoView){let{main:d}=u.state.selection,{x:p,y:m}=this.state.facet(L.cursorScrollMargin);f=new di(d.empty?d:v.cursor(d.head,d.head>d.anchor?-1:1),"nearest","nearest",m,p)}for(let d of u.effects)d.is(Ss)&&(f=d.value.clip(this.state))}this.viewState.update(n,f),this.bidiCache=cn.update(this.bidiCache,n.changes),n.empty||(this.updatePlugins(n),this.inputState.update(n)),t=this.docView.update(n),this.state.facet(Li)!=this.styleModules&&this.mountStyles(),i=this.updateAttrs(),this.showAnnouncements(e),this.docView.updateSelection(t,e.some(u=>u.isUserEvent("select.pointer")))}finally{this.updateState=0}if(n.startState.facet(Ts)!=n.state.facet(Ts)&&(this.viewState.mustMeasureContent=!0),(t||i||f||this.viewState.mustEnforceCursorAssoc||this.viewState.mustMeasureContent)&&this.requestMeasure(),t&&this.docViewUpdate(),!n.empty)for(let u of this.state.facet(Zr))try{u(n)}catch(d){Pe(this.state,d,"update listener")}(a||c)&&Promise.resolve().then(()=>{a&&this.state==a.startState&&this.dispatch(a),c&&!Oc(this,c)&&h.force&&ui(this.contentDOM,h.key,h.keyCode)})}setState(e){if(this.updateState!=0)throw new Error("Calls to EditorView.setState are not allowed while an update is in progress");if(this.destroyed){this.viewState.state=e;return}this.updateState=2;let t=this.hasFocus;try{for(let i of this.plugins)i.destroy(this);this.viewState=new na(this,e),this.plugins=e.facet(oi).map(i=>new Zn(i)),this.pluginMap.clear();for(let i of this.plugins)i.update(this);this.docView.destroy(),this.docView=new ql(this),this.inputState.ensureHandlers(this.plugins),this.mountStyles(),this.updateAttrs(),this.bidiCache=[]}finally{this.updateState=0}t&&this.focus(),this.requestMeasure()}updatePlugins(e){let t=e.startState.facet(oi),i=e.state.facet(oi);if(t!=i){let n=[];for(let r of i){let o=t.indexOf(r);if(o<0)n.push(new Zn(r));else{let l=this.plugins[o];l.mustUpdate=e,n.push(l)}}for(let r of this.plugins)r.mustUpdate!=e&&r.destroy(this);this.plugins=n,this.pluginMap.clear()}else for(let n of this.plugins)n.mustUpdate=e;for(let n=0;n-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.observer.delayedAndroidKey){this.measureScheduled=-1,this.requestMeasure();return}this.measureScheduled=0,e&&this.observer.forceFlush();let t=null,i=this.viewState.scrollParent,n=this.viewState.getScrollOffset(),{scrollAnchorPos:r,scrollAnchorHeight:o}=this.viewState;Math.abs(n-this.viewState.scrollOffset)>1&&(o=-1),this.viewState.scrollAnchorHeight=-1;try{for(let l=0;;l++){if(o<0)if(Jh(i||this.win))r=-1,o=this.viewState.heightMap.height;else{let d=this.viewState.scrollAnchorAt(n);r=d.from,o=d.top}this.updateState=1;let a=this.viewState.measure();if(!a&&!this.measureRequests.length&&this.viewState.scrollTarget==null)break;if(l>5){console.warn(this.measureRequests.length?"Measure loop restarted more than 5 times":"Viewport failed to stabilize");break}let h=[];a&4||([this.measureRequests,h]=[h,this.measureRequests]);let c=h.map(d=>{try{return d.read(this)}catch(p){return Pe(this.state,p),ha}}),f=rn.create(this,this.state,[]),u=!1;f.flags|=a,t?t.flags|=a:t=f,this.updateState=2,f.empty||(this.updatePlugins(f),this.inputState.update(f),this.updateAttrs(),u=this.docView.update(f),u&&this.docViewUpdate());for(let d=0;d1||p<-1)&&(i==this.scrollDOM||this.hasFocus||Math.max(this.inputState.lastWheelEvent,this.inputState.lastTouchTime)>Date.now()-100)){n=n+p,i?i.scrollTop+=p:this.win.scrollBy(0,p),o=-1;continue}}break}}}finally{this.updateState=0,this.measureScheduled=-1}if(t&&!t.empty)for(let l of this.state.facet(Zr))l(t)}get themeClasses(){return ro+" "+(this.state.facet(no)?Ic:Nc)+" "+this.state.facet(Ts)}updateAttrs(){let e=ca(this,gc,{class:"cm-editor"+(this.hasFocus?" cm-focused ":" ")+this.themeClasses}),t={spellcheck:"false",autocorrect:"off",autocapitalize:"off",writingsuggestions:"false",translate:"no",contenteditable:this.state.facet(dt)?"true":"false",class:"cm-content",style:`${W.tabSize}: ${this.state.tabSize}`,role:"textbox","aria-multiline":"true"};this.state.readOnly&&(t["aria-readonly"]="true"),ca(this,zo,t);let i=this.observer.ignore(()=>{let n=Vl(this.contentDOM,this.contentAttrs,t),r=Vl(this.dom,this.editorAttrs,e);return n||r});return this.editorAttrs=e,this.contentAttrs=t,i}showAnnouncements(e){let t=!0;for(let i of e)for(let n of i.effects)if(n.is(L.announce)){t&&(this.announceDOM.textContent=""),t=!1;let r=this.announceDOM.appendChild(document.createElement("div"));r.textContent=n.value}}mountStyles(){this.styleModules=this.state.facet(Li);let e=this.state.facet(L.cspNonce);Pt.mount(this.root,this.styleModules.concat(em).reverse(),e?{nonce:e}:void 0)}readMeasured(){if(this.updateState==2)throw new Error("Reading the editor layout isn't allowed during an update");this.updateState==0&&this.measureScheduled>-1&&this.measure(!1)}requestMeasure(e){if(this.measureScheduled<0&&(this.measureScheduled=this.win.requestAnimationFrame(()=>this.measure())),e){if(this.measureRequests.indexOf(e)>-1)return;if(e.key!=null){for(let t=0;ti.plugin==e)||null),t&&t.update(this).value}get documentTop(){return this.contentDOM.getBoundingClientRect().top+this.viewState.paddingTop}get documentPadding(){return{top:this.viewState.paddingTop,bottom:this.viewState.paddingBottom}}get scaleX(){return this.viewState.scaleX}get scaleY(){return this.viewState.scaleY}elementAtHeight(e){return this.readMeasured(),this.viewState.elementAtHeight(e)}lineBlockAtHeight(e){return this.readMeasured(),this.viewState.lineBlockAtHeight(e)}get viewportLineBlocks(){return this.viewState.viewportLines}lineBlockAt(e){return this.viewState.lineBlockAt(e)}get contentHeight(){return this.viewState.contentHeight}moveByChar(e,t,i){return sr(this,e,Xl(this,e,t,i))}moveByGroup(e,t){return sr(this,e,Xl(this,e,t,i=>mp(this,e.head,i)))}visualLineSide(e,t){let i=this.bidiSpans(e),n=this.textDirectionAt(e.from),r=i[t?i.length-1:0];return v.cursor(r.side(t,n)+e.from,r.forward(!t,n)?1:-1)}moveToLineBoundary(e,t,i=!0){return pp(this,e,t,i)}moveVertically(e,t,i){return sr(this,e,gp(this,e,t,i))}domAtPos(e,t=1){return this.docView.domAtPos(e,t)}posAtDOM(e,t=0){return this.docView.posFromDOM(e,t)}posAtCoords(e,t=!0){this.readMeasured();let i=io(this,e,t);return i&&i.pos}posAndSideAtCoords(e,t=!0){return this.readMeasured(),io(this,e,t)}coordsAtPos(e,t=1){this.readMeasured();let i=this.docView.coordsAt(e,t);if(!i||i.left==i.right)return i;let n=this.state.doc.lineAt(e),r=this.bidiSpans(n),o=r[nt.find(r,e-n.from,-1,t)];return Gi(i,o.dir==J.LTR==t>0)}coordsForChar(e){return this.readMeasured(),this.docView.coordsForChar(e)}get defaultCharacterWidth(){return this.viewState.heightOracle.charWidth}get defaultLineHeight(){return this.viewState.heightOracle.lineHeight}get textDirection(){return this.viewState.defaultTextDirection}textDirectionAt(e){return!this.state.facet(uc)||ethis.viewport.to?this.textDirection:(this.readMeasured(),this.docView.textDirectionAt(e))}get lineWrapping(){return this.viewState.heightOracle.lineWrapping}bidiSpans(e){if(e.length>rm)return nc(e.length);let t=this.textDirectionAt(e.from),i;for(let r of this.bidiCache)if(r.from==e.from&&r.dir==t&&(r.fresh||sc(r.isolates,i=Ql(this,e))))return r.order;i||(i=Ql(this,e));let n=zd(e.text,t,i);return this.bidiCache.push(new cn(e.from,e.to,t,i,!0,n)),n}get hasFocus(){var e;return(this.dom.ownerDocument.hasFocus()||W.safari&&((e=this.inputState)===null||e===void 0?void 0:e.lastContextMenu)>Date.now()-3e4)&&this.root.activeElement==this.contentDOM}focus(){this.observer.ignore(()=>{Gh(this.contentDOM),this.docView.updateSelection()})}setRoot(e){this._root!=e&&(this._root=e,this.observer.setWindow((e.nodeType==9?e:e.ownerDocument).defaultView||window),this.mountStyles())}destroy(){this.root.activeElement==this.contentDOM&&this.contentDOM.blur();for(let e of this.plugins)e.destroy(this);this.plugins=[],this.inputState.destroy(),this.docView.destroy(),this.dom.remove(),this.observer.destroy(),this.measureScheduled>-1&&this.win.cancelAnimationFrame(this.measureScheduled),this.destroyed=!0}static scrollIntoView(e,t={}){var i,n,r,o;return Ss.of(new di(typeof e=="number"?v.cursor(e):e,(i=t.y)!==null&&i!==void 0?i:"nearest",(n=t.x)!==null&&n!==void 0?n:"nearest",(r=t.yMargin)!==null&&r!==void 0?r:5,(o=t.xMargin)!==null&&o!==void 0?o:5))}scrollSnapshot(){let{scrollTop:e,scrollLeft:t}=this.scrollDOM,i=this.viewState.scrollAnchorAt(e);return Ss.of(new di(v.cursor(i.from),"start","start",i.top-e,t,!0))}setTabFocusMode(e){e==null?this.inputState.tabFocusMode=this.inputState.tabFocusMode<0?0:-1:typeof e=="boolean"?this.inputState.tabFocusMode=e?0:-1:this.inputState.tabFocusMode!=0&&(this.inputState.tabFocusMode=Date.now()+e)}static domEventHandlers(e){return se.define(()=>({}),{eventHandlers:e})}static domEventObservers(e){return se.define(()=>({}),{eventObservers:e})}static theme(e,t){let i=Pt.newName(),n=[Ts.of(i),Li.of(oo(`.${i}`,e))];return t&&t.dark&&n.push(no.of(!0)),n}static baseTheme(e){return ei.lowest(Li.of(oo("."+ro,e,Wc)))}static findFromDOM(e){var t;let i=e.querySelector(".cm-content"),n=i&&ie.get(i)||ie.get(e);return((t=n?.root)===null||t===void 0?void 0:t.view)||null}}L.styleModule=Li;L.inputHandler=cc;L.clipboardInputFilter=Vo;L.clipboardOutputFilter=Ho;L.scrollHandler=pc;L.focusChangeEffect=fc;L.perLineTextDirection=uc;L.exceptionSink=hc;L.updateListener=Zr;L.editable=dt;L.mouseSelectionStyle=ac;L.dragMovesSelection=lc;L.clickAddsSelectionRange=oc;L.decorations=Bn;L.blockWrappers=xc;L.outerDecorations=Qo;L.atomicRanges=fs;L.bidiIsolatedRanges=bc;L.cursorScrollMargin=I.define({combine:s=>{let e=5,t=5;for(let i of s)typeof i=="number"?e=t=i:{x:e,y:t}=i;return{x:e,y:t}}});L.scrollMargins=yc;L.darkTheme=no;L.cspNonce=I.define({combine:s=>s.length?s[0]:""});L.contentAttributes=zo;L.editorAttributes=gc;L.lineWrapping=L.contentAttributes.of({class:"cm-lineWrapping"});L.announce=$.define();const rm=4096,ha={};class cn{constructor(e,t,i,n,r,o){this.from=e,this.to=t,this.dir=i,this.isolates=n,this.fresh=r,this.order=o}static update(e,t){if(t.empty&&!e.some(r=>r.fresh))return e;let i=[],n=e.length?e[e.length-1].dir:J.LTR;for(let r=Math.max(0,e.length-10);r=0;n--){let r=i[n],o=typeof r=="function"?r(s):r;o&&Io(o,t)}return t}const om=W.mac?"mac":W.windows?"win":W.linux?"linux":"key";function lm(s,e){const t=s.split(/-(?!$)/);let i=t[t.length-1];i=="Space"&&(i=" ");let n,r,o,l;for(let a=0;ai.concat(n),[]))),t}function hm(s,e,t){return Vc(Fc(s.state),e,s,t)}let vt=null;const cm=4e3;function fm(s,e=om){let t=Object.create(null),i=Object.create(null),n=(o,l)=>{let a=i[o];if(a==null)i[o]=l;else if(a!=l)throw new Error("Key binding "+o+" is used both as a regular binding and as a multi-stroke prefix")},r=(o,l,a,h,c)=>{var f,u;let d=t[o]||(t[o]=Object.create(null)),p=l.split(/ (?!$)/).map(x=>lm(x,e));for(let x=1;x{let T=vt={view:w,prefix:k,scope:o};return setTimeout(()=>{vt==T&&(vt=null)},cm),!0}]})}let m=p.join(" ");n(m,!1);let g=d[m]||(d[m]={preventDefault:!1,stopPropagation:!1,run:((u=(f=d._any)===null||f===void 0?void 0:f.run)===null||u===void 0?void 0:u.slice())||[]});a&&g.run.push(a),h&&(g.preventDefault=!0),c&&(g.stopPropagation=!0)};for(let o of s){let l=o.scope?o.scope.split(" "):["editor"];if(o.any)for(let h of l){let c=t[h]||(t[h]=Object.create(null));c._any||(c._any={preventDefault:!1,stopPropagation:!1,run:[]});let{any:f}=o;for(let u in c)c[u].run.push(d=>f(d,lo))}let a=o[e]||o.key;if(a)for(let h of l)r(h,a,o.run,o.preventDefault,o.stopPropagation),o.shift&&r(h,"Shift-"+a,o.shift,o.preventDefault,o.stopPropagation)}return t}let lo=null;function Vc(s,e,t,i){lo=e;let n=Ad(e),r=Ce(n,0),o=it(r)==n.length&&n!=" ",l="",a=!1,h=!1,c=!1;vt&&vt.view==t&&vt.scope==i&&(l=vt.prefix+" ",Mc.indexOf(e.keyCode)<0&&(h=!0,vt=null));let f=new Set,u=g=>{if(g){for(let x of g.run)if(!f.has(x)&&(f.add(x),x(t)))return g.stopPropagation&&(c=!0),!0;g.preventDefault&&(g.stopPropagation&&(c=!0),h=!0)}return!1},d=s[i],p,m;return d&&(u(d[l+Ds(n,e,!o)])?a=!0:o&&(e.altKey||e.metaKey||e.ctrlKey)&&!(W.windows&&e.ctrlKey&&e.altKey)&&!(W.mac&&e.altKey&&!(e.ctrlKey||e.metaKey))&&(p=Tt[e.keyCode])&&p!=n?(u(d[l+Ds(p,e,!0)])||e.shiftKey&&(m=Yi[e.keyCode])!=n&&m!=p&&u(d[l+Ds(m,e,!1)]))&&(a=!0):o&&e.shiftKey&&u(d[l+Ds(n,e,!0)])&&(a=!0),!a&&u(d._any)&&(a=!0)),h&&(a=!0),a&&c&&e.stopPropagation(),lo=null,a}class Ut{constructor(e,t,i,n,r){this.className=e,this.left=t,this.top=i,this.width=n,this.height=r}draw(){let e=document.createElement("div");return e.className=this.className,this.adjust(e),e}update(e,t){return t.className!=this.className?!1:(this.adjust(e),!0)}adjust(e){e.style.left=this.left+"px",e.style.top=this.top+"px",this.width!=null&&(e.style.width=this.width+"px"),e.style.height=this.height+"px"}eq(e){return this.left==e.left&&this.top==e.top&&this.width==e.width&&this.height==e.height&&this.className==e.className}static forRange(e,t,i){if(i.empty){let n=e.coordsAtPos(i.head,i.assoc||1);if(!n)return[];let r=Hc(e);return[new Ut(t,n.left-r.left,n.top-r.top,null,n.bottom-n.top)]}else return um(e,t,i)}}function Hc(s){let e=s.scrollDOM.getBoundingClientRect();return{left:(s.textDirection==J.LTR?e.left:e.right-s.scrollDOM.clientWidth*s.scaleX)-s.scrollDOM.scrollLeft*s.scaleX,top:e.top-s.scrollDOM.scrollTop*s.scaleY}}function ua(s,e,t,i){let n=s.coordsAtPos(e,t*2);if(!n)return i;let r=s.dom.getBoundingClientRect(),o=(n.top+n.bottom)/2,l=s.posAtCoords({x:r.left+1,y:o}),a=s.posAtCoords({x:r.right-1,y:o});return l==null||a==null?i:{from:Math.max(i.from,Math.min(l,a)),to:Math.min(i.to,Math.max(l,a))}}function um(s,e,t){if(t.to<=s.viewport.from||t.from>=s.viewport.to)return[];let i=Math.max(t.from,s.viewport.from),n=Math.min(t.to,s.viewport.to),r=s.textDirection==J.LTR,o=s.contentDOM,l=o.getBoundingClientRect(),a=Hc(s),h=o.querySelector(".cm-line"),c=h&&window.getComputedStyle(h),f=l.left+(c?parseInt(c.paddingLeft)+Math.min(0,parseInt(c.textIndent)):0),u=l.right-(c?parseInt(c.paddingRight):0),d=to(s,i,1),p=to(s,n,-1),m=d.type==ge.Text?d:null,g=p.type==ge.Text?p:null;if(m&&(s.lineWrapping||d.widgetLineBreaks)&&(m=ua(s,i,1,m)),g&&(s.lineWrapping||p.widgetLineBreaks)&&(g=ua(s,n,-1,g)),m&&g&&m.from==g.from&&m.to==g.to)return k(w(t.from,t.to,m));{let S=m?w(t.from,null,m):T(d,!1),A=g?w(null,t.to,g):T(p,!0),O=[];return(m||d).to<(g||p).from-(m&&g?1:0)||d.widgetLineBreaks>1&&S.bottom+s.defaultLineHeight/2M&&R.from=B)break;ue>C&&D(Math.max(Q,C),S==null&&Q<=M,Math.min(ue,B),A==null&&ue>=F,oe.dir)}if(C=j.to+1,C>=B)break}return P.length==0&&D(M,S==null,F,A==null,s.textDirection),{top:V,bottom:N,horizontal:P}}function T(S,A){let O=l.top+(A?S.top:S.bottom);return{top:O,bottom:O,horizontal:[]}}}function dm(s,e){return s.constructor==e.constructor&&s.eq(e)}class pm{constructor(e,t){this.view=e,this.layer=t,this.drawn=[],this.scaleX=1,this.scaleY=1,this.measureReq={read:this.measure.bind(this),write:this.draw.bind(this)},this.dom=e.scrollDOM.appendChild(document.createElement("div")),this.dom.classList.add("cm-layer"),t.above&&this.dom.classList.add("cm-layer-above"),t.class&&this.dom.classList.add(t.class),this.scale(),this.dom.setAttribute("aria-hidden","true"),this.setOrder(e.state),e.requestMeasure(this.measureReq),t.mount&&t.mount(this.dom,e)}update(e){e.startState.facet(Us)!=e.state.facet(Us)&&this.setOrder(e.state),(this.layer.update(e,this.dom)||e.geometryChanged)&&(this.scale(),e.view.requestMeasure(this.measureReq))}docViewUpdate(e){this.layer.updateOnDocViewUpdate!==!1&&e.requestMeasure(this.measureReq)}setOrder(e){let t=0,i=e.facet(Us);for(;t!dm(t,this.drawn[i]))){let t=this.dom.firstChild,i=0;for(let n of e)n.update&&t&&n.constructor&&this.drawn[i].constructor&&n.update(t,this.drawn[i])?(t=t.nextSibling,i++):this.dom.insertBefore(n.draw(),t);for(;t;){let n=t.nextSibling;t.remove(),t=n}this.drawn=e,W.webkit&&(this.dom.style.display=this.dom.firstChild?"":"none")}}destroy(){this.layer.destroy&&this.layer.destroy(this.dom,this.view),this.dom.remove()}}const Us=I.define();function zc(s){return[se.define(e=>new pm(e,s)),Us.of(s)]}const wi=I.define({combine(s){return ht(s,{cursorBlinkRate:1200,drawRangeCursor:!0,iosSelectionHandles:!0},{cursorBlinkRate:(e,t)=>Math.min(e,t),drawRangeCursor:(e,t)=>e||t})}});function mm(s={}){return[wi.of(s),gm,xm,bm,dc.of(!0)]}function Qc(s){return s.startState.facet(wi)!=s.state.facet(wi)}const gm=zc({above:!0,markers(s){let{state:e}=s,t=e.facet(wi),i=[];for(let n of e.selection.ranges){let r=n==e.selection.main;if(n.empty||t.drawRangeCursor&&!(r&&W.ios&&t.iosSelectionHandles)){let o=r?"cm-cursor cm-cursor-primary":"cm-cursor cm-cursor-secondary",l=n.empty?n:v.cursor(n.head,n.assoc);for(let a of Ut.forRange(s,o,l))i.push(a)}}return i},update(s,e){s.transactions.some(i=>i.selection)&&(e.style.animationName=e.style.animationName=="cm-blink"?"cm-blink2":"cm-blink");let t=Qc(s);return t&&da(s.state,e),s.docChanged||s.selectionSet||t},mount(s,e){da(e.state,s)},class:"cm-cursorLayer"});function da(s,e){e.style.animationDuration=s.facet(wi).cursorBlinkRate+"ms"}const xm=zc({above:!1,markers(s){let e=[],{main:t,ranges:i}=s.state.selection;for(let n of i)if(!n.empty)for(let r of Ut.forRange(s,"cm-selectionBackground",n))e.push(r);if(W.ios&&!t.empty&&s.state.facet(wi).iosSelectionHandles){for(let n of Ut.forRange(s,"cm-selectionHandle cm-selectionHandle-start",v.cursor(t.from,1)))e.push(n);for(let n of Ut.forRange(s,"cm-selectionHandle cm-selectionHandle-end",v.cursor(t.to,1)))e.push(n)}return e},update(s,e){return s.docChanged||s.selectionSet||s.viewportChanged||Qc(s)},class:"cm-selectionLayer"}),bm=ei.highest(L.theme({".cm-line":{"& ::selection, &::selection":{backgroundColor:"transparent !important"},caretColor:"transparent !important"},".cm-content":{caretColor:"transparent !important","& :focus":{caretColor:"initial !important","&::selection, & ::selection":{backgroundColor:"Highlight !important"}}}})),$c=$.define({map(s,e){return s==null?null:e.mapPos(s)}}),Ii=ye.define({create(){return null},update(s,e){return s!=null&&(s=e.changes.mapPos(s)),e.effects.reduce((t,i)=>i.is($c)?i.value:t,s)}}),ym=se.fromClass(class{constructor(s){this.view=s,this.cursor=null,this.measureReq={read:this.readPos.bind(this),write:this.drawCursor.bind(this)}}update(s){var e;let t=s.state.field(Ii);t==null?this.cursor!=null&&((e=this.cursor)===null||e===void 0||e.remove(),this.cursor=null):(this.cursor||(this.cursor=this.view.scrollDOM.appendChild(document.createElement("div")),this.cursor.className="cm-dropCursor"),(s.startState.field(Ii)!=t||s.docChanged||s.geometryChanged)&&this.view.requestMeasure(this.measureReq))}readPos(){let{view:s}=this,e=s.state.field(Ii),t=e!=null&&s.coordsAtPos(e);if(!t)return null;let i=s.scrollDOM.getBoundingClientRect();return{left:t.left-i.left+s.scrollDOM.scrollLeft*s.scaleX,top:t.top-i.top+s.scrollDOM.scrollTop*s.scaleY,height:t.bottom-t.top}}drawCursor(s){if(this.cursor){let{scaleX:e,scaleY:t}=this.view;s?(this.cursor.style.left=s.left/e+"px",this.cursor.style.top=s.top/t+"px",this.cursor.style.height=s.height/t+"px"):this.cursor.style.left="-100000px"}}destroy(){this.cursor&&this.cursor.remove()}setDropPos(s){this.view.state.field(Ii)!=s&&this.view.dispatch({effects:$c.of(s)})}},{eventObservers:{dragover(s){this.setDropPos(this.view.posAtCoords({x:s.clientX,y:s.clientY}))},dragleave(s){(s.target==this.view.contentDOM||!this.view.contentDOM.contains(s.relatedTarget))&&this.setDropPos(null)},dragend(){this.setDropPos(null)},drop(){this.setDropPos(null)}}});function km(){return[Ii,ym]}function pa(s,e,t,i,n){e.lastIndex=0;for(let r=s.iterRange(t,i),o=t,l;!r.next().done;o+=r.value.length)if(!r.lineBreak)for(;l=e.exec(r.value);)n(o+l.index,l)}function wm(s,e){let t=s.visibleRanges;if(t.length==1&&t[0].from==s.viewport.from&&t[0].to==s.viewport.to)return t;let i=[];for(let{from:n,to:r}of t)n=Math.max(s.state.doc.lineAt(n).from,n-e),r=Math.min(s.state.doc.lineAt(r).to,r+e),i.length&&i[i.length-1].to>=n?i[i.length-1].to=r:i.push({from:n,to:r});return i}class vm{constructor(e){const{regexp:t,decoration:i,decorate:n,boundary:r,maxLength:o=1e3}=e;if(!t.global)throw new RangeError("The regular expression given to MatchDecorator should have its 'g' flag set");if(this.regexp=t,n)this.addMatch=(l,a,h,c)=>n(c,h,h+l[0].length,l,a);else if(typeof i=="function")this.addMatch=(l,a,h,c)=>{let f=i(l,a,h);f&&c(h,h+l[0].length,f)};else if(i)this.addMatch=(l,a,h,c)=>c(h,h+l[0].length,i);else throw new RangeError("Either 'decorate' or 'decoration' should be provided to MatchDecorator");this.boundary=r,this.maxLength=o}createDeco(e){let t=new mt,i=t.add.bind(t);for(let{from:n,to:r}of wm(e,this.maxLength))pa(e.state.doc,this.regexp,n,r,(o,l)=>this.addMatch(l,e,o,i));return t.finish()}updateDeco(e,t){let i=1e9,n=-1;return e.docChanged&&e.changes.iterChanges((r,o,l,a)=>{a>=e.view.viewport.from&&l<=e.view.viewport.to&&(i=Math.min(l,i),n=Math.max(a,n))}),e.viewportMoved||n-i>1e3?this.createDeco(e.view):n>-1?this.updateRange(e.view,t.map(e.changes),i,n):t}updateRange(e,t,i,n){for(let r of e.visibleRanges){let o=Math.max(r.from,i),l=Math.min(r.to,n);if(l>=o){let a=e.state.doc.lineAt(o),h=a.toa.from;o--)if(this.boundary.test(a.text[o-1-a.from])){c=o;break}for(;lu.push(x.range(m,g));if(a==h)for(this.regexp.lastIndex=c-a.from;(d=this.regexp.exec(a.text))&&d.indexthis.addMatch(g,e,m,p));t=t.update({filterFrom:c,filterTo:f,filter:(m,g)=>mf,add:u})}}return t}}const ao=/x/.unicode!=null?"gu":"g",Sm=new RegExp(`[\0-\b +--Ÿ­؜​‎‏\u2028\u2029‭‮⁦⁧⁩\uFEFF-]`,ao),Om={0:"null",7:"bell",8:"backspace",10:"newline",11:"vertical tab",13:"carriage return",27:"escape",8203:"zero width space",8204:"zero width non-joiner",8205:"zero width joiner",8206:"left-to-right mark",8207:"right-to-left mark",8232:"line separator",8237:"left-to-right override",8238:"right-to-left override",8294:"left-to-right isolate",8295:"right-to-left isolate",8297:"pop directional isolate",8233:"paragraph separator",65279:"zero width no-break space",65532:"object replacement"};let or=null;function Cm(){var s;if(or==null&&typeof document<"u"&&document.body){let e=document.body.style;or=((s=e.tabSize)!==null&&s!==void 0?s:e.MozTabSize)!=null}return or||!1}const Ys=I.define({combine(s){let e=ht(s,{render:null,specialChars:Sm,addSpecialChars:null});return(e.replaceTabs=!Cm())&&(e.specialChars=new RegExp(" |"+e.specialChars.source,ao)),e.addSpecialChars&&(e.specialChars=new RegExp(e.specialChars.source+"|"+e.addSpecialChars.source,ao)),e}});function Am(s={}){return[Ys.of(s),Mm()]}let ma=null;function Mm(){return ma||(ma=se.fromClass(class{constructor(s){this.view=s,this.decorations=z.none,this.decorationCache=Object.create(null),this.decorator=this.makeDecorator(s.state.facet(Ys)),this.decorations=this.decorator.createDeco(s)}makeDecorator(s){return new vm({regexp:s.specialChars,decoration:(e,t,i)=>{let{doc:n}=t.state,r=Ce(e[0],0);if(r==9){let o=n.lineAt(i),l=t.state.tabSize,a=Ci(o.text,l,i-o.from);return z.replace({widget:new Rm((l-a%l)*this.view.defaultCharacterWidth/this.view.scaleX)})}return this.decorationCache[r]||(this.decorationCache[r]=z.replace({widget:new Dm(s,r)}))},boundary:s.replaceTabs?void 0:/[^]/})}update(s){let e=s.state.facet(Ys);s.startState.facet(Ys)!=e?(this.decorator=this.makeDecorator(e),this.decorations=this.decorator.createDeco(s.view)):this.decorations=this.decorator.updateDeco(s,this.decorations)}},{decorations:s=>s.decorations}))}const Pm="•";function Tm(s){return s>=32?Pm:s==10?"␤":String.fromCharCode(9216+s)}class Dm extends ct{constructor(e,t){super(),this.options=e,this.code=t}eq(e){return e.code==this.code}toDOM(e){let t=Tm(this.code),i=e.state.phrase("Control character")+" "+(Om[this.code]||"0x"+this.code.toString(16)),n=this.options.render&&this.options.render(this.code,i,t);if(n)return n;let r=document.createElement("span");return r.textContent=t,r.title=i,r.setAttribute("aria-label",i),r.className="cm-specialChar",r}ignoreEvent(){return!1}}class Rm extends ct{constructor(e){super(),this.width=e}eq(e){return e.width==this.width}toDOM(){let e=document.createElement("span");return e.textContent=" ",e.className="cm-tab",e.style.width=this.width+"px",e}ignoreEvent(){return!1}}function Bm(){return Lm}const Em=z.line({class:"cm-activeLine"}),Lm=se.fromClass(class{constructor(s){this.decorations=this.getDeco(s)}update(s){(s.docChanged||s.selectionSet)&&(this.decorations=this.getDeco(s.view))}getDeco(s){let e=-1,t=[];for(let i of s.state.selection.ranges){let n=s.lineBlockAt(i.head);n.from>e&&(t.push(Em.range(n.from)),e=n.from)}return z.set(t)}},{decorations:s=>s.decorations});class Nm extends ct{constructor(e){super(),this.content=e}toDOM(e){let t=document.createElement("span");return t.className="cm-placeholder",t.style.pointerEvents="none",t.appendChild(typeof this.content=="string"?document.createTextNode(this.content):typeof this.content=="function"?this.content(e):this.content.cloneNode(!0)),t.setAttribute("aria-hidden","true"),t}coordsAt(e){let t=e.firstChild?Hi(e.firstChild):[];if(!t.length)return null;let i=window.getComputedStyle(e.parentNode),n=Gi(t[0],i.direction!="rtl"),r=parseInt(i.lineHeight);return n.bottom-n.top>r*1.5?{left:n.left,right:n.right,top:n.top,bottom:n.top+r}:n}ignoreEvent(){return!1}}function Im(s){let e=se.fromClass(class{constructor(t){this.view=t,this.placeholder=s?z.set([z.widget({widget:new Nm(s),side:1}).range(0)]):z.none}get decorations(){return this.view.state.doc.length?z.none:this.placeholder}},{decorations:t=>t.decorations});return typeof s=="string"?[e,L.contentAttributes.of({"aria-placeholder":s})]:e}const ho=2e3;function Wm(s,e,t){let i=Math.min(e.line,t.line),n=Math.max(e.line,t.line),r=[];if(e.off>ho||t.off>ho||e.col<0||t.col<0){let o=Math.min(e.off,t.off),l=Math.max(e.off,t.off);for(let a=i;a<=n;a++){let h=s.doc.line(a);h.length<=l&&r.push(v.range(h.from+o,h.to+l))}}else{let o=Math.min(e.col,t.col),l=Math.max(e.col,t.col);for(let a=i;a<=n;a++){let h=s.doc.line(a),c=Qr(h.text,o,s.tabSize,!0);if(c<0)r.push(v.cursor(h.to));else{let f=Qr(h.text,l,s.tabSize);r.push(v.range(h.from+c,h.from+f))}}}return r}function Fm(s,e){let t=s.coordsAtPos(s.viewport.from);return t?Math.round(Math.abs((t.left-e)/s.defaultCharacterWidth)):-1}function ga(s,e){let t=s.posAtCoords({x:e.clientX,y:e.clientY},!1),i=s.state.doc.lineAt(t),n=t-i.from,r=n>ho?-1:n==i.length?Fm(s,e.clientX):Ci(i.text,s.state.tabSize,t-i.from);return{line:i.number,col:r,off:n}}function Vm(s,e){let t=ga(s,e),i=s.state.selection;return t?{update(n){if(n.docChanged){let r=n.changes.mapPos(n.startState.doc.line(t.line).from),o=n.state.doc.lineAt(r);t={line:o.number,col:t.col,off:Math.min(t.off,o.length)},i=i.map(n.changes)}},get(n,r,o){let l=ga(s,n);if(!l)return i;let a=Wm(s.state,t,l);return a.length?o?v.create(a.concat(i.ranges)):v.create(a):i}}:null}function Hm(s){let e=(t=>t.altKey&&t.button==0);return L.mouseSelectionStyle.of((t,i)=>e(i)?Vm(t,i):null)}const zm={Alt:[18,s=>!!s.altKey],Control:[17,s=>!!s.ctrlKey],Shift:[16,s=>!!s.shiftKey],Meta:[91,s=>!!s.metaKey]},Qm={style:"cursor: crosshair"};function $m(s={}){let[e,t]=zm[s.key||"Alt"],i=se.fromClass(class{constructor(n){this.view=n,this.isDown=!1}set(n){this.isDown!=n&&(this.isDown=n,this.view.update([]))}},{eventObservers:{keydown(n){this.set(n.keyCode==e||t(n))},keyup(n){(n.keyCode==e||!t(n))&&this.set(!1)},mousemove(n){this.set(t(n))}}});return[i,L.contentAttributes.of(n=>{var r;return!((r=n.plugin(i))===null||r===void 0)&&r.isDown?Qm:null})]}const Rs="-10000px";class jc{constructor(e,t,i,n){this.facet=t,this.createTooltipView=i,this.removeTooltipView=n,this.input=e.state.facet(t),this.tooltips=this.input.filter(o=>o);let r=null;this.tooltipViews=this.tooltips.map(o=>r=i(o,r))}update(e,t){var i;let n=e.state.facet(this.facet),r=n.filter(a=>a);if(n===this.input){for(let a of this.tooltipViews)a.update&&a.update(e);return!1}let o=[],l=t?[]:null;for(let a=0;at[h]=a),t.length=l.length),this.input=n,this.tooltips=r,this.tooltipViews=o,!0}}function jm(s){let e=s.dom.ownerDocument.documentElement;return{top:0,left:0,bottom:e.clientHeight,right:e.clientWidth}}const lr=I.define({combine:s=>{var e,t,i;return{position:W.ios?"absolute":((e=s.find(n=>n.position))===null||e===void 0?void 0:e.position)||"fixed",parent:((t=s.find(n=>n.parent))===null||t===void 0?void 0:t.parent)||null,tooltipSpace:((i=s.find(n=>n.tooltipSpace))===null||i===void 0?void 0:i.tooltipSpace)||jm}}}),xa=new WeakMap,Uo=se.fromClass(class{constructor(s){this.view=s,this.above=[],this.inView=!0,this.madeAbsolute=!1,this.lastTransaction=0,this.measureTimeout=-1;let e=s.state.facet(lr);this.position=e.position,this.parent=e.parent,this.classes=s.themeClasses,this.createContainer(),this.measureReq={read:this.readMeasure.bind(this),write:this.writeMeasure.bind(this),key:this},this.resizeObserver=typeof ResizeObserver=="function"?new ResizeObserver(()=>this.measureSoon()):null,this.manager=new jc(s,Yo,(t,i)=>this.createTooltip(t,i),t=>{this.resizeObserver&&this.resizeObserver.unobserve(t.dom),t.dom.remove()}),this.above=this.manager.tooltips.map(t=>!!t.above),this.intersectionObserver=typeof IntersectionObserver=="function"?new IntersectionObserver(t=>{Date.now()>this.lastTransaction-50&&t.length>0&&t[t.length-1].intersectionRatio<1&&this.measureSoon()},{threshold:[1]}):null,this.observeIntersection(),s.win.addEventListener("resize",this.measureSoon=this.measureSoon.bind(this)),this.maybeMeasure()}createContainer(){this.parent?(this.container=document.createElement("div"),this.container.style.position="relative",this.container.className=this.view.themeClasses,this.parent.appendChild(this.container)):this.container=this.view.dom}observeIntersection(){if(this.intersectionObserver){this.intersectionObserver.disconnect();for(let s of this.manager.tooltipViews)this.intersectionObserver.observe(s.dom)}}measureSoon(){this.measureTimeout<0&&(this.measureTimeout=setTimeout(()=>{this.measureTimeout=-1,this.maybeMeasure()},50))}update(s){s.transactions.length&&(this.lastTransaction=Date.now());let e=this.manager.update(s,this.above);e&&this.observeIntersection();let t=e||s.geometryChanged,i=s.state.facet(lr);if(i.position!=this.position&&!this.madeAbsolute){this.position=i.position;for(let n of this.manager.tooltipViews)n.dom.style.position=this.position;t=!0}if(i.parent!=this.parent){this.parent&&this.container.remove(),this.parent=i.parent,this.createContainer();for(let n of this.manager.tooltipViews)this.container.appendChild(n.dom);t=!0}else this.parent&&this.view.themeClasses!=this.classes&&(this.classes=this.container.className=this.view.themeClasses);t&&this.maybeMeasure()}createTooltip(s,e){let t=s.create(this.view),i=e?e.dom:null;if(t.dom.classList.add("cm-tooltip"),s.arrow&&!t.dom.querySelector(".cm-tooltip > .cm-tooltip-arrow")){let n=document.createElement("div");n.className="cm-tooltip-arrow",t.dom.appendChild(n)}return t.dom.style.position=this.position,t.dom.style.top=Rs,t.dom.style.left="0px",this.container.insertBefore(t.dom,i),t.mount&&t.mount(this.view),this.resizeObserver&&this.resizeObserver.observe(t.dom),t}destroy(){var s,e,t;this.view.win.removeEventListener("resize",this.measureSoon);for(let i of this.manager.tooltipViews)i.dom.remove(),(s=i.destroy)===null||s===void 0||s.call(i);this.parent&&this.container.remove(),(e=this.resizeObserver)===null||e===void 0||e.disconnect(),(t=this.intersectionObserver)===null||t===void 0||t.disconnect(),clearTimeout(this.measureTimeout)}readMeasure(){let s=1,e=1,t=!1;if(this.position=="fixed"&&this.manager.tooltipViews.length){let{dom:r}=this.manager.tooltipViews[0];if(W.safari){let o=r.getBoundingClientRect();t=Math.abs(o.top+1e4)>1||Math.abs(o.left)>1}else t=!!r.offsetParent&&r.offsetParent!=this.container.ownerDocument.body}if(t||this.position=="absolute")if(this.parent){let r=this.parent.getBoundingClientRect();r.width&&r.height&&(s=r.width/this.parent.offsetWidth,e=r.height/this.parent.offsetHeight)}else({scaleX:s,scaleY:e}=this.view.viewState);let i=this.view.scrollDOM.getBoundingClientRect(),n=$o(this.view);return{visible:{left:i.left+n.left,top:i.top+n.top,right:i.right-n.right,bottom:i.bottom-n.bottom},parent:this.parent?this.container.getBoundingClientRect():this.view.dom.getBoundingClientRect(),pos:this.manager.tooltips.map((r,o)=>{let l=this.manager.tooltipViews[o];return l.getCoords?l.getCoords(r.pos):this.view.coordsAtPos(r.pos)}),size:this.manager.tooltipViews.map(({dom:r})=>r.getBoundingClientRect()),space:this.view.state.facet(lr).tooltipSpace(this.view),scaleX:s,scaleY:e,makeAbsolute:t}}writeMeasure(s){var e;if(s.makeAbsolute){this.madeAbsolute=!0,this.position="absolute";for(let l of this.manager.tooltipViews)l.dom.style.position="absolute"}let{visible:t,space:i,scaleX:n,scaleY:r}=s,o=[];for(let l=0;l=Math.min(t.bottom,i.bottom)||f.rightMath.min(t.right,i.right)+.1)){c.style.top=Rs;continue}let d=a.arrow?h.dom.querySelector(".cm-tooltip-arrow"):null,p=d?7:0,m=u.right-u.left,g=(e=xa.get(h))!==null&&e!==void 0?e:u.bottom-u.top,x=h.offset||Xm,k=this.view.textDirection==J.LTR,w=u.width>i.right-i.left?k?i.left:i.right-u.width:k?Math.max(i.left,Math.min(f.left-(d?14:0)+x.x,i.right-m)):Math.min(Math.max(i.left,f.left-m+(d?14:0)-x.x),i.right-m),T=this.above[l];!a.strictSide&&(T?f.top-g-p-x.yi.bottom)&&T==i.bottom-f.bottom>f.top-i.top&&(T=this.above[l]=!T);let S=(T?f.top-i.top:i.bottom-f.bottom)-p;if(Sw&&V.topA&&(A=T?V.top-g-2-p:V.bottom+p+2);if(this.position=="absolute"?(c.style.top=(A-s.parent.top)/r+"px",ba(c,(w-s.parent.left)/n)):(c.style.top=A/r+"px",ba(c,w/n)),d){let V=f.left+(k?x.x:-x.x)-(w+14-7);d.style.left=V/n+"px"}h.overlap!==!0&&o.push({left:w,top:A,right:O,bottom:A+g}),c.classList.toggle("cm-tooltip-above",T),c.classList.toggle("cm-tooltip-below",!T),h.positioned&&h.positioned(s.space)}}maybeMeasure(){if(this.manager.tooltips.length&&(this.view.inView&&this.view.requestMeasure(this.measureReq),this.inView!=this.view.inView&&(this.inView=this.view.inView,!this.inView)))for(let s of this.manager.tooltipViews)s.dom.style.top=Rs}},{eventObservers:{scroll(){this.maybeMeasure()}}});function ba(s,e){let t=parseInt(s.style.left,10);(isNaN(t)||Math.abs(e-t)>1)&&(s.style.left=e+"px")}const qm=L.baseTheme({".cm-tooltip":{zIndex:500,boxSizing:"border-box"},"&light .cm-tooltip":{border:"1px solid #bbb",backgroundColor:"#f5f5f5"},"&light .cm-tooltip-section:not(:first-child)":{borderTop:"1px solid #bbb"},"&dark .cm-tooltip":{backgroundColor:"#333338",color:"white"},".cm-tooltip-arrow":{height:"7px",width:"14px",position:"absolute",zIndex:-1,overflow:"hidden","&:before, &:after":{content:"''",position:"absolute",width:0,height:0,borderLeft:"7px solid transparent",borderRight:"7px solid transparent"},".cm-tooltip-above &":{bottom:"-7px","&:before":{borderTop:"7px solid #bbb"},"&:after":{borderTop:"7px solid #f5f5f5",bottom:"1px"}},".cm-tooltip-below &":{top:"-7px","&:before":{borderBottom:"7px solid #bbb"},"&:after":{borderBottom:"7px solid #f5f5f5",top:"1px"}}},"&dark .cm-tooltip .cm-tooltip-arrow":{"&:before":{borderTopColor:"#333338",borderBottomColor:"#333338"},"&:after":{borderTopColor:"transparent",borderBottomColor:"transparent"}}}),Xm={x:0,y:0},Yo=I.define({enables:[Uo,qm]}),fn=I.define({combine:s=>s.reduce((e,t)=>e.concat(t),[])});class Wn{static create(e){return new Wn(e)}constructor(e){this.view=e,this.mounted=!1,this.dom=document.createElement("div"),this.dom.classList.add("cm-tooltip-hover"),this.manager=new jc(e,fn,(t,i)=>this.createHostedView(t,i),t=>t.dom.remove())}createHostedView(e,t){let i=e.create(this.view);return i.dom.classList.add("cm-tooltip-section"),this.dom.insertBefore(i.dom,t?t.dom.nextSibling:this.dom.firstChild),this.mounted&&i.mount&&i.mount(this.view),i}mount(e){for(let t of this.manager.tooltipViews)t.mount&&t.mount(e);this.mounted=!0}positioned(e){for(let t of this.manager.tooltipViews)t.positioned&&t.positioned(e)}update(e){this.manager.update(e)}destroy(){var e;for(let t of this.manager.tooltipViews)(e=t.destroy)===null||e===void 0||e.call(t)}passProp(e){let t;for(let i of this.manager.tooltipViews){let n=i[e];if(n!==void 0){if(t===void 0)t=n;else if(t!==n)return}}return t}get offset(){return this.passProp("offset")}get getCoords(){return this.passProp("getCoords")}get overlap(){return this.passProp("overlap")}get resize(){return this.passProp("resize")}}const Um=Yo.compute([fn],s=>{let e=s.facet(fn);return e.length===0?null:{pos:Math.min(...e.map(t=>t.pos)),end:Math.max(...e.map(t=>{var i;return(i=t.end)!==null&&i!==void 0?i:t.pos})),create:Wn.create,above:e[0].above,arrow:e.some(t=>t.arrow)}}),qc=I.define();class Ym{constructor(e,t,i,n,r,o){this.view=e,this.source=t,this.field=i,this.locked=n,this.setHover=r,this.hoverTime=o,this.hoverTimeout=-1,this.restartTimeout=-1,this.pending=null,this.lastMove={x:0,y:0,target:e.dom,time:0},this.checkHover=this.checkHover.bind(this),e.dom.addEventListener("mouseleave",this.mouseleave=this.mouseleave.bind(this)),e.dom.addEventListener("mousemove",this.mousemove=this.mousemove.bind(this))}update(e){this.pending&&(this.pending=null,clearTimeout(this.restartTimeout),this.restartTimeout=setTimeout(()=>this.startHover(),20))}get active(){return this.view.state.field(this.field)}checkHover(){if(this.hoverTimeout=-1,this.active.length)return;let e=Date.now()-this.lastMove.time;eo.bottom||t.xo.right+e.defaultCharacterWidth)return;let l=e.bidiSpans(e.state.doc.lineAt(n)).find(h=>h.from<=n&&h.to>=n),a=l&&l.dir==J.RTL?-1:1;r=t.x{if(l&&!(Array.isArray(l)&&!l.length)){let a=Array.isArray(l)?l:[l];n&&this.locked.set(a,n),e.dispatch({effects:this.setHover.of(a)})}};if(r&&"then"in r){let l=this.pending={pos:t};r.then(a=>{this.pending==l&&(this.pending=null,o(a))},a=>Pe(e.state,a,"hover tooltip"))}else o(r)}get tooltip(){let e=this.view.plugin(Uo),t=e?e.manager.tooltips.findIndex(i=>i.create==Wn.create):-1;return t>-1?e.manager.tooltipViews[t]:null}mousemove(e){var t,i;this.lastMove={x:e.clientX,y:e.clientY,target:e.target,time:Date.now()},this.hoverTimeout<0&&(this.hoverTimeout=setTimeout(this.checkHover,this.hoverTime));let{active:n,tooltip:r}=this;if(n.length&&!this.locked.has(n)&&r&&!_m(r.dom,e)||this.pending){let{pos:o}=n[0]||this.pending,l=(i=(t=n[0])===null||t===void 0?void 0:t.end)!==null&&i!==void 0?i:o;(o==l?this.view.posAtCoords(this.lastMove)!=o:!Km(this.view,o,l,e.clientX,e.clientY))&&(this.view.dispatch({effects:this.setHover.of([])}),this.pending=null)}}mouseleave(e){clearTimeout(this.hoverTimeout),this.hoverTimeout=-1;let{active:t}=this;if(t.length&&!this.locked.has(t)){let{tooltip:i}=this;i&&i.dom.contains(e.relatedTarget)?this.watchTooltipLeave(i.dom):this.view.dispatch({effects:this.setHover.of([])})}}watchTooltipLeave(e){let t=i=>{e.removeEventListener("mouseleave",t);let{active:n}=this;n.length&&!this.locked.has(n)&&!this.view.dom.contains(i.relatedTarget)&&this.view.dispatch({effects:this.setHover.of([])})};e.addEventListener("mouseleave",t)}destroy(){clearTimeout(this.hoverTimeout),clearTimeout(this.restartTimeout),this.view.dom.removeEventListener("mouseleave",this.mouseleave),this.view.dom.removeEventListener("mousemove",this.mousemove)}}const Bs=4;function _m(s,e){let{left:t,right:i,top:n,bottom:r}=s.getBoundingClientRect(),o;if(o=s.querySelector(".cm-tooltip-arrow")){let l=o.getBoundingClientRect();n=Math.min(l.top,n),r=Math.max(l.bottom,r)}return e.clientX>=t-Bs&&e.clientX<=i+Bs&&e.clientY>=n-Bs&&e.clientY<=r+Bs}function Km(s,e,t,i,n,r){let o=s.scrollDOM.getBoundingClientRect(),l=s.documentTop+s.documentPadding.top+s.contentHeight;if(o.left>i||o.rightn||Math.min(o.bottom,l)=e&&a<=t}function Gm(s,e={}){let t=$.define(),i=new WeakMap,n=ye.define({create(){return[]},update(o,l){let a=i.get(o);if(o.length&&(e.hideOnChange&&(l.docChanged||l.selection)?o=[]:a&&a(l)?o=[]:e.hideOn&&(o=o.filter(h=>!e.hideOn(l,h)))),l.docChanged&&o.length){let h=[];for(let c of o){let f=l.changes.mapPos(c.pos,-1,Se.TrackDel);if(f!=null){let u=Object.assign(Object.create(null),c);u.pos=f,u.end!=null&&(u.end=l.changes.mapPos(u.end)),h.push(u)}}o=h}for(let h of l.effects)h.is(t)&&(o=h.value,a=void 0),(h.is(Zm)&&!h.value||h.value==n)&&(o=[]);return o.length&&a&&i.set(o,a),o},provide:o=>fn.from(o)});const r=se.define(o=>new Ym(o,s,n,i,t,e.hoverTime||300));return{active:n,extension:[n,r,qc.of(r),Um]}}function Jm(s,e,t,i={}){var n;let r=s.state.facet(qc).map(o=>s.plugin(o)).filter(o=>!!o);if(i.tooltip&&i.tooltip.active){let o=r.find(l=>l.field==i.tooltip.active);o&&(r=[o])}for(let o of r)o.activateHover(s,e,t,(n=i.until)!==null&&n!==void 0?n:(()=>!1))}function Xc(s,e){let t=s.plugin(Uo);if(!t)return null;let i=t.manager.tooltips.indexOf(e);return i<0?null:t.manager.tooltipViews[i]}const Zm=$.define(),ya=I.define({combine(s){let e,t;for(let i of s)e=e||i.topContainer,t=t||i.bottomContainer;return{topContainer:e,bottomContainer:t}}});function _o(s,e){let t=s.plugin(Uc),i=t?t.specs.indexOf(e):-1;return i>-1?t.panels[i]:null}const Uc=se.fromClass(class{constructor(s){this.input=s.state.facet(Zi),this.specs=this.input.filter(t=>t),this.panels=this.specs.map(t=>t(s));let e=s.state.facet(ya);this.top=new Es(s,!0,e.topContainer),this.bottom=new Es(s,!1,e.bottomContainer),this.top.sync(this.panels.filter(t=>t.top)),this.bottom.sync(this.panels.filter(t=>!t.top));for(let t of this.panels)t.dom.classList.add("cm-panel"),t.mount&&t.mount()}update(s){let e=s.state.facet(ya);this.top.container!=e.topContainer&&(this.top.sync([]),this.top=new Es(s.view,!0,e.topContainer)),this.bottom.container!=e.bottomContainer&&(this.bottom.sync([]),this.bottom=new Es(s.view,!1,e.bottomContainer)),this.top.syncClasses(),this.bottom.syncClasses();let t=s.state.facet(Zi);if(t!=this.input){let i=t.filter(a=>a),n=[],r=[],o=[],l=[];for(let a of i){let h=this.specs.indexOf(a),c;h<0?(c=a(s.view),l.push(c)):(c=this.panels[h],c.update&&c.update(s)),n.push(c),(c.top?r:o).push(c)}this.specs=i,this.panels=n,this.top.sync(r),this.bottom.sync(o);for(let a of l)a.dom.classList.add("cm-panel"),a.mount&&a.mount()}else for(let i of this.panels)i.update&&i.update(s)}destroy(){this.top.sync([]),this.bottom.sync([])}},{provide:s=>L.scrollMargins.of(e=>{let t=e.plugin(s);return t&&{top:t.top.scrollMargin(),bottom:t.bottom.scrollMargin()}})});class Es{constructor(e,t,i){this.view=e,this.top=t,this.container=i,this.dom=void 0,this.classes="",this.panels=[],this.syncClasses()}sync(e){for(let t of this.panels)t.destroy&&e.indexOf(t)<0&&t.destroy();this.panels=e,this.syncDOM()}syncDOM(){if(this.panels.length==0){this.dom&&(this.dom.remove(),this.dom=void 0);return}if(!this.dom){this.dom=document.createElement("div"),this.dom.className=this.top?"cm-panels cm-panels-top":"cm-panels cm-panels-bottom",this.dom.style[this.top?"top":"bottom"]="0";let t=this.container||this.view.dom;t.insertBefore(this.dom,this.top?t.firstChild:null)}let e=this.dom.firstChild;for(let t of this.panels)if(t.dom.parentNode==this.dom){for(;e!=t.dom;)e=ka(e);e=e.nextSibling}else this.dom.insertBefore(t.dom,e);for(;e;)e=ka(e)}scrollMargin(){return!this.dom||this.container?0:Math.max(0,this.top?this.dom.getBoundingClientRect().bottom-Math.max(0,this.view.scrollDOM.getBoundingClientRect().top):Math.min(innerHeight,this.view.scrollDOM.getBoundingClientRect().bottom)-this.dom.getBoundingClientRect().top)}syncClasses(){if(!(!this.container||this.classes==this.view.themeClasses)){for(let e of this.classes.split(" "))e&&this.container.classList.remove(e);for(let e of(this.classes=this.view.themeClasses).split(" "))e&&this.container.classList.add(e)}}}function ka(s){let e=s.nextSibling;return s.remove(),e}const Zi=I.define({enables:Uc});function eg(s,e){let t,i=new Promise(o=>t=o),n=o=>tg(o,e,t);s.state.field(ar,!1)?s.dispatch({effects:Yc.of(n)}):s.dispatch({effects:$.appendConfig.of(ar.init(()=>[n]))});let r=_c.of(n);return{close:r,result:i.then(o=>((s.win.queueMicrotask||(a=>s.win.setTimeout(a,10)))(()=>{s.state.field(ar).indexOf(n)>-1&&s.dispatch({effects:r})}),o))}}const ar=ye.define({create(){return[]},update(s,e){for(let t of e.effects)t.is(Yc)?s=[t.value].concat(s):t.is(_c)&&(s=s.filter(i=>i!=t.value));return s},provide:s=>Zi.computeN([s],e=>e.field(s))}),Yc=$.define(),_c=$.define();function tg(s,e,t){let i=e.content?e.content(s,()=>o(null)):null;if(!i){if(i=_("form"),e.input){let l=_("input",e.input);/^(text|password|number|email|tel|url)$/.test(l.type)&&l.classList.add("cm-textfield"),l.name||(l.name="input"),i.appendChild(_("label",(e.label||"")+": ",l))}else i.appendChild(document.createTextNode(e.label||""));i.appendChild(document.createTextNode(" ")),i.appendChild(_("button",{class:"cm-button",type:"submit"},e.submitLabel||"OK"))}let n=i.nodeName=="FORM"?[i]:i.querySelectorAll("form");for(let l=0;l{h.keyCode==27?(h.preventDefault(),o(null)):h.keyCode==13&&(h.preventDefault(),o(a))}),a.addEventListener("submit",h=>{h.preventDefault(),o(a)})}let r=_("div",i,_("button",{onclick:()=>o(null),"aria-label":s.state.phrase("close"),class:"cm-dialog-close",type:"button"},["×"]));e.class&&(r.className=e.class),r.classList.add("cm-dialog");function o(l){r.contains(r.ownerDocument.activeElement)&&s.focus(),t(l)}return{dom:r,top:e.top,mount:()=>{if(e.focus){let l;typeof e.focus=="string"?l=i.querySelector(e.focus):l=i.querySelector("input")||i.querySelector("button"),l&&"select"in l?l.select():l&&"focus"in l&&l.focus()}}}}class xt extends Mt{compare(e){return this==e||this.constructor==e.constructor&&this.eq(e)}eq(e){return!1}destroy(e){}}xt.prototype.elementClass="";xt.prototype.toDOM=void 0;xt.prototype.mapMode=Se.TrackBefore;xt.prototype.startSide=xt.prototype.endSide=-1;xt.prototype.point=!0;const _s=I.define(),ig=I.define(),sg={class:"",renderEmptyElements:!1,elementStyle:"",markers:()=>X.empty,lineMarker:()=>null,widgetMarker:()=>null,lineMarkerChange:null,initialSpacer:null,updateSpacer:null,domEventHandlers:{},side:"before"},$i=I.define();function ng(s){return[Kc(),$i.of({...sg,...s})]}const wa=I.define({combine:s=>s.some(e=>e)});function Kc(s){return[rg]}const rg=se.fromClass(class{constructor(s){this.view=s,this.domAfter=null,this.prevViewport=s.viewport,this.dom=document.createElement("div"),this.dom.className="cm-gutters cm-gutters-before",this.dom.setAttribute("aria-hidden","true"),this.dom.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.gutters=s.state.facet($i).map(e=>new Sa(s,e)),this.fixed=!s.state.facet(wa);for(let e of this.gutters)e.config.side=="after"?this.getDOMAfter().appendChild(e.dom):this.dom.appendChild(e.dom);this.fixed&&(this.dom.style.position="sticky"),this.syncGutters(!1),s.scrollDOM.insertBefore(this.dom,s.contentDOM)}getDOMAfter(){return this.domAfter||(this.domAfter=document.createElement("div"),this.domAfter.className="cm-gutters cm-gutters-after",this.domAfter.setAttribute("aria-hidden","true"),this.domAfter.style.minHeight=this.view.contentHeight/this.view.scaleY+"px",this.domAfter.style.position=this.fixed?"sticky":"",this.view.scrollDOM.appendChild(this.domAfter)),this.domAfter}update(s){if(this.updateGutters(s)){let e=this.prevViewport,t=s.view.viewport,i=Math.min(e.to,t.to)-Math.max(e.from,t.from);this.syncGutters(i<(t.to-t.from)*.8)}if(s.geometryChanged){let e=this.view.contentHeight/this.view.scaleY+"px";this.dom.style.minHeight=e,this.domAfter&&(this.domAfter.style.minHeight=e)}this.view.state.facet(wa)!=!this.fixed&&(this.fixed=!this.fixed,this.dom.style.position=this.fixed?"sticky":"",this.domAfter&&(this.domAfter.style.position=this.fixed?"sticky":"")),this.prevViewport=s.view.viewport}syncGutters(s){let e=this.dom.nextSibling;s&&(this.dom.remove(),this.domAfter&&this.domAfter.remove());let t=X.iter(this.view.state.facet(_s),this.view.viewport.from),i=[],n=this.gutters.map(r=>new og(r,this.view.viewport,-this.view.documentPadding.top));for(let r of this.view.viewportLineBlocks)if(i.length&&(i=[]),Array.isArray(r.type)){let o=!0;for(let l of r.type)if(l.type==ge.Text&&o){co(t,i,l.from);for(let a of n)a.line(this.view,l,i);o=!1}else if(l.widget)for(let a of n)a.widget(this.view,l)}else if(r.type==ge.Text){co(t,i,r.from);for(let o of n)o.line(this.view,r,i)}else if(r.widget)for(let o of n)o.widget(this.view,r);for(let r of n)r.finish();s&&(this.view.scrollDOM.insertBefore(this.dom,e),this.domAfter&&this.view.scrollDOM.appendChild(this.domAfter))}updateGutters(s){let e=s.startState.facet($i),t=s.state.facet($i),i=s.docChanged||s.heightChanged||s.viewportChanged||!X.eq(s.startState.facet(_s),s.state.facet(_s),s.view.viewport.from,s.view.viewport.to);if(e==t)for(let n of this.gutters)n.update(s)&&(i=!0);else{i=!0;let n=[];for(let r of t){let o=e.indexOf(r);o<0?n.push(new Sa(this.view,r)):(this.gutters[o].update(s),n.push(this.gutters[o]))}for(let r of this.gutters)r.dom.remove(),n.indexOf(r)<0&&r.destroy();for(let r of n)r.config.side=="after"?this.getDOMAfter().appendChild(r.dom):this.dom.appendChild(r.dom);this.gutters=n}return i}destroy(){for(let s of this.gutters)s.destroy();this.dom.remove(),this.domAfter&&this.domAfter.remove()}},{provide:s=>L.scrollMargins.of(e=>{let t=e.plugin(s);if(!t||t.gutters.length==0||!t.fixed)return null;let i=t.dom.offsetWidth*e.scaleX,n=t.domAfter?t.domAfter.offsetWidth*e.scaleX:0;return e.textDirection==J.LTR?{left:i,right:n}:{right:i,left:n}})});function va(s){return Array.isArray(s)?s:[s]}function co(s,e,t){for(;s.value&&s.from<=t;)s.from==t&&e.push(s.value),s.next()}class og{constructor(e,t,i){this.gutter=e,this.height=i,this.i=0,this.cursor=X.iter(e.markers,t.from)}addElement(e,t,i){let{gutter:n}=this,r=(t.top-this.height)/e.scaleY,o=t.height/e.scaleY;if(this.i==n.elements.length){let l=new Gc(e,o,r,i);n.elements.push(l),n.dom.appendChild(l.dom)}else n.elements[this.i].update(e,o,r,i);this.height=t.bottom,this.i++}line(e,t,i){let n=[];co(this.cursor,n,t.from),i.length&&(n=n.concat(i));let r=this.gutter.config.lineMarker(e,t,n);r&&n.unshift(r);let o=this.gutter;n.length==0&&!o.config.renderEmptyElements||this.addElement(e,t,n)}widget(e,t){let i=this.gutter.config.widgetMarker(e,t.widget,t),n=i?[i]:null;for(let r of e.state.facet(ig)){let o=r(e,t.widget,t);o&&(n||(n=[])).push(o)}n&&this.addElement(e,t,n)}finish(){let e=this.gutter;for(;e.elements.length>this.i;){let t=e.elements.pop();e.dom.removeChild(t.dom),t.destroy()}}}class Sa{constructor(e,t){this.view=e,this.config=t,this.elements=[],this.spacer=null,this.dom=document.createElement("div"),this.dom.className="cm-gutter"+(this.config.class?" "+this.config.class:"");for(let i in t.domEventHandlers)this.dom.addEventListener(i,n=>{let r=n.target,o;if(r!=this.dom&&this.dom.contains(r)){for(;r.parentNode!=this.dom;)r=r.parentNode;let a=r.getBoundingClientRect();o=(a.top+a.bottom)/2}else o=n.clientY;let l=e.lineBlockAtHeight(o-e.documentTop);t.domEventHandlers[i](e,l,n)&&n.preventDefault()});this.markers=va(t.markers(e)),t.initialSpacer&&(this.spacer=new Gc(e,0,0,[t.initialSpacer(e)]),this.dom.appendChild(this.spacer.dom),this.spacer.dom.style.cssText+="visibility: hidden; pointer-events: none")}update(e){let t=this.markers;if(this.markers=va(this.config.markers(e.view)),this.spacer&&this.config.updateSpacer){let n=this.config.updateSpacer(this.spacer.markers[0],e);n!=this.spacer.markers[0]&&this.spacer.update(e.view,0,0,[n])}let i=e.view.viewport;return!X.eq(this.markers,t,i.from,i.to)||(this.config.lineMarkerChange?this.config.lineMarkerChange(e):!1)}destroy(){for(let e of this.elements)e.destroy()}}class Gc{constructor(e,t,i,n){this.height=-1,this.above=0,this.markers=[],this.dom=document.createElement("div"),this.dom.className="cm-gutterElement",this.update(e,t,i,n)}update(e,t,i,n){this.height!=t&&(this.height=t,this.dom.style.height=t+"px"),this.above!=i&&(this.dom.style.marginTop=(this.above=i)?i+"px":""),lg(this.markers,n)||this.setMarkers(e,n)}setMarkers(e,t){let i="cm-gutterElement",n=this.dom.firstChild;for(let r=0,o=0;;){let l=o,a=rr(l,a,h)||o(l,a,h):o}return i}})}});class hr extends xt{constructor(e){super(),this.number=e}eq(e){return this.number==e.number}toDOM(){return document.createTextNode(this.number)}}function cr(s,e){return s.state.facet(li).formatNumber(e,s.state)}const cg=$i.compute([li],s=>({class:"cm-lineNumbers",renderEmptyElements:!1,markers(e){return e.state.facet(ag)},lineMarker(e,t,i){return i.some(n=>n.toDOM)?null:new hr(cr(e,e.state.doc.lineAt(t.from).number))},widgetMarker:(e,t,i)=>{for(let n of e.state.facet(hg)){let r=n(e,t,i);if(r)return r}return null},lineMarkerChange:e=>e.startState.facet(li)!=e.state.facet(li),initialSpacer(e){return new hr(cr(e,Oa(e.state.doc.lines)))},updateSpacer(e,t){let i=cr(t.view,Oa(t.view.state.doc.lines));return i==e.number?e:new hr(i)},domEventHandlers:s.facet(li).domEventHandlers,side:"before"}));function fg(s={}){return[li.of(s),Kc(),cg]}function Oa(s){let e=9;for(;e{let e=[],t=-1;for(let i of s.selection.ranges){let n=s.doc.lineAt(i.head).from;n>t&&(t=n,e.push(ug.range(n)))}return X.of(e)});function pg(){return dg}const Jc=1024;let mg=0;class fr{constructor(e,t){this.from=e,this.to=t}}class q{constructor(e={}){this.id=mg++,this.perNode=!!e.perNode,this.deserialize=e.deserialize||(()=>{throw new Error("This node type doesn't define a deserialize function")}),this.combine=e.combine||null}add(e){if(this.perNode)throw new RangeError("Can't add per-node props to node types");return typeof e!="function"&&(e=Re.match(e)),t=>{let i=e(t);return i===void 0?null:[this,i]}}}q.closedBy=new q({deserialize:s=>s.split(" ")});q.openedBy=new q({deserialize:s=>s.split(" ")});q.group=new q({deserialize:s=>s.split(" ")});q.isolate=new q({deserialize:s=>{if(s&&s!="rtl"&&s!="ltr"&&s!="auto")throw new RangeError("Invalid value for isolate: "+s);return s||"auto"}});q.contextHash=new q({perNode:!0});q.lookAhead=new q({perNode:!0});q.mounted=new q({perNode:!0});class ji{constructor(e,t,i,n=!1){this.tree=e,this.overlay=t,this.parser=i,this.bracketed=n}static get(e){return e&&e.props&&e.props[q.mounted.id]}}const gg=Object.create(null);class Re{constructor(e,t,i,n=0){this.name=e,this.props=t,this.id=i,this.flags=n}static define(e){let t=e.props&&e.props.length?Object.create(null):gg,i=(e.top?1:0)|(e.skipped?2:0)|(e.error?4:0)|(e.name==null?8:0),n=new Re(e.name||"",t,e.id,i);if(e.props){for(let r of e.props)if(Array.isArray(r)||(r=r(n)),r){if(r[0].perNode)throw new RangeError("Can't store a per-node prop on a node type");t[r[0].id]=r[1]}}return n}prop(e){return this.props[e.id]}get isTop(){return(this.flags&1)>0}get isSkipped(){return(this.flags&2)>0}get isError(){return(this.flags&4)>0}get isAnonymous(){return(this.flags&8)>0}is(e){if(typeof e=="string"){if(this.name==e)return!0;let t=this.prop(q.group);return t?t.indexOf(e)>-1:!1}return this.id==e}static match(e){let t=Object.create(null);for(let i in e)for(let n of i.split(" "))t[n]=e[i];return i=>{for(let n=i.prop(q.group),r=-1;r<(n?n.length:0);r++){let o=t[r<0?i.name:n[r]];if(o)return o}}}}Re.none=new Re("",Object.create(null),0,8);class Ko{constructor(e){this.types=e;for(let t=0;t0;for(let a=this.cursor(o|te.IncludeAnonymous);;){let h=!1;if(a.from<=r&&a.to>=n&&(!l&&a.type.isAnonymous||t(a)!==!1)){if(a.firstChild())continue;h=!0}for(;h&&i&&(l||!a.type.isAnonymous)&&i(a),!a.nextSibling();){if(!a.parent())return;h=!0}}}prop(e){return e.perNode?this.props?this.props[e.id]:void 0:this.type.prop(e)}get propValues(){let e=[];if(this.props)for(let t in this.props)e.push([+t,this.props[t]]);return e}balance(e={}){return this.children.length<=8?this:Zo(Re.none,this.children,this.positions,0,this.children.length,0,this.length,(t,i,n)=>new re(this.type,t,i,n,this.propValues),e.makeTree||((t,i,n)=>new re(Re.none,t,i,n)))}static build(e){return kg(e)}}re.empty=new re(Re.none,[],[],0);class Go{constructor(e,t){this.buffer=e,this.index=t}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}get pos(){return this.index}next(){this.index-=4}fork(){return new Go(this.buffer,this.index)}}class Rt{constructor(e,t,i){this.buffer=e,this.length=t,this.set=i}get type(){return Re.none}toString(){let e=[];for(let t=0;t0));a=o[a+3]);return l}slice(e,t,i){let n=this.buffer,r=new Uint16Array(t-e),o=0;for(let l=e,a=0;l=e&&te;case 1:return t<=e&&i>e;case 2:return i>e;case 4:return!0}}function es(s,e,t,i){for(var n;s.from==s.to||(t<1?s.from>=e:s.from>e)||(t>-1?s.to<=e:s.to0?l.length:-1;e!=h;e+=t){let c=l[e],f=a[e]+o.from,u;if(!(!(r&te.EnterBracketed&&c instanceof re&&(u=ji.get(c))&&!u.overlay&&u.bracketed&&i>=f&&i<=f+c.length)&&!Zc(n,i,f,f+c.length))){if(c instanceof Rt){if(r&te.ExcludeBuffers)continue;let d=c.findChild(0,c.buffer.length,t,i-f,n);if(d>-1)return new Ct(new xg(o,c,e,f),null,d)}else if(r&te.IncludeAnonymous||!c.type.isAnonymous||Jo(c)){let d;if(!(r&te.IgnoreMounts)&&(d=ji.get(c))&&!d.overlay)return new He(d.tree,f,e,o);let p=new He(c,f,e,o);return r&te.IncludeAnonymous||!p.type.isAnonymous?p:p.nextChild(t<0?c.children.length-1:0,t,i,n,r)}}}if(r&te.IncludeAnonymous||!o.type.isAnonymous||(o.index>=0?e=o.index+t:e=t<0?-1:o._parent._tree.children.length,o=o._parent,!o))return null}}get firstChild(){return this.nextChild(0,1,0,4)}get lastChild(){return this.nextChild(this._tree.children.length-1,-1,0,4)}childAfter(e){return this.nextChild(0,1,e,2)}childBefore(e){return this.nextChild(this._tree.children.length-1,-1,e,-2)}prop(e){return this._tree.prop(e)}enter(e,t,i=0){let n;if(!(i&te.IgnoreOverlays)&&(n=ji.get(this._tree))&&n.overlay){let r=e-this.from,o=i&te.EnterBracketed&&n.bracketed;for(let{from:l,to:a}of n.overlay)if((t>0||o?l<=r:l=r:a>r))return new He(n.tree,n.overlay[0].from+this.from,-1,this)}return this.nextChild(0,1,e,t,i)}nextSignificantParent(){let e=this;for(;e.type.isAnonymous&&e._parent;)e=e._parent;return e}get parent(){return this._parent?this._parent.nextSignificantParent():null}get nextSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index+1,1,0,4):null}get prevSibling(){return this._parent&&this.index>=0?this._parent.nextChild(this.index-1,-1,0,4):null}get tree(){return this._tree}toTree(){return this._tree}toString(){return this._tree.toString()}}function Aa(s,e,t,i){let n=s.cursor(),r=[];if(!n.firstChild())return r;if(t!=null){for(let o=!1;!o;)if(o=n.type.is(t),!n.nextSibling())return r}for(;;){if(i!=null&&n.type.is(i))return r;if(n.type.is(e)&&r.push(n.node),!n.nextSibling())return i==null?r:[]}}function fo(s,e,t=e.length-1){for(let i=s;t>=0;i=i.parent){if(!i)return!1;if(!i.type.isAnonymous){if(e[t]&&e[t]!=i.name)return!1;t--}}return!0}class xg{constructor(e,t,i,n){this.parent=e,this.buffer=t,this.index=i,this.start=n}}class Ct extends ef{get name(){return this.type.name}get from(){return this.context.start+this.context.buffer.buffer[this.index+1]}get to(){return this.context.start+this.context.buffer.buffer[this.index+2]}constructor(e,t,i){super(),this.context=e,this._parent=t,this.index=i,this.type=e.buffer.set.types[e.buffer.buffer[i]]}child(e,t,i){let{buffer:n}=this.context,r=n.findChild(this.index+4,n.buffer[this.index+3],e,t-this.context.start,i);return r<0?null:new Ct(this.context,this,r)}get firstChild(){return this.child(1,0,4)}get lastChild(){return this.child(-1,0,4)}childAfter(e){return this.child(1,e,2)}childBefore(e){return this.child(-1,e,-2)}prop(e){return this.type.prop(e)}enter(e,t,i=0){if(i&te.ExcludeBuffers)return null;let{buffer:n}=this.context,r=n.findChild(this.index+4,n.buffer[this.index+3],t>0?1:-1,e-this.context.start,t);return r<0?null:new Ct(this.context,this,r)}get parent(){return this._parent||this.context.parent.nextSignificantParent()}externalSibling(e){return this._parent?null:this.context.parent.nextChild(this.context.index+e,e,0,4)}get nextSibling(){let{buffer:e}=this.context,t=e.buffer[this.index+3];return t<(this._parent?e.buffer[this._parent.index+3]:e.buffer.length)?new Ct(this.context,this._parent,t):this.externalSibling(1)}get prevSibling(){let{buffer:e}=this.context,t=this._parent?this._parent.index+4:0;return this.index==t?this.externalSibling(-1):new Ct(this.context,this._parent,e.findChild(t,this.index,-1,0,4))}get tree(){return null}toTree(){let e=[],t=[],{buffer:i}=this.context,n=this.index+4,r=i.buffer[this.index+3];if(r>n){let o=i.buffer[this.index+1];e.push(i.slice(n,r,o)),t.push(0)}return new re(this.type,e,t,this.to-this.from)}toString(){return this.context.buffer.childString(this.index)}}function tf(s){if(!s.length)return null;let e=0,t=s[0];for(let r=1;rt.from||o.to=e){let l=new He(o.tree,o.overlay[0].from+r.from,-1,r);(n||(n=[i])).push(es(l,e,t,!1))}}return n?tf(n):i}class uo{get name(){return this.type.name}constructor(e,t=0){if(this.buffer=null,this.stack=[],this.index=0,this.bufferNode=null,this.mode=t&~te.EnterBracketed,e instanceof He)this.yieldNode(e);else{this._tree=e.context.parent,this.buffer=e.context;for(let i=e._parent;i;i=i._parent)this.stack.unshift(i.index);this.bufferNode=e,this.yieldBuf(e.index)}}yieldNode(e){return e?(this._tree=e,this.type=e.type,this.from=e.from,this.to=e.to,!0):!1}yieldBuf(e,t){this.index=e;let{start:i,buffer:n}=this.buffer;return this.type=t||n.set.types[n.buffer[e]],this.from=i+n.buffer[e+1],this.to=i+n.buffer[e+2],!0}yield(e){return e?e instanceof He?(this.buffer=null,this.yieldNode(e)):(this.buffer=e.context,this.yieldBuf(e.index,e.type)):!1}toString(){return this.buffer?this.buffer.buffer.childString(this.index):this._tree.toString()}enterChild(e,t,i){if(!this.buffer)return this.yield(this._tree.nextChild(e<0?this._tree._tree.children.length-1:0,e,t,i,this.mode));let{buffer:n}=this.buffer,r=n.findChild(this.index+4,n.buffer[this.index+3],e,t-this.buffer.start,i);return r<0?!1:(this.stack.push(this.index),this.yieldBuf(r))}firstChild(){return this.enterChild(1,0,4)}lastChild(){return this.enterChild(-1,0,4)}childAfter(e){return this.enterChild(1,e,2)}childBefore(e){return this.enterChild(-1,e,-2)}enter(e,t,i=this.mode){return this.buffer?i&te.ExcludeBuffers?!1:this.enterChild(1,e,t):this.yield(this._tree.enter(e,t,i))}parent(){if(!this.buffer)return this.yieldNode(this.mode&te.IncludeAnonymous?this._tree._parent:this._tree.parent);if(this.stack.length)return this.yieldBuf(this.stack.pop());let e=this.mode&te.IncludeAnonymous?this.buffer.parent:this.buffer.parent.nextSignificantParent();return this.buffer=null,this.yieldNode(e)}sibling(e){if(!this.buffer)return this._tree._parent?this.yield(this._tree.index<0?null:this._tree._parent.nextChild(this._tree.index+e,e,0,4,this.mode)):!1;let{buffer:t}=this.buffer,i=this.stack.length-1;if(e<0){let n=i<0?0:this.stack[i]+4;if(this.index!=n)return this.yieldBuf(t.findChild(n,this.index,-1,0,4))}else{let n=t.buffer[this.index+3];if(n<(i<0?t.buffer.length:t.buffer[this.stack[i]+3]))return this.yieldBuf(n)}return i<0?this.yield(this.buffer.parent.nextChild(this.buffer.index+e,e,0,4,this.mode)):!1}nextSibling(){return this.sibling(1)}prevSibling(){return this.sibling(-1)}atLastNode(e){let t,i,{buffer:n}=this;if(n){if(e>0){if(this.index-1)for(let r=t+e,o=e<0?-1:i._tree.children.length;r!=o;r+=e){let l=i._tree.children[r];if(this.mode&te.IncludeAnonymous||l instanceof Rt||!l.type.isAnonymous||Jo(l))return!1}return!0}move(e,t){if(t&&this.enterChild(e,0,4))return!0;for(;;){if(this.sibling(e))return!0;if(this.atLastNode(e)||!this.parent())return!1}}next(e=!0){return this.move(1,e)}prev(e=!0){return this.move(-1,e)}moveTo(e,t=0){for(;(this.from==this.to||(t<1?this.from>=e:this.from>e)||(t>-1?this.to<=e:this.to=0;){for(let o=e;o;o=o._parent)if(o.index==n){if(n==this.index)return o;t=o,i=r+1;break e}n=this.stack[--r]}for(let n=i;n=0;r--){if(r<0)return fo(this._tree,e,n);let o=i[t.buffer[this.stack[r]]];if(!o.isAnonymous){if(e[n]&&e[n]!=o.name)return!1;n--}}return!0}}function Jo(s){return s.children.some(e=>e instanceof Rt||!e.type.isAnonymous||Jo(e))}function kg(s){var e;let{buffer:t,nodeSet:i,maxBufferLength:n=Jc,reused:r=[],minRepeatType:o=i.types.length}=s,l=Array.isArray(t)?new Go(t,t.length):t,a=i.types,h=0,c=0;function f(S,A,O,V,N,P){let{id:D,start:M,end:F,size:R}=l,C=c,B=h;if(R<0)if(l.next(),R==-1){let de=r[D];O.push(de),V.push(M-S);return}else if(R==-3){h=D;return}else if(R==-4){c=D;return}else throw new RangeError(`Unrecognized record size: ${R}`);let j=a[D],oe,Q,ue=M-S;if(F-M<=n&&(Q=g(l.pos-A,N))){let de=new Uint16Array(Q.size-Q.skip),we=l.pos-Q.size,Be=de.length;for(;l.pos>we;)Be=x(Q.start,de,Be);oe=new Rt(de,F-Q.start,i),ue=Q.start-S}else{let de=l.pos-R;l.next();let we=[],Be=[],K=D>=o?D:-1,Qe=0,Nt=F;for(;l.pos>de;)K>=0&&l.id==K&&l.size>=0?(l.end<=Nt-n&&(p(we,Be,M,Qe,l.end,Nt,K,C,B),Qe=we.length,Nt=l.end),l.next()):P>2500?u(M,de,we,Be):f(M,de,we,Be,K,P+1);if(K>=0&&Qe>0&&Qe-1&&Qe>0){let ti=d(j,B);oe=Zo(j,we,Be,0,we.length,0,F-M,ti,ti)}else oe=m(j,we,Be,F-M,C-F,B)}O.push(oe),V.push(ue)}function u(S,A,O,V){let N=[],P=0,D=-1;for(;l.pos>A;){let{id:M,start:F,end:R,size:C}=l;if(C>4)l.next();else{if(D>-1&&F=0;R-=3)M[C++]=N[R],M[C++]=N[R+1]-F,M[C++]=N[R+2]-F,M[C++]=C;O.push(new Rt(M,N[2]-F,i)),V.push(F-S)}}function d(S,A){return(O,V,N)=>{let P=0,D=O.length-1,M,F;if(D>=0&&(M=O[D])instanceof re){if(!D&&M.type==S&&M.length==N)return M;(F=M.prop(q.lookAhead))&&(P=V[D]+M.length+F)}return m(S,O,V,N,P,A)}}function p(S,A,O,V,N,P,D,M,F){let R=[],C=[];for(;S.length>V;)R.push(S.pop()),C.push(A.pop()+O-N);S.push(m(i.types[D],R,C,P-N,M-P,F)),A.push(N-O)}function m(S,A,O,V,N,P,D){if(P){let M=[q.contextHash,P];D=D?[M].concat(D):[M]}if(N>25){let M=[q.lookAhead,N];D=D?[M].concat(D):[M]}return new re(S,A,O,V,D)}function g(S,A){let O=l.fork(),V=0,N=0,P=0,D=O.end-n,M={size:0,start:0,skip:0};e:for(let F=O.pos-S;O.pos>F;){let R=O.size;if(O.id==A&&R>=0){M.size=V,M.start=N,M.skip=P,P+=4,V+=4,O.next();continue}let C=O.pos-R;if(R<0||C=o?4:0,j=O.start;for(O.next();O.pos>C;){if(O.size<0)if(O.size==-3||O.size==-4)B+=4;else break e;else O.id>=o&&(B+=4);O.next()}N=j,V+=R,P+=B}return(A<0||V==S)&&(M.size=V,M.start=N,M.skip=P),M.size>4?M:void 0}function x(S,A,O){let{id:V,start:N,end:P,size:D}=l;if(l.next(),D>=0&&V4){let F=l.pos-(D-4);for(;l.pos>F;)O=x(S,A,O)}A[--O]=M,A[--O]=P-S,A[--O]=N-S,A[--O]=V}else D==-3?h=V:D==-4&&(c=V);return O}let k=[],w=[];for(;l.pos>0;)f(s.start||0,s.bufferStart||0,k,w,-1,0);let T=(e=s.length)!==null&&e!==void 0?e:k.length?w[0]+k[0].length:0;return new re(a[s.topID],k.reverse(),w.reverse(),T)}const Ma=new WeakMap;function Ks(s,e){if(!s.isAnonymous||e instanceof Rt||e.type!=s)return 1;let t=Ma.get(e);if(t==null){t=1;for(let i of e.children){if(i.type!=s||!(i instanceof re)){t=1;break}t+=Ks(s,i)}Ma.set(e,t)}return t}function Zo(s,e,t,i,n,r,o,l,a){let h=0;for(let p=i;p=c)break;A+=O}if(w==T+1){if(A>c){let O=p[T];d(O.children,O.positions,0,O.children.length,m[T]+k);continue}f.push(p[T])}else{let O=m[w-1]+p[w-1].length-S;f.push(Zo(s,p,m,T,w,S,O,null,a))}u.push(S+k-r)}}return d(e,t,i,n,0),(l||a)(f,u,o)}class Yt{constructor(e,t,i,n,r=!1,o=!1){this.from=e,this.to=t,this.tree=i,this.offset=n,this.open=(r?1:0)|(o?2:0)}get openStart(){return(this.open&1)>0}get openEnd(){return(this.open&2)>0}static addTree(e,t=[],i=!1){let n=[new Yt(0,e.length,e,0,!1,i)];for(let r of t)r.to>e.length&&n.push(r);return n}static applyChanges(e,t,i=128){if(!t.length)return e;let n=[],r=1,o=e.length?e[0]:null;for(let l=0,a=0,h=0;;l++){let c=l=i)for(;o&&o.from=u.from||f<=u.to||h){let d=Math.max(u.from,a)-h,p=Math.min(u.to,f)-h;u=d>=p?null:new Yt(d,p,u.tree,u.offset+h,l>0,!!c)}if(u&&n.push(u),o.to>f)break;o=rnew fr(n.from,n.to)):[new fr(0,0)]:[new fr(0,e.length)],this.createParse(e,t||[],i)}parse(e,t,i){let n=this.startParse(e,t,i);for(;;){let r=n.advance();if(r)return r}}}class wg{constructor(e){this.string=e}get length(){return this.string.length}chunk(e){return this.string.slice(e)}get lineChunks(){return!1}read(e,t){return this.string.slice(e,t)}}new q({perNode:!0});let vg=0,ft=class po{constructor(e,t,i,n){this.name=e,this.set=t,this.base=i,this.modified=n,this.id=vg++}toString(){let{name:e}=this;for(let t of this.modified)t.name&&(e=`${t.name}(${e})`);return e}static define(e,t){let i=typeof e=="string"?e:"?";if(e instanceof po&&(t=e),t?.base)throw new Error("Can not derive from a modified tag");let n=new po(i,[],null,[]);if(n.set.push(n),t)for(let r of t.set)n.set.push(r);return n}static defineModifier(e){let t=new un(e);return i=>i.modified.indexOf(t)>-1?i:un.get(i.base||i,i.modified.concat(t).sort((n,r)=>n.id-r.id))}},Sg=0;class un{constructor(e){this.name=e,this.instances=[],this.id=Sg++}static get(e,t){if(!t.length)return e;let i=t[0].instances.find(l=>l.base==e&&Og(t,l.modified));if(i)return i;let n=[],r=new ft(e.name,n,e,t);for(let l of t)l.instances.push(r);let o=Cg(t);for(let l of e.set)if(!l.modified.length)for(let a of o)n.push(un.get(l,a));return r}}function Og(s,e){return s.length==e.length&&s.every((t,i)=>t==e[i])}function Cg(s){let e=[[]];for(let t=0;ti.length-t.length)}function nf(s){let e=Object.create(null);for(let t in s){let i=s[t];Array.isArray(i)||(i=[i]);for(let n of t.split(" "))if(n){let r=[],o=2,l=n;for(let f=0;;){if(l=="..."&&f>0&&f+3==n.length){o=1;break}let u=/^"(?:[^"\\]|\\.)*?"|[^\/!]+/.exec(l);if(!u)throw new RangeError("Invalid path: "+n);if(r.push(u[0]=="*"?"":u[0][0]=='"'?JSON.parse(u[0]):u[0]),f+=u[0].length,f==n.length)break;let d=n[f++];if(f==n.length&&d=="!"){o=0;break}if(d!="/")throw new RangeError("Invalid path: "+n);l=n.slice(f)}let a=r.length-1,h=r[a];if(!h)throw new RangeError("Invalid path: "+n);let c=new ts(i,o,a>0?r.slice(0,a):null);e[h]=c.sort(e[h])}}return rf.add(e)}const rf=new q({combine(s,e){let t,i,n;for(;s||e;){if(!s||e&&s.depth>=e.depth?(n=e,e=e.next):(n=s,s=s.next),t&&t.mode==n.mode&&!n.context&&!t.context)continue;let r=new ts(n.tags,n.mode,n.context);t?t.next=r:i=r,t=r}return i}});class ts{constructor(e,t,i,n){this.tags=e,this.mode=t,this.context=i,this.next=n}get opaque(){return this.mode==0}get inherit(){return this.mode==1}sort(e){return!e||e.depth{let o=n;for(let l of r)for(let a of l.set){let h=t[a.id];if(h){o=o?o+" "+h:h;break}}return o},scope:i}}function Ag(s,e){let t=null;for(let i of s){let n=i.style(e);n&&(t=t?t+" "+n:n)}return t}function Mg(s,e,t,i=0,n=s.length){let r=new Pg(i,Array.isArray(e)?e:[e],t);r.highlightRange(s.cursor(),i,n,"",r.highlighters),r.flush(n)}class Pg{constructor(e,t,i){this.at=e,this.highlighters=t,this.span=i,this.class=""}startSpan(e,t){t!=this.class&&(this.flush(e),e>this.at&&(this.at=e),this.class=t)}flush(e){e>this.at&&this.class&&this.span(this.at,e,this.class)}highlightRange(e,t,i,n,r){let{type:o,from:l,to:a}=e;if(l>=i||a<=t)return;o.isTop&&(r=this.highlighters.filter(d=>!d.scope||d.scope(o)));let h=n,c=Tg(e)||ts.empty,f=Ag(r,c.tags);if(f&&(h&&(h+=" "),h+=f,c.mode==1&&(n+=(n?" ":"")+f)),this.startSpan(Math.max(t,l),h),c.opaque)return;let u=e.tree&&e.tree.prop(q.mounted);if(u&&u.overlay){let d=e.node.enter(u.overlay[0].from+l,1),p=this.highlighters.filter(g=>!g.scope||g.scope(u.tree.type)),m=e.firstChild();for(let g=0,x=l;;g++){let k=g=w||!e.nextSibling())););if(!k||w>i)break;x=k.to+l,x>t&&(this.highlightRange(d.cursor(),Math.max(t,k.from+l),Math.min(i,x),"",p),this.startSpan(Math.min(i,x),h))}m&&e.parent()}else if(e.firstChild()){u&&(n="");do if(!(e.to<=t)){if(e.from>=i)break;this.highlightRange(e,t,i,n,r),this.startSpan(Math.min(i,e.to),h)}while(e.nextSibling());e.parent()}}}function Tg(s){let e=s.type.prop(rf);for(;e&&e.context&&!s.matchContext(e.context);)e=e.next;return e||null}const E=ft.define,Ns=E(),yt=E(),Pa=E(yt),Ta=E(yt),kt=E(),Is=E(kt),ur=E(kt),et=E(),Ft=E(et),Je=E(),Ze=E(),mo=E(),Ri=E(mo),Ws=E(),b={comment:Ns,lineComment:E(Ns),blockComment:E(Ns),docComment:E(Ns),name:yt,variableName:E(yt),typeName:Pa,tagName:E(Pa),propertyName:Ta,attributeName:E(Ta),className:E(yt),labelName:E(yt),namespace:E(yt),macroName:E(yt),literal:kt,string:Is,docString:E(Is),character:E(Is),attributeValue:E(Is),number:ur,integer:E(ur),float:E(ur),bool:E(kt),regexp:E(kt),escape:E(kt),color:E(kt),url:E(kt),keyword:Je,self:E(Je),null:E(Je),atom:E(Je),unit:E(Je),modifier:E(Je),operatorKeyword:E(Je),controlKeyword:E(Je),definitionKeyword:E(Je),moduleKeyword:E(Je),operator:Ze,derefOperator:E(Ze),arithmeticOperator:E(Ze),logicOperator:E(Ze),bitwiseOperator:E(Ze),compareOperator:E(Ze),updateOperator:E(Ze),definitionOperator:E(Ze),typeOperator:E(Ze),controlOperator:E(Ze),punctuation:mo,separator:E(mo),bracket:Ri,angleBracket:E(Ri),squareBracket:E(Ri),paren:E(Ri),brace:E(Ri),content:et,heading:Ft,heading1:E(Ft),heading2:E(Ft),heading3:E(Ft),heading4:E(Ft),heading5:E(Ft),heading6:E(Ft),contentSeparator:E(et),list:E(et),quote:E(et),emphasis:E(et),strong:E(et),link:E(et),monospace:E(et),strikethrough:E(et),inserted:E(),deleted:E(),changed:E(),invalid:E(),meta:Ws,documentMeta:E(Ws),annotation:E(Ws),processingInstruction:E(Ws),definition:ft.defineModifier("definition"),constant:ft.defineModifier("constant"),function:ft.defineModifier("function"),standard:ft.defineModifier("standard"),local:ft.defineModifier("local"),special:ft.defineModifier("special")};for(let s in b){let e=b[s];e instanceof ft&&(e.name=s)}of([{tag:b.link,class:"tok-link"},{tag:b.heading,class:"tok-heading"},{tag:b.emphasis,class:"tok-emphasis"},{tag:b.strong,class:"tok-strong"},{tag:b.keyword,class:"tok-keyword"},{tag:b.atom,class:"tok-atom"},{tag:b.bool,class:"tok-bool"},{tag:b.url,class:"tok-url"},{tag:b.labelName,class:"tok-labelName"},{tag:b.inserted,class:"tok-inserted"},{tag:b.deleted,class:"tok-deleted"},{tag:b.literal,class:"tok-literal"},{tag:b.string,class:"tok-string"},{tag:b.number,class:"tok-number"},{tag:[b.regexp,b.escape,b.special(b.string)],class:"tok-string2"},{tag:b.variableName,class:"tok-variableName"},{tag:b.local(b.variableName),class:"tok-variableName tok-local"},{tag:b.definition(b.variableName),class:"tok-variableName tok-definition"},{tag:b.special(b.variableName),class:"tok-variableName2"},{tag:b.definition(b.propertyName),class:"tok-propertyName tok-definition"},{tag:b.typeName,class:"tok-typeName"},{tag:b.namespace,class:"tok-namespace"},{tag:b.className,class:"tok-className"},{tag:b.macroName,class:"tok-macroName"},{tag:b.propertyName,class:"tok-propertyName"},{tag:b.operator,class:"tok-operator"},{tag:b.comment,class:"tok-comment"},{tag:b.meta,class:"tok-meta"},{tag:b.invalid,class:"tok-invalid"},{tag:b.punctuation,class:"tok-punctuation"}]);var dr;const ai=new q;function Dg(s){return I.define({combine:s?e=>e.concat(s):void 0})}const Rg=new q;class qe{constructor(e,t,i=[],n=""){this.data=e,this.name=n,U.prototype.hasOwnProperty("tree")||Object.defineProperty(U.prototype,"tree",{get(){return be(this)}}),this.parser=t,this.extension=[Bt.of(this),U.languageData.of((r,o,l)=>{let a=Da(r,o,l),h=a.type.prop(ai);if(!h)return[];let c=r.facet(h),f=a.type.prop(Rg);if(f){let u=a.resolve(o-a.from,l);for(let d of f)if(d.test(u,r)){let p=r.facet(d.facet);return d.type=="replace"?p:p.concat(c)}}return c})].concat(i)}isActiveAt(e,t,i=-1){return Da(e,t,i).type.prop(ai)==this.data}findRegions(e){let t=e.facet(Bt);if(t?.data==this.data)return[{from:0,to:e.doc.length}];if(!t||!t.allowsNesting)return[];let i=[],n=(r,o)=>{if(r.prop(ai)==this.data){i.push({from:o,to:o+r.length});return}let l=r.prop(q.mounted);if(l){if(l.tree.prop(ai)==this.data){if(l.overlay)for(let a of l.overlay)i.push({from:a.from+o,to:a.to+o});else i.push({from:o,to:o+r.length});return}else if(l.overlay){let a=i.length;if(n(l.tree,l.overlay[0].from+o),i.length>a)return}}for(let a=0;ai.isTop?t:void 0)]}),e.name)}configure(e,t){return new dn(this.data,this.parser.configure(e),t||this.name)}get allowsNesting(){return this.parser.hasWrappers()}}function be(s){let e=s.field(qe.state,!1);return e?e.tree:re.empty}class Bg{constructor(e){this.doc=e,this.cursorPos=0,this.string="",this.cursor=e.iter()}get length(){return this.doc.length}syncTo(e){return this.string=this.cursor.next(e-this.cursorPos).value,this.cursorPos=e+this.string.length,this.cursorPos-this.string.length}chunk(e){return this.syncTo(e),this.string}get lineChunks(){return!0}read(e,t){let i=this.cursorPos-this.string.length;return e=this.cursorPos?this.doc.sliceString(e,t):this.string.slice(e-i,t-i)}}let Bi=null;class pn{constructor(e,t,i=[],n,r,o,l,a){this.parser=e,this.state=t,this.fragments=i,this.tree=n,this.treeLen=r,this.viewport=o,this.skipped=l,this.scheduleOn=a,this.parse=null,this.tempSkipped=[]}static create(e,t,i){return new pn(e,t,[],re.empty,0,i,[],null)}startParse(){return this.parser.startParse(new Bg(this.state.doc),this.fragments)}work(e,t){return t!=null&&t>=this.state.doc.length&&(t=void 0),this.tree!=re.empty&&this.isDone(t??this.state.doc.length)?(this.takeTree(),!0):this.withContext(()=>{var i;if(typeof e=="number"){let n=Date.now()+e;e=()=>Date.now()>n}for(this.parse||(this.parse=this.startParse()),t!=null&&(this.parse.stoppedAt==null||this.parse.stoppedAt>t)&&t=this.treeLen&&((this.parse.stoppedAt==null||this.parse.stoppedAt>e)&&this.parse.stopAt(e),this.withContext(()=>{for(;!(t=this.parse.advance()););}),this.treeLen=e,this.tree=t,this.fragments=this.withoutTempSkipped(Yt.addTree(this.tree,this.fragments,!0)),this.parse=null)}withContext(e){let t=Bi;Bi=this;try{return e()}finally{Bi=t}}withoutTempSkipped(e){for(let t;t=this.tempSkipped.pop();)e=Ra(e,t.from,t.to);return e}changes(e,t){let{fragments:i,tree:n,treeLen:r,viewport:o,skipped:l}=this;if(this.takeTree(),!e.empty){let a=[];if(e.iterChangedRanges((h,c,f,u)=>a.push({fromA:h,toA:c,fromB:f,toB:u})),i=Yt.applyChanges(i,a),n=re.empty,r=0,o={from:e.mapPos(o.from,-1),to:e.mapPos(o.to,1)},this.skipped.length){l=[];for(let h of this.skipped){let c=e.mapPos(h.from,1),f=e.mapPos(h.to,-1);ce.from&&(this.fragments=Ra(this.fragments,n,r),this.skipped.splice(i--,1))}return this.skipped.length>=t?!1:(this.reset(),!0)}reset(){this.parse&&(this.takeTree(),this.parse=null)}skipUntilInView(e,t){this.skipped.push({from:e,to:t})}static getSkippingParser(e){return new class extends sf{createParse(t,i,n){let r=n[0].from,o=n[n.length-1].to;return{parsedPos:r,advance(){let a=Bi;if(a){for(let h of n)a.tempSkipped.push(h);e&&(a.scheduleOn=a.scheduleOn?Promise.all([a.scheduleOn,e]):e)}return this.parsedPos=o,new re(Re.none,[],[],o-r)},stoppedAt:null,stopAt(){}}}}}isDone(e){e=Math.min(e,this.state.doc.length);let t=this.fragments;return this.treeLen>=e&&t.length&&t[0].from==0&&t[0].to>=e}static get(){return Bi}}function Ra(s,e,t){return Yt.applyChanges(s,[{fromA:e,toA:t,fromB:e,toB:t}])}class vi{constructor(e){this.context=e,this.tree=e.tree}apply(e){if(!e.docChanged&&this.tree==this.context.tree)return this;let t=this.context.changes(e.changes,e.state),i=this.context.treeLen==e.startState.doc.length?void 0:Math.max(e.changes.mapPos(this.context.treeLen),t.viewport.to);return t.work(20,i)||t.takeTree(),new vi(t)}static init(e){let t=Math.min(3e3,e.doc.length),i=pn.create(e.facet(Bt).parser,e,{from:0,to:t});return i.work(20,t)||i.takeTree(),new vi(i)}}qe.state=ye.define({create:vi.init,update(s,e){for(let t of e.effects)if(t.is(qe.setState))return t.value;return e.startState.facet(Bt)!=e.state.facet(Bt)?vi.init(e.state):s.apply(e)}});let lf=s=>{let e=setTimeout(()=>s(),500);return()=>clearTimeout(e)};typeof requestIdleCallback<"u"&&(lf=s=>{let e=-1,t=setTimeout(()=>{e=requestIdleCallback(s,{timeout:400})},100);return()=>e<0?clearTimeout(t):cancelIdleCallback(e)});const pr=typeof navigator<"u"&&(!((dr=navigator.scheduling)===null||dr===void 0)&&dr.isInputPending)?()=>navigator.scheduling.isInputPending():null,Eg=se.fromClass(class{constructor(e){this.view=e,this.working=null,this.workScheduled=0,this.chunkEnd=-1,this.chunkBudget=-1,this.work=this.work.bind(this),this.scheduleWork()}update(e){let t=this.view.state.field(qe.state).context;(t.updateViewport(e.view.viewport)||this.view.viewport.to>t.treeLen)&&this.scheduleWork(),(e.docChanged||e.selectionSet)&&(this.view.hasFocus&&(this.chunkBudget+=50),this.scheduleWork()),this.checkAsyncSchedule(t)}scheduleWork(){if(this.working)return;let{state:e}=this.view,t=e.field(qe.state);(t.tree!=t.context.tree||!t.context.isDone(e.doc.length))&&(this.working=lf(this.work))}work(e){this.working=null;let t=Date.now();if(this.chunkEndn+1e3,a=r.context.work(()=>pr&&pr()||Date.now()>o,n+(l?0:1e5));this.chunkBudget-=Date.now()-t,(a||this.chunkBudget<=0)&&(r.context.takeTree(),this.view.dispatch({effects:qe.setState.of(new vi(r.context))})),this.chunkBudget>0&&!(a&&!l)&&this.scheduleWork(),this.checkAsyncSchedule(r.context)}checkAsyncSchedule(e){e.scheduleOn&&(this.workScheduled++,e.scheduleOn.then(()=>this.scheduleWork()).catch(t=>Pe(this.view.state,t)).then(()=>this.workScheduled--),e.scheduleOn=null)}destroy(){this.working&&this.working()}isWorking(){return!!(this.working||this.workScheduled>0)}},{eventHandlers:{focus(){this.scheduleWork()}}}),Bt=I.define({combine(s){return s.length?s[0]:null},enables:s=>[qe.state,Eg,L.contentAttributes.compute([s],e=>{let t=e.facet(s);return t&&t.name?{"data-language":t.name}:{}})]});class Lg{constructor(e,t=[]){this.language=e,this.support=t,this.extension=[e,t]}}const Ng=I.define(),Fn=I.define({combine:s=>{if(!s.length)return" ";let e=s[0];if(!e||/\S/.test(e)||Array.from(e).some(t=>t!=e[0]))throw new Error("Invalid indent unit: "+JSON.stringify(s[0]));return e}});function mn(s){let e=s.facet(Fn);return e.charCodeAt(0)==9?s.tabSize*e.length:e.length}function is(s,e){let t="",i=s.tabSize,n=s.facet(Fn)[0];if(n==" "){for(;e>=i;)t+=" ",e-=i;n=" "}for(let r=0;r=e?Ig(s,t,e):null}class Vn{constructor(e,t={}){this.state=e,this.options=t,this.unit=mn(e)}lineAt(e,t=1){let i=this.state.doc.lineAt(e),{simulateBreak:n,simulateDoubleBreak:r}=this.options;return n!=null&&n>=i.from&&n<=i.to?r&&n==e?{text:"",from:e}:(t<0?n-1&&(r+=o-this.countColumn(i,i.search(/\S|$/))),r}countColumn(e,t=e.length){return Ci(e,this.state.tabSize,t)}lineIndent(e,t=1){let{text:i,from:n}=this.lineAt(e,t),r=this.options.overrideIndentation;if(r){let o=r(n);if(o>-1)return o}return this.countColumn(i,i.search(/\S|$/))}get simulatedBreak(){return this.options.simulateBreak||null}}const af=new q;function Ig(s,e,t){let i=e.resolveStack(t),n=e.resolveInner(t,-1).resolve(t,0).enterUnfinishedNodesBefore(t);if(n!=i.node){let r=[];for(let o=n;o&&!(o.fromi.node.to||o.from==i.node.from&&o.type==i.node.type);o=o.parent)r.push(o);for(let o=r.length-1;o>=0;o--)i={node:r[o],next:i}}return hf(i,s,t)}function hf(s,e,t){for(let i=s;i;i=i.next){let n=Fg(i.node);if(n)return n(tl.create(e,t,i))}return 0}function Wg(s){return s.pos==s.options.simulateBreak&&s.options.simulateDoubleBreak}function Fg(s){let e=s.type.prop(af);if(e)return e;let t=s.firstChild,i;if(t&&(i=t.type.prop(q.closedBy))){let n=s.lastChild,r=n&&i.indexOf(n.name)>-1;return o=>cf(o,!0,1,void 0,r&&!Wg(o)?n.from:void 0)}return s.parent==null?Vg:null}function Vg(){return 0}class tl extends Vn{constructor(e,t,i){super(e.state,e.options),this.base=e,this.pos=t,this.context=i}get node(){return this.context.node}static create(e,t,i){return new tl(e,t,i)}get textAfter(){return this.textAfterPos(this.pos)}get baseIndent(){return this.baseIndentFor(this.node)}baseIndentFor(e){let t=this.state.doc.lineAt(e.from);for(;;){let i=e.resolve(t.from);for(;i.parent&&i.parent.from==i.from;)i=i.parent;if(Hg(i,e))break;t=this.state.doc.lineAt(i.from)}return this.lineIndent(t.from)}continue(){return hf(this.context.next,this.base,this.pos)}}function Hg(s,e){for(let t=e;t;t=t.parent)if(s==t)return!0;return!1}function zg(s){let e=s.node,t=e.childAfter(e.from),i=e.lastChild;if(!t)return null;let n=s.options.simulateBreak,r=s.state.doc.lineAt(t.from),o=n==null||n<=r.from?r.to:Math.min(r.to,n);for(let l=t.to;;){let a=e.childAfter(l);if(!a||a==i)return null;if(!a.type.isSkipped){if(a.from>=o)return null;let h=/^ */.exec(r.text.slice(t.to-r.from))[0].length;return{from:t.from,to:t.to+h}}l=a.to}}function Ba({closing:s,align:e=!0,units:t=1}){return i=>cf(i,e,t,s)}function cf(s,e,t,i,n){let r=s.textAfter,o=r.match(/^\s*/)[0].length,l=i&&r.slice(o,o+i.length)==i||n==s.pos+o,a=e?zg(s):null;return a?l?s.column(a.from):s.column(a.to):s.baseIndent+(l?0:s.unit*t)}const Qg=200;function $g(){return U.transactionFilter.of(s=>{if(!s.docChanged||!s.isUserEvent("input.type")&&!s.isUserEvent("input.complete"))return s;let e=s.startState.languageDataAt("indentOnInput",s.startState.selection.main.head);if(!e.length)return s;let t=s.newDoc,{head:i}=s.newSelection.main,n=t.lineAt(i);if(i>n.from+Qg)return s;let r=t.sliceString(n.from,i);if(!e.some(h=>h.test(r)))return s;let{state:o}=s,l=-1,a=[];for(let{head:h}of o.selection.ranges){let c=o.doc.lineAt(h);if(c.from==l)continue;l=c.from;let f=el(o,c.from);if(f==null)continue;let u=/^\s*/.exec(c.text)[0],d=is(o,f);u!=d&&a.push({from:c.from,to:c.from+u.length,insert:d})}return a.length?[s,{changes:a,sequential:!0}]:s})}const jg=I.define(),ff=new q;function qg(s){let e=s.firstChild,t=s.lastChild;return e&&e.tot)continue;if(r&&l.from=e&&h.to>t&&(r=h)}}return r}function Ug(s){let e=s.lastChild;return e&&e.to==s.to&&e.type.isError}function gn(s,e,t){for(let i of s.facet(jg)){let n=i(s,e,t);if(n)return n}return Xg(s,e,t)}function uf(s,e){let t=e.mapPos(s.from,1),i=e.mapPos(s.to,-1);return t>=i?void 0:{from:t,to:i}}const Hn=$.define({map:uf}),us=$.define({map:uf});function df(s){let e=[];for(let{head:t}of s.state.selection.ranges)e.some(i=>i.from<=t&&i.to>=t)||e.push(s.lineBlockAt(t));return e}const Zt=ye.define({create(){return z.none},update(s,e){e.isUserEvent("delete")&&e.changes.iterChangedRanges((t,i)=>s=Ea(s,t,i)),s=s.map(e.changes);for(let t of e.effects)if(t.is(Hn)&&!Yg(s,t.value.from,t.value.to)){let{preparePlaceholder:i}=e.state.facet(gf),n=i?z.replace({widget:new t0(i(e.state,t.value))}):La;s=s.update({add:[n.range(t.value.from,t.value.to)]})}else t.is(us)&&(s=s.update({filter:(i,n)=>t.value.from!=i||t.value.to!=n,filterFrom:t.value.from,filterTo:t.value.to}));return e.selection&&(s=Ea(s,e.selection.main.head)),s},provide:s=>L.decorations.from(s),toJSON(s,e){let t=[];return s.between(0,e.doc.length,(i,n)=>{t.push(i,n)}),t},fromJSON(s){if(!Array.isArray(s)||s.length%2)throw new RangeError("Invalid JSON for fold state");let e=[];for(let t=0;t{ne&&(i=!0)}),i?s.update({filterFrom:e,filterTo:t,filter:(n,r)=>n>=t||r<=e}):s}function xn(s,e,t){var i;let n=null;return(i=s.field(Zt,!1))===null||i===void 0||i.between(e,t,(r,o)=>{(!n||n.from>r)&&(n={from:r,to:o})}),n}function Yg(s,e,t){let i=!1;return s.between(e,e,(n,r)=>{n==e&&r==t&&(i=!0)}),i}function pf(s,e){return s.field(Zt,!1)?e:e.concat($.appendConfig.of(xf()))}const _g=s=>{for(let e of df(s)){let t=gn(s.state,e.from,e.to);if(t)return s.dispatch({effects:pf(s.state,[Hn.of(t),mf(s,t)])}),!0}return!1},Kg=s=>{if(!s.state.field(Zt,!1))return!1;let e=[];for(let t of df(s)){let i=xn(s.state,t.from,t.to);i&&e.push(us.of(i),mf(s,i,!1))}return e.length&&s.dispatch({effects:e}),e.length>0};function mf(s,e,t=!0){let i=s.state.doc.lineAt(e.from).number,n=s.state.doc.lineAt(e.to).number;return L.announce.of(`${s.state.phrase(t?"Folded lines":"Unfolded lines")} ${i} ${s.state.phrase("to")} ${n}.`)}const Gg=s=>{let{state:e}=s,t=[];for(let i=0;i{let e=s.state.field(Zt,!1);if(!e||!e.size)return!1;let t=[];return e.between(0,s.state.doc.length,(i,n)=>{t.push(us.of({from:i,to:n}))}),s.dispatch({effects:t}),!0},Zg=[{key:"Ctrl-Shift-[",mac:"Cmd-Alt-[",run:_g},{key:"Ctrl-Shift-]",mac:"Cmd-Alt-]",run:Kg},{key:"Ctrl-Alt-[",run:Gg},{key:"Ctrl-Alt-]",run:Jg}],e0={placeholderDOM:null,preparePlaceholder:null,placeholderText:"…"},gf=I.define({combine(s){return ht(s,e0)}});function xf(s){return[Zt,n0]}function bf(s,e){let{state:t}=s,i=t.facet(gf),n=o=>{let l=s.lineBlockAt(s.posAtDOM(o.target)),a=xn(s.state,l.from,l.to);a&&s.dispatch({effects:us.of(a)}),o.preventDefault()};if(i.placeholderDOM)return i.placeholderDOM(s,n,e);let r=document.createElement("span");return r.textContent=i.placeholderText,r.setAttribute("aria-label",t.phrase("folded code")),r.title=t.phrase("unfold"),r.className="cm-foldPlaceholder",r.onclick=n,r}const La=z.replace({widget:new class extends ct{toDOM(s){return bf(s,null)}}});class t0 extends ct{constructor(e){super(),this.value=e}eq(e){return this.value==e.value}toDOM(e){return bf(e,this.value)}}const i0={openText:"⌄",closedText:"›",markerDOM:null,domEventHandlers:{},foldingChanged:()=>!1};class mr extends xt{constructor(e,t){super(),this.config=e,this.open=t}eq(e){return this.config==e.config&&this.open==e.open}toDOM(e){if(this.config.markerDOM)return this.config.markerDOM(this.open);let t=document.createElement("span");return t.textContent=this.open?this.config.openText:this.config.closedText,t.title=e.state.phrase(this.open?"Fold line":"Unfold line"),t}}function s0(s={}){let e={...i0,...s},t=new mr(e,!0),i=new mr(e,!1),n=se.fromClass(class{constructor(o){this.from=o.viewport.from,this.markers=this.buildMarkers(o)}update(o){(o.docChanged||o.viewportChanged||o.startState.facet(Bt)!=o.state.facet(Bt)||o.startState.field(Zt,!1)!=o.state.field(Zt,!1)||be(o.startState)!=be(o.state)||e.foldingChanged(o))&&(this.markers=this.buildMarkers(o.view))}buildMarkers(o){let l=new mt;for(let a of o.viewportLineBlocks){let h=xn(o.state,a.from,a.to)?i:gn(o.state,a.from,a.to)?t:null;h&&l.add(a.from,a.from,h)}return l.finish()}}),{domEventHandlers:r}=e;return[n,ng({class:"cm-foldGutter",markers(o){var l;return((l=o.plugin(n))===null||l===void 0?void 0:l.markers)||X.empty},initialSpacer(){return new mr(e,!1)},domEventHandlers:{...r,click:(o,l,a)=>{if(r.click&&r.click(o,l,a))return!0;let h=xn(o.state,l.from,l.to);if(h)return o.dispatch({effects:us.of(h)}),!0;let c=gn(o.state,l.from,l.to);return c?(o.dispatch({effects:Hn.of(c)}),!0):!1}}}),xf()]}const n0=L.baseTheme({".cm-foldPlaceholder":{backgroundColor:"#eee",border:"1px solid #ddd",color:"#888",borderRadius:".2em",margin:"0 1px",padding:"0 1px",cursor:"pointer"},".cm-foldGutter span":{padding:"0 1px",cursor:"pointer"}});class ds{constructor(e,t){this.specs=e;let i;function n(l){let a=Pt.newName();return(i||(i=Object.create(null)))["."+a]=l,a}const r=typeof t.all=="string"?t.all:t.all?n(t.all):void 0,o=t.scope;this.scope=o instanceof qe?l=>l.prop(ai)==o.data:o?l=>l==o:void 0,this.style=of(e.map(l=>({tag:l.tag,class:l.class||n(Object.assign({},l,{tag:null}))})),{all:r}).style,this.module=i?new Pt(i):null,this.themeType=t.themeType}static define(e,t){return new ds(e,t||{})}}const go=I.define(),yf=I.define({combine(s){return s.length?[s[0]]:null}});function gr(s){let e=s.facet(go);return e.length?e:s.facet(yf)}function kf(s,e){let t=[o0],i;return s instanceof ds&&(s.module&&t.push(L.styleModule.of(s.module)),i=s.themeType),e?.fallback?t.push(yf.of(s)):i?t.push(go.computeN([L.darkTheme],n=>n.facet(L.darkTheme)==(i=="dark")?[s]:[])):t.push(go.of(s)),t}class r0{constructor(e){this.markCache=Object.create(null),this.tree=be(e.state),this.decorations=this.buildDeco(e,gr(e.state)),this.decoratedTo=e.viewport.to}update(e){let t=be(e.state),i=gr(e.state),n=i!=gr(e.startState),{viewport:r}=e.view,o=e.changes.mapPos(this.decoratedTo,1);t.length=r.to?(this.decorations=this.decorations.map(e.changes),this.decoratedTo=o):(t!=this.tree||e.viewportChanged||n)&&(this.tree=t,this.decorations=this.buildDeco(e.view,i),this.decoratedTo=r.to)}buildDeco(e,t){if(!t||!this.tree.length)return z.none;let i=new mt;for(let{from:n,to:r}of e.visibleRanges)Mg(this.tree,t,(o,l,a)=>{i.add(o,l,this.markCache[a]||(this.markCache[a]=z.mark({class:a})))},n,r);return i.finish()}}const o0=ei.high(se.fromClass(r0,{decorations:s=>s.decorations})),l0=ds.define([{tag:b.meta,color:"#404740"},{tag:b.link,textDecoration:"underline"},{tag:b.heading,textDecoration:"underline",fontWeight:"bold"},{tag:b.emphasis,fontStyle:"italic"},{tag:b.strong,fontWeight:"bold"},{tag:b.strikethrough,textDecoration:"line-through"},{tag:b.keyword,color:"#708"},{tag:[b.atom,b.bool,b.url,b.contentSeparator,b.labelName],color:"#219"},{tag:[b.literal,b.inserted],color:"#164"},{tag:[b.string,b.deleted],color:"#a11"},{tag:[b.regexp,b.escape,b.special(b.string)],color:"#e40"},{tag:b.definition(b.variableName),color:"#00f"},{tag:b.local(b.variableName),color:"#30a"},{tag:[b.typeName,b.namespace],color:"#085"},{tag:b.className,color:"#167"},{tag:[b.special(b.variableName),b.macroName],color:"#256"},{tag:b.definition(b.propertyName),color:"#00c"},{tag:b.comment,color:"#940"},{tag:b.invalid,color:"#f00"}]),a0=L.baseTheme({"&.cm-focused .cm-matchingBracket":{backgroundColor:"#328c8252"},"&.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bb555544"}}),wf=1e4,vf="()[]{}",Sf=I.define({combine(s){return ht(s,{afterCursor:!0,brackets:vf,maxScanDistance:wf,renderMatch:f0})}}),h0=z.mark({class:"cm-matchingBracket"}),c0=z.mark({class:"cm-nonmatchingBracket"});function f0(s){let e=[],t=s.matched?h0:c0;return e.push(t.range(s.start.from,s.start.to)),s.end&&e.push(t.range(s.end.from,s.end.to)),e}function Na(s){let e=[],t=s.facet(Sf);for(let i of s.selection.ranges){if(!i.empty)continue;let n=rt(s,i.head,-1,t)||i.head>0&&rt(s,i.head-1,1,t)||t.afterCursor&&(rt(s,i.head,1,t)||i.heads.decorations}),d0=[u0,a0];function p0(s={}){return[Sf.of(s),d0]}const m0=new q;function xo(s,e,t){let i=s.prop(e<0?q.openedBy:q.closedBy);if(i)return i;if(s.name.length==1){let n=t.indexOf(s.name);if(n>-1&&n%2==(e<0?1:0))return[t[n+e]]}return null}function bo(s){let e=s.type.prop(m0);return e?e(s.node):s}function rt(s,e,t,i={}){let n=i.maxScanDistance||wf,r=i.brackets||vf,o=be(s),l=o.resolveInner(e,t);for(let a=l;a;a=a.parent){let h=xo(a.type,t,r);if(h&&a.from0?e>=c.from&&ec.from&&e<=c.to))return g0(s,e,t,a,c,h,r)}}return x0(s,e,t,o,l.type,n,r)}function g0(s,e,t,i,n,r,o){let l=i.parent,a={from:n.from,to:n.to},h=0,c=l?.cursor();if(c&&(t<0?c.childBefore(i.from):c.childAfter(i.to)))do if(t<0?c.to<=i.from:c.from>=i.to){if(h==0&&r.indexOf(c.type.name)>-1&&c.from0)return null;let h={from:t<0?e-1:e,to:t>0?e+1:e},c=s.doc.iterRange(e,t>0?s.doc.length:0),f=0;for(let u=0;!c.next().done&&u<=r;){let d=c.value;t<0&&(u+=d.length);let p=e+u*t;for(let m=t>0?0:d.length-1,g=t>0?d.length:-1;m!=g;m+=t){let x=o.indexOf(d[m]);if(!(x<0||i.resolveInner(p+m,1).type!=n))if(x%2==0==t>0)f++;else{if(f==1)return{start:h,end:{from:p+m,to:p+m+1},matched:x>>1==a>>1};f--}}t>0&&(u+=d.length)}return c.done?{start:h,matched:!1}:null}const b0=Object.create(null),Ia=[Re.none],Wa=[],Fa=Object.create(null),y0=Object.create(null);for(let[s,e]of[["variable","variableName"],["variable-2","variableName.special"],["string-2","string.special"],["def","variableName.definition"],["tag","tagName"],["attribute","attributeName"],["type","typeName"],["builtin","variableName.standard"],["qualifier","modifier"],["error","invalid"],["header","heading"],["property","propertyName"]])y0[s]=k0(b0,e);function xr(s,e){Wa.indexOf(s)>-1||(Wa.push(s),console.warn(e))}function k0(s,e){let t=[];for(let l of e.split(" ")){let a=[];for(let h of l.split(".")){let c=s[h]||b[h];c?typeof c=="function"?a.length?a=a.map(c):xr(h,`Modifier ${h} used at start of tag`):a.length?xr(h,`Tag ${h} used as modifier`):a=Array.isArray(c)?c:[c]:xr(h,`Unknown highlighting tag ${h}`)}for(let h of a)t.push(h)}if(!t.length)return 0;let i=e.replace(/ /g,"_"),n=i+" "+t.map(l=>l.id),r=Fa[n];if(r)return r.id;let o=Fa[n]=Re.define({id:Ia.length,name:i,props:[nf({[i]:t})]});return Ia.push(o),o.id}J.RTL,J.LTR;const w0=s=>{let{state:e}=s,t=e.doc.lineAt(e.selection.main.from),i=sl(s.state,t.from);return i.line?v0(s):i.block?O0(s):!1};function il(s,e){return({state:t,dispatch:i})=>{if(t.readOnly)return!1;let n=s(e,t);return n?(i(t.update(n)),!0):!1}}const v0=il(M0,0),S0=il(Of,0),O0=il((s,e)=>Of(s,e,A0(e)),0);function sl(s,e){let t=s.languageDataAt("commentTokens",e,1);return t.length?t[0]:{}}const Ei=50;function C0(s,{open:e,close:t},i,n){let r=s.sliceDoc(i-Ei,i),o=s.sliceDoc(n,n+Ei),l=/\s*$/.exec(r)[0].length,a=/^\s*/.exec(o)[0].length,h=r.length-l;if(r.slice(h-e.length,h)==e&&o.slice(a,a+t.length)==t)return{open:{pos:i-l,margin:l&&1},close:{pos:n+a,margin:a&&1}};let c,f;n-i<=2*Ei?c=f=s.sliceDoc(i,n):(c=s.sliceDoc(i,i+Ei),f=s.sliceDoc(n-Ei,n));let u=/^\s*/.exec(c)[0].length,d=/\s*$/.exec(f)[0].length,p=f.length-d-t.length;return c.slice(u,u+e.length)==e&&f.slice(p,p+t.length)==t?{open:{pos:i+u+e.length,margin:/\s/.test(c.charAt(u+e.length))?1:0},close:{pos:n-d-t.length,margin:/\s/.test(f.charAt(p-1))?1:0}}:null}function A0(s){let e=[];for(let t of s.selection.ranges){let i=s.doc.lineAt(t.from),n=t.to<=i.to?i:s.doc.lineAt(t.to);n.from>i.from&&n.from==t.to&&(n=t.to==i.to+1?i:s.doc.lineAt(t.to-1));let r=e.length-1;r>=0&&e[r].to>i.from?e[r].to=n.to:e.push({from:i.from+/^\s*/.exec(i.text)[0].length,to:n.to})}return e}function Of(s,e,t=e.selection.ranges){let i=t.map(r=>sl(e,r.from).block);if(!i.every(r=>r))return null;let n=t.map((r,o)=>C0(e,i[o],r.from,r.to));if(s!=2&&!n.every(r=>r))return{changes:e.changes(t.map((r,o)=>n[o]?[]:[{from:r.from,insert:i[o].open+" "},{from:r.to,insert:" "+i[o].close}]))};if(s!=1&&n.some(r=>r)){let r=[];for(let o=0,l;on&&(r==o||o>f.from)){n=f.from;let u=/^\s*/.exec(f.text)[0].length,d=u==f.length,p=f.text.slice(u,u+h.length)==h?u:-1;ur.comment<0&&(!r.empty||r.single))){let r=[];for(let{line:l,token:a,indent:h,empty:c,single:f}of i)(f||!c)&&r.push({from:l.from+h,insert:a+" "});let o=e.changes(r);return{changes:o,selection:e.selection.map(o,1)}}else if(s!=1&&i.some(r=>r.comment>=0)){let r=[];for(let{line:o,comment:l,token:a}of i)if(l>=0){let h=o.from+l,c=h+a.length;o.text[c-o.from]==" "&&c++,r.push({from:h,to:c})}return{changes:r}}return null}const yo=at.define(),P0=at.define(),T0=I.define(),Cf=I.define({combine(s){return ht(s,{minDepth:100,newGroupDelay:500,joinToEvent:(e,t)=>t},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(e,t)=>(i,n)=>e(i,n)||t(i,n)})}}),Af=ye.define({create(){return ot.empty},update(s,e){let t=e.state.facet(Cf),i=e.annotation(yo);if(i){let a=Te.fromTransaction(e,i.selection),h=i.side,c=h==0?s.undone:s.done;return a?c=bn(c,c.length,t.minDepth,a):c=Tf(c,e.startState.selection),new ot(h==0?i.rest:c,h==0?c:i.rest)}let n=e.annotation(P0);if((n=="full"||n=="before")&&(s=s.isolate()),e.annotation(he.addToHistory)===!1)return e.changes.empty?s:s.addMapping(e.changes.desc);let r=Te.fromTransaction(e),o=e.annotation(he.time),l=e.annotation(he.userEvent);return r?s=s.addChanges(r,o,l,t,e):e.selection&&(s=s.addSelection(e.startState.selection,o,l,t.newGroupDelay)),(n=="full"||n=="after")&&(s=s.isolate()),s},toJSON(s){return{done:s.done.map(e=>e.toJSON()),undone:s.undone.map(e=>e.toJSON())}},fromJSON(s){return new ot(s.done.map(Te.fromJSON),s.undone.map(Te.fromJSON))}});function D0(s={}){return[Af,Cf.of(s),L.domEventHandlers({beforeinput(e,t){let i=e.inputType=="historyUndo"?Mf:e.inputType=="historyRedo"?ko:null;return i?(e.preventDefault(),i(t)):!1}})]}function zn(s,e){return function({state:t,dispatch:i}){if(!e&&t.readOnly)return!1;let n=t.field(Af,!1);if(!n)return!1;let r=n.pop(s,t,e);return r?(i(r),!0):!1}}const Mf=zn(0,!1),ko=zn(1,!1),R0=zn(0,!0),B0=zn(1,!0);class Te{constructor(e,t,i,n,r){this.changes=e,this.effects=t,this.mapped=i,this.startSelection=n,this.selectionsAfter=r}setSelAfter(e){return new Te(this.changes,this.effects,this.mapped,this.startSelection,e)}toJSON(){var e,t,i;return{changes:(e=this.changes)===null||e===void 0?void 0:e.toJSON(),mapped:(t=this.mapped)===null||t===void 0?void 0:t.toJSON(),startSelection:(i=this.startSelection)===null||i===void 0?void 0:i.toJSON(),selectionsAfter:this.selectionsAfter.map(n=>n.toJSON())}}static fromJSON(e){return new Te(e.changes&&ae.fromJSON(e.changes),[],e.mapped&<.fromJSON(e.mapped),e.startSelection&&v.fromJSON(e.startSelection),e.selectionsAfter.map(v.fromJSON))}static fromTransaction(e,t){let i=Fe;for(let n of e.startState.facet(T0)){let r=n(e);r.length&&(i=i.concat(r))}return!i.length&&e.changes.empty?null:new Te(e.changes.invert(e.startState.doc),i,void 0,t||e.startState.selection,Fe)}static selection(e){return new Te(void 0,Fe,void 0,void 0,e)}}function bn(s,e,t,i){let n=e+1>t+20?e-t-1:0,r=s.slice(n,e);return r.push(i),r}function E0(s,e){let t=[],i=!1;return s.iterChangedRanges((n,r)=>t.push(n,r)),e.iterChangedRanges((n,r,o,l)=>{for(let a=0;a=h&&o<=c&&(i=!0)}}),i}function L0(s,e){return s.ranges.length==e.ranges.length&&s.ranges.filter((t,i)=>t.empty!=e.ranges[i].empty).length===0}function Pf(s,e){return s.length?e.length?s.concat(e):s:e}const Fe=[],N0=200;function Tf(s,e){if(s.length){let t=s[s.length-1],i=t.selectionsAfter.slice(Math.max(0,t.selectionsAfter.length-N0));return i.length&&i[i.length-1].eq(e)?s:(i.push(e),bn(s,s.length-1,1e9,t.setSelAfter(i)))}else return[Te.selection([e])]}function I0(s){let e=s[s.length-1],t=s.slice();return t[s.length-1]=e.setSelAfter(e.selectionsAfter.slice(0,e.selectionsAfter.length-1)),t}function br(s,e){if(!s.length)return s;let t=s.length,i=Fe;for(;t;){let n=W0(s[t-1],e,i);if(n.changes&&!n.changes.empty||n.effects.length){let r=s.slice(0,t);return r[t-1]=n,r}else e=n.mapped,t--,i=n.selectionsAfter}return i.length?[Te.selection(i)]:Fe}function W0(s,e,t){let i=Pf(s.selectionsAfter.length?s.selectionsAfter.map(l=>l.map(e)):Fe,t);if(!s.changes)return Te.selection(i);let n=s.changes.map(e),r=e.mapDesc(s.changes,!0),o=s.mapped?s.mapped.composeDesc(r):r;return new Te(n,$.mapEffects(s.effects,e),o,s.startSelection.map(r),i)}const F0=/^(input\.type|delete)($|\.)/;class ot{constructor(e,t,i=0,n=void 0){this.done=e,this.undone=t,this.prevTime=i,this.prevUserEvent=n}isolate(){return this.prevTime?new ot(this.done,this.undone):this}addChanges(e,t,i,n,r){let o=this.done,l=o[o.length-1];return l&&l.changes&&!l.changes.empty&&e.changes&&(!i||F0.test(i))&&(!l.selectionsAfter.length&&t-this.prevTime0&&t-this.prevTimet.empty?s.moveByChar(t,e):Qn(t,e))}function ke(s){return s.textDirectionAt(s.state.selection.main.head)==J.LTR}const Rf=s=>Df(s,!ke(s)),Bf=s=>Df(s,ke(s));function Ef(s,e){return Ye(s,t=>t.empty?s.moveByGroup(t,e):Qn(t,e))}const H0=s=>Ef(s,!ke(s)),z0=s=>Ef(s,ke(s));function Q0(s,e,t){if(e.type.prop(t))return!0;let i=e.to-e.from;return i&&(i>2||/[^\s,.;:]/.test(s.sliceDoc(e.from,e.to)))||e.firstChild}function $n(s,e,t){let i=be(s).resolveInner(e.head),n=t?q.closedBy:q.openedBy;for(let a=e.head;;){let h=t?i.childAfter(a):i.childBefore(a);if(!h)break;Q0(s,h,n)?i=h:a=t?h.to:h.from}let r=i.type.prop(n),o,l;return r&&(o=t?rt(s,i.from,1):rt(s,i.to,-1))&&o.matched?l=t?o.end.to:o.end.from:l=t?i.to:i.from,v.cursor(l,t?-1:1)}const $0=s=>Ye(s,e=>$n(s.state,e,!ke(s))),j0=s=>Ye(s,e=>$n(s.state,e,ke(s)));function Lf(s,e){return Ye(s,t=>{if(!t.empty)return Qn(t,e);let i=s.moveVertically(t,e);return i.head!=t.head?i:s.moveToLineBoundary(t,e)})}const Nf=s=>Lf(s,!1),If=s=>Lf(s,!0);function Wf(s){let e=s.scrollDOM.clientHeighto.empty?s.moveVertically(o,e,t.height):Qn(o,e));if(n.eq(i.selection))return!1;let r;if(t.selfScroll){let o=s.coordsAtPos(i.selection.main.head),l=s.scrollDOM.getBoundingClientRect(),a=l.top+t.marginTop,h=l.bottom-t.marginBottom;o&&o.top>a&&o.bottomFf(s,!1),wo=s=>Ff(s,!0);function Lt(s,e,t){let i=s.lineBlockAt(e.head),n=s.moveToLineBoundary(e,t);if(n.head==e.head&&n.head!=(t?i.to:i.from)&&(n=s.moveToLineBoundary(e,t,!1)),!t&&n.head==i.from&&i.length){let r=/^\s*/.exec(s.state.sliceDoc(i.from,Math.min(i.from+100,i.to)))[0].length;r&&e.head!=i.from+r&&(n=v.cursor(i.from+r))}return n}const q0=s=>Ye(s,e=>Lt(s,e,!0)),X0=s=>Ye(s,e=>Lt(s,e,!1)),U0=s=>Ye(s,e=>Lt(s,e,!ke(s))),Y0=s=>Ye(s,e=>Lt(s,e,ke(s))),_0=s=>Ye(s,e=>v.cursor(s.lineBlockAt(e.head).from,1)),K0=s=>Ye(s,e=>v.cursor(s.lineBlockAt(e.head).to,-1));function G0(s,e,t){let i=!1,n=Ai(s.selection,r=>{let o=rt(s,r.head,-1)||rt(s,r.head,1)||r.head>0&&rt(s,r.head-1,1)||r.headG0(s,e);function ze(s,e){let t=Ai(s.state.selection,i=>{let n=e(i);return v.range(i.anchor,n.head,n.goalColumn,n.bidiLevel||void 0,n.assoc)});return t.eq(s.state.selection)?!1:(s.dispatch(Ue(s.state,t)),!0)}function Vf(s,e){return ze(s,t=>s.moveByChar(t,e))}const Hf=s=>Vf(s,!ke(s)),zf=s=>Vf(s,ke(s));function Qf(s,e){return ze(s,t=>s.moveByGroup(t,e))}const Z0=s=>Qf(s,!ke(s)),ex=s=>Qf(s,ke(s)),tx=s=>ze(s,e=>$n(s.state,e,!ke(s))),ix=s=>ze(s,e=>$n(s.state,e,ke(s)));function $f(s,e){return ze(s,t=>s.moveVertically(t,e))}const jf=s=>$f(s,!1),qf=s=>$f(s,!0);function Xf(s,e){return ze(s,t=>s.moveVertically(t,e,Wf(s).height))}const Ha=s=>Xf(s,!1),za=s=>Xf(s,!0),sx=s=>ze(s,e=>Lt(s,e,!0)),nx=s=>ze(s,e=>Lt(s,e,!1)),rx=s=>ze(s,e=>Lt(s,e,!ke(s))),ox=s=>ze(s,e=>Lt(s,e,ke(s))),lx=s=>ze(s,e=>v.cursor(s.lineBlockAt(e.head).from)),ax=s=>ze(s,e=>v.cursor(s.lineBlockAt(e.head).to)),Qa=({state:s,dispatch:e})=>(e(Ue(s,{anchor:0})),!0),$a=({state:s,dispatch:e})=>(e(Ue(s,{anchor:s.doc.length})),!0),ja=({state:s,dispatch:e})=>(e(Ue(s,{anchor:s.selection.main.anchor,head:0})),!0),qa=({state:s,dispatch:e})=>(e(Ue(s,{anchor:s.selection.main.anchor,head:s.doc.length})),!0),hx=({state:s,dispatch:e})=>(e(s.update({selection:{anchor:0,head:s.doc.length},userEvent:"select"})),!0),cx=({state:s,dispatch:e})=>{let t=jn(s).map(({from:i,to:n})=>v.range(i,Math.min(n+1,s.doc.length)));return e(s.update({selection:v.create(t),userEvent:"select"})),!0},fx=({state:s,dispatch:e})=>{let t=Ai(s.selection,i=>{let n=be(s),r=n.resolveStack(i.from,1);if(i.empty){let o=n.resolveStack(i.from,-1);o.node.from>=r.node.from&&o.node.to<=r.node.to&&(r=o)}for(let o=r;o;o=o.next){let{node:l}=o;if((l.from=i.to||l.to>i.to&&l.from<=i.from)&&o.next)return v.range(l.to,l.from)}return i});return t.eq(s.selection)?!1:(e(Ue(s,t)),!0)};function Uf(s,e){let{state:t}=s,i=t.selection,n=t.selection.ranges.slice();for(let r of t.selection.ranges){let o=t.doc.lineAt(r.head);if(e?o.to0)for(let l=r;;){let a=s.moveVertically(l,e);if(a.heado.to){n.some(h=>h.head==a.head)||n.push(a);break}else{if(a.head==l.head)break;l=a}}}return n.length==i.ranges.length?!1:(s.dispatch(Ue(t,v.create(n,n.length-1))),!0)}const ux=s=>Uf(s,!1),dx=s=>Uf(s,!0),px=({state:s,dispatch:e})=>{let t=s.selection,i=null;return t.ranges.length>1?i=v.create([t.main]):t.main.empty||(i=v.create([v.cursor(t.main.head)])),i?(e(Ue(s,i)),!0):!1};function ps(s,e){if(s.state.readOnly)return!1;let t="delete.selection",{state:i}=s,n=i.changeByRange(r=>{let{from:o,to:l}=r;if(o==l){let a=e(r);ao&&(t="delete.forward",a=Fs(s,a,!0)),o=Math.min(o,a),l=Math.max(l,a)}else o=Fs(s,o,!1),l=Fs(s,l,!0);return o==l?{range:r}:{changes:{from:o,to:l},range:v.cursor(o,on(s)))i.between(e,e,(n,r)=>{ne&&(e=t?r:n)});return e}const Yf=(s,e,t)=>ps(s,i=>{let n=i.from,{state:r}=s,o=r.doc.lineAt(n),l,a;if(t&&!e&&n>o.from&&nYf(s,!1,!0),_f=s=>Yf(s,!0,!1),Kf=(s,e)=>ps(s,t=>{let i=t.head,{state:n}=s,r=n.doc.lineAt(i),o=n.charCategorizer(i);for(let l=null;;){if(i==(e?r.to:r.from)){i==t.head&&r.number!=(e?n.doc.lines:1)&&(i+=e?1:-1);break}let a=fe(r.text,i-r.from,e)+r.from,h=r.text.slice(Math.min(i,a)-r.from,Math.max(i,a)-r.from),c=o(h);if(l!=null&&c!=l)break;(h!=" "||i!=t.head)&&(l=c),i=a}return i}),Gf=s=>Kf(s,!1),mx=s=>Kf(s,!0),gx=s=>ps(s,e=>{let t=s.lineBlockAt(e.head).to;return e.headps(s,e=>{let t=s.moveToLineBoundary(e,!1).head;return e.head>t?t:Math.max(0,e.head-1)}),bx=s=>ps(s,e=>{let t=s.moveToLineBoundary(e,!0).head;return e.head{if(s.readOnly)return!1;let t=s.changeByRange(i=>({changes:{from:i.from,to:i.to,insert:Y.of(["",""])},range:v.cursor(i.from)}));return e(s.update(t,{scrollIntoView:!0,userEvent:"input"})),!0},kx=({state:s,dispatch:e})=>{if(s.readOnly)return!1;let t=s.changeByRange(i=>{if(!i.empty||i.from==0||i.from==s.doc.length)return{range:i};let n=i.from,r=s.doc.lineAt(n),o=n==r.from?n-1:fe(r.text,n-r.from,!1)+r.from,l=n==r.to?n+1:fe(r.text,n-r.from,!0)+r.from;return{changes:{from:o,to:l,insert:s.doc.slice(n,l).append(s.doc.slice(o,n))},range:v.cursor(l)}});return t.changes.empty?!1:(e(s.update(t,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function jn(s){let e=[],t=-1;for(let i of s.selection.ranges){let n=s.doc.lineAt(i.from),r=s.doc.lineAt(i.to);if(!i.empty&&i.to==r.from&&(r=s.doc.lineAt(i.to-1)),t>=n.number){let o=e[e.length-1];o.to=r.to,o.ranges.push(i)}else e.push({from:n.from,to:r.to,ranges:[i]});t=r.number+1}return e}function Jf(s,e,t){if(s.readOnly)return!1;let i=[],n=[];for(let r of jn(s)){if(t?r.to==s.doc.length:r.from==0)continue;let o=s.doc.lineAt(t?r.to+1:r.from-1),l=o.length+1;if(t){i.push({from:r.to,to:o.to},{from:r.from,insert:o.text+s.lineBreak});for(let a of r.ranges)n.push(v.range(Math.min(s.doc.length,a.anchor+l),Math.min(s.doc.length,a.head+l)))}else{i.push({from:o.from,to:r.from},{from:r.to,insert:s.lineBreak+o.text});for(let a of r.ranges)n.push(v.range(a.anchor-l,a.head-l))}}return i.length?(e(s.update({changes:i,scrollIntoView:!0,selection:v.create(n,s.selection.mainIndex),userEvent:"move.line"})),!0):!1}const wx=({state:s,dispatch:e})=>Jf(s,e,!1),vx=({state:s,dispatch:e})=>Jf(s,e,!0);function Zf(s,e,t){if(s.readOnly)return!1;let i=[];for(let r of jn(s))t?i.push({from:r.from,insert:s.doc.slice(r.from,r.to)+s.lineBreak}):i.push({from:r.to,insert:s.lineBreak+s.doc.slice(r.from,r.to)});let n=s.changes(i);return e(s.update({changes:n,selection:s.selection.map(n,t?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const Sx=({state:s,dispatch:e})=>Zf(s,e,!1),Ox=({state:s,dispatch:e})=>Zf(s,e,!0),Cx=s=>{if(s.state.readOnly)return!1;let{state:e}=s,t=e.changes(jn(e).map(({from:n,to:r})=>(n>0?n--:r{let r;if(s.lineWrapping){let o=s.lineBlockAt(n.head),l=s.coordsAtPos(n.head,n.assoc||1);l&&(r=o.bottom+s.documentTop-l.bottom+s.defaultLineHeight/2)}return s.moveVertically(n,!0,r)}).map(t);return s.dispatch({changes:t,selection:i,scrollIntoView:!0,userEvent:"delete.line"}),!0};function Ax(s,e){if(/\(\)|\[\]|\{\}/.test(s.sliceDoc(e-1,e+1)))return{from:e,to:e};let t=be(s).resolveInner(e),i=t.childBefore(e),n=t.childAfter(e),r;return i&&n&&i.to<=e&&n.from>=e&&(r=i.type.prop(q.closedBy))&&r.indexOf(n.name)>-1&&s.doc.lineAt(i.to).from==s.doc.lineAt(n.from).from&&!/\S/.test(s.sliceDoc(i.to,n.from))?{from:i.to,to:n.from}:null}const Xa=eu(!1),Mx=eu(!0);function eu(s){return({state:e,dispatch:t})=>{if(e.readOnly)return!1;let i=e.changeByRange(n=>{let{from:r,to:o}=n,l=e.doc.lineAt(r),a=!s&&r==o&&Ax(e,r);s&&(r=o=(o<=l.to?l:e.doc.lineAt(o)).to);let h=new Vn(e,{simulateBreak:r,simulateDoubleBreak:!!a}),c=el(h,r);for(c==null&&(c=Ci(/^\s*/.exec(e.doc.lineAt(r).text)[0],e.tabSize));ol.from&&r{let n=[];for(let o=i.from;o<=i.to;){let l=s.doc.lineAt(o);l.number>t&&(i.empty||i.to>l.from)&&(e(l,n,i),t=l.number),o=l.to+1}let r=s.changes(n);return{changes:n,range:v.range(r.mapPos(i.anchor,1),r.mapPos(i.head,1))}})}const Px=({state:s,dispatch:e})=>{if(s.readOnly)return!1;let t=Object.create(null),i=new Vn(s,{overrideIndentation:r=>{let o=t[r];return o??-1}}),n=nl(s,(r,o,l)=>{let a=el(i,r.from);if(a==null)return;/\S/.test(r.text)||(a=0);let h=/^\s*/.exec(r.text)[0],c=is(s,a);(h!=c||l.froms.readOnly?!1:(e(s.update(nl(s,(t,i)=>{i.push({from:t.from,insert:s.facet(Fn)})}),{userEvent:"input.indent"})),!0),iu=({state:s,dispatch:e})=>s.readOnly?!1:(e(s.update(nl(s,(t,i)=>{let n=/^\s*/.exec(t.text)[0];if(!n)return;let r=Ci(n,s.tabSize),o=0,l=is(s,Math.max(0,r-mn(s)));for(;o(s.setTabFocusMode(),!0),Dx=[{key:"Ctrl-b",run:Rf,shift:Hf,preventDefault:!0},{key:"Ctrl-f",run:Bf,shift:zf},{key:"Ctrl-p",run:Nf,shift:jf},{key:"Ctrl-n",run:If,shift:qf},{key:"Ctrl-a",run:_0,shift:lx},{key:"Ctrl-e",run:K0,shift:ax},{key:"Ctrl-d",run:_f},{key:"Ctrl-h",run:vo},{key:"Ctrl-k",run:gx},{key:"Ctrl-Alt-h",run:Gf},{key:"Ctrl-o",run:yx},{key:"Ctrl-t",run:kx},{key:"Ctrl-v",run:wo}],Rx=[{key:"ArrowLeft",run:Rf,shift:Hf,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:H0,shift:Z0,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:U0,shift:rx,preventDefault:!0},{key:"ArrowRight",run:Bf,shift:zf,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:z0,shift:ex,preventDefault:!0},{mac:"Cmd-ArrowRight",run:Y0,shift:ox,preventDefault:!0},{key:"ArrowUp",run:Nf,shift:jf,preventDefault:!0},{mac:"Cmd-ArrowUp",run:Qa,shift:ja},{mac:"Ctrl-ArrowUp",run:Va,shift:Ha},{key:"ArrowDown",run:If,shift:qf,preventDefault:!0},{mac:"Cmd-ArrowDown",run:$a,shift:qa},{mac:"Ctrl-ArrowDown",run:wo,shift:za},{key:"PageUp",run:Va,shift:Ha},{key:"PageDown",run:wo,shift:za},{key:"Home",run:X0,shift:nx,preventDefault:!0},{key:"Mod-Home",run:Qa,shift:ja},{key:"End",run:q0,shift:sx,preventDefault:!0},{key:"Mod-End",run:$a,shift:qa},{key:"Enter",run:Xa,shift:Xa},{key:"Mod-a",run:hx},{key:"Backspace",run:vo,shift:vo,preventDefault:!0},{key:"Delete",run:_f,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:Gf,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:mx,preventDefault:!0},{mac:"Mod-Backspace",run:xx,preventDefault:!0},{mac:"Mod-Delete",run:bx,preventDefault:!0}].concat(Dx.map(s=>({mac:s.key,run:s.run,shift:s.shift}))),Bx=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:$0,shift:tx},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:j0,shift:ix},{key:"Alt-ArrowUp",run:wx},{key:"Shift-Alt-ArrowUp",run:Sx},{key:"Alt-ArrowDown",run:vx},{key:"Shift-Alt-ArrowDown",run:Ox},{key:"Mod-Alt-ArrowUp",run:ux},{key:"Mod-Alt-ArrowDown",run:dx},{key:"Escape",run:px},{key:"Mod-Enter",run:Mx},{key:"Alt-l",mac:"Ctrl-l",run:cx},{key:"Mod-i",run:fx,preventDefault:!0},{key:"Mod-[",run:iu},{key:"Mod-]",run:tu},{key:"Mod-Alt-\\",run:Px},{key:"Shift-Mod-k",run:Cx},{key:"Shift-Mod-\\",run:J0},{key:"Mod-/",run:w0},{key:"Alt-A",run:S0},{key:"Ctrl-m",mac:"Shift-Alt-m",run:Tx}].concat(Rx),Ex={key:"Tab",run:tu,shift:iu},Ua=typeof String.prototype.normalize=="function"?s=>s.normalize("NFKD"):s=>s;class Si{constructor(e,t,i=0,n=e.length,r,o){this.test=o,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=e.iterRange(i,n),this.bufferStart=i,this.normalize=r?l=>r(Ua(l)):Ua,this.query=this.normalize(t)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return Ce(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let e=this.peek();if(e<0)return this.done=!0,this;let t=Ro(e),i=this.bufferStart+this.bufferPos;this.bufferPos+=it(e);let n=this.normalize(t);if(n.length)for(let r=0,o=i,l=!0;;r++){let a=n.charCodeAt(r),h=this.match(a,o,l,this.bufferPos+this.bufferStart,r==n.length-1);if(h)return this.value=h,this;if(r==n.length-1)break;l&&rthis.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let e=this.matchPos-this.curLineStart;;){this.re.lastIndex=e;let t=this.matchPos<=this.to&&this.re.exec(this.curLine);if(t){let i=this.curLineStart+t.index,n=i+t[0].length;if(this.matchPos=yn(this.text,n+(i==n?1:0)),i==this.curLineStart+this.curLine.length&&this.nextLine(),(ithis.value.to)&&(!this.test||this.test(i,n,t)))return this.value={from:i,to:n,precise:!0,match:t},this;e=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length=i||n.to<=t){let l=new pi(t,e.sliceString(t,i));return yr.set(e,l),l}if(n.from==t&&n.to==i)return n;let{text:r,from:o}=n;return o>t&&(r=e.sliceString(t,o)+r,o=t),n.to=this.to?this.to:this.text.lineAt(e).to}next(){for(;;){let e=this.re.lastIndex=this.matchPos-this.flat.from,t=this.re.exec(this.flat.text);if(t&&!t[0]&&t.index==e&&(this.re.lastIndex=e+1,t=this.re.exec(this.flat.text)),t){let i=this.flat.from+t.index,n=i+t[0].length;if((this.flat.to>=this.to||t.index+t[0].length<=this.flat.text.length-10)&&(!this.test||this.test(i,n,t)))return this.value={from:i,to:n,precise:!0,match:t},this.matchPos=yn(this.text,n+(i==n?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=pi.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(nu.prototype[Symbol.iterator]=ru.prototype[Symbol.iterator]=function(){return this});function Lx(s){try{return new RegExp(s,rl),!0}catch{return!1}}function yn(s,e){if(e>=s.length)return e;let t=s.lineAt(e),i;for(;e=56320&&i<57344;)e++;return e}const Nx=s=>{let{state:e}=s,t=String(e.doc.lineAt(s.state.selection.main.head).number),{close:i,result:n}=eg(s,{label:e.phrase("Go to line"),input:{type:"text",name:"line",value:t},focus:!0,submitLabel:e.phrase("go")});return n.then(r=>{let o=r&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(r.elements.line.value);if(!o){s.dispatch({effects:i});return}let l=e.doc.lineAt(e.selection.main.head),[,a,h,c,f]=o,u=c?+c.slice(1):0,d=h?+h:l.number;if(h&&f){let g=d/100;a&&(g=g*(a=="-"?-1:1)+l.number/e.doc.lines),d=Math.round(e.doc.lines*g)}else h&&a&&(d=d*(a=="-"?-1:1)+l.number);let p=e.doc.line(Math.max(1,Math.min(e.doc.lines,d))),m=v.cursor(p.from+Math.max(0,Math.min(u,p.length)));s.dispatch({effects:[i,L.scrollIntoView(m.from,{y:"center"})],selection:m})}),!0},Ix={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},Wx=I.define({combine(s){return ht(s,Ix,{highlightWordAroundCursor:(e,t)=>e||t,minSelectionLength:Math.min,maxMatches:Math.min})}});function Fx(s){return[$x,Qx]}const Vx=z.mark({class:"cm-selectionMatch"}),Hx=z.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function Ya(s,e,t,i){return(t==0||s(e.sliceDoc(t-1,t))!=ee.Word)&&(i==e.doc.length||s(e.sliceDoc(i,i+1))!=ee.Word)}function zx(s,e,t,i){return s(e.sliceDoc(t,t+1))==ee.Word&&s(e.sliceDoc(i-1,i))==ee.Word}const Qx=se.fromClass(class{constructor(s){this.decorations=this.getDeco(s)}update(s){(s.selectionSet||s.docChanged||s.viewportChanged)&&(this.decorations=this.getDeco(s.view))}getDeco(s){let e=s.state.facet(Wx),{state:t}=s,i=t.selection;if(i.ranges.length>1)return z.none;let n=i.main,r,o=null;if(n.empty){if(!e.highlightWordAroundCursor)return z.none;let a=t.wordAt(n.head);if(!a)return z.none;o=t.charCategorizer(n.head),r=t.sliceDoc(a.from,a.to)}else{let a=n.to-n.from;if(a200)return z.none;if(e.wholeWords){if(r=t.sliceDoc(n.from,n.to),o=t.charCategorizer(n.head),!(Ya(o,t,n.from,n.to)&&zx(o,t,n.from,n.to)))return z.none}else if(r=t.sliceDoc(n.from,n.to),!r)return z.none}let l=[];for(let a of s.visibleRanges){let h=new Si(t.doc,r,a.from,a.to);for(;!h.next().done;){let{from:c,to:f}=h.value;if((!o||Ya(o,t,c,f))&&(n.empty&&c<=n.from&&f>=n.to?l.push(Hx.range(c,f)):(c>=n.to||f<=n.from)&&l.push(Vx.range(c,f)),l.length>e.maxMatches))return z.none}}return z.set(l)}},{decorations:s=>s.decorations}),$x=L.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),jx=({state:s,dispatch:e})=>{let{selection:t}=s,i=v.create(t.ranges.map(n=>s.wordAt(n.head)||v.cursor(n.head)),t.mainIndex);return i.eq(t)?!1:(e(s.update({selection:i})),!0)};function qx(s,e){let{main:t,ranges:i}=s.selection,n=s.wordAt(t.head),r=n&&n.from==t.from&&n.to==t.to;for(let o=!1,l=new Si(s.doc,e,i[i.length-1].to);;)if(l.next(),l.done){if(o)return null;l=new Si(s.doc,e,0,Math.max(0,i[i.length-1].from-1)),o=!0}else{if(o&&i.some(a=>a.from==l.value.from))continue;if(r){let a=s.wordAt(l.value.from);if(!a||a.from!=l.value.from||a.to!=l.value.to)continue}return l.value}}const Xx=({state:s,dispatch:e})=>{let{ranges:t}=s.selection;if(t.some(r=>r.from===r.to))return jx({state:s,dispatch:e});let i=s.sliceDoc(t[0].from,t[0].to);if(s.selection.ranges.some(r=>s.sliceDoc(r.from,r.to)!=i))return!1;let n=qx(s,i);return n?(e(s.update({selection:s.selection.addRange(v.range(n.from,n.to),!1),effects:L.scrollIntoView(n.to)})),!0):!1},Mi=I.define({combine(s){return ht(s,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:e=>new ob(e),scrollToMatch:e=>L.scrollIntoView(e)})}});class ou{constructor(e){this.search=e.search,this.caseSensitive=!!e.caseSensitive,this.literal=!!e.literal,this.regexp=!!e.regexp,this.replace=e.replace||"",this.valid=!!this.search&&(!this.regexp||Lx(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!e.wholeWord,this.test=e.test}unquote(e){return this.literal?e:e.replace(/\\([nrt\\])/g,(t,i)=>i=="n"?` +`:i=="r"?"\r":i=="t"?" ":"\\")}eq(e){return this.search==e.search&&this.replace==e.replace&&this.caseSensitive==e.caseSensitive&&this.regexp==e.regexp&&this.wholeWord==e.wholeWord&&this.test==e.test}create(){return this.regexp?new Jx(this):new _x(this)}getCursor(e,t=0,i){let n=e.doc?e:U.create({doc:e});return i==null&&(i=n.doc.length),this.regexp?ni(this,n,t,i):si(this,n,t,i)}}class lu{constructor(e){this.spec=e}}function Ux(s,e,t){return(i,n,r,o)=>{if(t&&!t(i,n,r,o))return!1;let l=i>=o&&n<=o+r.length?r.slice(i-o,n-o):e.doc.sliceString(i,n);return s(l,e,i,n)}}function si(s,e,t,i){let n;return s.wholeWord&&(n=Yx(e.doc,e.charCategorizer(e.selection.main.head))),s.test&&(n=Ux(s.test,e,n)),new Si(e.doc,s.unquoted,t,i,s.caseSensitive?void 0:r=>r.toLowerCase(),n)}function Yx(s,e){return(t,i,n,r)=>((r>t||r+n.length=t)return null;n.push(i.value)}return n}highlight(e,t,i,n){let r=si(this.spec,e,Math.max(0,t-this.spec.unquoted.length),Math.min(i+this.spec.unquoted.length,e.doc.length));for(;!r.next().done;)n(r.value.from,r.value.to)}}function Kx(s,e,t){return(i,n,r)=>(!t||t(i,n,r))&&s(r[0],e,i,n)}function ni(s,e,t,i){let n;return s.wholeWord&&(n=Gx(e.charCategorizer(e.selection.main.head))),s.test&&(n=Kx(s.test,e,n)),new nu(e.doc,s.search,{ignoreCase:!s.caseSensitive,test:n},t,i)}function kn(s,e){return s.slice(fe(s,e,!1),e)}function wn(s,e){return s.slice(e,fe(s,e))}function Gx(s){return(e,t,i)=>!i[0].length||(s(kn(i.input,i.index))!=ee.Word||s(wn(i.input,i.index))!=ee.Word)&&(s(wn(i.input,i.index+i[0].length))!=ee.Word||s(kn(i.input,i.index+i[0].length))!=ee.Word)}class Jx extends lu{nextMatch(e,t,i){let n=ni(this.spec,e,i,e.doc.length).next();return n.done&&(n=ni(this.spec,e,0,t).next()),n.done?null:n.value}prevMatchInRange(e,t,i){for(let n=1;;n++){let r=Math.max(t,i-n*1e4),o=ni(this.spec,e,r,i),l=null;for(;!o.next().done;)l=o.value;if(l&&(r==t||l.from>r+10))return l;if(r==t)return null}}prevMatch(e,t,i){return this.prevMatchInRange(e,0,t)||this.prevMatchInRange(e,i,e.doc.length)}getReplacement(e){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(t,i)=>{if(i=="&")return e.match[0];if(i=="$")return"$";for(let n=i.length;n>0;n--){let r=+i.slice(0,n);if(r>0&&r=t)return null;n.push(i.value)}return n}highlight(e,t,i,n){let r=ni(this.spec,e,Math.max(0,t-250),Math.min(i+250,e.doc.length));for(;!r.next().done;)n(r.value.from,r.value.to)}}const ss=$.define(),ol=$.define(),At=ye.define({create(s){return new kr(So(s).create(),null)},update(s,e){for(let t of e.effects)t.is(ss)?s=new kr(t.value.create(),s.panel):t.is(ol)&&(s=new kr(s.query,t.value?ll:null));return s},provide:s=>Zi.from(s,e=>e.panel)});class kr{constructor(e,t){this.query=e,this.panel=t}}const Zx=z.mark({class:"cm-searchMatch"}),eb=z.mark({class:"cm-searchMatch cm-searchMatch-selected"}),tb=se.fromClass(class{constructor(s){this.view=s,this.decorations=this.highlight(s.state.field(At))}update(s){let e=s.state.field(At);(e!=s.startState.field(At)||s.docChanged||s.selectionSet||s.viewportChanged)&&(this.decorations=this.highlight(e))}highlight({query:s,panel:e}){if(!e||!s.spec.valid)return z.none;let{view:t}=this,i=new mt;for(let n=0,r=t.visibleRanges,o=r.length;nr[n+1].from-500;)a=r[++n].to;s.highlight(t.state,l,a,(h,c)=>{let f=t.state.selection.ranges.some(u=>u.from==h&&u.to==c);i.add(h,c,f?eb:Zx)})}return i.finish()}},{decorations:s=>s.decorations});function ms(s){return e=>{let t=e.state.field(At,!1);return t&&t.query.spec.valid?s(e,t):cu(e)}}const vn=ms((s,{query:e})=>{let{to:t}=s.state.selection.main,i=e.nextMatch(s.state,t,t);if(!i)return!1;let n=v.single(i.from,i.to),r=s.state.facet(Mi);return s.dispatch({selection:n,effects:[al(s,i),r.scrollToMatch(n.main,s)],userEvent:"select.search"}),hu(s),!0}),Sn=ms((s,{query:e})=>{let{state:t}=s,{from:i}=t.selection.main,n=e.prevMatch(t,i,i);if(!n)return!1;let r=v.single(n.from,n.to),o=s.state.facet(Mi);return s.dispatch({selection:r,effects:[al(s,n),o.scrollToMatch(r.main,s)],userEvent:"select.search"}),hu(s),!0}),ib=ms((s,{query:e})=>{let t=e.matchAll(s.state,1e3);return!t||!t.length?!1:(s.dispatch({selection:v.create(t.map(i=>v.range(i.from,i.to))),userEvent:"select.search.matches"}),!0)}),sb=({state:s,dispatch:e})=>{let t=s.selection;if(t.ranges.length>1||t.main.empty)return!1;let{from:i,to:n}=t.main,r=[],o=0;for(let l=new Si(s.doc,s.sliceDoc(i,n));!l.next().done;){if(r.length>1e3)return!1;l.value.from==i&&(o=r.length),r.push(v.range(l.value.from,l.value.to))}return e(s.update({selection:v.create(r,o),userEvent:"select.search.matches"})),!0},_a=ms((s,{query:e})=>{let{state:t}=s,{from:i,to:n}=t.selection.main;if(t.readOnly)return!1;let r=e.nextMatch(t,i,i);if(!r)return!1;let o=r,l=[],a,h,c=[];o.precise?o.from==i&&o.to==n&&(h=t.toText(e.getReplacement(o)),l.push({from:o.from,to:o.to,insert:h}),o=e.nextMatch(t,o.from,o.to),c.push(L.announce.of(t.phrase("replaced match on line $",t.doc.lineAt(i).number)+"."))):o=e.nextMatch(t,o.from,o.to);let f=s.state.changes(l);return o&&(a=v.single(o.from,o.to).map(f),c.push(al(s,o)),c.push(t.facet(Mi).scrollToMatch(a.main,s))),s.dispatch({changes:f,selection:a,effects:c,userEvent:"input.replace"}),!0}),nb=ms((s,{query:e})=>{if(s.state.readOnly)return!1;let t=[];for(let n of e.matchAll(s.state,1e9)){let{from:r,to:o,precise:l}=n;l&&t.push({from:r,to:o,insert:e.getReplacement(n)})}if(!t.length)return!1;let i=s.state.phrase("replaced $ matches",t.length)+".";return s.dispatch({changes:t,effects:L.announce.of(i),userEvent:"input.replace.all"}),!0});function ll(s){return s.state.facet(Mi).createPanel(s)}function So(s,e){var t,i,n,r,o;let l=s.selection.main,a=l.empty||l.to>l.from+100?"":s.sliceDoc(l.from,l.to);if(e&&!a)return e;let h=s.facet(Mi);return new ou({search:((t=e?.literal)!==null&&t!==void 0?t:h.literal)?a:a.replace(/\n/g,"\\n"),caseSensitive:(i=e?.caseSensitive)!==null&&i!==void 0?i:h.caseSensitive,literal:(n=e?.literal)!==null&&n!==void 0?n:h.literal,regexp:(r=e?.regexp)!==null&&r!==void 0?r:h.regexp,wholeWord:(o=e?.wholeWord)!==null&&o!==void 0?o:h.wholeWord})}function au(s){let e=_o(s,ll);return e&&e.dom.querySelector("[main-field]")}function hu(s){let e=au(s);e&&e==s.root.activeElement&&e.select()}const cu=s=>{let e=s.state.field(At,!1);if(e&&e.panel){let t=au(s);if(t&&t!=s.root.activeElement){let i=So(s.state,e.query.spec);i.valid&&s.dispatch({effects:ss.of(i)}),t.focus(),t.select()}}else s.dispatch({effects:[ol.of(!0),e?ss.of(So(s.state,e.query.spec)):$.appendConfig.of(ab)]});return!0},fu=s=>{let e=s.state.field(At,!1);if(!e||!e.panel)return!1;let t=_o(s,ll);return t&&t.dom.contains(s.root.activeElement)&&s.focus(),s.dispatch({effects:ol.of(!1)}),!0},rb=[{key:"Mod-f",run:cu,scope:"editor search-panel"},{key:"F3",run:vn,shift:Sn,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:vn,shift:Sn,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:fu,scope:"editor search-panel"},{key:"Mod-Shift-l",run:sb},{key:"Mod-Alt-g",run:Nx},{key:"Mod-d",run:Xx,preventDefault:!0}];class ob{constructor(e){this.view=e;let t=this.query=e.state.field(At).query.spec;this.commit=this.commit.bind(this),this.searchField=_("input",{value:t.search,placeholder:Ee(e,"Find"),"aria-label":Ee(e,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=_("input",{value:t.replace,placeholder:Ee(e,"Replace"),"aria-label":Ee(e,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=_("input",{type:"checkbox",name:"case",form:"",checked:t.caseSensitive,onchange:this.commit}),this.reField=_("input",{type:"checkbox",name:"re",form:"",checked:t.regexp,onchange:this.commit}),this.wordField=_("input",{type:"checkbox",name:"word",form:"",checked:t.wholeWord,onchange:this.commit});function i(n,r,o){return _("button",{class:"cm-button",name:n,onclick:r,type:"button"},o)}this.dom=_("div",{onkeydown:n=>this.keydown(n),class:"cm-search"},[this.searchField,i("next",()=>vn(e),[Ee(e,"next")]),i("prev",()=>Sn(e),[Ee(e,"previous")]),i("select",()=>ib(e),[Ee(e,"all")]),_("label",null,[this.caseField,Ee(e,"match case")]),_("label",null,[this.reField,Ee(e,"regexp")]),_("label",null,[this.wordField,Ee(e,"by word")]),...e.state.readOnly?[]:[_("br"),this.replaceField,i("replace",()=>_a(e),[Ee(e,"replace")]),i("replaceAll",()=>nb(e),[Ee(e,"replace all")])],_("button",{name:"close",onclick:()=>fu(e),"aria-label":Ee(e,"close"),type:"button"},["×"])])}commit(){let e=new ou({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});e.eq(this.query)||(this.query=e,this.view.dispatch({effects:ss.of(e)}))}keydown(e){hm(this.view,e,"search-panel")?e.preventDefault():e.keyCode==13&&e.target==this.searchField?(e.preventDefault(),(e.shiftKey?Sn:vn)(this.view)):e.keyCode==13&&e.target==this.replaceField&&(e.preventDefault(),_a(this.view))}update(e){for(let t of e.transactions)for(let i of t.effects)i.is(ss)&&!i.value.eq(this.query)&&this.setQuery(i.value)}setQuery(e){this.query=e,this.searchField.value=e.search,this.replaceField.value=e.replace,this.caseField.checked=e.caseSensitive,this.reField.checked=e.regexp,this.wordField.checked=e.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(Mi).top}}function Ee(s,e){return s.state.phrase(e)}const Vs=30,Hs=/[\s\.,:;?!]/;function al(s,{from:e,to:t}){let i=s.state.doc.lineAt(e),n=s.state.doc.lineAt(t).to,r=Math.max(i.from,e-Vs),o=Math.min(n,t+Vs),l=s.state.sliceDoc(r,o);if(r!=i.from){for(let a=0;al.length-Vs;a--)if(!Hs.test(l[a-1])&&Hs.test(l[a])){l=l.slice(0,a);break}}return L.announce.of(`${s.state.phrase("current match")}. ${l} ${s.state.phrase("on line")} ${i.number}.`)}const lb=L.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),ab=[At,ei.low(tb),lb];class uu{constructor(e,t,i,n){this.state=e,this.pos=t,this.explicit=i,this.view=n,this.abortListeners=[],this.abortOnDocChange=!1}tokenBefore(e){let t=be(this.state).resolveInner(this.pos,-1);for(;t&&e.indexOf(t.name)<0;)t=t.parent;return t?{from:t.from,to:this.pos,text:this.state.sliceDoc(t.from,this.pos),type:t.type}:null}matchBefore(e){let t=this.state.doc.lineAt(this.pos),i=Math.max(t.from,this.pos-250),n=t.text.slice(i-t.from,this.pos-t.from),r=n.search(du(e,!1));return r<0?null:{from:i+r,to:this.pos,text:n.slice(r)}}get aborted(){return this.abortListeners==null}addEventListener(e,t,i){e=="abort"&&this.abortListeners&&(this.abortListeners.push(t),i&&i.onDocChange&&(this.abortOnDocChange=!0))}}function Ka(s){let e=Object.keys(s).join(""),t=/\w/.test(e);return t&&(e=e.replace(/\w/g,"")),`[${t?"\\w":""}${e.replace(/[^\w\s]/g,"\\$&")}]`}function hb(s){let e=Object.create(null),t=Object.create(null);for(let{label:n}of s){e[n[0]]=!0;for(let r=1;rtypeof n=="string"?{label:n}:n),[t,i]=e.every(n=>/^\w+$/.test(n.label))?[/\w*$/,/\w+$/]:hb(e);return n=>{let r=n.matchBefore(i);return r||n.explicit?{from:r?r.from:n.pos,options:e,validFor:t}:null}}class Ga{constructor(e,t,i,n){this.completion=e,this.source=t,this.match=i,this.score=n}}function _t(s){return s.selection.main.from}function du(s,e){var t;let{source:i}=s,n=e&&i[0]!="^",r=i[i.length-1]!="$";return!n&&!r?s:new RegExp(`${n?"^":""}(?:${i})${r?"$":""}`,(t=s.flags)!==null&&t!==void 0?t:s.ignoreCase?"i":"")}const pu=at.define();function fb(s,e,t,i){let{main:n}=s.selection,r=t-n.from,o=i-n.from;return{...s.changeByRange(l=>{if(l!=n&&t!=i&&s.sliceDoc(l.from+r,l.from+o)!=s.sliceDoc(t,i))return{range:l};let a=s.toText(e);return{changes:{from:l.from+r,to:i==n.from?l.to:l.from+o,insert:a},range:v.cursor(l.from+r+a.length)}}),scrollIntoView:!0,userEvent:"input.complete"}}const Ja=new WeakMap;function ub(s){if(!Array.isArray(s))return s;let e=Ja.get(s);return e||Ja.set(s,e=cb(s)),e}const On=$.define(),ns=$.define();class db{constructor(e){this.pattern=e,this.chars=[],this.folded=[],this.any=[],this.precise=[],this.byWord=[],this.score=0,this.matched=[];for(let t=0;t=48&&S<=57||S>=97&&S<=122?2:S>=65&&S<=90?1:0:(A=Ro(S))!=A.toLowerCase()?1:A!=A.toUpperCase()?2:0;(!k||O==1&&g||T==0&&O!=0)&&(t[f]==S||i[f]==S&&(u=!0)?o[f++]=k:o.length&&(x=!1)),T=O,k+=it(S)}return f==a&&o[0]==0&&x?this.result(-100+(u?-200:0),o,e):d==a&&p==0?this.ret(-200-e.length+(m==e.length?0:-100),[0,m]):l>-1?this.ret(-700-e.length,[l,l+this.pattern.length]):d==a?this.ret(-900-e.length,[p,m]):f==a?this.result(-100+(u?-200:0)+-700+(x?0:-1100),o,e):t.length==2?null:this.result((n[0]?-700:0)+-200+-1100,n,e)}result(e,t,i){let n=[],r=0;for(let o of t){let l=o+(this.astral?it(Ce(i,o)):1);r&&n[r-1]==o?n[r-1]=l:(n[r++]=o,n[r++]=l)}return this.ret(e-i.length,n)}}class pb{constructor(e){this.pattern=e,this.matched=[],this.score=0,this.folded=e.toLowerCase()}match(e){if(e.length!1,activateOnTypingDelay:100,selectOnOpen:!0,override:null,closeOnBlur:!0,maxRenderedOptions:100,defaultKeymap:!0,tooltipClass:()=>"",optionClass:()=>"",aboveCursor:!1,icons:!0,addToOptions:[],positionInfo:mb,filterStrict:!1,compareCompletions:(e,t)=>(e.sortText||e.label).localeCompare(t.sortText||t.label),interactionDelay:75,updateSyncTime:100},{defaultKeymap:(e,t)=>e&&t,closeOnBlur:(e,t)=>e&&t,icons:(e,t)=>e&&t,tooltipClass:(e,t)=>i=>Za(e(i),t(i)),optionClass:(e,t)=>i=>Za(e(i),t(i)),addToOptions:(e,t)=>e.concat(t),filterStrict:(e,t)=>e||t})}});function Za(s,e){return s?e?s+" "+e:s:e}function mb(s,e,t,i,n,r){let o=s.textDirection==J.RTL,l=o,a=!1,h="top",c,f,u=e.left-n.left,d=n.right-e.right,p=i.right-i.left,m=i.bottom-i.top;if(l&&u=m||k>e.top?c=t.bottom-e.top:(h="bottom",c=e.bottom-t.top)}let g=(e.bottom-e.top)/r.offsetHeight,x=(e.right-e.left)/r.offsetWidth;return{style:`${h}: ${c/g}px; max-width: ${f/x}px`,class:"cm-completionInfo-"+(a?o?"left-narrow":"right-narrow":l?"left":"right")}}const hl=$.define();function gb(s){let e=s.addToOptions.slice();return s.icons&&e.push({render(t){let i=document.createElement("div");return i.classList.add("cm-completionIcon"),t.type&&i.classList.add(...t.type.split(/\s+/g).map(n=>"cm-completionIcon-"+n)),i.setAttribute("aria-hidden","true"),i},position:20}),e.push({render(t,i,n,r){let o=document.createElement("span");o.className="cm-completionLabel";let l=t.displayLabel||t.label,a=0;for(let h=0;ha&&o.appendChild(document.createTextNode(l.slice(a,c)));let u=o.appendChild(document.createElement("span"));u.appendChild(document.createTextNode(l.slice(c,f))),u.className="cm-completionMatchedText",a=f}return at.position-i.position).map(t=>t.render)}function wr(s,e,t){if(s<=t)return{from:0,to:s};if(e<0&&(e=0),e<=s>>1){let n=Math.floor(e/t);return{from:n*t,to:(n+1)*t}}let i=Math.ceil((s-e)/t);return{from:s-i*t,to:s-(i-1)*t}}class xb{constructor(e,t,i){this.view=e,this.stateField=t,this.applyCompletion=i,this.info=null,this.infoDestroy=null,this.placeInfoReq={read:()=>this.measureInfo(),write:a=>this.placeInfo(a),key:this},this.space=null,this.currentClass="";let n=e.state.field(t),{options:r,selected:o}=n.open,l=e.state.facet(ce);this.optionContent=gb(l),this.optionClass=l.optionClass,this.tooltipClass=l.tooltipClass,this.range=wr(r.length,o,l.maxRenderedOptions),this.dom=document.createElement("div"),this.dom.className="cm-tooltip-autocomplete",this.updateTooltipClass(e.state),this.dom.addEventListener("mousedown",a=>{let{options:h}=e.state.field(t).open;for(let c=a.target,f;c&&c!=this.dom;c=c.parentNode)if(c.nodeName=="LI"&&(f=/-(\d+)$/.exec(c.id))&&+f[1]this.list.lastChild.getBoundingClientRect().bottom?this.range.to:null;c!=null&&(e.dispatch({effects:hl.of(c)}),a.preventDefault())}}),this.dom.addEventListener("focusout",a=>{let h=e.state.field(this.stateField,!1);h&&h.tooltip&&e.state.facet(ce).closeOnBlur&&a.relatedTarget!=e.contentDOM&&e.dispatch({effects:ns.of(null)})}),this.showOptions(r,n.id)}mount(){this.updateSel()}showOptions(e,t){this.list&&this.list.remove(),this.list=this.dom.appendChild(this.createListBox(e,t,this.range)),this.list.addEventListener("scroll",()=>{this.info&&this.view.requestMeasure(this.placeInfoReq)})}update(e){var t;let i=e.state.field(this.stateField),n=e.startState.field(this.stateField);if(this.updateTooltipClass(e.state),i!=n){let{options:r,selected:o,disabled:l}=i.open;(!n.open||n.open.options!=r)&&(this.range=wr(r.length,o,e.state.facet(ce).maxRenderedOptions),this.showOptions(r,i.id)),this.updateSel(),l!=((t=n.open)===null||t===void 0?void 0:t.disabled)&&this.dom.classList.toggle("cm-tooltip-autocomplete-disabled",!!l)}}updateTooltipClass(e){let t=this.tooltipClass(e);if(t!=this.currentClass){for(let i of this.currentClass.split(" "))i&&this.dom.classList.remove(i);for(let i of t.split(" "))i&&this.dom.classList.add(i);this.currentClass=t}}positioned(e){this.space=e,this.info&&this.view.requestMeasure(this.placeInfoReq)}updateSel(){let e=this.view.state.field(this.stateField),t=e.open;(t.selected>-1&&t.selected=this.range.to)&&(this.range=wr(t.options.length,t.selected,this.view.state.facet(ce).maxRenderedOptions),this.showOptions(t.options,e.id));let i=this.updateSelectedOption(t.selected);if(i){this.destroyInfo();let{completion:n}=t.options[t.selected],{info:r}=n;if(!r)return;let o=typeof r=="string"?document.createTextNode(r):r(n);if(!o)return;"then"in o?o.then(l=>{l&&this.view.state.field(this.stateField,!1)==e&&this.addInfoPane(l,n)}).catch(l=>Pe(this.view.state,l,"completion info")):(this.addInfoPane(o,n),i.setAttribute("aria-describedby",this.info.id))}}addInfoPane(e,t){this.destroyInfo();let i=this.info=document.createElement("div");if(i.className="cm-tooltip cm-completionInfo",i.id="cm-completionInfo-"+Math.floor(Math.random()*65535).toString(16),e.nodeType!=null)i.appendChild(e),this.infoDestroy=null;else{let{dom:n,destroy:r}=e;i.appendChild(n),this.infoDestroy=r||null}this.dom.appendChild(i),this.view.requestMeasure(this.placeInfoReq)}updateSelectedOption(e){let t=null;for(let i=this.list.firstChild,n=this.range.from;i;i=i.nextSibling,n++)i.nodeName!="LI"||!i.id?n--:n==e?i.hasAttribute("aria-selected")||(i.setAttribute("aria-selected","true"),t=i):i.hasAttribute("aria-selected")&&(i.removeAttribute("aria-selected"),i.removeAttribute("aria-describedby"));return t&&yb(this.list,t),t}measureInfo(){let e=this.dom.querySelector("[aria-selected]");if(!e||!this.info)return null;let t=this.dom.getBoundingClientRect(),i=this.info.getBoundingClientRect(),n=e.getBoundingClientRect(),r=this.space;if(!r){let o=this.dom.ownerDocument.documentElement;r={left:0,top:0,right:o.clientWidth,bottom:o.clientHeight}}return n.top>Math.min(r.bottom,t.bottom)-10||n.bottom{o.target==n&&o.preventDefault()});let r=null;for(let o=i.from;oi.from||i.from==0))if(r=u,typeof h!="string"&&h.header)n.appendChild(h.header(h));else{let d=n.appendChild(document.createElement("completion-section"));d.textContent=u}}const c=n.appendChild(document.createElement("li"));c.id=t+"-"+o,c.setAttribute("role","option");let f=this.optionClass(l);f&&(c.className=f);for(let u of this.optionContent){let d=u(l,this.view.state,this.view,a);d&&c.appendChild(d)}}return i.from&&n.classList.add("cm-completionListIncompleteTop"),i.tonew xb(t,s,e)}function yb(s,e){let t=s.getBoundingClientRect(),i=e.getBoundingClientRect(),n=t.height/s.offsetHeight;i.topt.bottom&&(s.scrollTop+=(i.bottom-t.bottom)/n)}function eh(s){return(s.boost||0)*100+(s.apply?10:0)+(s.info?5:0)+(s.type?1:0)}function kb(s,e){let t=[],i=null,n=null,r=c=>{t.push(c);let{section:f}=c.completion;if(f){i||(i=[]);let u=typeof f=="string"?f:f.name;i.some(d=>d.name==u)||i.push(typeof f=="string"?{name:u}:f)}},o=e.facet(ce);for(let c of s)if(c.hasResult()){let f=c.result.getMatch;if(c.result.filter===!1)for(let u of c.result.options)r(new Ga(u,c.source,f?f(u):[],1e9-t.length));else{let u=e.sliceDoc(c.from,c.to),d,p=o.filterStrict?new pb(u):new db(u);for(let m of c.result.options)if(d=p.match(m.label)){let g=m.displayLabel?f?f(m,d.matched):[]:d.matched,x=d.score+(m.boost||0);if(r(new Ga(m,c.source,g,x)),typeof m.section=="object"&&m.section.rank==="dynamic"){let{name:k}=m.section;n||(n=Object.create(null)),n[k]=Math.max(x,n[k]||-1e9)}}}}if(i){let c=Object.create(null),f=0,u=(d,p)=>(d.rank==="dynamic"&&p.rank==="dynamic"?n[p.name]-n[d.name]:0)||(typeof d.rank=="number"?d.rank:1e9)-(typeof p.rank=="number"?p.rank:1e9)||(d.nameu.score-f.score||h(f.completion,u.completion))){let f=c.completion;!a||a.label!=f.label||a.detail!=f.detail||a.type!=null&&f.type!=null&&a.type!=f.type||a.apply!=f.apply||a.boost!=f.boost?l.push(c):eh(c.completion)>eh(a)&&(l[l.length-1]=c),a=c.completion}return l}class hi{constructor(e,t,i,n,r,o){this.options=e,this.attrs=t,this.tooltip=i,this.timestamp=n,this.selected=r,this.disabled=o}setSelected(e,t){return e==this.selected||e>=this.options.length?this:new hi(this.options,th(t,e),this.tooltip,this.timestamp,e,this.disabled)}static build(e,t,i,n,r,o){if(n&&!o&&e.some(h=>h.isPending))return n.setDisabled();let l=kb(e,t);if(!l.length)return n&&e.some(h=>h.isPending)?n.setDisabled():null;let a=t.facet(ce).selectOnOpen?0:-1;if(n&&n.selected!=a&&n.selected!=-1){let h=n.options[n.selected].completion;for(let c=0;cc.hasResult()?Math.min(h,c.from):h,1e8),create:Ab,above:r.aboveCursor},n?n.timestamp:Date.now(),a,!1)}map(e){return new hi(this.options,this.attrs,{...this.tooltip,pos:e.mapPos(this.tooltip.pos)},this.timestamp,this.selected,this.disabled)}setDisabled(){return new hi(this.options,this.attrs,this.tooltip,this.timestamp,this.selected,!0)}}class Cn{constructor(e,t,i){this.active=e,this.id=t,this.open=i}static start(){return new Cn(Ob,"cm-ac-"+Math.floor(Math.random()*2e6).toString(36),null)}update(e){let{state:t}=e,i=t.facet(ce),r=(i.override||t.languageDataAt("autocomplete",_t(t)).map(ub)).map(a=>(this.active.find(c=>c.source==a)||new Ve(a,this.active.some(c=>c.state!=0)?1:0)).update(e,i));r.length==this.active.length&&r.every((a,h)=>a==this.active[h])&&(r=this.active);let o=this.open,l=e.effects.some(a=>a.is(cl));o&&e.docChanged&&(o=o.map(e.changes)),e.selection||r.some(a=>a.hasResult()&&e.changes.touchesRange(a.from,a.to))||!wb(r,this.active)||l?o=hi.build(r,t,this.id,o,i,l):o&&o.disabled&&!r.some(a=>a.isPending)&&(o=null),!o&&r.every(a=>!a.isPending)&&r.some(a=>a.hasResult())&&(r=r.map(a=>a.hasResult()?new Ve(a.source,0):a));for(let a of e.effects)a.is(hl)&&(o=o&&o.setSelected(a.value,this.id));return r==this.active&&o==this.open?this:new Cn(r,this.id,o)}get tooltip(){return this.open?this.open.tooltip:null}get attrs(){return this.open?this.open.attrs:this.active.length?vb:Sb}}function wb(s,e){if(s==e)return!0;for(let t=0,i=0;;){for(;t-1&&(t["aria-activedescendant"]=s+"-"+e),t}const Ob=[];function mu(s,e){if(s.isUserEvent("input.complete")){let i=s.annotation(pu);if(i&&e.activateOnCompletion(i))return 12}let t=s.isUserEvent("input.type");return t&&e.activateOnTyping?5:t?1:s.isUserEvent("delete.backward")?2:s.selection?8:s.docChanged?16:0}class Ve{constructor(e,t,i=!1){this.source=e,this.state=t,this.explicit=i}hasResult(){return!1}get isPending(){return this.state==1}update(e,t){let i=mu(e,t),n=this;(i&8||i&16&&this.touches(e))&&(n=new Ve(n.source,0)),i&4&&n.state==0&&(n=new Ve(this.source,1)),n=n.updateFor(e,i);for(let r of e.effects)if(r.is(On))n=new Ve(n.source,1,r.value);else if(r.is(ns))n=new Ve(n.source,0);else if(r.is(cl))for(let o of r.value)o.source==n.source&&(n=o);return n}updateFor(e,t){return this.map(e.changes)}map(e){return this}touches(e){return e.changes.touchesRange(_t(e.state))}}class mi extends Ve{constructor(e,t,i,n,r,o){super(e,3,t),this.limit=i,this.result=n,this.from=r,this.to=o}hasResult(){return!0}updateFor(e,t){var i;if(!(t&3))return this.map(e.changes);let n=this.result;n.map&&!e.changes.empty&&(n=n.map(n,e.changes));let r=e.changes.mapPos(this.from),o=e.changes.mapPos(this.to,1),l=_t(e.state);if(l>o||!n||t&2&&(_t(e.startState)==this.from||lt.map(e))}}),Ae=ye.define({create(){return Cn.start()},update(s,e){return s.update(e)},provide:s=>[Yo.from(s,e=>e.tooltip),L.contentAttributes.from(s,e=>e.attrs)]});function fl(s,e){const t=e.completion.apply||e.completion.label;let i=s.state.field(Ae).active.find(n=>n.source==e.source);return i instanceof mi?(typeof t=="string"?s.dispatch({...fb(s.state,t,i.from,i.to),annotations:pu.of(e.completion)}):t(s,e.completion,i.from,i.to),!0):!1}const Ab=bb(Ae,fl);function zs(s,e="option"){return t=>{let i=t.state.field(Ae,!1);if(!i||!i.open||i.open.disabled||Date.now()-i.open.timestamp-1?i.open.selected+n*(s?1:-1):s?0:o-1;return l<0?l=e=="page"?0:o-1:l>=o&&(l=e=="page"?o-1:0),t.dispatch({effects:hl.of(l)}),!0}}const Mb=s=>{let e=s.state.field(Ae,!1);return s.state.readOnly||!e||!e.open||e.open.selected<0||e.open.disabled||Date.now()-e.open.timestamps.state.field(Ae,!1)?(s.dispatch({effects:On.of(!0)}),!0):!1,Pb=s=>{let e=s.state.field(Ae,!1);return!e||!e.active.some(t=>t.state!=0)?!1:(s.dispatch({effects:ns.of(null)}),!0)};class Tb{constructor(e,t){this.active=e,this.context=t,this.time=Date.now(),this.updates=[],this.done=void 0}}const Db=50,Rb=1e3,Bb=se.fromClass(class{constructor(s){this.view=s,this.debounceUpdate=-1,this.running=[],this.debounceAccept=-1,this.pendingStart=!1,this.composing=0;for(let e of s.state.field(Ae).active)e.isPending&&this.startQuery(e)}update(s){let e=s.state.field(Ae),t=s.state.facet(ce);if(!s.selectionSet&&!s.docChanged&&s.startState.field(Ae)==e)return;let i=s.transactions.some(r=>{let o=mu(r,t);return o&8||(r.selection||r.docChanged)&&!(o&3)});for(let r=0;rDb&&Date.now()-o.time>Rb){for(let l of o.context.abortListeners)try{l()}catch(a){Pe(this.view.state,a)}o.context.abortListeners=null,this.running.splice(r--,1)}else o.updates.push(...s.transactions)}this.debounceUpdate>-1&&clearTimeout(this.debounceUpdate),s.transactions.some(r=>r.effects.some(o=>o.is(On)))&&(this.pendingStart=!0);let n=this.pendingStart?50:t.activateOnTypingDelay;if(this.debounceUpdate=e.active.some(r=>r.isPending&&!this.running.some(o=>o.active.source==r.source))?setTimeout(()=>this.startUpdate(),n):-1,this.composing!=0)for(let r of s.transactions)r.isUserEvent("input.type")?this.composing=2:this.composing==2&&r.selection&&(this.composing=3)}startUpdate(){this.debounceUpdate=-1,this.pendingStart=!1;let{state:s}=this.view,e=s.field(Ae);for(let t of e.active)t.isPending&&!this.running.some(i=>i.active.source==t.source)&&this.startQuery(t);this.running.length&&e.open&&e.open.disabled&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(ce).updateSyncTime))}startQuery(s){let{state:e}=this.view,t=_t(e),i=new uu(e,t,s.explicit,this.view),n=new Tb(s,i);this.running.push(n),Promise.resolve(s.source(i)).then(r=>{n.context.aborted||(n.done=r||null,this.scheduleAccept())},r=>{this.view.dispatch({effects:ns.of(null)}),Pe(this.view.state,r)})}scheduleAccept(){this.running.every(s=>s.done!==void 0)?this.accept():this.debounceAccept<0&&(this.debounceAccept=setTimeout(()=>this.accept(),this.view.state.facet(ce).updateSyncTime))}accept(){var s;this.debounceAccept>-1&&clearTimeout(this.debounceAccept),this.debounceAccept=-1;let e=[],t=this.view.state.facet(ce),i=this.view.state.field(Ae);for(let n=0;nl.source==r.active.source);if(o&&o.isPending)if(r.done==null){let l=new Ve(r.active.source,0);for(let a of r.updates)l=l.update(a,t);l.isPending||e.push(l)}else this.startQuery(o)}(e.length||i.open&&i.open.disabled)&&this.view.dispatch({effects:cl.of(e)})}},{eventHandlers:{blur(s){let e=this.view.state.field(Ae,!1);if(e&&e.tooltip&&this.view.state.facet(ce).closeOnBlur){let t=e.open&&Xc(this.view,e.open.tooltip);(!t||!t.dom.contains(s.relatedTarget))&&setTimeout(()=>this.view.dispatch({effects:ns.of(null)}),10)}},compositionstart(){this.composing=1},compositionend(){this.composing==3&&setTimeout(()=>this.view.dispatch({effects:On.of(!1)}),20),this.composing=0}}}),Eb=typeof navigator=="object"&&/Win/.test(navigator.platform),Lb=ei.highest(L.domEventHandlers({keydown(s,e){let t=e.state.field(Ae,!1);if(!t||!t.open||t.open.disabled||t.open.selected<0||s.key.length>1||s.ctrlKey&&!(Eb&&s.altKey)||s.metaKey)return!1;let i=t.open.options[t.open.selected],n=t.active.find(o=>o.source==i.source),r=i.completion.commitCharacters||n.result.commitCharacters;return r&&r.indexOf(s.key)>-1&&fl(e,i),!1}})),Nb=L.baseTheme({".cm-tooltip.cm-tooltip-autocomplete":{"& > ul":{fontFamily:"monospace",whiteSpace:"nowrap",overflow:"hidden auto",maxWidth_fallback:"700px",maxWidth:"min(700px, 95vw)",minWidth:"250px",maxHeight:"10em",height:"100%",listStyle:"none",margin:0,padding:0,"& > li, & > completion-section":{padding:"1px 3px",lineHeight:1.2},"& > li":{overflowX:"hidden",textOverflow:"ellipsis",cursor:"pointer"},"& > completion-section":{display:"list-item",borderBottom:"1px solid silver",paddingLeft:"0.5em",opacity:.7}}},"&light .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#17c",color:"white"},"&light .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#777"},"&dark .cm-tooltip-autocomplete ul li[aria-selected]":{background:"#347",color:"white"},"&dark .cm-tooltip-autocomplete-disabled ul li[aria-selected]":{background:"#444"},".cm-completionListIncompleteTop:before, .cm-completionListIncompleteBottom:after":{content:'"···"',opacity:.5,display:"block",textAlign:"center",cursor:"pointer"},".cm-tooltip.cm-completionInfo":{position:"absolute",padding:"3px 9px",width:"max-content",maxWidth:"400px",boxSizing:"border-box",whiteSpace:"pre-line"},".cm-completionInfo.cm-completionInfo-left":{right:"100%"},".cm-completionInfo.cm-completionInfo-right":{left:"100%"},".cm-completionInfo.cm-completionInfo-left-narrow":{right:"30px"},".cm-completionInfo.cm-completionInfo-right-narrow":{left:"30px"},"&light .cm-snippetField":{backgroundColor:"#00000022"},"&dark .cm-snippetField":{backgroundColor:"#ffffff22"},".cm-snippetFieldPosition":{verticalAlign:"text-top",width:0,height:"1.15em",display:"inline-block",margin:"0 -0.7px -.7em",borderLeft:"1.4px dotted #888"},".cm-completionMatchedText":{textDecoration:"underline"},".cm-completionDetail":{marginLeft:"0.5em",fontStyle:"italic"},".cm-completionIcon":{fontSize:"90%",width:".8em",display:"inline-block",textAlign:"center",paddingRight:".6em",opacity:"0.6",boxSizing:"content-box"},".cm-completionIcon-function, .cm-completionIcon-method":{"&:after":{content:"'ƒ'"}},".cm-completionIcon-class":{"&:after":{content:"'○'"}},".cm-completionIcon-interface":{"&:after":{content:"'◌'"}},".cm-completionIcon-variable":{"&:after":{content:"'𝑥'"}},".cm-completionIcon-constant":{"&:after":{content:"'𝐶'"}},".cm-completionIcon-type":{"&:after":{content:"'𝑡'"}},".cm-completionIcon-enum":{"&:after":{content:"'∪'"}},".cm-completionIcon-property":{"&:after":{content:"'□'"}},".cm-completionIcon-keyword":{"&:after":{content:"'🔑︎'"}},".cm-completionIcon-namespace":{"&:after":{content:"'▢'"}},".cm-completionIcon-text":{"&:after":{content:"'abc'",fontSize:"50%",verticalAlign:"middle"}}}),rs={brackets:["(","[","{","'",'"'],before:")]}:;>",stringPrefixes:[]},qt=$.define({map(s,e){let t=e.mapPos(s,-1,Se.TrackAfter);return t??void 0}}),ul=new class extends Mt{};ul.startSide=1;ul.endSide=-1;const gu=ye.define({create(){return X.empty},update(s,e){if(s=s.map(e.changes),e.selection){let t=e.state.doc.lineAt(e.selection.main.head);s=s.update({filter:i=>i>=t.from&&i<=t.to})}for(let t of e.effects)t.is(qt)&&(s=s.update({add:[ul.range(t.value,t.value+1)]}));return s}});function Ib(){return[Fb,gu]}const Sr="()[]{}<>«»»«[]{}";function xu(s){for(let e=0;e{if((Wb?s.composing:s.compositionStarted)||s.state.readOnly)return!1;let n=s.state.selection.main;if(i.length>2||i.length==2&&it(Ce(i,0))==1||e!=n.from||t!=n.to)return!1;let r=zb(s.state,i);return r?(s.dispatch(r),!0):!1}),Vb=({state:s,dispatch:e})=>{if(s.readOnly)return!1;let i=bu(s,s.selection.main.head).brackets||rs.brackets,n=null,r=s.changeByRange(o=>{if(o.empty){let l=Qb(s.doc,o.head);for(let a of i)if(a==l&&qn(s.doc,o.head)==xu(Ce(a,0)))return{changes:{from:o.head-a.length,to:o.head+a.length},range:v.cursor(o.head-a.length)}}return{range:n=o}});return n||e(s.update(r,{scrollIntoView:!0,userEvent:"delete.backward"})),!n},Hb=[{key:"Backspace",run:Vb}];function zb(s,e){let t=bu(s,s.selection.main.head),i=t.brackets||rs.brackets;for(let n of i){let r=xu(Ce(n,0));if(e==n)return r==n?qb(s,n,i.indexOf(n+n+n)>-1,t):$b(s,n,r,t.before||rs.before);if(e==r&&yu(s,s.selection.main.from))return jb(s,n,r)}return null}function yu(s,e){let t=!1;return s.field(gu).between(0,s.doc.length,i=>{i==e&&(t=!0)}),t}function qn(s,e){let t=s.sliceString(e,e+2);return t.slice(0,it(Ce(t,0)))}function Qb(s,e){let t=s.sliceString(e-2,e);return it(Ce(t,0))==t.length?t:t.slice(1)}function $b(s,e,t,i){let n=null,r=s.changeByRange(o=>{if(!o.empty)return{changes:[{insert:e,from:o.from},{insert:t,from:o.to}],effects:qt.of(o.to+e.length),range:v.range(o.anchor+e.length,o.head+e.length)};let l=qn(s.doc,o.head);return!l||/\s/.test(l)||i.indexOf(l)>-1?{changes:{insert:e+t,from:o.head},effects:qt.of(o.head+e.length),range:v.cursor(o.head+e.length)}:{range:n=o}});return n?null:s.update(r,{scrollIntoView:!0,userEvent:"input.type"})}function jb(s,e,t){let i=null,n=s.changeByRange(r=>r.empty&&qn(s.doc,r.head)==t?{changes:{from:r.head,to:r.head+t.length,insert:t},range:v.cursor(r.head+t.length)}:i={range:r});return i?null:s.update(n,{scrollIntoView:!0,userEvent:"input.type"})}function qb(s,e,t,i){let n=i.stringPrefixes||rs.stringPrefixes,r=null,o=s.changeByRange(l=>{if(!l.empty)return{changes:[{insert:e,from:l.from},{insert:e,from:l.to}],effects:qt.of(l.to+e.length),range:v.range(l.anchor+e.length,l.head+e.length)};let a=l.head,h=qn(s.doc,a),c;if(h==e){if(ih(s,a))return{changes:{insert:e+e,from:a},effects:qt.of(a+e.length),range:v.cursor(a+e.length)};if(yu(s,a)){let u=t&&s.sliceDoc(a,a+e.length*3)==e+e+e?e+e+e:e;return{changes:{from:a,to:a+u.length,insert:u},range:v.cursor(a+u.length)}}}else{if(t&&s.sliceDoc(a-2*e.length,a)==e+e&&(c=sh(s,a-2*e.length,n))>-1&&ih(s,c))return{changes:{insert:e+e+e+e,from:a},effects:qt.of(a+e.length),range:v.cursor(a+e.length)};if(s.charCategorizer(a)(h)!=ee.Word&&sh(s,a,n)>-1&&!Xb(s,a,e,n))return{changes:{insert:e+e,from:a},effects:qt.of(a+e.length),range:v.cursor(a+e.length)}}return{range:r=l}});return r?null:s.update(o,{scrollIntoView:!0,userEvent:"input.type"})}function ih(s,e){let t=be(s).resolveInner(e+1);return t.parent&&t.from==e}function Xb(s,e,t,i){let n=be(s).resolveInner(e,-1),r=i.reduce((o,l)=>Math.max(o,l.length),0);for(let o=0;o<5;o++){let l=s.sliceDoc(n.from,Math.min(n.to,n.from+t.length+r)),a=l.indexOf(t);if(!a||a>-1&&i.indexOf(l.slice(0,a))>-1){let c=n.firstChild;for(;c&&c.from==n.from&&c.to-c.from>t.length+a;){if(s.sliceDoc(c.to-t.length,c.to)==t)return!1;c=c.firstChild}return!0}let h=n.to==e&&n.parent;if(!h)break;n=h}return!1}function sh(s,e,t){let i=s.charCategorizer(e);if(i(s.sliceDoc(e-1,e))!=ee.Word)return e;for(let n of t){let r=e-n.length;if(s.sliceDoc(r,e)==n&&i(s.sliceDoc(r-1,r))!=ee.Word)return r}return-1}function Ub(s={}){return[Lb,Ae,ce.of(s),Bb,Yb,Nb]}const ku=[{key:"Ctrl-Space",run:vr},{mac:"Alt-`",run:vr},{mac:"Alt-i",run:vr},{key:"Escape",run:Pb},{key:"ArrowDown",run:zs(!0)},{key:"ArrowUp",run:zs(!1)},{key:"PageDown",run:zs(!0,"page")},{key:"PageUp",run:zs(!1,"page")},{key:"Enter",run:Mb}],Yb=ei.highest(In.computeN([ce],s=>s.facet(ce).defaultKeymap?[ku]:[]));class nh{constructor(e,t,i){this.from=e,this.to=t,this.diagnostic=i}}class zt{constructor(e,t,i){this.diagnostics=e,this.panel=t,this.selected=i}static init(e,t,i){let n=i.facet(os).markerFilter;n&&(e=n(e,i));let r=e.slice().sort((d,p)=>d.from-p.from||d.to-p.to),o=new mt,l=[],a=0,h=i.doc.iter(),c=0,f=i.doc.length;for(let d=0;;){let p=d==r.length?null:r[d];if(!p&&!l.length)break;let m,g;if(l.length)m=a,g=l.reduce((w,T)=>Math.min(w,T.to),p&&p.from>m?p.from:1e8);else{if(m=p.from,m>f)break;g=p.to,l.push(p),d++}for(;dw.from||w.to==m))l.push(w),d++,g=Math.min(w.to,g);else{g=Math.min(w.from,g);break}}g=Math.min(g,f);let x=!1;if(l.some(w=>w.from==m&&(w.to==g||g==f))&&(x=m==g,!x&&g-m<10)){let w=m-(c+h.value.length);w>0&&(h.next(w),c=m);for(let T=m;;){if(T>=g){x=!0;break}if(!h.lineBreak&&c+h.value.length>T)break;T=c+h.value.length,c+=h.value.length,h.next()}}let k=l1(l);if(x)o.add(m,m,z.widget({widget:new s1(k),diagnostics:l.slice()}));else{let w=l.reduce((T,S)=>S.markClass?T+" "+S.markClass:T,"");o.add(m,g,z.mark({class:"cm-lintRange cm-lintRange-"+k+w,diagnostics:l.slice(),inclusiveEnd:l.some(T=>T.to>g)}))}if(a=g,a==f)break;for(let w=0;w{if(!(e&&o.diagnostics.indexOf(e)<0))if(!i)i=new nh(n,r,e||o.diagnostics[0]);else{if(o.diagnostics.indexOf(i.diagnostic)<0)return!1;i=new nh(i.from,r,i.diagnostic)}}),i}function _b(s,e){let t=e.pos,i=e.end||t,n=s.state.facet(os).hideOn(s,t,i);if(n!=null)return n;let r=s.startState.doc.lineAt(e.pos);return!!(s.effects.some(o=>o.is(wu))||s.changes.touchesRange(r.from,Math.max(r.to,i)))}function Kb(s,e){return s.field(Ie,!1)?e:e.concat($.appendConfig.of(a1))}const wu=$.define(),dl=$.define(),vu=$.define(),Ie=ye.define({create(){return new zt(z.none,null,null)},update(s,e){if(e.docChanged&&s.diagnostics.size){let t=s.diagnostics.map(e.changes),i=null,n=s.panel;if(s.selected){let r=e.changes.mapPos(s.selected.from,1);i=Et(t,s.selected.diagnostic,r)||Et(t,null,r)}!t.size&&n&&e.state.facet(os).autoPanel&&(n=null),s=new zt(t,n,i)}for(let t of e.effects)if(t.is(wu)){let i=e.state.facet(os).autoPanel?t.value.length?ls.open:null:s.panel;s=zt.init(t.value,i,e.state)}else t.is(dl)?s=new zt(s.diagnostics,t.value?ls.open:null,s.selected):t.is(vu)&&(s=new zt(s.diagnostics,s.panel,t.value));return s},provide:s=>[Zi.from(s,e=>e.panel),L.decorations.from(s,e=>e.diagnostics)]}),Gb=z.mark({class:"cm-lintRange cm-lintRange-active"});function Jb(s,e,t){let{diagnostics:i}=s.state.field(Ie),n,r=-1,o=-1;i.between(e-(t<0?1:0),e+(t>0?1:0),(a,h,{spec:c})=>{if(e>=a&&e<=h&&(a==h||(e>a||t>0)&&(eOu(s,t,!1)))}const e1=s=>{let e=s.state.field(Ie,!1);(!e||!e.panel)&&s.dispatch({effects:Kb(s.state,[dl.of(!0)])});let t=_o(s,ls.open);return t&&t.dom.querySelector(".cm-panel-lint ul").focus(),!0},rh=s=>{let e=s.state.field(Ie,!1);return!e||!e.panel?!1:(s.dispatch({effects:dl.of(!1)}),!0)},t1=s=>{let e=s.state.field(Ie,!1);if(!e)return!1;let t=s.state.selection.main,i=Et(e.diagnostics,null,t.to+1);return!i&&(i=Et(e.diagnostics,null,0),!i||i.from==t.from&&i.to==t.to)?!1:(s.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0}),Jm(s,i.from,1,{tooltip:Cu,until:n=>n.docChanged||n.newSelection.main.headi.to}),!0)},i1=[{key:"Mod-Shift-m",run:e1,preventDefault:!0},{key:"F8",run:t1}],os=I.define({combine(s){return{sources:s.map(e=>e.source).filter(e=>e!=null),...ht(s.map(e=>e.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:oh,tooltipFilter:oh,needsRefresh:(e,t)=>e?t?i=>e(i)||t(i):e:t,hideOn:(e,t)=>e?t?(i,n,r)=>e(i,n,r)||t(i,n,r):e:t,autoPanel:(e,t)=>e||t})}}});function oh(s,e){return s?e?(t,i)=>e(s(t,i),i):s:e}function Su(s){let e=[];if(s)e:for(let{name:t}of s){for(let i=0;ir.toLowerCase()==n.toLowerCase())){e.push(n);continue e}}e.push("")}return e}function Ou(s,e,t){var i;let n=t?Su(e.actions):[];return _("li",{class:"cm-diagnostic cm-diagnostic-"+e.severity},_("span",{class:"cm-diagnosticText"},e.renderMessage?e.renderMessage(s):e.message),(i=e.actions)===null||i===void 0?void 0:i.map((r,o)=>{let l=!1,a=d=>{if(d.preventDefault(),l)return;l=!0;let p=Et(s.state.field(Ie).diagnostics,e);p&&r.apply(s,p.from,p.to)},{name:h}=r,c=n[o]?h.indexOf(n[o]):-1,f=c<0?h:[h.slice(0,c),_("u",h.slice(c,c+1)),h.slice(c+1)],u=r.markClass?" "+r.markClass:"";return _("button",{type:"button",class:"cm-diagnosticAction"+u,onclick:a,onmousedown:a,"aria-label":` Action: ${h}${c<0?"":` (access key "${n[o]})"`}.`},f)}),e.source&&_("div",{class:"cm-diagnosticSource"},e.source))}class s1 extends ct{constructor(e){super(),this.sev=e}eq(e){return e.sev==this.sev}toDOM(){return _("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class lh{constructor(e,t){this.diagnostic=t,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=Ou(e,t,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class ls{constructor(e){this.view=e,this.items=[];let t=n=>{if(!(n.ctrlKey||n.altKey||n.metaKey)){if(n.keyCode==27)rh(this.view),this.view.focus();else if(n.keyCode==38||n.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(n.keyCode==40||n.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(n.keyCode==36)this.moveSelection(0);else if(n.keyCode==35)this.moveSelection(this.items.length-1);else if(n.keyCode==13)this.view.focus();else if(n.keyCode>=65&&n.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:r}=this.items[this.selectedIndex],o=Su(r.actions);for(let l=0;l{for(let r=0;rrh(this.view)},"×")),this.update()}get selectedIndex(){let e=this.view.state.field(Ie).selected;if(!e)return-1;for(let t=0;t{for(let c of h.diagnostics){if(o.has(c))continue;o.add(c);let f=-1,u;for(let d=i;di&&(this.items.splice(i,f-i),n=!0)),t&&u.diagnostic==t.diagnostic?u.dom.hasAttribute("aria-selected")||(u.dom.setAttribute("aria-selected","true"),r=u):u.dom.hasAttribute("aria-selected")&&u.dom.removeAttribute("aria-selected"),i++}});i({sel:r.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:a})=>{let h=a.height/this.list.offsetHeight;l.topa.bottom&&(this.list.scrollTop+=(l.bottom-a.bottom)/h)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),n&&this.sync()}sync(){let e=this.list.firstChild;function t(){let i=e;e=i.nextSibling,i.remove()}for(let i of this.items)if(i.dom.parentNode==this.list){for(;e!=i.dom;)t();e=i.dom.nextSibling}else this.list.insertBefore(i.dom,e);for(;e;)t()}moveSelection(e){if(this.selectedIndex<0)return;let t=this.view.state.field(Ie),i=Et(t.diagnostics,this.items[e].diagnostic);i&&this.view.dispatch({selection:{anchor:i.from,head:i.to},scrollIntoView:!0,effects:vu.of(i)})}static open(e){return new ls(e)}}function n1(s,e='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,${encodeURIComponent(s)}')`}function Qs(s){return n1(``,'width="6" height="3"')}const r1=L.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:Qs("#f11")},".cm-lintRange-warning":{backgroundImage:Qs("orange")},".cm-lintRange-info":{backgroundImage:Qs("#999")},".cm-lintRange-hint":{backgroundImage:Qs("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}},"&dark .cm-lintRange-active":{backgroundColor:"#86714a80"},"&dark .cm-panel.cm-panel-lint ul":{"& [aria-selected]":{backgroundColor:"#2e343e"}}});function o1(s){return s=="error"?4:s=="warning"?3:s=="info"?2:1}function l1(s){let e="hint",t=1;for(let i of s){let n=o1(i.severity);n>t&&(t=n,e=i.severity)}return e}const Cu=Gm(Jb,{hideOn:_b}),a1=[Ie,L.decorations.compute([Ie],s=>{let{selected:e,panel:t}=s.field(Ie);return!e||!t||e.from==e.to?z.none:z.set([Gb.range(e.from,e.to)])}),Cu,r1];var ah=function(e){e===void 0&&(e={});var t=e,i=t.crosshairCursor,n=i===void 0?!1:i,r=[];e.closeBracketsKeymap!==!1&&(r=r.concat(Hb)),e.defaultKeymap!==!1&&(r=r.concat(Bx)),e.searchKeymap!==!1&&(r=r.concat(rb)),e.historyKeymap!==!1&&(r=r.concat(V0)),e.foldKeymap!==!1&&(r=r.concat(Zg)),e.completionKeymap!==!1&&(r=r.concat(ku)),e.lintKeymap!==!1&&(r=r.concat(i1));var o=[];return e.lineNumbers!==!1&&o.push(fg()),e.highlightActiveLineGutter!==!1&&o.push(pg()),e.highlightSpecialChars!==!1&&o.push(Am()),e.history!==!1&&o.push(D0()),e.foldGutter!==!1&&o.push(s0()),e.drawSelection!==!1&&o.push(mm()),e.dropCursor!==!1&&o.push(km()),e.allowMultipleSelections!==!1&&o.push(U.allowMultipleSelections.of(!0)),e.indentOnInput!==!1&&o.push($g()),e.syntaxHighlighting!==!1&&o.push(kf(l0,{fallback:!0})),e.bracketMatching!==!1&&o.push(p0()),e.closeBrackets!==!1&&o.push(Ib()),e.autocompletion!==!1&&o.push(Ub()),e.rectangularSelection!==!1&&o.push(Hm()),n!==!1&&o.push($m()),e.highlightActiveLine!==!1&&o.push(Bm()),e.highlightSelectionMatches!==!1&&o.push(Fx()),e.tabSize&&typeof e.tabSize=="number"&&o.push(Fn.of(" ".repeat(e.tabSize))),o.concat([In.of(r.flat())]).filter(Boolean)};const h1="#e5c07b",hh="#e06c75",c1="#56b6c2",f1="#ffffff",Gs="#abb2bf",Oo="#7d8799",u1="#61afef",d1="#98c379",ch="#d19a66",p1="#c678dd",m1="#21252b",fh="#2c313a",uh="#282c34",Or="#353a42",g1="#3E4451",dh="#528bff",x1=L.theme({"&":{color:Gs,backgroundColor:uh},".cm-content":{caretColor:dh},".cm-cursor, .cm-dropCursor":{borderLeftColor:dh},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:g1},".cm-panels":{backgroundColor:m1,color:Gs},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:uh,color:Oo,border:"none"},".cm-activeLineGutter":{backgroundColor:fh},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Or},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Or,borderBottomColor:Or},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:fh,color:Gs}}},{dark:!0}),b1=ds.define([{tag:b.keyword,color:p1},{tag:[b.name,b.deleted,b.character,b.propertyName,b.macroName],color:hh},{tag:[b.function(b.variableName),b.labelName],color:u1},{tag:[b.color,b.constant(b.name),b.standard(b.name)],color:ch},{tag:[b.definition(b.name),b.separator],color:Gs},{tag:[b.typeName,b.className,b.number,b.changed,b.annotation,b.modifier,b.self,b.namespace],color:h1},{tag:[b.operator,b.operatorKeyword,b.url,b.escape,b.regexp,b.link,b.special(b.string)],color:c1},{tag:[b.meta,b.comment],color:Oo},{tag:b.strong,fontWeight:"bold"},{tag:b.emphasis,fontStyle:"italic"},{tag:b.strikethrough,textDecoration:"line-through"},{tag:b.link,color:Oo,textDecoration:"underline"},{tag:b.heading,fontWeight:"bold",color:hh},{tag:[b.atom,b.bool,b.special(b.variableName)],color:ch},{tag:[b.processingInstruction,b.string,b.inserted],color:d1},{tag:b.invalid,color:f1}]),Co=[x1,kf(b1)];var y1=L.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),k1=function(e){e===void 0&&(e={});var t=e,i=t.indentWithTab,n=i===void 0?!0:i,r=t.editable,o=r===void 0?!0:r,l=t.readOnly,a=l===void 0?!1:l,h=t.theme,c=h===void 0?"light":h,f=t.placeholder,u=f===void 0?"":f,d=t.basicSetup,p=d===void 0?!0:d,m=[];switch(n&&m.unshift(In.of([Ex])),p&&(typeof p=="boolean"?m.unshift(ah()):m.unshift(ah(p))),u&&m.unshift(Im(u)),c){case"light":m.push(y1);break;case"dark":m.push(Co);break;case"none":break;default:m.push(c);break}return o===!1&&m.push(L.editable.of(!1)),a&&m.push(U.readOnly.of(!0)),[...m]},w1=s=>({line:s.state.doc.lineAt(s.state.selection.main.from),lineCount:s.state.doc.lines,lineBreak:s.state.lineBreak,length:s.state.doc.length,readOnly:s.state.readOnly,tabSize:s.state.tabSize,selection:s.state.selection,selectionAsSingle:s.state.selection.asSingle().main,ranges:s.state.selection.ranges,selectionCode:s.state.sliceDoc(s.state.selection.main.from,s.state.selection.main.to),selections:s.state.selection.ranges.map(e=>s.state.sliceDoc(e.from,e.to)),selectedText:s.state.selection.ranges.some(e=>!e.empty)});class v1{constructor(e,t){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=t,this.timeoutMS=t,this.callbacks.push(e)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var e=this.callbacks.slice();this.callbacks.length=0,e.forEach(t=>{try{t()}catch(i){console.error("TimeoutLatch callback error:",i)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}}class ph{constructor(){this.interval=null,this.latches=new Set}add(e){this.latches.add(e),this.start()}remove(e){this.latches.delete(e),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(e=>{e.tick(),e.isDone&&this.remove(e)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}}var Cr=null,S1=()=>typeof window>"u"?new ph:(Cr||(Cr=new ph),Cr),mh=at.define(),O1=200,C1=[];function A1(s){var e=s.value,t=s.selection,i=s.onChange,n=s.onStatistics,r=s.onCreateEditor,o=s.onUpdate,l=s.extensions,a=l===void 0?C1:l,h=s.autoFocus,c=s.theme,f=c===void 0?"light":c,u=s.height,d=u===void 0?null:u,p=s.minHeight,m=p===void 0?null:p,g=s.maxHeight,x=g===void 0?null:g,k=s.width,w=k===void 0?null:k,T=s.minWidth,S=T===void 0?null:T,A=s.maxWidth,O=A===void 0?null:A,V=s.placeholder,N=V===void 0?"":V,P=s.editable,D=P===void 0?!0:P,M=s.readOnly,F=M===void 0?!1:M,R=s.indentWithTab,C=R===void 0?!0:R,B=s.basicSetup,j=B===void 0?!0:B,oe=s.root,Q=s.initialState,ue=H.useState(),de=ue[0],we=ue[1],Be=H.useState(),K=Be[0],Qe=Be[1],Nt=H.useState(),ti=Nt[0],Un=Nt[1],_e=H.useState(()=>({current:null}))[0],gs=H.useState(()=>({current:null}))[0],Eu=L.theme({"&":{height:d,minHeight:m,maxHeight:x,width:w,minWidth:S,maxWidth:O},"& .cm-scroller":{height:"100% !important"}}),Lu=L.updateListener.of(Ke=>{if(Ke.docChanged&&typeof i=="function"&&!Ke.transactions.some(Yn=>Yn.annotation(mh))){_e.current?_e.current.reset():(_e.current=new v1(()=>{if(gs.current){var Yn=gs.current;gs.current=null,Yn()}_e.current=null},O1),S1().add(_e.current));var It=Ke.state.doc,Wt=It.toString();i(Wt,Ke)}n&&n(w1(Ke))}),Nu=k1({theme:f,editable:D,readOnly:F,placeholder:N,indentWithTab:C,basicSetup:j}),Pi=[Lu,Eu,...Nu];return o&&typeof o=="function"&&Pi.push(L.updateListener.of(o)),Pi=Pi.concat(a),H.useLayoutEffect(()=>{if(de&&!ti){var Ke={doc:e,selection:t,extensions:Pi},It=Q?U.fromJSON(Q.json,Ke,Q.fields):U.create(Ke);if(Un(It),!K){var Wt=new L({state:It,parent:de,root:oe});Qe(Wt),r&&r(Wt,It)}}return()=>{K&&(Un(void 0),Qe(void 0))}},[de,ti]),H.useEffect(()=>{s.container&&we(s.container)},[s.container]),H.useEffect(()=>()=>{K&&(K.destroy(),Qe(void 0)),_e.current&&(_e.current.cancel(),_e.current=null)},[K]),H.useEffect(()=>{h&&K&&K.focus()},[h,K]),H.useEffect(()=>{K&&K.dispatch({effects:$.reconfigure.of(Pi)})},[f,a,d,m,x,w,S,O,N,D,F,C,j,i,o]),H.useEffect(()=>{if(e!==void 0){var Ke=K?K.state.doc.toString():"";if(K&&e!==Ke){var It=_e.current&&!_e.current.isDone,Wt=()=>{K&&e!==K.state.doc.toString()&&K.dispatch({changes:{from:0,to:K.state.doc.toString().length,insert:e||""},annotations:[mh.of(!0)]})};It?gs.current=Wt:Wt()}}},[e,K]),{state:ti,setState:Un,view:K,setView:Qe,container:de,setContainer:we}}var M1=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],Ao=H.forwardRef((s,e)=>{var t=s.className,i=s.value,n=i===void 0?"":i,r=s.selection,o=s.extensions,l=o===void 0?[]:o,a=s.onChange,h=s.onStatistics,c=s.onCreateEditor,f=s.onUpdate,u=s.autoFocus,d=s.theme,p=d===void 0?"light":d,m=s.height,g=s.minHeight,x=s.maxHeight,k=s.width,w=s.minWidth,T=s.maxWidth,S=s.basicSetup,A=s.placeholder,O=s.indentWithTab,V=s.editable,N=s.readOnly,P=s.root,D=s.initialState,M=id(s,M1),F=H.useRef(null),R=A1({root:P,value:n,autoFocus:u,theme:p,height:m,minHeight:g,maxHeight:x,width:k,minWidth:w,maxWidth:T,basicSetup:S,placeholder:A,indentWithTab:O,editable:V,readOnly:N,selection:r,onChange:a,onStatistics:h,onCreateEditor:c,onUpdate:f,extensions:l,initialState:D}),C=R.state,B=R.view,j=R.container,oe=R.setContainer;H.useImperativeHandle(e,()=>({editor:F.current,state:C,view:B}),[F,j,C,B]);var Q=H.useCallback(de=>{F.current=de,oe(de)},[oe]);if(typeof n!="string")throw new Error("value must be typeof string but got "+typeof n);var ue=typeof p=="string"?"cm-theme-"+p:"cm-theme";return y.jsx("div",Tr({ref:Q,className:""+ue+(t?" "+t:"")},M))});Ao.displayName="CodeMirror";var gh={};class An{constructor(e,t,i,n,r,o,l,a,h,c=0,f){this.p=e,this.stack=t,this.state=i,this.reducePos=n,this.pos=r,this.score=o,this.buffer=l,this.bufferBase=a,this.curContext=h,this.lookAhead=c,this.parent=f}toString(){return`[${this.stack.filter((e,t)=>t%3==0).concat(this.state)}]@${this.pos}${this.score?"!"+this.score:""}`}static start(e,t,i=0){let n=e.parser.context;return new An(e,[],t,i,i,0,[],0,n?new xh(n,n.start):null,0,null)}get context(){return this.curContext?this.curContext.context:null}pushState(e,t){this.stack.push(this.state,t,this.bufferBase+this.buffer.length),this.state=e}reduce(e){var t;let i=e>>19,n=e&65535,{parser:r}=this.p,o=this.reducePos=2e3&&!(!((t=this.p.parser.nodeSet.types[n])===null||t===void 0)&&t.isAnonymous)&&(h==this.p.lastBigReductionStart?(this.p.bigReductionCount++,this.p.lastBigReductionSize=c):this.p.lastBigReductionSizea;)this.stack.pop();this.reduceContext(n,h)}storeNode(e,t,i,n=4,r=!1){if(e==0&&(!this.stack.length||this.stack[this.stack.length-1]0&&this.buffer[o-4]==0&&this.buffer[o-1]>-1){if(t==i)return;if(this.buffer[o-2]>=t){this.buffer[o-2]=i;return}}}if(!r||this.pos==i)this.buffer.push(e,t,i,n);else{let o=this.buffer.length;if(o>0&&(this.buffer[o-4]!=0||this.buffer[o-1]<0)){let l=!1;for(let a=o;a>0&&this.buffer[a-2]>i;a-=4)if(this.buffer[a-1]>=0){l=!0;break}if(l)for(;o>0&&this.buffer[o-2]>i;)this.buffer[o]=this.buffer[o-4],this.buffer[o+1]=this.buffer[o-3],this.buffer[o+2]=this.buffer[o-2],this.buffer[o+3]=this.buffer[o-1],o-=4,n>4&&(n-=4)}this.buffer[o]=e,this.buffer[o+1]=t,this.buffer[o+2]=i,this.buffer[o+3]=n}}shift(e,t,i,n){if(e&131072)this.pushState(e&65535,this.pos);else if((e&262144)==0){let r=e,{parser:o}=this.p;this.pos=n;let l=o.stateFlag(r,1);!l&&(n>i||t<=o.maxNode)&&(this.reducePos=n),this.pushState(r,l?i:Math.min(i,this.reducePos)),this.shiftContext(t,i),t<=o.maxNode&&this.buffer.push(t,i,n,4)}else this.pos=n,this.shiftContext(t,i),t<=this.p.parser.maxNode&&this.buffer.push(t,i,n,4)}apply(e,t,i,n){e&65536?this.reduce(e):this.shift(e,t,i,n)}useNode(e,t){let i=this.p.reused.length-1;(i<0||this.p.reused[i]!=e)&&(this.p.reused.push(e),i++);let n=this.pos;this.reducePos=this.pos=n+e.length,this.pushState(t,n),this.buffer.push(i,n,this.reducePos,-1),this.curContext&&this.updateContext(this.curContext.tracker.reuse(this.curContext.context,e,this,this.p.stream.reset(this.pos-e.length)))}split(){let e=this,t=e.buffer.length;for(t&&e.buffer[t-4]==0&&(t-=4);t>0&&e.buffer[t-2]>e.reducePos;)t-=4;let i=e.buffer.slice(t),n=e.bufferBase+t;for(;e&&n==e.bufferBase;)e=e.parent;return new An(this.p,this.stack.slice(),this.state,this.reducePos,this.pos,this.score,i,n,this.curContext,this.lookAhead,e)}recoverByDelete(e,t){let i=e<=this.p.parser.maxNode;i&&this.storeNode(e,this.pos,t,4),this.storeNode(0,this.pos,t,i?8:4),this.pos=this.reducePos=t,this.score-=190}canShift(e){for(let t=new P1(this);;){let i=this.p.parser.stateSlot(t.state,4)||this.p.parser.hasAction(t.state,e);if(i==0)return!1;if((i&65536)==0)return!0;t.reduce(i)}}recoverByInsert(e){if(this.stack.length>=300)return[];let t=this.p.parser.nextStates(this.state);if(t.length>8||this.stack.length>=120){let n=[];for(let r=0,o;ra&1&&l==o)||n.push(t[r],o)}t=n}let i=[];for(let n=0;n>19,n=t&65535,r=this.stack.length-i*3;if(r<0||e.getGoto(this.stack[r],n,!1)<0){let o=this.findForcedReduction();if(o==null)return!1;t=o}this.storeNode(0,this.pos,this.pos,4,!0),this.score-=100}return this.reducePos=this.pos,this.reduce(t),!0}findForcedReduction(){let{parser:e}=this.p,t=[],i=(n,r)=>{if(!t.includes(n))return t.push(n),e.allActions(n,o=>{if(!(o&393216))if(o&65536){let l=(o>>19)-r;if(l>1){let a=o&65535,h=this.stack.length-l*3;if(h>=0&&e.getGoto(this.stack[h],a,!1)>=0)return l<<19|65536|a}}else{let l=i(o,r+1);if(l!=null)return l}})};return i(this.state,0)}forceAll(){for(;!this.p.parser.stateFlag(this.state,2);)if(!this.forceReduce()){this.storeNode(0,this.pos,this.pos,4,!0);break}return this}get deadEnd(){if(this.stack.length!=3)return!1;let{parser:e}=this.p;return e.data[e.stateSlot(this.state,1)]==65535&&!e.stateSlot(this.state,4)}restart(){this.storeNode(0,this.pos,this.pos,4,!0),this.state=this.stack[0],this.stack.length=0}sameState(e){if(this.state!=e.state||this.stack.length!=e.stack.length)return!1;for(let t=0;t0&&this.emitLookAhead()}}class xh{constructor(e,t){this.tracker=e,this.context=t,this.hash=e.strict?e.hash(t):0}}class P1{constructor(e){this.start=e,this.state=e.state,this.stack=e.stack,this.base=this.stack.length}reduce(e){let t=e&65535,i=e>>19;i==0?(this.stack==this.start.stack&&(this.stack=this.stack.slice()),this.stack.push(this.state,0,0),this.base+=3):this.base-=(i-1)*3;let n=this.start.p.parser.getGoto(this.stack[this.base-3],t,!0);this.state=n}}class Mn{constructor(e,t,i){this.stack=e,this.pos=t,this.index=i,this.buffer=e.buffer,this.index==0&&this.maybeNext()}static create(e,t=e.bufferBase+e.buffer.length){return new Mn(e,t,t-e.bufferBase)}maybeNext(){let e=this.stack.parent;e!=null&&(this.index=this.stack.bufferBase-e.bufferBase,this.stack=e,this.buffer=e.buffer)}get id(){return this.buffer[this.index-4]}get start(){return this.buffer[this.index-3]}get end(){return this.buffer[this.index-2]}get size(){return this.buffer[this.index-1]}next(){this.index-=4,this.pos-=4,this.index==0&&this.maybeNext()}fork(){return new Mn(this.stack,this.pos,this.index)}}function $s(s,e=Uint16Array){if(typeof s!="string")return s;let t=null;for(let i=0,n=0;i=92&&o--,o>=34&&o--;let a=o-32;if(a>=46&&(a-=46,l=!0),r+=a,l)break;r*=46}t?t[n++]=r:t=new e(r)}return t}class Js{constructor(){this.start=-1,this.value=-1,this.end=-1,this.extended=-1,this.lookAhead=0,this.mask=0,this.context=0}}const bh=new Js;class T1{constructor(e,t){this.input=e,this.ranges=t,this.chunk="",this.chunkOff=0,this.chunk2="",this.chunk2Pos=0,this.next=-1,this.token=bh,this.rangeIndex=0,this.pos=this.chunkPos=t[0].from,this.range=t[0],this.end=t[t.length-1].to,this.readNext()}resolveOffset(e,t){let i=this.range,n=this.rangeIndex,r=this.pos+e;for(;ri.to:r>=i.to;){if(n==this.ranges.length-1)return null;let o=this.ranges[++n];r+=o.from-i.to,i=o}return r}clipPos(e){if(e>=this.range.from&&ee)return Math.max(e,t.from);return this.end}peek(e){let t=this.chunkOff+e,i,n;if(t>=0&&t=this.chunk2Pos&&il.to&&(this.chunk2=this.chunk2.slice(0,l.to-i)),n=this.chunk2.charCodeAt(0)}}return i>=this.token.lookAhead&&(this.token.lookAhead=i+1),n}acceptToken(e,t=0){let i=t?this.resolveOffset(t,-1):this.pos;if(i==null||i=this.chunk2Pos&&this.posthis.range.to?e.slice(0,this.range.to-this.pos):e,this.chunkPos=this.pos,this.chunkOff=0}}readNext(){return this.chunkOff>=this.chunk.length&&(this.getChunk(),this.chunkOff==this.chunk.length)?this.next=-1:this.next=this.chunk.charCodeAt(this.chunkOff)}advance(e=1){for(this.chunkOff+=e;this.pos+e>=this.range.to;){if(this.rangeIndex==this.ranges.length-1)return this.setDone();e-=this.range.to-this.pos,this.range=this.ranges[++this.rangeIndex],this.pos=this.range.from}return this.pos+=e,this.pos>=this.token.lookAhead&&(this.token.lookAhead=this.pos+1),this.readNext()}setDone(){return this.pos=this.chunkPos=this.end,this.range=this.ranges[this.rangeIndex=this.ranges.length-1],this.chunk="",this.next=-1}reset(e,t){if(t?(this.token=t,t.start=e,t.lookAhead=e+1,t.value=t.extended=-1):this.token=bh,this.pos!=e){if(this.pos=e,e==this.end)return this.setDone(),this;for(;e=this.range.to;)this.range=this.ranges[++this.rangeIndex];e>=this.chunkPos&&e=this.chunkPos&&t<=this.chunkPos+this.chunk.length)return this.chunk.slice(e-this.chunkPos,t-this.chunkPos);if(e>=this.chunk2Pos&&t<=this.chunk2Pos+this.chunk2.length)return this.chunk2.slice(e-this.chunk2Pos,t-this.chunk2Pos);if(e>=this.range.from&&t<=this.range.to)return this.input.read(e,t);let i="";for(let n of this.ranges){if(n.from>=t)break;n.to>e&&(i+=this.input.read(Math.max(n.from,e),Math.min(n.to,t)))}return i}}class gi{constructor(e,t){this.data=e,this.id=t}token(e,t){let{parser:i}=t.p;D1(this.data,e,t,this.id,i.data,i.tokenPrecTable)}}gi.prototype.contextual=gi.prototype.fallback=gi.prototype.extend=!1;gi.prototype.fallback=gi.prototype.extend=!1;class Xn{constructor(e,t={}){this.token=e,this.contextual=!!t.contextual,this.fallback=!!t.fallback,this.extend=!!t.extend}}function D1(s,e,t,i,n,r){let o=0,l=1<0){let p=s[d];if(a.allows(p)&&(e.token.value==-1||e.token.value==p||R1(p,e.token.value,n,r))){e.acceptToken(p);break}}let c=e.next,f=0,u=s[o+2];if(e.next<0&&u>f&&s[h+u*3-3]==65535){o=s[h+u*3-1];continue e}for(;f>1,p=h+d+(d<<1),m=s[p],g=s[p+1]||65536;if(c=g)f=d+1;else{o=s[p+2],e.advance();continue e}}break}}function yh(s,e,t){for(let i=e,n;(n=s[i])!=65535;i++)if(n==t)return i-e;return-1}function R1(s,e,t,i){let n=yh(t,i,e);return n<0||yh(t,i,s)e)&&!i.type.isError)return t<0?Math.max(0,Math.min(i.to-1,e-25)):Math.min(s.length,Math.max(i.from+1,e+25));if(t<0?i.prevSibling():i.nextSibling())break;if(!i.parent())return t<0?0:s.length}}class B1{constructor(e,t){this.fragments=e,this.nodeSet=t,this.i=0,this.fragment=null,this.safeFrom=-1,this.safeTo=-1,this.trees=[],this.start=[],this.index=[],this.nextFragment()}nextFragment(){let e=this.fragment=this.i==this.fragments.length?null:this.fragments[this.i++];if(e){for(this.safeFrom=e.openStart?kh(e.tree,e.from+e.offset,1)-e.offset:e.from,this.safeTo=e.openEnd?kh(e.tree,e.to+e.offset,-1)-e.offset:e.to;this.trees.length;)this.trees.pop(),this.start.pop(),this.index.pop();this.trees.push(e.tree),this.start.push(-e.offset),this.index.push(0),this.nextStart=this.safeFrom}else this.nextStart=1e9}nodeAt(e){if(ee)return this.nextStart=o,null;if(r instanceof re){if(o==e){if(o=Math.max(this.safeFrom,e)&&(this.trees.push(r),this.start.push(o),this.index.push(0))}else this.index[t]++,this.nextStart=o+r.length}}}class E1{constructor(e,t){this.stream=t,this.tokens=[],this.mainToken=null,this.actions=[],this.tokens=e.tokenizers.map(i=>new Js)}getActions(e){let t=0,i=null,{parser:n}=e.p,{tokenizers:r}=n,o=n.stateSlot(e.state,3),l=e.curContext?e.curContext.hash:0,a=0;for(let h=0;hf.end+25&&(a=Math.max(f.lookAhead,a)),f.value!=0)){let u=t;if(f.extended>-1&&(t=this.addActions(e,f.extended,f.end,t)),t=this.addActions(e,f.value,f.end,t),!c.extend&&(i=f,t>u))break}}for(;this.actions.length>t;)this.actions.pop();return a&&e.setLookAhead(a),!i&&e.pos==this.stream.end&&(i=new Js,i.value=e.p.parser.eofTerm,i.start=i.end=e.pos,t=this.addActions(e,i.value,i.end,t)),this.mainToken=i,this.actions}getMainToken(e){if(this.mainToken)return this.mainToken;let t=new Js,{pos:i,p:n}=e;return t.start=i,t.end=Math.min(i+1,n.stream.end),t.value=i==n.stream.end?n.parser.eofTerm:0,t}updateCachedToken(e,t,i){let n=this.stream.clipPos(i.pos);if(t.token(this.stream.reset(n,e),i),e.value>-1){let{parser:r}=i.p;for(let o=0;o=0&&i.p.parser.dialect.allows(l>>1)){(l&1)==0?e.value=l>>1:e.extended=l>>1;break}}}else e.value=0,e.end=this.stream.clipPos(n+1)}putAction(e,t,i,n){for(let r=0;re.bufferLength*4?new B1(i,e.nodeSet):null}get parsedPos(){return this.minStackPos}advance(){let e=this.stacks,t=this.minStackPos,i=this.stacks=[],n,r;if(this.bigReductionCount>300&&e.length==1){let[o]=e;for(;o.forceReduce()&&o.stack.length&&o.stack[o.stack.length-2]>=this.lastBigReductionStart;);this.bigReductionCount=this.lastBigReductionSize=0}for(let o=0;ot)i.push(l);else{if(this.advanceStack(l,i,e))continue;{n||(n=[],r=[]),n.push(l);let a=this.tokens.getMainToken(l);r.push(a.value,a.end)}}break}}if(!i.length){let o=n&&W1(n);if(o)return Le&&console.log("Finish with "+this.stackID(o)),this.stackToTree(o);if(this.parser.strict)throw Le&&n&&console.log("Stuck with token "+(this.tokens.mainToken?this.parser.getName(this.tokens.mainToken.value):"none")),new SyntaxError("No parse at "+t);this.recovering||(this.recovering=5)}if(this.recovering&&n){let o=this.stoppedAt!=null&&n[0].pos>this.stoppedAt?n[0]:this.runRecovery(n,r,i);if(o)return Le&&console.log("Force-finish "+this.stackID(o)),this.stackToTree(o.forceAll())}if(this.recovering){let o=this.recovering==1?1:this.recovering*3;if(i.length>o)for(i.sort((l,a)=>a.score-l.score);i.length>o;)i.pop();i.some(l=>l.reducePos>t)&&this.recovering--}else if(i.length>1){e:for(let o=0;o500&&h.buffer.length>500)if((l.score-h.score||l.buffer.length-h.buffer.length)>0)i.splice(a--,1);else{i.splice(o--,1);continue e}}}i.length>12&&(i.sort((o,l)=>l.score-o.score),i.splice(12,i.length-12))}this.minStackPos=i[0].pos;for(let o=1;o ":"";if(this.stoppedAt!=null&&n>this.stoppedAt)return e.forceReduce()?e:null;if(this.fragments){let h=e.curContext&&e.curContext.tracker.strict,c=h?e.curContext.hash:0;for(let f=this.fragments.nodeAt(n);f;){let u=this.parser.nodeSet.types[f.type.id]==f.type?r.getGoto(e.state,f.type.id):-1;if(u>-1&&f.length&&(!h||(f.prop(q.contextHash)||0)==c))return e.useNode(f,u),Le&&console.log(o+this.stackID(e)+` (via reuse of ${r.getName(f.type.id)})`),!0;if(!(f instanceof re)||f.children.length==0||f.positions[0]>0)break;let d=f.children[0];if(d instanceof re&&f.positions[0]==0)f=d;else break}}let l=r.stateSlot(e.state,4);if(l>0)return e.reduce(l),Le&&console.log(o+this.stackID(e)+` (via always-reduce ${r.getName(l&65535)})`),!0;if(e.stack.length>=8400)for(;e.stack.length>6e3&&e.forceReduce(););let a=this.tokens.getActions(e);for(let h=0;hn?t.push(p):i.push(p)}return!1}advanceFully(e,t){let i=e.pos;for(;;){if(!this.advanceStack(e,null,null))return!1;if(e.pos>i)return wh(e,t),!0}}runRecovery(e,t,i){let n=null,r=!1;for(let o=0;o ":"";if(l.deadEnd&&(r||(r=!0,l.restart(),Le&&console.log(c+this.stackID(l)+" (restarted)"),this.advanceFully(l,i))))continue;let f=l.split(),u=c;for(let d=0;d<10&&f.forceReduce()&&(Le&&console.log(u+this.stackID(f)+" (via force-reduce)"),!this.advanceFully(f,i));d++)Le&&(u=this.stackID(f)+" -> ");for(let d of l.recoverByInsert(a))Le&&console.log(c+this.stackID(d)+" (via recover-insert)"),this.advanceFully(d,i);this.stream.end>l.pos?(h==l.pos&&(h++,a=0),l.recoverByDelete(a,h),Le&&console.log(c+this.stackID(l)+` (via recover-delete ${this.parser.getName(a)})`),wh(l,i)):(!n||n.scores;class I1{constructor(e){this.start=e.start,this.shift=e.shift||Mr,this.reduce=e.reduce||Mr,this.reuse=e.reuse||Mr,this.hash=e.hash||(()=>0),this.strict=e.strict!==!1}}class Pn extends sf{constructor(e){if(super(),this.wrappers=[],e.version!=14)throw new RangeError(`Parser version (${e.version}) doesn't match runtime version (14)`);let t=e.nodeNames.split(" ");this.minRepeatTerm=t.length;for(let l=0;le.topRules[l][1]),n=[];for(let l=0;l=0)r(c,a,l[h++]);else{let f=l[h+-c];for(let u=-c;u>0;u--)r(l[h++],a,f);h++}}}this.nodeSet=new Ko(t.map((l,a)=>Re.define({name:a>=this.minRepeatTerm?void 0:l,id:a,props:n[a],top:i.indexOf(a)>-1,error:a==0,skipped:e.skippedNodes&&e.skippedNodes.indexOf(a)>-1}))),e.propSources&&(this.nodeSet=this.nodeSet.extend(...e.propSources)),this.strict=!1,this.bufferLength=Jc;let o=$s(e.tokenData);this.context=e.context,this.specializerSpecs=e.specialized||[],this.specialized=new Uint16Array(this.specializerSpecs.length);for(let l=0;ltypeof l=="number"?new gi(o,l):l),this.topRules=e.topRules,this.dialects=e.dialects||{},this.dynamicPrecedences=e.dynamicPrecedences||null,this.tokenPrecTable=e.tokenPrec,this.termNames=e.termNames||null,this.maxNode=this.nodeSet.types.length-1,this.dialect=this.parseDialect(),this.top=this.topRules[Object.keys(this.topRules)[0]]}createParse(e,t,i){let n=new L1(this,e,t,i);for(let r of this.wrappers)n=r(n,e,t,i);return n}getGoto(e,t,i=!1){let n=this.goto;if(t>=n[0])return-1;for(let r=n[t+1];;){let o=n[r++],l=o&1,a=n[r++];if(l&&i)return a;for(let h=r+(o>>1);r0}validAction(e,t){return!!this.allActions(e,i=>i==t?!0:null)}allActions(e,t){let i=this.stateSlot(e,4),n=i?t(i):void 0;for(let r=this.stateSlot(e,1);n==null;r+=3){if(this.data[r]==65535)if(this.data[r+1]==1)r=ut(this.data,r+2);else break;n=t(ut(this.data,r+1))}return n}nextStates(e){let t=[];for(let i=this.stateSlot(e,1);;i+=3){if(this.data[i]==65535)if(this.data[i+1]==1)i=ut(this.data,i+2);else break;if((this.data[i+2]&1)==0){let n=this.data[i+1];t.some((r,o)=>o&1&&r==n)||t.push(this.data[i],n)}}return t}configure(e){let t=Object.assign(Object.create(Pn.prototype),this);if(e.props&&(t.nodeSet=this.nodeSet.extend(...e.props)),e.top){let i=this.topRules[e.top];if(!i)throw new RangeError(`Invalid top rule name ${e.top}`);t.top=i}return e.tokenizers&&(t.tokenizers=this.tokenizers.map(i=>{let n=e.tokenizers.find(r=>r.from==i);return n?n.to:i})),e.specializers&&(t.specializers=this.specializers.slice(),t.specializerSpecs=this.specializerSpecs.map((i,n)=>{let r=e.specializers.find(l=>l.from==i.external);if(!r)return i;let o=Object.assign(Object.assign({},i),{external:r.to});return t.specializers[n]=vh(o),o})),e.contextTracker&&(t.context=e.contextTracker),e.dialect&&(t.dialect=this.parseDialect(e.dialect)),e.strict!=null&&(t.strict=e.strict),e.wrap&&(t.wrappers=t.wrappers.concat(e.wrap)),e.bufferLength!=null&&(t.bufferLength=e.bufferLength),t}hasWrappers(){return this.wrappers.length>0}getName(e){return this.termNames?this.termNames[e]:String(e<=this.maxNode&&this.nodeSet.types[e].name||e)}get eofTerm(){return this.maxNode+1}get topNode(){return this.nodeSet.types[this.top[1]]}dynamicPrecedence(e){let t=this.dynamicPrecedences;return t==null?0:t[e]||0}parseDialect(e){let t=Object.keys(this.dialects),i=t.map(()=>!1);if(e)for(let r of e.split(" ")){let o=t.indexOf(r);o>=0&&(i[o]=!0)}let n=null;for(let r=0;ri)&&t.p.parser.stateFlag(t.state,2)&&(!e||e.scores.external(t,i)<<1|e}return s.get}const ri=63,Sh=64,F1=1,V1=2,Au=3,H1=4,Mu=5,z1=6,Q1=7,Pu=65,$1=66,j1=8,q1=9,X1=10,U1=11,Y1=12,Tu=13,_1=19,K1=20,G1=29,J1=33,Z1=34,ey=47,ty=0,pl=1,Mo=2,as=3,Po=4;class Qt{constructor(e,t,i){this.parent=e,this.depth=t,this.type=i,this.hash=(e?e.hash+e.hash<<8:0)+t+(t<<4)+i}}Qt.top=new Qt(null,-1,ty);function qi(s,e){for(let t=0,i=e-s.pos-1;;i--,t++){let n=s.peek(i);if(bt(n)||n==-1)return t}}function To(s){return s==32||s==9}function bt(s){return s==10||s==13}function Du(s){return To(s)||bt(s)}function Xt(s){return s<0||Du(s)}const iy=new I1({start:Qt.top,reduce(s,e){return s.type==as&&(e==K1||e==Z1)?s.parent:s},shift(s,e,t,i){if(e==Au)return new Qt(s,qi(i,i.pos),pl);if(e==Pu||e==Mu)return new Qt(s,qi(i,i.pos),Mo);if(e==ri)return s.parent;if(e==_1||e==J1)return new Qt(s,0,as);if(e==Tu&&s.type==Po)return s.parent;if(e==ey){let n=/[1-9]/.exec(i.read(i.pos,t.pos));if(n)return new Qt(s,s.depth+ +n[0],Po)}return s},hash(s){return s.hash}});function Oi(s,e,t=0){return s.peek(t)==e&&s.peek(t+1)==e&&s.peek(t+2)==e&&Xt(s.peek(t+3))}const sy=new Xn((s,e)=>{if(s.next==-1&&e.canShift(Sh))return s.acceptToken(Sh);let t=s.peek(-1);if((bt(t)||t<0)&&e.context.type!=as){if(Oi(s,45))if(e.canShift(ri))s.acceptToken(ri);else return s.acceptToken(F1,3);if(Oi(s,46))if(e.canShift(ri))s.acceptToken(ri);else return s.acceptToken(V1,3);let i=0;for(;s.next==32;)i++,s.advance();(i{if(e.context.type==as){s.next==63&&(s.advance(),Xt(s.next)&&s.acceptToken(Q1));return}if(s.next==45)s.advance(),Xt(s.next)&&s.acceptToken(e.context.type==pl&&e.context.depth==qi(s,s.pos-1)?H1:Au);else if(s.next==63)s.advance(),Xt(s.next)&&s.acceptToken(e.context.type==Mo&&e.context.depth==qi(s,s.pos-1)?z1:Mu);else{let t=s.pos;for(;;)if(To(s.next)){if(s.pos==t)return;s.advance()}else if(s.next==33)Ru(s);else if(s.next==38)Do(s);else if(s.next==42){Do(s);break}else if(s.next==39||s.next==34){if(ml(s,!0))break;return}else if(s.next==91||s.next==123){if(!oy(s))return;break}else{Bu(s,!0,!1,0);break}for(;To(s.next);)s.advance();if(s.next==58){if(s.pos==t&&e.canShift(G1))return;let i=s.peek(1);Xt(i)&&s.acceptTokenTo(e.context.type==Mo&&e.context.depth==qi(s,t)?$1:Pu,t)}}},{contextual:!0});function ry(s){return s>32&&s<127&&s!=34&&s!=37&&s!=44&&s!=60&&s!=62&&s!=92&&s!=94&&s!=96&&s!=123&&s!=124&&s!=125}function Oh(s){return s>=48&&s<=57||s>=97&&s<=102||s>=65&&s<=70}function Ch(s,e){return s.next==37?(s.advance(),Oh(s.next)&&s.advance(),Oh(s.next)&&s.advance(),!0):ry(s.next)||e&&s.next==44?(s.advance(),!0):!1}function Ru(s){if(s.advance(),s.next==60){for(s.advance();;)if(!Ch(s,!0)){s.next==62&&s.advance();break}}else for(;Ch(s,!1););}function Do(s){for(s.advance();!Xt(s.next)&&Tn(s.next)!="f";)s.advance()}function ml(s,e){let t=s.next,i=!1,n=s.pos;for(s.advance();;){let r=s.next;if(r<0)break;if(s.advance(),r==t)if(r==39)if(s.next==39)s.advance();else break;else break;else if(r==92&&t==34)s.next>=0&&s.advance();else if(bt(r)){if(e)return!1;i=!0}else if(e&&s.pos>=n+1024)return!1}return!i}function oy(s){for(let e=[],t=s.pos+1024;;)if(s.next==91||s.next==123)e.push(s.next),s.advance();else if(s.next==39||s.next==34){if(!ml(s,!0))return!1}else if(s.next==93||s.next==125){if(e[e.length-1]!=s.next-2)return!1;if(e.pop(),s.advance(),!e.length)return!0}else{if(s.next<0||s.pos>t||bt(s.next))return!1;s.advance()}}const ly="iiisiiissisfissssssssssssisssiiissssssssssssssssssssssssssfsfssissssssssssssssssssssssssssfif";function Tn(s){return s<33?"u":s>125?"s":ly[s-33]}function Pr(s,e){let t=Tn(s);return t!="u"&&!(e&&t=="f")}function Bu(s,e,t,i){if(Tn(s.next)=="s"||(s.next==63||s.next==58||s.next==45)&&Pr(s.peek(1),t))s.advance();else return!1;let n=s.pos;for(;;){let r=s.next,o=0,l=i+1;for(;Du(r);){if(bt(r)){if(e)return!1;l=0}else l++;r=s.peek(++o)}if(!(r>=0&&(r==58?Pr(s.peek(o+1),t):r==35?s.peek(o-1)!=32:Pr(r,t)))||!t&&l<=i||l==0&&!t&&(Oi(s,45,o)||Oi(s,46,o)))break;if(e&&Tn(r)=="f")return!1;for(let h=o;h>=0;h--)s.advance();if(e&&s.pos>n+1024)return!1}return!0}const ay=new Xn((s,e)=>{if(s.next==33)Ru(s),s.acceptToken(Y1);else if(s.next==38||s.next==42){let t=s.next==38?X1:U1;Do(s),s.acceptToken(t)}else s.next==39||s.next==34?(ml(s,!1),s.acceptToken(q1)):Bu(s,!1,e.context.type==as,e.context.depth)&&s.acceptToken(j1)}),hy=new Xn((s,e)=>{let t=e.context.type==Po?e.context.depth:-1,i=s.pos;e:for(;;){let n=0,r=s.next;for(;r==32;)r=s.peek(++n);if(!n&&(Oi(s,45,n)||Oi(s,46,n))||!bt(r)&&(t<0&&(t=Math.max(e.context.depth+1,n)),nYAN>Y",stateData:";S~O!fOS!gOS^OS~OP_OQbORSOTUOWROXROYYOZZO[XOcPOqQO!PVO!V[O!cTO~O`cO~P]OVkOWROXROYeOZfO[dOcPOmhOqQO~OboO~P!bOVtOWROXROYeOZfO[dOcPOmrOqQO~OpwO~P#WORSOTUOWROXROYYOZZO[XOcPOqQO!PVO!cTO~OSvP!avP!bvP~P#|OWROXROYeOZfO[dOcPOqQO~OmzO~P%OOm!OOUzP!azP!bzP!dzP~P#|O^!SO!b!QO!f!TO!g!RO~ORSOTUOWROXROcPOqQO!PVO!cTO~OY!UOP!QXQ!QX!V!QX!`!QXS!QX!a!QX!b!QXU!QXm!QX!d!QX~P&aO[!WOP!SXQ!SX!V!SX!`!SXS!SX!a!SX!b!SXU!SXm!SX!d!SX~P&aO^!ZO!W![O!b!YO!f!]O!g!YO~OP!_O!V[OQaX!`aX~OPaXQaX!VaX!`aX~P#|OP!bOQ!cO!V[O~OP_O!V[O~P#|OWROXROY!fOcPOqQObfXmfXofXpfX~OWROXRO[!hOcPOqQObhXmhXohXphX~ObeXmlXoeX~ObkXokX~P%OOm!kO~Om!lObnPonP~P%OOb!pOo!oO~Ob!pO~P!bOm!sOosXpsX~OosXpsX~P%OOm!uOotPptP~P%OOo!xOp!yO~Op!yO~P#WOS!|O!a#OO!b#OO~OUyX!ayX!byX!dyX~P#|Om#QO~OU#SO!a#UO!b#UO!d#RO~Om#WOUzX!azX!bzX!dzX~O]#XO~O!b#XO!g#YO~O^#ZO!b#XO!g#YO~OP!RXQ!RX!V!RX!`!RXS!RX!a!RX!b!RXU!RXm!RX!d!RX~P&aOP!TXQ!TX!V!TX!`!TXS!TX!a!TX!b!TXU!TXm!TX!d!TX~P&aO!b#^O!g#^O~O^#_O!b#^O!f#`O!g#^O~O^#_O!W#aO!b#^O!g#^O~OPaaQaa!Vaa!`aa~P#|OP#cO!V[OQ!XX!`!XX~OP!XXQ!XX!V!XX!`!XX~P#|OP_O!V[OQ!_X!`!_X~P#|OWROXROcPOqQObgXmgXogXpgX~OWROXROcPOqQObiXmiXoiXpiX~Obkaoka~P%OObnXonX~P%OOm#kO~Ob#lOo!oO~Oosapsa~P%OOotXptX~P%OOm#pO~Oo!xOp#qO~OSwP!awP!bwP~P#|OS!|O!a#vO!b#vO~OUya!aya!bya!dya~P#|Om#xO~P%OOm#{OU}P!a}P!b}P!d}P~P#|OU#SO!a$OO!b$OO!d#RO~O]$QO~O!b$QO!g$RO~O!b$SO!g$SO~O^$TO!b$SO!g$SO~O^$TO!b$SO!f$UO!g$SO~OP!XaQ!Xa!V!Xa!`!Xa~P#|Obnaona~P%OOotapta~P%OOo!xO~OU|X!a|X!b|X!d|X~P#|Om$ZO~Om$]OU}X!a}X!b}X!d}X~O]$^O~O!b$_O!g$_O~O^$`O!b$_O!g$_O~OU|a!a|a!b|a!d|a~P#|O!b$cO!g$cO~O",goto:",]!mPPPPPPPPPPPPPPPPP!nPP!v#v#|$`#|$c$f$j$nP%VPPP!v%Y%^%a%{&O%a&R&U&X&_&b%aP&e&{&e'O'RPP']'a'g'm's'y(XPPPPPPPP(_)e*X+c,VUaObcR#e!c!{ROPQSTUXY_bcdehknrtvz!O!U!W!_!b!c!f!h!k!l!s!u!|#Q#R#S#W#c#k#p#x#{$Z$]QmPR!qnqfPQThknrtv!k!l!s!u#R#k#pR!gdR!ieTlPnTjPnSiPnSqQvQ{TQ!mkQ!trQ!vtR#y#RR!nkTsQvR!wt!RWOSUXY_bcz!O!U!W!_!b!c!|#Q#S#W#c#x#{$Z$]RySR#t!|R|TR|UQ!PUR#|#SR#z#RR#z#SyZOSU_bcz!O!_!b!c!|#Q#S#W#c#x#{$Z$]R!VXR!XYa]O^abc!a!c!eT!da!eQnPR!rnQvQR!{vQ!}yR#u!}Q#T|R#}#TW^Obc!cS!^^!aT!aa!eQ!eaR#f!eW`Obc!cQxSS}U#SQ!`_Q#PzQ#V!OQ#b!_Q#d!bQ#s!|Q#w#QQ$P#WQ$V#cQ$Y#xQ$[#{Q$a$ZR$b$]xZOSU_bcz!O!_!b!c!|#Q#S#W#c#x#{$Z$]Q!VXQ!XYQ#[!UR#]!W!QWOSUXY_bcz!O!U!W!_!b!c!|#Q#S#W#c#x#{$Z$]pfPQThknrtv!k!l!s!u#R#k#pQ!gdQ!ieQ#g!fR#h!hSgPn^pQTkrtv#RQ!jhQ#i!kQ#j!lQ#n!sQ#o!uQ$W#kR$X#pQuQR!zv",nodeNames:"⚠ DirectiveEnd DocEnd - - ? ? ? Literal QuotedLiteral Anchor Alias Tag BlockLiteralContent Comment Stream BOM Document ] [ FlowSequence Item Tagged Anchored Anchored Tagged FlowMapping Pair Key : Pair , } { FlowMapping Pair Pair BlockSequence Item Item BlockMapping Pair Pair Key Pair Pair BlockLiteral BlockLiteralHeader Tagged Anchored Anchored Tagged Directive DirectiveName DirectiveContent Document",maxTerm:74,context:iy,nodeProps:[["isolate",-3,8,9,14,""],["openedBy",18,"[",32,"{"],["closedBy",19,"]",33,"}"]],propSources:[cy],skippedNodes:[0],repeatNodeCount:6,tokenData:"-Y~RnOX#PXY$QYZ$]Z]#P]^$]^p#Ppq$Qqs#Pst$btu#Puv$yv|#P|}&e}![#P![!]'O!]!`#P!`!a'i!a!}#P!}#O*g#O#P#P#P#Q+Q#Q#o#P#o#p+k#p#q'i#q#r,U#r;'S#P;'S;=`#z<%l?HT#P?HT?HU,o?HUO#PQ#UU!WQOY#PZp#Ppq#hq;'S#P;'S;=`#z<%lO#PQ#kTOY#PZs#Pt;'S#P;'S;=`#z<%lO#PQ#}P;=`<%l#P~$VQ!f~XY$Qpq$Q~$bO!g~~$gS^~OY$bZ;'S$b;'S;=`$s<%lO$b~$vP;=`<%l$bR%OX!WQOX%kXY#PZ]%k]^#P^p%kpq#hq;'S%k;'S;=`&_<%lO%kR%rX!WQ!VPOX%kXY#PZ]%k]^#P^p%kpq#hq;'S%k;'S;=`&_<%lO%kR&bP;=`<%l%kR&lUoP!WQOY#PZp#Ppq#hq;'S#P;'S;=`#z<%lO#PR'VUmP!WQOY#PZp#Ppq#hq;'S#P;'S;=`#z<%lO#PR'p[!PP!WQOY#PZp#Ppq#hq{#P{|(f|}#P}!O(f!O!R#P!R![)p![;'S#P;'S;=`#z<%lO#PR(mW!PP!WQOY#PZp#Ppq#hq!R#P!R![)V![;'S#P;'S;=`#z<%lO#PR)^U!PP!WQOY#PZp#Ppq#hq;'S#P;'S;=`#z<%lO#PR)wY!PP!WQOY#PZp#Ppq#hq{#P{|)V|}#P}!O)V!O;'S#P;'S;=`#z<%lO#PR*nUcP!WQOY#PZp#Ppq#hq;'S#P;'S;=`#z<%lO#PR+XUbP!WQOY#PZp#Ppq#hq;'S#P;'S;=`#z<%lO#PR+rUqP!WQOY#PZp#Ppq#hq;'S#P;'S;=`#z<%lO#PR,]UpP!WQOY#PZp#Ppq#hq;'S#P;'S;=`#z<%lO#PR,vU`P!WQOY#PZp#Ppq#hq;'S#P;'S;=`#z<%lO#P",tokenizers:[sy,ny,ay,hy,0,1],topRules:{Stream:[0,15]},tokenPrec:0}),uy=dn.define({name:"yaml",parser:fy.configure({props:[af.add({Stream:s=>{for(let e=s.node.resolve(s.pos,-1);e&&e.to>=s.pos;e=e.parent){if(e.name=="BlockLiteralContent"&&e.froms.pos)return null}}return null},FlowMapping:Ba({closing:"}"}),FlowSequence:Ba({closing:"]"})}),ff.add({"FlowMapping FlowSequence":qg,"Item Pair BlockLiteral":(s,e)=>({from:e.doc.lineAt(s.from).to,to:s.to})})]}),languageData:{commentTokens:{line:"#"},indentOnInput:/^\s*[\]\}]$/}});function dy(){return new Lg(uy)}function Vy({clusterCode:s,namespace:e,resource:t,name:i,onClose:n,onSaved:r,cleanBeforeEdit:o=!1,autoEdit:l=!1,inline:a=!1,initialYaml:h}){const{toast:c}=Ah(),[f,u]=H.useState(h||""),[d,p]=H.useState(""),[m,g]=H.useState(!h),[x,k]=H.useState(!1),[w,T]=H.useState(l),[S,A]=H.useState(!1),O=o||l,V=async()=>{if(h){u(h),p(O?bs(h):h),g(!1);return}g(!0);try{const B=await wt.getResourceYaml(s,e,t,i);u(B),p(O?bs(B):B)}catch(B){c({title:"获取YAML失败",description:B.message,variant:"destructive"});const j=`# Error: ${B.message}`;u(j),p(j)}finally{g(!1)}},N=()=>{const B=O?bs(f):f;p(B),T(!0),O&&c({title:"已清理只读字段",description:"已剥离 status / managedFields / uid 等"})},[P,D]=H.useState(!1),M=async()=>{k(!0);try{await wt.updateResourceYaml(s,e,t,i,d),c({title:"YAML已应用",description:`${t}/${i} 更新成功`}),T(!1),u(d),r?.()}catch(B){c({title:"保存失败",description:B.message,variant:"destructive"})}finally{k(!1)}},F=async()=>{const B=w?d:f;await navigator.clipboard.writeText(B),A(!0),setTimeout(()=>A(!1),2e3)};H.useEffect(()=>{V()},[]);const R=w?d:O&&!P?bs(f):f,C=H.useMemo(()=>[dy(),L.lineWrapping,...w?[]:[L.editable.of(!1)]],[w]);return a?y.jsxs("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:113:7",className:"space-y-3",children:[y.jsxs("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:114:9",className:"flex items-center justify-between",children:[y.jsxs("p",{"code-path":"src/components/kubernetes/YamlViewer.tsx:115:11",className:"text-xs text-slate-500",children:[y.jsxs("code",{"code-path":"src/components/kubernetes/YamlViewer.tsx:116:13",className:"text-slate-400",children:[t,"/",i]})," · ",e," · ",s]}),y.jsxs("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:118:11",className:"flex items-center gap-2",children:[y.jsxs(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:119:13",variant:"outline",size:"sm",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:F,children:[S?y.jsx(gl,{"code-path":"src/components/kubernetes/YamlViewer.tsx:120:25",className:"h-3 w-3 mr-1 text-emerald-400"}):y.jsx(bl,{"code-path":"src/components/kubernetes/YamlViewer.tsx:120:79",className:"h-3 w-3 mr-1"}),S?"已复制":"复制"]}),O&&!w&&y.jsxs(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:124:15",variant:"outline",size:"sm",className:`h-7 text-xs ${P?"border-slate-700 text-slate-500":"border-emerald-700/50 text-emerald-400"}`,onClick:()=>D(B=>!B),title:"切换 精简/原始 视图",children:[y.jsx(xs,{"code-path":"src/components/kubernetes/YamlViewer.tsx:126:17",className:"h-3 w-3 mr-1"}),P?"原始":"精简"]}),w?y.jsxs(y.Fragment,{children:[y.jsx(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:144:17",variant:"outline",size:"sm",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:()=>{T(!1),V()},children:"取消"}),y.jsxs(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:147:17",size:"sm",className:"h-7 bg-blue-600 hover:bg-blue-700 text-xs",onClick:M,disabled:x,children:[x?y.jsx(St,{"code-path":"src/components/kubernetes/YamlViewer.tsx:148:29",className:"h-3 w-3 animate-spin mr-1"}):y.jsx(yl,{"code-path":"src/components/kubernetes/YamlViewer.tsx:148:81",className:"h-3 w-3 mr-1"}),"保存"]})]}):y.jsxs(y.Fragment,{children:[O&&y.jsxs(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:132:19",variant:"outline",size:"sm",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:N,title:"清理 status / managedFields 等只读字段后编辑",children:[y.jsx(xs,{"code-path":"src/components/kubernetes/YamlViewer.tsx:133:19",className:"h-3 w-3 mr-1 text-amber-400"}),"编辑"]}),!O&&y.jsx(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:137:19",variant:"outline",size:"sm",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:()=>T(!0),children:"编辑"})]})]})]}),y.jsx("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:155:9",className:"border border-slate-700 rounded-lg overflow-hidden",children:m?y.jsx("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:157:13",className:"flex items-center justify-center h-96",children:y.jsx(St,{"code-path":"src/components/kubernetes/YamlViewer.tsx:157:68",className:"h-6 w-6 animate-spin text-slate-500"})}):y.jsx(Ao,{"code-path":"src/components/kubernetes/YamlViewer.tsx:159:13",value:R,height:"600px",theme:Co,extensions:C,onChange:B=>w&&p(B),basicSetup:{lineNumbers:!0,foldGutter:!0,highlightActiveLine:w,highlightActiveLineGutter:w,autocompletion:!0,bracketMatching:!0,closeBrackets:!0,indentOnInput:!0},style:{fontSize:"12px"}})})]}):y.jsx("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:185:5",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/60",onClick:n,children:y.jsxs("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:186:7",className:"bg-slate-900 border border-slate-700 rounded-xl w-[90vw] max-w-4xl max-h-[85vh] flex flex-col shadow-2xl",onClick:B=>B.stopPropagation(),children:[y.jsxs("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:188:9",className:"flex items-center justify-between p-4 border-b border-slate-700",children:[y.jsxs("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:189:11",children:[y.jsxs("h2",{"code-path":"src/components/kubernetes/YamlViewer.tsx:190:13",className:"text-lg font-bold text-slate-100",children:[t,"/",i]}),y.jsxs("p",{"code-path":"src/components/kubernetes/YamlViewer.tsx:191:13",className:"text-xs text-slate-500",children:[e," · ",s]})]}),y.jsxs("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:193:11",className:"flex items-center gap-2",children:[y.jsxs(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:194:13",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300",onClick:F,children:[S?y.jsx(gl,{"code-path":"src/components/kubernetes/YamlViewer.tsx:195:25",className:"h-3 w-3 mr-1 text-emerald-400"}):y.jsx(bl,{"code-path":"src/components/kubernetes/YamlViewer.tsx:195:79",className:"h-3 w-3 mr-1"}),S?"已复制":"复制"]}),O&&!w&&y.jsxs(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:199:15",variant:"outline",size:"sm",className:`h-8 text-xs ${P?"border-slate-700 text-slate-500":"border-emerald-700/50 text-emerald-400"}`,onClick:()=>D(B=>!B),title:"切换 精简/原始 视图",children:[y.jsx(xs,{"code-path":"src/components/kubernetes/YamlViewer.tsx:201:17",className:"h-3 w-3 mr-1"}),P?"原始":"精简"]}),w?y.jsxs(y.Fragment,{children:[y.jsx(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:219:17",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300",onClick:()=>{T(!1),V()},children:"取消"}),y.jsxs(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:222:17",size:"sm",className:"h-8 bg-blue-600 hover:bg-blue-700",onClick:M,disabled:x,children:[x?y.jsx(St,{"code-path":"src/components/kubernetes/YamlViewer.tsx:223:29",className:"h-3 w-3 animate-spin mr-1"}):y.jsx(yl,{"code-path":"src/components/kubernetes/YamlViewer.tsx:223:81",className:"h-3 w-3 mr-1"}),"保存"]})]}):y.jsxs(y.Fragment,{children:[O&&y.jsxs(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:207:19",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300",onClick:N,title:"清理 status / managedFields 等只读字段后编辑",children:[y.jsx(xs,{"code-path":"src/components/kubernetes/YamlViewer.tsx:208:21",className:"h-3 w-3 mr-1 text-amber-400"}),"清理并编辑"]}),!O&&y.jsx(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:212:19",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300",onClick:()=>T(!0),children:"编辑"})]}),y.jsx(le,{"code-path":"src/components/kubernetes/YamlViewer.tsx:228:13",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400",onClick:n,children:y.jsx(Zs,{"code-path":"src/components/kubernetes/YamlViewer.tsx:228:102",className:"h-4 w-4"})})]})]}),y.jsx("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:232:9",className:"flex-1 overflow-auto p-4",children:m?y.jsx("div",{"code-path":"src/components/kubernetes/YamlViewer.tsx:234:13",className:"flex items-center justify-center h-full",children:y.jsx(St,{"code-path":"src/components/kubernetes/YamlViewer.tsx:234:70",className:"h-6 w-6 animate-spin text-slate-500"})}):y.jsx(Ao,{"code-path":"src/components/kubernetes/YamlViewer.tsx:236:13",value:R,height:"600px",theme:Co,extensions:C,onChange:B=>w&&p(B),basicSetup:{lineNumbers:!0,foldGutter:!0,highlightActiveLine:w,highlightActiveLineGutter:w,autocompletion:!0,bracketMatching:!0,closeBrackets:!0,indentOnInput:!0},style:{fontSize:"12px"}})})]})})}const py=[{value:"sh",label:"/bin/sh"},{value:"bash",label:"/bin/bash"}];function Hy({open:s,onOpenChange:e,clusterId:t,namespace:i,podName:n,containers:r=[],initialContainer:o}){const{toast:l}=Ah(),a=H.useRef(null),h=H.useRef(null),c=H.useRef(null),f=H.useRef(null),u=H.useRef(!1),d=H.useRef(!1),[p,m]=H.useState("idle"),[g,x]=H.useState(!1),[k,w]=H.useState(o||r[0]||""),[T,S]=H.useState("sh");H.useEffect(()=>{s||(x(!1),u.current=!1)},[s]),H.useEffect(()=>{s&&!k&&r.length>0&&w(o||r[0])},[s,r,o,k]);const A=H.useCallback(()=>{if(!h.current){console.error("[PodExec:connect] ABORT: termRef.current is null");return}const P=h.current;if(c.current){try{c.current.close()}catch{}c.current=null}m("connecting"),P.clear(),P.writeln(`\x1B[36m[正在连接 ${n}${k?"/"+k:""} shell=${T} ...]\x1B[0m`);const D=wt.buildPodExecWsUrl(t,i,n,k||void 0,T),M=new WebSocket(D);c.current=M,M.onopen=()=>{m("connected"),P.reset();try{const{cols:R,rows:C}=P;M.send(JSON.stringify({status:1,cols:R,rows:C}))}catch(R){console.error("[PodExec:connect] resize error:",R)}const F=()=>{try{P.focus()}catch{}};F(),setTimeout(F,100),setTimeout(F,300)},M.onmessage=F=>{try{const R=JSON.parse(F.data);if(R.status===0&&typeof R.data=="string")P.write(R.data);else if(R.status===2||R.error){const C=R.data||R.message||R.error||"执行错误";if(C.includes("not found")&&T==="bash"){P.writeln(`\r +\x1B[33m⚠ bash 不可用,请切换 /bin/sh 后重连。\x1B[0m`),d.current=!0;return}P.write(C.includes("\x1B")?C:`\r +\x1B[31m${C}\x1B[0m\r +`)}}catch{typeof F.data=="string"&&P.write(F.data)}},M.onclose=F=>{m(R=>R==="error"?R:"closed"),d.current||P.write(`\r +\x1B[33m[连接已关闭]\x1B[0m\r +`)},M.onerror=F=>{console.error("[PodExec:connect] WS error event fired, readyState=",M.readyState,"type=",F.type),m("error"),P.write(`\r +\x1B[31m[连接发生错误]\x1B[0m\r +`)}},[t,i,n,k,T]);H.useEffect(()=>{if(!s)return;if(!t){console.error("[PodExec:initEffect] ABORT: clusterId is falsy:",t);return}if(!n){console.error("[PodExec:initEffect] ABORT: podName is falsy:",n);return}let P=!1,D=0;const M=performance.now(),F=()=>{if(P)return;const R=a.current;if(!R){D++,D<20?requestAnimationFrame(F):console.error("[PodExec:tryInit] FAILED: containerRef still null after 20 retries (",Math.round(performance.now()-M),"ms)");return}const C=new Qu.Terminal({cursorBlink:!0,fontSize:14,fontFamily:'Menlo, Monaco, "Courier New", monospace',allowProposedApi:!0,scrollback:5e3,theme:{background:"#0f172a",foreground:"#e2e8f0",cursor:"#38bdf8",selectionBackground:"#1e40af",black:"#1e293b",red:"#ef4444",green:"#10b981",yellow:"#f59e0b",blue:"#3b82f6",magenta:"#a855f7",cyan:"#06b6d4",white:"#e2e8f0",brightBlack:"#475569",brightRed:"#f87171",brightGreen:"#34d399",brightYellow:"#fbbf24",brightBlue:"#60a5fa",brightMagenta:"#c084fc",brightCyan:"#22d3ee",brightWhite:"#f8fafc"}}),B=new $u.FitAddon;C.loadAddon(B),h.current=C,f.current=B,C.onData(j=>{c.current&&c.current.readyState===WebSocket.OPEN?c.current.send(JSON.stringify({status:0,data:j})):console.warn("[PodExec:term] TX dropped — WS not open, readyState=",c.current?.readyState)}),C.open(R),requestAnimationFrame(()=>{try{B.fit()}catch{}}),u.current=!0,A()};return requestAnimationFrame(F),()=>{P=!0}},[s,t,n]),H.useEffect(()=>{if(!s){try{c.current?.close()}catch{}try{h.current?.dispose()}catch{}h.current=null,c.current=null,f.current=null,u.current=!1,m("idle")}},[s]),H.useEffect(()=>{s&&h.current&&u.current&&A()},[k,T]),H.useEffect(()=>{if(!s)return;const P=a.current;if(!P)return;let D;const M=new ResizeObserver(()=>{clearTimeout(D),D=setTimeout(()=>{if(f.current&&h.current)try{f.current.fit(),h.current.focus();const{cols:F,rows:R}=h.current;c.current?.readyState===WebSocket.OPEN&&c.current.send(JSON.stringify({status:1,cols:F,rows:R}))}catch{}},60)});return M.observe(P),()=>{clearTimeout(D),M.disconnect()}},[s,g]);const O=p==="connected"?"bg-emerald-400":p==="error"?"bg-red-400":p==="closed"?"bg-slate-500":"bg-amber-400",V=p==="connected"?"已连接":p==="connecting"?"连接中":p==="error"?"连接错误":p==="closed"?"已断开":"空闲",N=H.useCallback(()=>{try{h.current?.focus()}catch{}},[]);return y.jsx(Iu,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:279:5",open:s,onOpenChange:e,children:y.jsxs(Wu,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:280:7",showCloseButton:!1,className:xl("bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] p-0 gap-0","!duration-0 !transition-none",g?"!max-w-none !w-screen !h-screen !rounded-none !translate-x-0 !translate-y-0 !left-0 !top-0":""),style:g?{maxWidth:"100vw",width:"100vw",height:"100vh"}:{maxWidth:"960px",width:"92vw"},children:[y.jsxs(Fu,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:289:9",className:"sr-only",children:["exec — ",n]}),y.jsx(Vu,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:290:9",className:"sr-only",children:"进入 Pod 容器执行命令"}),y.jsxs("div",{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:293:9",className:"flex items-center justify-between gap-2 px-4 py-2 border-b border-[var(--dg-border)] flex-wrap",children:[y.jsxs("div",{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:294:11",className:"flex items-center gap-2 text-sm min-w-0",children:[y.jsx("div",{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:295:13",className:xl("w-2 h-2 rounded-full shrink-0",O),title:V}),y.jsx(Hu,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:296:13",className:"h-4 w-4 text-blue-400 shrink-0"}),y.jsxs("span",{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:297:13",className:"text-[var(--dg-text-primary)] font-medium truncate",children:["exec — ",n]}),p==="connecting"&&y.jsx(St,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:298:44",className:"h-3 w-3 animate-spin text-[var(--dg-text-muted)]"}),y.jsx("span",{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:299:13",className:"text-xs text-[var(--dg-text-muted)]",children:V})]}),y.jsxs("div",{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:301:11",className:"flex items-center gap-2",children:[r.length>0&&y.jsxs(kl,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:303:15",value:k,onValueChange:w,children:[y.jsxs(wl,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:304:17",className:"h-8 w-[150px] text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)]",children:[y.jsx(ju,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:305:19",className:"h-3 w-3 mr-1 text-[var(--dg-text-muted)]"}),y.jsx(vl,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:306:19",placeholder:"容器"})]}),y.jsx(Sl,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:308:17",children:r.map(P=>y.jsx(Ol,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:308:55",value:P,children:P},P))})]}),y.jsxs(kl,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:311:13",value:T,onValueChange:S,children:[y.jsx(wl,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:312:15",className:"h-8 w-[110px] text-xs bg-[var(--dg-bg-hover)] border-[var(--dg-border)]",children:y.jsx(vl,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:313:17"})}),y.jsx(Sl,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:315:15",children:py.map(P=>y.jsx(Ol,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:315:47",value:P.value,children:P.label},P.value))})]}),y.jsx(le,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:317:13",variant:"ghost",size:"sm",className:"h-8 px-2 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]",onClick:()=>{A(),l({title:"正在重连…"})},title:"重连",children:y.jsx(qu,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:319:15",className:"h-3.5 w-3.5"})}),y.jsx("button",{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:321:13",onClick:()=>x(!g),className:"p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]",title:g?"退出全屏":"全屏",children:g?y.jsx(Xu,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:322:29",className:"h-4 w-4"}):y.jsx(Uu,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:322:65",className:"h-4 w-4"})}),y.jsx("button",{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:324:13",onClick:()=>e(!1),className:"p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]",title:"关闭",children:y.jsx(Zs,{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:325:15",className:"h-4 w-4"})})]})]}),y.jsx("div",{"code-path":"src/components/kubernetes/PodExecTerminal.tsx:331:9",ref:a,className:"bg-[#0f172a] cursor-text",style:{height:g?"calc(100vh - 49px)":"480px"},onClick:N})]})})}function zy({open:s,onOpenChange:e,clusterCode:t,namespace:i,podName:n,containers:r=[],initialContainer:o}){const[l,a]=H.useState(o||r[0]||""),[h,c]=H.useState("/"),[f,u]=H.useState([]),[d,p]=H.useState(!1),[m,g]=H.useState(""),[x,k]=H.useState(null),[w,T]=H.useState(!1),S=H.useRef(null),A=H.useRef(!1),O=H.useCallback(async C=>{p(!0),g(""),k(null);try{const B=await wt.listPodFiles(t,i,n,C,l||void 0),oe=(B?.entries||B?.files||B?.data?.entries||B?.data?.files||(Array.isArray(B)?B:[])).map(Q=>({name:Q.name??Q.Name??"",isDir:!!(Q.isDir??Q.is_dir??Q.IsDir??Q.dir??Q.directory),size:typeof Q.size=="number"?Q.size:Q.Size?Number(Q.Size):void 0,modTime:Q.modTime??Q.mod_time??Q.ModTime??Q.mtime??Q.modified})).filter(Q=>Q.name&&Q.name!==".");u(oe),c(C)}catch(B){g(B.message||"加载文件列表失败"),u([])}finally{p(!1)}},[t,i,n,l]);H.useEffect(()=>{s?(async()=>{if(A.current){O(h);return}p(!0);try{const B=await wt.execPod(t,i,n,["pwd"],l||void 0),j=(B?.stdout||B?.data?.stdout||"").trim(),oe=j&&j.startsWith("/")?j:"/";A.current=!0,c(oe),O(oe)}catch{A.current=!0,O("/")}})():A.current=!1},[s,l]);const V=C=>{if(C.isDir){const B=h==="/"?`/${C.name}`:`${h}/${C.name}`;O(B)}else N(C.name)},N=async C=>{const B=h==="/"?`/${C}`:`${h}/${C}`;try{const j=await wt.readPodFileText(t,i,n,B,l||void 0);k({file:C,content:j})}catch(j){k({file:C,content:`读取失败: ${j.message}`})}},P=C=>{const B=h==="/"?`/${C}`:`${h}/${C}`,j=wt.buildPodFileDownloadUrl(t,i,n,B,l||void 0);window.open(j,"_blank")},D=async C=>{const B=C.target.files?.[0];if(B){T(!0);try{await wt.uploadPodFile(t,i,n,h,B,l||void 0),O(h)}catch(j){g(`上传失败: ${j.message}`)}finally{T(!1),S.current&&(S.current.value="")}}},M=()=>{if(h==="/")return;const C=h.split("/").filter(Boolean);C.pop(),O(C.length===0?"/":`/${C.join("/")}`)},F=C=>C==null?"-":C<1024?`${C} B`:C<1024*1024?`${(C/1024).toFixed(1)} KB`:`${(C/(1024*1024)).toFixed(1)} MB`,R=h.split("/").filter(Boolean);return s?y.jsx("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:163:5",className:"fixed inset-0 z-50 flex items-center justify-center bg-black/70",onClick:()=>e(!1),children:y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:164:7",className:"bg-slate-900 border border-slate-700 rounded-xl w-[90vw] max-w-5xl h-[80vh] flex flex-col shadow-2xl",onClick:C=>C.stopPropagation(),children:[y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:169:9",className:"flex items-center justify-between p-3 border-b border-slate-700 shrink-0",children:[y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:170:11",className:"flex items-center gap-2",children:[y.jsx(_u,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:171:13",className:"h-4 w-4 text-amber-400"}),y.jsxs("span",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:172:13",className:"text-sm font-semibold text-slate-200",children:["文件浏览器: ",n]}),y.jsx(Yu,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:173:13",variant:"outline",className:"border-slate-700 text-slate-400 text-[10px]",children:i})]}),y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:175:11",className:"flex items-center gap-2",children:[r.length>0&&y.jsx("select",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:177:15",value:l,onChange:C=>{a(C.target.value)},className:"bg-slate-800 border border-slate-700 rounded text-xs text-slate-300 px-2 py-1",children:r.map(C=>y.jsx("option",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:182:40",value:C,children:C},C))}),y.jsx(le,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:185:13",variant:"ghost",size:"icon",className:"h-7 w-7 text-slate-400",onClick:()=>e(!1),children:y.jsx(Zs,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:186:15",className:"h-4 w-4"})})]})]}),y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:192:9",className:"flex items-center justify-between p-2 border-b border-slate-800 shrink-0",children:[y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:193:11",className:"flex items-center gap-1 text-xs text-slate-400",children:[y.jsx(le,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:194:13",variant:"ghost",size:"icon",className:"h-6 w-6 text-slate-500",onClick:M,disabled:h==="/",children:y.jsx(Ku,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:195:15",className:"h-3.5 w-3.5"})}),y.jsx("button",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:197:13",className:"hover:text-slate-200",onClick:()=>O("/"),children:"root"}),R.map((C,B)=>{const j=`/${R.slice(0,B+1).join("/")}`;return y.jsxs("span",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:201:17",className:"flex items-center gap-1",children:[y.jsx(zu,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:202:19",className:"h-3 w-3"}),y.jsx("button",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:203:19",className:"hover:text-slate-200",onClick:()=>O(j),children:C})]},j)})]}),y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:208:11",className:"flex items-center gap-2",children:[y.jsx("input",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:209:13",type:"file",ref:S,className:"hidden",onChange:D}),y.jsxs(le,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:210:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:()=>S.current?.click(),disabled:w,children:[w?y.jsx(St,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:211:28",className:"h-3 w-3 animate-spin mr-1"}):y.jsx(Gu,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:211:80",className:"h-3 w-3 mr-1"}),"上传"]}),y.jsx(le,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:213:13",size:"sm",variant:"outline",className:"h-7 border-slate-700 text-slate-300 text-xs",onClick:()=>O(h),disabled:d,children:d?y.jsx(St,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:214:26",className:"h-3 w-3 animate-spin"}):y.jsx(Ju,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:214:73",className:"h-3 w-3"})})]})]}),y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:220:9",className:"flex-1 overflow-hidden flex",children:[y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:222:11",className:`${x?"w-1/2":"w-full"} overflow-auto p-2 border-r border-slate-800`,children:[m&&y.jsx("p",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:223:23",className:"text-xs text-red-400 p-2",children:m}),d?y.jsx("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:225:15",className:"flex items-center justify-center h-32",children:y.jsx(St,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:225:70",className:"h-5 w-5 animate-spin text-slate-500"})}):f.length===0?y.jsx("p",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:227:15",className:"text-xs text-slate-500 p-4 text-center",children:"空目录"}):y.jsx("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:229:15",className:"space-y-0.5",children:f.sort((C,B)=>C.isDir===B.isDir?C.name.localeCompare(B.name):C.isDir?-1:1).map(C=>y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:231:19",className:"flex items-center gap-2 px-2 py-1.5 rounded hover:bg-slate-800/50 cursor-pointer group",onClick:()=>V(C),children:[C.isDir?y.jsx(Zu,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:237:23",className:"h-4 w-4 text-blue-400 shrink-0"}):y.jsx(ed,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:239:23",className:"h-4 w-4 text-slate-500 shrink-0"}),y.jsx("span",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:241:21",className:`text-xs truncate ${C.isDir?"text-blue-300":"text-slate-300"}`,children:C.name}),!C.isDir&&y.jsx("span",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:245:23",className:"text-[10px] text-slate-600 ml-auto shrink-0",children:F(C.size)}),!C.isDir&&y.jsx(le,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:248:23",variant:"ghost",size:"icon",className:"h-5 w-5 opacity-0 group-hover:opacity-100 text-slate-400 hover:text-emerald-400 shrink-0",onClick:B=>{B.stopPropagation(),P(C.name)},title:"下载",children:y.jsx(td,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:253:25",className:"h-3 w-3"})})]},C.name))})]}),x&&y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:264:13",className:"w-1/2 flex flex-col overflow-hidden",children:[y.jsxs("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:265:15",className:"flex items-center justify-between p-2 border-b border-slate-800 shrink-0",children:[y.jsx("span",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:266:17",className:"text-xs text-slate-300 font-mono",children:x.file}),y.jsx(le,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:267:17",variant:"ghost",size:"icon",className:"h-6 w-6 text-slate-400",onClick:()=>k(null),children:y.jsx(Zs,{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:268:19",className:"h-3.5 w-3.5"})})]}),y.jsx("div",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:271:15",className:"flex-1 overflow-auto p-3",children:y.jsx("pre",{"code-path":"src/components/kubernetes/PodFileBrowser.tsx:272:17",className:"text-xs text-slate-300 font-mono whitespace-pre-wrap break-all bg-slate-950 rounded p-3",children:x.content||"(空文件)"})})]})]})]})}):null}export{Hy as P,Ao as R,ys as S,Vy as Y,zy as a,Iy as b,bs as c,Ny as e,Ly as f,Co as o,Ey as s,dy as y}; diff --git a/backend/static/assets/PodMetricsPage-DjvvN_IG.js b/backend/static/assets/PodMetricsPage-DjvvN_IG.js new file mode 100644 index 0000000..8db2c97 --- /dev/null +++ b/backend/static/assets/PodMetricsPage-DjvvN_IG.js @@ -0,0 +1 @@ +import{i as H,k as U,r as c,j as e,m as N,n as f,A as V,B as W,o as F}from"./index-DfyorCky.js";import{C as i,a as x}from"./card-C55cvSHg.js";import{B as L}from"./badge-xNW8x0G1.js";import{S as v,a as C,b as y,c as S,d as P}from"./select-D5qUzdAs.js";import{T as z,a as D,b as u,c as d,d as G,e as n}from"./table-5sHV4Akp.js";import{k as b}from"./kubernetes-J8O09fK7.js";import{R as K}from"./refresh-cw-DUB_tAG-.js";import{H as q}from"./hard-drive-BbPmnARR.js";import"./index-CWVNW_qu.js";function te(){const{clusterCode:w}=H(),g=U(),[m,M]=c.useState(!1),[p,k]=c.useState([]),[A,T]=c.useState([]),[$,E]=c.useState([]),[l,B]=c.useState("all"),[a,j]=c.useState(w||"");c.useEffect(()=>{b.getClusters().then(s=>{const t=s?.list||[];if(T(t),!a&&t.length>0){const r=t[0].code||String(t[0].id);j(r),g(`/kubernetes/${r}/metrics/pods`,{replace:!0})}}).catch(()=>{})},[]),c.useEffect(()=>{a&&b.getNamespaces(a).then(s=>{E(Array.isArray(s)?s:s?.list||s?.data||[])}).catch(()=>{})},[a]);const h=c.useCallback(async()=>{if(a){M(!0);try{const s=l==="all"?void 0:l,t=await b.getPodMetrics(a,s);k(Array.isArray(t)?t:t?.list||[])}catch{k([])}finally{M(!1)}}},[a,l]);c.useEffect(()=>{h()},[h]);const o=c.useMemo(()=>p.flatMap(s=>(s.containers||[]).map(t=>({pod:s.name,namespace:s.namespace,container:t.name,cpu:t.cpu||"0m",memory:t.memory||"0Mi"}))),[p]),I=c.useMemo(()=>o.reduce((s,t)=>s+(parseInt(t.cpu)||0),0),[o]),R=c.useMemo(()=>{let s=0;return o.forEach(t=>{const r=t.memory;r.endsWith("Mi")?s+=parseInt(r):r.endsWith("Ki")?s+=parseInt(r)/1024:r.endsWith("Gi")&&(s+=parseInt(r)*1024)}),s},[o]);return e.jsxs("div",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:81:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:82:7",className:"flex items-center gap-2 text-sm text-slate-500",children:[e.jsx(N,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:83:9",to:"/kubernetes",className:"hover:text-slate-300",children:"集群"}),a&&e.jsxs(e.Fragment,{children:[e.jsx(f,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:84:29",className:"h-3 w-3"}),e.jsx(N,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:84:65",to:`/kubernetes/${a}`,className:"hover:text-slate-300",children:a})]}),e.jsx(f,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:85:9",className:"h-3 w-3"}),e.jsx("span",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:85:45",className:"text-slate-300",children:"Pod 资源用量"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:88:7",className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs("h2",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:89:9",className:"text-lg font-semibold text-slate-100 flex items-center gap-2",children:[e.jsx(V,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:89:86",className:"h-5 w-5 text-blue-400"}),"Pod 资源用量"]}),e.jsxs("div",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:90:9",className:"flex items-center gap-2",children:[e.jsxs(v,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:91:11",value:a,onValueChange:s=>{j(s),g(`/kubernetes/${s}/metrics/pods`)},children:[e.jsx(C,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:92:13",className:"w-44 h-8 text-xs bg-slate-800 border-slate-700",children:e.jsx(y,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:92:87"})}),e.jsx(S,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:93:13",className:"bg-slate-800 border-slate-700",children:A.map(s=>e.jsx(P,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:94:42",value:s.code||String(s.id),className:"text-xs",children:s.name||s.code},s.id))})]}),e.jsxs(v,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:97:11",value:l,onValueChange:B,children:[e.jsx(C,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:98:13",className:"w-36 h-8 text-xs bg-slate-800 border-slate-700",children:e.jsx(y,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:98:87",placeholder:"所有命名空间"})}),e.jsxs(S,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:99:13",className:"bg-slate-800 border-slate-700",children:[e.jsx(P,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:100:15",value:"all",className:"text-xs",children:"所有命名空间"}),$.map(s=>e.jsx(P,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:101:36",value:s,className:"text-xs",children:s},s))]})]}),e.jsxs(W,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:104:11",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300 text-xs",onClick:h,disabled:m,children:[e.jsx(K,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:105:13",className:`h-3 w-3 mr-1 ${m?"animate-spin":""}`}),"刷新"]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:111:7",className:"grid grid-cols-3 gap-3",children:[e.jsx(i,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:112:9",className:"bg-slate-900 border-slate-800",children:e.jsxs(x,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:112:57",className:"p-3 text-center",children:[e.jsx("p",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:113:11",className:"text-xs text-slate-500",children:"Pod 数"}),e.jsx("p",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:113:58",className:"text-xl font-bold text-slate-200",children:p.length})]})}),e.jsx(i,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:115:9",className:"bg-slate-900 border-slate-800",children:e.jsxs(x,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:115:57",className:"p-3 text-center",children:[e.jsx("p",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:116:11",className:"text-xs text-slate-500",children:"总 CPU"}),e.jsxs("p",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:116:58",className:"text-xl font-bold text-blue-400",children:[I,"m"]})]})}),e.jsx(i,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:118:9",className:"bg-slate-900 border-slate-800",children:e.jsxs(x,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:118:57",className:"p-3 text-center",children:[e.jsx("p",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:119:11",className:"text-xs text-slate-500",children:"总内存"}),e.jsxs("p",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:119:56",className:"text-xl font-bold text-emerald-400",children:[R.toFixed(0),"Mi"]})]})})]}),e.jsx(i,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:123:7",className:"bg-slate-900 border-slate-800",children:e.jsx(x,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:124:9",className:"p-0",children:e.jsxs(z,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:125:11",children:[e.jsx(D,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:126:13",children:e.jsxs(u,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:126:26",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(d,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:127:15",className:"text-slate-400",children:"Pod"}),e.jsx(d,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:128:15",className:"text-slate-400",children:"命名空间"}),e.jsx(d,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:129:15",className:"text-slate-400",children:"容器"}),e.jsxs(d,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:130:15",className:"text-slate-400",children:[e.jsx(F,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:130:53",className:"h-3 w-3 inline mr-1"}),"CPU"]}),e.jsxs(d,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:131:15",className:"text-slate-400",children:[e.jsx(q,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:131:53",className:"h-3 w-3 inline mr-1"}),"Memory"]})]})}),e.jsx(G,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:133:13",children:o.length===0?e.jsx(u,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:135:17",children:e.jsxs(n,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:135:27",colSpan:5,className:"text-center text-slate-500 py-8",children:["暂无数据",m?e.jsx("span",{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:135:109",className:"animate-spin inline-block ml-2",children:"⏳"}):""]})}):o.map((s,t)=>e.jsxs(u,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:137:17",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(n,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:138:19",className:"font-medium text-slate-200 text-sm",children:s.pod}),e.jsx(n,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:139:19",children:e.jsx(L,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:139:30",variant:"outline",className:"border-slate-700 text-slate-400 text-xs",children:s.namespace})}),e.jsx(n,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:140:19",className:"text-sm text-slate-400",children:s.container}),e.jsx(n,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:141:19",className:"text-sm text-blue-400",children:s.cpu}),e.jsx(n,{"code-path":"src/components/kubernetes/PodMetricsPage.tsx:142:19",className:"text-sm text-emerald-400",children:s.memory})]},`${s.pod}-${s.container}-${t}`))})]})})})]})}export{te as default}; diff --git a/backend/static/assets/RegionManager-Bj8EPK6w.js b/backend/static/assets/RegionManager-Bj8EPK6w.js new file mode 100644 index 0000000..ca162c2 --- /dev/null +++ b/backend/static/assets/RegionManager-Bj8EPK6w.js @@ -0,0 +1 @@ +import{a as ee,r as t,j as e,S as se,I as u,B as j,L as O,M as ae,D as oe,b as te,c as ce,d as ne,e as re,f as le}from"./index-DfyorCky.js";import{L as i}from"./label-BK0h2apY.js";import{B as A}from"./badge-xNW8x0G1.js";import{C as V}from"./checkbox-CH0bpj6b.js";import{T as de,a as ie,b as H,c as r,d as pe,e as l}from"./table-5sHV4Akp.js";import{S as y,a as C,b as w,c as S,d as R}from"./select-D5qUzdAs.js";import{r as M}from"./server-CjDPBaTN.js";import{t as N}from"./index-a3ybMjbR.js";import{P as ge}from"./plus-CUG-9kpu.js";import{T as $}from"./trash-2-Dx32pOzT.js";import{C as xe}from"./circle-check-DWcXrx2k.js";import{C as he}from"./circle-x-DK79Dhg2.js";import{P as me}from"./pencil-BqUotcjf.js";import"./index-CWVNW_qu.js";const k={aws:"AWS",aliyun:"阿里云",tencent:"腾讯云",huawei:"华为云",azure:"Azure"},ue={aws:"text-orange-400",aliyun:"text-orange-400",tencent:"text-blue-400",huawei:"text-red-400",azure:"text-blue-400"};function Le(){const D=ee(),[T,L]=t.useState([]),[F,P]=t.useState(!0),[f,Q]=t.useState(""),[b,W]=t.useState("all"),[c,d]=t.useState([]),[X,p]=t.useState(!1),[g,I]=t.useState(null),[B,z]=t.useState(!1),[a,n]=t.useState({name:"",code:"",provider:"aliyun",location:"",status:"active",endpoint:""}),x=t.useCallback(async()=>{P(!0);try{const o=(await M.list())?.list||[];L(o)}catch{L([])}finally{P(!1)}},[]);t.useEffect(()=>{x()},[x]);const h=T.filter(s=>{const o=s.name?.toLowerCase().includes(f.toLowerCase())||s.code?.toLowerCase().includes(f.toLowerCase()),v=b==="all"||s.provider===b;return o&&v}),E=h.length>0&&h.every(s=>c.includes(s.id)),q=()=>{d(E?[]:h.map(s=>s.id))},G=s=>{d(o=>o.includes(s)?o.filter(v=>v!==s):[...o,s])},J=()=>{I(null),n({name:"",code:"",provider:"aliyun",location:"",status:"active",endpoint:""}),p(!0)},K=s=>{I(s),n({name:s.name||"",code:s.code||"",provider:s.provider||"aliyun",location:s.location||"",status:s.status||"active",endpoint:s.endpoint||""}),p(!0)},U=async()=>{if(!(!a.name.trim()||!a.code.trim())){z(!0);try{g?await M.update(g.id,a):await M.create(a),p(!1),x()}catch{}finally{z(!1)}}},Y=async s=>{const o=T.find(m=>m.id===s);if(await D({title:"删除区域",description:`确定删除「${o?.name||s}」吗?此操作不可撤销。`,confirmText:"删除",variant:"destructive"}))try{await M.delete(s),N.success("区域已删除"),d(m=>m.filter(_=>_!==s)),x()}catch(m){console.error("删除区域失败:",m),N.error("删除失败")}},Z=async()=>{if(!(c.length===0||!await D({title:"批量删除区域",description:`确定删除选中的 ${c.length} 个区域吗?此操作不可撤销。`,confirmText:"批量删除",variant:"destructive"})))try{await M.batchDelete(c),N.success(`已删除 ${c.length} 个区域`),d([]),x()}catch(o){console.error("批量删除失败:",o),N.error("批量删除失败")}};return e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:185:5",className:"p-6 space-y-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:187:7",className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:188:9",className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:189:11",className:"relative w-72",children:[e.jsx(se,{"code-path":"src/components/cloud/RegionManager.tsx:190:13",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(u,{"code-path":"src/components/cloud/RegionManager.tsx:191:13",placeholder:"搜索区域名称或编码...",value:f,onChange:s=>Q(s.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700"})]}),e.jsxs(y,{"code-path":"src/components/cloud/RegionManager.tsx:198:11",value:b,onValueChange:W,children:[e.jsx(C,{"code-path":"src/components/cloud/RegionManager.tsx:199:13",className:"w-32 h-9 bg-slate-800/50 border-slate-700",children:e.jsx(w,{"code-path":"src/components/cloud/RegionManager.tsx:200:15"})}),e.jsxs(S,{"code-path":"src/components/cloud/RegionManager.tsx:202:13",children:[e.jsx(R,{"code-path":"src/components/cloud/RegionManager.tsx:203:15",value:"all",children:"全部云商"}),Object.entries(k).map(([s,o])=>e.jsx(R,{"code-path":"src/components/cloud/RegionManager.tsx:205:17",value:s,children:o},s))]})]})]}),e.jsxs(j,{"code-path":"src/components/cloud/RegionManager.tsx:210:9",onClick:J,className:"gap-2",children:[e.jsx(ge,{"code-path":"src/components/cloud/RegionManager.tsx:211:11",className:"h-4 w-4"}),"添加区域"]})]}),c.length>0&&e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:218:9",className:"flex items-center justify-between gap-4 px-4 py-2.5 rounded-lg bg-slate-800/50 border border-slate-700",children:[e.jsxs("span",{"code-path":"src/components/cloud/RegionManager.tsx:219:11",className:"text-sm text-slate-300",children:["已选择 ",e.jsx("span",{"code-path":"src/components/cloud/RegionManager.tsx:220:17",className:"font-semibold text-slate-100",children:c.length})," 个区域"]}),e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:222:11",className:"flex items-center gap-2",children:[e.jsx(j,{"code-path":"src/components/cloud/RegionManager.tsx:223:13",variant:"ghost",size:"sm",onClick:()=>d([]),className:"text-slate-400 hover:text-slate-200",children:"取消选择"}),e.jsxs(j,{"code-path":"src/components/cloud/RegionManager.tsx:226:13",variant:"outline",size:"sm",className:"border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:Z,children:[e.jsx($,{"code-path":"src/components/cloud/RegionManager.tsx:232:15",className:"h-4 w-4 mr-1.5"}),"批量删除"]})]})]}),F?e.jsx("div",{"code-path":"src/components/cloud/RegionManager.tsx:241:9",className:"flex justify-center py-20",children:e.jsx(O,{"code-path":"src/components/cloud/RegionManager.tsx:242:11",className:"h-6 w-6 animate-spin text-slate-500"})}):h.length===0?e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:245:9",className:"text-center py-20 text-slate-500",children:[e.jsx(ae,{"code-path":"src/components/cloud/RegionManager.tsx:246:11",className:"h-12 w-12 mx-auto mb-3 opacity-40"}),e.jsx("p",{"code-path":"src/components/cloud/RegionManager.tsx:247:11",children:"暂无区域数据"})]}):e.jsx("div",{"code-path":"src/components/cloud/RegionManager.tsx:250:9",className:"rounded-lg overflow-hidden",children:e.jsxs(de,{"code-path":"src/components/cloud/RegionManager.tsx:251:11",children:[e.jsx(ie,{"code-path":"src/components/cloud/RegionManager.tsx:252:13",children:e.jsxs(H,{"code-path":"src/components/cloud/RegionManager.tsx:253:15",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(r,{"code-path":"src/components/cloud/RegionManager.tsx:254:17",className:"w-10",children:e.jsx(V,{"code-path":"src/components/cloud/RegionManager.tsx:255:19",checked:E,onCheckedChange:q,className:"border-slate-600"})}),e.jsx(r,{"code-path":"src/components/cloud/RegionManager.tsx:261:17",className:"text-slate-400",children:"区域名称"}),e.jsx(r,{"code-path":"src/components/cloud/RegionManager.tsx:262:17",className:"text-slate-400",children:"编码"}),e.jsx(r,{"code-path":"src/components/cloud/RegionManager.tsx:263:17",className:"text-slate-400",children:"云商"}),e.jsx(r,{"code-path":"src/components/cloud/RegionManager.tsx:264:17",className:"text-slate-400",children:"位置"}),e.jsx(r,{"code-path":"src/components/cloud/RegionManager.tsx:265:17",className:"text-slate-400",children:"接入端点"}),e.jsx(r,{"code-path":"src/components/cloud/RegionManager.tsx:266:17",className:"text-slate-400",children:"状态"}),e.jsx(r,{"code-path":"src/components/cloud/RegionManager.tsx:267:17",className:"text-slate-400 text-right",children:"操作"})]})}),e.jsx(pe,{"code-path":"src/components/cloud/RegionManager.tsx:270:13",children:h.map(s=>e.jsxs(H,{"code-path":"src/components/cloud/RegionManager.tsx:272:17",className:"border-slate-800/50 group",children:[e.jsx(l,{"code-path":"src/components/cloud/RegionManager.tsx:273:19",children:e.jsx(V,{"code-path":"src/components/cloud/RegionManager.tsx:274:21",checked:c.includes(s.id),onCheckedChange:()=>G(s.id),className:"border-slate-600"})}),e.jsx(l,{"code-path":"src/components/cloud/RegionManager.tsx:280:19",className:"font-medium text-slate-200",children:s.name}),e.jsx(l,{"code-path":"src/components/cloud/RegionManager.tsx:281:19",className:"font-mono text-sm text-slate-400",children:s.code}),e.jsx(l,{"code-path":"src/components/cloud/RegionManager.tsx:282:19",children:e.jsx("span",{"code-path":"src/components/cloud/RegionManager.tsx:283:21",className:ue[s.provider]||"text-slate-400",children:k[s.provider]||s.provider})}),e.jsx(l,{"code-path":"src/components/cloud/RegionManager.tsx:287:19",className:"text-slate-400",children:s.location||"-"}),e.jsx(l,{"code-path":"src/components/cloud/RegionManager.tsx:288:19",className:"max-w-[200px] truncate font-mono text-xs text-slate-400",title:s.endpoint,children:s.endpoint||"-"}),e.jsx(l,{"code-path":"src/components/cloud/RegionManager.tsx:289:19",children:s.status==="active"?e.jsxs(A,{"code-path":"src/components/cloud/RegionManager.tsx:291:23",className:"bg-emerald-500/20 text-emerald-400 gap-1",children:[e.jsx(xe,{"code-path":"src/components/cloud/RegionManager.tsx:292:25",className:"h-3 w-3"})," 启用"]}):e.jsxs(A,{"code-path":"src/components/cloud/RegionManager.tsx:295:23",className:"bg-slate-500/20 text-slate-400 gap-1",children:[e.jsx(he,{"code-path":"src/components/cloud/RegionManager.tsx:296:25",className:"h-3 w-3"})," 禁用"]})}),e.jsx(l,{"code-path":"src/components/cloud/RegionManager.tsx:300:19",children:e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:301:21",className:"flex justify-end gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{"code-path":"src/components/cloud/RegionManager.tsx:302:23",onClick:()=>K(s),className:"p-1.5 rounded hover:bg-slate-700 text-slate-400 hover:text-slate-200",children:e.jsx(me,{"code-path":"src/components/cloud/RegionManager.tsx:303:25",className:"h-3.5 w-3.5"})}),e.jsx("button",{"code-path":"src/components/cloud/RegionManager.tsx:305:23",onClick:()=>Y(s.id),className:"p-1.5 rounded hover:bg-slate-700 text-slate-400 hover:text-red-400",children:e.jsx($,{"code-path":"src/components/cloud/RegionManager.tsx:306:25",className:"h-3.5 w-3.5"})})]})})]},s.id))})]})}),e.jsx(oe,{"code-path":"src/components/cloud/RegionManager.tsx:318:7",open:X,onOpenChange:p,children:e.jsxs(te,{"code-path":"src/components/cloud/RegionManager.tsx:319:9",children:[e.jsxs(ce,{"code-path":"src/components/cloud/RegionManager.tsx:320:11",children:[e.jsx(ne,{"code-path":"src/components/cloud/RegionManager.tsx:321:13",children:g?"编辑区域":"添加区域"}),e.jsx(re,{"code-path":"src/components/cloud/RegionManager.tsx:322:13",className:"sr-only",children:"描述"})]}),e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:324:11",className:"space-y-4 py-2",children:[e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:325:13",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:326:15",className:"space-y-1.5",children:[e.jsx(i,{"code-path":"src/components/cloud/RegionManager.tsx:327:17",children:"区域名称 *"}),e.jsx(u,{"code-path":"src/components/cloud/RegionManager.tsx:328:17",value:a.name,onChange:s=>n({...a,name:s.target.value}),placeholder:"如:华北-北京",className:"bg-slate-800/50 border-slate-700"})]}),e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:335:15",className:"space-y-1.5",children:[e.jsx(i,{"code-path":"src/components/cloud/RegionManager.tsx:336:17",children:"编码 *"}),e.jsx(u,{"code-path":"src/components/cloud/RegionManager.tsx:337:17",value:a.code,onChange:s=>n({...a,code:s.target.value}),placeholder:"如:cn-north-1",className:"bg-slate-800/50 border-slate-700 font-mono",disabled:!!g})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:346:13",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:347:15",className:"space-y-1.5",children:[e.jsx(i,{"code-path":"src/components/cloud/RegionManager.tsx:348:17",children:"云商"}),e.jsxs(y,{"code-path":"src/components/cloud/RegionManager.tsx:349:17",value:a.provider,onValueChange:s=>n({...a,provider:s}),children:[e.jsx(C,{"code-path":"src/components/cloud/RegionManager.tsx:350:19",className:"bg-slate-800/50 border-slate-700",children:e.jsx(w,{"code-path":"src/components/cloud/RegionManager.tsx:351:21"})}),e.jsx(S,{"code-path":"src/components/cloud/RegionManager.tsx:353:19",children:Object.entries(k).map(([s,o])=>e.jsx(R,{"code-path":"src/components/cloud/RegionManager.tsx:355:23",value:s,children:o},s))})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:360:15",className:"space-y-1.5",children:[e.jsx(i,{"code-path":"src/components/cloud/RegionManager.tsx:361:17",children:"状态"}),e.jsxs(y,{"code-path":"src/components/cloud/RegionManager.tsx:362:17",value:a.status,onValueChange:s=>n({...a,status:s}),children:[e.jsx(C,{"code-path":"src/components/cloud/RegionManager.tsx:363:19",className:"bg-slate-800/50 border-slate-700",children:e.jsx(w,{"code-path":"src/components/cloud/RegionManager.tsx:364:21"})}),e.jsxs(S,{"code-path":"src/components/cloud/RegionManager.tsx:366:19",children:[e.jsx(R,{"code-path":"src/components/cloud/RegionManager.tsx:367:21",value:"active",children:"启用"}),e.jsx(R,{"code-path":"src/components/cloud/RegionManager.tsx:368:21",value:"inactive",children:"禁用"})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:373:13",className:"space-y-1.5",children:[e.jsx(i,{"code-path":"src/components/cloud/RegionManager.tsx:374:15",children:"地理位置"}),e.jsx(u,{"code-path":"src/components/cloud/RegionManager.tsx:375:15",value:a.location,onChange:s=>n({...a,location:s.target.value}),placeholder:"如:中国北京",className:"bg-slate-800/50 border-slate-700"})]}),e.jsxs("div",{"code-path":"src/components/cloud/RegionManager.tsx:382:13",className:"space-y-1.5",children:[e.jsx(i,{"code-path":"src/components/cloud/RegionManager.tsx:383:15",children:"接入端点"}),e.jsx(u,{"code-path":"src/components/cloud/RegionManager.tsx:384:15",value:a.endpoint,onChange:s=>n({...a,endpoint:s.target.value}),placeholder:"如:ecs.cn-north-1.aliyuncs.com",className:"bg-slate-800/50 border-slate-700 font-mono text-sm"})]})]}),e.jsxs(le,{"code-path":"src/components/cloud/RegionManager.tsx:392:11",children:[e.jsx(j,{"code-path":"src/components/cloud/RegionManager.tsx:393:13",variant:"ghost",onClick:()=>p(!1),children:"取消"}),e.jsxs(j,{"code-path":"src/components/cloud/RegionManager.tsx:394:13",onClick:U,disabled:B||!a.name.trim()||!a.code.trim(),children:[B&&e.jsx(O,{"code-path":"src/components/cloud/RegionManager.tsx:395:30",className:"h-4 w-4 mr-1 animate-spin"}),g?"保存":"创建"]})]})]})})]})}export{Le as RegionManager}; diff --git a/backend/static/assets/ScriptManager-BFWlhlzw.js b/backend/static/assets/ScriptManager-BFWlhlzw.js new file mode 100644 index 0000000..a3600bd --- /dev/null +++ b/backend/static/assets/ScriptManager-BFWlhlzw.js @@ -0,0 +1,17 @@ +import{j as t,a3 as Z,L as $,x as Lt,D as P,b as B,c as O,d as A,e as I,I as D,f as V,B as p,F as tt,a2 as et,U as _t,R as ot,H as zt,a as $t,r as i,S as Pt}from"./index-DfyorCky.js";import{S as st,a as at,b as ct,c as nt,d as z}from"./select-D5qUzdAs.js";import{T as Bt,a as Ot,b as J,c as K}from"./tabs-CIh_yD4s.js";import{C as rt}from"./checkbox-CH0bpj6b.js";import{t as l}from"./index-a3ybMjbR.js";import{s as j,t as At}from"./automation-mtL167W_.js";import{B as N}from"./badge-xNW8x0G1.js";import{C as It}from"./circle-x-DK79Dhg2.js";import{L as b}from"./label-BK0h2apY.js";import{T as Vt}from"./textarea-NXY8u32k.js";import{S as it}from"./square-pen-BxUFAe0F.js";import{C as pt,b as Rt,c as Ht,d as qt,a as lt}from"./card-C55cvSHg.js";import{P as Qt}from"./play-cdPayOtJ.js";import{C as Ut}from"./copy-DXW4LnkN.js";import{T as mt}from"./trash-2-Dx32pOzT.js";import{P as Xt}from"./plus-CUG-9kpu.js";import"./index-CWVNW_qu.js";function Gt(o){return{id:o.id,name:o.name,code:o.code||"",description:o.description||"",type:o.type||"shell",content:o.content||"",timeout:o.timeout||300,version:o.version||1,run_count:o.run_count||0,created_at:o.created_at,updated_at:o.updated_at}}const w=[{value:"shell",label:"Shell",sample:`#!/bin/bash +# 系统巡检脚本 +echo "===== 系统信息 =====" +uname -a +echo "" +echo "===== 磁盘使用 =====" +df -h +echo "" +echo "===== 内存使用 =====" +free -h +`},{value:"python",label:"Python",sample:`#!/usr/bin/env python3 +# 主机信息采集 +import platform, socket +print("主机名:", socket.gethostname()) +print("系统:", platform.platform()) +print("Python:", platform.python_version()) +`}],W={shell:"border-green-500/30 text-green-500 bg-green-500/10",bash:"border-green-500/30 text-green-500 bg-green-500/10",python:"border-blue-500/30 text-blue-500 bg-blue-500/10",powershell:"border-cyan-500/30 text-cyan-500 bg-cyan-500/10",yaml:"border-purple-500/30 text-purple-500 bg-purple-500/10"},dt=o=>t.jsx(N,{"code-path":"src/components/automation/script-helpers.tsx:66:3",variant:"outline",className:W[o]||W.shell,children:(o||"shell").toUpperCase()}),Y=()=>`sc-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,6)}`;function xt(o){switch(o){case"pending":return t.jsxs(N,{"code-path":"src/components/automation/script-helpers.tsx:78:14",variant:"outline",className:"gap-1",children:[t.jsx(Lt,{"code-path":"src/components/automation/script-helpers.tsx:78:57",className:"w-3 h-3"}),"等待中"]});case"running":return t.jsxs(N,{"code-path":"src/components/automation/script-helpers.tsx:80:14",variant:"default",className:"bg-blue-500 gap-1",children:[t.jsx($,{"code-path":"src/components/automation/script-helpers.tsx:80:69",className:"w-3 h-3 animate-spin"}),"执行中"]});case"success":return t.jsxs(N,{"code-path":"src/components/automation/script-helpers.tsx:82:14",variant:"default",className:"bg-green-600 gap-1",children:[t.jsx(Z,{"code-path":"src/components/automation/script-helpers.tsx:82:70",className:"w-3 h-3"}),"成功"]});case"failed":return t.jsxs(N,{"code-path":"src/components/automation/script-helpers.tsx:84:14",variant:"destructive",className:"gap-1",children:[t.jsx(It,{"code-path":"src/components/automation/script-helpers.tsx:84:61",className:"w-3 h-3"}),"失败"]});default:return t.jsx(N,{"code-path":"src/components/automation/script-helpers.tsx:86:14",variant:"secondary",children:o||"未知"})}}const Jt=o=>{if(!o)return"-";const a=new Date(o);return Number.isNaN(a.getTime())?"-":a.toLocaleString("zh-CN",{hour12:!1})},Kt=({open:o,onOpenChange:a,editingId:s,editingCode:n,formData:m,setFormData:x,onTypeChange:f,onSave:C})=>t.jsx(P,{"code-path":"src/components/automation/ScriptFormDialog.tsx:38:5",open:o,onOpenChange:a,children:t.jsxs(B,{"code-path":"src/components/automation/ScriptFormDialog.tsx:39:7",className:"max-w-4xl max-h-[90vh]",children:[t.jsxs(O,{"code-path":"src/components/automation/ScriptFormDialog.tsx:40:9",children:[t.jsx(A,{"code-path":"src/components/automation/ScriptFormDialog.tsx:41:11",children:s!==null?"编辑脚本":"新建脚本"}),t.jsx(I,{"code-path":"src/components/automation/ScriptFormDialog.tsx:42:11",children:"编写运维脚本,支持 Shell / Python / PowerShell"})]}),t.jsxs("div",{"code-path":"src/components/automation/ScriptFormDialog.tsx:44:9",className:"space-y-4 overflow-y-auto max-h-[60vh] pr-1",children:[t.jsxs("div",{"code-path":"src/components/automation/ScriptFormDialog.tsx:45:11",className:"grid grid-cols-2 gap-4",children:[t.jsxs("div",{"code-path":"src/components/automation/ScriptFormDialog.tsx:46:13",children:[t.jsx(b,{"code-path":"src/components/automation/ScriptFormDialog.tsx:47:15",children:"名称"}),t.jsx(D,{"code-path":"src/components/automation/ScriptFormDialog.tsx:48:15",value:m.name,onChange:r=>x({...m,name:r.target.value}),placeholder:"如:系统巡检脚本"})]}),t.jsxs("div",{"code-path":"src/components/automation/ScriptFormDialog.tsx:54:13",children:[t.jsx(b,{"code-path":"src/components/automation/ScriptFormDialog.tsx:55:15",children:"类型"}),t.jsxs(st,{"code-path":"src/components/automation/ScriptFormDialog.tsx:56:15",value:m.type,onValueChange:f,children:[t.jsx(at,{"code-path":"src/components/automation/ScriptFormDialog.tsx:57:17",children:t.jsx(ct,{"code-path":"src/components/automation/ScriptFormDialog.tsx:57:32"})}),t.jsx(nt,{"code-path":"src/components/automation/ScriptFormDialog.tsx:58:17",children:w.map(r=>t.jsx(z,{"code-path":"src/components/automation/ScriptFormDialog.tsx:60:21",value:r.value,children:r.label},r.value))})]})]})]}),t.jsxs("div",{"code-path":"src/components/automation/ScriptFormDialog.tsx:66:11",children:[t.jsx(b,{"code-path":"src/components/automation/ScriptFormDialog.tsx:67:13",children:"描述"}),t.jsx(D,{"code-path":"src/components/automation/ScriptFormDialog.tsx:68:13",value:m.description,onChange:r=>x({...m,description:r.target.value}),placeholder:"脚本用途说明"})]}),t.jsxs("div",{"code-path":"src/components/automation/ScriptFormDialog.tsx:74:11",className:"grid grid-cols-2 gap-4",children:[t.jsxs("div",{"code-path":"src/components/automation/ScriptFormDialog.tsx:75:13",children:[t.jsx(b,{"code-path":"src/components/automation/ScriptFormDialog.tsx:76:15",children:"超时(秒)"}),t.jsx(D,{"code-path":"src/components/automation/ScriptFormDialog.tsx:77:15",type:"number",value:m.timeout,onChange:r=>x({...m,timeout:Number(r.target.value)}),placeholder:"300"})]}),s!==null&&t.jsxs("div",{"code-path":"src/components/automation/ScriptFormDialog.tsx:85:15",children:[t.jsx(b,{"code-path":"src/components/automation/ScriptFormDialog.tsx:86:17",children:"编码"}),t.jsx(D,{"code-path":"src/components/automation/ScriptFormDialog.tsx:87:17",value:n,disabled:!0,className:"font-mono text-xs"})]})]}),t.jsxs("div",{"code-path":"src/components/automation/ScriptFormDialog.tsx:91:11",children:[t.jsx(b,{"code-path":"src/components/automation/ScriptFormDialog.tsx:92:13",children:"脚本内容"}),t.jsx(Vt,{"code-path":"src/components/automation/ScriptFormDialog.tsx:93:13",value:m.content,onChange:r=>x({...m,content:r.target.value}),className:"min-h-[360px] font-mono text-sm",placeholder:"在此编写脚本内容..."})]})]}),t.jsxs(V,{"code-path":"src/components/automation/ScriptFormDialog.tsx:101:9",children:[t.jsx(p,{"code-path":"src/components/automation/ScriptFormDialog.tsx:102:11",variant:"outline",onClick:()=>a(!1),children:"取消"}),t.jsxs(p,{"code-path":"src/components/automation/ScriptFormDialog.tsx:103:11",onClick:C,children:[t.jsx(Z,{"code-path":"src/components/automation/ScriptFormDialog.tsx:104:13",className:"w-4 h-4 mr-2"}),s!==null?"保存":"创建"]})]})]})}),Wt=({open:o,onOpenChange:a,script:s,onEdit:n})=>t.jsx(P,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:20:5",open:o,onOpenChange:a,children:t.jsxs(B,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:21:7",className:"max-w-4xl max-h-[90vh]",children:[t.jsxs(O,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:22:9",children:[t.jsxs(A,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:23:11",className:"flex items-center gap-2",children:[t.jsx(tt,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:24:13",className:"w-5 h-5 text-purple-500"}),s?.name,s&&dt(s.type)]}),t.jsx(I,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:28:11",children:s?.description})]}),t.jsx(et,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:30:9",className:"h-[500px] w-full rounded-md border bg-black",children:t.jsx("pre",{"code-path":"src/components/automation/ScriptDetailDialog.tsx:31:11",className:"p-4 font-mono text-sm text-green-400 whitespace-pre-wrap",children:s?.content||"(空)"})}),t.jsxs(V,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:35:9",children:[t.jsx(p,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:36:11",variant:"outline",onClick:()=>a(!1),children:"关闭"}),s&&t.jsxs(p,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:38:13",onClick:()=>n(s),children:[t.jsx(it,{"code-path":"src/components/automation/ScriptDetailDialog.tsx:39:15",className:"w-4 h-4 mr-2"}),"编辑"]})]})]})}),Yt=({open:o,onOpenChange:a,exec:s})=>t.jsx(P,{"code-path":"src/components/automation/ScriptLogsDialog.tsx:18:5",open:o,onOpenChange:a,children:t.jsxs(B,{"code-path":"src/components/automation/ScriptLogsDialog.tsx:19:7",className:"max-w-4xl max-h-[90vh]",children:[t.jsxs(O,{"code-path":"src/components/automation/ScriptLogsDialog.tsx:20:9",children:[t.jsx(A,{"code-path":"src/components/automation/ScriptLogsDialog.tsx:21:11",children:"执行日志"}),t.jsxs(I,{"code-path":"src/components/automation/ScriptLogsDialog.tsx:22:11",children:[s?.task_name," · ",xt(s?.status||"")]})]}),t.jsx(et,{"code-path":"src/components/automation/ScriptLogsDialog.tsx:26:9",className:"h-[480px] w-full rounded-md border bg-black",children:t.jsx("pre",{"code-path":"src/components/automation/ScriptLogsDialog.tsx:27:11",className:"p-4 font-mono text-sm text-green-400 whitespace-pre-wrap",children:s?.output||"暂无日志输出..."})}),t.jsx(V,{"code-path":"src/components/automation/ScriptLogsDialog.tsx:31:9",children:t.jsx(p,{"code-path":"src/components/automation/ScriptLogsDialog.tsx:32:11",variant:"outline",onClick:()=>a(!1),children:"关闭"})})]})});function Zt({script:o,selected:a,executing:s,onToggleSelect:n,onView:m,onExecute:x,onEdit:f,onClone:C,onDelete:r}){return t.jsxs(pt,{"code-path":"src/components/automation/ScriptCard.tsx:26:5",className:"hover:shadow-md transition-shadow",children:[t.jsxs(Rt,{"code-path":"src/components/automation/ScriptCard.tsx:27:7",className:"pb-3",children:[t.jsxs("div",{"code-path":"src/components/automation/ScriptCard.tsx:28:9",className:"flex items-start justify-between gap-2",children:[t.jsxs("div",{"code-path":"src/components/automation/ScriptCard.tsx:29:11",className:"flex items-center gap-2 min-w-0",children:[t.jsx(rt,{"code-path":"src/components/automation/ScriptCard.tsx:30:13",checked:a,onCheckedChange:n,className:"border-[var(--dg-border)]"}),t.jsx(tt,{"code-path":"src/components/automation/ScriptCard.tsx:35:13",className:"w-5 h-5 text-purple-500 shrink-0"}),t.jsx(Ht,{"code-path":"src/components/automation/ScriptCard.tsx:36:13",className:"text-base truncate",children:o.name})]}),dt(o.type)]}),t.jsx(qt,{"code-path":"src/components/automation/ScriptCard.tsx:40:9",className:"line-clamp-2",children:o.description||"暂无描述"})]}),t.jsxs(lt,{"code-path":"src/components/automation/ScriptCard.tsx:42:7",className:"pt-0",children:[t.jsx("div",{"code-path":"src/components/automation/ScriptCard.tsx:43:9",className:"bg-muted/40 rounded-md p-2 mb-3 font-mono text-xs text-muted-foreground overflow-hidden",children:t.jsx("pre",{"code-path":"src/components/automation/ScriptCard.tsx:44:11",className:"whitespace-pre-wrap line-clamp-3",children:o.content})}),t.jsxs("div",{"code-path":"src/components/automation/ScriptCard.tsx:46:9",className:"flex items-center justify-between text-xs text-muted-foreground mb-3",children:[t.jsxs("span",{"code-path":"src/components/automation/ScriptCard.tsx:47:11",children:["执行 ",o.run_count," 次 · v",o.version]}),t.jsxs("span",{"code-path":"src/components/automation/ScriptCard.tsx:48:11",children:["超时 ",o.timeout,"s"]})]}),t.jsxs("div",{"code-path":"src/components/automation/ScriptCard.tsx:50:9",className:"flex items-center gap-1",children:[t.jsx(p,{"code-path":"src/components/automation/ScriptCard.tsx:51:11",variant:"ghost",size:"sm",title:"查看内容",onClick:m,children:t.jsx(_t,{"code-path":"src/components/automation/ScriptCard.tsx:52:13",className:"w-4 h-4"})}),t.jsx(p,{"code-path":"src/components/automation/ScriptCard.tsx:54:11",variant:"ghost",size:"sm",title:"执行",disabled:s,onClick:x,children:s?t.jsx($,{"code-path":"src/components/automation/ScriptCard.tsx:56:17",className:"w-4 h-4 animate-spin text-blue-600"}):t.jsx(Qt,{"code-path":"src/components/automation/ScriptCard.tsx:57:17",className:"w-4 h-4 text-green-600"})}),t.jsx(p,{"code-path":"src/components/automation/ScriptCard.tsx:59:11",variant:"ghost",size:"sm",title:"编辑",onClick:f,children:t.jsx(it,{"code-path":"src/components/automation/ScriptCard.tsx:60:13",className:"w-4 h-4"})}),t.jsx(p,{"code-path":"src/components/automation/ScriptCard.tsx:62:11",variant:"ghost",size:"sm",title:"复制",onClick:C,children:t.jsx(Ut,{"code-path":"src/components/automation/ScriptCard.tsx:63:13",className:"w-4 h-4"})}),t.jsx(p,{"code-path":"src/components/automation/ScriptCard.tsx:65:11",variant:"ghost",size:"sm",title:"删除",onClick:r,children:t.jsx(mt,{"code-path":"src/components/automation/ScriptCard.tsx:66:13",className:"w-4 h-4 text-red-600"})})]})]})]})}function te({executions:o,onRefresh:a,onViewLogs:s}){return t.jsxs("div",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:16:5",className:"space-y-4",children:[t.jsx("div",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:17:7",className:"flex justify-end",children:t.jsxs(p,{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:18:9",variant:"outline",onClick:a,children:[t.jsx(ot,{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:19:11",className:"w-4 h-4 mr-2"}),"刷新"]})}),t.jsx(pt,{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:23:7",children:t.jsx(lt,{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:24:9",className:"p-0",children:t.jsx("div",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:25:11",className:"overflow-x-auto",children:t.jsxs("table",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:26:13",className:"w-full",children:[t.jsx("thead",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:27:15",className:"bg-muted/50",children:t.jsxs("tr",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:28:17",children:[t.jsx("th",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:29:19",className:"px-4 py-3 text-left text-sm font-medium",children:"#"}),t.jsx("th",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:30:19",className:"px-4 py-3 text-left text-sm font-medium",children:"脚本"}),t.jsx("th",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:31:19",className:"px-4 py-3 text-left text-sm font-medium",children:"状态"}),t.jsx("th",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:32:19",className:"px-4 py-3 text-left text-sm font-medium",children:"开始时间"}),t.jsx("th",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:33:19",className:"px-4 py-3 text-left text-sm font-medium",children:"耗时"}),t.jsx("th",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:34:19",className:"px-4 py-3 text-left text-sm font-medium",children:"操作"})]})}),t.jsx("tbody",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:37:15",className:"divide-y",children:o.length===0?t.jsx("tr",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:39:19",children:t.jsx("td",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:40:21",colSpan:6,className:"px-4 py-8 text-center text-muted-foreground",children:"暂无执行记录"})}):o.map(n=>t.jsxs("tr",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:46:21",className:"hover:bg-muted/50",children:[t.jsx("td",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:47:23",className:"px-4 py-3 text-sm text-muted-foreground",children:n.id}),t.jsx("td",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:48:23",className:"px-4 py-3 text-sm",children:n.task_name}),t.jsx("td",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:49:23",className:"px-4 py-3",children:xt(n.status)}),t.jsx("td",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:50:23",className:"px-4 py-3 text-sm text-muted-foreground",children:Jt(n.started_at)}),t.jsx("td",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:51:23",className:"px-4 py-3 text-sm",children:n.duration?`${(n.duration/1e3).toFixed(1)}s`:"-"}),t.jsx("td",{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:54:23",className:"px-4 py-3",children:t.jsx(p,{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:55:25",variant:"ghost",size:"sm",title:"查看日志",onClick:()=>s(n),children:t.jsx(zt,{"code-path":"src/components/automation/ScriptExecutionsTable.tsx:56:27",className:"w-4 h-4"})})})]},n.id))})]})})})})]})}function je(){const o=$t(),[a,s]=i.useState([]),[n,m]=i.useState([]),[x,f]=i.useState(!1),[C,r]=i.useState(!1),[R,ht]=i.useState(""),[k,ut]=i.useState("all"),[gt,St]=i.useState("scripts"),[h,T]=i.useState([]),[jt,E]=i.useState(!1),[ft,L]=i.useState(!1),[vt,H]=i.useState(!1),[y,q]=i.useState(null),[Q,U]=i.useState(null),[bt,Nt]=i.useState(null),[u,M]=i.useState({name:"",description:"",content:"",type:"shell",timeout:300}),S=async()=>{f(!0);try{const c=(await j.getScripts({page_size:100}))?.list||[];s(c.map(Gt))}catch{l.error("获取脚本列表失败")}finally{f(!1)}},F=async()=>{try{const c=(await At.getExecutions({task_type:"script",page_size:50}))?.list||[];m(c)}catch{}};i.useEffect(()=>{S(),F()},[]);const Ct=()=>{q(null),M({name:"",description:"",content:w[0].sample,type:"shell",timeout:300}),E(!0)},X=e=>{q(e.id),U(e),M({name:e.name,description:e.description,content:e.content,type:e.type,timeout:e.timeout}),E(!0),L(!1)},yt=e=>{M(c=>{const g=w.some(_=>_.sample===c.content)||c.content==="",d=w.find(_=>_.value===e);return{...c,type:e,content:y===null&&g&&d?d.sample:c.content}})},Dt=async()=>{if(!u.name.trim()||!u.content.trim()){l.error("请填写名称和脚本内容");return}const e={name:u.name.trim(),code:Y(),description:u.description,type:u.type,content:u.content,timeout:Number(u.timeout)||300};try{y!==null?(await j.updateScript(y,e),l.success("脚本更新成功")):(await j.createScript(e),l.success("脚本创建成功")),E(!1),S()}catch{l.error(y!==null?"更新失败":"创建失败")}},wt=async e=>{try{await j.createScript({name:`${e.name} (副本)`,code:Y(),description:e.description,type:e.type,content:e.content,timeout:e.timeout}),l.success("复制成功"),S()}catch{l.error("复制失败")}},Tt=async e=>{if(await o({title:"删除脚本",description:`确定删除「${e.name}」吗?此操作不可恢复。`,confirmText:"删除",variant:"destructive"}))try{await j.deleteScript(e.id),l.success("删除成功"),S()}catch{l.error("删除失败")}},Et=async e=>{if(await o({title:"执行脚本",description:`将在 AIOps 主机上本地执行「${e.name}」(${e.type})。`,confirmText:"开始执行"})){r(!0);try{const g=await j.executeScript(e.id),d=g?.data??g;d?.status==="success"?l.success(`执行成功,耗时 ${d.duration??0}ms`):l.error(`执行失败,耗时 ${d?.duration??0}ms`,{description:(d?.output||"").slice(0,120)}),S(),F()}catch{l.error("执行请求失败")}finally{r(!1)}}},v=a.filter(e=>{const c=R.toLowerCase(),g=e.name.toLowerCase().includes(c)||e.description.toLowerCase().includes(c)||e.code.toLowerCase().includes(c),d=k==="all"||e.type===k;return g&&d}),Mt=e=>{T(c=>c.includes(e)?c.filter(g=>g!==e):[...c,e])},G=v.length>0&&h.length===v.length,Ft=()=>{T(G?[]:v.map(e=>e.id))},kt=async()=>{if(!(h.length===0||!await o({title:"批量删除脚本",description:`确定删除选中的 ${h.length} 个脚本吗?此操作不可恢复。`,confirmText:"批量删除",variant:"destructive"})))try{await j.batchDelete(h),l.success(`已删除 ${h.length} 个脚本`),T([]),S()}catch{l.error("批量删除失败")}};return t.jsxs("div",{"code-path":"src/components/automation/ScriptManager.tsx:252:5",className:"space-y-6",children:[t.jsxs(Bt,{"code-path":"src/components/automation/ScriptManager.tsx:254:7",value:gt,onValueChange:e=>{St(e),e==="jobs"&&F()},children:[t.jsxs(Ot,{"code-path":"src/components/automation/ScriptManager.tsx:255:9",className:"grid w-full grid-cols-2 lg:w-[360px]",children:[t.jsx(J,{"code-path":"src/components/automation/ScriptManager.tsx:256:11",value:"scripts",children:"脚本库"}),t.jsx(J,{"code-path":"src/components/automation/ScriptManager.tsx:257:11",value:"jobs",children:"执行记录"})]}),t.jsxs(K,{"code-path":"src/components/automation/ScriptManager.tsx:261:9",value:"scripts",className:"space-y-4",children:[t.jsxs("div",{"code-path":"src/components/automation/ScriptManager.tsx:262:11",className:"flex flex-wrap items-center justify-between gap-4",children:[t.jsxs("div",{"code-path":"src/components/automation/ScriptManager.tsx:263:13",className:"flex items-center gap-2 flex-1 min-w-[300px]",children:[t.jsxs("div",{"code-path":"src/components/automation/ScriptManager.tsx:264:15",className:"relative flex-1",children:[t.jsx(Pt,{"code-path":"src/components/automation/ScriptManager.tsx:265:17",className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),t.jsx(D,{"code-path":"src/components/automation/ScriptManager.tsx:266:17",placeholder:"搜索名称、编码、描述...",value:R,onChange:e=>ht(e.target.value),className:"pl-10"})]}),t.jsxs(st,{"code-path":"src/components/automation/ScriptManager.tsx:273:15",value:k,onValueChange:ut,children:[t.jsx(at,{"code-path":"src/components/automation/ScriptManager.tsx:274:17",className:"w-[140px]",children:t.jsx(ct,{"code-path":"src/components/automation/ScriptManager.tsx:275:19",placeholder:"类型"})}),t.jsxs(nt,{"code-path":"src/components/automation/ScriptManager.tsx:277:17",children:[t.jsx(z,{"code-path":"src/components/automation/ScriptManager.tsx:278:19",value:"all",children:"全部类型"}),w.map(e=>t.jsx(z,{"code-path":"src/components/automation/ScriptManager.tsx:280:21",value:e.value,children:e.label},e.value))]})]})]}),t.jsxs("div",{"code-path":"src/components/automation/ScriptManager.tsx:285:13",className:"flex items-center gap-2",children:[t.jsxs(p,{"code-path":"src/components/automation/ScriptManager.tsx:286:15",variant:"outline",onClick:S,children:[t.jsx(ot,{"code-path":"src/components/automation/ScriptManager.tsx:287:17",className:"w-4 h-4 mr-2"}),"刷新"]}),t.jsxs(p,{"code-path":"src/components/automation/ScriptManager.tsx:290:15",onClick:Ct,children:[t.jsx(Xt,{"code-path":"src/components/automation/ScriptManager.tsx:291:17",className:"w-4 h-4 mr-2"}),"新建脚本"]})]})]}),h.length>0&&t.jsxs("div",{"code-path":"src/components/automation/ScriptManager.tsx:299:13",className:"flex items-center justify-between gap-4 px-4 py-2.5 rounded-lg border border-[var(--dg-border)] bg-[var(--dg-bg-secondary)]",children:[t.jsxs("div",{"code-path":"src/components/automation/ScriptManager.tsx:300:15",className:"flex items-center gap-3",children:[t.jsx(rt,{"code-path":"src/components/automation/ScriptManager.tsx:301:17",checked:G,onCheckedChange:Ft,className:"border-[var(--dg-border)]"}),t.jsxs("span",{"code-path":"src/components/automation/ScriptManager.tsx:306:17",className:"text-sm text-[var(--dg-text-secondary)]",children:["已选择 ",h.length," 项 / 共 ",v.length," 项"]})]}),t.jsxs("div",{"code-path":"src/components/automation/ScriptManager.tsx:310:15",className:"flex items-center gap-2",children:[t.jsx(p,{"code-path":"src/components/automation/ScriptManager.tsx:311:17",variant:"outline",size:"sm",onClick:()=>T([]),children:"取消选择"}),t.jsxs(p,{"code-path":"src/components/automation/ScriptManager.tsx:314:17",variant:"outline",size:"sm",className:"border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:kt,children:[t.jsx(mt,{"code-path":"src/components/automation/ScriptManager.tsx:320:19",className:"w-4 h-4 mr-2"}),"批量删除"]})]})]}),t.jsx("div",{"code-path":"src/components/automation/ScriptManager.tsx:328:11",className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:x?t.jsxs("div",{"code-path":"src/components/automation/ScriptManager.tsx:330:15",className:"col-span-full text-center py-8 text-muted-foreground",children:[t.jsx($,{"code-path":"src/components/automation/ScriptManager.tsx:331:17",className:"w-5 h-5 animate-spin inline mr-2"}),"加载中..."]}):v.length===0?t.jsx("div",{"code-path":"src/components/automation/ScriptManager.tsx:335:15",className:"col-span-full text-center py-8 text-muted-foreground",children:a.length===0?"暂无脚本,点击「新建脚本」创建第一个":"未匹配到符合条件的脚本"}):v.map(e=>t.jsx(Zt,{"code-path":"src/components/automation/ScriptManager.tsx:340:17",script:e,selected:h.includes(e.id),executing:C,onToggleSelect:()=>Mt(e.id),onView:()=>{U(e),L(!0)},onExecute:()=>Et(e),onEdit:()=>X(e),onClone:()=>wt(e),onDelete:()=>Tt(e)},e.id))})]}),t.jsx(K,{"code-path":"src/components/automation/ScriptManager.tsx:358:9",value:"jobs",children:t.jsx(te,{"code-path":"src/components/automation/ScriptManager.tsx:359:11",executions:n,onRefresh:F,onViewLogs:e=>{Nt(e),H(!0)}})})]}),t.jsx(Kt,{"code-path":"src/components/automation/ScriptManager.tsx:368:7",open:jt,onOpenChange:E,editingId:y,editingCode:Q?.code||"",formData:u,setFormData:M,onTypeChange:yt,onSave:Dt}),t.jsx(Wt,{"code-path":"src/components/automation/ScriptManager.tsx:380:7",open:ft,onOpenChange:L,script:Q,onEdit:X}),t.jsx(Yt,{"code-path":"src/components/automation/ScriptManager.tsx:388:7",open:vt,onOpenChange:H,exec:bt})]})}export{je as ScriptManager}; diff --git a/backend/static/assets/ServerManager-JxMW-hQt.js b/backend/static/assets/ServerManager-JxMW-hQt.js new file mode 100644 index 0000000..45dd1f4 --- /dev/null +++ b/backend/static/assets/ServerManager-JxMW-hQt.js @@ -0,0 +1,11 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./index-CHhHmizP.js","./index-DfyorCky.js","./index-1EStmE-w.css","./dashboard-BjQPIG2G.js","./server-CjDPBaTN.js","./kubernetes-J8O09fK7.js","./deploy-B3Sg3N1U.js","./automation-mtL167W_.js","./monitor-BAaBXIsC.js","./agent-DqqIRCQX.js","./cloud-Dzoer-2i.js","./system-BgtMMm0X.js","./ai-BTgmlP5Q.js"])))=>i.map(i=>d[i]); +import{g as He,j as e,q as Ee,A as Fr,r as t,aT as kr,D as Te,b as Re,c as Ue,d as Me,e as Be,s as xr,P as $e,M as Ge,a3 as ar,a9 as ge,n as _e,B as g,S as ir,I as H,$ as Oe,f as Je,W as vr,X as Se,a5 as fe,t as hr,L as Le,af as Er,ac as _r,ak as Tr,ae as Qe,ah as Rr,ad as Mr,ag as Br,aw as Pr,h as Ar,a4 as $r,N as Or,H as cr,aK as gr,aL as ur,aM as Sr,aN as br,aO as Ke,aP as we,a as zr}from"./index-DfyorCky.js";import{C as me,a as xe}from"./card-C55cvSHg.js";import{C as ue}from"./checkbox-CH0bpj6b.js";import{b as ze,e as re,T as Lr,a as Hr,c as le,d as Ur}from"./table-5sHV4Akp.js";import{S as Ce,a as Ie,b as Fe,c as ke,d as O}from"./select-D5qUzdAs.js";import{s as se,r as Dr}from"./server-CjDPBaTN.js";import{R as Vr}from"./rotate-cw-5qcj_h_q.js";import{t as V}from"./index-a3ybMjbR.js";import{B as A}from"./badge-xNW8x0G1.js";import{c as ye}from"./cloud-Dzoer-2i.js";import{R as pe}from"./refresh-cw-DUB_tAG-.js";import{x as Wr,a as Gr}from"./xterm-DSqgeKvr.js";import{c as jr,s as Kr}from"./deploy-B3Sg3N1U.js";import{M as qr,a as Jr}from"./minimize-2-CiCQYRfn.js";import{F as Nr}from"./folder-open-IMBifk-r.js";import{U as Xe}from"./upload-Ba6rlaGS.js";import{a as nr,F as Qr}from"./folder-DoMwqvzv.js";import{A as Xr}from"./arrow-left-BDgGyrD0.js";import{D as Ye}from"./download-DoZfYs2h.js";import{T as Ze}from"./trash-2-Dx32pOzT.js";import{L}from"./label-BK0h2apY.js";import{T as dr}from"./textarea-NXY8u32k.js";import{S as Yr}from"./save-DoGGjfwC.js";import{H as Zr}from"./hard-drive-BbPmnARR.js";import{E as es}from"./ellipsis-DU5enAwm.js";import{S as rs}from"./square-pen-BxUFAe0F.js";import{P as ss}from"./plus-CUG-9kpu.js";import"./index-CWVNW_qu.js";const ts=[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]],er=He("chevron-left",ts);const os=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]],qe=He("file-spreadsheet",os);const as=[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],cs=He("folder-plus",as);const ns=[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]],ds=He("power",ns);function ls({servers:s}){const m=s.filter(o=>o.status==="running").length,a=s.filter(o=>o.status==="maintenance").length,c=s.filter(o=>o.status==="stopped").length;return e.jsxs("div",{"code-path":"src/components/server/ServerStatsCards.tsx:15:5",className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(me,{"code-path":"src/components/server/ServerStatsCards.tsx:16:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(xe,{"code-path":"src/components/server/ServerStatsCards.tsx:17:9",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/server/ServerStatsCards.tsx:18:11",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/server/ServerStatsCards.tsx:19:13",children:[e.jsx("p",{"code-path":"src/components/server/ServerStatsCards.tsx:20:15",className:"text-sm text-[var(--dg-text-muted)]",children:"服务器总数"}),e.jsx("p",{"code-path":"src/components/server/ServerStatsCards.tsx:21:15",className:"text-2xl font-bold text-[var(--dg-text-primary)]",children:s.length})]}),e.jsx("div",{"code-path":"src/components/server/ServerStatsCards.tsx:23:13",className:"p-3 rounded-lg bg-[var(--dg-blue)]/10 text-[var(--dg-blue)]",children:e.jsx(Ee,{"code-path":"src/components/server/ServerStatsCards.tsx:24:15",className:"h-5 w-5"})})]})})}),e.jsx(me,{"code-path":"src/components/server/ServerStatsCards.tsx:29:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(xe,{"code-path":"src/components/server/ServerStatsCards.tsx:30:9",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/server/ServerStatsCards.tsx:31:11",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/server/ServerStatsCards.tsx:32:13",children:[e.jsx("p",{"code-path":"src/components/server/ServerStatsCards.tsx:33:15",className:"text-sm text-[var(--dg-text-muted)]",children:"运行中"}),e.jsx("p",{"code-path":"src/components/server/ServerStatsCards.tsx:34:15",className:"text-2xl font-bold text-emerald-400",children:m})]}),e.jsx("div",{"code-path":"src/components/server/ServerStatsCards.tsx:36:13",className:"p-3 rounded-lg bg-emerald-500/10 text-emerald-400",children:e.jsx(Fr,{"code-path":"src/components/server/ServerStatsCards.tsx:37:15",className:"h-5 w-5"})})]})})}),e.jsx(me,{"code-path":"src/components/server/ServerStatsCards.tsx:42:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(xe,{"code-path":"src/components/server/ServerStatsCards.tsx:43:9",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/server/ServerStatsCards.tsx:44:11",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/server/ServerStatsCards.tsx:45:13",children:[e.jsx("p",{"code-path":"src/components/server/ServerStatsCards.tsx:46:15",className:"text-sm text-[var(--dg-text-muted)]",children:"维护中"}),e.jsx("p",{"code-path":"src/components/server/ServerStatsCards.tsx:47:15",className:"text-2xl font-bold text-amber-400",children:a})]}),e.jsx("div",{"code-path":"src/components/server/ServerStatsCards.tsx:49:13",className:"p-3 rounded-lg bg-amber-500/10 text-amber-400",children:e.jsx(Vr,{"code-path":"src/components/server/ServerStatsCards.tsx:50:15",className:"h-5 w-5"})})]})})}),e.jsx(me,{"code-path":"src/components/server/ServerStatsCards.tsx:55:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsx(xe,{"code-path":"src/components/server/ServerStatsCards.tsx:56:9",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/server/ServerStatsCards.tsx:57:11",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/server/ServerStatsCards.tsx:58:13",children:[e.jsx("p",{"code-path":"src/components/server/ServerStatsCards.tsx:59:15",className:"text-sm text-[var(--dg-text-muted)]",children:"已停止"}),e.jsx("p",{"code-path":"src/components/server/ServerStatsCards.tsx:60:15",className:"text-2xl font-bold text-[var(--dg-text-muted)]",children:c})]}),e.jsx("div",{"code-path":"src/components/server/ServerStatsCards.tsx:62:13",className:"p-3 rounded-lg bg-[var(--dg-bg-tertiary)] text-[var(--dg-text-secondary)]",children:e.jsx(ds,{"code-path":"src/components/server/ServerStatsCards.tsx:63:15",className:"h-5 w-5"})})]})})})]})}const ps=[{id:"aws",name:"AWS",color:"bg-orange-500",icon:"AWS"},{id:"aliyun",name:"阿里云",color:"bg-orange-600",icon:"AL"},{id:"tencent",name:"腾讯云",color:"bg-blue-500",icon:"TX"},{id:"huawei",name:"华为云",color:"bg-red-500",icon:"HW"},{id:"azure",name:"Azure",color:"bg-blue-600",icon:"AZ"}];function ms({open:s,onClose:m}){const[a,c]=t.useState([]),[o,i]=t.useState(1),[b,j]=t.useState(""),[x,w]=t.useState(null),[N,I]=t.useState([]),[n,y]=t.useState([]),[F,T]=t.useState(""),[u,f]=t.useState(!1),[h,v]=t.useState([]),[k,z]=t.useState([]),[$,d]=t.useState(!1),[S,_]=t.useState([]),[J,W]=t.useState(!1),[B,U]=t.useState(null),[Q,Z]=t.useState("22"),[ie,l]=t.useState([]),[R,D]=t.useState(""),ee=async()=>{try{const r=await ye.getAccounts();c(r?.list||[])}catch(r){console.error("加载云账号失败:",r)}};t.useEffect(()=>{s&&(ee(),kr(async()=>{const{credentialApi:r}=await import("./index-CHhHmizP.js");return{credentialApi:r}},__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12]),import.meta.url).then(({credentialApi:r})=>{r.list().then(E=>l(E?.list||[])).catch(()=>l([]))}))},[s]);const M=a.filter(r=>r.provider===b&&r.status==="active"),te=t.useCallback(async r=>{try{return(await ye.getAccountRegions(r))?.list||[]}catch{return[]}},[]),G=t.useCallback(async r=>{f(!0);try{await ye.syncRegions(r);const E=await te(r);I(E)}catch(E){throw console.error("同步区域失败:",E),E}finally{f(!1)}},[te]),P=t.useCallback(async()=>{if(!x)return;const r=await te(x.id);if(I(r),r.length===0)try{await G(x.id)}catch{}},[x,te,G]),K=t.useCallback(async()=>{if(!(!x||n.length===0)){d(!0),_([]),v([]),z([]);try{const r=await ye.discoverInstances(x.id,n);v(r?.list||[]),_(r?.errors||[])}catch(r){console.error("发现主机失败:",r),_([r?.message||"发现主机失败"])}finally{d(!1)}}},[x,n]),oe=async()=>{if(!(!x||k.length===0)){W(!0);try{const r=h.filter(ne=>k.includes(ne.instance_id)),E=await ye.importInstances(x.id,r,{default_port:Number(Q)||22,credential_id:R?Number(R):void 0});U(E||{imported:0,skipped:0})}catch(r){console.error("导入失败:",r)}finally{W(!1)}}},ve=()=>{o===2&&x&&o<4?(i(3),P()):o<4&&i(o+1)},ce=()=>{o>1&&i(o-1)},he=()=>{n.length===N.length&&N.length>0?y([]):y(N.map(r=>r.code))},Ve=r=>{z(E=>E.includes(r)?E.filter(ne=>ne!==r):[...E,r])},Pe=()=>{k.length===h.length&&h.length>0?z([]):z(h.map(r=>r.instance_id))},be=()=>{m(),i(1),j(""),w(null),y([]),I([]),v([]),z([]),T(""),_([]),U(null),Z("22"),D("")},We=N.filter(r=>!F||r.name?.toLowerCase().includes(F.toLowerCase())||r.code?.toLowerCase().includes(F.toLowerCase())),Ae=[{id:1,title:"公有云",icon:xr},{id:2,title:"访问凭据",icon:$e},{id:3,title:"选择区域",icon:Ge},{id:4,title:"导入确认",icon:ar}];return e.jsx(Te,{"code-path":"src/components/server/CloudServerImport.tsx:232:5",open:s,onOpenChange:be,children:e.jsxs(Re,{"code-path":"src/components/server/CloudServerImport.tsx:233:7",className:"max-w-3xl bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:[e.jsxs(Ue,{"code-path":"src/components/server/CloudServerImport.tsx:234:9",children:[e.jsx(Me,{"code-path":"src/components/server/CloudServerImport.tsx:235:11",className:"text-xl",children:"导入云主机"}),e.jsx(Be,{"code-path":"src/components/server/CloudServerImport.tsx:236:11",className:"sr-only",children:"从云平台批量导入主机资产"})]}),e.jsx("div",{"code-path":"src/components/server/CloudServerImport.tsx:240:9",className:"flex items-center justify-center mb-6 flex-wrap gap-1",children:Ae.map((r,E)=>e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:242:13",className:"flex items-center",children:[e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:243:15",className:`flex items-center gap-2 px-3 py-2 rounded-lg text-sm ${o===r.id?"bg-blue-600 text-white":o>r.id?"bg-emerald-600/20 text-emerald-400":"bg-[var(--dg-bg-secondary)] text-[var(--dg-text-muted)]"}`,children:[e.jsx(r.icon,{"code-path":"src/components/server/CloudServerImport.tsx:250:17",className:"h-4 w-4"}),e.jsx("span",{"code-path":"src/components/server/CloudServerImport.tsx:251:17",className:"font-medium hidden sm:inline",children:r.title}),o>r.id&&e.jsx(ge,{"code-path":"src/components/server/CloudServerImport.tsx:252:33",className:"h-3 w-3 ml-1"})]}),Ee.jsx(me,{"code-path":"src/components/server/CloudServerImport.tsx:267:17",className:`cursor-pointer transition-all ${b===r.id?"border-blue-500 ring-2 ring-blue-500/30 bg-[var(--dg-bg-secondary)]":"border-[var(--dg-border)] hover:border-blue-500 bg-[var(--dg-bg-secondary)]"}`,onClick:()=>j(r.id),children:e.jsxs(xe,{"code-path":"src/components/server/CloudServerImport.tsx:276:19",className:"p-4 flex items-center gap-3",children:[e.jsx("div",{"code-path":"src/components/server/CloudServerImport.tsx:277:21",className:`w-10 h-10 rounded-lg ${r.color} flex items-center justify-center text-white font-bold text-sm`,children:r.icon}),e.jsx("span",{"code-path":"src/components/server/CloudServerImport.tsx:280:21",className:"font-medium text-[var(--dg-text-primary)]",children:r.name})]})},r.id))})]}),o===2&&e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:290:11",className:"space-y-4",children:[e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:291:13",className:"text-[var(--dg-text-secondary)] text-sm",children:"请选择访问凭据(AccessKey)"}),M.length>0?e.jsx("div",{"code-path":"src/components/server/CloudServerImport.tsx:293:15",className:"space-y-2 max-h-[300px] overflow-y-auto",children:M.map(r=>e.jsx(me,{"code-path":"src/components/server/CloudServerImport.tsx:295:19",className:`cursor-pointer transition-all ${x?.id===r.id?"border-blue-500 ring-1 ring-blue-500/30 bg-[var(--dg-bg-secondary)]":"border-[var(--dg-border)] hover:border-blue-500 bg-[var(--dg-bg-secondary)]"}`,onClick:()=>w(r),children:e.jsxs(xe,{"code-path":"src/components/server/CloudServerImport.tsx:304:21",className:"p-3 flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:305:23",className:"flex items-center gap-3",children:[e.jsx($e,{"code-path":"src/components/server/CloudServerImport.tsx:306:25",className:"h-5 w-5 text-blue-400"}),e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:307:25",children:[e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:308:27",className:"font-medium text-[var(--dg-text-primary)]",children:r.name}),e.jsxs("p",{"code-path":"src/components/server/CloudServerImport.tsx:309:27",className:"text-xs text-[var(--dg-text-muted)]",children:[(r.access_key||r.accessKey||"******").slice(0,20),"..."]})]})]}),e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:314:23",className:"text-right",children:[e.jsxs(A,{"code-path":"src/components/server/CloudServerImport.tsx:315:25",className:"bg-emerald-500/20 text-emerald-400 border-0",children:[r.region_count??r.regionCount??0," 区域"]}),e.jsxs("p",{"code-path":"src/components/server/CloudServerImport.tsx:318:25",className:"text-xs text-[var(--dg-text-muted)] mt-1",children:[r.server_count??r.serverCount??0," 服务器"]})]})]})},r.id))}):e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:325:15",className:"text-center py-8 text-[var(--dg-text-muted)]",children:[e.jsx($e,{"code-path":"src/components/server/CloudServerImport.tsx:326:17",className:"h-12 w-12 mx-auto mb-3 opacity-50"}),e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:327:17",children:"该云平台暂无有效的访问凭据"})]})]}),o===3&&e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:335:11",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:336:13",className:"flex items-center justify-between",children:[e.jsxs("p",{"code-path":"src/components/server/CloudServerImport.tsx:337:15",className:"text-[var(--dg-text-secondary)] text-sm",children:["请选择要同步的区域",N.length>0&&e.jsxs("span",{"code-path":"src/components/server/CloudServerImport.tsx:340:19",className:"ml-2 text-[var(--dg-text-muted)]",children:["(共 ",N.length," 个区域,已选 ",n.length," 个)"]})]}),e.jsxs(g,{"code-path":"src/components/server/CloudServerImport.tsx:343:15",variant:"outline",size:"sm",className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",onClick:()=>x&&G(x.id),disabled:u,children:[e.jsx(pe,{"code-path":"src/components/server/CloudServerImport.tsx:350:17",className:`h-3 w-3 mr-1 ${u?"animate-spin":""}`}),u?"同步中...":"刷新区域"]})]}),u?e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:356:15",className:"text-center py-12",children:[e.jsx(pe,{"code-path":"src/components/server/CloudServerImport.tsx:357:17",className:"h-8 w-8 mx-auto mb-3 animate-spin text-blue-400"}),e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:358:17",className:"text-[var(--dg-text-secondary)]",children:"正在从云平台同步区域列表..."})]}):N.length===0?e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:361:15",className:"text-center py-8 text-[var(--dg-text-muted)]",children:[e.jsx(Ge,{"code-path":"src/components/server/CloudServerImport.tsx:362:17",className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:363:17",children:"暂无区域数据"}),e.jsxs(g,{"code-path":"src/components/server/CloudServerImport.tsx:364:17",variant:"outline",size:"sm",className:"mt-3 border-[var(--dg-border)] text-blue-400",onClick:()=>x&&G(x.id),children:[e.jsx(pe,{"code-path":"src/components/server/CloudServerImport.tsx:370:19",className:"h-3 w-3 mr-1"}),"立即同步"]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:377:17",className:"flex items-center gap-2",children:[e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:378:19",className:"relative flex-1",children:[e.jsx(ir,{"code-path":"src/components/server/CloudServerImport.tsx:379:21",className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-[var(--dg-text-muted)]"}),e.jsx(H,{"code-path":"src/components/server/CloudServerImport.tsx:380:21",placeholder:"搜索区域名称或编码...",value:F,onChange:r=>T(r.target.value),className:"pl-9 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]"})]}),e.jsx(g,{"code-path":"src/components/server/CloudServerImport.tsx:387:19",variant:"outline",size:"sm",onClick:he,className:"border-[var(--dg-border)]",children:n.length===N.length&&N.length>0?"取消全选":"全选"})]}),e.jsx("div",{"code-path":"src/components/server/CloudServerImport.tsx:393:17",className:"border rounded-lg border-[var(--dg-border)] overflow-hidden max-h-[300px] overflow-y-auto",children:e.jsxs("table",{"code-path":"src/components/server/CloudServerImport.tsx:394:19",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/server/CloudServerImport.tsx:395:21",className:"bg-[var(--dg-bg-secondary)] sticky top-0",children:e.jsxs("tr",{"code-path":"src/components/server/CloudServerImport.tsx:396:23",children:[e.jsx("th",{"code-path":"src/components/server/CloudServerImport.tsx:397:25",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)] w-10",children:e.jsx(ue,{"code-path":"src/components/server/CloudServerImport.tsx:398:27",checked:n.length===N.length&&N.length>0,onCheckedChange:he})}),e.jsx("th",{"code-path":"src/components/server/CloudServerImport.tsx:403:25",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]",children:"区域编码"}),e.jsx("th",{"code-path":"src/components/server/CloudServerImport.tsx:404:25",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]",children:"区域名称"}),e.jsx("th",{"code-path":"src/components/server/CloudServerImport.tsx:405:25",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]",children:"Endpoint"})]})}),e.jsx("tbody",{"code-path":"src/components/server/CloudServerImport.tsx:408:21",className:"divide-y divide-[var(--dg-border)]",children:We.map(r=>e.jsxs("tr",{"code-path":"src/components/server/CloudServerImport.tsx:410:25",className:`cursor-pointer hover:bg-[var(--dg-bg-hover)] ${n.includes(r.code)?"bg-blue-500/10":""}`,onClick:()=>{y(E=>E.includes(r.code)?E.filter(ne=>ne!==r.code):[...E,r.code])},children:[e.jsx("td",{"code-path":"src/components/server/CloudServerImport.tsx:421:27",className:"px-3 py-2",children:e.jsx(ue,{"code-path":"src/components/server/CloudServerImport.tsx:422:29",checked:n.includes(r.code)})}),e.jsx("td",{"code-path":"src/components/server/CloudServerImport.tsx:424:27",className:"px-3 py-2 text-sm text-blue-400 font-mono",children:r.code}),e.jsx("td",{"code-path":"src/components/server/CloudServerImport.tsx:425:27",className:"px-3 py-2 text-sm text-[var(--dg-text-primary)]",children:r.name}),e.jsx("td",{"code-path":"src/components/server/CloudServerImport.tsx:426:27",className:"px-3 py-2 text-xs text-[var(--dg-text-muted)] font-mono truncate max-w-[200px]",children:r.endpoint||"-"})]},r.id||r.code))})]})})]})]}),o===4&&e.jsx("div",{"code-path":"src/components/server/CloudServerImport.tsx:439:11",className:"space-y-4",children:B?e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:442:15",className:"text-center py-12",children:[e.jsx(ar,{"code-path":"src/components/server/CloudServerImport.tsx:443:17",className:"h-12 w-12 mx-auto mb-3 text-emerald-400"}),e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:444:17",className:"text-lg font-medium text-[var(--dg-text-primary)]",children:"导入完成"}),e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:445:17",className:"flex items-center justify-center gap-6 mt-4",children:[e.jsxs(A,{"code-path":"src/components/server/CloudServerImport.tsx:446:19",className:"bg-emerald-500/20 text-emerald-400 border-0 text-base px-4 py-1",children:["成功导入 ",B.imported," 台"]}),B.skipped>0&&e.jsxs(A,{"code-path":"src/components/server/CloudServerImport.tsx:450:21",className:"bg-amber-500/20 text-amber-400 border-0 text-base px-4 py-1",children:["跳过 ",B.skipped," 台(已存在)"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:458:17",className:"flex items-center justify-between",children:[e.jsxs("p",{"code-path":"src/components/server/CloudServerImport.tsx:459:19",className:"text-[var(--dg-text-secondary)] text-sm",children:["已选 ",n.length," 个区域",h.length>0&&e.jsxs("span",{"code-path":"src/components/server/CloudServerImport.tsx:462:23",className:"ml-2",children:["· 发现 ",h.length," 台主机"]})]}),e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:465:19",className:"flex items-center gap-2",children:[h.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(g,{"code-path":"src/components/server/CloudServerImport.tsx:468:25",variant:"outline",size:"sm",onClick:Pe,className:"border-[var(--dg-border)]",children:k.length===h.length&&h.length>0?"取消全选":"全选"}),e.jsxs(A,{"code-path":"src/components/server/CloudServerImport.tsx:471:25",className:"bg-blue-500/20 text-blue-400 border-0",children:["已选 ",k.length," 台"]})]}),e.jsxs(g,{"code-path":"src/components/server/CloudServerImport.tsx:476:21",variant:"outline",size:"sm",onClick:K,disabled:$||n.length===0,className:"border-[var(--dg-border)] text-blue-400",children:[e.jsx(pe,{"code-path":"src/components/server/CloudServerImport.tsx:483:23",className:`h-3 w-3 mr-1 ${$?"animate-spin":""}`}),$?"发现中...":h.length>0?"重新发现":"发现主机"]})]})]}),e.jsx("div",{"code-path":"src/components/server/CloudServerImport.tsx:490:17",className:"flex flex-wrap gap-1",children:n.map(r=>{const E=N.find(ne=>ne.code===r);return e.jsxs(A,{"code-path":"src/components/server/CloudServerImport.tsx:494:23",className:"bg-[var(--dg-bg-secondary)] text-[var(--dg-text-muted)] border border-[var(--dg-border)] text-xs",children:[e.jsx(Ge,{"code-path":"src/components/server/CloudServerImport.tsx:495:25",className:"h-3 w-3 mr-1"}),E?.name||r]},r)})}),S.length>0&&e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:504:19",className:"flex items-start gap-2 p-3 rounded-lg bg-amber-500/10 border border-amber-500/30 text-amber-400 text-sm",children:[e.jsx(Oe,{"code-path":"src/components/server/CloudServerImport.tsx:505:21",className:"h-4 w-4 mt-0.5 flex-shrink-0"}),e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:506:21",children:[e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:507:23",className:"font-medium",children:"部分区域发现失败:"}),S.map((r,E)=>e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:509:25",className:"text-xs mt-1 opacity-80",children:r},E))]})]}),$?e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:517:19",className:"text-center py-12",children:[e.jsx(pe,{"code-path":"src/components/server/CloudServerImport.tsx:518:21",className:"h-8 w-8 mx-auto mb-3 animate-spin text-blue-400"}),e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:519:21",className:"text-[var(--dg-text-secondary)]",children:"正在发现云主机,请稍候..."}),e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:520:21",className:"text-xs text-[var(--dg-text-muted)] mt-1",children:"正在逐区域查询,可能需要数秒"})]}):h.length===0&&!$?e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:523:19",className:"text-center py-8 text-[var(--dg-text-muted)]",children:[e.jsx(Ee,{"code-path":"src/components/server/CloudServerImport.tsx:524:21",className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{"code-path":"src/components/server/CloudServerImport.tsx:525:21",children:'点击"发现主机"按钮,开始扫描所选区域'})]}):e.jsx("div",{"code-path":"src/components/server/CloudServerImport.tsx:528:19",className:"border rounded-lg border-[var(--dg-border)] overflow-hidden max-h-[300px] overflow-y-auto",children:e.jsxs("table",{"code-path":"src/components/server/CloudServerImport.tsx:529:21",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/server/CloudServerImport.tsx:530:23",className:"bg-[var(--dg-bg-secondary)] sticky top-0",children:e.jsxs("tr",{"code-path":"src/components/server/CloudServerImport.tsx:531:25",children:[e.jsx("th",{"code-path":"src/components/server/CloudServerImport.tsx:532:27",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)] w-10",children:e.jsx(ue,{"code-path":"src/components/server/CloudServerImport.tsx:533:29",checked:k.length===h.length&&h.length>0,onCheckedChange:Pe})}),e.jsx("th",{"code-path":"src/components/server/CloudServerImport.tsx:538:27",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]",children:"主机名"}),e.jsx("th",{"code-path":"src/components/server/CloudServerImport.tsx:539:27",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]",children:"IP地址"})]})}),e.jsx("tbody",{"code-path":"src/components/server/CloudServerImport.tsx:542:23",className:"divide-y divide-[var(--dg-border)]",children:h.map(r=>e.jsxs("tr",{"code-path":"src/components/server/CloudServerImport.tsx:544:27",className:`cursor-pointer hover:bg-[var(--dg-bg-hover)] ${k.includes(r.instance_id)?"bg-blue-500/10":""}`,onClick:()=>Ve(r.instance_id),children:[e.jsx("td",{"code-path":"src/components/server/CloudServerImport.tsx:549:29",className:"px-3 py-2",children:e.jsx(ue,{"code-path":"src/components/server/CloudServerImport.tsx:550:31",checked:k.includes(r.instance_id)})}),e.jsx("td",{"code-path":"src/components/server/CloudServerImport.tsx:552:29",className:"px-3 py-2 text-sm text-[var(--dg-text-primary)]",children:r.instance_name||r.hostname||"-"}),e.jsx("td",{"code-path":"src/components/server/CloudServerImport.tsx:553:29",className:"px-3 py-2 text-sm text-[var(--dg-text-secondary)]",children:r.private_ip||r.public_ip||"-"})]},r.instance_id))})]})}),h.length>0&&k.length>0&&e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:565:19",className:"grid grid-cols-2 gap-4 p-4 rounded-lg bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)]",children:[e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:566:21",children:[e.jsxs("label",{"code-path":"src/components/server/CloudServerImport.tsx:567:23",className:"block text-xs font-medium text-[var(--dg-text-secondary)] mb-1",children:["SSH 端口",e.jsx("span",{"code-path":"src/components/server/CloudServerImport.tsx:569:25",className:"text-[var(--dg-text-muted)] ml-1",children:"(导入时统一设置)"})]}),e.jsx(H,{"code-path":"src/components/server/CloudServerImport.tsx:571:23",type:"number",placeholder:"22",value:Q,onChange:r=>Z(r.target.value),className:"w-32 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]}),e.jsxs("div",{"code-path":"src/components/server/CloudServerImport.tsx:579:21",children:[e.jsxs("label",{"code-path":"src/components/server/CloudServerImport.tsx:580:23",className:"block text-xs font-medium text-[var(--dg-text-secondary)] mb-1",children:["关联凭证",e.jsx("span",{"code-path":"src/components/server/CloudServerImport.tsx:582:25",className:"text-[var(--dg-text-muted)] ml-1",children:"(可选,用于SSH远程管理)"})]}),e.jsxs("select",{"code-path":"src/components/server/CloudServerImport.tsx:584:23",value:R,onChange:r=>D(r.target.value),className:"w-full px-3 py-1.5 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-md text-[var(--dg-text-primary)] text-xs",children:[e.jsx("option",{"code-path":"src/components/server/CloudServerImport.tsx:589:25",value:"",children:"不使用凭据"}),ie.map(r=>e.jsxs("option",{"code-path":"src/components/server/CloudServerImport.tsx:591:27",value:String(r.id),children:[r.type==="ssh_key"?"🔑":"🔒"," ",r.name]},r.id))]})]})]})]})}),e.jsxs(Je,{"code-path":"src/components/server/CloudServerImport.tsx:605:9",className:"flex justify-between items-center",children:[e.jsx("div",{"code-path":"src/components/server/CloudServerImport.tsx:606:11",children:o>1&&!B&&e.jsxs(g,{"code-path":"src/components/server/CloudServerImport.tsx:608:15",variant:"outline",onClick:ce,className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",children:[e.jsx(er,{"code-path":"src/components/server/CloudServerImport.tsx:609:17",className:"h-4 w-4 mr-1"}),"上一步"]})}),e.jsx("div",{"code-path":"src/components/server/CloudServerImport.tsx:614:11",className:"flex gap-2",children:B?e.jsx(g,{"code-path":"src/components/server/CloudServerImport.tsx:616:15",onClick:be,className:"bg-blue-600 hover:bg-blue-700",children:"完成"}):e.jsxs(e.Fragment,{children:[e.jsx(g,{"code-path":"src/components/server/CloudServerImport.tsx:621:17",variant:"outline",onClick:be,className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",children:"取消"}),o<4?e.jsxs(g,{"code-path":"src/components/server/CloudServerImport.tsx:625:19",onClick:ve,disabled:o===1&&!b||o===2&&!x||o===3&&n.length===0,className:"bg-blue-600 hover:bg-blue-700",children:["下一步",e.jsx(_e,{"code-path":"src/components/server/CloudServerImport.tsx:635:21",className:"h-4 w-4 ml-1"})]}):e.jsx(g,{"code-path":"src/components/server/CloudServerImport.tsx:638:19",onClick:oe,disabled:k.length===0||J,className:"bg-emerald-600 hover:bg-emerald-700",children:J?e.jsxs(e.Fragment,{children:[e.jsx(pe,{"code-path":"src/components/server/CloudServerImport.tsx:645:25",className:"h-4 w-4 mr-1 animate-spin"}),"导入中..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ge,{"code-path":"src/components/server/CloudServerImport.tsx:650:25",className:"h-4 w-4 mr-1"}),"确认导入 (",k.length,")"]})})]})})]})]})})}function xs({open:s,onOpenChange:m,serverId:a,serverName:c,serverIp:o,hasAuth:i=!0}){const b=t.useRef(null),j=t.useRef(null),x=t.useRef(null),w=t.useRef(null),[N,I]=t.useState(!1),[n,y]=t.useState(!1),[F,T]=t.useState([]),[u,f]=t.useState(""),[h,v]=t.useState(!1),[k,z]=t.useState(i);t.useEffect(()=>{!s||i||jr.list().then(d=>T(d?.list||[])).catch(()=>{})},[s,i]);const $=async()=>{if(!(!u||!a))try{v(!0),await Kr.assign(a,Number(u)),V.success("凭据已关联"),z(!0)}catch(d){V.error(d?.message||"关联失败")}finally{v(!1)}};return t.useEffect(()=>{s||(z(i),f(""))},[s,i]),t.useEffect(()=>{if(!s||!a||!k)return;const d=new Wr.Terminal({cursorBlink:!0,fontSize:13,fontFamily:'Menlo, Monaco, "Courier New", monospace',allowProposedApi:!0,theme:{background:"#0a0e14",foreground:"#d6d6d6",cursor:"#d6d6d6",selectionBackground:"rgba(255,255,255,0.2)"}}),S=new Gr.FitAddon;d.loadAddon(S),j.current=d,w.current=S;const _=location.protocol==="https:"?"wss":"ws",J=vr.getState().token||"",W=`${_}://${location.host}/ws/terminal?id=${a}&cols=80&rows=24&token=${encodeURIComponent(J)}`,B=new WebSocket(W);return x.current=B,d.onData(U=>{B.readyState===WebSocket.OPEN&&B.send(JSON.stringify({status:0,data:U}))}),B.onmessage=U=>{try{const Q=JSON.parse(U.data);Q.status===0&&typeof Q.data=="string"&&d.write(Q.data)}catch{d.write(typeof U.data=="string"?U.data:"")}},B.onopen=()=>{I(!0),b.current&&(d.open(b.current),requestAnimationFrame(()=>{try{S.fit(),d.focus()}catch{}}))},B.onclose=()=>{I(!1),d.write(`\r +\x1B[31m[连接已关闭]\x1B[0m\r +`)},B.onerror=()=>{d.write(`\r +\x1B[31m[连接发生错误]\x1B[0m\r +`)},()=>{try{B.close(),d.dispose()}catch{}j.current=null,x.current=null,I(!1)}},[s,a,k]),t.useEffect(()=>{if(!s)return;const d=b.current;if(!d)return;let S;const _=new ResizeObserver(()=>{clearTimeout(S),S=setTimeout(()=>{if(w.current&&j.current&&x.current)try{w.current.fit(),j.current.focus();const{cols:J,rows:W}=j.current;x.current.readyState===WebSocket.OPEN&&x.current.send(JSON.stringify({status:1,cols:J,rows:W}))}catch{}},60)});return _.observe(d),()=>{clearTimeout(S),_.disconnect()}},[s]),e.jsx(Te,{"code-path":"src/components/server/TerminalDialog.tsx:196:5",open:s,onOpenChange:m,children:e.jsxs(Re,{"code-path":"src/components/server/TerminalDialog.tsx:197:7",showCloseButton:!1,className:Se("bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] p-0 gap-0","!duration-0 !transition-none",n?"!max-w-none !w-screen !h-screen !rounded-none !translate-x-0 !translate-y-0 !left-0 !top-0":""),style:n?{maxWidth:"100vw",width:"100vw",height:"100vh"}:{maxWidth:"900px",width:"90vw"},children:[e.jsxs(Me,{"code-path":"src/components/server/TerminalDialog.tsx:209:9",className:"sr-only",children:["终端 - ",c]}),e.jsx(Be,{"code-path":"src/components/server/TerminalDialog.tsx:210:9",className:"sr-only",children:"SSH 终端连接"}),e.jsxs("div",{"code-path":"src/components/server/TerminalDialog.tsx:212:9",className:"flex items-center justify-between px-4 py-2 border-b border-[var(--dg-border)]",children:[e.jsxs("div",{"code-path":"src/components/server/TerminalDialog.tsx:213:11",className:"flex items-center gap-2 text-sm",children:[e.jsx("div",{"code-path":"src/components/server/TerminalDialog.tsx:214:13",className:Se("w-2 h-2 rounded-full",N?"bg-emerald-400":"bg-red-400")}),e.jsx("span",{"code-path":"src/components/server/TerminalDialog.tsx:215:13",className:"text-[var(--dg-text-primary)] font-medium",children:c}),e.jsxs("span",{"code-path":"src/components/server/TerminalDialog.tsx:216:13",className:"text-[var(--dg-text-muted)]",children:["(",o,")"]})]}),e.jsxs("div",{"code-path":"src/components/server/TerminalDialog.tsx:218:11",className:"flex items-center gap-1",children:[e.jsx("button",{"code-path":"src/components/server/TerminalDialog.tsx:219:13",onClick:()=>y(!n),className:"p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]",children:n?e.jsx(qr,{"code-path":"src/components/server/TerminalDialog.tsx:223:29",className:"h-4 w-4"}):e.jsx(Jr,{"code-path":"src/components/server/TerminalDialog.tsx:223:65",className:"h-4 w-4"})}),e.jsx("button",{"code-path":"src/components/server/TerminalDialog.tsx:225:13",onClick:()=>m(!1),className:"p-1.5 rounded hover:bg-[var(--dg-bg-hover)] text-[var(--dg-text-secondary)]",children:e.jsx(fe,{"code-path":"src/components/server/TerminalDialog.tsx:229:15",className:"h-4 w-4"})})]})]}),!k&&e.jsxs("div",{"code-path":"src/components/server/TerminalDialog.tsx:235:11",className:"p-6 flex flex-col items-center justify-center gap-4",style:{height:"480px"},children:[e.jsx(hr,{"code-path":"src/components/server/TerminalDialog.tsx:236:13",className:"h-12 w-12 text-amber-400"}),e.jsxs("div",{"code-path":"src/components/server/TerminalDialog.tsx:237:13",className:"text-center",children:[e.jsx("p",{"code-path":"src/components/server/TerminalDialog.tsx:238:15",className:"text-[var(--dg-text-primary)] font-medium mb-1",children:"服务器未配置认证凭据"}),e.jsx("p",{"code-path":"src/components/server/TerminalDialog.tsx:239:15",className:"text-sm text-[var(--dg-text-muted)]",children:"请选择一个凭据用于 SSH 连接"})]}),F.length===0?e.jsx("p",{"code-path":"src/components/server/TerminalDialog.tsx:242:15",className:"text-xs text-[var(--dg-text-muted)]",children:"暂无可用凭据,请先去「凭证配置」添加"}):e.jsxs("select",{"code-path":"src/components/server/TerminalDialog.tsx:244:15",value:u,onChange:d=>f(d.target.value),className:"w-64 px-3 py-2 bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)] rounded-md text-[var(--dg-text-primary)] text-sm",children:[e.jsx("option",{"code-path":"src/components/server/TerminalDialog.tsx:249:17",value:"",children:"-- 选择凭据 --"}),F.map(d=>e.jsxs("option",{"code-path":"src/components/server/TerminalDialog.tsx:251:19",value:String(d.id),children:[d.type==="ssh_key"?"🔑":"🔒"," ",d.name]},d.id))]}),e.jsx(g,{"code-path":"src/components/server/TerminalDialog.tsx:257:13",onClick:$,disabled:!u||h,className:"bg-[var(--dg-blue)] hover:opacity-90 text-white",children:h?"关联中...":"确认连接"})]}),k&&e.jsx("div",{"code-path":"src/components/server/TerminalDialog.tsx:268:11",ref:b,className:"bg-[#0a0e14]",style:{height:n?"calc(100vh - 49px)":"480px"}})]})})}const is=s=>s<1024?`${s} B`:s<1048576?`${(s/1024).toFixed(1)} KB`:`${(s/1048576).toFixed(2)} MB`;function vs({open:s,onOpenChange:m,serverId:a,serverName:c}){const[o,i]=t.useState([]),[b,j]=t.useState([]),[x,w]=t.useState("/"),[N,I]=t.useState(!1),[n,y]=t.useState(""),[F,T]=t.useState(!1),u=t.useRef(null),f=t.useCallback(async d=>{if(a){I(!0),y("");try{const S=await se.listFiles(a,d),_=S?.data||S;i(_.items||[]),j(_.breadcrumbs||[]),w(_.path||d)}catch(S){y(S?.message||"加载目录失败"),i([])}finally{I(!1)}}},[a]);t.useEffect(()=>{s&&a&&f("/")},[s,a,f]);const h=async d=>{if(a)try{await se.downloadFile(a,d)}catch{}},v=async d=>{const S=d.target.files?.[0];if(!(!S||!a)){T(!0);try{await se.uploadFile(a,x,S),await f(x)}catch(_){y(_?.message||"上传失败")}finally{T(!1),u.current&&(u.current.value="")}}},k=async(d,S)=>{if(!(!a||!confirm(`确认删除 ${S?"目录":"文件"} "${d}"?`)))try{await se.deleteFile(a,d),await f(x)}catch(_){y(_?.message||"删除失败")}},z=async()=>{const d=prompt("输入目录名:");if(!d||!a)return;const S=x==="/"?`/${d}`:`${x}/${d}`;try{await se.mkdir(a,S),await f(x)}catch(_){y(_?.message||"创建失败")}},$=[...o].sort((d,S)=>d.is_dir!==S.is_dir?d.is_dir?-1:1:d.name.localeCompare(S.name));return e.jsx(Te,{"code-path":"src/components/server/ServerFileBrowser.tsx:142:5",open:s,onOpenChange:m,children:e.jsxs(Re,{"code-path":"src/components/server/ServerFileBrowser.tsx:143:7",showOverlay:!1,className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-w-[95vw] max-h-[90vh] w-[900px]",children:[e.jsxs(Ue,{"code-path":"src/components/server/ServerFileBrowser.tsx:144:9",children:[e.jsxs(Me,{"code-path":"src/components/server/ServerFileBrowser.tsx:145:11",className:"text-[var(--dg-text-primary)] flex items-center gap-2",children:[e.jsx(Nr,{"code-path":"src/components/server/ServerFileBrowser.tsx:146:13",className:"h-5 w-5 text-[var(--dg-blue)]"}),"文件浏览 — ",c]}),e.jsx(Be,{"code-path":"src/components/server/ServerFileBrowser.tsx:149:11",className:"text-[var(--dg-text-secondary)]",children:"SFTP 文件管理 · 上传 · 下载 · 删除"})]}),e.jsxs("div",{"code-path":"src/components/server/ServerFileBrowser.tsx:155:9",className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(g,{"code-path":"src/components/server/ServerFileBrowser.tsx:156:11",variant:"outline",size:"sm",className:"border-[var(--dg-border)]",onClick:()=>f(x),children:[e.jsx(pe,{"code-path":"src/components/server/ServerFileBrowser.tsx:158:13",className:"h-3.5 w-3.5 mr-1"}),"刷新"]}),e.jsxs("label",{"code-path":"src/components/server/ServerFileBrowser.tsx:160:11",children:[e.jsxs(g,{"code-path":"src/components/server/ServerFileBrowser.tsx:161:13",variant:"outline",size:"sm",className:"border-[var(--dg-border)] cursor-pointer",onClick:()=>u.current?.click(),disabled:F,children:[F?e.jsx(Le,{"code-path":"src/components/server/ServerFileBrowser.tsx:163:28",className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(Xe,{"code-path":"src/components/server/ServerFileBrowser.tsx:163:84",className:"h-3.5 w-3.5 mr-1"}),"上传"]}),e.jsx("input",{"code-path":"src/components/server/ServerFileBrowser.tsx:166:13",ref:u,type:"file",className:"hidden",onChange:v})]}),e.jsxs(g,{"code-path":"src/components/server/ServerFileBrowser.tsx:168:11",variant:"outline",size:"sm",className:"border-[var(--dg-border)]",onClick:z,children:[e.jsx(cs,{"code-path":"src/components/server/ServerFileBrowser.tsx:170:13",className:"h-3.5 w-3.5 mr-1"}),"新建目录"]}),n&&e.jsxs(A,{"code-path":"src/components/server/ServerFileBrowser.tsx:173:13",variant:"outline",className:"border-red-500/30 text-red-400 ml-auto",children:[e.jsx(fe,{"code-path":"src/components/server/ServerFileBrowser.tsx:174:15",className:"h-3 w-3 mr-1 cursor-pointer",onClick:()=>y("")}),n]})]}),e.jsx("div",{"code-path":"src/components/server/ServerFileBrowser.tsx:181:9",className:"flex items-center gap-0.5 text-sm flex-wrap bg-[var(--dg-bg-tertiary)] rounded-md p-1.5 border border-[var(--dg-border)]",children:b.map((d,S)=>e.jsxs("span",{"code-path":"src/components/server/ServerFileBrowser.tsx:183:13",className:"flex items-center gap-0.5",children:[S>0&&e.jsx(_e,{"code-path":"src/components/server/ServerFileBrowser.tsx:184:25",className:"h-3 w-3 text-[var(--dg-text-muted)]"}),e.jsx("button",{"code-path":"src/components/server/ServerFileBrowser.tsx:185:15",onClick:()=>f(d.path),className:"text-[var(--dg-blue)] hover:underline px-0.5",children:d.name})]},d.path))}),e.jsx("div",{"code-path":"src/components/server/ServerFileBrowser.tsx:196:9",className:"border border-[var(--dg-border)] rounded-md overflow-hidden",style:{maxHeight:"50vh",overflowY:"auto"},children:N?e.jsx("div",{"code-path":"src/components/server/ServerFileBrowser.tsx:198:13",className:"flex items-center justify-center py-16",children:e.jsx(Le,{"code-path":"src/components/server/ServerFileBrowser.tsx:199:15",className:"h-6 w-6 animate-spin text-[var(--dg-blue)]"})}):$.length===0?e.jsxs("div",{"code-path":"src/components/server/ServerFileBrowser.tsx:202:13",className:"flex flex-col items-center justify-center py-16 text-[var(--dg-text-muted)]",children:[e.jsx(nr,{"code-path":"src/components/server/ServerFileBrowser.tsx:203:15",className:"h-10 w-10 mb-2 opacity-30"}),e.jsx("p",{"code-path":"src/components/server/ServerFileBrowser.tsx:204:15",className:"text-sm",children:"空目录"})]}):e.jsxs("table",{"code-path":"src/components/server/ServerFileBrowser.tsx:207:13",className:"w-full text-sm",children:[e.jsx("thead",{"code-path":"src/components/server/ServerFileBrowser.tsx:208:15",children:e.jsxs("tr",{"code-path":"src/components/server/ServerFileBrowser.tsx:209:17",className:"border-b border-[var(--dg-border)] bg-[var(--dg-bg-tertiary)]",children:[e.jsx("th",{"code-path":"src/components/server/ServerFileBrowser.tsx:210:19",className:"text-left p-2.5 text-[var(--dg-text-muted)] font-medium w-8"}),e.jsx("th",{"code-path":"src/components/server/ServerFileBrowser.tsx:211:19",className:"text-left p-2.5 text-[var(--dg-text-muted)] font-medium",children:"名称"}),e.jsx("th",{"code-path":"src/components/server/ServerFileBrowser.tsx:212:19",className:"text-right p-2.5 text-[var(--dg-text-muted)] font-medium w-28",children:"大小"}),e.jsx("th",{"code-path":"src/components/server/ServerFileBrowser.tsx:213:19",className:"text-left p-2.5 text-[var(--dg-text-muted)] font-medium w-44",children:"修改时间"}),e.jsx("th",{"code-path":"src/components/server/ServerFileBrowser.tsx:214:19",className:"text-left p-2.5 text-[var(--dg-text-muted)] font-medium w-24",children:"权限"}),e.jsx("th",{"code-path":"src/components/server/ServerFileBrowser.tsx:215:19",className:"text-center p-2.5 text-[var(--dg-text-muted)] font-medium w-28",children:"操作"})]})}),e.jsxs("tbody",{"code-path":"src/components/server/ServerFileBrowser.tsx:218:15",children:[x!=="/"&&e.jsxs("tr",{"code-path":"src/components/server/ServerFileBrowser.tsx:220:19",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)] cursor-pointer",onClick:()=>{const d=x.split("/").slice(0,-1).join("/")||"/";f(d)},children:[e.jsx("td",{"code-path":"src/components/server/ServerFileBrowser.tsx:225:21",className:"p-2.5",children:e.jsx(Xr,{"code-path":"src/components/server/ServerFileBrowser.tsx:225:43",className:"h-4 w-4 text-[var(--dg-text-muted)]"})}),e.jsx("td",{"code-path":"src/components/server/ServerFileBrowser.tsx:226:21",className:"p-2.5 text-[var(--dg-text-muted)]",colSpan:5,children:".."})]}),$.map(d=>e.jsxs("tr",{"code-path":"src/components/server/ServerFileBrowser.tsx:230:19",className:"border-b border-[var(--dg-border)] hover:bg-[var(--dg-bg-hover)]",children:[e.jsx("td",{"code-path":"src/components/server/ServerFileBrowser.tsx:233:21",className:"p-2.5",children:d.is_dir?e.jsx(nr,{"code-path":"src/components/server/ServerFileBrowser.tsx:235:25",className:"h-4 w-4 text-[var(--dg-yellow)]"}):e.jsx(Qr,{"code-path":"src/components/server/ServerFileBrowser.tsx:237:25",className:"h-4 w-4 text-[var(--dg-text-muted)]"})}),e.jsx("td",{"code-path":"src/components/server/ServerFileBrowser.tsx:240:21",className:"p-2.5",children:d.is_dir?e.jsx("button",{"code-path":"src/components/server/ServerFileBrowser.tsx:242:25",onClick:()=>f(d.path),className:"text-[var(--dg-blue)] hover:underline font-medium",children:d.name}):e.jsx("span",{"code-path":"src/components/server/ServerFileBrowser.tsx:249:25",className:"text-[var(--dg-text-primary)]",children:d.name})}),e.jsx("td",{"code-path":"src/components/server/ServerFileBrowser.tsx:252:21",className:"p-2.5 text-right text-[var(--dg-text-muted)]",children:d.is_dir?"—":is(d.size)}),e.jsx("td",{"code-path":"src/components/server/ServerFileBrowser.tsx:255:21",className:"p-2.5 text-[var(--dg-text-muted)]",children:d.mod_time}),e.jsx("td",{"code-path":"src/components/server/ServerFileBrowser.tsx:256:21",className:"p-2.5 text-[var(--dg-text-muted)] font-mono text-xs",children:d.mode}),e.jsx("td",{"code-path":"src/components/server/ServerFileBrowser.tsx:257:21",className:"p-2.5",children:e.jsxs("div",{"code-path":"src/components/server/ServerFileBrowser.tsx:258:23",className:"flex items-center justify-center gap-1",children:[!d.is_dir&&e.jsx(g,{"code-path":"src/components/server/ServerFileBrowser.tsx:260:27",variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>h(d.path),title:"下载",children:e.jsx(Ye,{"code-path":"src/components/server/ServerFileBrowser.tsx:263:29",className:"h-3.5 w-3.5"})}),e.jsx(g,{"code-path":"src/components/server/ServerFileBrowser.tsx:266:25",variant:"ghost",size:"icon",className:"h-7 w-7 text-red-400 hover:text-red-300",onClick:()=>k(d.path,d.is_dir),title:"删除",children:e.jsx(Ze,{"code-path":"src/components/server/ServerFileBrowser.tsx:270:27",className:"h-3.5 w-3.5"})})]})})]},d.path))]})]})})]})})}function lr(s){const m=[];let a="",c=!1;for(let o=0;oo.trim())}function hs(s){const m=s.replace(/\r\n/g,` +`).replace(/\r/g,` +`).split(` +`).filter(o=>o.trim());if(m.length<2)return[];const a=lr(m[0]).map(o=>o.toLowerCase()),c=[];for(let o=1;o{b[j]=i[x]??""}),c.push(b)}return c}function gs(s){return/^(\d{1,3}\.){3}\d{1,3}$/.test(s)&&s.split(".").every(m=>Number(m)>=0&&Number(m)<=255)}function us(){const s=["hostname,ip,port","web-01,192.168.1.10,22","db-01,192.168.1.20,22","cache-01,192.168.1.30,2222"].join(` +`),m=new Blob(["\uFEFF"+s],{type:"text/csv;charset=utf-8;"}),a=URL.createObjectURL(m),c=document.createElement("a");c.href=a,c.download="servers-template.csv",c.click(),URL.revokeObjectURL(a)}function Ss({open:s,onClose:m}){const[a,c]=t.useState(1),[o,i]=t.useState(""),[,b]=t.useState("password"),[j,x]=t.useState(null),[w,N]=t.useState(!1),[I,n]=t.useState([]),[y,F]=t.useState([]),[T,u]=t.useState(!1),[f,h]=t.useState([]),[v,k]=t.useState(""),[z,$]=t.useState("22");t.useEffect(()=>{if(!s)return;let l=!1;return(async()=>{try{const[R,D]=await Promise.all([Dr.list(),jr.list()]);if(l)return;const ee=R?.list??[];F(ee.map(M=>({id:String(M.id??""),name:M.name??"",code:M.code??""}))),h(D?.list??[])}catch{l||(F([]),h([]))}})(),()=>{l=!0}},[s]);const d=async()=>{if(a===2&&j){N(!0);try{const l=await j.text(),R=hs(l);if(R.length===0){V.error("文件无有效数据,请使用模板格式(首行为表头)"),N(!1);return}const D=new Set,ee=R.map((M,te)=>{const G=(M.hostname??"").trim(),P=(M.ip??"").trim(),K={row:te+2,hostname:G,ip:P,port:Number(M.port)||22,username:(M.username??"").trim()||"root",os:M.os??"",cpu:Number(M.cpu)||0,memory:Number(M.memory)||0,disk:Number(M.disk)||0,tags:M.tags??"",status:"valid",message:"有效"},oe=[];G||oe.push("主机名缺失"),P?gs(P)||oe.push("IP格式错误"):oe.push("IP缺失");const ve=`${G}|${P}`;return G&&P&&D.has(ve)?oe.push("重复行"):D.add(ve),oe.length>0&&(K.status="error",K.message=oe.join("、")),K});n(ee),c(a+1)}catch{V.error("文件解析失败,请确认是 CSV 格式")}finally{N(!1)}}else c(a+1)},S=()=>{a>1&&c(a-1)},_=l=>{l.target.files&&l.target.files[0]&&x(l.target.files[0])},J=()=>{c(1),i(""),$("22"),k(""),x(null),n([])},W=async()=>{const l=I.filter(R=>R.status==="valid");if(l.length!==0){u(!0);try{const R=l.map(P=>({hostname:P.hostname,ip:P.ip,port:P.port,username:P.username,os:P.os,cpu:P.cpu,memory:P.memory,disk:P.disk,tags:P.tags})),ee=await se.batchCreate({servers:R,region_id:o||void 0,credential_id:v?Number(v):void 0,default_port:Number(z)||22})??{},M=ee.success??0,te=ee.skipped??0,G=ee.failed??0;V.success(`导入完成:成功 ${M},跳过 ${te},失败 ${G}`),J(),m()}catch(R){V.error(R?.message||"导入失败,请重试")}finally{u(!1)}}},B=()=>{m(),J()},U=I.filter(l=>l.status==="valid").length,Q=I.filter(l=>l.status==="warning").length,Z=I.filter(l=>l.status==="error").length,ie=[{id:1,title:"配置"},{id:2,title:"上传"},{id:3,title:"确认"}];return e.jsx(Te,{"code-path":"src/components/server/ExcelServerImport.tsx:278:5",open:s,onOpenChange:B,children:e.jsxs(Re,{"code-path":"src/components/server/ExcelServerImport.tsx:279:7",className:"max-w-3xl bg-[var(--dg-bg-primary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:[e.jsxs(Ue,{"code-path":"src/components/server/ExcelServerImport.tsx:280:9",children:[e.jsx(Me,{"code-path":"src/components/server/ExcelServerImport.tsx:281:11",className:"text-xl",children:"CSV 批量导入服务器"}),e.jsx(Be,{"code-path":"src/components/server/ExcelServerImport.tsx:282:11",className:"sr-only",children:"通过 CSV 文件批量导入服务器资产"})]}),e.jsx("div",{"code-path":"src/components/server/ExcelServerImport.tsx:286:9",className:"flex items-center justify-center mb-6",children:ie.map((l,R)=>e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:288:13",className:"flex items-center",children:[e.jsx("div",{"code-path":"src/components/server/ExcelServerImport.tsx:289:15",className:`flex items-center justify-center w-8 h-8 rounded-full ${a===l.id?"bg-blue-600 text-white":a>l.id?"bg-emerald-600 text-white":"bg-[var(--dg-bg-secondary)] text-[var(--dg-text-muted)]"}`,children:a>l.id?e.jsx(ge,{"code-path":"src/components/server/ExcelServerImport.tsx:296:32",className:"h-4 w-4"}):l.id}),e.jsx("span",{"code-path":"src/components/server/ExcelServerImport.tsx:298:15",className:`ml-2 text-sm ${a===l.id?"text-[var(--dg-text-primary)]":"text-[var(--dg-text-muted)]"}`,children:l.title}),Ri(l.target.value),className:"w-full px-3 py-2 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-md text-[var(--dg-text-primary)] text-sm",children:[e.jsx("option",{"code-path":"src/components/server/ExcelServerImport.tsx:340:17",value:"",children:"请选择区域"}),y.map(l=>e.jsxs("option",{"code-path":"src/components/server/ExcelServerImport.tsx:342:19",value:l.id,children:[l.name," (",l.code,")"]},l.id))]})]}),e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:350:13",children:[e.jsxs("label",{"code-path":"src/components/server/ExcelServerImport.tsx:351:15",className:"block text-sm font-medium text-[var(--dg-text-secondary)] mb-2",children:["选择凭据",e.jsx("span",{"code-path":"src/components/server/ExcelServerImport.tsx:353:17",className:"text-xs text-[var(--dg-text-muted)] ml-1",children:"(可选,用于SSH连接)"})]}),f.length===0?e.jsx("p",{"code-path":"src/components/server/ExcelServerImport.tsx:356:17",className:"text-xs text-[var(--dg-text-muted)] py-2",children:"暂无凭据,先去「凭证配置」添加 SSH 密钥或密码"}):e.jsxs("select",{"code-path":"src/components/server/ExcelServerImport.tsx:360:17",value:v,onChange:l=>k(l.target.value),className:"w-full px-3 py-2 bg-[var(--dg-bg-secondary)] border border-[var(--dg-border)] rounded-md text-[var(--dg-text-primary)] text-sm",children:[e.jsx("option",{"code-path":"src/components/server/ExcelServerImport.tsx:365:19",value:"",children:"不使用凭据(后续手动配置)"}),f.map(l=>e.jsxs("option",{"code-path":"src/components/server/ExcelServerImport.tsx:367:21",value:String(l.id),children:[l.type==="ssh_key"?"🔑":l.type==="api_token"?"🌐":"🔒"," ",l.name," (",l.type==="ssh_key"?"SSH密钥":l.type==="api_token"?"API Token":"密码",")"]},l.id))]})]}),e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:376:13",children:[e.jsxs("label",{"code-path":"src/components/server/ExcelServerImport.tsx:377:15",className:"block text-sm font-medium text-[var(--dg-text-secondary)] mb-2",children:["SSH 端口",e.jsx("span",{"code-path":"src/components/server/ExcelServerImport.tsx:379:17",className:"text-xs text-[var(--dg-text-muted)] ml-1",children:"(导入时统一设置,可在服务器管理页单独修改)"})]}),e.jsx(H,{"code-path":"src/components/server/ExcelServerImport.tsx:381:15",type:"number",placeholder:"22",value:z,onChange:l=>$(l.target.value),className:"w-32 bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]"})]})]}),a===2&&e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:394:11",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:395:13",className:"border-2 border-dashed border-[var(--dg-border)] rounded-lg p-8 text-center hover:border-blue-500/50 transition-colors",children:[e.jsx(Xe,{"code-path":"src/components/server/ExcelServerImport.tsx:398:15",className:"h-12 w-12 mx-auto mb-4 text-[var(--dg-text-muted)]"}),e.jsx("p",{"code-path":"src/components/server/ExcelServerImport.tsx:399:15",className:"text-[var(--dg-text-secondary)] mb-2",children:"点击或拖拽文件到此处上传"}),e.jsx("p",{"code-path":"src/components/server/ExcelServerImport.tsx:400:15",className:"text-xs text-[var(--dg-text-muted)] mb-4",children:'支持 CSV 格式文件(可点击左侧"下载模板"获取)'}),e.jsx(H,{"code-path":"src/components/server/ExcelServerImport.tsx:401:15",type:"file",accept:".csv,text/csv",onChange:_,className:"hidden",id:"excel-upload"}),e.jsx("label",{"code-path":"src/components/server/ExcelServerImport.tsx:408:15",htmlFor:"excel-upload",children:e.jsx(g,{"code-path":"src/components/server/ExcelServerImport.tsx:409:17",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",asChild:!0,children:e.jsx("span",{"code-path":"src/components/server/ExcelServerImport.tsx:410:19",children:"选择文件"})})})]}),j&&e.jsx(me,{"code-path":"src/components/server/ExcelServerImport.tsx:416:15",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(xe,{"code-path":"src/components/server/ExcelServerImport.tsx:417:17",className:"p-3 flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:418:19",className:"flex items-center gap-3",children:[e.jsx(qe,{"code-path":"src/components/server/ExcelServerImport.tsx:419:21",className:"h-8 w-8 text-emerald-400"}),e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:420:21",children:[e.jsx("p",{"code-path":"src/components/server/ExcelServerImport.tsx:421:23",className:"text-sm text-[var(--dg-text-primary)]",children:j.name}),e.jsxs("p",{"code-path":"src/components/server/ExcelServerImport.tsx:422:23",className:"text-xs text-[var(--dg-text-muted)]",children:[(j.size/1024).toFixed(2)," KB"]})]})]}),e.jsx(g,{"code-path":"src/components/server/ExcelServerImport.tsx:425:19",variant:"ghost",size:"icon",className:"text-[var(--dg-text-muted)] hover:text-red-400",onClick:()=>x(null),children:e.jsx(fe,{"code-path":"src/components/server/ExcelServerImport.tsx:431:21",className:"h-4 w-4"})})]})}),w&&e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:438:15",className:"text-center py-4",children:[e.jsx("div",{"code-path":"src/components/server/ExcelServerImport.tsx:439:17",className:"w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin mx-auto mb-2"}),e.jsx("p",{"code-path":"src/components/server/ExcelServerImport.tsx:440:17",className:"text-[var(--dg-text-secondary)] text-sm",children:"正在解析文件..."})]})]}),a===3&&e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:448:11",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:449:13",className:"flex items-center justify-between",children:[e.jsx("p",{"code-path":"src/components/server/ExcelServerImport.tsx:450:15",className:"text-[var(--dg-text-secondary)] text-sm",children:"数据预览"}),e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:451:15",className:"flex items-center gap-2",children:[e.jsxs(A,{"code-path":"src/components/server/ExcelServerImport.tsx:452:17",className:"bg-emerald-500/20 text-emerald-400 border-0",children:[e.jsx(ge,{"code-path":"src/components/server/ExcelServerImport.tsx:453:19",className:"h-3 w-3 mr-1"}),U," 有效"]}),Q>0&&e.jsxs(A,{"code-path":"src/components/server/ExcelServerImport.tsx:457:19",className:"bg-amber-500/20 text-amber-400 border-0",children:[e.jsx(Oe,{"code-path":"src/components/server/ExcelServerImport.tsx:458:21",className:"h-3 w-3 mr-1"}),Q," 警告"]}),Z>0&&e.jsxs(A,{"code-path":"src/components/server/ExcelServerImport.tsx:463:19",className:"bg-red-500/20 text-red-400 border-0",children:[e.jsx(fe,{"code-path":"src/components/server/ExcelServerImport.tsx:464:21",className:"h-3 w-3 mr-1"}),Z," 错误"]})]})]}),e.jsx("div",{"code-path":"src/components/server/ExcelServerImport.tsx:471:13",className:"border rounded-lg border-[var(--dg-border)] overflow-hidden max-h-[350px] overflow-y-auto",children:e.jsxs("table",{"code-path":"src/components/server/ExcelServerImport.tsx:472:15",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/server/ExcelServerImport.tsx:473:17",className:"bg-[var(--dg-bg-secondary)] sticky top-0",children:e.jsxs("tr",{"code-path":"src/components/server/ExcelServerImport.tsx:474:19",children:[e.jsx("th",{"code-path":"src/components/server/ExcelServerImport.tsx:475:21",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]",children:"行号"}),e.jsx("th",{"code-path":"src/components/server/ExcelServerImport.tsx:476:21",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]",children:"主机名"}),e.jsx("th",{"code-path":"src/components/server/ExcelServerImport.tsx:477:21",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]",children:"IP地址"}),e.jsx("th",{"code-path":"src/components/server/ExcelServerImport.tsx:478:21",className:"px-3 py-2 text-left text-xs font-medium text-[var(--dg-text-secondary)]",children:"状态"})]})}),e.jsx("tbody",{"code-path":"src/components/server/ExcelServerImport.tsx:481:17",className:"divide-y divide-[var(--dg-border)]",children:I.map(l=>e.jsxs("tr",{"code-path":"src/components/server/ExcelServerImport.tsx:483:21",className:"hover:bg-[var(--dg-bg-hover)]",children:[e.jsx("td",{"code-path":"src/components/server/ExcelServerImport.tsx:484:23",className:"px-3 py-2 text-sm text-[var(--dg-text-muted)]",children:l.row}),e.jsx("td",{"code-path":"src/components/server/ExcelServerImport.tsx:485:23",className:"px-3 py-2 text-sm text-[var(--dg-text-primary)]",children:l.hostname||"-"}),e.jsx("td",{"code-path":"src/components/server/ExcelServerImport.tsx:486:23",className:"px-3 py-2 text-sm text-[var(--dg-text-secondary)]",children:l.ip}),e.jsx("td",{"code-path":"src/components/server/ExcelServerImport.tsx:487:23",className:"px-3 py-2",children:e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:488:25",className:"flex items-center gap-1",children:[l.status==="valid"&&e.jsxs(A,{"code-path":"src/components/server/ExcelServerImport.tsx:490:29",className:"bg-emerald-500/20 text-emerald-400 border-0 text-xs",children:[e.jsx(ge,{"code-path":"src/components/server/ExcelServerImport.tsx:491:31",className:"h-3 w-3 mr-1"}),l.message]}),l.status==="warning"&&e.jsxs(A,{"code-path":"src/components/server/ExcelServerImport.tsx:496:29",className:"bg-amber-500/20 text-amber-400 border-0 text-xs",children:[e.jsx(Oe,{"code-path":"src/components/server/ExcelServerImport.tsx:497:31",className:"h-3 w-3 mr-1"}),l.message]}),l.status==="error"&&e.jsxs(A,{"code-path":"src/components/server/ExcelServerImport.tsx:502:29",className:"bg-red-500/20 text-red-400 border-0 text-xs",children:[e.jsx(fe,{"code-path":"src/components/server/ExcelServerImport.tsx:503:31",className:"h-3 w-3 mr-1"}),l.message]})]})})]},l.row))})]})}),Z>0&&e.jsx("div",{"code-path":"src/components/server/ExcelServerImport.tsx:516:15",className:"p-3 rounded-lg bg-red-500/10 border border-red-500/30",children:e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:517:17",className:"flex items-center gap-2 text-red-400",children:[e.jsx(Oe,{"code-path":"src/components/server/ExcelServerImport.tsx:518:19",className:"h-4 w-4"}),e.jsxs("span",{"code-path":"src/components/server/ExcelServerImport.tsx:519:19",className:"text-sm",children:["存在 ",Z," 条错误数据,请修正后重新上传"]})]})})]}),e.jsxs(Je,{"code-path":"src/components/server/ExcelServerImport.tsx:527:9",className:"flex justify-between items-center",children:[e.jsx("div",{"code-path":"src/components/server/ExcelServerImport.tsx:528:11",children:a>1&&e.jsxs(g,{"code-path":"src/components/server/ExcelServerImport.tsx:530:15",variant:"outline",onClick:S,className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",children:[e.jsx(er,{"code-path":"src/components/server/ExcelServerImport.tsx:531:17",className:"h-4 w-4 mr-1"}),"上一步"]})}),e.jsxs("div",{"code-path":"src/components/server/ExcelServerImport.tsx:536:11",className:"flex gap-2",children:[e.jsx(g,{"code-path":"src/components/server/ExcelServerImport.tsx:537:13",variant:"outline",onClick:B,className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)]",children:"取消"}),a<3?e.jsxs(g,{"code-path":"src/components/server/ExcelServerImport.tsx:541:15",onClick:d,disabled:a===1&&!o||a===2&&!j,className:"bg-blue-600 hover:bg-blue-700",children:["下一步",e.jsx(_e,{"code-path":"src/components/server/ExcelServerImport.tsx:547:17",className:"h-4 w-4 ml-1"})]}):e.jsxs(g,{"code-path":"src/components/server/ExcelServerImport.tsx:550:15",onClick:W,disabled:T||Z>0||U===0,className:"bg-emerald-600 hover:bg-emerald-700",children:[T?e.jsx(Le,{"code-path":"src/components/server/ExcelServerImport.tsx:556:19",className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ge,{"code-path":"src/components/server/ExcelServerImport.tsx:558:19",className:"h-4 w-4 mr-1"}),T?"导入中...":`确认导入 (${U})`]})]})]})]})})}var De="Collapsible",[bs]=_r(De),[js,rr]=bs(De),yr=t.forwardRef((s,m)=>{const{__scopeCollapsible:a,open:c,defaultOpen:o,disabled:i,onOpenChange:b,...j}=s,[x,w]=Er({prop:c,defaultProp:o??!1,onChange:b,caller:De});return e.jsx(js,{scope:a,disabled:i,contentId:Tr(),open:x,onOpenToggle:t.useCallback(()=>w(N=>!N),[w]),children:e.jsx(Qe.div,{"data-state":tr(x),"data-disabled":i?"":void 0,...j,ref:m})})});yr.displayName=De;var fr="CollapsibleTrigger",wr=t.forwardRef((s,m)=>{const{__scopeCollapsible:a,...c}=s,o=rr(fr,a);return e.jsx(Qe.button,{type:"button","aria-controls":o.contentId,"aria-expanded":o.open||!1,"data-state":tr(o.open),"data-disabled":o.disabled?"":void 0,disabled:o.disabled,...c,ref:m,onClick:Rr(s.onClick,o.onOpenToggle)})});wr.displayName=fr;var sr="CollapsibleContent",Cr=t.forwardRef((s,m)=>{const{forceMount:a,...c}=s,o=rr(sr,s.__scopeCollapsible);return e.jsx(Mr,{present:a||o.open,children:({present:i})=>e.jsx(Ns,{...c,ref:m,present:i})})});Cr.displayName=sr;var Ns=t.forwardRef((s,m)=>{const{__scopeCollapsible:a,present:c,children:o,...i}=s,b=rr(sr,a),[j,x]=t.useState(c),w=t.useRef(null),N=Br(m,w),I=t.useRef(0),n=I.current,y=t.useRef(0),F=y.current,T=b.open||j,u=t.useRef(T),f=t.useRef(void 0);return t.useEffect(()=>{const h=requestAnimationFrame(()=>u.current=!1);return()=>cancelAnimationFrame(h)},[]),Pr(()=>{const h=w.current;if(h){f.current=f.current||{transitionDuration:h.style.transitionDuration,animationName:h.style.animationName},h.style.transitionDuration="0s",h.style.animationName="none";const v=h.getBoundingClientRect();I.current=v.height,y.current=v.width,u.current||(h.style.transitionDuration=f.current.transitionDuration,h.style.animationName=f.current.animationName),x(c)}},[b.open,c]),e.jsx(Qe.div,{"data-state":tr(b.open),"data-disabled":b.disabled?"":void 0,id:b.contentId,hidden:!T,...i,ref:N,style:{"--radix-collapsible-content-height":n?`${n}px`:void 0,"--radix-collapsible-content-width":F?`${F}px`:void 0,...s.style},children:T&&o})});function tr(s){return s?"open":"closed"}var ys=yr;function fs({...s}){return e.jsx(ys,{"code-path":"src/components/ui/collapsible.tsx:6:10","data-slot":"collapsible",...s})}function ws({...s}){return e.jsx(wr,{"code-path":"src/components/ui/collapsible.tsx:13:5","data-slot":"collapsible-trigger",...s})}function Cs({...s}){return e.jsx(Cr,{"code-path":"src/components/ui/collapsible.tsx:24:5","data-slot":"collapsible-content",...s})}const pr={hostname:"",ip:"",public_ip:"",port:"22",username:"root",auth_type:"password",password:"",ssh_key:"",credential_id:null,os:"",cpu:"",memory:"",disk:"",status:"running",tags:"",description:""};function Is({open:s,onOpenChange:m,editingId:a,formData:c,setFormData:o,detailsOpen:i,setDetailsOpen:b,onSave:j,formSaving:x}){const[w,N]=t.useState([]);t.useEffect(()=>{s&&Ar.get("/credentials").then(n=>{const y=Array.isArray(n)?n:n?.data||[];N(y)}).catch(()=>N([]))},[s]);const I=n=>{const y=Number(n);if(!y){o({...c,credential_id:null});return}const F=w.find(T=>T.id===y);F&&o({...c,credential_id:y,username:F.username||"root",auth_type:F.auth_type||"password",password:"",ssh_key:""})};return e.jsx(Te,{"code-path":"src/components/server/ServerForm.tsx:135:5",open:s,onOpenChange:m,children:e.jsxs(Re,{"code-path":"src/components/server/ServerForm.tsx:136:7",className:"max-w-2xl bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Ue,{"code-path":"src/components/server/ServerForm.tsx:137:9",children:[e.jsxs(Me,{"code-path":"src/components/server/ServerForm.tsx:138:11",className:"text-[var(--dg-text-primary)] flex items-center gap-2",children:[e.jsx(Ee,{"code-path":"src/components/server/ServerForm.tsx:139:13",className:"h-5 w-5 text-[var(--dg-blue)]"}),a?"编辑服务器":"添加服务器"]}),e.jsx(Be,{"code-path":"src/components/server/ServerForm.tsx:142:11",className:"text-[var(--dg-text-muted)]",children:a?"修改服务器资产信息":"录入新的服务器资产到 CMDB"})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:147:9",className:"space-y-4 py-2",children:[e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:149:11",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:150:13",className:"space-y-1.5",children:[e.jsxs(L,{"code-path":"src/components/server/ServerForm.tsx:151:15",className:"text-[var(--dg-text-secondary)]",children:["主机名 ",e.jsx("span",{"code-path":"src/components/server/ServerForm.tsx:152:21",className:"text-red-400",children:"*"})]}),e.jsx(H,{"code-path":"src/components/server/ServerForm.tsx:154:15",placeholder:"web-server-01",value:c.hostname,onChange:n=>o({...c,hostname:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:161:13",className:"space-y-1.5",children:[e.jsxs(L,{"code-path":"src/components/server/ServerForm.tsx:162:15",className:"text-[var(--dg-text-secondary)]",children:["IP地址 ",e.jsx("span",{"code-path":"src/components/server/ServerForm.tsx:163:22",className:"text-red-400",children:"*"})]}),e.jsx(H,{"code-path":"src/components/server/ServerForm.tsx:165:15",placeholder:"10.0.0.1",value:c.ip,onChange:n=>o({...c,ip:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:175:11",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:176:13",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:177:15",className:"text-[var(--dg-text-secondary)]",children:"公网IP"}),e.jsx(H,{"code-path":"src/components/server/ServerForm.tsx:178:15",placeholder:"如 203.0.113.10",value:c.public_ip,onChange:n=>o({...c,public_ip:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:185:13",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:186:15",className:"text-[var(--dg-text-secondary)]",children:"SSH端口"}),e.jsx(H,{"code-path":"src/components/server/ServerForm.tsx:187:15",type:"number",placeholder:"22",value:c.port,onChange:n=>o({...c,port:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:198:11",className:"space-y-1.5",children:[e.jsxs(L,{"code-path":"src/components/server/ServerForm.tsx:199:13",className:"text-[var(--dg-text-secondary)] flex items-center gap-1.5",children:[e.jsx($e,{"code-path":"src/components/server/ServerForm.tsx:200:15",className:"h-3.5 w-3.5"})," SSH 凭证",!a&&!c.credential_id&&e.jsx("span",{"code-path":"src/components/server/ServerForm.tsx:201:57",className:"text-red-400 ml-1",children:"*"})]}),e.jsxs(Ce,{"code-path":"src/components/server/ServerForm.tsx:203:13",value:c.credential_id?String(c.credential_id):"",onValueChange:I,children:[e.jsx(Ie,{"code-path":"src/components/server/ServerForm.tsx:207:15",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(Fe,{"code-path":"src/components/server/ServerForm.tsx:208:17",placeholder:"选择已有凭证..."})}),e.jsxs(ke,{"code-path":"src/components/server/ServerForm.tsx:210:15",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]",children:[e.jsx(O,{"code-path":"src/components/server/ServerForm.tsx:211:17",value:"__manual",children:"手动输入(不关联凭证)"}),w.map(n=>e.jsx(O,{"code-path":"src/components/server/ServerForm.tsx:213:19",value:String(n.id),children:e.jsxs("span",{"code-path":"src/components/server/ServerForm.tsx:214:21",className:"flex items-center gap-2",children:[e.jsx(hr,{"code-path":"src/components/server/ServerForm.tsx:215:23",className:"h-3 w-3 text-blue-400"}),n.name," (",n.username,"@",n.auth_type==="key"?"密钥":"密码",")"]})},n.id))]})]}),c.credential_id&&e.jsx("p",{"code-path":"src/components/server/ServerForm.tsx:223:15",className:"text-[10px] text-green-400/70",children:"已关联凭证,登录信息从凭证自动获取"})]}),!c.credential_id&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:230:15",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:231:17",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:232:19",className:"text-[var(--dg-text-secondary)]",children:"登录用户"}),e.jsx(H,{"code-path":"src/components/server/ServerForm.tsx:233:19",placeholder:"root",value:c.username,onChange:n=>o({...c,username:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:240:17",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:241:19",className:"text-[var(--dg-text-secondary)]",children:"认证方式"}),e.jsxs(Ce,{"code-path":"src/components/server/ServerForm.tsx:242:19",value:c.auth_type,onValueChange:n=>o({...c,auth_type:n}),children:[e.jsx(Ie,{"code-path":"src/components/server/ServerForm.tsx:246:21",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(Fe,{"code-path":"src/components/server/ServerForm.tsx:247:23"})}),e.jsxs(ke,{"code-path":"src/components/server/ServerForm.tsx:249:21",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]",children:[e.jsx(O,{"code-path":"src/components/server/ServerForm.tsx:250:23",value:"password",children:"密码认证"}),e.jsx(O,{"code-path":"src/components/server/ServerForm.tsx:251:23",value:"key",children:"密钥认证"})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:257:15",className:"space-y-1.5",children:[e.jsxs(L,{"code-path":"src/components/server/ServerForm.tsx:258:17",className:"text-[var(--dg-text-secondary)]",children:[c.auth_type==="key"?"SSH 私钥":"登录密码",!a&&e.jsx("span",{"code-path":"src/components/server/ServerForm.tsx:260:34",className:"text-red-400 ml-1",children:"*"}),a&&e.jsx("span",{"code-path":"src/components/server/ServerForm.tsx:261:33",className:"text-[var(--dg-text-muted)] ml-1 text-xs",children:"(留空则不修改)"})]}),e.jsx(dr,{"code-path":"src/components/server/ServerForm.tsx:263:17",placeholder:c.auth_type==="key"?"粘贴 SSH 私钥内容...":"输入登录密码...",value:c.password,onChange:n=>o({...c,password:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] min-h-[50px] font-mono text-sm"})]})]}),e.jsxs(fs,{"code-path":"src/components/server/ServerForm.tsx:274:11",open:i,onOpenChange:b,children:[e.jsx(ws,{"code-path":"src/components/server/ServerForm.tsx:275:13",asChild:!0,children:e.jsxs(g,{"code-path":"src/components/server/ServerForm.tsx:276:15",variant:"ghost",size:"sm",className:"w-full justify-between text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-tertiary)] border border-[var(--dg-border)]",children:[e.jsxs("span",{"code-path":"src/components/server/ServerForm.tsx:281:17",className:"flex items-center gap-2",children:[e.jsx(Ee,{"code-path":"src/components/server/ServerForm.tsx:282:19",className:"h-4 w-4"}),"更多详情(OS版本 / 运行状态 / CPU / 内存 / 磁盘 / 标签 / 描述)"]}),e.jsx($r,{"code-path":"src/components/server/ServerForm.tsx:285:17",className:Se("h-4 w-4 transition-transform",i&&"rotate-180")})]})}),e.jsxs(Cs,{"code-path":"src/components/server/ServerForm.tsx:288:13",className:"space-y-4 pt-4",children:[e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:289:15",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:290:17",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:291:19",className:"text-[var(--dg-text-secondary)]",children:"操作系统"}),e.jsx(H,{"code-path":"src/components/server/ServerForm.tsx:292:19",placeholder:"如 CentOS 7.9",value:c.os,onChange:n=>o({...c,os:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:299:17",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:300:19",className:"text-[var(--dg-text-secondary)]",children:"运行状态"}),e.jsxs(Ce,{"code-path":"src/components/server/ServerForm.tsx:301:19",value:c.status,onValueChange:n=>o({...c,status:n}),children:[e.jsx(Ie,{"code-path":"src/components/server/ServerForm.tsx:305:21",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(Fe,{"code-path":"src/components/server/ServerForm.tsx:306:23"})}),e.jsxs(ke,{"code-path":"src/components/server/ServerForm.tsx:308:21",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]",children:[e.jsx(O,{"code-path":"src/components/server/ServerForm.tsx:309:23",value:"running",children:"运行中"}),e.jsx(O,{"code-path":"src/components/server/ServerForm.tsx:310:23",value:"stopped",children:"已停止"}),e.jsx(O,{"code-path":"src/components/server/ServerForm.tsx:311:23",value:"maintenance",children:"维护中"}),e.jsx(O,{"code-path":"src/components/server/ServerForm.tsx:312:23",value:"offline",children:"离线"})]})]})]})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:317:15",className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:318:17",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:319:19",className:"text-[var(--dg-text-secondary)]",children:"CPU核数"}),e.jsx(H,{"code-path":"src/components/server/ServerForm.tsx:320:19",type:"number",placeholder:"4",value:c.cpu,onChange:n=>o({...c,cpu:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:328:17",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:329:19",className:"text-[var(--dg-text-secondary)]",children:"内存 (GB)"}),e.jsx(H,{"code-path":"src/components/server/ServerForm.tsx:330:19",type:"number",placeholder:"8",value:c.memory,onChange:n=>o({...c,memory:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:338:17",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:339:19",className:"text-[var(--dg-text-secondary)]",children:"磁盘 (GB)"}),e.jsx(H,{"code-path":"src/components/server/ServerForm.tsx:340:19",type:"number",placeholder:"100",value:c.disk,onChange:n=>o({...c,disk:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:349:15",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:350:17",className:"text-[var(--dg-text-secondary)]",children:"标签"}),e.jsx(H,{"code-path":"src/components/server/ServerForm.tsx:351:17",placeholder:'JSON 格式,如 {"project":"web","team":"ops"}',value:c.tags,onChange:n=>o({...c,tags:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] font-mono text-sm"})]}),e.jsxs("div",{"code-path":"src/components/server/ServerForm.tsx:358:15",className:"space-y-1.5",children:[e.jsx(L,{"code-path":"src/components/server/ServerForm.tsx:359:17",className:"text-[var(--dg-text-secondary)]",children:"描述"}),e.jsx(dr,{"code-path":"src/components/server/ServerForm.tsx:360:17",placeholder:"补充说明...",value:c.description,onChange:n=>o({...c,description:n.target.value}),className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)] min-h-[60px]"})]})]})]})]}),e.jsxs(Je,{"code-path":"src/components/server/ServerForm.tsx:371:9",children:[e.jsx(g,{"code-path":"src/components/server/ServerForm.tsx:372:11",variant:"outline",onClick:()=>m(!1),className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:bg-[var(--dg-bg-hover)] hover:text-[var(--dg-text-primary)]",children:"取消"}),e.jsxs(g,{"code-path":"src/components/server/ServerForm.tsx:379:11",onClick:j,disabled:!c.hostname||!c.ip||x,className:"bg-[var(--dg-blue)] hover:opacity-90 text-white",children:[x?e.jsx(Le,{"code-path":"src/components/server/ServerForm.tsx:385:15",className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Yr,{"code-path":"src/components/server/ServerForm.tsx:387:15",className:"h-4 w-4 mr-2"}),a?"保存修改":"创建"]})]})]})})}function Ir(s){const m=s.tags;if(!m)return[];if(Array.isArray(m))return m;try{const a=JSON.parse(m);return Array.isArray(a)?a:typeof a=="object"&&a!==null?Object.entries(a).map(([c,o])=>`${c}:${String(o)}`):[String(a)]}catch{return String(m).split(",").map(a=>a.trim()).filter(Boolean)}}function Fs(s){switch(s){case"running":return e.jsxs(A,{"code-path":"src/components/server/serverHelpers.tsx:31:9",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:[e.jsx("div",{"code-path":"src/components/server/serverHelpers.tsx:32:11",className:"w-1.5 h-1.5 rounded-full bg-emerald-400 mr-1.5 animate-pulse"}),"运行中"]});case"stopped":return e.jsx(A,{"code-path":"src/components/server/serverHelpers.tsx:38:9",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-muted)] bg-[var(--dg-bg-tertiary)]",children:"已停止"});case"maintenance":return e.jsxs(A,{"code-path":"src/components/server/serverHelpers.tsx:44:9",variant:"outline",className:"border-amber-500/30 text-amber-400 bg-amber-500/10",children:[e.jsx("div",{"code-path":"src/components/server/serverHelpers.tsx:45:11",className:"w-1.5 h-1.5 rounded-full bg-amber-400 mr-1.5"}),"维护中"]});case"offline":return e.jsx(A,{"code-path":"src/components/server/serverHelpers.tsx:51:9",variant:"outline",className:"border-red-500/30 text-red-400 bg-red-500/10",children:"离线"});default:return null}}function mr(s){return s>80?"bg-red-400":s>60?"bg-amber-400":"bg-emerald-400"}function ks({server:s,selected:m,onToggleSelect:a,onOpenTerminal:c,onOpenEdit:o,onOpenFiles:i,onDelete:b}){const j=Number(s.cpu_usage||0),x=Number(s.memory_usage||0),w=Ir(s),N=s.memory?Math.round(s.memory/1024):0,I=s.tcp_established||0,n=s.tcp_time_wait||0;s.net_rx_bps,s.net_tx_bps;const y=s.disk_read_bps||0,F=s.disk_write_bps||0,T=u=>u>=1e6?(u/1e6).toFixed(1)+"MB/s":u>=1e3?(u/1e3).toFixed(1)+"KB/s":u.toFixed(0)+"B/s";return e.jsxs(ze,{"code-path":"src/components/server/ServerTableRow.tsx:56:5",className:"border-[var(--dg-border)] hover:bg-[var(--dg-bg-tertiary)]/50",children:[e.jsx(re,{"code-path":"src/components/server/ServerTableRow.tsx:57:7",children:e.jsx(ue,{"code-path":"src/components/server/ServerTableRow.tsx:58:9",checked:m,onCheckedChange:()=>a(s.id),className:"border-[var(--dg-border)]"})}),e.jsx(re,{"code-path":"src/components/server/ServerTableRow.tsx:64:7",children:e.jsxs("div",{"code-path":"src/components/server/ServerTableRow.tsx:65:9",className:"flex items-center gap-2",children:[e.jsx(Ee,{"code-path":"src/components/server/ServerTableRow.tsx:66:11",className:"h-4 w-4 text-[var(--dg-text-muted)]"}),e.jsxs("div",{"code-path":"src/components/server/ServerTableRow.tsx:67:11",children:[e.jsx("p",{"code-path":"src/components/server/ServerTableRow.tsx:68:13",className:"font-medium text-[var(--dg-text-primary)]",children:s.hostname}),e.jsx("p",{"code-path":"src/components/server/ServerTableRow.tsx:69:13",className:"text-xs text-[var(--dg-text-muted)]",children:s.os})]})]})}),e.jsx(re,{"code-path":"src/components/server/ServerTableRow.tsx:73:7",children:e.jsx("code",{"code-path":"src/components/server/ServerTableRow.tsx:74:9",className:"text-sm text-[var(--dg-text-secondary)] bg-[var(--dg-bg-tertiary)] px-2 py-0.5 rounded",children:s.ip})}),e.jsx(re,{"code-path":"src/components/server/ServerTableRow.tsx:78:7",children:s.public_ip?e.jsx("code",{"code-path":"src/components/server/ServerTableRow.tsx:80:11",className:"text-sm text-[var(--dg-cyan)] bg-[var(--dg-cyan)]/10 px-2 py-0.5 rounded",children:s.public_ip}):e.jsx("span",{"code-path":"src/components/server/ServerTableRow.tsx:84:11",className:"text-sm text-[var(--dg-text-muted)]",children:"-"})}),e.jsx(re,{"code-path":"src/components/server/ServerTableRow.tsx:87:7",children:Fs(s.status)}),e.jsx(re,{"code-path":"src/components/server/ServerTableRow.tsx:88:7",children:e.jsxs("div",{"code-path":"src/components/server/ServerTableRow.tsx:89:9",className:"text-sm text-[var(--dg-text-secondary)]",children:[e.jsxs("span",{"code-path":"src/components/server/ServerTableRow.tsx:90:11",className:"text-[var(--dg-text-muted)]",children:[s.cpu,"核"]}),e.jsx("span",{"code-path":"src/components/server/ServerTableRow.tsx:91:11",className:"mx-1 text-[var(--dg-text-muted)] opacity-50",children:"/"}),e.jsxs("span",{"code-path":"src/components/server/ServerTableRow.tsx:92:11",className:"text-[var(--dg-text-muted)]",children:[N,"GB"]}),e.jsx("span",{"code-path":"src/components/server/ServerTableRow.tsx:93:11",className:"mx-1 text-[var(--dg-text-muted)] opacity-50",children:"/"}),e.jsxs("span",{"code-path":"src/components/server/ServerTableRow.tsx:94:11",className:"text-[var(--dg-text-muted)]",children:[s.disk,"GB"]})]})}),e.jsx(re,{"code-path":"src/components/server/ServerTableRow.tsx:97:7",children:e.jsxs("div",{"code-path":"src/components/server/ServerTableRow.tsx:98:9",className:"space-y-1",children:[e.jsxs("div",{"code-path":"src/components/server/ServerTableRow.tsx:99:11",className:"flex items-center gap-2",children:[e.jsx("span",{"code-path":"src/components/server/ServerTableRow.tsx:100:13",className:"text-xs text-[var(--dg-text-muted)] w-8",children:"CPU"}),e.jsx("div",{"code-path":"src/components/server/ServerTableRow.tsx:101:13",className:"w-16 h-1.5 bg-[var(--dg-bg-tertiary)] rounded-full overflow-hidden",children:e.jsx("div",{"code-path":"src/components/server/ServerTableRow.tsx:102:15",className:Se("h-full rounded-full",mr(j)),style:{width:`${j}%`}})}),e.jsxs("span",{"code-path":"src/components/server/ServerTableRow.tsx:107:13",className:"text-xs text-[var(--dg-text-secondary)]",children:[j.toFixed(1),"%"]})]}),e.jsxs("div",{"code-path":"src/components/server/ServerTableRow.tsx:109:11",className:"flex items-center gap-2",children:[e.jsx("span",{"code-path":"src/components/server/ServerTableRow.tsx:110:13",className:"text-xs text-[var(--dg-text-muted)] w-8",children:"内存"}),e.jsx("div",{"code-path":"src/components/server/ServerTableRow.tsx:111:13",className:"w-16 h-1.5 bg-[var(--dg-bg-tertiary)] rounded-full overflow-hidden",children:e.jsx("div",{"code-path":"src/components/server/ServerTableRow.tsx:112:15",className:Se("h-full rounded-full",mr(x)),style:{width:`${x}%`}})}),e.jsxs("span",{"code-path":"src/components/server/ServerTableRow.tsx:117:13",className:"text-xs text-[var(--dg-text-secondary)]",children:[x.toFixed(1),"%"]})]}),e.jsxs("div",{"code-path":"src/components/server/ServerTableRow.tsx:119:11",className:"flex items-center gap-1 text-xs text-[var(--dg-text-muted)] pt-0.5",children:[e.jsx(Or,{"code-path":"src/components/server/ServerTableRow.tsx:120:13",className:"h-3 w-3"}),e.jsxs("span",{"code-path":"src/components/server/ServerTableRow.tsx:121:13",children:[I,"连接"]}),n>0&&e.jsxs("span",{"code-path":"src/components/server/ServerTableRow.tsx:122:27",className:"text-[var(--dg-orange)]",children:["(",n,"TW)"]})]}),e.jsxs("div",{"code-path":"src/components/server/ServerTableRow.tsx:124:11",className:"flex items-center gap-1 text-xs text-[var(--dg-text-muted)]",children:[e.jsx(Zr,{"code-path":"src/components/server/ServerTableRow.tsx:125:13",className:"h-3 w-3"}),e.jsxs("span",{"code-path":"src/components/server/ServerTableRow.tsx:126:13",children:["读",T(y),"/写",T(F)]})]})]})}),e.jsx(re,{"code-path":"src/components/server/ServerTableRow.tsx:130:7",children:e.jsxs("div",{"code-path":"src/components/server/ServerTableRow.tsx:131:9",className:"flex flex-wrap gap-1",children:[w.slice(0,3).map(u=>e.jsx(A,{"code-path":"src/components/server/ServerTableRow.tsx:133:13",variant:"outline",className:"text-xs border-[var(--dg-border)] text-[var(--dg-text-secondary)] bg-[var(--dg-bg-tertiary)]/50",children:u},u)),w.length>3&&e.jsxs(A,{"code-path":"src/components/server/ServerTableRow.tsx:142:13",variant:"outline",className:"text-xs border-[var(--dg-border)] text-[var(--dg-text-secondary)]",children:["+",w.length-3]})]})}),e.jsx(re,{"code-path":"src/components/server/ServerTableRow.tsx:148:7",className:"text-right",children:e.jsxs("div",{"code-path":"src/components/server/ServerTableRow.tsx:149:9",className:"flex items-center justify-end gap-1",children:[e.jsx(g,{"code-path":"src/components/server/ServerTableRow.tsx:150:11",variant:"ghost",size:"icon",className:"h-8 w-8 text-[var(--dg-text-secondary)] hover:text-[var(--dg-blue)]",onClick:()=>c(s),title:"终端",children:e.jsx(cr,{"code-path":"src/components/server/ServerTableRow.tsx:151:13",className:"h-4 w-4"})}),e.jsx(g,{"code-path":"src/components/server/ServerTableRow.tsx:153:11",variant:"ghost",size:"icon",className:"h-8 w-8 text-[var(--dg-text-secondary)] hover:text-emerald-400",onClick:()=>i?.(s),title:"文件",children:e.jsx(Nr,{"code-path":"src/components/server/ServerTableRow.tsx:154:13",className:"h-4 w-4"})}),e.jsxs(gr,{"code-path":"src/components/server/ServerTableRow.tsx:156:11",children:[e.jsx(ur,{"code-path":"src/components/server/ServerTableRow.tsx:157:13",asChild:!0,children:e.jsx(g,{"code-path":"src/components/server/ServerTableRow.tsx:158:15",variant:"ghost",size:"icon",className:"h-8 w-8 text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)]",children:e.jsx(es,{"code-path":"src/components/server/ServerTableRow.tsx:159:17",className:"h-4 w-4"})})}),e.jsxs(Sr,{"code-path":"src/components/server/ServerTableRow.tsx:162:13",align:"end",className:"w-48 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]",children:[e.jsx(br,{"code-path":"src/components/server/ServerTableRow.tsx:163:15",className:"text-[var(--dg-text-secondary)]",children:"操作"}),e.jsx(Ke,{"code-path":"src/components/server/ServerTableRow.tsx:164:15",className:"bg-[var(--dg-border)]"}),e.jsxs(we,{"code-path":"src/components/server/ServerTableRow.tsx:165:15",className:"text-[var(--dg-text-secondary)] focus:bg-[var(--dg-bg-hover)] focus:text-[var(--dg-text-primary)] cursor-pointer",onClick:()=>o(s),children:[e.jsx(rs,{"code-path":"src/components/server/ServerTableRow.tsx:169:17",className:"h-4 w-4 mr-2"}),"编辑"]}),e.jsxs(we,{"code-path":"src/components/server/ServerTableRow.tsx:172:15",className:"text-[var(--dg-text-secondary)] focus:bg-[var(--dg-bg-hover)] focus:text-[var(--dg-text-primary)] cursor-pointer",onClick:()=>c(s),children:[e.jsx(cr,{"code-path":"src/components/server/ServerTableRow.tsx:176:17",className:"h-4 w-4 mr-2"}),"终端"]}),e.jsx(Ke,{"code-path":"src/components/server/ServerTableRow.tsx:179:15",className:"bg-[var(--dg-border)]"}),e.jsxs(we,{"code-path":"src/components/server/ServerTableRow.tsx:180:15",className:"text-red-400 focus:bg-[var(--dg-bg-hover)] focus:text-red-400 cursor-pointer",onClick:()=>b(s.id),children:[e.jsx(Ze,{"code-path":"src/components/server/ServerTableRow.tsx:184:17",className:"h-4 w-4 mr-2"}),"删除"]})]})]})]})})]})}function tt(){const s=zr(),[m,a]=t.useState([]),[c,o]=t.useState(!0),[i,b]=t.useState([]),[j,x]=t.useState(""),[w,N]=t.useState("all"),[I,n]=t.useState(!1),[y,F]=t.useState(!1),[T,u]=t.useState(!1),[f,h]=t.useState(null),[v,k]=t.useState(pr),[z,$]=t.useState(!1),[d,S]=t.useState(!1),[_,J]=t.useState(!1),[W,B]=t.useState(null),[U,Q]=t.useState(!1),[Z,ie]=t.useState(null),[l,R]=t.useState(1),[D,ee]=t.useState(10),[M,te]=t.useState(0),G=p=>{B({id:p.id,name:p.hostname,ip:p.ip,hasAuth:p.has_auth??!0}),J(!0)},P=p=>{ie({id:p.id,name:p.hostname}),Q(!0)},K=async(p,X)=>{try{o(!0);const de=p??j,Y=X??w,q={page:l,page_size:D};de&&(q.keyword=de),Y&&Y!=="all"&&(q.status=Y);const ae=await se.getServers(q);a(ae?.list||[]),te(ae?.total||0)}catch(de){console.error("加载服务器列表失败:",de),a([])}finally{o(!1)}},oe=p=>{x(p),R(1)},ve=p=>{N(p),R(1)};t.useEffect(()=>{K()},[l,D]);const ce=t.useRef(null),he=t.useRef(null);t.useEffect(()=>{const p=vr.getState().token;if(!p)return;const de=`${window.location.protocol==="https:"?"wss:":"ws:"}//${window.location.host}/ws/metrics?token=${p}`,Y=()=>{if(ce.current?.readyState===WebSocket.OPEN)return;const q=new WebSocket(de);ce.current=q,q.onopen=()=>{},q.onmessage=ae=>{try{const C=JSON.parse(ae.data);C.type==="metrics_update"&&a(je=>je.map(Ne=>Ne.hostname===C.hostname?{...Ne,cpu_usage:C.cpu_usage,memory_usage:C.memory_usage,disk_usage:C.disk_usage,status:C.status,tcp_established:C.tcp_established,tcp_time_wait:C.tcp_time_wait,net_rx_bps:C.net_rx_bps,net_tx_bps:C.net_tx_bps,disk_read_bps:C.disk_read_bps,disk_write_bps:C.disk_write_bps}:Ne))}catch{}},q.onclose=()=>{ce.current=null,he.current=setTimeout(Y,3e3)},q.onerror=ae=>{console.error("[MetricsWS] 连接错误:",ae),q.close()}};return Y(),()=>{he.current&&clearTimeout(he.current),ce.current&&(ce.current.onclose=null,ce.current.close(),ce.current=null)}},[]);const Ve=()=>{i.length===m.length?b([]):b(m.map(p=>p.id))},Pe=p=>{i.includes(p)?b(i.filter(X=>X!==p)):b([...i,p])},be=async p=>{const X=m.find(Y=>String(Y.id)===String(p));if(await s({title:"删除服务器",description:`确定删除「${X?.hostname||p}」吗?此操作不可撤销。`,confirmText:"删除",variant:"destructive"}))try{await se.deleteServer(p),V.success("服务器已删除"),K()}catch(Y){console.error("删除服务器失败:",Y),V.error("删除失败")}},We=async()=>{if(!(i.length===0||!await s({title:"批量删除服务器",description:`确定删除选中的 ${i.length} 台服务器吗?此操作不可撤销。`,confirmText:"批量删除",variant:"destructive"})))try{await se.batchDelete(i.map(X=>Number(X))),V.success(`已删除 ${i.length} 台服务器`),b([]),K()}catch(X){console.error("批量删除失败:",X),V.error("批量删除失败")}},Ae=()=>{h(null),k(pr),S(!1),u(!0)},r=p=>{h(p.id),k({hostname:p.hostname||"",ip:p.ip||"",public_ip:p.public_ip||"",port:String(p.port||22),username:p.username||"root",auth_type:p.auth_type||"password",password:"",ssh_key:"",credential_id:null,os:p.os||"",cpu:String(p.cpu||""),memory:p.memory?String(Math.round(p.memory/1024)):"",disk:String(p.disk||""),status:p.status||"running",tags:p.tags||"",description:p.description||""}),S(!1),u(!0)},E=async()=>{if(!(!v.hostname||!v.ip))try{$(!0);const p={hostname:v.hostname,ip:v.ip,public_ip:v.public_ip||void 0,port:Number(v.port)||22,username:v.username||"root",auth_type:v.auth_type||"password",os:v.os,cpu:Number(v.cpu)||0,memory:(Number(v.memory)||0)*1024,disk:Number(v.disk)||0,status:v.status,tags:v.tags||void 0,description:v.description||void 0};v.credential_id?p.credential_id=v.credential_id:(v.password&&(p.password=v.password),v.ssh_key&&(p.ssh_key=v.ssh_key)),f?await se.updateServer(f,p):await se.createServer(p),V.success(f?"服务器已更新":"服务器已创建"),u(!1),K()}catch(p){console.error("保存服务器失败:",p),V.error("保存失败,请重试")}finally{$(!1)}},ne=()=>{if(m.length===0){V.error("没有可导出的数据");return}const p=["主机名","IP地址","公网IP","端口","操作系统","CPU(核)","内存(GB)","磁盘(GB)","状态","标签"],X=m.map(C=>{const je=C.memory?Math.round(C.memory/1024):0,Ne=Ir(C).join(";");return[C.hostname||"",C.ip||"",C.public_ip||"",C.port||22,C.os||"",C.cpu||0,je,C.disk||0,C.status||"",Ne]}),de=[p,...X].map(C=>C.map(je=>`"${String(je).replace(/"/g,'""')}"`).join(",")).join(` +`),Y=new Blob(["\uFEFF"+de],{type:"text/csv;charset=utf-8;"}),q=URL.createObjectURL(Y),ae=document.createElement("a");ae.href=q,ae.download=`servers_${new Date().toISOString().slice(0,10)}.csv`,ae.click(),URL.revokeObjectURL(q),V.success(`已导出 ${m.length} 台服务器`)},or=8;return e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:371:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:373:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:374:9",children:[e.jsx("h1",{"code-path":"src/components/server/ServerManager.tsx:375:11",className:"text-2xl font-bold text-[var(--dg-text-primary)]",children:"服务器管理"}),e.jsx("p",{"code-path":"src/components/server/ServerManager.tsx:376:11",className:"text-sm text-[var(--dg-text-muted)] mt-1",children:"管理云平台服务器资产"})]}),e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:378:9",className:"flex items-center gap-2",children:[e.jsxs(g,{"code-path":"src/components/server/ServerManager.tsx:379:11",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]",onClick:()=>K(),children:[e.jsx(pe,{"code-path":"src/components/server/ServerManager.tsx:384:13",className:Se("h-4 w-4 mr-2",c&&"animate-spin")}),"刷新"]}),e.jsxs(g,{"code-path":"src/components/server/ServerManager.tsx:387:11",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]",onClick:ne,children:[e.jsx(Ye,{"code-path":"src/components/server/ServerManager.tsx:392:13",className:"h-4 w-4 mr-2"}),"导出"]}),e.jsxs(gr,{"code-path":"src/components/server/ServerManager.tsx:395:11",children:[e.jsx(ur,{"code-path":"src/components/server/ServerManager.tsx:396:13",asChild:!0,children:e.jsxs(g,{"code-path":"src/components/server/ServerManager.tsx:397:15",variant:"outline",className:"border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]",children:[e.jsx(Xe,{"code-path":"src/components/server/ServerManager.tsx:398:17",className:"h-4 w-4 mr-2"}),"批量导入"]})}),e.jsxs(Sr,{"code-path":"src/components/server/ServerManager.tsx:402:13",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:[e.jsx(br,{"code-path":"src/components/server/ServerManager.tsx:403:15",children:"选择导入方式"}),e.jsx(Ke,{"code-path":"src/components/server/ServerManager.tsx:404:15",className:"bg-[var(--dg-border)]"}),e.jsxs(we,{"code-path":"src/components/server/ServerManager.tsx:405:15",className:"hover:bg-[var(--dg-bg-hover)] cursor-pointer focus:bg-[var(--dg-bg-hover)] focus:text-[var(--dg-text-primary)]",onClick:()=>n(!0),children:[e.jsx(xr,{"code-path":"src/components/server/ServerManager.tsx:409:17",className:"h-4 w-4 mr-2 text-[var(--dg-blue)]"}),"云主机导入",e.jsx("span",{"code-path":"src/components/server/ServerManager.tsx:411:17",className:"ml-2 text-xs text-[var(--dg-text-muted)]",children:"从云平台同步"})]}),e.jsxs(we,{"code-path":"src/components/server/ServerManager.tsx:413:15",className:"hover:bg-[var(--dg-bg-hover)] cursor-pointer focus:bg-[var(--dg-bg-hover)] focus:text-[var(--dg-text-primary)]",onClick:()=>F(!0),children:[e.jsx(qe,{"code-path":"src/components/server/ServerManager.tsx:417:17",className:"h-4 w-4 mr-2 text-emerald-400"}),"CSV导入",e.jsx("span",{"code-path":"src/components/server/ServerManager.tsx:419:17",className:"ml-2 text-xs text-[var(--dg-text-muted)]",children:"hostname + IP 即可"})]})]})]}),e.jsxs(g,{"code-path":"src/components/server/ServerManager.tsx:423:11",className:"bg-[var(--dg-blue)] hover:opacity-90 text-white",onClick:Ae,children:[e.jsx(ss,{"code-path":"src/components/server/ServerManager.tsx:427:13",className:"h-4 w-4 mr-2"}),"添加服务器"]})]})]}),e.jsx(ls,{"code-path":"src/components/server/ServerManager.tsx:434:7",servers:m}),e.jsx(me,{"code-path":"src/components/server/ServerManager.tsx:437:7",className:"bg-[var(--dg-bg-secondary)] border-[var(--dg-border)]",children:e.jsxs(xe,{"code-path":"src/components/server/ServerManager.tsx:438:9",className:"p-0",children:[e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:440:11",className:"flex items-center justify-between flex-wrap gap-4 p-4",children:[e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:441:13",className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:442:15",className:"relative w-64",children:[e.jsx(ir,{"code-path":"src/components/server/ServerManager.tsx:443:17",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-[var(--dg-text-muted)]"}),e.jsx(H,{"code-path":"src/components/server/ServerManager.tsx:444:17",placeholder:"搜索主机名或IP...",value:j,onChange:p=>oe(p.target.value),className:"pl-9 h-9 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]"})]}),e.jsxs(Ce,{"code-path":"src/components/server/ServerManager.tsx:451:15",value:w,onValueChange:ve,children:[e.jsx(Ie,{"code-path":"src/components/server/ServerManager.tsx:452:17",className:"w-32 h-9 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)]",children:e.jsx(Fe,{"code-path":"src/components/server/ServerManager.tsx:453:19",placeholder:"状态"})}),e.jsxs(ke,{"code-path":"src/components/server/ServerManager.tsx:455:17",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]",children:[e.jsx(O,{"code-path":"src/components/server/ServerManager.tsx:456:19",value:"all",children:"全部状态"}),e.jsx(O,{"code-path":"src/components/server/ServerManager.tsx:457:19",value:"running",children:"运行中"}),e.jsx(O,{"code-path":"src/components/server/ServerManager.tsx:458:19",value:"stopped",children:"已停止"}),e.jsx(O,{"code-path":"src/components/server/ServerManager.tsx:459:19",value:"maintenance",children:"维护中"}),e.jsx(O,{"code-path":"src/components/server/ServerManager.tsx:460:19",value:"offline",children:"离线"})]})]})]}),i.length>0&&e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:465:15",className:"flex items-center gap-2",children:[e.jsxs("span",{"code-path":"src/components/server/ServerManager.tsx:466:17",className:"text-sm text-[var(--dg-text-secondary)]",children:["已选择 ",i.length," 项"]}),e.jsxs(g,{"code-path":"src/components/server/ServerManager.tsx:467:17",variant:"outline",size:"sm",className:"border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:We,children:[e.jsx(Ze,{"code-path":"src/components/server/ServerManager.tsx:473:19",className:"h-4 w-4 mr-2"}),"批量删除"]})]})]}),e.jsx("div",{"code-path":"src/components/server/ServerManager.tsx:480:11",className:"border-t border-[var(--dg-border)]",children:e.jsxs(Lr,{"code-path":"src/components/server/ServerManager.tsx:481:13",children:[e.jsx(Hr,{"code-path":"src/components/server/ServerManager.tsx:482:15",children:e.jsxs(ze,{"code-path":"src/components/server/ServerManager.tsx:483:17",className:"border-[var(--dg-border)] hover:bg-transparent",children:[e.jsx(le,{"code-path":"src/components/server/ServerManager.tsx:484:19",className:"w-12",children:e.jsx(ue,{"code-path":"src/components/server/ServerManager.tsx:485:21",checked:i.length===m.length&&m.length>0,onCheckedChange:Ve,className:"border-[var(--dg-border)]"})}),e.jsx(le,{"code-path":"src/components/server/ServerManager.tsx:493:19",className:"text-[var(--dg-text-secondary)]",children:"主机名"}),e.jsx(le,{"code-path":"src/components/server/ServerManager.tsx:494:19",className:"text-[var(--dg-text-secondary)]",children:"IP地址"}),e.jsx(le,{"code-path":"src/components/server/ServerManager.tsx:495:19",className:"text-[var(--dg-text-secondary)]",children:"公网IP"}),e.jsx(le,{"code-path":"src/components/server/ServerManager.tsx:496:19",className:"text-[var(--dg-text-secondary)]",children:"状态"}),e.jsx(le,{"code-path":"src/components/server/ServerManager.tsx:497:19",className:"text-[var(--dg-text-secondary)]",children:"配置"}),e.jsx(le,{"code-path":"src/components/server/ServerManager.tsx:498:19",className:"text-[var(--dg-text-secondary)]",children:"使用率"}),e.jsx(le,{"code-path":"src/components/server/ServerManager.tsx:499:19",className:"text-[var(--dg-text-secondary)]",children:"标签"}),e.jsx(le,{"code-path":"src/components/server/ServerManager.tsx:500:19",className:"text-[var(--dg-text-secondary)] text-right",children:"操作"})]})}),e.jsx(Ur,{"code-path":"src/components/server/ServerManager.tsx:503:15",children:c?e.jsx(ze,{"code-path":"src/components/server/ServerManager.tsx:505:19",className:"border-[var(--dg-border)]",children:e.jsxs(re,{"code-path":"src/components/server/ServerManager.tsx:506:21",colSpan:or,className:"text-center text-[var(--dg-text-muted)] py-12",children:[e.jsx(pe,{"code-path":"src/components/server/ServerManager.tsx:507:23",className:"h-5 w-5 animate-spin mx-auto mb-2"}),"加载中..."]})}):m.length===0?e.jsx(ze,{"code-path":"src/components/server/ServerManager.tsx:512:19",className:"border-[var(--dg-border)]",children:e.jsx(re,{"code-path":"src/components/server/ServerManager.tsx:513:21",colSpan:or,className:"text-center text-[var(--dg-text-muted)] py-12",children:"暂无服务器数据"})}):m.map(p=>e.jsx(ks,{"code-path":"src/components/server/ServerManager.tsx:519:21",server:p,selected:i.includes(p.id),onToggleSelect:Pe,onOpenTerminal:G,onOpenFiles:P,onOpenEdit:r,onDelete:be},p.id))})]})}),e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:536:11",className:"flex items-center justify-between px-4 py-3 border-t border-[var(--dg-border)]",children:[e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:537:13",className:"flex items-center gap-2 text-sm text-[var(--dg-text-muted)]",children:[e.jsx("span",{"code-path":"src/components/server/ServerManager.tsx:538:15",children:"每页"}),e.jsxs(Ce,{"code-path":"src/components/server/ServerManager.tsx:539:15",value:String(D),onValueChange:p=>{ee(Number(p)),R(1)},children:[e.jsx(Ie,{"code-path":"src/components/server/ServerManager.tsx:540:17",className:"w-16 h-8 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)] text-[var(--dg-text-primary)] text-xs",children:e.jsx(Fe,{"code-path":"src/components/server/ServerManager.tsx:541:19"})}),e.jsxs(ke,{"code-path":"src/components/server/ServerManager.tsx:543:17",className:"bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]",children:[e.jsx(O,{"code-path":"src/components/server/ServerManager.tsx:544:19",value:"10",children:"10"}),e.jsx(O,{"code-path":"src/components/server/ServerManager.tsx:545:19",value:"20",children:"20"}),e.jsx(O,{"code-path":"src/components/server/ServerManager.tsx:546:19",value:"30",children:"30"})]})]}),e.jsx("span",{"code-path":"src/components/server/ServerManager.tsx:549:15",children:"条"}),e.jsxs("span",{"code-path":"src/components/server/ServerManager.tsx:550:15",className:"ml-4",children:["共 ",M," 条"]})]}),e.jsxs("div",{"code-path":"src/components/server/ServerManager.tsx:552:13",className:"flex items-center gap-1",children:[e.jsx(g,{"code-path":"src/components/server/ServerManager.tsx:553:15",variant:"outline",size:"sm",className:"h-8 border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]",disabled:l<=1,onClick:()=>R(p=>Math.max(1,p-1)),children:e.jsx(er,{"code-path":"src/components/server/ServerManager.tsx:560:17",className:"h-4 w-4"})}),e.jsxs("span",{"code-path":"src/components/server/ServerManager.tsx:562:15",className:"text-sm text-[var(--dg-text-secondary)] px-2",children:[l," / ",Math.max(1,Math.ceil(M/D))]}),e.jsx(g,{"code-path":"src/components/server/ServerManager.tsx:565:15",variant:"outline",size:"sm",className:"h-8 border-[var(--dg-border)] text-[var(--dg-text-secondary)] hover:text-[var(--dg-text-primary)] hover:bg-[var(--dg-bg-hover)]",disabled:l>=Math.ceil(M/D),onClick:()=>R(p=>p+1),children:e.jsx(_e,{"code-path":"src/components/server/ServerManager.tsx:572:17",className:"h-4 w-4"})})]})]})]})}),e.jsx(Is,{"code-path":"src/components/server/ServerManager.tsx:580:7",open:T,onOpenChange:u,editingId:f,formData:v,setFormData:k,detailsOpen:d,setDetailsOpen:S,onSave:E,formSaving:z}),e.jsx(ms,{"code-path":"src/components/server/ServerManager.tsx:593:7",open:I,onClose:()=>{n(!1),K()}}),e.jsx(Ss,{"code-path":"src/components/server/ServerManager.tsx:600:7",open:y,onClose:()=>{F(!1),K()}}),e.jsx(xs,{"code-path":"src/components/server/ServerManager.tsx:609:7",open:_,onOpenChange:J,serverId:W?.id??null,serverName:W?.name??"",serverIp:W?.ip??"",hasAuth:W?.hasAuth??!0}),e.jsx(vs,{"code-path":"src/components/server/ServerManager.tsx:619:7",open:U,onOpenChange:Q,serverId:Z?.id??null,serverName:Z?.name??""})]})}export{tt as ServerManager}; diff --git a/backend/static/assets/SystemManager-D4SbaG04.js b/backend/static/assets/SystemManager-D4SbaG04.js new file mode 100644 index 0000000..af6775e --- /dev/null +++ b/backend/static/assets/SystemManager-D4SbaG04.js @@ -0,0 +1,2 @@ +import{r as o,u as q,j as s,D as X,b as G,c as Y,d as Z,a8 as le,e as ss,I as S,f as ms,B as i,P as qs,a3 as Js,N as Ws,L as Ns,S as Ne,U as re,t as Us,a as Xs,a4 as ve,aa as de,y as Vs,V as Te,E as pe,l as z,z as Le}from"./index-DfyorCky.js";import{T as De,a as fe,b as Hs,c as Ks}from"./tabs-CIh_yD4s.js";import{B as os}from"./badge-xNW8x0G1.js";import{C as xs,a as hs,b as Ss,c as js,d as us}from"./card-C55cvSHg.js";import{T as Ps,a as zs,b as J,c as U,d as Es,e as T}from"./table-5sHV4Akp.js";import{S as ws,a as Cs,b as Ms,c as Is,d as B}from"./select-D5qUzdAs.js";import{S as vs}from"./square-pen-BxUFAe0F.js";import{U as Qs}from"./upload-Ba6rlaGS.js";import{D as ie}from"./download-DoZfYs2h.js";import{C as Gs}from"./circle-x-DK79Dhg2.js";import{R as Ys}from"./refresh-cw-DUB_tAG-.js";import{P as Zs}from"./plus-CUG-9kpu.js";import{M as Ue,P as we}from"./phone-DgvWDdJl.js";import{T as se}from"./trash-2-Dx32pOzT.js";import{t as Q}from"./index-a3ybMjbR.js";import{T as Ce}from"./textarea-NXY8u32k.js";import{L as fs}from"./label-BK0h2apY.js";import{C as Me}from"./checkbox-CH0bpj6b.js";import{S as bs}from"./switch-CGiGgOnh.js";import{U as Ie}from"./user-plus-BwUWtcQl.js";import{H as ke}from"./history-D_9jPUQg.js";import"./index-CWVNW_qu.js";function Re({open:e,onOpenChange:r,editingUser:t,form:n,setForm:d,saving:x,onSubmit:D}){const[N,b]=o.useState([]);return o.useEffect(()=>{if(!e)return;let a=!1;return(async()=>{try{const u=await q.getRoles();if(a)return;const I=u?.list??[];b(I.map(L=>({id:String(L.id??""),name:L.name??L.code??""})))}catch{a||b([])}})(),()=>{a=!0}},[e]),s.jsx(X,{"code-path":"src/components/system/UserFormDialog.tsx:78:5",open:e,onOpenChange:r,children:s.jsxs(G,{"code-path":"src/components/system/UserFormDialog.tsx:79:7",className:"bg-slate-900 border-slate-800",children:[s.jsxs(Y,{"code-path":"src/components/system/UserFormDialog.tsx:80:9",children:[s.jsxs(Z,{"code-path":"src/components/system/UserFormDialog.tsx:81:11",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(le,{"code-path":"src/components/system/UserFormDialog.tsx:82:13",className:"h-5 w-5 text-blue-400"}),t?"编辑用户":"新建用户"]}),s.jsx(ss,{"code-path":"src/components/system/UserFormDialog.tsx:85:11",className:"text-slate-500",children:t?"修改用户信息":"创建新的系统用户"})]}),s.jsxs("div",{"code-path":"src/components/system/UserFormDialog.tsx:90:9",className:"space-y-4",children:[s.jsxs("div",{"code-path":"src/components/system/UserFormDialog.tsx:91:11",className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{"code-path":"src/components/system/UserFormDialog.tsx:92:13",className:"space-y-2",children:[s.jsx("label",{"code-path":"src/components/system/UserFormDialog.tsx:93:15",className:"text-xs text-slate-500",children:"用户名"}),s.jsx(S,{"code-path":"src/components/system/UserFormDialog.tsx:94:15",value:n.username,onChange:a=>d({...n,username:a.target.value}),disabled:!!t,className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500",placeholder:"登录用户名"})]}),s.jsxs("div",{"code-path":"src/components/system/UserFormDialog.tsx:102:13",className:"space-y-2",children:[s.jsx("label",{"code-path":"src/components/system/UserFormDialog.tsx:103:15",className:"text-xs text-slate-500",children:"昵称"}),s.jsx(S,{"code-path":"src/components/system/UserFormDialog.tsx:104:15",value:n.nickname,onChange:a=>d({...n,nickname:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500",placeholder:"显示昵称"})]}),s.jsxs("div",{"code-path":"src/components/system/UserFormDialog.tsx:111:13",className:"space-y-2",children:[s.jsx("label",{"code-path":"src/components/system/UserFormDialog.tsx:112:15",className:"text-xs text-slate-500",children:"邮箱"}),s.jsx(S,{"code-path":"src/components/system/UserFormDialog.tsx:113:15",value:n.email,onChange:a=>d({...n,email:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500",placeholder:"user@example.com"})]}),s.jsxs("div",{"code-path":"src/components/system/UserFormDialog.tsx:120:13",className:"space-y-2",children:[s.jsx("label",{"code-path":"src/components/system/UserFormDialog.tsx:121:15",className:"text-xs text-slate-500",children:"手机号"}),s.jsx(S,{"code-path":"src/components/system/UserFormDialog.tsx:122:15",value:n.phone,onChange:a=>d({...n,phone:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500",placeholder:"可选"})]}),s.jsxs("div",{"code-path":"src/components/system/UserFormDialog.tsx:129:13",className:"space-y-2",children:[s.jsx("label",{"code-path":"src/components/system/UserFormDialog.tsx:130:15",className:"text-xs text-slate-500",children:"角色"}),s.jsxs(ws,{"code-path":"src/components/system/UserFormDialog.tsx:131:15",value:n.role,onValueChange:a=>d({...n,role:a}),children:[s.jsx(Cs,{"code-path":"src/components/system/UserFormDialog.tsx:132:17",className:"bg-slate-800/50 border-slate-700 text-slate-200",children:s.jsx(Ms,{"code-path":"src/components/system/UserFormDialog.tsx:133:19",placeholder:"选择角色"})}),s.jsx(Is,{"code-path":"src/components/system/UserFormDialog.tsx:135:17",className:"bg-slate-800 border-slate-700",children:N.map(a=>s.jsx(B,{"code-path":"src/components/system/UserFormDialog.tsx:137:21",value:a.name,children:a.name},a.id))})]})]}),s.jsxs("div",{"code-path":"src/components/system/UserFormDialog.tsx:144:13",className:"space-y-2",children:[s.jsx("label",{"code-path":"src/components/system/UserFormDialog.tsx:145:15",className:"text-xs text-slate-500",children:"状态"}),s.jsxs(ws,{"code-path":"src/components/system/UserFormDialog.tsx:146:15",value:String(n.status),onValueChange:a=>d({...n,status:Number(a)}),children:[s.jsx(Cs,{"code-path":"src/components/system/UserFormDialog.tsx:150:17",className:"bg-slate-800/50 border-slate-700 text-slate-200",children:s.jsx(Ms,{"code-path":"src/components/system/UserFormDialog.tsx:151:19"})}),s.jsxs(Is,{"code-path":"src/components/system/UserFormDialog.tsx:153:17",className:"bg-slate-800 border-slate-700",children:[s.jsx(B,{"code-path":"src/components/system/UserFormDialog.tsx:154:19",value:"1",children:"正常"}),s.jsx(B,{"code-path":"src/components/system/UserFormDialog.tsx:155:19",value:"0",children:"禁用"})]})]})]})]}),s.jsxs("div",{"code-path":"src/components/system/UserFormDialog.tsx:160:11",className:"space-y-2",children:[s.jsxs("label",{"code-path":"src/components/system/UserFormDialog.tsx:161:13",className:"text-xs text-slate-500",children:["密码",t?"(留空则不修改)":""]}),s.jsx(S,{"code-path":"src/components/system/UserFormDialog.tsx:164:13",type:"password",value:n.password,onChange:a=>d({...n,password:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500",placeholder:t?"留空则不修改":"设置初始密码"})]})]}),s.jsxs(ms,{"code-path":"src/components/system/UserFormDialog.tsx:174:9",children:[s.jsx(i,{"code-path":"src/components/system/UserFormDialog.tsx:175:11",variant:"outline",className:"border-slate-700 text-slate-300",onClick:()=>r(!1),children:"取消"}),s.jsx(i,{"code-path":"src/components/system/UserFormDialog.tsx:178:11",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:D,disabled:x,children:x?"保存中...":"保存"})]})]})})}function Fe({selectedUser:e,setSelectedUser:r,getUserStatusBadge:t,openEdit:n}){return s.jsx(X,{"code-path":"src/components/system/UserDetailDialog.tsx:29:5",open:!!e,onOpenChange:()=>r(null),children:s.jsxs(G,{"code-path":"src/components/system/UserDetailDialog.tsx:30:7",className:"bg-slate-900 border-slate-800",children:[s.jsxs(Y,{"code-path":"src/components/system/UserDetailDialog.tsx:31:9",children:[s.jsxs(Z,{"code-path":"src/components/system/UserDetailDialog.tsx:32:11",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(le,{"code-path":"src/components/system/UserDetailDialog.tsx:33:13",className:"h-5 w-5 text-blue-400"}),e?.nickname]}),s.jsxs(ss,{"code-path":"src/components/system/UserDetailDialog.tsx:36:11",className:"text-slate-500",children:["@",e?.username," · ",e?.email]})]}),s.jsxs("div",{"code-path":"src/components/system/UserDetailDialog.tsx:41:9",className:"space-y-4",children:[s.jsxs("div",{"code-path":"src/components/system/UserDetailDialog.tsx:42:11",className:"grid grid-cols-2 gap-4 p-4 rounded-lg bg-slate-800/50",children:[s.jsxs("div",{"code-path":"src/components/system/UserDetailDialog.tsx:43:13",children:[s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:44:15",className:"text-xs text-slate-500 mb-1",children:"用户名"}),s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:45:15",className:"text-sm text-slate-200",children:e?.username})]}),s.jsxs("div",{"code-path":"src/components/system/UserDetailDialog.tsx:47:13",children:[s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:48:15",className:"text-xs text-slate-500 mb-1",children:"昵称"}),s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:49:15",className:"text-sm text-slate-200",children:e?.nickname})]}),s.jsxs("div",{"code-path":"src/components/system/UserDetailDialog.tsx:51:13",children:[s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:52:15",className:"text-xs text-slate-500 mb-1",children:"邮箱"}),s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:53:15",className:"text-sm text-slate-200",children:e?.email})]}),s.jsxs("div",{"code-path":"src/components/system/UserDetailDialog.tsx:55:13",children:[s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:56:15",className:"text-xs text-slate-500 mb-1",children:"手机号"}),s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:57:15",className:"text-sm text-slate-200",children:e?.phone||"--"})]}),s.jsxs("div",{"code-path":"src/components/system/UserDetailDialog.tsx:59:13",children:[s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:60:15",className:"text-xs text-slate-500 mb-1",children:"状态"}),s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:61:15",className:"text-sm text-slate-200",children:e&&t(e.status)})]}),s.jsxs("div",{"code-path":"src/components/system/UserDetailDialog.tsx:63:13",children:[s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:64:15",className:"text-xs text-slate-500 mb-1",children:"创建时间"}),s.jsx("p",{"code-path":"src/components/system/UserDetailDialog.tsx:65:15",className:"text-sm text-slate-200",children:e&&e.createdAt?new Date(e.createdAt).toLocaleDateString():"--"})]})]}),s.jsxs("div",{"code-path":"src/components/system/UserDetailDialog.tsx:71:11",children:[s.jsx("h4",{"code-path":"src/components/system/UserDetailDialog.tsx:72:13",className:"text-sm font-medium text-slate-300 mb-2",children:"角色"}),s.jsx("div",{"code-path":"src/components/system/UserDetailDialog.tsx:73:13",className:"flex flex-wrap gap-2",children:e?.roles.map(d=>s.jsx(os,{"code-path":"src/components/system/UserDetailDialog.tsx:75:17",variant:"outline",className:"border-slate-700 text-slate-400",children:d},d))})]})]}),s.jsxs(ms,{"code-path":"src/components/system/UserDetailDialog.tsx:83:9",children:[s.jsxs(i,{"code-path":"src/components/system/UserDetailDialog.tsx:84:11",variant:"outline",className:"border-slate-700 text-slate-300",children:[s.jsx(qs,{"code-path":"src/components/system/UserDetailDialog.tsx:85:13",className:"h-4 w-4 mr-2"}),"重置密码"]}),s.jsxs(i,{"code-path":"src/components/system/UserDetailDialog.tsx:88:11",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:()=>{e&&(r(null),n(e))},children:[s.jsx(vs,{"code-path":"src/components/system/UserDetailDialog.tsx:97:13",className:"h-4 w-4 mr-2"}),"编辑"]})]})]})})}function _e({importDialogOpen:e,setImportDialogOpen:r,importPreview:t,setImportPreview:n,importing:d,importResult:x,setImportResult:D,handleCsvUpload:N,handleBatchImport:b}){return s.jsx(X,{"code-path":"src/components/system/CsvImportDialog.tsx:47:5",open:e==="csv",onOpenChange:a=>!a&&r(null),children:s.jsxs(G,{"code-path":"src/components/system/CsvImportDialog.tsx:48:7",className:"bg-slate-900 border-slate-800 max-w-2xl",children:[s.jsxs(Y,{"code-path":"src/components/system/CsvImportDialog.tsx:49:9",children:[s.jsxs(Z,{"code-path":"src/components/system/CsvImportDialog.tsx:50:11",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(Qs,{"code-path":"src/components/system/CsvImportDialog.tsx:51:13",className:"h-5 w-5 text-blue-400"}),"批量导入用户(CSV)"]}),s.jsx(ss,{"code-path":"src/components/system/CsvImportDialog.tsx:54:11",className:"text-slate-500",children:"上传 CSV 文件批量创建用户。请先下载模板,按格式填写后上传。"})]}),x?s.jsxs("div",{"code-path":"src/components/system/CsvImportDialog.tsx:120:11",className:"space-y-4 py-2",children:[s.jsxs("div",{"code-path":"src/components/system/CsvImportDialog.tsx:121:13",className:`flex items-center gap-3 p-4 rounded-lg ${x.code===200?"bg-emerald-500/10":"bg-red-500/10"}`,children:[x.code===200?s.jsx(Js,{"code-path":"src/components/system/CsvImportDialog.tsx:123:17",className:"h-6 w-6 text-emerald-400 shrink-0"}):s.jsx(Gs,{"code-path":"src/components/system/CsvImportDialog.tsx:125:17",className:"h-6 w-6 text-red-400 shrink-0"}),s.jsx("span",{"code-path":"src/components/system/CsvImportDialog.tsx:127:15",className:"text-sm text-slate-200",children:x.message})]}),x.errors?.length>0&&s.jsx("div",{"code-path":"src/components/system/CsvImportDialog.tsx:130:15",className:"max-h-32 overflow-auto rounded-lg bg-slate-800/50 p-3 space-y-1",children:x.errors.map((a,u)=>s.jsx("div",{"code-path":"src/components/system/CsvImportDialog.tsx:132:19",className:"text-xs text-red-400",children:a},u))}),s.jsx(ms,{"code-path":"src/components/system/CsvImportDialog.tsx:136:13",children:s.jsx(i,{"code-path":"src/components/system/CsvImportDialog.tsx:137:15",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:()=>{r(null),n([]),D(null)},children:"完成"})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{"code-path":"src/components/system/CsvImportDialog.tsx:61:13",className:"space-y-3",children:[s.jsxs("div",{"code-path":"src/components/system/CsvImportDialog.tsx:62:15",className:"flex items-center gap-2",children:[s.jsxs(i,{"code-path":"src/components/system/CsvImportDialog.tsx:63:17",variant:"outline",size:"sm",className:"border-slate-700 text-slate-300",onClick:()=>q.downloadTemplate(),children:[s.jsx(ie,{"code-path":"src/components/system/CsvImportDialog.tsx:64:19",className:"h-4 w-4 mr-1.5"}),"下载模板"]}),s.jsxs("label",{"code-path":"src/components/system/CsvImportDialog.tsx:67:17",className:"inline-flex items-center px-3 py-1.5 rounded-md text-sm bg-slate-800 border border-slate-700 text-slate-200 cursor-pointer hover:bg-slate-700 transition-colors",children:[s.jsx(Qs,{"code-path":"src/components/system/CsvImportDialog.tsx:68:19",className:"h-4 w-4 mr-1.5"}),"选择 CSV 文件",s.jsx("input",{"code-path":"src/components/system/CsvImportDialog.tsx:70:19",type:"file",accept:".csv",className:"hidden",onChange:N})]})]}),t.length>0&&s.jsxs("div",{"code-path":"src/components/system/CsvImportDialog.tsx:75:17",className:"rounded-lg border border-slate-800 overflow-hidden",children:[s.jsxs("div",{"code-path":"src/components/system/CsvImportDialog.tsx:76:19",className:"px-3 py-2 bg-slate-800/50 text-xs text-slate-400",children:["预览:",t.length," 条数据"]}),s.jsxs(Ps,{"code-path":"src/components/system/CsvImportDialog.tsx:79:19",children:[s.jsx(zs,{"code-path":"src/components/system/CsvImportDialog.tsx:80:21",children:s.jsxs(J,{"code-path":"src/components/system/CsvImportDialog.tsx:81:23",className:"border-slate-800",children:[s.jsx(U,{"code-path":"src/components/system/CsvImportDialog.tsx:82:25",className:"text-slate-400 text-xs",children:"用户名"}),s.jsx(U,{"code-path":"src/components/system/CsvImportDialog.tsx:83:25",className:"text-slate-400 text-xs",children:"昵称"}),s.jsx(U,{"code-path":"src/components/system/CsvImportDialog.tsx:84:25",className:"text-slate-400 text-xs",children:"邮箱"}),s.jsx(U,{"code-path":"src/components/system/CsvImportDialog.tsx:85:25",className:"text-slate-400 text-xs",children:"手机"})]})}),s.jsxs(Es,{"code-path":"src/components/system/CsvImportDialog.tsx:88:21",children:[t.slice(0,5).map((a,u)=>s.jsxs(J,{"code-path":"src/components/system/CsvImportDialog.tsx:90:25",className:"border-slate-800",children:[s.jsx(T,{"code-path":"src/components/system/CsvImportDialog.tsx:91:27",className:"text-slate-200 text-xs",children:a.username}),s.jsx(T,{"code-path":"src/components/system/CsvImportDialog.tsx:92:27",className:"text-slate-300 text-xs",children:a.nickname}),s.jsx(T,{"code-path":"src/components/system/CsvImportDialog.tsx:93:27",className:"text-slate-400 text-xs",children:a.email}),s.jsx(T,{"code-path":"src/components/system/CsvImportDialog.tsx:94:27",className:"text-slate-400 text-xs",children:a.phone})]},u)),t.length>5&&s.jsx(J,{"code-path":"src/components/system/CsvImportDialog.tsx:98:25",className:"border-slate-800",children:s.jsxs(T,{"code-path":"src/components/system/CsvImportDialog.tsx:99:27",colSpan:4,className:"text-slate-500 text-xs text-center",children:["还有 ",t.length-5," 条..."]})})]})]})]})]}),s.jsxs(ms,{"code-path":"src/components/system/CsvImportDialog.tsx:110:13",children:[s.jsx(i,{"code-path":"src/components/system/CsvImportDialog.tsx:111:15",variant:"outline",className:"border-slate-700 text-slate-300",onClick:()=>{r(null),n([])},children:"取消"}),s.jsx(i,{"code-path":"src/components/system/CsvImportDialog.tsx:114:15",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:b,disabled:d||t.length===0,children:d?"导入中...":`确认导入 (${t.length})`})]})]})]})})}function Oe({importDialogOpen:e,setImportDialogOpen:r,ldapUsers:t,setLdapUsers:n,ldapSelected:d,setLdapSelected:x,ldapLoading:D,ldapImportOUs:N,ldapImportOUDN:b,setLdapImportOUDN:a,loadLdapUsers:u,handleLdapImport:I,importing:L,importResult:w,setImportResult:R}){return s.jsx(X,{"code-path":"src/components/system/LdapImportDialog.tsx:58:5",open:e==="ldap",onOpenChange:y=>!y&&r(null),children:s.jsxs(G,{"code-path":"src/components/system/LdapImportDialog.tsx:59:7",className:"bg-slate-900 border-slate-800 max-w-2xl",children:[s.jsxs(Y,{"code-path":"src/components/system/LdapImportDialog.tsx:60:9",children:[s.jsxs(Z,{"code-path":"src/components/system/LdapImportDialog.tsx:61:11",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(Ws,{"code-path":"src/components/system/LdapImportDialog.tsx:62:13",className:"h-5 w-5 text-cyan-400"}),"从 LDAP 导入用户"]}),s.jsx(ss,{"code-path":"src/components/system/LdapImportDialog.tsx:65:11",className:"text-slate-500",children:"从 LDAP 服务器检索用户列表,选择需要导入的用户"})]}),w?s.jsxs("div",{"code-path":"src/components/system/LdapImportDialog.tsx:163:11",className:"space-y-4 py-2",children:[s.jsxs("div",{"code-path":"src/components/system/LdapImportDialog.tsx:164:13",className:`flex items-center gap-3 p-4 rounded-lg ${w.code===200?"bg-emerald-500/10":"bg-red-500/10"}`,children:[w.code===200?s.jsx(Js,{"code-path":"src/components/system/LdapImportDialog.tsx:166:17",className:"h-6 w-6 text-emerald-400 shrink-0"}):s.jsx(Gs,{"code-path":"src/components/system/LdapImportDialog.tsx:168:17",className:"h-6 w-6 text-red-400 shrink-0"}),s.jsx("span",{"code-path":"src/components/system/LdapImportDialog.tsx:170:15",className:"text-sm text-slate-200",children:w.message})]}),s.jsx(ms,{"code-path":"src/components/system/LdapImportDialog.tsx:172:13",children:s.jsx(i,{"code-path":"src/components/system/LdapImportDialog.tsx:173:15",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:()=>{r(null),n([]),R(null)},children:"完成"})})]}):s.jsxs(s.Fragment,{children:[s.jsxs("div",{"code-path":"src/components/system/LdapImportDialog.tsx:72:13",className:"space-y-3",children:[s.jsxs("div",{"code-path":"src/components/system/LdapImportDialog.tsx:73:15",className:"flex items-center gap-3",children:[s.jsxs("div",{"code-path":"src/components/system/LdapImportDialog.tsx:74:17",className:"flex items-center gap-2",children:[s.jsx("span",{"code-path":"src/components/system/LdapImportDialog.tsx:75:19",className:"text-xs text-slate-500 whitespace-nowrap",children:"选择 OU"}),s.jsxs("select",{"code-path":"src/components/system/LdapImportDialog.tsx:76:19",className:"bg-slate-800 border border-slate-700 text-slate-200 text-xs rounded-md px-2 py-1.5 focus:outline-none focus:ring-1 focus:ring-blue-500",value:b,onChange:y=>{a(y.target.value),u(y.target.value)},children:[s.jsx("option",{"code-path":"src/components/system/LdapImportDialog.tsx:84:21",value:"",children:"根 (全部)"}),N.map(y=>s.jsx("option",{"code-path":"src/components/system/LdapImportDialog.tsx:86:23",value:y.dn,children:y.name},y.dn))]})]}),s.jsxs(i,{"code-path":"src/components/system/LdapImportDialog.tsx:90:17",variant:"outline",size:"sm",className:"border-slate-700 text-slate-300 ml-auto",onClick:()=>u(b),disabled:D,children:[D?s.jsx(Ns,{"code-path":"src/components/system/LdapImportDialog.tsx:91:34",className:"h-4 w-4 mr-1.5 animate-spin"}):s.jsx(Ys,{"code-path":"src/components/system/LdapImportDialog.tsx:91:88",className:"h-4 w-4 mr-1.5"}),"刷新"]})]}),s.jsx("p",{"code-path":"src/components/system/LdapImportDialog.tsx:96:15",className:"text-xs text-slate-500",children:t.length>0?`找到 ${t.length} 个用户`:"选择 OU 或点击刷新获取用户列表"}),t.length>0&&s.jsx("div",{"code-path":"src/components/system/LdapImportDialog.tsx:101:17",className:"max-h-80 overflow-auto rounded-lg border border-slate-800",children:s.jsxs(Ps,{"code-path":"src/components/system/LdapImportDialog.tsx:102:19",children:[s.jsx(zs,{"code-path":"src/components/system/LdapImportDialog.tsx:103:21",children:s.jsxs(J,{"code-path":"src/components/system/LdapImportDialog.tsx:104:23",className:"border-slate-800 sticky top-0 bg-slate-900",children:[s.jsx(U,{"code-path":"src/components/system/LdapImportDialog.tsx:105:25",className:"w-10 text-slate-400 text-xs",children:s.jsx("input",{"code-path":"src/components/system/LdapImportDialog.tsx:106:27",type:"checkbox",className:"accent-blue-600",checked:d.size===t.length&&t.length>0,onChange:y=>{y.target.checked?x(new Set(t.map(k=>k.dn))):x(new Set)}})}),s.jsx(U,{"code-path":"src/components/system/LdapImportDialog.tsx:119:25",className:"text-slate-400 text-xs",children:"用户名"}),s.jsx(U,{"code-path":"src/components/system/LdapImportDialog.tsx:120:25",className:"text-slate-400 text-xs",children:"显示名"}),s.jsx(U,{"code-path":"src/components/system/LdapImportDialog.tsx:121:25",className:"text-slate-400 text-xs",children:"邮箱"}),s.jsx(U,{"code-path":"src/components/system/LdapImportDialog.tsx:122:25",className:"text-slate-400 text-xs",children:"DN"})]})}),s.jsx(Es,{"code-path":"src/components/system/LdapImportDialog.tsx:125:21",children:t.map(y=>s.jsxs(J,{"code-path":"src/components/system/LdapImportDialog.tsx:127:25",className:"border-slate-800 hover:bg-slate-800/50",children:[s.jsx(T,{"code-path":"src/components/system/LdapImportDialog.tsx:128:27",children:s.jsx("input",{"code-path":"src/components/system/LdapImportDialog.tsx:129:29",type:"checkbox",className:"accent-blue-600",checked:d.has(y.dn),onChange:k=>{const f=new Set(d);k.target.checked?f.add(y.dn):f.delete(y.dn),x(f)}})}),s.jsx(T,{"code-path":"src/components/system/LdapImportDialog.tsx:141:27",className:"text-slate-200 text-xs",children:y.uid}),s.jsx(T,{"code-path":"src/components/system/LdapImportDialog.tsx:142:27",className:"text-slate-300 text-xs",children:y.cn}),s.jsx(T,{"code-path":"src/components/system/LdapImportDialog.tsx:143:27",className:"text-slate-400 text-xs",children:y.mail}),s.jsx(T,{"code-path":"src/components/system/LdapImportDialog.tsx:144:27",className:"text-slate-500 text-xs font-mono truncate max-w-[200px]",children:y.dn})]},y.dn))})]})})]}),s.jsxs(ms,{"code-path":"src/components/system/LdapImportDialog.tsx:153:13",children:[s.jsx(i,{"code-path":"src/components/system/LdapImportDialog.tsx:154:15",variant:"outline",className:"border-slate-700 text-slate-300",onClick:()=>{r(null),n([])},children:"取消"}),s.jsx(i,{"code-path":"src/components/system/LdapImportDialog.tsx:157:15",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:I,disabled:L||d.size===0,children:L?"导入中...":`导入选中 (${d.size})`})]})]})]})})}function Ae({searchQuery:e,setSearchQuery:r,filteredUsers:t,loading:n,selectedUser:d,setSelectedUser:x,getUserStatusBadge:D,dialogOpen:N,setDialogOpen:b,editingUser:a,form:u,setForm:I,saving:L,handleSubmit:w,openCreate:R,openEdit:y,handleDelete:k,importDialogOpen:f,setImportDialogOpen:A,importPreview:F,setImportPreview:E,importing:C,importResult:_,setImportResult:p,handleCsvUpload:O,handleBatchImport:g,ldapUsers:$,ldapSelected:es,setLdapSelected:ts,ldapLoading:W,ldapImportOUs:j,ldapImportOUDN:ls,setLdapImportOUDN:as,loadLdapUsers:rs,handleLdapImport:ds,setLdapUsers:V}){return s.jsxs(s.Fragment,{children:[s.jsxs("div",{"code-path":"src/components/system/SystemUserTab.tsx:114:7",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/system/SystemUserTab.tsx:115:9",className:"relative w-64",children:[s.jsx(Ne,{"code-path":"src/components/system/SystemUserTab.tsx:116:11",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),s.jsx(S,{"code-path":"src/components/system/SystemUserTab.tsx:117:11",placeholder:"搜索用户...",value:e,onChange:v=>r(v.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemUserTab.tsx:124:9",className:"flex items-center gap-2",children:[s.jsxs(i,{"code-path":"src/components/system/SystemUserTab.tsx:125:11",variant:"outline",className:"border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800",onClick:()=>A("csv"),children:[s.jsx(Qs,{"code-path":"src/components/system/SystemUserTab.tsx:126:13",className:"h-4 w-4 mr-2"}),"批量导入"]}),s.jsxs(i,{"code-path":"src/components/system/SystemUserTab.tsx:129:11",variant:"outline",className:"border-slate-700 text-slate-300 hover:text-slate-100 hover:bg-slate-800",onClick:()=>A("ldap"),children:[s.jsx(Ws,{"code-path":"src/components/system/SystemUserTab.tsx:130:13",className:"h-4 w-4 mr-2"}),"LDAP 导入"]}),s.jsxs(i,{"code-path":"src/components/system/SystemUserTab.tsx:133:11",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:R,children:[s.jsx(Zs,{"code-path":"src/components/system/SystemUserTab.tsx:134:13",className:"h-4 w-4 mr-2"}),"新建用户"]})]})]}),s.jsx(xs,{"code-path":"src/components/system/SystemUserTab.tsx:141:7",className:"bg-slate-900 border-slate-800",children:s.jsx(hs,{"code-path":"src/components/system/SystemUserTab.tsx:142:9",className:"p-0",children:s.jsx("div",{"code-path":"src/components/system/SystemUserTab.tsx:143:11",className:"border-t border-slate-800",children:s.jsxs(Ps,{"code-path":"src/components/system/SystemUserTab.tsx:144:13",children:[s.jsx(zs,{"code-path":"src/components/system/SystemUserTab.tsx:145:15",children:s.jsxs(J,{"code-path":"src/components/system/SystemUserTab.tsx:146:17",className:"border-slate-800 hover:bg-transparent",children:[s.jsx(U,{"code-path":"src/components/system/SystemUserTab.tsx:147:19",className:"text-slate-400",children:"用户信息"}),s.jsx(U,{"code-path":"src/components/system/SystemUserTab.tsx:148:19",className:"text-slate-400",children:"联系方式"}),s.jsx(U,{"code-path":"src/components/system/SystemUserTab.tsx:149:19",className:"text-slate-400",children:"角色"}),s.jsx(U,{"code-path":"src/components/system/SystemUserTab.tsx:150:19",className:"text-slate-400",children:"来源"}),s.jsx(U,{"code-path":"src/components/system/SystemUserTab.tsx:151:19",className:"text-slate-400",children:"状态"}),s.jsx(U,{"code-path":"src/components/system/SystemUserTab.tsx:152:19",className:"text-slate-400",children:"最后登录"}),s.jsx(U,{"code-path":"src/components/system/SystemUserTab.tsx:153:19",className:"text-slate-400 text-right",children:"操作"})]})}),s.jsx(Es,{"code-path":"src/components/system/SystemUserTab.tsx:156:15",children:n?s.jsx(J,{"code-path":"src/components/system/SystemUserTab.tsx:158:19",className:"border-slate-800",children:s.jsx(T,{"code-path":"src/components/system/SystemUserTab.tsx:159:21",colSpan:7,className:"text-center py-12",children:s.jsx("div",{"code-path":"src/components/system/SystemUserTab.tsx:160:23",className:"flex items-center justify-center",children:s.jsx("div",{"code-path":"src/components/system/SystemUserTab.tsx:161:25",className:"h-6 w-6 border-2 border-slate-700 border-t-blue-500 rounded-full animate-spin"})})})}):t.length===0?s.jsx(J,{"code-path":"src/components/system/SystemUserTab.tsx:166:19",className:"border-slate-800",children:s.jsx(T,{"code-path":"src/components/system/SystemUserTab.tsx:167:21",colSpan:7,className:"text-center py-12 text-sm text-slate-500",children:"暂无用户数据"})}):t.map(v=>s.jsxs(J,{"code-path":"src/components/system/SystemUserTab.tsx:173:21",className:"border-slate-800 hover:bg-slate-800/50",children:[s.jsx(T,{"code-path":"src/components/system/SystemUserTab.tsx:174:23",children:s.jsxs("div",{"code-path":"src/components/system/SystemUserTab.tsx:175:25",className:"flex items-center gap-3",children:[s.jsx("div",{"code-path":"src/components/system/SystemUserTab.tsx:176:27",className:"w-8 h-8 rounded-full bg-blue-600 flex items-center justify-center text-white text-sm font-medium",children:(v.nickname||v.username||"?").charAt(0)}),s.jsxs("div",{"code-path":"src/components/system/SystemUserTab.tsx:179:27",children:[s.jsx("p",{"code-path":"src/components/system/SystemUserTab.tsx:180:29",className:"text-sm font-medium text-slate-200",children:v.nickname||v.username}),s.jsxs("p",{"code-path":"src/components/system/SystemUserTab.tsx:181:29",className:"text-xs text-slate-500",children:["@",v.username]})]})]})}),s.jsx(T,{"code-path":"src/components/system/SystemUserTab.tsx:185:23",children:s.jsxs("div",{"code-path":"src/components/system/SystemUserTab.tsx:186:25",className:"space-y-1",children:[s.jsxs("div",{"code-path":"src/components/system/SystemUserTab.tsx:187:27",className:"flex items-center gap-1 text-sm text-slate-400",children:[s.jsx(Ue,{"code-path":"src/components/system/SystemUserTab.tsx:188:29",className:"h-3.5 w-3.5"}),v.email||"--"]}),v.phone&&s.jsxs("div",{"code-path":"src/components/system/SystemUserTab.tsx:192:29",className:"flex items-center gap-1 text-sm text-slate-400",children:[s.jsx(we,{"code-path":"src/components/system/SystemUserTab.tsx:193:31",className:"h-3.5 w-3.5"}),v.phone]})]})}),s.jsx(T,{"code-path":"src/components/system/SystemUserTab.tsx:199:23",children:s.jsx("div",{"code-path":"src/components/system/SystemUserTab.tsx:200:25",className:"flex flex-wrap gap-1",children:(v.roles||[]).map(H=>s.jsx(os,{"code-path":"src/components/system/SystemUserTab.tsx:202:29",variant:"outline",className:"border-slate-700 text-slate-400",children:H},H))})}),s.jsx(T,{"code-path":"src/components/system/SystemUserTab.tsx:208:23",children:v.authSource==="ldap"?s.jsx(os,{"code-path":"src/components/system/SystemUserTab.tsx:210:27",variant:"outline",className:"border-cyan-500/30 text-cyan-400 bg-cyan-500/10",children:"LDAP"}):s.jsx(os,{"code-path":"src/components/system/SystemUserTab.tsx:214:27",variant:"outline",className:"border-slate-600/30 text-slate-400 bg-slate-600/10",children:"本地"})}),s.jsx(T,{"code-path":"src/components/system/SystemUserTab.tsx:219:23",children:D(v.status)}),s.jsx(T,{"code-path":"src/components/system/SystemUserTab.tsx:220:23",children:s.jsx("span",{"code-path":"src/components/system/SystemUserTab.tsx:221:25",className:"text-sm text-slate-400",children:v.lastLoginAt?new Date(v.lastLoginAt).toLocaleString():"--"})}),s.jsx(T,{"code-path":"src/components/system/SystemUserTab.tsx:225:23",className:"text-right",children:s.jsxs("div",{"code-path":"src/components/system/SystemUserTab.tsx:226:25",className:"flex items-center justify-end gap-1",children:[s.jsx(i,{"code-path":"src/components/system/SystemUserTab.tsx:227:27",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-slate-100",onClick:()=>x(v),children:s.jsx(re,{"code-path":"src/components/system/SystemUserTab.tsx:233:29",className:"h-4 w-4"})}),s.jsx(i,{"code-path":"src/components/system/SystemUserTab.tsx:235:27",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-slate-100",onClick:()=>y(v),children:s.jsx(vs,{"code-path":"src/components/system/SystemUserTab.tsx:241:29",className:"h-4 w-4"})}),s.jsx(i,{"code-path":"src/components/system/SystemUserTab.tsx:243:27",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-red-400",onClick:()=>k(v),children:s.jsx(se,{"code-path":"src/components/system/SystemUserTab.tsx:249:29",className:"h-4 w-4"})})]})})]},v.id))})]})})})}),s.jsx(Fe,{"code-path":"src/components/system/SystemUserTab.tsx:263:7",selectedUser:d,setSelectedUser:x,getUserStatusBadge:D,openEdit:y}),s.jsx(Re,{"code-path":"src/components/system/SystemUserTab.tsx:270:7",open:N,onOpenChange:b,editingUser:a,form:u,setForm:I,saving:L,onSubmit:w}),s.jsx(_e,{"code-path":"src/components/system/SystemUserTab.tsx:280:7",importDialogOpen:f,setImportDialogOpen:A,importPreview:F,setImportPreview:E,importing:C,importResult:_,setImportResult:p,handleCsvUpload:O,handleBatchImport:g}),s.jsx(Oe,{"code-path":"src/components/system/SystemUserTab.tsx:292:7",importDialogOpen:f,setImportDialogOpen:A,ldapUsers:$,setLdapUsers:V,ldapSelected:es,setLdapSelected:ts,ldapLoading:W,ldapImportOUs:j,ldapImportOUDN:ls,setLdapImportOUDN:as,loadLdapUsers:rs,handleLdapImport:ds,importing:C,importResult:_,setImportResult:p})]})}function Pe({open:e,onOpenChange:r,editingRole:t,form:n,setForm:d,saving:x,onSubmit:D,permissions:N}){const b=(a,u)=>{d(I=>{const L=new Set(I.permission_ids);return u?L.add(a):L.delete(a),{...I,permission_ids:Array.from(L)}})};return s.jsx(X,{"code-path":"src/components/system/RoleFormDialog.tsx:64:5",open:e,onOpenChange:r,children:s.jsxs(G,{"code-path":"src/components/system/RoleFormDialog.tsx:65:7",className:"bg-slate-900 border-slate-800",children:[s.jsxs(Y,{"code-path":"src/components/system/RoleFormDialog.tsx:66:9",children:[s.jsxs(Z,{"code-path":"src/components/system/RoleFormDialog.tsx:67:11",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(Us,{"code-path":"src/components/system/RoleFormDialog.tsx:68:13",className:"h-5 w-5 text-purple-400"}),t?"编辑角色":"新建角色"]}),s.jsx(ss,{"code-path":"src/components/system/RoleFormDialog.tsx:71:11",className:"text-slate-500",children:t?"修改角色信息与权限":"创建新的系统角色并分配权限"})]}),s.jsxs("div",{"code-path":"src/components/system/RoleFormDialog.tsx:76:9",className:"space-y-4",children:[s.jsxs("div",{"code-path":"src/components/system/RoleFormDialog.tsx:77:11",className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{"code-path":"src/components/system/RoleFormDialog.tsx:78:13",className:"space-y-2",children:[s.jsx(fs,{"code-path":"src/components/system/RoleFormDialog.tsx:79:15",className:"text-xs text-slate-500",children:"角色名称"}),s.jsx(S,{"code-path":"src/components/system/RoleFormDialog.tsx:80:15",value:n.name,onChange:a=>d({...n,name:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500",placeholder:"如:运维工程师"})]}),s.jsxs("div",{"code-path":"src/components/system/RoleFormDialog.tsx:87:13",className:"space-y-2",children:[s.jsx(fs,{"code-path":"src/components/system/RoleFormDialog.tsx:88:15",className:"text-xs text-slate-500",children:"角色编码"}),s.jsx(S,{"code-path":"src/components/system/RoleFormDialog.tsx:89:15",value:n.code,onChange:a=>d({...n,code:a.target.value}),disabled:!!t,className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500 disabled:opacity-60",placeholder:"如:ops_engineer"})]})]}),s.jsxs("div",{"code-path":"src/components/system/RoleFormDialog.tsx:98:11",className:"space-y-2",children:[s.jsx(fs,{"code-path":"src/components/system/RoleFormDialog.tsx:99:13",className:"text-xs text-slate-500",children:"描述"}),s.jsx(Ce,{"code-path":"src/components/system/RoleFormDialog.tsx:100:13",value:n.description,onChange:a=>d({...n,description:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-500 resize-none",placeholder:"角色职责描述(可选)",rows:2})]}),s.jsxs("div",{"code-path":"src/components/system/RoleFormDialog.tsx:108:11",className:"space-y-2",children:[s.jsxs(fs,{"code-path":"src/components/system/RoleFormDialog.tsx:109:13",className:"text-xs text-slate-500",children:["权限分配",n.permission_ids.length>0&&s.jsxs("span",{"code-path":"src/components/system/RoleFormDialog.tsx:112:17",className:"ml-2 text-slate-400",children:["已选 ",n.permission_ids.length," 项"]})]}),s.jsx("div",{"code-path":"src/components/system/RoleFormDialog.tsx:115:13",className:"max-h-48 overflow-y-auto rounded-lg border border-slate-800 bg-slate-800/30 p-3",children:N.length===0?s.jsx("p",{"code-path":"src/components/system/RoleFormDialog.tsx:117:17",className:"text-xs text-slate-500 text-center py-4",children:"暂无可分配权限"}):s.jsx("div",{"code-path":"src/components/system/RoleFormDialog.tsx:119:17",className:"grid grid-cols-2 gap-2",children:N.map(a=>s.jsxs(fs,{"code-path":"src/components/system/RoleFormDialog.tsx:121:21",className:"flex items-center gap-2 text-xs text-slate-300 font-normal cursor-pointer hover:text-slate-100",children:[s.jsx(Me,{"code-path":"src/components/system/RoleFormDialog.tsx:125:23",checked:n.permission_ids.includes(a.id),onCheckedChange:u=>b(a.id,u===!0),className:"border-slate-600 data-[state=checked]:bg-blue-600 data-[state=checked]:border-blue-600"}),s.jsx("span",{"code-path":"src/components/system/RoleFormDialog.tsx:130:23",className:"truncate",children:a.name})]},a.id))})})]})]}),s.jsxs(ms,{"code-path":"src/components/system/RoleFormDialog.tsx:139:9",children:[s.jsx(i,{"code-path":"src/components/system/RoleFormDialog.tsx:140:11",variant:"outline",className:"border-slate-700 text-slate-300",onClick:()=>r(!1),children:"取消"}),s.jsx(i,{"code-path":"src/components/system/RoleFormDialog.tsx:143:11",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:D,disabled:x,children:x?"保存中...":"保存"})]})]})})}function ze(e){const r=Array.isArray(e.permissions)?e.permissions:[];return{id:String(e.id??""),name:e.name??"",code:e.code??"",description:e.description??"",permissions:r.map(t=>typeof t=="string"?t:t?.name??t?.code??"").filter(Boolean),permissionCodes:r.map(t=>typeof t=="string"?t:t?.code??"").filter(Boolean),createdAt:e.createdAt??e.created_at??"",_permissionIds:r.map(t=>typeof t=="object"?Number(t.id):0).filter(Boolean)}}const oe={name:"",code:"",description:"",permission_ids:[]};function Ee({selectedRole:e,setSelectedRole:r}){const t=Xs(),[n,d]=o.useState([]),[x,D]=o.useState(!0),[N,b]=o.useState([]),[a,u]=o.useState(!1),[I,L]=o.useState(null),[w,R]=o.useState({...oe}),[y,k]=o.useState(!1),f=o.useCallback(async()=>{D(!0);try{const O=(await q.getRoles())?.list??[];d(O.map(ze))}catch{d([])}finally{D(!1)}},[]),A=o.useCallback(async()=>{try{const O=(await q.getPermissions())?.list??[];b(O.map(g=>({id:Number(g.id),name:g.name??g.code??"",code:g.code??"",type:g.type})))}catch{b([])}},[]);o.useEffect(()=>{f(),A()},[f,A]);const F=()=>{L(null),R({...oe}),u(!0)},E=p=>{L(p),R({name:p.name??"",code:p.code??"",description:p.description??"",permission_ids:Array.isArray(p._permissionIds)?[...p._permissionIds]:[]}),u(!0)},C=async()=>{if(!w.name.trim()){Q.error("请输入角色名称");return}if(!w.code.trim()){Q.error("请输入角色编码");return}k(!0);try{const p={name:w.name.trim(),code:w.code.trim(),description:w.description.trim(),permission_ids:w.permission_ids};I?(await q.updateRole(I.id,p),Q.success("角色更新成功")):(await q.createRole(p),Q.success("角色创建成功")),u(!1),await f()}catch(p){Q.error(p?.message||"保存失败")}finally{k(!1)}},_=async p=>{if(await t({title:"删除角色",description:`确认删除角色「${p.name}」吗?该操作不可恢复。`,confirmText:"删除",variant:"destructive"}))try{await q.deleteRole(p.id),Q.success("角色已删除"),await f()}catch(g){Q.error(g?.message||"删除失败")}};return s.jsxs(s.Fragment,{children:[s.jsx("div",{"code-path":"src/components/system/SystemRolesTab.tsx:171:7",className:"flex items-center justify-end",children:s.jsxs(i,{"code-path":"src/components/system/SystemRolesTab.tsx:172:9",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:F,children:[s.jsx(Zs,{"code-path":"src/components/system/SystemRolesTab.tsx:173:11",className:"h-4 w-4 mr-2"}),"新建角色"]})}),x?s.jsx("div",{"code-path":"src/components/system/SystemRolesTab.tsx:179:9",className:"flex items-center justify-center py-16",children:s.jsx("div",{"code-path":"src/components/system/SystemRolesTab.tsx:180:11",className:"w-8 h-8 border-2 border-blue-500 border-t-transparent rounded-full animate-spin"})}):n.length===0?s.jsxs("div",{"code-path":"src/components/system/SystemRolesTab.tsx:183:9",className:"flex flex-col items-center justify-center py-16 text-slate-500",children:[s.jsx(Us,{"code-path":"src/components/system/SystemRolesTab.tsx:184:11",className:"h-10 w-10 mb-3 opacity-40"}),s.jsx("p",{"code-path":"src/components/system/SystemRolesTab.tsx:185:11",className:"text-sm",children:"暂无角色数据"})]}):s.jsx("div",{"code-path":"src/components/system/SystemRolesTab.tsx:188:9",className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:n.map(p=>s.jsxs(xs,{"code-path":"src/components/system/SystemRolesTab.tsx:190:13",className:"bg-slate-900 border-slate-800",children:[s.jsx(Ss,{"code-path":"src/components/system/SystemRolesTab.tsx:191:15",className:"pb-2",children:s.jsxs("div",{"code-path":"src/components/system/SystemRolesTab.tsx:192:17",className:"flex items-start justify-between",children:[s.jsxs("div",{"code-path":"src/components/system/SystemRolesTab.tsx:193:19",className:"flex items-center gap-3",children:[s.jsx("div",{"code-path":"src/components/system/SystemRolesTab.tsx:194:21",className:"w-10 h-10 rounded-lg bg-purple-500/10 flex items-center justify-center",children:s.jsx(Us,{"code-path":"src/components/system/SystemRolesTab.tsx:195:23",className:"h-5 w-5 text-purple-400"})}),s.jsxs("div",{"code-path":"src/components/system/SystemRolesTab.tsx:197:21",children:[s.jsx(js,{"code-path":"src/components/system/SystemRolesTab.tsx:198:23",className:"text-base text-slate-100",children:p.name}),s.jsx(us,{"code-path":"src/components/system/SystemRolesTab.tsx:199:23",className:"text-slate-500",children:p.code})]})]}),s.jsxs("div",{"code-path":"src/components/system/SystemRolesTab.tsx:202:19",className:"flex items-center gap-1",children:[s.jsx(i,{"code-path":"src/components/system/SystemRolesTab.tsx:203:21",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-slate-100",onClick:()=>r(p),children:s.jsx(re,{"code-path":"src/components/system/SystemRolesTab.tsx:209:23",className:"h-4 w-4"})}),s.jsx(i,{"code-path":"src/components/system/SystemRolesTab.tsx:211:21",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-slate-100",onClick:()=>E(p),children:s.jsx(vs,{"code-path":"src/components/system/SystemRolesTab.tsx:217:23",className:"h-4 w-4"})}),s.jsx(i,{"code-path":"src/components/system/SystemRolesTab.tsx:219:21",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-red-400",onClick:()=>_(p),children:s.jsx(se,{"code-path":"src/components/system/SystemRolesTab.tsx:225:23",className:"h-4 w-4"})})]})]})}),s.jsxs(hs,{"code-path":"src/components/system/SystemRolesTab.tsx:230:15",children:[s.jsx("p",{"code-path":"src/components/system/SystemRolesTab.tsx:231:17",className:"text-sm text-slate-400 mb-3",children:p.description||"暂无描述"}),s.jsxs("div",{"code-path":"src/components/system/SystemRolesTab.tsx:233:17",className:"flex flex-wrap gap-1",children:[p.permissions.slice(0,8).map((O,g)=>s.jsx(os,{"code-path":"src/components/system/SystemRolesTab.tsx:235:21",variant:"outline",className:"border-slate-700 text-slate-400 text-xs",children:O},g)),p.permissions.length>8&&s.jsxs(os,{"code-path":"src/components/system/SystemRolesTab.tsx:240:21",variant:"outline",className:"border-blue-500/30 text-blue-400 text-xs",children:["+",p.permissions.length-8," 项"]}),p.permissions.length===0&&s.jsx("span",{"code-path":"src/components/system/SystemRolesTab.tsx:245:21",className:"text-xs text-slate-600",children:"未分配权限"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemRolesTab.tsx:248:17",className:"mt-2 text-xs text-slate-600",children:["共 ",p.permissions?.length||0," 项权限"]})]})]},p.id))}),s.jsx($e,{"code-path":"src/components/system/SystemRolesTab.tsx:258:7",role:e,onClose:()=>r(null),onEdit:p=>{r(null),E(p)}}),s.jsx(Pe,{"code-path":"src/components/system/SystemRolesTab.tsx:261:7",open:a,onOpenChange:u,editingRole:I,form:w,setForm:R,saving:y,onSubmit:C,permissions:N})]})}function $e({role:e,onClose:r,onEdit:t}){return s.jsx(X,{"code-path":"src/components/system/SystemRolesTab.tsx:286:5",open:!!e,onOpenChange:n=>!n&&r(),children:s.jsxs(G,{"code-path":"src/components/system/SystemRolesTab.tsx:287:7",className:"bg-slate-900 border-slate-800",children:[s.jsxs(Y,{"code-path":"src/components/system/SystemRolesTab.tsx:288:9",children:[s.jsxs(Z,{"code-path":"src/components/system/SystemRolesTab.tsx:289:11",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(Us,{"code-path":"src/components/system/SystemRolesTab.tsx:290:13",className:"h-5 w-5 text-purple-400"}),e?.name]}),s.jsxs(ss,{"code-path":"src/components/system/SystemRolesTab.tsx:293:11",className:"text-slate-500",children:["编码:",e?.code]})]}),s.jsxs("div",{"code-path":"src/components/system/SystemRolesTab.tsx:296:9",className:"space-y-4",children:[s.jsxs("div",{"code-path":"src/components/system/SystemRolesTab.tsx:297:11",className:"rounded-lg bg-slate-800/50 p-4",children:[s.jsx("p",{"code-path":"src/components/system/SystemRolesTab.tsx:298:13",className:"text-xs text-slate-500 mb-1",children:"描述"}),s.jsx("p",{"code-path":"src/components/system/SystemRolesTab.tsx:299:13",className:"text-sm text-slate-200",children:e?.description||"暂无描述"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemRolesTab.tsx:301:11",children:[s.jsxs("h4",{"code-path":"src/components/system/SystemRolesTab.tsx:302:13",className:"text-sm font-medium text-slate-300 mb-2",children:["权限列表 (",e?.permissions?.length||0," 项)"]}),e&&e.permissions.length>0?s.jsx("div",{"code-path":"src/components/system/SystemRolesTab.tsx:304:15",className:"flex flex-wrap gap-2 max-h-60 overflow-y-auto",children:e.permissions.map((n,d)=>s.jsx(os,{"code-path":"src/components/system/SystemRolesTab.tsx:306:19",variant:"outline",className:"border-slate-700 text-slate-300",children:n},d))}):s.jsx("p",{"code-path":"src/components/system/SystemRolesTab.tsx:312:15",className:"text-xs text-slate-500",children:"未分配权限"})]})]}),s.jsx(ms,{"code-path":"src/components/system/SystemRolesTab.tsx:317:9",children:s.jsxs(i,{"code-path":"src/components/system/SystemRolesTab.tsx:318:11",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:()=>e&&t(e),children:[s.jsx(vs,{"code-path":"src/components/system/SystemRolesTab.tsx:319:13",className:"h-4 w-4 mr-2"}),"编辑"]})})]})})}function Be(e){const{ldapConfig:r,ldapMgmtOpen:t,setLdapMgmtOpen:n,ldapOUs:d,selectedOUDN:x,setSelectedOUDN:D,ldapUsers:N,selectedLDAPUsers:b,setSelectedLDAPUsers:a,loadLdapOUs:u,loadLdapOUUsers:I,handleLdapImport:L,importing:w,importFeedback:R,importResultOpen:y,setImportResultOpen:k,createOUOpen:f,setCreateOUOpen:A,ouForm:F,setOuForm:E,handleCreateOU:C,ldapSaving:_,createUserOpen:p,setCreateUserOpen:O,newUser:g,setNewUser:$,handleCreateLDAPUser:es,ldapUserTestOpen:ts,setLdapUserTestOpen:W,ldapTestUser:j,setLdapTestUser:ls,ldapTestPass:as,setLdapTestPass:rs,ldapUserTesting:ds,ldapUserTestResult:V,handleLdapUserTest:v,editLdapUser:H,setEditLdapUser:ps,editLdapForm:l,setEditLdapForm:P,handleUpdateLdapUser:cs,handleDeleteLDAPEntry:Ts,openEditLdapUser:ks}=e;return s.jsxs(s.Fragment,{children:[s.jsxs("button",{"code-path":"src/components/system/LdapManagementSection.tsx:140:7",onClick:()=>{const c=!t;n(c),c&&d.length===0&&u()},className:"w-full flex items-center gap-2 px-4 py-2.5 bg-slate-900/50 hover:bg-slate-800/50 text-slate-400 text-sm transition-colors",children:[s.jsx(ve,{"code-path":"src/components/system/LdapManagementSection.tsx:148:9",className:`h-4 w-4 transition-transform ${t?"":"-rotate-90"}`}),s.jsx(de,{"code-path":"src/components/system/LdapManagementSection.tsx:149:9",className:"h-4 w-4 text-amber-400"}),s.jsx("span",{"code-path":"src/components/system/LdapManagementSection.tsx:150:9",className:"text-slate-300",children:"LDAP 账号管理"})]}),t&&s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:154:9",className:"bg-slate-900/30 border-t border-slate-800/50 px-4 py-4 space-y-4",children:[s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:155:11",className:"flex items-center gap-3 flex-wrap",children:[s.jsxs(X,{"code-path":"src/components/system/LdapManagementSection.tsx:157:13",open:ts,onOpenChange:W,children:[s.jsx(Vs,{"code-path":"src/components/system/LdapManagementSection.tsx:158:15",asChild:!0,children:s.jsxs(i,{"code-path":"src/components/system/LdapManagementSection.tsx:159:17",variant:"ghost",size:"sm",className:"text-slate-400 hover:text-slate-200",children:[s.jsx(qs,{"code-path":"src/components/system/LdapManagementSection.tsx:160:19",className:"h-3.5 w-3.5 mr-1"}),"账号验证"]})}),s.jsxs(G,{"code-path":"src/components/system/LdapManagementSection.tsx:164:15",className:"max-w-md bg-slate-900 border-slate-800",children:[s.jsxs(Y,{"code-path":"src/components/system/LdapManagementSection.tsx:165:17",children:[s.jsx(Z,{"code-path":"src/components/system/LdapManagementSection.tsx:166:19",className:"text-slate-100",children:"LDAP 账号验证测试"}),s.jsx(ss,{"code-path":"src/components/system/LdapManagementSection.tsx:167:19",className:"text-slate-500",children:"输入 LDAP 用户凭据进行认证测试"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:169:17",className:"space-y-3 py-2",children:[s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:170:19",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:171:21",className:"text-xs text-slate-500 mb-1 block",children:"用户名"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:172:21",value:j,onChange:c=>ls(c.target.value),placeholder:"zhangsan",className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:179:19",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:180:21",className:"text-xs text-slate-500 mb-1 block",children:"密码"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:181:21",type:"password",value:as,onChange:c=>rs(c.target.value),onKeyDown:c=>c.key==="Enter"&&v(),placeholder:"••••••",className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600"})]}),V&&s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:191:21",className:`p-3 rounded-lg text-sm ${V.success?"bg-emerald-500/10 text-emerald-300":"bg-red-500/10 text-red-300"}`,children:[V.message,V.user_info&&s.jsx("pre",{"code-path":"src/components/system/LdapManagementSection.tsx:194:25",className:"mt-2 text-xs whitespace-pre-wrap",children:JSON.stringify(V.user_info,null,2)})]}),s.jsxs(i,{"code-path":"src/components/system/LdapManagementSection.tsx:198:19",className:"w-full bg-blue-600 hover:bg-blue-700 text-white",onClick:v,disabled:ds||!j,children:[ds?s.jsx(Ns,{"code-path":"src/components/system/LdapManagementSection.tsx:203:40",className:"h-4 w-4 mr-1.5 animate-spin"}):null,"验证"]})]})]})]}),s.jsxs(i,{"code-path":"src/components/system/LdapManagementSection.tsx:210:13",variant:"ghost",size:"sm",className:"text-slate-400 hover:text-slate-200",onClick:u,children:[s.jsx(Ys,{"code-path":"src/components/system/LdapManagementSection.tsx:211:15",className:"h-3.5 w-3.5 mr-1"}),"刷新"]}),s.jsxs(ws,{"code-path":"src/components/system/LdapManagementSection.tsx:216:13",value:x,onValueChange:c=>{D(c),I(c)},children:[s.jsx(Cs,{"code-path":"src/components/system/LdapManagementSection.tsx:217:15",className:"w-60 h-7 bg-slate-800 border-slate-700 text-slate-200 text-xs",children:s.jsx(Ms,{"code-path":"src/components/system/LdapManagementSection.tsx:218:17",placeholder:"选择组织单元"})}),s.jsxs(Is,{"code-path":"src/components/system/LdapManagementSection.tsx:220:15",className:"bg-slate-800 border-slate-700",children:[s.jsxs(B,{"code-path":"src/components/system/LdapManagementSection.tsx:221:17",value:r.base_dn,children:["根 (",r.base_dn,")"]}),d.map(c=>s.jsx(B,{"code-path":"src/components/system/LdapManagementSection.tsx:223:19",value:c.dn,children:c.description?`${c.name} (${c.description})`:c.name},c.dn))]})]}),s.jsxs(X,{"code-path":"src/components/system/LdapManagementSection.tsx:231:13",open:f,onOpenChange:A,children:[s.jsx(Vs,{"code-path":"src/components/system/LdapManagementSection.tsx:232:15",asChild:!0,children:s.jsxs(i,{"code-path":"src/components/system/LdapManagementSection.tsx:233:17",variant:"ghost",size:"sm",className:"text-slate-400 hover:text-slate-200",children:[s.jsx(Zs,{"code-path":"src/components/system/LdapManagementSection.tsx:234:19",className:"h-3.5 w-3.5 mr-1"}),"新建 OU"]})}),s.jsxs(G,{"code-path":"src/components/system/LdapManagementSection.tsx:238:15",className:"max-w-md bg-slate-900 border-slate-800",children:[s.jsxs(Y,{"code-path":"src/components/system/LdapManagementSection.tsx:239:17",children:[s.jsx(Z,{"code-path":"src/components/system/LdapManagementSection.tsx:240:19",className:"text-slate-100",children:"新建组织单元"}),s.jsx(ss,{"code-path":"src/components/system/LdapManagementSection.tsx:241:19",className:"text-slate-500",children:"在 LDAP 目录中创建新的组织单元 (OU)"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:243:17",className:"space-y-3 py-2",children:[s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:244:19",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:245:21",className:"text-xs text-slate-500 mb-1 block",children:"OU 名称 *"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:246:21",value:F.ou_name,onChange:c=>E({...F,ou_name:c.target.value}),placeholder:"dev",className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:248:19",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:249:21",className:"text-xs text-slate-500 mb-1 block",children:"父级 DN"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:250:21",value:F.parent_dn,onChange:c=>E({...F,parent_dn:c.target.value}),placeholder:r.base_dn,className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:252:19",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:253:21",className:"text-xs text-slate-500 mb-1 block",children:"描述"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:254:21",value:F.description,onChange:c=>E({...F,description:c.target.value}),placeholder:"开发团队",className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs(i,{"code-path":"src/components/system/LdapManagementSection.tsx:256:19",className:"w-full bg-blue-600 hover:bg-blue-700 text-white",onClick:C,disabled:!F.ou_name||_,children:[_?s.jsx(Ns,{"code-path":"src/components/system/LdapManagementSection.tsx:257:35",className:"h-4 w-4 mr-1.5 animate-spin"}):null,"创建"]})]})]})]}),s.jsxs(X,{"code-path":"src/components/system/LdapManagementSection.tsx:265:13",open:p,onOpenChange:O,children:[s.jsx(Vs,{"code-path":"src/components/system/LdapManagementSection.tsx:266:15",asChild:!0,children:s.jsxs(i,{"code-path":"src/components/system/LdapManagementSection.tsx:267:17",variant:"ghost",size:"sm",className:"text-slate-400 hover:text-slate-200",children:[s.jsx(Ie,{"code-path":"src/components/system/LdapManagementSection.tsx:268:19",className:"h-3.5 w-3.5 mr-1"}),"添加用户"]})}),s.jsxs(G,{"code-path":"src/components/system/LdapManagementSection.tsx:272:15",className:"max-w-md bg-slate-900 border-slate-800",children:[s.jsxs(Y,{"code-path":"src/components/system/LdapManagementSection.tsx:273:17",children:[s.jsx(Z,{"code-path":"src/components/system/LdapManagementSection.tsx:274:19",className:"text-slate-100",children:"添加 LDAP 用户"}),s.jsx(ss,{"code-path":"src/components/system/LdapManagementSection.tsx:275:19",className:"text-slate-500",children:"在 LDAP 目录中创建新的用户账号"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:277:17",className:"space-y-3 py-2",children:[s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:278:19",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:279:21",className:"text-xs text-slate-500 mb-1 block",children:"用户名 *"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:280:21",value:g.username,onChange:c=>$({...g,username:c.target.value}),placeholder:"zhangsan",className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:282:19",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:283:21",className:"text-xs text-slate-500 mb-1 block",children:"密码 *"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:284:21",type:"password",value:g.password,onChange:c=>$({...g,password:c.target.value}),placeholder:"••••••",className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:286:19",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:287:21",className:"text-xs text-slate-500 mb-1 block",children:"显示名称"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:288:21",value:g.display_name,onChange:c=>$({...g,display_name:c.target.value}),placeholder:"张三",className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:290:19",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:291:21",className:"text-xs text-slate-500 mb-1 block",children:"邮箱"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:292:21",value:g.email,onChange:c=>$({...g,email:c.target.value}),placeholder:"zs@example.com",className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:294:19",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:295:21",className:"text-xs text-slate-500 mb-1 block",children:"目标 OU"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:296:21",value:g.ou_dn||x||r.base_dn,onChange:c=>$({...g,ou_dn:c.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs(i,{"code-path":"src/components/system/LdapManagementSection.tsx:298:19",className:"w-full bg-blue-600 hover:bg-blue-700 text-white",onClick:es,disabled:!g.username||!g.password||_,children:[_?s.jsx(Ns,{"code-path":"src/components/system/LdapManagementSection.tsx:299:35",className:"h-4 w-4 mr-1.5 animate-spin"}):null,"创建"]})]})]})]}),s.jsxs(i,{"code-path":"src/components/system/LdapManagementSection.tsx:307:13",variant:"outline",size:"sm",className:"border-blue-600/50 text-blue-400 hover:bg-blue-600/10 ml-auto",onClick:L,disabled:N.length===0||w,children:[w?s.jsx(Ns,{"code-path":"src/components/system/LdapManagementSection.tsx:314:28",className:"h-3.5 w-3.5 mr-1 animate-spin"}):s.jsx(ie,{"code-path":"src/components/system/LdapManagementSection.tsx:314:84",className:"h-3.5 w-3.5 mr-1"}),b.length>0?`导入 (${b.length})`:`导入全部 (${N.length})`]})]}),R&&s.jsx(X,{"code-path":"src/components/system/LdapManagementSection.tsx:320:13",open:y,onOpenChange:k,children:s.jsxs(G,{"code-path":"src/components/system/LdapManagementSection.tsx:321:15",className:"max-w-sm bg-slate-900 border-slate-800",children:[s.jsxs(Y,{"code-path":"src/components/system/LdapManagementSection.tsx:322:17",children:[s.jsx(Z,{"code-path":"src/components/system/LdapManagementSection.tsx:323:19",className:"text-slate-100",children:"导入结果"}),s.jsx(ss,{"code-path":"src/components/system/LdapManagementSection.tsx:324:19",className:"text-slate-500",children:"LDAP 用户导入到本地用户库的执行结果"})]}),s.jsx("div",{"code-path":"src/components/system/LdapManagementSection.tsx:326:17",className:"py-3 text-sm text-slate-300",children:R}),s.jsx(i,{"code-path":"src/components/system/LdapManagementSection.tsx:329:17",className:"w-full bg-blue-600 hover:bg-blue-700 text-white",onClick:()=>k(!1),children:"确定"})]})}),s.jsx("div",{"code-path":"src/components/system/LdapManagementSection.tsx:337:11",className:"border border-slate-800 rounded-lg overflow-hidden",children:s.jsxs(Ps,{"code-path":"src/components/system/LdapManagementSection.tsx:338:13",children:[s.jsx(zs,{"code-path":"src/components/system/LdapManagementSection.tsx:339:15",children:s.jsxs(J,{"code-path":"src/components/system/LdapManagementSection.tsx:340:17",className:"border-slate-800 hover:bg-transparent",children:[s.jsx(U,{"code-path":"src/components/system/LdapManagementSection.tsx:341:19",className:"text-slate-400 w-8",children:s.jsx("input",{"code-path":"src/components/system/LdapManagementSection.tsx:342:21",type:"checkbox",className:"rounded bg-slate-800 border-slate-600",checked:b.length>0&&b.length===N.length,onChange:c=>a(c.target.checked?N.map(K=>K.dn):[])})}),s.jsx(U,{"code-path":"src/components/system/LdapManagementSection.tsx:349:19",className:"text-slate-400",children:"用户名"}),s.jsx(U,{"code-path":"src/components/system/LdapManagementSection.tsx:350:19",className:"text-slate-400",children:"显示名称"}),s.jsx(U,{"code-path":"src/components/system/LdapManagementSection.tsx:351:19",className:"text-slate-400",children:"邮箱"}),s.jsx(U,{"code-path":"src/components/system/LdapManagementSection.tsx:352:19",className:"text-slate-400",children:"DN"}),s.jsx(U,{"code-path":"src/components/system/LdapManagementSection.tsx:353:19",className:"text-slate-400 w-12",children:"操作"})]})}),s.jsx(Es,{"code-path":"src/components/system/LdapManagementSection.tsx:356:15",children:N.length===0?s.jsx(J,{"code-path":"src/components/system/LdapManagementSection.tsx:358:19",className:"border-slate-800",children:s.jsx(T,{"code-path":"src/components/system/LdapManagementSection.tsx:359:21",colSpan:6,className:"text-center text-slate-500 py-8",children:"点击「刷新」加载 LDAP 用户"})}):N.map(c=>s.jsxs(J,{"code-path":"src/components/system/LdapManagementSection.tsx:365:21",className:"border-slate-800 hover:bg-slate-800/50",children:[s.jsx(T,{"code-path":"src/components/system/LdapManagementSection.tsx:366:23",children:s.jsx("input",{"code-path":"src/components/system/LdapManagementSection.tsx:367:25",type:"checkbox",className:"rounded bg-slate-800 border-slate-600",checked:b.includes(c.dn),onChange:K=>{K.target.checked?a([...b,c.dn]):a(b.filter(is=>is!==c.dn))}})}),s.jsx(T,{"code-path":"src/components/system/LdapManagementSection.tsx:377:23",children:s.jsx("span",{"code-path":"src/components/system/LdapManagementSection.tsx:378:25",className:"text-sm text-slate-200 font-medium",children:c.uid})}),s.jsx(T,{"code-path":"src/components/system/LdapManagementSection.tsx:380:23",children:s.jsx("span",{"code-path":"src/components/system/LdapManagementSection.tsx:381:25",className:"text-sm text-slate-300",children:c.cn})}),s.jsx(T,{"code-path":"src/components/system/LdapManagementSection.tsx:383:23",children:s.jsx("span",{"code-path":"src/components/system/LdapManagementSection.tsx:384:25",className:"text-sm text-slate-400",children:c.mail||"-"})}),s.jsx(T,{"code-path":"src/components/system/LdapManagementSection.tsx:386:23",children:s.jsx("code",{"code-path":"src/components/system/LdapManagementSection.tsx:387:25",className:"text-xs text-slate-500",children:c.dn})}),s.jsx(T,{"code-path":"src/components/system/LdapManagementSection.tsx:389:23",children:s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:390:25",className:"flex items-center gap-1",children:[s.jsx(i,{"code-path":"src/components/system/LdapManagementSection.tsx:391:27",variant:"ghost",size:"icon",className:"h-6 w-6 text-slate-400 hover:text-blue-400 hover:bg-blue-500/10",onClick:()=>ks(c),children:s.jsx(vs,{"code-path":"src/components/system/LdapManagementSection.tsx:397:29",className:"h-3 w-3"})}),s.jsx(i,{"code-path":"src/components/system/LdapManagementSection.tsx:399:27",variant:"ghost",size:"icon",className:"h-6 w-6 text-red-400 hover:text-red-300 hover:bg-red-500/10",onClick:()=>Ts(c.dn),children:s.jsx(se,{"code-path":"src/components/system/LdapManagementSection.tsx:405:29",className:"h-3 w-3"})})]})})]},c.dn))})]})})]}),s.jsx(X,{"code-path":"src/components/system/LdapManagementSection.tsx:419:7",open:!!H,onOpenChange:c=>!c&&ps(null),children:s.jsxs(G,{"code-path":"src/components/system/LdapManagementSection.tsx:420:9",className:"max-w-md bg-slate-900 border-slate-800",children:[s.jsxs(Y,{"code-path":"src/components/system/LdapManagementSection.tsx:421:11",children:[s.jsxs(Z,{"code-path":"src/components/system/LdapManagementSection.tsx:422:13",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(vs,{"code-path":"src/components/system/LdapManagementSection.tsx:423:15",className:"h-5 w-5 text-blue-400"}),"编辑 LDAP 用户"]}),s.jsxs(ss,{"code-path":"src/components/system/LdapManagementSection.tsx:426:13",className:"text-slate-500",children:["修改 ",H?.uid," 的属性"]})]}),H&&s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:431:13",className:"space-y-3 py-2",children:[s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:432:15",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:433:17",className:"text-xs text-slate-500 mb-1 block",children:"用户名(只读)"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:434:17",value:H.uid||"",disabled:!0,className:"bg-slate-800/50 border-slate-700 text-slate-500"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:436:15",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:437:17",className:"text-xs text-slate-500 mb-1 block",children:"显示名称 (cn)"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:438:17",value:l.cn,onChange:c=>P({...l,cn:c.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:440:15",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:441:17",className:"text-xs text-slate-500 mb-1 block",children:"邮箱"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:442:17",value:l.mail,onChange:c=>P({...l,mail:c.target.value}),placeholder:"user@example.com",className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:444:15",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:445:17",className:"text-xs text-slate-500 mb-1 block",children:"电话"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:446:17",value:l.phone,onChange:c=>P({...l,phone:c.target.value}),placeholder:"13800138000",className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),s.jsxs("div",{"code-path":"src/components/system/LdapManagementSection.tsx:448:15",children:[s.jsx("label",{"code-path":"src/components/system/LdapManagementSection.tsx:449:17",className:"text-xs text-slate-500 mb-1 block",children:"职位/头衔"}),s.jsx(S,{"code-path":"src/components/system/LdapManagementSection.tsx:450:17",value:l.title,onChange:c=>P({...l,title:c.target.value}),placeholder:"运维工程师",className:"bg-slate-800/50 border-slate-700 text-slate-200"})]})]}),s.jsxs(ms,{"code-path":"src/components/system/LdapManagementSection.tsx:454:11",children:[s.jsx(i,{"code-path":"src/components/system/LdapManagementSection.tsx:455:13",variant:"outline",className:"border-slate-700 text-slate-300",onClick:()=>ps(null),children:"取消"}),s.jsx(i,{"code-path":"src/components/system/LdapManagementSection.tsx:456:13",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:cs,children:"保存"})]})]})})]})}function Ve(e){const{ldapConfig:r,ldapForm:t,setLdapForm:n,ldapSaving:d,ldapTesting:x,ldapTestResult:D,handleLdapSave:N,handleLdapTest:b}=e;return s.jsxs(s.Fragment,{children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:93:7",className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[s.jsxs(xs,{"code-path":"src/components/system/SystemSettingsTab.tsx:94:9",className:"bg-slate-900 border-slate-800",children:[s.jsxs(Ss,{"code-path":"src/components/system/SystemSettingsTab.tsx:95:11",children:[s.jsxs(js,{"code-path":"src/components/system/SystemSettingsTab.tsx:96:13",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(Te,{"code-path":"src/components/system/SystemSettingsTab.tsx:97:15",className:"h-5 w-5 text-blue-400"}),"安全设置"]}),s.jsx(us,{"code-path":"src/components/system/SystemSettingsTab.tsx:100:13",className:"text-slate-500",children:"密码策略与登录安全"})]}),s.jsxs(hs,{"code-path":"src/components/system/SystemSettingsTab.tsx:102:11",className:"space-y-4",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:103:13",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:104:15",children:[s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:105:17",className:"text-sm font-medium text-slate-200",children:"强制密码复杂度"}),s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:106:17",className:"text-xs text-slate-500",children:"要求密码包含大小写字母、数字和特殊字符"})]}),s.jsx(bs,{"code-path":"src/components/system/SystemSettingsTab.tsx:108:15",defaultChecked:!0,className:"data-[state=checked]:bg-blue-600"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:110:13",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:111:15",children:[s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:112:17",className:"text-sm font-medium text-slate-200",children:"登录失败锁定"}),s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:113:17",className:"text-xs text-slate-500",children:"连续5次登录失败锁定账户30分钟"})]}),s.jsx(bs,{"code-path":"src/components/system/SystemSettingsTab.tsx:115:15",defaultChecked:!0,className:"data-[state=checked]:bg-blue-600"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:117:13",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:118:15",children:[s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:119:17",className:"text-sm font-medium text-slate-200",children:"双因素认证"}),s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:120:17",className:"text-xs text-slate-500",children:"启用后需要手机验证码登录"})]}),s.jsx(bs,{"code-path":"src/components/system/SystemSettingsTab.tsx:122:15",className:"data-[state=checked]:bg-blue-600"})]})]})]}),s.jsxs(xs,{"code-path":"src/components/system/SystemSettingsTab.tsx:127:9",className:"bg-slate-900 border-slate-800",children:[s.jsxs(Ss,{"code-path":"src/components/system/SystemSettingsTab.tsx:128:11",children:[s.jsxs(js,{"code-path":"src/components/system/SystemSettingsTab.tsx:129:13",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(ke,{"code-path":"src/components/system/SystemSettingsTab.tsx:130:15",className:"h-5 w-5 text-emerald-400"}),"审计设置"]}),s.jsx(us,{"code-path":"src/components/system/SystemSettingsTab.tsx:133:13",className:"text-slate-500",children:"操作日志与审计策略"})]}),s.jsxs(hs,{"code-path":"src/components/system/SystemSettingsTab.tsx:135:11",className:"space-y-4",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:136:13",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:137:15",children:[s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:138:17",className:"text-sm font-medium text-slate-200",children:"记录所有操作"}),s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:139:17",className:"text-xs text-slate-500",children:"记录用户的所有操作行为"})]}),s.jsx(bs,{"code-path":"src/components/system/SystemSettingsTab.tsx:141:15",defaultChecked:!0,className:"data-[state=checked]:bg-blue-600"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:143:13",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:144:15",children:[s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:145:17",className:"text-sm font-medium text-slate-200",children:"日志保留时间"}),s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:146:17",className:"text-xs text-slate-500",children:"操作日志保留180天"})]}),s.jsxs(ws,{"code-path":"src/components/system/SystemSettingsTab.tsx:148:15",defaultValue:"180",children:[s.jsx(Cs,{"code-path":"src/components/system/SystemSettingsTab.tsx:149:17",className:"w-32 h-8 bg-slate-800 border-slate-700 text-slate-200",children:s.jsx(Ms,{"code-path":"src/components/system/SystemSettingsTab.tsx:150:19"})}),s.jsxs(Is,{"code-path":"src/components/system/SystemSettingsTab.tsx:152:17",className:"bg-slate-800 border-slate-700",children:[s.jsx(B,{"code-path":"src/components/system/SystemSettingsTab.tsx:153:19",value:"30",children:"30天"}),s.jsx(B,{"code-path":"src/components/system/SystemSettingsTab.tsx:154:19",value:"90",children:"90天"}),s.jsx(B,{"code-path":"src/components/system/SystemSettingsTab.tsx:155:19",value:"180",children:"180天"}),s.jsx(B,{"code-path":"src/components/system/SystemSettingsTab.tsx:156:19",value:"365",children:"1年"})]})]})]})]})]}),s.jsxs(xs,{"code-path":"src/components/system/SystemSettingsTab.tsx:163:9",className:"bg-slate-900 border-slate-800",children:[s.jsxs(Ss,{"code-path":"src/components/system/SystemSettingsTab.tsx:164:11",children:[s.jsxs(js,{"code-path":"src/components/system/SystemSettingsTab.tsx:165:13",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(qs,{"code-path":"src/components/system/SystemSettingsTab.tsx:166:15",className:"h-5 w-5 text-amber-400"}),"会话设置"]}),s.jsx(us,{"code-path":"src/components/system/SystemSettingsTab.tsx:169:13",className:"text-slate-500",children:"会话超时与Token配置"})]}),s.jsxs(hs,{"code-path":"src/components/system/SystemSettingsTab.tsx:171:11",className:"space-y-4",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:172:13",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:173:15",children:[s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:174:17",className:"text-sm font-medium text-slate-200",children:"会话超时时间"}),s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:175:17",className:"text-xs text-slate-500",children:"用户无操作30分钟后自动登出"})]}),s.jsxs(ws,{"code-path":"src/components/system/SystemSettingsTab.tsx:177:15",defaultValue:"30",children:[s.jsx(Cs,{"code-path":"src/components/system/SystemSettingsTab.tsx:178:17",className:"w-32 h-8 bg-slate-800 border-slate-700 text-slate-200",children:s.jsx(Ms,{"code-path":"src/components/system/SystemSettingsTab.tsx:179:19"})}),s.jsxs(Is,{"code-path":"src/components/system/SystemSettingsTab.tsx:181:17",className:"bg-slate-800 border-slate-700",children:[s.jsx(B,{"code-path":"src/components/system/SystemSettingsTab.tsx:182:19",value:"15",children:"15分钟"}),s.jsx(B,{"code-path":"src/components/system/SystemSettingsTab.tsx:183:19",value:"30",children:"30分钟"}),s.jsx(B,{"code-path":"src/components/system/SystemSettingsTab.tsx:184:19",value:"60",children:"1小时"}),s.jsx(B,{"code-path":"src/components/system/SystemSettingsTab.tsx:185:19",value:"120",children:"2小时"})]})]})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:189:13",className:"flex items-center justify-between",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:190:15",children:[s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:191:17",className:"text-sm font-medium text-slate-200",children:"单点登录"}),s.jsx("p",{"code-path":"src/components/system/SystemSettingsTab.tsx:192:17",className:"text-xs text-slate-500",children:"同一账号只能在一个设备登录"})]}),s.jsx(bs,{"code-path":"src/components/system/SystemSettingsTab.tsx:194:15",className:"data-[state=checked]:bg-blue-600"})]})]})]}),s.jsxs(xs,{"code-path":"src/components/system/SystemSettingsTab.tsx:199:9",className:"bg-slate-900 border-slate-800",children:[s.jsxs(Ss,{"code-path":"src/components/system/SystemSettingsTab.tsx:200:11",children:[s.jsxs(js,{"code-path":"src/components/system/SystemSettingsTab.tsx:201:13",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(pe,{"code-path":"src/components/system/SystemSettingsTab.tsx:202:15",className:"h-5 w-5 text-purple-400"}),"系统信息"]}),s.jsx(us,{"code-path":"src/components/system/SystemSettingsTab.tsx:205:13",className:"text-slate-500",children:"版本与系统状态"})]}),s.jsxs(hs,{"code-path":"src/components/system/SystemSettingsTab.tsx:207:11",className:"space-y-4",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:208:13",className:"flex items-center justify-between",children:[s.jsx("span",{"code-path":"src/components/system/SystemSettingsTab.tsx:209:15",className:"text-sm text-slate-400",children:"系统版本"}),s.jsx("span",{"code-path":"src/components/system/SystemSettingsTab.tsx:210:15",className:"text-sm text-slate-200",children:"v2.5.1"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:212:13",className:"flex items-center justify-between",children:[s.jsx("span",{"code-path":"src/components/system/SystemSettingsTab.tsx:213:15",className:"text-sm text-slate-400",children:"运行时间"}),s.jsx("span",{"code-path":"src/components/system/SystemSettingsTab.tsx:214:15",className:"text-sm text-slate-200",children:"30天 12小时"})]})]})]})]}),s.jsxs(xs,{"code-path":"src/components/system/SystemSettingsTab.tsx:221:7",className:"bg-slate-900 border-slate-800 mt-4",children:[s.jsx(Ss,{"code-path":"src/components/system/SystemSettingsTab.tsx:222:9",children:s.jsx("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:223:11",className:"flex items-center justify-between",children:s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:224:13",children:[s.jsxs(js,{"code-path":"src/components/system/SystemSettingsTab.tsx:225:15",className:"text-slate-100 flex items-center gap-2",children:[s.jsx(Ws,{"code-path":"src/components/system/SystemSettingsTab.tsx:226:17",className:"h-5 w-5 text-cyan-400"}),"LDAP / Active Directory"]}),s.jsx(us,{"code-path":"src/components/system/SystemSettingsTab.tsx:229:15",className:"text-slate-500 mt-1",children:"配置 LDAP 服务器,实现统一身份认证"})]})})}),s.jsxs(hs,{"code-path":"src/components/system/SystemSettingsTab.tsx:233:9",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:234:11",className:"grid grid-cols-2 gap-4",children:[s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:235:13",className:"space-y-1.5",children:[s.jsx("label",{"code-path":"src/components/system/SystemSettingsTab.tsx:236:15",className:"text-xs text-slate-500",children:"LDAP 服务器地址"}),s.jsx(S,{"code-path":"src/components/system/SystemSettingsTab.tsx:237:15",value:t.ldap_host,onChange:a=>n({...t,ldap_host:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600",placeholder:"ldap.example.com"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:244:13",className:"space-y-1.5",children:[s.jsx("label",{"code-path":"src/components/system/SystemSettingsTab.tsx:245:15",className:"text-xs text-slate-500",children:"端口"}),s.jsx(S,{"code-path":"src/components/system/SystemSettingsTab.tsx:246:15",type:"number",value:t.ldap_port,onChange:a=>n({...t,ldap_port:Number(a.target.value)}),className:"bg-slate-800/50 border-slate-700 text-slate-200",placeholder:"389"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:254:13",className:"space-y-1.5 col-span-2",children:[s.jsx("label",{"code-path":"src/components/system/SystemSettingsTab.tsx:255:15",className:"text-xs text-slate-500",children:"Base DN(用户搜索基础)"}),s.jsx(S,{"code-path":"src/components/system/SystemSettingsTab.tsx:256:15",value:t.base_dn,onChange:a=>n({...t,base_dn:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600",placeholder:"ou=users,dc=example,dc=com"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:263:13",className:"space-y-1.5",children:[s.jsx("label",{"code-path":"src/components/system/SystemSettingsTab.tsx:264:15",className:"text-xs text-slate-500",children:"管理员 Bind DN"}),s.jsx(S,{"code-path":"src/components/system/SystemSettingsTab.tsx:265:15",value:t.admin_dn,onChange:a=>n({...t,admin_dn:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600",placeholder:"cn=admin,dc=example,dc=com"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:272:13",className:"space-y-1.5",children:[s.jsxs("label",{"code-path":"src/components/system/SystemSettingsTab.tsx:273:15",className:"text-xs text-slate-500",children:["管理员密码 ",r&&"(留空不修改)"]}),s.jsx(S,{"code-path":"src/components/system/SystemSettingsTab.tsx:274:15",type:"password",value:t.admin_password,onChange:a=>n({...t,admin_password:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600",placeholder:"******"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:282:13",className:"space-y-1.5 col-span-2",children:[s.jsx("label",{"code-path":"src/components/system/SystemSettingsTab.tsx:283:15",className:"text-xs text-slate-500",children:"搜索过滤器(可选,用 %s 代表用户名)"}),s.jsx(S,{"code-path":"src/components/system/SystemSettingsTab.tsx:284:15",value:t.search_filter,onChange:a=>n({...t,search_filter:a.target.value}),className:"bg-slate-800/50 border-slate-700 text-slate-200 placeholder:text-slate-600",placeholder:"(uid=%s)"})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:291:13",className:"flex items-center gap-2 col-span-2",children:[s.jsx(bs,{"code-path":"src/components/system/SystemSettingsTab.tsx:292:15",checked:t.use_ldaps,onCheckedChange:a=>n({...t,use_ldaps:a}),className:"data-[state=checked]:bg-blue-600"}),s.jsx("span",{"code-path":"src/components/system/SystemSettingsTab.tsx:297:15",className:"text-sm text-slate-300",children:"启用 LDAPS(SSL 加密)"})]})]}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:302:11",className:"flex items-center gap-3 mt-4 pt-4 border-t border-slate-800",children:[D&&s.jsx("span",{"code-path":"src/components/system/SystemSettingsTab.tsx:304:15",className:`text-xs ${D.includes("成功")?"text-emerald-400":"text-red-400"}`,children:D}),s.jsxs("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:308:13",className:"flex items-center gap-2 ml-auto",children:[s.jsxs(i,{"code-path":"src/components/system/SystemSettingsTab.tsx:309:15",variant:"outline",size:"sm",className:"border-slate-700 text-slate-300",onClick:b,disabled:x,children:[x?s.jsx(Ns,{"code-path":"src/components/system/SystemSettingsTab.tsx:316:32",className:"h-3.5 w-3.5 mr-1 animate-spin"}):s.jsx(Ys,{"code-path":"src/components/system/SystemSettingsTab.tsx:316:88",className:"h-3.5 w-3.5 mr-1"}),"测试连接"]}),s.jsx(i,{"code-path":"src/components/system/SystemSettingsTab.tsx:319:15",size:"sm",className:"bg-blue-600 hover:bg-blue-700 text-white",onClick:N,disabled:d,children:d?"保存中...":"保存配置"})]})]})]})]}),r&&s.jsx("div",{"code-path":"src/components/system/SystemSettingsTab.tsx:334:9",className:"mt-4",children:s.jsx(Be,{"code-path":"src/components/system/SystemSettingsTab.tsx:335:11",...e})})]})}function He(e){const r=Xs(),[t,n]=o.useState([]),[d,x]=o.useState(new Set),[D,N]=o.useState(!1),[b,a]=o.useState([]),[u,I]=o.useState(""),[L,w]=o.useState(null),[R,y]=o.useState({ldap_host:"",ldap_port:389,use_ldaps:!1,admin_dn:"",admin_password:"",base_dn:"",search_filter:""}),[k,f]=o.useState(!1),[A,F]=o.useState(!1),[E,C]=o.useState(null),[_,p]=o.useState(!1),[O,g]=o.useState(null),[$,es]=o.useState(!1),[ts,W]=o.useState([]),[j,ls]=o.useState(""),[as,rs]=o.useState([]),[ds,V]=o.useState(!1),[v,H]=o.useState(!1),[ps,l]=o.useState({ou_name:"",parent_dn:"",description:""}),[P,cs]=o.useState({username:"",password:"",display_name:"",email:"",ou_dn:""}),[Ts,ks]=o.useState(!1),[c,K]=o.useState(""),[is,Rs]=o.useState(""),[Fs,Ls]=o.useState(!1),[_s,ys]=o.useState(null),[gs,h]=o.useState(null),[ns,Os]=o.useState({cn:"",mail:"",phone:"",title:""}),[ee,$s]=o.useState(!1),te=async()=>{try{const m=await z.getConfig();m&&m.ldap_host&&(w(m),y({ldap_host:m.ldap_host||"",ldap_port:m.ldap_port||389,use_ldaps:m.use_ldaps||!1,admin_dn:m.admin_dn||"",admin_password:"",base_dn:m.base_dn||"",search_filter:m.search_filter||""}))}catch{}},xe=async()=>{f(!0);try{await z.updateConfig(R),await te()}catch(m){console.error("Failed to save LDAP config:",m)}finally{f(!1)}},he=async()=>{F(!0),C(null);try{await z.updateConfig(R);const m=await z.testConnection();C(m?.message||(m?.success?"连接成功":"连接失败"))}catch(m){C(m?.message||"连接失败")}finally{F(!1)}},Ds=async m=>{try{const M=await z.listUsers(m);n(M||[])}catch(M){console.error("loadOUUsers",M)}},ae=async()=>{try{const m=await z.listOUs();W(m||[]),!j&&L?.base_dn&&(ls(L.base_dn),await Ds(L.base_dn))}catch(m){console.error("loadOUs",m)}},ye=async()=>{f(!0);try{await z.createOU(ps),V(!1),l({ou_name:"",parent_dn:"",description:""}),await ae()}catch(m){const M=m?.message||"";M.includes("Already Exists")||M.includes("68")?Q.error(`OU "${ps.ou_name}" 已存在,请使用其他名称`):Q.error("创建失败: "+M)}finally{f(!1)}},ge=async()=>{f(!0);try{await z.createUser({...P,ou_dn:P.ou_dn||j||L?.base_dn}),H(!1),cs({username:"",password:"",display_name:"",email:"",ou_dn:""}),await Ds(j)}catch(m){Q.error(m?.message||"创建失败")}finally{f(!1)}},be=async(m,M=!1)=>{if(!(!M&&!await r({title:"删除 LDAP 条目",description:`确定删除 ${m}?`,confirmText:"删除",variant:"destructive"})))try{await z.deleteUser(m),M||await Ds(j)}catch(As){M||Q.error(As?.message||"删除失败")}},Se=m=>{h(m),Os({cn:m.cn||"",mail:m.mail||"",phone:m.phone||"",title:m.title||""})},je=async()=>{if(gs)try{await z.updateUser({dn:gs.dn,...ns}),h(null),await Ds(j)}catch(m){Q.error(m?.message||"修改失败")}},ue=async()=>{Ls(!0),ys(null);try{const m=await z.testConnection({test_user:c,test_password:is});ys(m)}catch(m){ys({success:!1,message:m?.message||"验证失败"})}finally{Ls(!1)}},ce=async m=>{N(!0);try{const M=await z.listUsers(m);n(Array.isArray(M)?M:[]),x(new Set)}catch{n([])}finally{N(!1)}},ne=async()=>{let m=[];if(as.length>0?m=t.filter(M=>as.includes(M.dn)):m=t,m.length!==0){$s(!0);try{const M=m.map(Bs=>({username:Bs.uid||"",nickname:Bs.cn||"",email:Bs.mail||""})),As=await z.batchImport(M);g(As?.message||`成功导入 ${m.length} 个用户`),es(!0),rs([]),await e()}catch(M){g("导入失败: "+(M?.message||"未知错误")),es(!0)}finally{$s(!1)}}};return{ldapUsers:t,setLdapUsers:n,ldapSelected:d,setLdapSelected:x,ldapLoading:D,ldapImportOUs:b,ldapImportOUDN:u,setLdapImportOUDN:I,loadLdapUsers:ce,handleLdapImport:ne,loadImportDialogData:()=>{z.listOUs().then(m=>a(Array.isArray(m)?m:[])).catch(()=>{}),ce("")},importing:ee,setImporting:$s,importFeedback:O,importResultOpen:$,setImportResultOpen:es,loadLdapConfig:te,settingsTabProps:{ldapConfig:L,ldapForm:R,setLdapForm:y,ldapSaving:k,ldapTesting:A,ldapTestResult:E,handleLdapSave:xe,handleLdapTest:he,ldapMgmtOpen:_,setLdapMgmtOpen:p,ldapOUs:ts,selectedOUDN:j,setSelectedOUDN:ls,ldapUsers:t,selectedLDAPUsers:as,setSelectedLDAPUsers:rs,loadLdapOUs:ae,loadLdapOUUsers:Ds,handleLdapImport:ne,importing:ee,importFeedback:O,importResultOpen:$,setImportResultOpen:es,createOUOpen:ds,setCreateOUOpen:V,ouForm:ps,setOuForm:l,handleCreateOU:ye,createUserOpen:v,setCreateUserOpen:H,newUser:P,setNewUser:cs,handleCreateLDAPUser:ge,ldapUserTestOpen:Ts,setLdapUserTestOpen:ks,ldapTestUser:c,setLdapTestUser:K,ldapTestPass:is,setLdapTestPass:Rs,ldapUserTesting:Fs,ldapUserTestResult:_s,handleLdapUserTest:ue,editLdapUser:gs,setEditLdapUser:h,editLdapForm:ns,setEditLdapForm:Os,handleUpdateLdapUser:je,handleDeleteLDAPEntry:be,openEditLdapUser:Se}}}function Ke(e){return{...e,status:e.status===1||e.status==="active"?"active":"inactive",roles:Array.isArray(e.roles)?e.roles:e.role?[e.role]:[],lastLoginAt:e.last_login??e.lastLoginAt,createdAt:e.created_at??e.createdAt,authSource:e.auth_source??e.authSource??"local"}}const me={username:"",nickname:"",email:"",phone:"",role:"",password:"",status:1};function gt(){const e=Xs(),r=Le(),t={"/users":"users","/roles":"roles","/settings":"settings"},[n,d]=o.useState(t[r.pathname]||"users");o.useEffect(()=>{const l=t[r.pathname];l&&l!==n&&d(l)},[r.pathname]);const[x,D]=o.useState(""),[N,b]=o.useState([]),[a,u]=o.useState(!0),[I,L]=o.useState(null),[w,R]=o.useState(null),[y,k]=o.useState(!1),[f,A]=o.useState(null),[F,E]=o.useState(!1),[C,_]=o.useState({...me}),[p,O]=o.useState(null),[g,$]=o.useState([]),[es,ts]=o.useState(null),W=async()=>{u(!0);try{const P=(await q.getUsers({page:1,page_size:100}))?.list??[];b(P.map(Ke))}catch(l){console.error("Failed to fetch users:",l),b([])}finally{u(!1)}},j=He(W);o.useEffect(()=>{W(),j.loadLdapConfig()},[]),o.useEffect(()=>{p==="ldap"&&j.loadImportDialogData()},[p]);const ls=N.filter(l=>(l.username||"").toLowerCase().includes(x.toLowerCase())||(l.nickname||"").toLowerCase().includes(x.toLowerCase())||(l.email||"").toLowerCase().includes(x.toLowerCase())),as=l=>l==="active"?s.jsxs(os,{"code-path":"src/components/system/SystemManager.tsx:110:7",variant:"outline",className:"border-emerald-500/30 text-emerald-400 bg-emerald-500/10",children:[s.jsx(Js,{"code-path":"src/components/system/SystemManager.tsx:111:9",className:"h-3 w-3 mr-1"}),"正常"]}):s.jsxs(os,{"code-path":"src/components/system/SystemManager.tsx:115:7",variant:"outline",className:"border-slate-500/30 text-slate-400 bg-slate-500/10",children:[s.jsx(Gs,{"code-path":"src/components/system/SystemManager.tsx:116:9",className:"h-3 w-3 mr-1"}),"禁用"]}),rs=()=>{A(null),_({...me}),k(!0)},ds=l=>{A(l),_({username:l.username||"",nickname:l.nickname||"",email:l.email||"",phone:l.phone||"",role:Array.isArray(l.roles)?l.roles[0]||"":l.role||"",password:"",status:l.status==="active"?1:0}),k(!0)},V=async()=>{E(!0);try{const l={username:C.username,nickname:C.nickname,email:C.email,phone:C.phone,role:C.role,status:C.status};C.password&&(l.password=C.password),f?await q.updateUser(f.id,l):await q.createUser(l),k(!1),await W()}catch(l){console.error("Failed to save user:",l)}finally{E(!1)}},v=async l=>{if(await e({title:"删除用户",description:`确认删除用户「${l.nickname||l.username}」吗?`,confirmText:"删除",variant:"destructive"}))try{await q.deleteUser(l.id),await W()}catch(cs){console.error("Failed to delete user:",cs)}},H=l=>{const P=l.target.files?.[0];if(!P)return;const cs=new FileReader;cs.onload=Ts=>{const c=(Ts.target?.result).split(` +`).filter(h=>h.trim()&&!h.startsWith(""));if(c.length<2)return;const K=c[0].split(",").map(h=>h.trim().toLowerCase()),is=K.findIndex(h=>h.includes("用户名")||h.includes("username")),Rs=K.findIndex(h=>h.includes("昵称")||h.includes("name")||h.includes("显示名")),Fs=K.findIndex(h=>h.includes("邮箱")||h.includes("email")||h.includes("mail")),Ls=K.findIndex(h=>h.includes("手机")||h.includes("phone")),_s=K.findIndex(h=>h.includes("角色")||h.includes("role")),ys=K.findIndex(h=>h.includes("密码")||h.includes("password")),gs=[];for(let h=1;hOs.trim());gs.push({username:is>=0?ns[is]:"",nickname:Rs>=0?ns[Rs]:"",email:Fs>=0?ns[Fs]:"",phone:Ls>=0?ns[Ls]:"",role:_s>=0?ns[_s]:"",password:ys>=0?ns[ys]:""})}$(gs),ts(null)},cs.readAsText(P,"UTF-8")},ps=async()=>{j.setImporting(!0);try{const l=await q.batchImport({users:g,skip_existing:!0});ts(l),await W()}catch(l){ts({code:500,message:l?.message||"导入失败"})}finally{j.setImporting(!1)}};return s.jsxs("div",{"code-path":"src/components/system/SystemManager.tsx:232:5",className:"space-y-6",children:[s.jsx("div",{"code-path":"src/components/system/SystemManager.tsx:234:7",className:"flex items-center justify-between",children:s.jsxs("div",{"code-path":"src/components/system/SystemManager.tsx:235:9",children:[s.jsx("h1",{"code-path":"src/components/system/SystemManager.tsx:236:11",className:"text-2xl font-bold text-slate-100",children:"系统管理"}),s.jsx("p",{"code-path":"src/components/system/SystemManager.tsx:237:11",className:"text-sm text-slate-500 mt-1",children:"用户、权限与系统配置"})]})}),s.jsxs(De,{"code-path":"src/components/system/SystemManager.tsx:242:7",value:n,onValueChange:d,className:"w-full",children:[s.jsxs(fe,{"code-path":"src/components/system/SystemManager.tsx:243:9",className:"bg-slate-800 border border-slate-700",children:[s.jsxs(Hs,{"code-path":"src/components/system/SystemManager.tsx:244:11",value:"users",className:"data-[state=active]:bg-slate-700",children:[s.jsx(de,{"code-path":"src/components/system/SystemManager.tsx:245:13",className:"h-4 w-4 mr-2"}),"用户管理"]}),s.jsxs(Hs,{"code-path":"src/components/system/SystemManager.tsx:248:11",value:"roles",className:"data-[state=active]:bg-slate-700",children:[s.jsx(Us,{"code-path":"src/components/system/SystemManager.tsx:249:13",className:"h-4 w-4 mr-2"}),"角色权限"]}),s.jsxs(Hs,{"code-path":"src/components/system/SystemManager.tsx:252:11",value:"settings",className:"data-[state=active]:bg-slate-700",children:[s.jsx(pe,{"code-path":"src/components/system/SystemManager.tsx:253:13",className:"h-4 w-4 mr-2"}),"系统设置"]})]}),s.jsx(Ks,{"code-path":"src/components/system/SystemManager.tsx:258:9",value:"users",className:"mt-4 space-y-4",children:s.jsx(Ae,{"code-path":"src/components/system/SystemManager.tsx:259:11",searchQuery:x,setSearchQuery:D,filteredUsers:ls,loading:a,selectedUser:I,setSelectedUser:L,getUserStatusBadge:as,dialogOpen:y,setDialogOpen:k,editingUser:f,form:C,setForm:_,saving:F,handleSubmit:V,openCreate:rs,openEdit:ds,handleDelete:v,importDialogOpen:p,setImportDialogOpen:O,importPreview:g,setImportPreview:$,importing:j.importing,importResult:es,setImportResult:ts,handleCsvUpload:H,handleBatchImport:ps,ldapUsers:j.ldapUsers,ldapSelected:j.ldapSelected,setLdapSelected:j.setLdapSelected,ldapLoading:j.ldapLoading,ldapImportOUs:j.ldapImportOUs,ldapImportOUDN:j.ldapImportOUDN,setLdapImportOUDN:j.setLdapImportOUDN,loadLdapUsers:j.loadLdapUsers,handleLdapImport:j.handleLdapImport,setLdapUsers:j.setLdapUsers})}),s.jsx(Ks,{"code-path":"src/components/system/SystemManager.tsx:299:9",value:"roles",className:"mt-4 space-y-4",children:s.jsx(Ee,{"code-path":"src/components/system/SystemManager.tsx:300:11",selectedRole:w,setSelectedRole:R})}),s.jsx(Ks,{"code-path":"src/components/system/SystemManager.tsx:306:9",value:"settings",className:"mt-4",children:s.jsx(Ve,{"code-path":"src/components/system/SystemManager.tsx:307:11",...j.settingsTabProps})})]})]})}export{gt as SystemManager}; diff --git a/backend/static/assets/TopologyView-scPjlVYA.js b/backend/static/assets/TopologyView-scPjlVYA.js new file mode 100644 index 0000000..9841910 --- /dev/null +++ b/backend/static/assets/TopologyView-scPjlVYA.js @@ -0,0 +1 @@ +import{g as Ue,j as e,q as Te,G as Fe,N as Je,p as Ge,s as de,O as Ke,i as qe,a as Ze,r as p,B as v,L as je,R as es,S as ss,I as Ve,D as Ne,b as ve,c as Se,d as Ce,e as Ee,f as ts}from"./index-DfyorCky.js";import{C as oe,a as ne,b as os,c as ns,d as as}from"./card-C55cvSHg.js";import{L as ae}from"./label-BK0h2apY.js";import{B as _e}from"./badge-xNW8x0G1.js";import{S as ce,a as re,b as le,c as ie,d as Z}from"./select-D5qUzdAs.js";import{T as cs}from"./textarea-NXY8u32k.js";import{k as _}from"./kubernetes-J8O09fK7.js";import{t as j}from"./index-a3ybMjbR.js";import{B as rs}from"./box-TTGA1p57.js";import{Z as ls}from"./zap-D2uWSK32.js";import{P as Me}from"./pencil-BqUotcjf.js";import{R as is}from"./refresh-cw-DUB_tAG-.js";import{P as ps}from"./plus-CUG-9kpu.js";import{S as ds}from"./save-DoGGjfwC.js";import{T as ms}from"./trash-2-Dx32pOzT.js";import"./index-CWVNW_qu.js";const us=[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]],$e=Ue("link-2",us),pe={cluster:"集群",loadbalancer:"Ingress",service:"Service",app:"Deployment",server:"Node",database:"数据库",external:"外部服务",custom:"自定义"},xs=[{value:"database",label:"数据库",desc:"MySQL / Redis / PostgreSQL 等"},{value:"external",label:"外部服务",desc:"外部 API / CDN / DNS 等"},{value:"custom",label:"自定义",desc:"其他自定义节点"}],X=u=>u.startsWith("custom-");function $(u,h="h-5 w-5"){switch(u){case"server":return e.jsx(Te,{"code-path":"src/components/kubernetes/topology-helpers.tsx:31:27",className:h});case"loadbalancer":return e.jsx(Ke,{"code-path":"src/components/kubernetes/topology-helpers.tsx:32:33",className:h});case"cluster":return e.jsx(de,{"code-path":"src/components/kubernetes/topology-helpers.tsx:33:28",className:h});case"app":return e.jsx(Ge,{"code-path":"src/components/kubernetes/topology-helpers.tsx:34:24",className:h});case"service":return e.jsx(Je,{"code-path":"src/components/kubernetes/topology-helpers.tsx:35:28",className:h});case"database":return e.jsx(Fe,{"code-path":"src/components/kubernetes/topology-helpers.tsx:36:29",className:h});case"external":return e.jsx(ls,{"code-path":"src/components/kubernetes/topology-helpers.tsx:37:29",className:h});case"custom":return e.jsx(rs,{"code-path":"src/components/kubernetes/topology-helpers.tsx:38:27",className:h});default:return e.jsx(Te,{"code-path":"src/components/kubernetes/topology-helpers.tsx:39:21",className:h})}}function ee(u){switch(u){case"server":return"bg-blue-500/20 text-blue-400 border-blue-500/30";case"loadbalancer":return"bg-purple-500/20 text-purple-400 border-purple-500/30";case"cluster":return"bg-cyan-500/20 text-cyan-400 border-cyan-500/30";case"app":return"bg-rose-500/20 text-rose-400 border-rose-500/30";case"service":return"bg-emerald-500/20 text-emerald-400 border-emerald-500/30";case"database":return"bg-amber-500/20 text-amber-400 border-amber-500/30";case"external":return"bg-orange-500/20 text-orange-400 border-orange-500/30";case"custom":return"bg-slate-500/20 text-slate-400 border-slate-500/30";default:return"bg-slate-500/20 text-slate-400 border-slate-500/30"}}function hs(u,h,D,Y,x){const V=[],l=[],z=Math.max(1,h.length,D.length,Y.length,x.length),L=Math.max(900,Math.min(z*130,2400)),r=[60,180,320,480,640],N=o=>{const i=Math.min(o,12);if(i===0)return[];if(i===1)return[L/2];const c=L/(i+1);return Array.from({length:i},(d,g)=>c*(g+1))},E=`cluster-${u.id}`;V.push({id:E,name:u.name||"集群",type:"cluster",x:L/2,y:r[0],data:{kind:"cluster",version:u.version,status:u.status,api_server:u.api_server,node_count:u.node_count,pod_count:u.pod_count}});const R=h.slice(0,12),B=N(R.length);R.forEach((o,i)=>{const c=`ingress-${o.id}`;V.push({id:c,name:o.name,type:"loadbalancer",x:B[i],y:r[1],data:{kind:"ingress",namespace:o.namespace,backend:o.backend,tls:o.tls,hosts:o.hosts}}),l.push({id:`e-${E}-${c}`,source:E,target:c,label:"route"})});const f=D.slice(0,12),A=N(f.length);f.forEach((o,i)=>{const c=`service-${o.id}`;V.push({id:c,name:o.name,type:"service",x:A[i],y:r[2],data:{kind:"service",namespace:o.namespace,type:o.type,cluster_ip:o.cluster_ip,external_ip:o.external_ip,selector:o.selector}})}),R.length>0&&f.length>0?R.forEach(o=>{const i=`ingress-${o.id}`,c=(o.backend||"").split(":")[0].trim();let d=f.filter(g=>g.name===c);d.length===0&&(d=f.filter(g=>g.namespace===o.namespace)),d.length===0&&(d=[f[0]]),d.forEach(g=>l.push({id:`e-${i}-service-${g.id}`,source:i,target:`service-${g.id}`,label:"→"}))}):f.length>0&&f.forEach(o=>l.push({id:`e-${E}-service-${o.id}`,source:E,target:`service-${o.id}`,label:"expose"}));const T=Y.slice(0,12),F=N(T.length);T.forEach((o,i)=>{const c=`deploy-${o.id}`;V.push({id:c,name:o.name,type:"app",x:F[i],y:r[3],data:{kind:"deployment",namespace:o.namespace,replicas:o.replicas,ready_replicas:o.ready_replicas,available_replicas:o.available_replicas,image:o.image}})}),f.length>0&&T.length>0&&f.forEach(o=>{const i=`service-${o.id}`;let c=[];try{const d=typeof o.selector=="string"?JSON.parse(o.selector||"{}"):o.selector||{},g=Object.entries(d);g.length>0&&(c=T.filter(P=>{let W={};try{W=typeof P.labels=="string"?JSON.parse(P.labels||"{}"):P.labels||{}}catch{}return g.every(([se,G])=>W[se]===G)}))}catch{}c.length===0&&(c=T.filter(d=>d.name===o.name)),c.length===0&&(c=T.filter(d=>d.namespace===o.namespace)),c.length===0&&(c=[T[0]]),c.slice(0,4).forEach(d=>l.push({id:`e-${i}-deploy-${d.id}`,source:i,target:`deploy-${d.id}`,label:"select"}))});const I=x.slice(0,12),J=N(I.length);I.forEach((o,i)=>{const c=`k8snode-${o.id}`;V.push({id:c,name:o.name,type:"server",x:J[i],y:r[4],data:{kind:"node",ip:o.ip,role:o.role,status:o.status,os:o.os,cpu:o.cpu,memory:o.memory,cpu_usage:o.cpu_usage,memory_usage:o.memory_usage,pod_count:o.pod_count}})});const y=I.filter(o=>(o.role||"").toLowerCase()==="worker"),O=y.length>0?y:I;return T.length>0&&O.length>0&&T.forEach(o=>{const i=`deploy-${o.id}`;O.slice(0,3).forEach(c=>l.push({id:`e-${i}-k8snode-${c.id}`,source:i,target:`k8snode-${c.id}`,label:"schedule"}))}),{nodes:V,edges:l}}function $s(){const{clusterCode:u}=qe(),h=Ze(),[D,Y]=p.useState([]),[x,V]=p.useState(""),[l,S]=p.useState({nodes:[],edges:[]}),[z,L]=p.useState(!1),[r,N]=p.useState(null),[E,R]=p.useState(""),[B,f]=p.useState("all"),[A,T]=p.useState(null),[F,I]=p.useState({x:0,y:0}),J=p.useRef(null),[y,O]=p.useState(!1),[o,i]=p.useState(!1),[c,d]=p.useState(null),[,g]=p.useState(null),[P,W]=p.useState(!1),[se,G]=p.useState(1),[De,H]=p.useState(!1),[Q,me]=p.useState(null),[k,U]=p.useState({name:"",type:"database",note:""}),ue=p.useCallback(async()=>{try{const n=(await _.getClusters())?.list||[];if(Y(n),!x)if(u){const t=n.find(a=>(a.code||String(a.id))===u);t&&V(String(t.id))}else n.length>0&&V(String(n[0].id))}catch{Y([])}},[u]);p.useEffect(()=>{ue()},[ue]);const xe=p.useCallback(async s=>{try{const t=await _.getTopology(s);if(t?.layout_data){const a=JSON.parse(t.layout_data);if(g(a),a.customNodes?.length>0){const m=Math.max(...a.customNodes.map(w=>{const b=w.id.match(/custom-(\d+)/);return b?parseInt(b[1]):0}));G(m+1)}return a}}catch{}return g(null),null},[]),K=p.useCallback(async()=>{if(x){L(!0);try{const s=C=>Array.isArray(C)?C:C?.list||[],[n,t,a,m]=await Promise.all([_.getNodes(x).catch(()=>[]),_.getServices(x).catch(()=>[]),_.getDeployments(x).catch(()=>[]),_.getIngresses(x).catch(()=>[])]),w=D.find(C=>String(C.id)===x)||{},b=hs(w,s(m),s(t),s(a),s(n)),M=await xe(x);M&&(M.positions&&(b.nodes=b.nodes.map(C=>{const te=M.positions[C.id];return te?{...C,x:te.x,y:te.y}:C})),M.customNodes&&(b.nodes=[...b.nodes,...M.customNodes]),M.customEdges&&(b.edges=[...b.edges,...M.customEdges])),S(b)}catch{S({nodes:[],edges:[]})}finally{L(!1)}}},[x,D,xe]);p.useEffect(()=>{K()},[K]);const q=l.nodes.filter(s=>s.name.toLowerCase().includes(E.toLowerCase())&&(B==="all"||s.type===B)),he=new Set(q.map(s=>s.id)),ge=s=>{const n=J.current;if(!n)return{x:0,y:0};const t=n.createSVGPoint();t.x=s.clientX,t.y=s.clientY;const a=n.getScreenCTM();return a?{x:t.matrixTransform(a.inverse()).x,y:t.matrixTransform(a.inverse()).y}:{x:0,y:0}},Le=(s,n)=>{if(o)return;s.stopPropagation();const t=ge(s);I({x:t.x-n.x,y:t.y-n.y}),T(n.id)},Re=s=>{if(!A)return;const n=ge(s);S(t=>({...t,nodes:t.nodes.map(a=>a.id===A?{...a,x:n.x-F.x,y:n.y-F.y}:a)}))},be=()=>T(null),Ae=s=>{if(!A){if(o){if(!c)d(s.id),j.info(`已选择源节点: ${s.name},请点击目标节点`);else if(c===s.id)j.info("不能连接自身");else{const n={id:`custom-edge-${Date.now()}`,source:c,target:s.id,label:"connect"};S(t=>({...t,edges:[...t.edges,n]})),j.success("连线已添加"),d(null),i(!1)}return}N(s)}},Ie=()=>{me(null),U({name:"",type:"database",note:""}),H(!0)},ye=s=>{me(s),U({name:s.name,type:s.type,note:s.data?.note||""}),H(!0)},Oe=()=>{if(!k.name.trim()){j.error("请输入节点名称");return}if(Q)S(s=>({...s,nodes:s.nodes.map(n=>n.id===Q.id?{...n,name:k.name,type:k.type,data:{...n.data,note:k.note}}:n)})),j.success("节点已更新");else{const n={id:`custom-${se}`,name:k.name,type:k.type,x:ke/2+(Math.random()-.5)*100,y:we/2+(Math.random()-.5)*100,data:{kind:"custom",note:k.note}};S(t=>({...t,nodes:[...t.nodes,n]})),G(t=>t+1),j.success("节点已添加")}H(!1)},Pe=async s=>{await h({title:"删除节点",description:`确定删除「${s.name}」?相关连线也会一并删除`,variant:"destructive"})&&(S(t=>({nodes:t.nodes.filter(a=>a.id!==s.id),edges:t.edges.filter(a=>a.source!==s.id&&a.target!==s.id)})),N(null),j.success("节点已删除"))},Xe=async s=>{if(!s.id.startsWith("custom-edge")){j.info("Kubernetes 原生关系不可删除");return}await h({title:"删除连线",description:"确定删除此自定义连线?",variant:"destructive"})&&(S(t=>({...t,edges:t.edges.filter(a=>a.id!==s.id)})),j.success("连线已删除"))},Ye=async()=>{if(x){W(!0);try{const s={positions:Object.fromEntries(l.nodes.map(n=>[n.id,{x:n.x,y:n.y}])),customNodes:l.nodes.filter(n=>X(n.id)),customEdges:l.edges.filter(n=>n.id.startsWith("custom-edge"))};await _.saveTopology(x,JSON.stringify(s)),j.success("布局已保存")}catch{j.error("保存失败")}finally{W(!1)}}},ze=async()=>{if(await h({title:"重置布局",description:"将清除已保存的布局并重新自动排列",variant:"destructive"})){try{await _.saveTopology(x,"")}catch{}g(null),O(!1),i(!1),d(null),await K(),j.success("布局已重置")}},Be=l.nodes.length>0?Math.max(...l.nodes.map(s=>s.x))+80:900,We=l.nodes.length>0?Math.max(...l.nodes.map(s=>s.y))+80:700,ke=Math.max(Be,900),we=Math.max(We,700),fe=s=>l.nodes.filter(n=>n.type===s).length,He=()=>{if(l.nodes.length===0)return null;const s=[60,180,320,480,640],n=["集群","Ingress","Service","Deployment","Node"];return e.jsxs("svg",{"code-path":"src/components/kubernetes/TopologyView.tsx:291:7",ref:J,width:"100%",height:"100%",viewBox:`0 0 ${ke} ${we}`,className:"bg-slate-950 rounded-lg",preserveAspectRatio:"xMidYMin meet",onMouseMove:Re,onMouseUp:be,onMouseLeave:be,children:[e.jsxs("defs",{"code-path":"src/components/kubernetes/TopologyView.tsx:293:9",children:[e.jsx("pattern",{"code-path":"src/components/kubernetes/TopologyView.tsx:294:11",id:"grid",width:"20",height:"20",patternUnits:"userSpaceOnUse",children:e.jsx("path",{"code-path":"src/components/kubernetes/TopologyView.tsx:295:13",d:"M 20 0 L 0 0 0 20",fill:"none",stroke:"#1e293b",strokeWidth:"0.5"})}),e.jsx("marker",{"code-path":"src/components/kubernetes/TopologyView.tsx:297:11",id:"arrowhead",markerWidth:"10",markerHeight:"7",refX:"28",refY:"3.5",orient:"auto",children:e.jsx("polygon",{"code-path":"src/components/kubernetes/TopologyView.tsx:298:13",points:"0 0, 10 3.5, 0 7",fill:o?"#f59e0b":"#475569"})})]}),e.jsx("rect",{"code-path":"src/components/kubernetes/TopologyView.tsx:301:9",width:"100%",height:"100%",fill:"url(#grid)"}),n.map((t,a)=>e.jsx("text",{"code-path":"src/components/kubernetes/TopologyView.tsx:303:11",x:14,y:s[a]+4,fill:"#475569",fontSize:"11",className:"font-medium select-none",children:t},t)),l.edges.map(t=>{const a=l.nodes.find(b=>b.id===t.source),m=l.nodes.find(b=>b.id===t.target);if(!a||!m||!he.has(a.id)||!he.has(m.id))return null;const w=t.id.startsWith("custom-edge");return e.jsxs("g",{"code-path":"src/components/kubernetes/TopologyView.tsx:311:13",className:y&&w?"cursor-pointer":"",onClick:()=>{y&&w&&Xe(t)},children:[e.jsx("line",{"code-path":"src/components/kubernetes/TopologyView.tsx:312:15",x1:a.x,y1:a.y,x2:m.x,y2:m.y,stroke:w?"#f59e0b":"#475569",strokeWidth:w?2:1.5,strokeDasharray:w?"6 3":void 0,markerEnd:"url(#arrowhead)",opacity:w?.8:.6}),y&&w&&e.jsx("text",{"code-path":"src/components/kubernetes/TopologyView.tsx:317:17",x:(a.x+m.x)/2,y:(a.y+m.y)/2,fill:"#f59e0b",fontSize:"10",textAnchor:"middle",className:"select-none pointer-events-none",children:"✕ 删除"})]},t.id)}),q.map(t=>{const a=X(t.id),m=c===t.id;return e.jsxs("g",{"code-path":"src/components/kubernetes/TopologyView.tsx:327:13",transform:`translate(${t.x}, ${t.y})`,className:o?"cursor-crosshair":A===t.id?"cursor-grabbing":"cursor-grab",onMouseDown:w=>Le(w,t),onClick:()=>Ae(t),onDoubleClick:()=>{y&&ye(t)},children:[e.jsx("circle",{"code-path":"src/components/kubernetes/TopologyView.tsx:332:15",r:"28",fill:"#0f172a",stroke:m?"#f59e0b":r?.id===t.id?"#3b82f6":a?"#f59e0b":"#334155",strokeWidth:m||r?.id===t.id?3:2,strokeDasharray:a?"4 2":void 0,className:"transition-all hover:stroke-blue-500"}),e.jsx("foreignObject",{"code-path":"src/components/kubernetes/TopologyView.tsx:337:15",x:"-12",y:"-12",width:"24",height:"24",children:e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:338:17",className:`flex items-center justify-center w-full h-full ${ee(t.type).split(" ")[1]}`,children:$(t.type)})}),e.jsx("text",{"code-path":"src/components/kubernetes/TopologyView.tsx:340:15",y:"45",fill:a?"#f59e0b":"#94a3b8",fontSize:"12",textAnchor:"middle",className:"font-medium select-none",children:t.name.length>20?t.name.slice(0,18)+"…":t.name})]},t.id)})]})},Qe=s=>{const n=s.data||{},t=Object.entries(n).filter(([a])=>a!=="kind");return t.length===0?null:e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:355:7",className:"grid grid-cols-2 gap-3",children:t.map(([a,m])=>e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:357:11",className:"p-2 rounded-lg bg-slate-800/50",children:[e.jsx("p",{"code-path":"src/components/kubernetes/TopologyView.tsx:358:13",className:"text-xs text-slate-500 mb-0.5",children:a}),e.jsx("p",{"code-path":"src/components/kubernetes/TopologyView.tsx:359:13",className:"text-sm text-slate-200 truncate",title:String(m),children:m==null?"—":String(m)})]},a))})};return e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:367:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:369:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:370:9",children:[e.jsx("h1",{"code-path":"src/components/kubernetes/TopologyView.tsx:371:11",className:"text-2xl font-bold text-slate-100",children:"架构拓扑"}),e.jsxs("p",{"code-path":"src/components/kubernetes/TopologyView.tsx:372:11",className:"text-sm text-slate-500 mt-1",children:["Kubernetes 集群资源拓扑可视化 · 拖拽节点调整布局",y&&e.jsx("span",{"code-path":"src/components/kubernetes/TopologyView.tsx:374:26",className:"text-amber-400 ml-2",children:"· 编辑模式"}),o&&e.jsxs("span",{"code-path":"src/components/kubernetes/TopologyView.tsx:375:29",className:"text-amber-400 ml-1",children:["· 连线中",c?"(选择目标节点)":"(选择源节点)"]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:378:9",className:"flex items-center gap-2",children:[e.jsxs(ce,{"code-path":"src/components/kubernetes/TopologyView.tsx:379:11",value:x,onValueChange:s=>{V(s),N(null),O(!1)},children:[e.jsx(re,{"code-path":"src/components/kubernetes/TopologyView.tsx:380:13",className:"w-44 h-9 bg-slate-800/50 border-slate-700 text-slate-200",children:e.jsx(le,{"code-path":"src/components/kubernetes/TopologyView.tsx:380:97",placeholder:"选择集群"})}),e.jsx(ie,{"code-path":"src/components/kubernetes/TopologyView.tsx:381:13",className:"bg-slate-800 border-slate-700",children:D.map(s=>e.jsx(Z,{"code-path":"src/components/kubernetes/TopologyView.tsx:382:36",value:String(s.id),children:s.name},s.id))})]}),e.jsxs(v,{"code-path":"src/components/kubernetes/TopologyView.tsx:385:11",variant:y?"default":"outline",size:"sm",className:"h-9",onClick:()=>{O(!y),i(!1),d(null)},children:[e.jsx(Me,{"code-path":"src/components/kubernetes/TopologyView.tsx:387:13",className:"h-4 w-4 mr-1"}),y?"退出编辑":"编辑"]}),e.jsx(v,{"code-path":"src/components/kubernetes/TopologyView.tsx:389:11",variant:"outline",size:"icon",className:"h-9 w-9 border-slate-700 text-slate-400",onClick:K,disabled:z,children:z?e.jsx(je,{"code-path":"src/components/kubernetes/TopologyView.tsx:390:24",className:"h-4 w-4 animate-spin"}):e.jsx(is,{"code-path":"src/components/kubernetes/TopologyView.tsx:390:71",className:"h-4 w-4"})})]})]}),y&&e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:397:9",className:"flex items-center gap-2 p-3 rounded-lg bg-slate-800/50 border border-slate-700",children:[e.jsxs(v,{"code-path":"src/components/kubernetes/TopologyView.tsx:398:11",size:"sm",variant:"outline",className:"border-slate-600 text-slate-200",onClick:Ie,children:[e.jsx(ps,{"code-path":"src/components/kubernetes/TopologyView.tsx:399:13",className:"h-4 w-4 mr-1"}),"添加节点"]}),e.jsxs(v,{"code-path":"src/components/kubernetes/TopologyView.tsx:401:11",size:"sm",variant:o?"default":"outline",className:o?"bg-amber-600 hover:bg-amber-700":"border-slate-600 text-slate-200",onClick:()=>{i(!o),d(null)},children:[e.jsx($e,{"code-path":"src/components/kubernetes/TopologyView.tsx:403:13",className:"h-4 w-4 mr-1"}),o?"取消连线":"添加连线"]}),e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:405:11",className:"h-5 w-px bg-slate-600"}),e.jsxs(v,{"code-path":"src/components/kubernetes/TopologyView.tsx:406:11",size:"sm",variant:"outline",className:"border-emerald-600/30 text-emerald-400 hover:bg-emerald-600/10",onClick:Ye,disabled:P,children:[e.jsx(ds,{"code-path":"src/components/kubernetes/TopologyView.tsx:407:13",className:"h-4 w-4 mr-1"}),P?"保存中...":"保存布局"]}),e.jsxs(v,{"code-path":"src/components/kubernetes/TopologyView.tsx:409:11",size:"sm",variant:"outline",className:"border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:ze,children:[e.jsx(es,{"code-path":"src/components/kubernetes/TopologyView.tsx:410:13",className:"h-4 w-4 mr-1"}),"重置布局"]}),e.jsx("span",{"code-path":"src/components/kubernetes/TopologyView.tsx:412:11",className:"text-xs text-slate-500 ml-auto",children:"双击节点编辑 · 点击虚线删除 · 拖拽调整位置"})]}),e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:417:7",className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[{label:"总节点数",value:l.nodes.length,icon:e.jsx(de,{"code-path":"src/components/kubernetes/TopologyView.tsx:419:64",className:"h-5 w-5"}),color:"text-blue-400",bg:"bg-blue-500/10"},{label:"连接数",value:l.edges.length,icon:e.jsx($e,{"code-path":"src/components/kubernetes/TopologyView.tsx:420:63",className:"h-5 w-5"}),color:"text-purple-400",bg:"bg-purple-500/10"},{label:"Service",value:fe("service"),icon:$("service"),color:"text-emerald-400",bg:"bg-emerald-500/10"},{label:"Deployment",value:fe("app"),icon:$("app"),color:"text-rose-400",bg:"bg-rose-500/10"},{label:"自定义",value:l.nodes.filter(s=>X(s.id)).length,icon:$("custom"),color:"text-amber-400",bg:"bg-amber-500/10"}].map(s=>e.jsx(oe,{"code-path":"src/components/kubernetes/TopologyView.tsx:425:11",className:"bg-slate-900 border-slate-800",children:e.jsx(ne,{"code-path":"src/components/kubernetes/TopologyView.tsx:426:13",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:427:15",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:428:17",children:[e.jsx("p",{"code-path":"src/components/kubernetes/TopologyView.tsx:429:19",className:"text-sm text-slate-500",children:s.label}),e.jsx("p",{"code-path":"src/components/kubernetes/TopologyView.tsx:430:19",className:`text-2xl font-bold ${s.color}`,children:s.value})]}),e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:432:17",className:`p-3 rounded-lg ${s.bg} ${s.color}`,children:s.icon})]})})},s.label))}),e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:440:7",className:"flex items-center gap-3",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:441:9",className:"relative w-48",children:[e.jsx(ss,{"code-path":"src/components/kubernetes/TopologyView.tsx:442:11",className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-500"}),e.jsx(Ve,{"code-path":"src/components/kubernetes/TopologyView.tsx:443:11",placeholder:"搜索节点...",value:E,onChange:s=>R(s.target.value),className:"pl-9 h-9 bg-slate-800/50 border-slate-700 text-slate-200"})]}),e.jsxs(ce,{"code-path":"src/components/kubernetes/TopologyView.tsx:445:9",value:B,onValueChange:f,children:[e.jsx(re,{"code-path":"src/components/kubernetes/TopologyView.tsx:446:11",className:"w-36 h-9 bg-slate-800/50 border-slate-700 text-slate-200",children:e.jsx(le,{"code-path":"src/components/kubernetes/TopologyView.tsx:446:95",placeholder:"节点类型"})}),e.jsxs(ie,{"code-path":"src/components/kubernetes/TopologyView.tsx:447:11",className:"bg-slate-800 border-slate-700",children:[e.jsx(Z,{"code-path":"src/components/kubernetes/TopologyView.tsx:448:13",value:"all",children:"全部类型"}),Object.entries(pe).map(([s,n])=>e.jsx(Z,{"code-path":"src/components/kubernetes/TopologyView.tsx:449:63",value:s,children:n},s))]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:455:7",className:"grid grid-cols-1 lg:grid-cols-4 gap-6",children:[e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:456:9",className:"lg:col-span-3",children:e.jsx(oe,{"code-path":"src/components/kubernetes/TopologyView.tsx:457:11",className:"bg-slate-900 border-slate-800",children:e.jsx(ne,{"code-path":"src/components/kubernetes/TopologyView.tsx:458:13",className:"p-4",children:e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:459:15",className:`h-[600px] overflow-auto ${o?"ring-2 ring-amber-500/30 rounded-lg":""}`,children:z?e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:461:19",className:"flex items-center justify-center h-full",children:e.jsx(je,{"code-path":"src/components/kubernetes/TopologyView.tsx:461:76",className:"h-8 w-8 animate-spin text-slate-600"})}):l.nodes.length===0?e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:463:19",className:"flex flex-col items-center justify-center h-full text-slate-600",children:[e.jsx(de,{"code-path":"src/components/kubernetes/TopologyView.tsx:464:21",className:"h-12 w-12 mb-3 opacity-50"}),e.jsx("p",{"code-path":"src/components/kubernetes/TopologyView.tsx:465:21",className:"text-sm",children:x?"该集群暂无拓扑数据":"请选择集群查看拓扑"})]}):He()})})})}),e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:472:9",children:e.jsxs(oe,{"code-path":"src/components/kubernetes/TopologyView.tsx:473:11",className:"bg-slate-900 border-slate-800",children:[e.jsxs(os,{"code-path":"src/components/kubernetes/TopologyView.tsx:474:13",className:"pb-2",children:[e.jsx(ns,{"code-path":"src/components/kubernetes/TopologyView.tsx:475:15",className:"text-base text-slate-100",children:"节点列表"}),e.jsx(as,{"code-path":"src/components/kubernetes/TopologyView.tsx:476:15",className:"text-slate-500",children:"点击节点查看详情"})]}),e.jsx(ne,{"code-path":"src/components/kubernetes/TopologyView.tsx:478:13",children:e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:479:15",className:"space-y-2 max-h-[520px] overflow-auto",children:q.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/TopologyView.tsx:481:19",className:"text-sm text-slate-600 text-center py-8",children:"暂无节点"}):q.map(s=>e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:484:21",className:`flex items-center gap-3 p-2 rounded-lg cursor-pointer transition-colors ${r?.id===s.id?"bg-blue-500/10 border border-blue-500/30":"hover:bg-slate-800/50"}`,onClick:()=>N(s),children:[e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:485:23",className:`p-2 rounded-lg ${ee(s.type)}`,children:$(s.type)}),e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:486:23",className:"flex-1 min-w-0",children:[e.jsx("p",{"code-path":"src/components/kubernetes/TopologyView.tsx:487:25",className:"text-sm font-medium text-slate-200 truncate",children:s.name}),e.jsxs("p",{"code-path":"src/components/kubernetes/TopologyView.tsx:488:25",className:"text-xs text-slate-500",children:[pe[s.type]||s.type,X(s.id)?" · 自定义":""]})]})]},s.id))})})]})})]}),e.jsx(Ne,{"code-path":"src/components/kubernetes/TopologyView.tsx:500:7",open:!!r,onOpenChange:()=>N(null),children:e.jsxs(ve,{"code-path":"src/components/kubernetes/TopologyView.tsx:501:9",className:"bg-slate-900 border-slate-800 max-w-lg",children:[e.jsxs(Se,{"code-path":"src/components/kubernetes/TopologyView.tsx:502:11",children:[e.jsxs(Ce,{"code-path":"src/components/kubernetes/TopologyView.tsx:503:13",className:"text-slate-100 flex items-center gap-2",children:[e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:504:15",className:`p-2 rounded-lg ${ee(r?.type||"server")}`,children:r&&$(r.type)}),r?.name,r&&X(r.id)&&e.jsx(_e,{"code-path":"src/components/kubernetes/TopologyView.tsx:506:65",variant:"outline",className:"border-amber-500/30 text-amber-400 text-xs",children:"自定义"})]}),e.jsxs(Ee,{"code-path":"src/components/kubernetes/TopologyView.tsx:508:13",className:"text-slate-500",children:["类型: ",pe[r?.type||""]||r?.type]})]}),r&&e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:511:13",className:"space-y-4",children:[Qe(r),e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:513:15",children:[e.jsx("h4",{"code-path":"src/components/kubernetes/TopologyView.tsx:514:17",className:"text-sm font-medium text-slate-300 mb-2",children:"关联连接"}),e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:515:17",className:"space-y-2",children:[l.edges.filter(s=>s.source===r.id||s.target===r.id).map(s=>{const n=s.source===r.id,t=l.nodes.find(a=>a.id===(n?s.target:s.source));return t?e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:521:23",className:"flex items-center gap-2 p-2 rounded-lg bg-slate-800/50",children:[e.jsx("span",{"code-path":"src/components/kubernetes/TopologyView.tsx:522:25",className:"text-sm text-slate-400",children:n?"→":"←"}),e.jsx("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:523:25",className:`p-1 rounded ${ee(t.type)}`,children:$(t.type,"h-4 w-4")}),e.jsx("span",{"code-path":"src/components/kubernetes/TopologyView.tsx:524:25",className:"text-sm text-slate-300",children:t.name}),e.jsx(_e,{"code-path":"src/components/kubernetes/TopologyView.tsx:525:25",variant:"outline",className:"ml-auto border-slate-700 text-slate-400 text-xs",children:s.label})]},s.id):null}),l.edges.filter(s=>s.source===r.id||s.target===r.id).length===0&&e.jsx("p",{"code-path":"src/components/kubernetes/TopologyView.tsx:529:127",className:"text-xs text-slate-600",children:"无关联连接"})]})]}),y&&r&&e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:534:17",className:"flex gap-2 pt-2 border-t border-slate-700",children:[e.jsxs(v,{"code-path":"src/components/kubernetes/TopologyView.tsx:535:19",size:"sm",variant:"outline",className:"border-slate-600 text-slate-200",onClick:()=>ye(r),children:[e.jsx(Me,{"code-path":"src/components/kubernetes/TopologyView.tsx:536:21",className:"h-3.5 w-3.5 mr-1"}),"编辑"]}),X(r.id)&&e.jsxs(v,{"code-path":"src/components/kubernetes/TopologyView.tsx:539:21",size:"sm",variant:"outline",className:"border-red-500/30 text-red-400 hover:bg-red-500/10",onClick:()=>Pe(r),children:[e.jsx(ms,{"code-path":"src/components/kubernetes/TopologyView.tsx:540:23",className:"h-3.5 w-3.5 mr-1"}),"删除"]})]})]})]})}),e.jsx(Ne,{"code-path":"src/components/kubernetes/TopologyView.tsx:551:7",open:De,onOpenChange:H,children:e.jsxs(ve,{"code-path":"src/components/kubernetes/TopologyView.tsx:552:9",className:"bg-slate-900 border-slate-800 max-w-md",children:[e.jsxs(Se,{"code-path":"src/components/kubernetes/TopologyView.tsx:553:11",children:[e.jsx(Ce,{"code-path":"src/components/kubernetes/TopologyView.tsx:554:13",className:"text-slate-100",children:Q?"编辑节点":"添加自定义节点"}),e.jsx(Ee,{"code-path":"src/components/kubernetes/TopologyView.tsx:555:13",className:"text-slate-500",children:Q?"修改节点属性":"添加数据库、外部服务等非 Kubernetes 资源节点"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:557:11",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:558:13",className:"space-y-2",children:[e.jsx(ae,{"code-path":"src/components/kubernetes/TopologyView.tsx:559:15",className:"text-slate-300",children:"名称"}),e.jsx(Ve,{"code-path":"src/components/kubernetes/TopologyView.tsx:560:15",value:k.name,onChange:s=>U({...k,name:s.target.value}),placeholder:"如 MySQL 主库、Redis 集群",className:"bg-slate-800/50 border-slate-700 text-slate-200"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:563:13",className:"space-y-2",children:[e.jsx(ae,{"code-path":"src/components/kubernetes/TopologyView.tsx:564:15",className:"text-slate-300",children:"类型"}),e.jsxs(ce,{"code-path":"src/components/kubernetes/TopologyView.tsx:565:15",value:k.type,onValueChange:s=>U({...k,type:s}),children:[e.jsx(re,{"code-path":"src/components/kubernetes/TopologyView.tsx:566:17",className:"bg-slate-800/50 border-slate-700 text-slate-200",children:e.jsx(le,{"code-path":"src/components/kubernetes/TopologyView.tsx:566:92"})}),e.jsx(ie,{"code-path":"src/components/kubernetes/TopologyView.tsx:567:17",className:"bg-slate-800 border-slate-700",children:xs.map(s=>e.jsxs(Z,{"code-path":"src/components/kubernetes/TopologyView.tsx:568:49",value:s.value,children:[s.label," — ",s.desc]},s.value))})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/TopologyView.tsx:572:13",className:"space-y-2",children:[e.jsx(ae,{"code-path":"src/components/kubernetes/TopologyView.tsx:573:15",className:"text-slate-300",children:"备注"}),e.jsx(cs,{"code-path":"src/components/kubernetes/TopologyView.tsx:574:15",value:k.note,onChange:s=>U({...k,note:s.target.value}),placeholder:"连接信息、用途说明等",rows:2,className:"bg-slate-800/50 border-slate-700 text-slate-200 resize-none"})]})]}),e.jsxs(ts,{"code-path":"src/components/kubernetes/TopologyView.tsx:578:11",children:[e.jsx(v,{"code-path":"src/components/kubernetes/TopologyView.tsx:579:13",variant:"outline",className:"border-slate-700 text-slate-300",onClick:()=>H(!1),children:"取消"}),e.jsx(v,{"code-path":"src/components/kubernetes/TopologyView.tsx:580:13",onClick:Oe,children:Q?"保存":"添加"})]})]})})]})}export{$s as TopologyView}; diff --git a/backend/static/assets/TraceManager-D4FRDBfs.js b/backend/static/assets/TraceManager-D4FRDBfs.js new file mode 100644 index 0000000..21d3312 --- /dev/null +++ b/backend/static/assets/TraceManager-D4FRDBfs.js @@ -0,0 +1 @@ +import{r,j as e,A as ge,$ as z,x as H,S as Te,I as ue,B as y,U as je,K as Me,D as K,b as Q,c as U,d as Z,a0 as Ne,e as G,a1 as w,a2 as fe,a3 as ve,a4 as ye,n as we,q as be}from"./index-DfyorCky.js";import{B as N}from"./badge-xNW8x0G1.js";import{C as p,a as x,b,c as S}from"./card-C55cvSHg.js";import{S as C,a as D,b as I,c as L,d as n}from"./select-D5qUzdAs.js";import{T as Se,a as Ce,b as R,c as A}from"./tabs-CIh_yD4s.js";import{L as s}from"./label-BK0h2apY.js";import{t as B}from"./index-a3ybMjbR.js";import{t as F}from"./monitor-BAaBXIsC.js";import{L as De}from"./layers-FW4KKJMi.js";import{R as Ie}from"./refresh-cw-DUB_tAG-.js";import{T as Le}from"./trending-up-CdusV6gc.js";import{C as Re}from"./circle-x-DK79Dhg2.js";import{C as Ae}from"./code-L62jFLTC.js";import{B as Be}from"./box-TTGA1p57.js";import{Z as Fe}from"./zap-D2uWSK32.js";import{A as Oe}from"./arrow-right-DyIltvNZ.js";import"./index-CWVNW_qu.js";const _e=()=>{const[O,J]=r.useState([]),[l,X]=r.useState([]),[W,k]=r.useState(!1),[f,Y]=r.useState(""),[g,_]=r.useState("all"),[T,ee]=r.useState("all"),[u,ae]=r.useState("1h"),[te,re]=r.useState("traces"),[m,ce]=r.useState(null),[o,se]=r.useState(null),[oe,E]=r.useState(!1),[ne,$]=r.useState(!1);r.useEffect(()=>{me()},[u]);const me=async()=>{await Promise.all([P(),de()])},P=async()=>{k(!0);try{const a=await F.getTraces({timeRange:u,service:g,status:T});J(a.data||[])}catch{B.error("获取链路数据失败")}finally{k(!1)}},de=async()=>{try{const a=await F.getServices(u);X(a.data||[])}catch{B.error("获取服务数据失败")}},ie=async a=>{try{return(await F.getTraceDetail(a)).data}catch{return B.error("获取链路详情失败"),null}},v=a=>{switch(a){case"success":return e.jsxs(N,{"code-path":"src/components/monitor/trace/TraceManager.tsx:140:16",variant:"default",className:"bg-green-500 gap-1",children:[e.jsx(ve,{"code-path":"src/components/monitor/trace/TraceManager.tsx:140:72",className:"w-3 h-3"}),"成功"]});case"error":return e.jsxs(N,{"code-path":"src/components/monitor/trace/TraceManager.tsx:142:16",variant:"destructive",className:"gap-1",children:[e.jsx(Re,{"code-path":"src/components/monitor/trace/TraceManager.tsx:142:63",className:"w-3 h-3"}),"错误"]});case"pending":return e.jsxs(N,{"code-path":"src/components/monitor/trace/TraceManager.tsx:144:16",variant:"outline",className:"gap-1",children:[e.jsx(H,{"code-path":"src/components/monitor/trace/TraceManager.tsx:144:59",className:"w-3 h-3"}),"进行中"]});default:return e.jsx(N,{"code-path":"src/components/monitor/trace/TraceManager.tsx:146:16",variant:"secondary",children:"未知"})}},pe=a=>{switch(a){case"client":return e.jsx(Oe,{"code-path":"src/components/monitor/trace/TraceManager.tsx:152:29",className:"w-4 h-4"});case"server":return e.jsx(be,{"code-path":"src/components/monitor/trace/TraceManager.tsx:153:29",className:"w-4 h-4"});case"producer":return e.jsx(Fe,{"code-path":"src/components/monitor/trace/TraceManager.tsx:154:31",className:"w-4 h-4"});case"consumer":return e.jsx(Be,{"code-path":"src/components/monitor/trace/TraceManager.tsx:155:31",className:"w-4 h-4"});default:return e.jsx(Ae,{"code-path":"src/components/monitor/trace/TraceManager.tsx:156:23",className:"w-4 h-4"})}},xe=a=>{switch(a){case"success":return"bg-green-500";case"error":return"bg-red-500";case"pending":return"bg-yellow-500";default:return"bg-gray-500"}},d=a=>a<1?`${(a*1e3).toFixed(2)}μs`:a<1e3?`${a.toFixed(2)}ms`:`${(a/1e3).toFixed(2)}s`,V=O.filter(a=>{const t=a.traceId.toLowerCase().includes(f.toLowerCase())||a.operationName.toLowerCase().includes(f.toLowerCase()),i=g==="all"||a.serviceName===g,c=T==="all"||a.status===T;return t&&i&&c}),le=Array.from(new Set(O.map(a=>a.serviceName))),he=a=>{const t=new Map,i=[];return a.forEach(c=>{t.set(c.spanId,{...c,children:[]})}),a.forEach(c=>{const j=t.get(c.spanId);if(c.parentSpanId&&t.has(c.parentSpanId)){const h=t.get(c.parentSpanId);h.children=h.children||[],h.children.push(j)}else i.push(j)}),i},q=({span:a,level:t,totalDuration:i})=>{const[c,j]=r.useState(!0),h=i>0?a.duration/i*100:0;return e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:215:7",className:"select-none",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:216:9",className:"flex items-center py-2 hover:bg-muted/50 cursor-pointer border-l-2 border-transparent hover:border-blue-500",style:{paddingLeft:`${t*24+12}px`},onClick:()=>{se(a),$(!0)},children:[a.children?.length>0&&e.jsx(y,{"code-path":"src/components/monitor/trace/TraceManager.tsx:222:13",variant:"ghost",size:"sm",className:"h-4 w-4 p-0 mr-1",onClick:M=>{M.stopPropagation(),j(!c)},children:c?e.jsx(ye,{"code-path":"src/components/monitor/trace/TraceManager.tsx:228:27",className:"w-3 h-3"}):e.jsx(we,{"code-path":"src/components/monitor/trace/TraceManager.tsx:228:65",className:"w-3 h-3"})}),!a.children?.length&&e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:231:38",className:"w-5"}),e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:233:11",className:"flex items-center gap-2 flex-1 min-w-0",children:[pe(a.kind),e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:235:13",className:"font-medium truncate",children:a.operationName}),e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:236:13",className:"text-xs text-muted-foreground",children:a.serviceName})]}),e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:239:11",className:"flex items-center gap-4",children:[e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:240:13",className:"w-32 h-4 bg-muted rounded overflow-hidden",children:e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:241:15",className:`h-full ${xe(a.status)}`,style:{width:`${Math.max(h,1)}%`}})}),e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:246:13",className:"text-sm text-muted-foreground w-20 text-right",children:d(a.duration)}),a.status==="error"&&e.jsx(z,{"code-path":"src/components/monitor/trace/TraceManager.tsx:249:41",className:"w-4 h-4 text-red-500"})]})]}),c&&a.children?.map(M=>e.jsx(q,{"code-path":"src/components/monitor/trace/TraceManager.tsx:254:11",span:M,level:t+1,totalDuration:i},M.spanId))]})};return e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:261:5",className:"space-y-6",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:263:7",className:"grid grid-cols-4 gap-4",children:[e.jsx(p,{"code-path":"src/components/monitor/trace/TraceManager.tsx:264:9",children:e.jsx(x,{"code-path":"src/components/monitor/trace/TraceManager.tsx:265:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:266:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:267:15",children:[e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:268:17",className:"text-sm text-muted-foreground",children:"总请求数"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:269:17",className:"text-2xl font-bold",children:l.reduce((a,t)=>a+t.requestCount,0).toLocaleString()})]}),e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:271:15",className:"p-3 bg-blue-100 rounded-lg",children:e.jsx(ge,{"code-path":"src/components/monitor/trace/TraceManager.tsx:272:17",className:"w-5 h-5 text-blue-600"})})]})})}),e.jsx(p,{"code-path":"src/components/monitor/trace/TraceManager.tsx:277:9",children:e.jsx(x,{"code-path":"src/components/monitor/trace/TraceManager.tsx:278:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:279:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:280:15",children:[e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:281:17",className:"text-sm text-muted-foreground",children:"平均错误率"}),e.jsxs("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:282:17",className:"text-2xl font-bold",children:[(l.reduce((a,t)=>a+t.errorRate,0)/(l.length||1)).toFixed(2),"%"]})]}),e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:286:15",className:"p-3 bg-red-100 rounded-lg",children:e.jsx(z,{"code-path":"src/components/monitor/trace/TraceManager.tsx:287:17",className:"w-5 h-5 text-red-600"})})]})})}),e.jsx(p,{"code-path":"src/components/monitor/trace/TraceManager.tsx:292:9",children:e.jsx(x,{"code-path":"src/components/monitor/trace/TraceManager.tsx:293:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:294:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:295:15",children:[e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:296:17",className:"text-sm text-muted-foreground",children:"平均延迟"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:297:17",className:"text-2xl font-bold",children:d(l.reduce((a,t)=>a+t.avgDuration,0)/(l.length||1))})]}),e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:301:15",className:"p-3 bg-green-100 rounded-lg",children:e.jsx(H,{"code-path":"src/components/monitor/trace/TraceManager.tsx:302:17",className:"w-5 h-5 text-green-600"})})]})})}),e.jsx(p,{"code-path":"src/components/monitor/trace/TraceManager.tsx:307:9",children:e.jsx(x,{"code-path":"src/components/monitor/trace/TraceManager.tsx:308:11",className:"p-4",children:e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:309:13",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:310:15",children:[e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:311:17",className:"text-sm text-muted-foreground",children:"服务数量"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:312:17",className:"text-2xl font-bold",children:l.length})]}),e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:314:15",className:"p-3 bg-purple-100 rounded-lg",children:e.jsx(De,{"code-path":"src/components/monitor/trace/TraceManager.tsx:315:17",className:"w-5 h-5 text-purple-600"})})]})})})]}),e.jsxs(Se,{"code-path":"src/components/monitor/trace/TraceManager.tsx:322:7",value:te,onValueChange:re,children:[e.jsxs(Ce,{"code-path":"src/components/monitor/trace/TraceManager.tsx:323:9",className:"grid w-full grid-cols-3 lg:w-[400px]",children:[e.jsx(R,{"code-path":"src/components/monitor/trace/TraceManager.tsx:324:11",value:"traces",children:"链路追踪"}),e.jsx(R,{"code-path":"src/components/monitor/trace/TraceManager.tsx:325:11",value:"services",children:"服务拓扑"}),e.jsx(R,{"code-path":"src/components/monitor/trace/TraceManager.tsx:326:11",value:"metrics",children:"性能指标"})]}),e.jsxs(A,{"code-path":"src/components/monitor/trace/TraceManager.tsx:329:9",value:"traces",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:331:11",className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:332:13",className:"flex items-center gap-2 flex-1 min-w-[400px]",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:333:15",className:"relative flex-1",children:[e.jsx(Te,{"code-path":"src/components/monitor/trace/TraceManager.tsx:334:17",className:"absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-muted-foreground"}),e.jsx(ue,{"code-path":"src/components/monitor/trace/TraceManager.tsx:335:17",placeholder:"搜索Trace ID、操作名...",value:f,onChange:a=>Y(a.target.value),className:"pl-10"})]}),e.jsxs(C,{"code-path":"src/components/monitor/trace/TraceManager.tsx:342:15",value:g,onValueChange:_,children:[e.jsx(D,{"code-path":"src/components/monitor/trace/TraceManager.tsx:343:17",className:"w-[150px]",children:e.jsx(I,{"code-path":"src/components/monitor/trace/TraceManager.tsx:344:19",placeholder:"服务"})}),e.jsxs(L,{"code-path":"src/components/monitor/trace/TraceManager.tsx:346:17",children:[e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:347:19",value:"all",children:"全部服务"}),le.map(a=>e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:349:21",value:a,children:a},a))]})]}),e.jsxs(C,{"code-path":"src/components/monitor/trace/TraceManager.tsx:353:15",value:T,onValueChange:ee,children:[e.jsx(D,{"code-path":"src/components/monitor/trace/TraceManager.tsx:354:17",className:"w-[120px]",children:e.jsx(I,{"code-path":"src/components/monitor/trace/TraceManager.tsx:355:19",placeholder:"状态"})}),e.jsxs(L,{"code-path":"src/components/monitor/trace/TraceManager.tsx:357:17",children:[e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:358:19",value:"all",children:"全部状态"}),e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:359:19",value:"success",children:"成功"}),e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:360:19",value:"error",children:"错误"}),e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:361:19",value:"pending",children:"进行中"})]})]}),e.jsxs(C,{"code-path":"src/components/monitor/trace/TraceManager.tsx:364:15",value:u,onValueChange:ae,children:[e.jsx(D,{"code-path":"src/components/monitor/trace/TraceManager.tsx:365:17",className:"w-[120px]",children:e.jsx(I,{"code-path":"src/components/monitor/trace/TraceManager.tsx:366:19"})}),e.jsxs(L,{"code-path":"src/components/monitor/trace/TraceManager.tsx:368:17",children:[e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:369:19",value:"15m",children:"15分钟"}),e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:370:19",value:"1h",children:"1小时"}),e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:371:19",value:"6h",children:"6小时"}),e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:372:19",value:"24h",children:"24小时"}),e.jsx(n,{"code-path":"src/components/monitor/trace/TraceManager.tsx:373:19",value:"7d",children:"7天"})]})]})]}),e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:377:13",className:"flex items-center gap-2",children:e.jsxs(y,{"code-path":"src/components/monitor/trace/TraceManager.tsx:378:15",variant:"outline",onClick:P,children:[e.jsx(Ie,{"code-path":"src/components/monitor/trace/TraceManager.tsx:379:17",className:"w-4 h-4 mr-2"}),"刷新"]})})]}),e.jsx(p,{"code-path":"src/components/monitor/trace/TraceManager.tsx:386:11",children:e.jsx(x,{"code-path":"src/components/monitor/trace/TraceManager.tsx:387:13",className:"p-0",children:e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:388:15",className:"overflow-x-auto",children:e.jsxs("table",{"code-path":"src/components/monitor/trace/TraceManager.tsx:389:17",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/monitor/trace/TraceManager.tsx:390:19",className:"bg-muted/50",children:e.jsxs("tr",{"code-path":"src/components/monitor/trace/TraceManager.tsx:391:21",children:[e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:392:23",className:"px-4 py-3 text-left text-sm font-medium",children:"Trace ID"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:393:23",className:"px-4 py-3 text-left text-sm font-medium",children:"服务 / 操作"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:394:23",className:"px-4 py-3 text-left text-sm font-medium",children:"状态"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:395:23",className:"px-4 py-3 text-left text-sm font-medium",children:"耗时"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:396:23",className:"px-4 py-3 text-left text-sm font-medium",children:"Span数"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:397:23",className:"px-4 py-3 text-left text-sm font-medium",children:"时间"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:398:23",className:"px-4 py-3 text-left text-sm font-medium",children:"操作"})]})}),e.jsx("tbody",{"code-path":"src/components/monitor/trace/TraceManager.tsx:401:19",className:"divide-y",children:W?e.jsx("tr",{"code-path":"src/components/monitor/trace/TraceManager.tsx:403:23",children:e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:404:25",colSpan:7,className:"px-4 py-8 text-center text-muted-foreground",children:"加载中..."})}):V.length===0?e.jsx("tr",{"code-path":"src/components/monitor/trace/TraceManager.tsx:407:23",children:e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:408:25",colSpan:7,className:"px-4 py-8 text-center text-muted-foreground",children:"暂无链路数据"})}):V.map(a=>e.jsxs("tr",{"code-path":"src/components/monitor/trace/TraceManager.tsx:412:25",className:"hover:bg-muted/50",children:[e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:413:27",className:"px-4 py-3",children:e.jsxs("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:414:29",className:"font-mono text-sm text-blue-500",children:[a.traceId.slice(0,16),"..."]})}),e.jsxs("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:416:27",className:"px-4 py-3",children:[e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:417:29",className:"font-medium",children:a.operationName}),e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:418:29",className:"text-sm text-muted-foreground",children:a.serviceName})]}),e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:420:27",className:"px-4 py-3",children:v(a.status)}),e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:421:27",className:"px-4 py-3 text-sm",children:d(a.duration)}),e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:422:27",className:"px-4 py-3 text-sm",children:a.spanCount}),e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:423:27",className:"px-4 py-3 text-sm text-muted-foreground",children:a.startTime}),e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:424:27",className:"px-4 py-3",children:e.jsx(y,{"code-path":"src/components/monitor/trace/TraceManager.tsx:425:29",variant:"ghost",size:"sm",onClick:async()=>{const t=await ie(a.traceId);t&&(ce({...a,spans:t.spans}),E(!0))},children:e.jsx(je,{"code-path":"src/components/monitor/trace/TraceManager.tsx:436:31",className:"w-4 h-4"})})})]},a.id))})]})})})})]}),e.jsx(A,{"code-path":"src/components/monitor/trace/TraceManager.tsx:449:9",value:"services",className:"space-y-4",children:e.jsxs(p,{"code-path":"src/components/monitor/trace/TraceManager.tsx:450:11",children:[e.jsx(b,{"code-path":"src/components/monitor/trace/TraceManager.tsx:451:13",children:e.jsx(S,{"code-path":"src/components/monitor/trace/TraceManager.tsx:452:15",children:"服务性能概览"})}),e.jsx(x,{"code-path":"src/components/monitor/trace/TraceManager.tsx:454:13",children:e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:455:15",className:"overflow-x-auto",children:e.jsxs("table",{"code-path":"src/components/monitor/trace/TraceManager.tsx:456:17",className:"w-full",children:[e.jsx("thead",{"code-path":"src/components/monitor/trace/TraceManager.tsx:457:19",className:"bg-muted/50",children:e.jsxs("tr",{"code-path":"src/components/monitor/trace/TraceManager.tsx:458:21",children:[e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:459:23",className:"px-4 py-3 text-left text-sm font-medium",children:"服务名称"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:460:23",className:"px-4 py-3 text-left text-sm font-medium",children:"请求数"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:461:23",className:"px-4 py-3 text-left text-sm font-medium",children:"错误率"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:462:23",className:"px-4 py-3 text-left text-sm font-medium",children:"平均延迟"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:463:23",className:"px-4 py-3 text-left text-sm font-medium",children:"P95延迟"}),e.jsx("th",{"code-path":"src/components/monitor/trace/TraceManager.tsx:464:23",className:"px-4 py-3 text-left text-sm font-medium",children:"P99延迟"})]})}),e.jsx("tbody",{"code-path":"src/components/monitor/trace/TraceManager.tsx:467:19",className:"divide-y",children:l.map(a=>e.jsxs("tr",{"code-path":"src/components/monitor/trace/TraceManager.tsx:469:23",className:"hover:bg-muted/50",children:[e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:470:25",className:"px-4 py-3 font-medium",children:a.serviceName}),e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:471:25",className:"px-4 py-3",children:a.requestCount.toLocaleString()}),e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:472:25",className:"px-4 py-3",children:e.jsxs("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:473:27",className:a.errorRate>1?"text-red-500":"text-green-500",children:[a.errorRate.toFixed(2),"%"]})}),e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:477:25",className:"px-4 py-3",children:d(a.avgDuration)}),e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:478:25",className:"px-4 py-3",children:d(a.p95Duration)}),e.jsx("td",{"code-path":"src/components/monitor/trace/TraceManager.tsx:479:25",className:"px-4 py-3",children:d(a.p99Duration)})]},a.serviceName))})]})})})]})}),e.jsx(A,{"code-path":"src/components/monitor/trace/TraceManager.tsx:489:9",value:"metrics",className:"space-y-4",children:e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:490:11",className:"grid grid-cols-2 gap-4",children:[e.jsxs(p,{"code-path":"src/components/monitor/trace/TraceManager.tsx:491:13",children:[e.jsx(b,{"code-path":"src/components/monitor/trace/TraceManager.tsx:492:15",children:e.jsx(S,{"code-path":"src/components/monitor/trace/TraceManager.tsx:493:17",children:"延迟分布"})}),e.jsxs(x,{"code-path":"src/components/monitor/trace/TraceManager.tsx:495:15",className:"h-[300px] flex items-center justify-center text-muted-foreground",children:[e.jsx(Me,{"code-path":"src/components/monitor/trace/TraceManager.tsx:496:17",className:"w-16 h-16 mr-4"}),"延迟分布图表(集成图表库后显示)"]})]}),e.jsxs(p,{"code-path":"src/components/monitor/trace/TraceManager.tsx:500:13",children:[e.jsx(b,{"code-path":"src/components/monitor/trace/TraceManager.tsx:501:15",children:e.jsx(S,{"code-path":"src/components/monitor/trace/TraceManager.tsx:502:17",children:"错误率趋势"})}),e.jsxs(x,{"code-path":"src/components/monitor/trace/TraceManager.tsx:504:15",className:"h-[300px] flex items-center justify-center text-muted-foreground",children:[e.jsx(Le,{"code-path":"src/components/monitor/trace/TraceManager.tsx:505:17",className:"w-16 h-16 mr-4"}),"错误率趋势图表(集成图表库后显示)"]})]})]})})]}),e.jsx(K,{"code-path":"src/components/monitor/trace/TraceManager.tsx:514:7",open:oe,onOpenChange:E,children:e.jsxs(Q,{"code-path":"src/components/monitor/trace/TraceManager.tsx:515:9",className:"max-w-6xl max-h-[90vh]",children:[e.jsxs(U,{"code-path":"src/components/monitor/trace/TraceManager.tsx:516:11",children:[e.jsxs(Z,{"code-path":"src/components/monitor/trace/TraceManager.tsx:517:13",className:"flex items-center gap-2",children:[e.jsx(Ne,{"code-path":"src/components/monitor/trace/TraceManager.tsx:518:15",className:"w-5 h-5"}),"Trace详情",e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:520:15",className:"font-mono text-sm text-muted-foreground",children:m?.traceId})]}),e.jsx(G,{"code-path":"src/components/monitor/trace/TraceManager.tsx:522:13",className:"sr-only",children:"描述"})]}),m&&e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:525:13",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:526:15",className:"flex items-center gap-4 p-3 bg-muted rounded-lg",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:527:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:528:19",className:"text-xs text-muted-foreground",children:"服务"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:529:19",className:"font-medium",children:m.serviceName})]}),e.jsx(w,{"code-path":"src/components/monitor/trace/TraceManager.tsx:531:17",orientation:"vertical",className:"h-8"}),e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:532:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:533:19",className:"text-xs text-muted-foreground",children:"操作"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:534:19",className:"font-medium",children:m.operationName})]}),e.jsx(w,{"code-path":"src/components/monitor/trace/TraceManager.tsx:536:17",orientation:"vertical",className:"h-8"}),e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:537:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:538:19",className:"text-xs text-muted-foreground",children:"总耗时"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:539:19",className:"font-medium",children:d(m.duration)})]}),e.jsx(w,{"code-path":"src/components/monitor/trace/TraceManager.tsx:541:17",orientation:"vertical",className:"h-8"}),e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:542:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:543:19",className:"text-xs text-muted-foreground",children:"状态"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:544:19",children:v(m.status)})]})]}),e.jsx(fe,{"code-path":"src/components/monitor/trace/TraceManager.tsx:548:15",className:"h-[500px]",children:e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:549:17",className:"border rounded-lg",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:550:19",className:"flex items-center px-4 py-2 bg-muted/50 border-b text-sm font-medium",children:[e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:551:21",className:"flex-1",children:"Span名称"}),e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:552:21",className:"w-32",children:"时间线"}),e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:553:21",className:"w-20 text-right",children:"耗时"})]}),m.spans&&he(m.spans).map(a=>e.jsx(q,{"code-path":"src/components/monitor/trace/TraceManager.tsx:557:21",span:a,level:0,totalDuration:m.duration},a.spanId))]})})]})]})}),e.jsx(K,{"code-path":"src/components/monitor/trace/TraceManager.tsx:567:7",open:ne,onOpenChange:$,children:e.jsxs(Q,{"code-path":"src/components/monitor/trace/TraceManager.tsx:568:9",className:"max-w-2xl",children:[e.jsxs(U,{"code-path":"src/components/monitor/trace/TraceManager.tsx:569:11",children:[e.jsx(Z,{"code-path":"src/components/monitor/trace/TraceManager.tsx:570:13",children:"Span详情"}),e.jsx(G,{"code-path":"src/components/monitor/trace/TraceManager.tsx:571:13",className:"sr-only",children:"描述"})]}),o&&e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:574:13",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:575:15",className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:576:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:577:19",className:"text-muted-foreground",children:"Span ID"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:578:19",className:"font-mono text-sm",children:o.spanId})]}),e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:580:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:581:19",className:"text-muted-foreground",children:"类型"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:582:19",className:"capitalize",children:o.kind})]}),e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:584:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:585:19",className:"text-muted-foreground",children:"服务"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:586:19",className:"font-medium",children:o.serviceName})]}),e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:588:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:589:19",className:"text-muted-foreground",children:"操作"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:590:19",className:"font-medium",children:o.operationName})]}),e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:592:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:593:19",className:"text-muted-foreground",children:"状态"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:594:19",children:v(o.status)})]}),e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:596:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:597:19",className:"text-muted-foreground",children:"耗时"}),e.jsx("p",{"code-path":"src/components/monitor/trace/TraceManager.tsx:598:19",className:"font-medium",children:d(o.duration)})]})]}),Object.keys(o.tags).length>0&&e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:603:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:604:19",className:"text-muted-foreground",children:"标签"}),e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:605:19",className:"mt-1 p-3 bg-muted rounded-lg",children:Object.entries(o.tags).map(([a,t])=>e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:607:23",className:"flex justify-between text-sm py-1",children:[e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:608:25",className:"text-muted-foreground",children:a}),e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:609:25",className:"font-mono",children:t})]},a))})]}),o.logs?.length>0&&e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:617:17",children:[e.jsx(s,{"code-path":"src/components/monitor/trace/TraceManager.tsx:618:19",className:"text-muted-foreground",children:"日志"}),e.jsx("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:619:19",className:"mt-1 space-y-2",children:o.logs.map((a,t)=>e.jsxs("div",{"code-path":"src/components/monitor/trace/TraceManager.tsx:621:23",className:"p-2 bg-muted rounded text-sm",children:[e.jsx("span",{"code-path":"src/components/monitor/trace/TraceManager.tsx:622:25",className:"text-muted-foreground",children:a.timestamp}),e.jsx("pre",{"code-path":"src/components/monitor/trace/TraceManager.tsx:623:25",className:"mt-1 text-xs",children:JSON.stringify(a.fields,null,2)})]},t))})]})]})]})})]})};export{_e as default}; diff --git a/backend/static/assets/UserGroupsManager-nOJ7di7Y.js b/backend/static/assets/UserGroupsManager-nOJ7di7Y.js new file mode 100644 index 0000000..8528e4d --- /dev/null +++ b/backend/static/assets/UserGroupsManager-nOJ7di7Y.js @@ -0,0 +1 @@ +import{g as R,a as F,r as o,j as e,B as t,L as I,aa as w,t as O,I as u,D as T,b as _,c as A,d as H}from"./index-DfyorCky.js";import{B as $}from"./badge-xNW8x0G1.js";import{L as y}from"./label-BK0h2apY.js";import{t as a}from"./index-a3ybMjbR.js";import{d as n}from"./deploy-B3Sg3N1U.js";import{R as q}from"./refresh-cw-DUB_tAG-.js";import{P as K}from"./plus-CUG-9kpu.js";import{P as X}from"./pencil-BqUotcjf.js";import{T as J}from"./trash-2-Dx32pOzT.js";import{U as Q}from"./user-plus-BwUWtcQl.js";const V=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]],W=R("user-x",V);function de(){const g=F(),[G,k]=o.useState([]),[C,M]=o.useState(!0),[S,D]=o.useState({}),[z,p]=o.useState(!1),[l,U]=o.useState(null),[i,m]=o.useState(""),[x,h]=o.useState(""),[j,v]=o.useState(!1),[f,N]=o.useState({}),c=async()=>{M(!0);try{const s=await n.getGroups();k(s?.list||[])}catch{a.error("加载失败")}finally{M(!1)}};o.useEffect(()=>{c()},[]);const E=async()=>{if(!i.trim()){a.error("请输入组名");return}v(!0);try{l?await n.updateGroup(l,{name:i,description:x}):await n.createGroup({name:i,description:x}),a.success(l?"已更新":"已创建"),p(!1),c()}catch{a.error("操作失败")}finally{v(!1)}},L=async s=>{if(await g({title:"删除用户组",description:`确定删除「${s.name}」?所有成员和流水线授权将同时移除。`,variant:"destructive"}))try{await n.deleteGroup(s.id),a.success("已删除"),c()}catch{a.error("删除失败")}},b=async s=>{const r=(f[s]||"").trim();if(!r){a.error("输入用户名");return}try{await n.addGroupMember(s,{username:r}),a.success("已添加"),c(),N(d=>({...d,[s]:""}))}catch{a.error("添加失败")}},P=async(s,r,d)=>{if(await g({title:"移除成员",description:`确定从组中移除「${d}」?`}))try{await n.removeGroupMember(s,r),a.success("已移除"),c()}catch{a.error("移除失败")}},B=s=>D(r=>({...r,[s]:!r[s]}));return e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:81:5",className:"space-y-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:82:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:83:9",children:[e.jsx("h2",{"code-path":"src/components/deploy/UserGroupsManager.tsx:84:11",className:"text-lg font-semibold text-[var(--dg-text-primary)]",children:"用户组管理"}),e.jsx("p",{"code-path":"src/components/deploy/UserGroupsManager.tsx:85:11",className:"text-sm text-[var(--dg-text-secondary)] mt-1",children:"创建用户组,将组授权给流水线,组内成员自动获得流水线权限"})]}),e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:87:9",className:"flex items-center gap-2",children:[e.jsxs(t,{"code-path":"src/components/deploy/UserGroupsManager.tsx:88:11",variant:"outline",size:"sm",onClick:c,children:[e.jsx(q,{"code-path":"src/components/deploy/UserGroupsManager.tsx:88:68",className:"w-4 h-4 mr-1"}),"刷新"]}),e.jsxs(t,{"code-path":"src/components/deploy/UserGroupsManager.tsx:89:11",size:"sm",onClick:()=>{U(null),m(""),h(""),p(!0)},children:[e.jsx(K,{"code-path":"src/components/deploy/UserGroupsManager.tsx:90:13",className:"w-4 h-4 mr-1"}),"新建用户组"]})]})]}),C?e.jsx("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:96:9",className:"flex justify-center py-12",children:e.jsx(I,{"code-path":"src/components/deploy/UserGroupsManager.tsx:96:52",className:"w-6 h-6 animate-spin text-[var(--dg-text-secondary)]"})}):G.length===0?e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:98:9",className:"text-center py-12 text-[var(--dg-text-secondary)]",children:[e.jsx(w,{"code-path":"src/components/deploy/UserGroupsManager.tsx:99:11",className:"w-10 h-10 mx-auto mb-3 opacity-30"}),e.jsx("p",{"code-path":"src/components/deploy/UserGroupsManager.tsx:100:11",children:"暂无用户组,点击「新建用户组」创建"})]}):e.jsx("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:103:9",className:"space-y-3",children:G.map(s=>e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:105:13",className:"border border-[var(--dg-border)] rounded-lg bg-[var(--dg-bg-secondary)]",children:[e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:106:15",className:"flex items-center justify-between p-4",children:[e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:107:17",className:"flex items-center gap-3",style:{cursor:"pointer"},onClick:()=>B(s.id),children:[e.jsx(O,{"code-path":"src/components/deploy/UserGroupsManager.tsx:108:19",className:"w-5 h-5 text-blue-400"}),e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:109:19",children:[e.jsx("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:110:21",className:"font-medium text-[var(--dg-text-primary)]",children:s.name}),e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:111:21",className:"text-xs text-[var(--dg-text-secondary)]",children:[s.description||"暂无描述"," · ",(s.members||[]).length," 位成员"]})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:114:17",className:"flex items-center gap-2",children:[e.jsx(t,{"code-path":"src/components/deploy/UserGroupsManager.tsx:115:19",variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{U(s.id),m(s.name),h(s.description||""),p(!0)},children:e.jsx(X,{"code-path":"src/components/deploy/UserGroupsManager.tsx:116:21",className:"w-4 h-4"})}),e.jsx(t,{"code-path":"src/components/deploy/UserGroupsManager.tsx:118:19",variant:"ghost",size:"icon",className:"h-8 w-8 text-red-500",onClick:()=>L(s),children:e.jsx(J,{"code-path":"src/components/deploy/UserGroupsManager.tsx:119:21",className:"w-4 h-4"})})]})]}),S[s.id]&&e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:125:17",className:"border-t border-[var(--dg-border)] px-4 py-3 space-y-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:127:19",className:"flex items-end gap-2",children:[e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:128:21",className:"flex-1 space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/UserGroupsManager.tsx:128:55",className:"text-xs",children:"添加用户"}),e.jsx(u,{"code-path":"src/components/deploy/UserGroupsManager.tsx:129:23",value:f[s.id]||"",onChange:r=>N(d=>({...d,[s.id]:r.target.value})),placeholder:"输入用户名",className:"h-8 text-sm",onKeyDown:r=>r.key==="Enter"&&b(s.id)})]}),e.jsxs(t,{"code-path":"src/components/deploy/UserGroupsManager.tsx:131:21",size:"sm",className:"h-8",onClick:()=>b(s.id),children:[e.jsx(Q,{"code-path":"src/components/deploy/UserGroupsManager.tsx:131:93",className:"w-3.5 h-3.5 mr-1"}),"添加"]})]}),(s.members||[]).length===0?e.jsx("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:135:21",className:"text-xs text-[var(--dg-text-secondary)] py-2",children:"暂无成员"}):e.jsx("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:137:21",className:"flex flex-wrap gap-2",children:(s.members||[]).map(r=>e.jsxs($,{"code-path":"src/components/deploy/UserGroupsManager.tsx:139:25",variant:"secondary",className:"flex items-center gap-1 pl-2 pr-1 py-1.5",children:[e.jsx(w,{"code-path":"src/components/deploy/UserGroupsManager.tsx:140:27",className:"w-3 h-3"}),r.username,e.jsx("button",{"code-path":"src/components/deploy/UserGroupsManager.tsx:141:27",className:"ml-1 hover:text-red-400",onClick:()=>P(s.id,r.id,r.username),children:e.jsx(W,{"code-path":"src/components/deploy/UserGroupsManager.tsx:142:29",className:"w-3 h-3"})})]},r.id))})]})]},s.id))}),e.jsx(T,{"code-path":"src/components/deploy/UserGroupsManager.tsx:156:7",open:z,onOpenChange:p,children:e.jsxs(_,{"code-path":"src/components/deploy/UserGroupsManager.tsx:157:9",children:[e.jsx(A,{"code-path":"src/components/deploy/UserGroupsManager.tsx:158:11",children:e.jsx(H,{"code-path":"src/components/deploy/UserGroupsManager.tsx:158:25",children:l?"编辑用户组":"新建用户组"})}),e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:159:11",className:"space-y-3",children:[e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:160:13",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/UserGroupsManager.tsx:160:40",children:"组名"}),e.jsx(u,{"code-path":"src/components/deploy/UserGroupsManager.tsx:160:57",value:i,onChange:s=>m(s.target.value),placeholder:"例如: 后端开发组"})]}),e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:161:13",className:"space-y-1",children:[e.jsx(y,{"code-path":"src/components/deploy/UserGroupsManager.tsx:161:40",children:"描述"}),e.jsx(u,{"code-path":"src/components/deploy/UserGroupsManager.tsx:161:57",value:x,onChange:s=>h(s.target.value),placeholder:"可选"})]})]}),e.jsxs("div",{"code-path":"src/components/deploy/UserGroupsManager.tsx:163:11",className:"flex justify-end gap-2 mt-4 pt-4 border-t",children:[e.jsx(t,{"code-path":"src/components/deploy/UserGroupsManager.tsx:164:13",variant:"outline",onClick:()=>p(!1),children:"取消"}),e.jsx(t,{"code-path":"src/components/deploy/UserGroupsManager.tsx:165:13",onClick:E,disabled:j,children:j?"...":"保存"})]})]})})]})}export{de as default}; diff --git a/backend/static/assets/WorkloadViewPage-Koq6nkyo.js b/backend/static/assets/WorkloadViewPage-Koq6nkyo.js new file mode 100644 index 0000000..5586d45 --- /dev/null +++ b/backend/static/assets/WorkloadViewPage-Koq6nkyo.js @@ -0,0 +1,2 @@ +import{i as Ue,k as Te,z as Re,r as d,j as e,B as x,p as ne,R as Le,F as $e,E as Ae,G as Me,v as he,A as ze,H as Be}from"./index-DfyorCky.js";import{C as V,a as W,b as y,c as S}from"./card-C55cvSHg.js";import{B as j}from"./badge-xNW8x0G1.js";import{T as ce,a as le,b as C,c as h,d as de,e as i}from"./table-5sHV4Akp.js";import{k as U}from"./kubernetes-J8O09fK7.js";import{u as Oe}from"./use-toast-CrSOP4cJ.js";import{Y as ie,S as w,f as me,s as I,P as Fe,a as He}from"./PodFileBrowser-BySN2XGN.js";import{A as _e}from"./arrow-left-BDgGyrD0.js";import{T as Ye}from"./tag-0HCfq8kH.js";import{H as De}from"./hard-drive-BbPmnARR.js";import{M as Ee}from"./minus-UVrx3jLc.js";import{P as Ie}from"./plus-CUG-9kpu.js";import"./copy-DXW4LnkN.js";import"./sparkles-Bld4NX5y.js";import"./save-DoGGjfwC.js";import"./select-D5qUzdAs.js";import"./index-CWVNW_qu.js";import"./xterm-DSqgeKvr.js";import"./box-TTGA1p57.js";import"./rotate-cw-5qcj_h_q.js";import"./minimize-2-CiCQYRfn.js";import"./upload-Ba6rlaGS.js";import"./refresh-cw-DUB_tAG-.js";import"./folder-DoMwqvzv.js";import"./download-DoZfYs2h.js";function n({label:t,value:m,sub:P,color:u}){return e.jsx(V,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:28:5",className:"bg-slate-900 border-slate-800",children:e.jsxs(W,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:29:7",className:"p-3",children:[e.jsx("p",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:30:9",className:"text-xs text-slate-500",children:t}),e.jsx("p",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:31:9",className:"text-base font-bold mt-0.5",style:{color:u||"#e2e8f0"},children:m}),P&&e.jsx("p",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:32:17",className:"text-[10px] text-slate-600 mt-0.5",children:P})]})})}function pe({labels:t}){const m=Object.entries(t||{});return m.length===0?e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:41:36",className:"text-xs text-slate-600",children:"无"}):e.jsx("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:43:5",className:"flex flex-wrap gap-1.5",children:m.map(([P,u])=>e.jsxs(j,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:45:9",variant:"outline",className:"border-slate-700 text-slate-400 text-[10px] font-mono",children:[P,"=",u]},P))})}function gs(){const t=Ue(),m=Te(),P=Re(),{toast:u}=Oe(),o=t.clusterCode||"",r=t.namespace||"",c=t.name||"",p=P.pathname.includes("/DaemonSet/")?"DaemonSet":"StatefulSet",T=t.mode==="yaml"?"yaml":"view",[N,ke]=d.useState(null),[R,ue]=d.useState([]),[be,J]=d.useState(!0),[ge,L]=d.useState(!1),[v,F]=d.useState(1),[$,A]=d.useState(!1),[H,q]=d.useState(null),[_,G]=d.useState(null),[we,K]=d.useState(!1),M=d.useCallback(async()=>{J(!0);try{const[s,l]=await Promise.all([U.getResourceYaml(o,r,p.toLowerCase()+"s",c).catch(()=>""),U.getPods(o).catch(()=>[])]);let f=null;if(s&&typeof s=="string")try{f=JSON.parse(s)}catch{f={_raw:s}}else s&&typeof s=="object"&&(f=s);ke(f);const E=(Array.isArray(l)?l:l?.list||l?.data||[]).filter(O=>{const Ce=O.name||O.metadata?.name||"",re=O.namespace||O.namespace_name||"";return Ce.startsWith(c)&&(!re||re===r)});ue(E)}catch(s){console.error("load error",s)}finally{J(!1)}},[o,r,c,p]);d.useEffect(()=>{M()},[M]);const Q=s=>{s!==T&&m(`/kubernetes/${o}/namespace/${r}/workload/${s}/${p}/${c}`,{replace:!0})},je=async()=>{if(confirm(`确认重启 ${p} ${c}? +将触发滚动重启。`)){A(!0);try{p==="StatefulSet"?await U.restartStatefulSet(o,r,c):await U.restartDaemonSet(o,r,c),u({title:"重启指令已下发",description:`${p} 滚动重启已触发`}),setTimeout(M,1e3)}catch(s){u({title:"重启失败",description:s?.message||String(s),variant:"destructive"})}finally{A(!1)}}},Pe=async()=>{A(!0);try{await U.scaleStatefulSet(o,r,c,v),u({title:"扩缩容成功",description:`StatefulSet 副本数已更新为 ${v}`}),L(!1),setTimeout(M,1e3)}catch(s){u({title:"扩缩容失败",description:s?.message||String(s),variant:"destructive"})}finally{A(!1)}},k=N?.spec||{},b=N?.status||{},X=k?.template?.spec?.containers||[],Z=k?.template?.spec?.initContainers||[],z=k.replicas??1,ee=b.readyReplicas??0,Ve=b.currentReplicas??0,We=b.updatedReplicas??0,Y=b.desiredNumberScheduled??0,Ne=b.currentNumberScheduled??0,se=b.numberReady??0,fe=b.numberAvailable??0,ve=b.updatedNumberScheduled??0,g=p==="StatefulSet",B=g?ee===z&&z>0:se===Y&&Y>0,a=k.updateStrategy||{},D=a.type||"RollingUpdate",te=k.volumeClaimTemplates||[],ye=k.selector?.matchLabels||{},Se=N?.metadata?.labels||{},ae=N?.metadata?.annotations||{};return e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:183:5",className:"p-4 space-y-4",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:185:7",className:"flex items-center justify-between",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:186:9",className:"flex items-center gap-3",children:[e.jsx(x,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:187:11",variant:"ghost",size:"icon",className:"h-8 w-8 text-slate-400 hover:text-slate-200",onClick:()=>m(-1),children:e.jsx(_e,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:188:13",className:"h-4 w-4"})}),e.jsx(ne,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:190:11",className:"h-5 w-5 text-blue-400"}),e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:191:11",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:192:13",className:"flex items-center gap-2",children:[e.jsx("h1",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:193:15",className:"text-lg font-bold text-slate-100",children:c}),e.jsx(j,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:194:15",variant:"outline",className:"border-slate-700 text-slate-400",children:p}),e.jsx(j,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:195:15",variant:"outline",className:"border-slate-700 text-slate-400",children:r}),B?e.jsx(j,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:197:19",className:"bg-emerald-500/20 text-emerald-400 border-emerald-500/30",children:"健康"}):e.jsx(j,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:198:19",className:"bg-amber-500/20 text-amber-400 border-amber-500/30",children:"更新中"})]}),e.jsxs("p",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:200:13",className:"text-xs text-slate-500 mt-0.5",children:["集群: ",o]})]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:203:9",className:"flex items-center gap-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:205:11",className:"flex items-center gap-1 bg-slate-900 border border-slate-800 rounded-lg p-0.5",children:[e.jsx("button",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:206:13",className:`px-3 py-1 text-xs rounded transition-colors ${T==="view"?"bg-blue-500/20 text-blue-400":"text-slate-400 hover:text-slate-200"}`,onClick:()=>Q("view"),children:"查看"}),e.jsx("button",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:210:13",className:`px-3 py-1 text-xs rounded transition-colors ${T==="yaml"?"bg-blue-500/20 text-blue-400":"text-slate-400 hover:text-slate-200"}`,onClick:()=>Q("yaml"),children:"YAML"})]}),g&&e.jsxs(x,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:217:13",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300 hover:text-slate-100",onClick:()=>{F(z),L(!0)},children:[e.jsx(ne,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:219:15",className:"h-3.5 w-3.5 mr-1"}),"伸缩"]}),e.jsxs(x,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:222:11",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300 hover:text-slate-100",disabled:$,onClick:je,children:[e.jsx(Le,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:224:13",className:"h-3.5 w-3.5 mr-1"}),$?"重启中...":"重启"]}),e.jsxs(x,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:226:11",variant:"outline",size:"sm",className:"h-8 border-slate-700 text-slate-300 hover:text-slate-100",onClick:()=>K(!0),children:[e.jsx($e,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:228:13",className:"h-3.5 w-3.5 mr-1"}),"YAML"]})]})]}),be?e.jsx("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:234:9",className:"text-center text-slate-500 py-20",children:"加载中..."}):T==="yaml"?e.jsx(V,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:236:9",className:"bg-slate-900 border-slate-800",children:e.jsx(W,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:237:11",className:"p-4",children:e.jsx(ie,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:238:13",clusterCode:o,namespace:r,resource:p.toLowerCase()+"s",name:c,onClose:()=>{},inline:!0,autoEdit:!0})})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:252:11",className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-3",children:g?e.jsxs(e.Fragment,{children:[e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:255:17",label:"副本就绪",value:`${ee}/${z}`,color:B?w.green:w.orange,sub:B?"全部就绪":"部分未就绪"}),e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:256:17",label:"当前副本",value:Ve,color:w.blue}),e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:257:17",label:"已更新副本",value:We,color:w.green}),e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:258:17",label:"服务名",value:k.serviceName||"-",color:"#94a3b8"}),e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:259:17",label:"Pod 数量",value:R.length,color:"#94a3b8"}),e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:260:17",label:"创建时间",value:e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:260:47",className:"text-xs",children:me(N?.metadata?.creationTimestamp)}),color:"#94a3b8"})]}):e.jsxs(e.Fragment,{children:[e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:264:17",label:"期望调度",value:Y,color:w.blue}),e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:265:17",label:"当前调度",value:Ne,color:"#94a3b8"}),e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:266:17",label:"就绪数量",value:se,color:B?w.green:w.orange}),e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:267:17",label:"可用数量",value:fe,color:w.green}),e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:268:17",label:"已更新",value:ve,color:"#94a3b8"}),e.jsx(n,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:269:17",label:"创建时间",value:e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:269:47",className:"text-xs",children:me(N?.metadata?.creationTimestamp)}),color:"#94a3b8"})]})}),e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:275:11",className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(V,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:276:13",className:"bg-slate-900 border-slate-800",children:[e.jsx(y,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:277:15",className:"pb-3",children:e.jsxs(S,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:278:17",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(Ae,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:279:19",className:"h-4 w-4 text-amber-400"}),"更新策略"]})}),e.jsxs(W,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:282:15",className:"pt-0 space-y-2 text-xs",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:283:17",className:"flex justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:284:19",className:"text-slate-500",children:"策略类型"}),e.jsx(j,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:285:19",variant:"outline",className:"border-slate-700 text-slate-300",children:D})]}),D==="RollingUpdate"&&g&&a.rollingUpdate&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:289:21",className:"flex justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:290:23",className:"text-slate-500",children:"分区 (partition)"}),e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:291:23",className:"text-slate-300 font-mono",children:a.rollingUpdate.partition??0})]}),a.rollingUpdate.maxUnavailable&&e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:294:23",className:"flex justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:295:25",className:"text-slate-500",children:"最大不可用"}),e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:296:25",className:"text-slate-300 font-mono",children:typeof a.rollingUpdate.maxUnavailable=="object"?JSON.stringify(a.rollingUpdate.maxUnavailable):a.rollingUpdate.maxUnavailable})]})]}),D==="RollingUpdate"&&!g&&a.rollingUpdate&&e.jsxs(e.Fragment,{children:[a.rollingUpdate.maxUnavailable&&e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:304:23",className:"flex justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:305:25",className:"text-slate-500",children:"最大不可用"}),e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:306:25",className:"text-slate-300 font-mono",children:typeof a.rollingUpdate.maxUnavailable=="object"?JSON.stringify(a.rollingUpdate.maxUnavailable):a.rollingUpdate.maxUnavailable})]}),a.rollingUpdate.maxSurge&&e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:310:23",className:"flex justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:311:25",className:"text-slate-500",children:"最大 surge"}),e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:312:25",className:"text-slate-300 font-mono",children:typeof a.rollingUpdate.maxSurge=="object"?JSON.stringify(a.rollingUpdate.maxSurge):a.rollingUpdate.maxSurge})]})]}),g&&e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:318:19",className:"flex justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:319:21",className:"text-slate-500",children:"Pod 管理策略"}),e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:320:21",className:"text-slate-300 font-mono",children:k.podManagementPolicy||"OrderedReady"})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:323:17",className:"flex justify-between",children:[e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:324:19",className:"text-slate-500",children:"修订历史限制"}),e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:325:19",className:"text-slate-300 font-mono",children:k.revisionHistoryLimit??10})]})]})]}),e.jsxs(V,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:330:13",className:"bg-slate-900 border-slate-800",children:[e.jsx(y,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:331:15",className:"pb-3",children:e.jsxs(S,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:332:17",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(Ye,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:333:19",className:"h-4 w-4 text-purple-400"}),"选择器与标签"]})}),e.jsxs(W,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:336:15",className:"pt-0 space-y-3 text-xs",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:337:17",children:[e.jsx("p",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:338:19",className:"text-slate-500 mb-1.5",children:"Selector (matchLabels)"}),e.jsx(pe,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:339:19",labels:ye})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:341:17",children:[e.jsx("p",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:342:19",className:"text-slate-500 mb-1.5",children:"Labels"}),e.jsx(pe,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:343:19",labels:Se})]}),Object.keys(ae).length>0&&e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:346:19",children:[e.jsx("p",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:347:21",className:"text-slate-500 mb-1.5",children:"Annotations"}),e.jsx("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:348:21",className:"flex flex-wrap gap-1.5",children:Object.entries(ae).slice(0,8).map(([s,l])=>e.jsx(j,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:350:25",variant:"outline",className:"border-slate-700 text-slate-500 text-[10px] font-mono max-w-[300px] truncate",children:s},s))})]})]})]})]}),g&&te.length>0&&e.jsxs(V,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:363:13",className:"bg-slate-900 border-slate-800",children:[e.jsx(y,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:364:15",className:"pb-3",children:e.jsxs(S,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:365:17",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(Me,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:366:19",className:"h-4 w-4 text-cyan-400"}),"存储卷声明模板 (VolumeClaimTemplates)"]})}),e.jsx(W,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:369:15",className:"pt-0",children:e.jsxs(ce,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:370:17",children:[e.jsx(le,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:371:19",children:e.jsxs(C,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:372:21",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(h,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:373:23",className:"text-slate-400",children:"名称"}),e.jsx(h,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:374:23",className:"text-slate-400",children:"访问模式"}),e.jsx(h,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:375:23",className:"text-slate-400",children:"存储类"}),e.jsx(h,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:376:23",className:"text-slate-400",children:"大小"})]})}),e.jsx(de,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:379:19",children:te.map((s,l)=>{const f=(s.spec?.accessModes||[]).join(", "),oe=s.spec?.storageClassName||s.spec?.storageClassName||"-",E=s.spec?.resources?.requests?.storage||"-";return e.jsxs(C,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:385:25",className:"border-slate-800",children:[e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:386:27",className:"font-medium text-slate-200",children:s.metadata?.name||"-"}),e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:387:27",className:"text-sm text-slate-400",children:f||"-"}),e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:388:27",className:"text-sm text-slate-400",children:oe}),e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:389:27",className:"text-sm text-slate-300 font-mono",children:E})]},l)})})]})})]}),e.jsxs(V,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:400:11",className:"bg-slate-900 border-slate-800",children:[e.jsx(y,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:401:13",className:"pb-3",children:e.jsxs(S,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:402:15",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(he,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:403:17",className:"h-4 w-4 text-blue-400"}),"容器模板(Pod Template)"]})}),e.jsxs(W,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:406:13",className:"pt-0",children:[Z.length>0&&e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:408:17",className:"mb-3",children:[e.jsx("p",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:409:19",className:"text-[11px] text-slate-500 mb-2 uppercase tracking-wide",children:"Init Containers"}),e.jsx("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:410:19",className:"space-y-2",children:Z.map((s,l)=>e.jsx(xe,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:412:23",c:s},`init-${l}`))})]}),X.length===0?e.jsx("p",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:418:17",className:"text-xs text-slate-500 py-3",children:"暂无容器数据,请查看 YAML"}):e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:420:17",className:"space-y-3",children:[e.jsx("p",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:421:19",className:"text-[11px] text-slate-500 mb-1 uppercase tracking-wide",children:"Containers"}),X.map((s,l)=>e.jsx(xe,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:423:21",c:s},l))]})]})]}),e.jsxs(V,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:431:11",className:"bg-slate-900 border-slate-800",children:[e.jsx(y,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:432:13",className:"pb-3",children:e.jsxs(S,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:433:15",className:"text-sm text-slate-200 flex items-center gap-2",children:[e.jsx(ze,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:434:17",className:"h-4 w-4 text-emerald-400"}),"Pod 实例 (",R.length,")"]})}),e.jsx(W,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:437:13",className:"p-0",children:e.jsxs(ce,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:438:15",children:[e.jsx(le,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:439:17",children:e.jsxs(C,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:440:19",className:"border-slate-800 hover:bg-transparent",children:[e.jsx(h,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:441:21",className:"text-slate-400",children:"Pod 名称"}),e.jsx(h,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:442:21",className:"text-slate-400",children:"状态"}),e.jsx(h,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:443:21",className:"text-slate-400",children:"所在节点"}),e.jsx(h,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:444:21",className:"text-slate-400",children:"Pod IP"}),e.jsx(h,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:445:21",className:"text-slate-400",children:"重启"}),e.jsx(h,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:446:21",className:"text-slate-400",children:"操作"})]})}),e.jsx(de,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:449:17",children:R.length===0?e.jsx(C,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:451:21",children:e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:451:31",colSpan:6,className:"text-center text-slate-500 py-8",children:"暂无 Pod"})}):R.map(s=>e.jsxs(C,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:453:21",className:"border-slate-800 hover:bg-slate-800/30",children:[e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:454:23",className:"font-medium text-slate-200",children:s.name}),e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:455:23",children:e.jsx(j,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:456:25",style:{background:`${I(s.status)}22`,color:I(s.status),border:`1px solid ${I(s.status)}44`},children:s.status||"Unknown"})}),e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:460:23",className:"text-sm text-slate-400",children:s.node_name||s.node||"-"}),e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:461:23",className:"text-sm text-slate-400 font-mono",children:s.ip||s.pod_ip||"-"}),e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:462:23",className:(s.restart_count||0)>0?"text-yellow-400":"text-slate-500",children:s.restart_count||0}),e.jsx(i,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:463:23",children:e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:464:25",className:"flex items-center gap-1",children:[e.jsxs(x,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:465:27",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-emerald-400 hover:text-emerald-300 hover:bg-emerald-500/10",onClick:()=>q(s),children:[e.jsx(Be,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:467:29",className:"h-3.5 w-3.5 mr-1"}),"终端"]}),e.jsxs(x,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:469:27",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs text-amber-400 hover:text-amber-300 hover:bg-amber-500/10",onClick:()=>G(s),children:[e.jsx(De,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:471:29",className:"h-3.5 w-3.5 mr-1"}),"文件浏览器"]})]})})]},s.name))})]})})]})]}),ge&&e.jsx("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:486:9",className:"fixed inset-0 bg-black/60 z-50 flex items-center justify-center",onClick:()=>L(!1),children:e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:487:11",className:"bg-slate-900 border border-slate-800 rounded-lg p-6 w-80",onClick:s=>s.stopPropagation(),children:[e.jsx("h3",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:488:13",className:"text-sm font-semibold text-slate-200 mb-4",children:"伸缩 StatefulSet"}),e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:489:13",className:"flex items-center justify-center gap-4 mb-4",children:[e.jsx(x,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:490:15",variant:"outline",size:"icon",className:"h-9 w-9",onClick:()=>F(Math.max(0,v-1)),children:e.jsx(Ee,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:491:17",className:"h-4 w-4"})}),e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:493:15",className:"text-2xl font-bold text-slate-100 w-12 text-center",children:v}),e.jsx(x,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:494:15",variant:"outline",size:"icon",className:"h-9 w-9",onClick:()=>F(v+1),children:e.jsx(Ie,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:495:17",className:"h-4 w-4"})})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:498:13",className:"flex gap-2",children:[e.jsx(x,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:499:15",variant:"outline",size:"sm",className:"flex-1 border-slate-700 text-slate-400",onClick:()=>L(!1),children:"取消"}),e.jsx(x,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:500:15",size:"sm",className:"flex-1 bg-blue-600 hover:bg-blue-500",disabled:$,onClick:Pe,children:$?"执行中...":"确认"})]})]})}),we&&e.jsx(ie,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:510:9",clusterCode:o,namespace:r,resource:p.toLowerCase()+"s",name:c,onClose:()=>K(!1)}),H&&e.jsx(Fe,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:521:9",open:!0,onOpenChange:s=>{s||q(null)},clusterId:o,namespace:r,podName:H.name,containers:H.containers?.map(s=>s.name).filter(Boolean)||[]}),_&&e.jsx(He,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:533:9",open:!0,onOpenChange:s=>{s||G(null)},clusterCode:o,namespace:r,podName:_.name,containers:_.containers?.map(s=>s.name).filter(Boolean)||[]})]})}function xe({c:t}){return e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:549:5",className:"border border-slate-800 rounded-lg p-3 bg-slate-950/30",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:550:7",className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:551:9",className:"flex items-center gap-2",children:[e.jsx(he,{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:552:11",className:"h-4 w-4 text-blue-400"}),e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:553:11",className:"text-sm font-semibold text-slate-200",children:t.name})]}),e.jsx("code",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:555:9",className:"text-[11px] text-slate-400 font-mono truncate max-w-[400px]",children:t.image})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:557:7",className:"grid grid-cols-2 md:grid-cols-3 gap-2 text-xs",children:[e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:558:9",className:"text-slate-400",children:["CPU: ",e.jsxs("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:559:16",className:"text-slate-200 font-mono",children:[t.resources?.requests?.cpu||"-","/",t.resources?.limits?.cpu||"-"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:561:9",className:"text-slate-400",children:["内存: ",e.jsxs("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:562:15",className:"text-slate-200 font-mono",children:[t.resources?.requests?.memory||"-","/",t.resources?.limits?.memory||"-"]})]}),e.jsxs("div",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:564:9",className:"text-slate-400",children:["端口: ",e.jsx("span",{"code-path":"src/components/kubernetes/WorkloadViewPage.tsx:565:15",className:"text-slate-200 font-mono",children:(t.ports||[]).map(m=>m.containerPort||m.port).join(", ")||"-"})]})]})]})}export{gs as default}; diff --git a/backend/static/assets/agent-DqqIRCQX.js b/backend/static/assets/agent-DqqIRCQX.js new file mode 100644 index 0000000..0b7a197 --- /dev/null +++ b/backend/static/assets/agent-DqqIRCQX.js @@ -0,0 +1 @@ +import{h as t}from"./index-DfyorCky.js";const g={getLatest:()=>t.get("/agent/latest"),getHistory:(e,a=1)=>t.get(`/agent/history/${e}?hours=${a}`),createTask:e=>t.post("/agent/tasks",e),listTasks:e=>t.get("/agent/tasks",e),execCommand:e=>t.post("/agent/exec",e),getAggregate:e=>t.get("/agent/aggregate",e),aggregate:e=>t.post("/agent/aggregate",e),listRules:()=>t.get("/agent/rules"),createRule:e=>t.post("/agent/rules",e),updateRule:(e,a)=>t.put(`/agent/rules/${e}`,a),deleteRule:e=>t.delete(`/agent/rules/${e}`),quickSetup:e=>t.post("/agent/rules/quick-setup",{type:e||"ecs"}),uninstallAgent:e=>t.post("/agent/uninstall",e),batchUninstall:e=>t.post("/agent/batch-uninstall",{server_ids:e}),batchUpgrade:e=>t.post("/agent/batch-upgrade",{server_ids:e}),listAlerts:e=>t.get("/agent/alerts",e),resolveAlert:e=>t.post(`/agent/alerts/${e}/resolve`),getHealthProbes:e=>t.get("/agent/health-probes",e),createHealthProbe:e=>t.post("/agent/health-probes",e),updateHealthProbe:(e,a)=>t.put(`/agent/health-probes/${e}`,a),deleteHealthProbe:e=>t.delete(`/agent/health-probes/${e}`),getPortPolicy:e=>t.get(`/agent/port-policies/${e}`),savePortPolicy:(e,a)=>t.put(`/agent/port-policies/${e}`,a)};export{g as a}; diff --git a/backend/static/assets/ai-BTgmlP5Q.js b/backend/static/assets/ai-BTgmlP5Q.js new file mode 100644 index 0000000..0a3a51b --- /dev/null +++ b/backend/static/assets/ai-BTgmlP5Q.js @@ -0,0 +1,4 @@ +import{h as o,W as h}from"./index-DfyorCky.js";const C={getConfig:()=>o.get("/aiops/llm-config"),saveConfig:e=>o.put("/aiops/llm-config",e),testConnection:()=>o.post("/aiops/llm-config/test"),chat:(e,s)=>o.post("/aiops/chat",{messages:e,session_id:s||""}),chatStream:async(e,s,d,g)=>{const c=h.getState().token,n=await fetch("/api/v1/aiops/chat/stream",{method:"POST",headers:{"Content-Type":"application/json",...c?{Authorization:`Bearer ${c}`}:{}},body:JSON.stringify({messages:e,session_id:g||""}),signal:d});if(n.status===401)throw h.getState().logout(),window.location.href="/login",new Error("登录已过期,请重新登录");if(!n.body)throw new Error("流式响应不可用");const m=n.body.getReader(),u=new TextDecoder("utf-8");let r="",f="";for(;;){const{done:w,value:y}=await m.read();if(w)break;r+=u.decode(y,{stream:!0});const p=r.split(` + +`);r=p.pop()??"";for(const S of p){const b=S.split(` +`);let a="message",l=[];for(const t of b)t.startsWith("event:")?a=t.slice(6).trim():t.startsWith("data:")&&l.push(t.slice(5).trim());const i=l.join("");if(i){if(a==="error")try{const t=JSON.parse(i);throw new Error(t.message||"LLM 流式响应错误")}catch(t){throw t instanceof Error&&t.message?t:new Error("LLM 流式响应错误")}if(a!=="done")try{const t=JSON.parse(i);typeof t.content=="string"&&(f+=t.content,s(t.content))}catch{}}}}return f},getHistory:e=>{const s=e?`?session_id=${encodeURIComponent(e)}`:"";return o.get(`/aiops/chat-history${s}`)},clearHistory:()=>o.delete("/aiops/chat-history")};export{C as a}; diff --git a/backend/static/assets/arrow-left-BDgGyrD0.js b/backend/static/assets/arrow-left-BDgGyrD0.js new file mode 100644 index 0000000..be50f0e7 --- /dev/null +++ b/backend/static/assets/arrow-left-BDgGyrD0.js @@ -0,0 +1 @@ +import{g as o}from"./index-DfyorCky.js";const e=[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]],r=o("arrow-left",e);export{r as A}; diff --git a/backend/static/assets/arrow-right-DyIltvNZ.js b/backend/static/assets/arrow-right-DyIltvNZ.js new file mode 100644 index 0000000..55ed95c --- /dev/null +++ b/backend/static/assets/arrow-right-DyIltvNZ.js @@ -0,0 +1 @@ +import{g as o}from"./index-DfyorCky.js";const r=[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]],a=o("arrow-right",r);export{a as A}; diff --git a/backend/static/assets/arrow-up-down-DnvTt5VG.js b/backend/static/assets/arrow-up-down-DnvTt5VG.js new file mode 100644 index 0000000..04c2d44 --- /dev/null +++ b/backend/static/assets/arrow-up-down-DnvTt5VG.js @@ -0,0 +1 @@ +import{g as o}from"./index-DfyorCky.js";const e=[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]],a=o("arrow-up-down",e);export{a as A}; diff --git a/backend/static/assets/automation-mtL167W_.js b/backend/static/assets/automation-mtL167W_.js new file mode 100644 index 0000000..ea51748 --- /dev/null +++ b/backend/static/assets/automation-mtL167W_.js @@ -0,0 +1 @@ +import{h as e}from"./index-DfyorCky.js";const c={getJobs:async t=>e.get("/cron-jobs",t),getJob:async t=>e.get(`/cron-jobs/${t}`),createJob:async t=>e.post("/cron-jobs",t),updateJob:async(t,r)=>e.put(`/cron-jobs/${t}`,r),deleteJob:async t=>e.delete(`/cron-jobs/${t}`),toggleJob:async t=>e.post(`/cron-jobs/${t}/toggle`),executeJob:async t=>e.post(`/cron-jobs/${t}/execute`),batchDelete:async t=>e.delete("/cron-jobs/batch-delete",{ids:t})},n={getScripts:async t=>e.get("/scripts",t),getScript:async t=>e.get(`/scripts/${t}`),createScript:async t=>e.post("/scripts",t),updateScript:async(t,r)=>e.put(`/scripts/${t}`,r),deleteScript:async t=>e.delete(`/scripts/${t}`),batchDelete:async t=>e.post("/scripts/batch-delete",{ids:t}),executeScript:async t=>e.post(`/scripts/${t}/execute`)},o={getExecutions:async t=>e.get("/task-executions",t)};export{c,n as s,o as t}; diff --git a/backend/static/assets/badge-xNW8x0G1.js b/backend/static/assets/badge-xNW8x0G1.js new file mode 100644 index 0000000..8c125d4 --- /dev/null +++ b/backend/static/assets/badge-xNW8x0G1.js @@ -0,0 +1 @@ +import{j as n,Y as s,X as o,Z as d}from"./index-DfyorCky.js";const c=d("inline-flex items-center justify-center rounded-full border px-2 py-0.5 text-xs font-medium w-fit whitespace-nowrap shrink-0 [&>svg]:size-3 gap-1 [&>svg]:pointer-events-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive transition-[color,box-shadow] overflow-hidden",{variants:{variant:{default:"border-transparent bg-primary text-primary-foreground [a&]:hover:bg-primary/90",secondary:"border-transparent bg-secondary text-secondary-foreground [a&]:hover:bg-secondary/90",destructive:"border-transparent bg-destructive text-white [a&]:hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60",outline:"text-foreground [a&]:hover:bg-accent [a&]:hover:text-accent-foreground"}},defaultVariants:{variant:"default"}});function v({className:e,variant:r,asChild:t=!1,...a}){const i=t?s:"span";return n.jsx(i,{"code-path":"src/components/ui/badge.tsx:38:5","data-slot":"badge",className:o(c({variant:r}),e),...a})}export{v as B}; diff --git a/backend/static/assets/box-TTGA1p57.js b/backend/static/assets/box-TTGA1p57.js new file mode 100644 index 0000000..fd7c1f6 --- /dev/null +++ b/backend/static/assets/box-TTGA1p57.js @@ -0,0 +1 @@ +import{g as a}from"./index-DfyorCky.js";const o=[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]],e=a("box",o);export{e as B}; diff --git a/backend/static/assets/card-C55cvSHg.js b/backend/static/assets/card-C55cvSHg.js new file mode 100644 index 0000000..490eace --- /dev/null +++ b/backend/static/assets/card-C55cvSHg.js @@ -0,0 +1 @@ +import{j as r,X as s}from"./index-DfyorCky.js";function d({className:a,...t}){return r.jsx("div",{"code-path":"src/components/ui/card.tsx:7:5","data-slot":"card",className:s("bg-card text-card-foreground flex flex-col gap-6 rounded-xl border py-6 shadow-sm",a),...t})}function e({className:a,...t}){return r.jsx("div",{"code-path":"src/components/ui/card.tsx:20:5","data-slot":"card-header",className:s("@container/card-header grid auto-rows-min grid-rows-[auto_auto] items-start gap-2 px-6 has-data-[slot=card-action]:grid-cols-[1fr_auto] [.border-b]:pb-6",a),...t})}function c({className:a,...t}){return r.jsx("div",{"code-path":"src/components/ui/card.tsx:33:5","data-slot":"card-title",className:s("leading-none font-semibold",a),...t})}function n({className:a,...t}){return r.jsx("div",{"code-path":"src/components/ui/card.tsx:43:5","data-slot":"card-description",className:s("text-muted-foreground text-sm",a),...t})}function i({className:a,...t}){return r.jsx("div",{"code-path":"src/components/ui/card.tsx:66:5","data-slot":"card-content",className:s("px-6",a),...t})}export{d as C,i as a,e as b,c,n as d}; diff --git a/backend/static/assets/checkbox-CH0bpj6b.js b/backend/static/assets/checkbox-CH0bpj6b.js new file mode 100644 index 0000000..7cb28c1 --- /dev/null +++ b/backend/static/assets/checkbox-CH0bpj6b.js @@ -0,0 +1 @@ +import{r as i,j as o,ac as L,ad as O,ae as _,af as H,ag as N,ah as j,ai as X,X as G,a9 as K}from"./index-DfyorCky.js";import{u as U}from"./index-CWVNW_qu.js";var y="Checkbox",[$]=L(y),[J,I]=$(y);function Q(t){const{__scopeCheckbox:n,checked:c,children:l,defaultChecked:a,disabled:e,form:h,name:b,onCheckedChange:d,required:k,value:x="on",internal_do_not_use_render:u}=t,[p,v]=H({prop:c,defaultProp:a??!1,onChange:d,caller:y}),[m,C]=i.useState(null),[g,r]=i.useState(null),s=i.useRef(!1),E=m?!!h||!!m.closest("form"):!0,R={checked:p,disabled:e,setChecked:v,control:m,setControl:C,name:b,form:h,value:x,hasConsumerStoppedPropagationRef:s,required:k,defaultChecked:f(a)?!1:a,isFormControl:E,bubbleInput:g,setBubbleInput:r};return o.jsx(J,{scope:n,...R,children:V(u)?u(R):l})}var w="CheckboxTrigger",S=i.forwardRef(({__scopeCheckbox:t,onKeyDown:n,onClick:c,...l},a)=>{const{control:e,value:h,disabled:b,checked:d,required:k,setControl:x,setChecked:u,hasConsumerStoppedPropagationRef:p,isFormControl:v,bubbleInput:m}=I(w,t),C=N(a,x),g=i.useRef(d);return i.useEffect(()=>{const r=e?.form;if(r){const s=()=>u(g.current);return r.addEventListener("reset",s),()=>r.removeEventListener("reset",s)}},[e,u]),o.jsx(_.button,{type:"button",role:"checkbox","aria-checked":f(d)?"mixed":d,"aria-required":k,"data-state":z(d),"data-disabled":b?"":void 0,disabled:b,value:h,...l,ref:C,onKeyDown:j(n,r=>{r.key==="Enter"&&r.preventDefault()}),onClick:j(c,r=>{u(s=>f(s)?!0:!s),m&&v&&(p.current=r.isPropagationStopped(),p.current||r.stopPropagation())})})});S.displayName=w;var B=i.forwardRef((t,n)=>{const{__scopeCheckbox:c,name:l,checked:a,defaultChecked:e,required:h,disabled:b,value:d,onCheckedChange:k,form:x,...u}=t;return o.jsx(Q,{__scopeCheckbox:c,checked:a,defaultChecked:e,disabled:b,required:h,onCheckedChange:k,name:l,form:x,value:d,internal_do_not_use_render:({isFormControl:p})=>o.jsxs(o.Fragment,{children:[o.jsx(S,{...u,ref:n,__scopeCheckbox:c}),p&&o.jsx(A,{__scopeCheckbox:c})]})})});B.displayName=y;var M="CheckboxIndicator",T=i.forwardRef((t,n)=>{const{__scopeCheckbox:c,forceMount:l,...a}=t,e=I(M,c);return o.jsx(O,{present:l||f(e.checked)||e.checked===!0,children:o.jsx(_.span,{"data-state":z(e.checked),"data-disabled":e.disabled?"":void 0,...a,ref:n,style:{pointerEvents:"none",...t.style}})})});T.displayName=M;var q="CheckboxBubbleInput",A=i.forwardRef(({__scopeCheckbox:t,...n},c)=>{const{control:l,hasConsumerStoppedPropagationRef:a,checked:e,defaultChecked:h,required:b,disabled:d,name:k,value:x,form:u,bubbleInput:p,setBubbleInput:v}=I(q,t),m=N(c,v),C=U(e),g=X(l);i.useEffect(()=>{const s=p;if(!s)return;const E=window.HTMLInputElement.prototype,P=Object.getOwnPropertyDescriptor(E,"checked").set,D=!a.current;if(C!==e&&P){const F=new Event("click",{bubbles:D});s.indeterminate=f(e),P.call(s,f(e)?!1:e),s.dispatchEvent(F)}},[p,C,e,a]);const r=i.useRef(f(e)?!1:e);return o.jsx(_.input,{type:"checkbox","aria-hidden":!0,defaultChecked:h??r.current,required:b,disabled:d,name:k,value:x,form:u,...n,tabIndex:-1,ref:m,style:{...n.style,...g,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});A.displayName=q;function V(t){return typeof t=="function"}function f(t){return t==="indeterminate"}function z(t){return f(t)?"indeterminate":t?"checked":"unchecked"}function Z({className:t,...n}){return o.jsx(B,{"code-path":"src/components/ui/checkbox.tsx:14:5","data-slot":"checkbox",className:G("peer border-input dark:bg-input/30 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground dark:data-[state=checked]:bg-primary data-[state=checked]:border-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive size-4 shrink-0 rounded-[4px] border shadow-xs transition-shadow outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",t),...n,children:o.jsx(T,{"code-path":"src/components/ui/checkbox.tsx:22:7","data-slot":"checkbox-indicator",className:"grid place-content-center text-current transition-none",children:o.jsx(K,{"code-path":"src/components/ui/checkbox.tsx:26:9",className:"size-3.5"})})})}export{Z as C}; diff --git a/backend/static/assets/circle-DOZr6_68.js b/backend/static/assets/circle-DOZr6_68.js new file mode 100644 index 0000000..338d91e --- /dev/null +++ b/backend/static/assets/circle-DOZr6_68.js @@ -0,0 +1 @@ +import{g as c}from"./index-DfyorCky.js";const e=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]],r=c("circle",e);export{r as C}; diff --git a/backend/static/assets/circle-check-DWcXrx2k.js b/backend/static/assets/circle-check-DWcXrx2k.js new file mode 100644 index 0000000..ad23614 --- /dev/null +++ b/backend/static/assets/circle-check-DWcXrx2k.js @@ -0,0 +1 @@ +import{g as c}from"./index-DfyorCky.js";const e=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]],r=c("circle-check",e);export{r as C}; diff --git a/backend/static/assets/circle-stop-s4wxdTEV.js b/backend/static/assets/circle-stop-s4wxdTEV.js new file mode 100644 index 0000000..0df4f3e --- /dev/null +++ b/backend/static/assets/circle-stop-s4wxdTEV.js @@ -0,0 +1 @@ +import{g as c}from"./index-DfyorCky.js";const e=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]],r=c("circle-stop",e);export{r as C}; diff --git a/backend/static/assets/circle-x-DK79Dhg2.js b/backend/static/assets/circle-x-DK79Dhg2.js new file mode 100644 index 0000000..c0b608c --- /dev/null +++ b/backend/static/assets/circle-x-DK79Dhg2.js @@ -0,0 +1 @@ +import{g as c}from"./index-DfyorCky.js";const e=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]],o=c("circle-x",e);export{o as C}; diff --git a/backend/static/assets/cloud-Dzoer-2i.js b/backend/static/assets/cloud-Dzoer-2i.js new file mode 100644 index 0000000..77d971e --- /dev/null +++ b/backend/static/assets/cloud-Dzoer-2i.js @@ -0,0 +1 @@ +import{h as e}from"./index-DfyorCky.js";const c={getAccounts:async()=>e.get("/cloud-accounts"),createAccount:async t=>e.post("/cloud-accounts",t),updateAccount:async(t,n)=>e.put(`/cloud-accounts/${t}`,n),deleteAccount:async t=>e.delete(`/cloud-accounts/${t}`),syncRegions:async t=>e.post(`/cloud-accounts/${t}/sync-regions`),getAccountRegions:async t=>e.get(`/cloud-accounts/${t}/regions`),discoverInstances:async(t,n)=>e.post(`/cloud-accounts/${t}/discover-instances`,{regions:n}),importInstances:async(t,n,s)=>e.post(`/cloud-accounts/${t}/import-instances`,{instances:n,...s}),getDomains:async t=>e.get("/domains",t),createDomain:async t=>e.post("/domains",t),updateDomain:async(t,n)=>e.put(`/domains/${t}`,n),deleteDomain:async t=>e.delete(`/domains/${t}`)},a={list:async()=>e.get("/platforms"),create:async t=>e.post("/platforms",t),update:async(t,n)=>e.put(`/platforms/${t}`,n),delete:async t=>e.delete(`/platforms/${t}`)},l={getStats:async()=>e.get("/cloud-billings/stats"),list:async t=>e.get("/cloud-billings",t),create:async t=>e.post("/cloud-billings",t),batchCreate:async t=>e.post("/cloud-billings/batch",{records:t}),remove:async t=>e.delete(`/cloud-billings/${t}`),getProviders:async()=>e.get("/cloud-billings/providers"),listAlertRules:async()=>e.get("/billing-alerts"),createAlertRule:async t=>e.post("/billing-alerts",t),updateAlertRule:async(t,n)=>e.put(`/billing-alerts/${t}`,n),deleteAlertRule:async t=>e.delete(`/billing-alerts/${t}`),toggleAlertRule:async t=>e.post(`/billing-alerts/${t}/toggle`)};export{l as b,c,a as p}; diff --git a/backend/static/assets/code-L62jFLTC.js b/backend/static/assets/code-L62jFLTC.js new file mode 100644 index 0000000..23cc9da --- /dev/null +++ b/backend/static/assets/code-L62jFLTC.js @@ -0,0 +1 @@ +import{g as o}from"./index-DfyorCky.js";const e=[["path",{d:"m16 18 6-6-6-6",key:"eg8j8"}],["path",{d:"m8 6-6 6 6 6",key:"ppft3o"}]],c=o("code",e);export{c as C}; diff --git a/backend/static/assets/copy-DXW4LnkN.js b/backend/static/assets/copy-DXW4LnkN.js new file mode 100644 index 0000000..650e30a --- /dev/null +++ b/backend/static/assets/copy-DXW4LnkN.js @@ -0,0 +1 @@ +import{g as c}from"./index-DfyorCky.js";const e=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]],t=c("copy",e);export{t as C}; diff --git a/backend/static/assets/dashboard-BjQPIG2G.js b/backend/static/assets/dashboard-BjQPIG2G.js new file mode 100644 index 0000000..9f0b142 --- /dev/null +++ b/backend/static/assets/dashboard-BjQPIG2G.js @@ -0,0 +1 @@ +import{h as t}from"./index-DfyorCky.js";const a={getStats:async()=>t.get("/dashboard/stats"),getAlerts:async e=>t.get("/dashboard/recent-alerts",e?{limit:e}:void 0),getReleases:async e=>t.get("/dashboard/recent-releases",e?{limit:e}:void 0),getMetrics:async e=>t.get("/dashboard/metrics",e?{hours:e}:void 0)};export{a as d}; diff --git a/backend/static/assets/deploy-B3Sg3N1U.js b/backend/static/assets/deploy-B3Sg3N1U.js new file mode 100644 index 0000000..9ee5fbe --- /dev/null +++ b/backend/static/assets/deploy-B3Sg3N1U.js @@ -0,0 +1 @@ +import{h as t}from"./index-DfyorCky.js";const p={getPipelines:async e=>t.get("/pipelines",e),getPipelineDetail:async e=>t.get(`/pipelines/${e}`),createPipeline:async e=>t.post("/pipelines",e),updatePipeline:async(e,s)=>t.put(`/pipelines/${e}`,s),deletePipeline:async e=>t.delete(`/pipelines/${e}`),triggerPipeline:async e=>t.post(`/pipelines/${e}/trigger`),getRuns:async e=>t.get(`/pipelines/${e}/runs`),stopRun:async(e,s)=>t.post(`/pipelines/${e}/runs/${s}/stop`),getRunLog:async(e,s)=>t.get(`/pipelines/${e}/runs/${s}/log`),getMembers:async e=>t.get(`/pipelines/${e}/members`),addMember:async(e,s)=>t.post(`/pipelines/${e}/members`,s),removeMember:async(e,s)=>t.delete(`/pipelines/${e}/members/${s}`),assignGroup:async(e,s)=>t.post(`/pipelines/${e}/groups`,s)},r={getRepos:()=>t.get("/deploy/repos"),getRepo:e=>t.get(`/deploy/repos/${e}`),createRepo:e=>t.post("/deploy/repos",e),updateRepo:(e,s)=>t.put(`/deploy/repos/${e}`,s),deleteRepo:e=>t.delete(`/deploy/repos/${e}`),getRegistries:()=>t.get("/deploy/registries"),getRegistry:e=>t.get(`/deploy/registries/${e}`),createRegistry:e=>t.post("/deploy/registries",e),updateRegistry:(e,s)=>t.put(`/deploy/registries/${e}`,s),deleteRegistry:e=>t.delete(`/deploy/registries/${e}`),getEnvironments:()=>t.get("/deploy/environments"),createEnvironment:e=>t.post("/deploy/environments",e),updateEnvironment:(e,s)=>t.put(`/deploy/environments/${e}`,s),deleteEnvironment:e=>t.delete(`/deploy/environments/${e}`),getItemRoles:()=>t.get("/admin/item-roles"),createItemRole:e=>t.post("/admin/item-roles",e),updateItemRole:(e,s)=>t.put(`/admin/item-roles/${e}`,s),deleteItemRole:e=>t.delete(`/admin/item-roles/${e}`),getUserItemRoles:e=>t.get(`/admin/users/${e}/item-roles`),assignItemRole:(e,s)=>t.post(`/admin/users/${e}/item-roles`,s),removeItemRole:(e,s)=>t.delete(`/admin/users/${e}/item-roles/${s}`),getGroups:()=>t.get("/deploy/groups"),createGroup:e=>t.post("/deploy/groups",e),updateGroup:(e,s)=>t.put(`/deploy/groups/${e}`,s),deleteGroup:e=>t.delete(`/deploy/groups/${e}`),getGroupMembers:e=>t.get(`/deploy/groups/${e}/members`),addGroupMember:(e,s)=>t.post(`/deploy/groups/${e}/members`,s),removeGroupMember:(e,s)=>t.delete(`/deploy/groups/${e}/members/${s}`),getTools:()=>t.get("/deploy/tools"),getTool:e=>t.get(`/deploy/tools/${e}`),updateTool:(e,s)=>t.put(`/deploy/tools/${e}`,s),installTool:(e,s)=>t.post(`/deploy/tools/${e}/install`,s?{version:s}:{}),checkTool:e=>t.post(`/deploy/tools/${e}/check`),getToolVersions:e=>t.get(`/deploy/tools/${e}/versions`)},l={list:()=>t.get("/credentials"),create:e=>t.post("/credentials",e),update:(e,s)=>t.put(`/credentials/${e}`,s),delete:e=>t.delete(`/credentials/${e}`)},i={assign:(e,s)=>t.post(`/servers/${e}/assign-credential`,{credential_id:s})};export{l as c,r as d,p,i as s}; diff --git a/backend/static/assets/disc-EsE6x5Oh.js b/backend/static/assets/disc-EsE6x5Oh.js new file mode 100644 index 0000000..1708c78 --- /dev/null +++ b/backend/static/assets/disc-EsE6x5Oh.js @@ -0,0 +1 @@ +import{g as c}from"./index-DfyorCky.js";const e=[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]],r=c("disc",e);export{r as D}; diff --git a/backend/static/assets/download-DoZfYs2h.js b/backend/static/assets/download-DoZfYs2h.js new file mode 100644 index 0000000..1704b5a --- /dev/null +++ b/backend/static/assets/download-DoZfYs2h.js @@ -0,0 +1 @@ +import{g as o}from"./index-DfyorCky.js";const a=[["path",{d:"M12 15V3",key:"m9g1x1"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["path",{d:"m7 10 5 5 5-5",key:"brsn70"}]],e=o("download",a);export{e as D}; diff --git a/backend/static/assets/ellipsis-DU5enAwm.js b/backend/static/assets/ellipsis-DU5enAwm.js new file mode 100644 index 0000000..b89cc81 --- /dev/null +++ b/backend/static/assets/ellipsis-DU5enAwm.js @@ -0,0 +1 @@ +import{g as c}from"./index-DfyorCky.js";const e=[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]],r=c("ellipsis",e);export{r as E}; diff --git a/backend/static/assets/external-link-CzIpMNu1.js b/backend/static/assets/external-link-CzIpMNu1.js new file mode 100644 index 0000000..a620dcc --- /dev/null +++ b/backend/static/assets/external-link-CzIpMNu1.js @@ -0,0 +1 @@ +import{g as a}from"./index-DfyorCky.js";const e=[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]],n=a("external-link",e);export{n as E}; diff --git a/backend/static/assets/file-text-C9G5abwR.js b/backend/static/assets/file-text-C9G5abwR.js new file mode 100644 index 0000000..9ad736e --- /dev/null +++ b/backend/static/assets/file-text-C9G5abwR.js @@ -0,0 +1 @@ +import{g as e}from"./index-DfyorCky.js";const a=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]],o=e("file-text",a);export{o as F}; diff --git a/backend/static/assets/folder-DoMwqvzv.js b/backend/static/assets/folder-DoMwqvzv.js new file mode 100644 index 0000000..25e5c76 --- /dev/null +++ b/backend/static/assets/folder-DoMwqvzv.js @@ -0,0 +1 @@ +import{g as a}from"./index-DfyorCky.js";const o=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z",key:"1oefj6"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5",key:"wfsgrz"}]],c=a("file",o);const e=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]],d=a("folder",e);export{c as F,d as a}; diff --git a/backend/static/assets/folder-open-IMBifk-r.js b/backend/static/assets/folder-open-IMBifk-r.js new file mode 100644 index 0000000..06b21e5 --- /dev/null +++ b/backend/static/assets/folder-open-IMBifk-r.js @@ -0,0 +1 @@ +import{g as a}from"./index-DfyorCky.js";const o=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],c=a("folder-open",o);export{c as F}; diff --git a/backend/static/assets/funnel-D2FHr15I.js b/backend/static/assets/funnel-D2FHr15I.js new file mode 100644 index 0000000..6ce206b --- /dev/null +++ b/backend/static/assets/funnel-D2FHr15I.js @@ -0,0 +1 @@ +import{g as e}from"./index-DfyorCky.js";const n=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z",key:"sc7q7i"}]],a=e("funnel",n);export{a as F}; diff --git a/backend/static/assets/generateCategoricalChart-6v9BPbG2.js b/backend/static/assets/generateCategoricalChart-6v9BPbG2.js new file mode 100644 index 0000000..641a01a --- /dev/null +++ b/backend/static/assets/generateCategoricalChart-6v9BPbG2.js @@ -0,0 +1,61 @@ +import{aV as Gn,aU as ue,r as N,ab as te,_ as T}from"./index-DfyorCky.js";var ka,ih;function Re(){if(ih)return ka;ih=1;var e=Array.isArray;return ka=e,ka}var Da,ah;function qm(){if(ah)return Da;ah=1;var e=typeof Gn=="object"&&Gn&&Gn.Object===Object&&Gn;return Da=e,Da}var Na,oh;function it(){if(oh)return Na;oh=1;var e=qm(),t=typeof self=="object"&&self&&self.Object===Object&&self,r=e||t||Function("return this")();return Na=r,Na}var qa,uh;function Dn(){if(uh)return qa;uh=1;var e=it(),t=e.Symbol;return qa=t,qa}var Ba,ch;function Vx(){if(ch)return Ba;ch=1;var e=Dn(),t=Object.prototype,r=t.hasOwnProperty,n=t.toString,i=e?e.toStringTag:void 0;function a(o){var u=r.call(o,i),c=o[i];try{o[i]=void 0;var s=!0}catch{}var f=n.call(o);return s&&(u?o[i]=c:delete o[i]),f}return Ba=a,Ba}var La,sh;function Yx(){if(sh)return La;sh=1;var e=Object.prototype,t=e.toString;function r(n){return t.call(n)}return La=r,La}var Fa,lh;function gt(){if(lh)return Fa;lh=1;var e=Dn(),t=Vx(),r=Yx(),n="[object Null]",i="[object Undefined]",a=e?e.toStringTag:void 0;function o(u){return u==null?u===void 0?i:n:a&&a in Object(u)?t(u):r(u)}return Fa=o,Fa}var Ua,fh;function mt(){if(fh)return Ua;fh=1;function e(t){return t!=null&&typeof t=="object"}return Ua=e,Ua}var Wa,hh;function Cr(){if(hh)return Wa;hh=1;var e=gt(),t=mt(),r="[object Symbol]";function n(i){return typeof i=="symbol"||t(i)&&e(i)==r}return Wa=n,Wa}var za,ph;function Zl(){if(ph)return za;ph=1;var e=Re(),t=Cr(),r=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,n=/^\w*$/;function i(a,o){if(e(a))return!1;var u=typeof a;return u=="number"||u=="symbol"||u=="boolean"||a==null||t(a)?!0:n.test(a)||!r.test(a)||o!=null&&a in Object(o)}return za=i,za}var Ha,dh;function Pt(){if(dh)return Ha;dh=1;function e(t){var r=typeof t;return t!=null&&(r=="object"||r=="function")}return Ha=e,Ha}var Ga,vh;function Jl(){if(vh)return Ga;vh=1;var e=gt(),t=Pt(),r="[object AsyncFunction]",n="[object Function]",i="[object GeneratorFunction]",a="[object Proxy]";function o(u){if(!t(u))return!1;var c=e(u);return c==n||c==i||c==r||c==a}return Ga=o,Ga}var Ka,yh;function Zx(){if(yh)return Ka;yh=1;var e=it(),t=e["__core-js_shared__"];return Ka=t,Ka}var Xa,gh;function Jx(){if(gh)return Xa;gh=1;var e=Zx(),t=(function(){var n=/[^.]+$/.exec(e&&e.keys&&e.keys.IE_PROTO||"");return n?"Symbol(src)_1."+n:""})();function r(n){return!!t&&t in n}return Xa=r,Xa}var Va,mh;function Bm(){if(mh)return Va;mh=1;var e=Function.prototype,t=e.toString;function r(n){if(n!=null){try{return t.call(n)}catch{}try{return n+""}catch{}}return""}return Va=r,Va}var Ya,bh;function Qx(){if(bh)return Ya;bh=1;var e=Jl(),t=Jx(),r=Pt(),n=Bm(),i=/[\\^$.*+?()[\]{}|]/g,a=/^\[object .+?Constructor\]$/,o=Function.prototype,u=Object.prototype,c=o.toString,s=u.hasOwnProperty,f=RegExp("^"+c.call(s).replace(i,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function l(h){if(!r(h)||t(h))return!1;var d=e(h)?f:a;return d.test(n(h))}return Ya=l,Ya}var Za,xh;function ew(){if(xh)return Za;xh=1;function e(t,r){return t?.[r]}return Za=e,Za}var Ja,wh;function Xt(){if(wh)return Ja;wh=1;var e=Qx(),t=ew();function r(n,i){var a=t(n,i);return e(a)?a:void 0}return Ja=r,Ja}var Qa,Oh;function ra(){if(Oh)return Qa;Oh=1;var e=Xt(),t=e(Object,"create");return Qa=t,Qa}var eo,_h;function tw(){if(_h)return eo;_h=1;var e=ra();function t(){this.__data__=e?e(null):{},this.size=0}return eo=t,eo}var to,Sh;function rw(){if(Sh)return to;Sh=1;function e(t){var r=this.has(t)&&delete this.__data__[t];return this.size-=r?1:0,r}return to=e,to}var ro,Ah;function nw(){if(Ah)return ro;Ah=1;var e=ra(),t="__lodash_hash_undefined__",r=Object.prototype,n=r.hasOwnProperty;function i(a){var o=this.__data__;if(e){var u=o[a];return u===t?void 0:u}return n.call(o,a)?o[a]:void 0}return ro=i,ro}var no,Ph;function iw(){if(Ph)return no;Ph=1;var e=ra(),t=Object.prototype,r=t.hasOwnProperty;function n(i){var a=this.__data__;return e?a[i]!==void 0:r.call(a,i)}return no=n,no}var io,Th;function aw(){if(Th)return io;Th=1;var e=ra(),t="__lodash_hash_undefined__";function r(n,i){var a=this.__data__;return this.size+=this.has(n)?0:1,a[n]=e&&i===void 0?t:i,this}return io=r,io}var ao,Eh;function ow(){if(Eh)return ao;Eh=1;var e=tw(),t=rw(),r=nw(),n=iw(),i=aw();function a(o){var u=-1,c=o==null?0:o.length;for(this.clear();++u-1}return fo=t,fo}var ho,kh;function fw(){if(kh)return ho;kh=1;var e=na();function t(r,n){var i=this.__data__,a=e(i,r);return a<0?(++this.size,i.push([r,n])):i[a][1]=n,this}return ho=t,ho}var po,Dh;function ia(){if(Dh)return po;Dh=1;var e=uw(),t=cw(),r=sw(),n=lw(),i=fw();function a(o){var u=-1,c=o==null?0:o.length;for(this.clear();++u0?1:-1},Nt=function(t){return zt(t)&&t.indexOf("%")===t.length-1},q=function(t){return Rw(t)&&!Nn(t)},kw=function(t){return Z(t)},xe=function(t){return q(t)||zt(t)},Dw=0,ua=function(t){var r=++Dw;return"".concat(t||"").concat(r)},Ye=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!q(t)&&!zt(t))return n;var a;if(Nt(t)){var o=t.indexOf("%");a=r*parseFloat(t.slice(0,o))/100}else a=+t;return Nn(a)&&(a=n),i&&a>r&&(a=r),a},Ot=function(t){if(!t)return null;var r=Object.keys(t);return r&&r.length?t[r[0]]:null},Nw=function(t){if(!Array.isArray(t))return!1;for(var r=t.length,n={},i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function zw(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Ns(e){"@babel/helpers - typeof";return Ns=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ns(e)}var lp={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},ft=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},fp=null,Lo=null,of=function e(t){if(t===fp&&Array.isArray(Lo))return Lo;var r=[];return N.Children.forEach(t,function(n){Z(n)||(Mw.isFragment(n)?r=r.concat(e(n.props.children)):r.push(n))}),Lo=r,fp=t,r};function Ze(e,t){var r=[],n=[];return Array.isArray(t)?n=t.map(function(i){return ft(i)}):n=[ft(t)],of(e).forEach(function(i){var a=We(i,"type.displayName")||We(i,"type.name");n.indexOf(a)!==-1&&r.push(i)}),r}function Ne(e,t){var r=Ze(e,t);return r&&r[0]}var hp=function(t){if(!t||!t.props)return!1;var r=t.props,n=r.width,i=r.height;return!(!q(n)||n<=0||!q(i)||i<=0)},Hw=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],Gw=function(t){return t&&t.type&&zt(t.type)&&Hw.indexOf(t.type)>=0},ID=function(t){return t&&Ns(t)==="object"&&"clipDot"in t},Kw=function(t,r,n,i){var a,o=(a=Bo?.[i])!==null&&a!==void 0?a:[];return r.startsWith("data-")||!Y(t)&&(i&&o.includes(r)||Lw.includes(r))||n&&af.includes(r)},ee=function(t,r,n){if(!t||typeof t=="function"||typeof t=="boolean")return null;var i=t;if(N.isValidElement(t)&&(i=t.props),!$r(i))return null;var a={};return Object.keys(i).forEach(function(o){var u;Kw((u=i)===null||u===void 0?void 0:u[o],o,r,n)&&(a[o]=i[o])}),a},qs=function e(t,r){if(t===r)return!0;var n=N.Children.count(t);if(n!==N.Children.count(r))return!1;if(n===0)return!0;if(n===1)return pp(Array.isArray(t)?t[0]:t,Array.isArray(r)?r[0]:r);for(var i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function Jw(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Ls(e){var t=e.children,r=e.width,n=e.height,i=e.viewBox,a=e.className,o=e.style,u=e.title,c=e.desc,s=Zw(e,Yw),f=i||{width:r,height:n,x:0,y:0},l=te("recharts-surface",a);return T.createElement("svg",Bs({},ee(s,!0,"svg"),{className:l,width:r,height:n,style:o,viewBox:"".concat(f.x," ").concat(f.y," ").concat(f.width," ").concat(f.height)}),T.createElement("title",null,u),T.createElement("desc",null,c),t)}var Qw=["children","className"];function Fs(){return Fs=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function tO(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var _e=T.forwardRef(function(e,t){var r=e.children,n=e.className,i=eO(e,Qw),a=te("recharts-layer",n);return T.createElement("g",Fs({className:a},ee(i,!0),{ref:t}),r)}),ht=function(t,r){for(var n=arguments.length,i=new Array(n>2?n-2:0),a=2;aa?0:a+r),n=n>a?a:n,n<0&&(n+=a),a=r>n?0:n-r>>>0,r>>>=0;for(var o=Array(a);++i=a?r:e(r,n,i)}return Uo=t,Uo}var Wo,gp;function Hm(){if(gp)return Wo;gp=1;var e="\\ud800-\\udfff",t="\\u0300-\\u036f",r="\\ufe20-\\ufe2f",n="\\u20d0-\\u20ff",i=t+r+n,a="\\ufe0e\\ufe0f",o="\\u200d",u=RegExp("["+o+e+i+a+"]");function c(s){return u.test(s)}return Wo=c,Wo}var zo,mp;function iO(){if(mp)return zo;mp=1;function e(t){return t.split("")}return zo=e,zo}var Ho,bp;function aO(){if(bp)return Ho;bp=1;var e="\\ud800-\\udfff",t="\\u0300-\\u036f",r="\\ufe20-\\ufe2f",n="\\u20d0-\\u20ff",i=t+r+n,a="\\ufe0e\\ufe0f",o="["+e+"]",u="["+i+"]",c="\\ud83c[\\udffb-\\udfff]",s="(?:"+u+"|"+c+")",f="[^"+e+"]",l="(?:\\ud83c[\\udde6-\\uddff]){2}",h="[\\ud800-\\udbff][\\udc00-\\udfff]",d="\\u200d",g=s+"?",v="["+a+"]?",p="(?:"+d+"(?:"+[f,l,h].join("|")+")"+v+g+")*",m=v+g+p,x="(?:"+[f+u+"?",u,l,h,o].join("|")+")",w=RegExp(c+"(?="+c+")|"+x+m,"g");function O(y){return y.match(w)||[]}return Ho=O,Ho}var Go,xp;function oO(){if(xp)return Go;xp=1;var e=iO(),t=Hm(),r=aO();function n(i){return t(i)?r(i):e(i)}return Go=n,Go}var Ko,wp;function uO(){if(wp)return Ko;wp=1;var e=nO(),t=Hm(),r=oO(),n=Fm();function i(a){return function(o){o=n(o);var u=t(o)?r(o):void 0,c=u?u[0]:o.charAt(0),s=u?e(u,1).join(""):o.slice(1);return c[a]()+s}}return Ko=i,Ko}var Xo,Op;function cO(){if(Op)return Xo;Op=1;var e=uO(),t=e("toUpperCase");return Xo=t,Xo}var sO=cO();const ca=ue(sO);function oe(e){return function(){return e}}const Gm=Math.cos,si=Math.sin,Qe=Math.sqrt,li=Math.PI,sa=2*li,Us=Math.PI,Ws=2*Us,kt=1e-6,lO=Ws-kt;function Km(e){this._+=e[0];for(let t=1,r=e.length;t=0))throw new Error(`invalid digits: ${e}`);if(t>15)return Km;const r=10**t;return function(n){this._+=n[0];for(let i=1,a=n.length;ikt)if(!(Math.abs(l*c-s*f)>kt)||!a)this._append`L${this._x1=t},${this._y1=r}`;else{let d=n-o,g=i-u,v=c*c+s*s,p=d*d+g*g,m=Math.sqrt(v),x=Math.sqrt(h),w=a*Math.tan((Us-Math.acos((v+h-p)/(2*m*x)))/2),O=w/x,y=w/m;Math.abs(O-1)>kt&&this._append`L${t+O*f},${r+O*l}`,this._append`A${a},${a},0,0,${+(l*d>f*g)},${this._x1=t+y*c},${this._y1=r+y*s}`}}arc(t,r,n,i,a,o){if(t=+t,r=+r,n=+n,o=!!o,n<0)throw new Error(`negative radius: ${n}`);let u=n*Math.cos(i),c=n*Math.sin(i),s=t+u,f=r+c,l=1^o,h=o?i-a:a-i;this._x1===null?this._append`M${s},${f}`:(Math.abs(this._x1-s)>kt||Math.abs(this._y1-f)>kt)&&this._append`L${s},${f}`,n&&(h<0&&(h=h%Ws+Ws),h>lO?this._append`A${n},${n},0,1,${l},${t-u},${r-c}A${n},${n},0,1,${l},${this._x1=s},${this._y1=f}`:h>kt&&this._append`A${n},${n},0,${+(h>=Us)},${l},${this._x1=t+n*Math.cos(a)},${this._y1=r+n*Math.sin(a)}`)}rect(t,r,n,i){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+r}h${n=+n}v${+i}h${-n}Z`}toString(){return this._}}function uf(e){let t=3;return e.digits=function(r){if(!arguments.length)return t;if(r==null)t=null;else{const n=Math.floor(r);if(!(n>=0))throw new RangeError(`invalid digits: ${r}`);t=n}return e},()=>new hO(t)}function cf(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function Xm(e){this._context=e}Xm.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function la(e){return new Xm(e)}function Vm(e){return e[0]}function Ym(e){return e[1]}function Zm(e,t){var r=oe(!0),n=null,i=la,a=null,o=uf(u);e=typeof e=="function"?e:e===void 0?Vm:oe(e),t=typeof t=="function"?t:t===void 0?Ym:oe(t);function u(c){var s,f=(c=cf(c)).length,l,h=!1,d;for(n==null&&(a=i(d=o())),s=0;s<=f;++s)!(s=d;--g)u.point(w[g],O[g]);u.lineEnd(),u.areaEnd()}m&&(w[h]=+e(p,h,l),O[h]=+t(p,h,l),u.point(n?+n(p,h,l):w[h],r?+r(p,h,l):O[h]))}if(x)return u=null,x+""||null}function f(){return Zm().defined(i).curve(o).context(a)}return s.x=function(l){return arguments.length?(e=typeof l=="function"?l:oe(+l),n=null,s):e},s.x0=function(l){return arguments.length?(e=typeof l=="function"?l:oe(+l),s):e},s.x1=function(l){return arguments.length?(n=l==null?null:typeof l=="function"?l:oe(+l),s):n},s.y=function(l){return arguments.length?(t=typeof l=="function"?l:oe(+l),r=null,s):t},s.y0=function(l){return arguments.length?(t=typeof l=="function"?l:oe(+l),s):t},s.y1=function(l){return arguments.length?(r=l==null?null:typeof l=="function"?l:oe(+l),s):r},s.lineX0=s.lineY0=function(){return f().x(e).y(t)},s.lineY1=function(){return f().x(e).y(r)},s.lineX1=function(){return f().x(n).y(t)},s.defined=function(l){return arguments.length?(i=typeof l=="function"?l:oe(!!l),s):i},s.curve=function(l){return arguments.length?(o=l,a!=null&&(u=o(a)),s):o},s.context=function(l){return arguments.length?(l==null?a=u=null:u=o(a=l),s):a},s}class Jm{constructor(t,r){this._context=t,this._x=r}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,r){switch(t=+t,r=+r,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,r):this._context.moveTo(t,r);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,r,t,r):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+r)/2,t,this._y0,t,r);break}}this._x0=t,this._y0=r}}function pO(e){return new Jm(e,!0)}function dO(e){return new Jm(e,!1)}const sf={draw(e,t){const r=Qe(t/li);e.moveTo(r,0),e.arc(0,0,r,0,sa)}},vO={draw(e,t){const r=Qe(t/5)/2;e.moveTo(-3*r,-r),e.lineTo(-r,-r),e.lineTo(-r,-3*r),e.lineTo(r,-3*r),e.lineTo(r,-r),e.lineTo(3*r,-r),e.lineTo(3*r,r),e.lineTo(r,r),e.lineTo(r,3*r),e.lineTo(-r,3*r),e.lineTo(-r,r),e.lineTo(-3*r,r),e.closePath()}},Qm=Qe(1/3),yO=Qm*2,gO={draw(e,t){const r=Qe(t/yO),n=r*Qm;e.moveTo(0,-r),e.lineTo(n,0),e.lineTo(0,r),e.lineTo(-n,0),e.closePath()}},mO={draw(e,t){const r=Qe(t),n=-r/2;e.rect(n,n,r,r)}},bO=.8908130915292852,eb=si(li/10)/si(7*li/10),xO=si(sa/10)*eb,wO=-Gm(sa/10)*eb,OO={draw(e,t){const r=Qe(t*bO),n=xO*r,i=wO*r;e.moveTo(0,-r),e.lineTo(n,i);for(let a=1;a<5;++a){const o=sa*a/5,u=Gm(o),c=si(o);e.lineTo(c*r,-u*r),e.lineTo(u*n-c*i,c*n+u*i)}e.closePath()}},Vo=Qe(3),_O={draw(e,t){const r=-Qe(t/(Vo*3));e.moveTo(0,r*2),e.lineTo(-Vo*r,-r),e.lineTo(Vo*r,-r),e.closePath()}},Be=-.5,Le=Qe(3)/2,zs=1/Qe(12),SO=(zs/2+1)*3,AO={draw(e,t){const r=Qe(t/SO),n=r/2,i=r*zs,a=n,o=r*zs+r,u=-a,c=o;e.moveTo(n,i),e.lineTo(a,o),e.lineTo(u,c),e.lineTo(Be*n-Le*i,Le*n+Be*i),e.lineTo(Be*a-Le*o,Le*a+Be*o),e.lineTo(Be*u-Le*c,Le*u+Be*c),e.lineTo(Be*n+Le*i,Be*i-Le*n),e.lineTo(Be*a+Le*o,Be*o-Le*a),e.lineTo(Be*u+Le*c,Be*c-Le*u),e.closePath()}};function PO(e,t){let r=null,n=uf(i);e=typeof e=="function"?e:oe(e||sf),t=typeof t=="function"?t:oe(t===void 0?64:+t);function i(){let a;if(r||(r=a=n()),e.apply(this,arguments).draw(r,+t.apply(this,arguments)),a)return r=null,a+""||null}return i.type=function(a){return arguments.length?(e=typeof a=="function"?a:oe(a),i):e},i.size=function(a){return arguments.length?(t=typeof a=="function"?a:oe(+a),i):t},i.context=function(a){return arguments.length?(r=a??null,i):r},i}function fi(){}function hi(e,t,r){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+r)/6)}function tb(e){this._context=e}tb.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:hi(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:hi(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function TO(e){return new tb(e)}function rb(e){this._context=e}rb.prototype={areaStart:fi,areaEnd:fi,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:hi(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function EO(e){return new rb(e)}function nb(e){this._context=e}nb.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var r=(this._x0+4*this._x1+e)/6,n=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(r,n):this._context.moveTo(r,n);break;case 3:this._point=4;default:hi(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function jO(e){return new nb(e)}function ib(e){this._context=e}ib.prototype={areaStart:fi,areaEnd:fi,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function MO(e){return new ib(e)}function _p(e){return e<0?-1:1}function Sp(e,t,r){var n=e._x1-e._x0,i=t-e._x1,a=(e._y1-e._y0)/(n||i<0&&-0),o=(r-e._y1)/(i||n<0&&-0),u=(a*i+o*n)/(n+i);return(_p(a)+_p(o))*Math.min(Math.abs(a),Math.abs(o),.5*Math.abs(u))||0}function Ap(e,t){var r=e._x1-e._x0;return r?(3*(e._y1-e._y0)/r-t)/2:t}function Yo(e,t,r){var n=e._x0,i=e._y0,a=e._x1,o=e._y1,u=(a-n)/3;e._context.bezierCurveTo(n+u,i+u*t,a-u,o-u*r,a,o)}function pi(e){this._context=e}pi.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:Yo(this,this._t0,Ap(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var r=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,Yo(this,Ap(this,r=Sp(this,e,t)),r);break;default:Yo(this,this._t0,r=Sp(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=r}}};function ab(e){this._context=new ob(e)}(ab.prototype=Object.create(pi.prototype)).point=function(e,t){pi.prototype.point.call(this,t,e)};function ob(e){this._context=e}ob.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,r,n,i,a){this._context.bezierCurveTo(t,e,n,r,a,i)}};function CO(e){return new pi(e)}function $O(e){return new ab(e)}function ub(e){this._context=e}ub.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,r=e.length;if(r)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),r===2)this._context.lineTo(e[1],t[1]);else for(var n=Pp(e),i=Pp(t),a=0,o=1;o=0;--t)i[t]=(o[t]-i[t+1])/a[t];for(a[r-1]=(e[r]+i[r-1])/2,t=0;t=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var r=this._x*(1-this._t)+e*this._t;this._context.lineTo(r,this._y),this._context.lineTo(r,t)}break}}this._x=e,this._y=t}};function RO(e){return new fa(e,.5)}function kO(e){return new fa(e,0)}function DO(e){return new fa(e,1)}function lr(e,t){if((o=e.length)>1)for(var r=1,n,i,a=e[t[0]],o,u=a.length;r=0;)r[t]=t;return r}function NO(e,t){return e[t]}function qO(e){const t=[];return t.key=e,t}function BO(){var e=oe([]),t=Hs,r=lr,n=NO;function i(a){var o=Array.from(e.apply(this,arguments),qO),u,c=o.length,s=-1,f;for(const l of a)for(u=0,++s;u0){for(var r,n,i=0,a=e[0].length,o;i0){for(var r=0,n=e[t[0]],i,a=n.length;r0)||!((a=(i=e[t[0]]).length)>0))){for(var r=0,n=1,i,a,o;n=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function XO(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var cb={symbolCircle:sf,symbolCross:vO,symbolDiamond:gO,symbolSquare:mO,symbolStar:OO,symbolTriangle:_O,symbolWye:AO},VO=Math.PI/180,YO=function(t){var r="symbol".concat(ca(t));return cb[r]||sf},ZO=function(t,r,n){if(r==="area")return t;switch(n){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var i=18*VO;return 1.25*t*t*(Math.tan(i)-Math.tan(i*2)*Math.pow(Math.tan(i),2))}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},JO=function(t,r){cb["symbol".concat(ca(t))]=r},lf=function(t){var r=t.type,n=r===void 0?"circle":r,i=t.size,a=i===void 0?64:i,o=t.sizeType,u=o===void 0?"area":o,c=KO(t,WO),s=Ep(Ep({},c),{},{type:n,size:a,sizeType:u}),f=function(){var p=YO(n),m=PO().type(p).size(ZO(a,u,n));return m()},l=s.className,h=s.cx,d=s.cy,g=ee(s,!0);return h===+h&&d===+d&&a===+a?T.createElement("path",Gs({},g,{className:te("recharts-symbols",l),transform:"translate(".concat(h,", ").concat(d,")"),d:f()})):null};lf.registerSymbol=JO;function fr(e){"@babel/helpers - typeof";return fr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},fr(e)}function Ks(){return Ks=Object.assign?Object.assign.bind():function(e){for(var t=1;t`);var x=d.inactive?s:d.color;return T.createElement("li",Ks({className:p,style:l,key:"legend-item-".concat(g)},ci(n.props,d,g)),T.createElement(Ls,{width:o,height:o,viewBox:f,style:h},n.renderIcon(d)),T.createElement("span",{className:"recharts-legend-item-text",style:{color:x}},v?v(m,d,g):m))})}},{key:"render",value:function(){var n=this.props,i=n.payload,a=n.layout,o=n.align;if(!i||!i.length)return null;var u={padding:0,margin:0,textAlign:a==="horizontal"?o:"left"};return T.createElement("ul",{className:"recharts-default-legend",style:u},this.renderItems())}}])})(N.PureComponent);tn(ff,"displayName","Legend");tn(ff,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var Zo,Mp;function c1(){if(Mp)return Zo;Mp=1;var e=ia();function t(){this.__data__=new e,this.size=0}return Zo=t,Zo}var Jo,Cp;function s1(){if(Cp)return Jo;Cp=1;function e(t){var r=this.__data__,n=r.delete(t);return this.size=r.size,n}return Jo=e,Jo}var Qo,$p;function l1(){if($p)return Qo;$p=1;function e(t){return this.__data__.get(t)}return Qo=e,Qo}var eu,Ip;function f1(){if(Ip)return eu;Ip=1;function e(t){return this.__data__.has(t)}return eu=e,eu}var tu,Rp;function h1(){if(Rp)return tu;Rp=1;var e=ia(),t=ef(),r=tf(),n=200;function i(a,o){var u=this.__data__;if(u instanceof e){var c=u.__data__;if(!t||c.lengthd))return!1;var v=l.get(o),p=l.get(u);if(v&&p)return v==u&&p==o;var m=-1,x=!0,w=c&i?new e:void 0;for(l.set(o,u),l.set(u,o);++m-1&&n%1==0&&n-1&&r%1==0&&r<=e}return _u=t,_u}var Su,id;function A1(){if(id)return Su;id=1;var e=gt(),t=vf(),r=mt(),n="[object Arguments]",i="[object Array]",a="[object Boolean]",o="[object Date]",u="[object Error]",c="[object Function]",s="[object Map]",f="[object Number]",l="[object Object]",h="[object RegExp]",d="[object Set]",g="[object String]",v="[object WeakMap]",p="[object ArrayBuffer]",m="[object DataView]",x="[object Float32Array]",w="[object Float64Array]",O="[object Int8Array]",y="[object Int16Array]",b="[object Int32Array]",_="[object Uint8Array]",S="[object Uint8ClampedArray]",P="[object Uint16Array]",M="[object Uint32Array]",A={};A[x]=A[w]=A[O]=A[y]=A[b]=A[_]=A[S]=A[P]=A[M]=!0,A[n]=A[i]=A[p]=A[a]=A[m]=A[o]=A[u]=A[c]=A[s]=A[f]=A[l]=A[h]=A[d]=A[g]=A[v]=!1;function E(j){return r(j)&&t(j.length)&&!!A[e(j)]}return Su=E,Su}var Au,ad;function mb(){if(ad)return Au;ad=1;function e(t){return function(r){return t(r)}}return Au=e,Au}var Xr={exports:{}};Xr.exports;var od;function P1(){return od||(od=1,(function(e,t){var r=qm(),n=t&&!t.nodeType&&t,i=n&&!0&&e&&!e.nodeType&&e,a=i&&i.exports===n,o=a&&r.process,u=(function(){try{var c=i&&i.require&&i.require("util").types;return c||o&&o.binding&&o.binding("util")}catch{}})();e.exports=u})(Xr,Xr.exports)),Xr.exports}var Pu,ud;function bb(){if(ud)return Pu;ud=1;var e=A1(),t=mb(),r=P1(),n=r&&r.isTypedArray,i=n?t(n):e;return Pu=i,Pu}var Tu,cd;function T1(){if(cd)return Tu;cd=1;var e=O1(),t=pf(),r=Re(),n=gb(),i=df(),a=bb(),o=Object.prototype,u=o.hasOwnProperty;function c(s,f){var l=r(s),h=!l&&t(s),d=!l&&!h&&n(s),g=!l&&!h&&!d&&a(s),v=l||h||d||g,p=v?e(s.length,String):[],m=p.length;for(var x in s)(f||u.call(s,x))&&!(v&&(x=="length"||d&&(x=="offset"||x=="parent")||g&&(x=="buffer"||x=="byteLength"||x=="byteOffset")||i(x,m)))&&p.push(x);return p}return Tu=c,Tu}var Eu,sd;function E1(){if(sd)return Eu;sd=1;var e=Object.prototype;function t(r){var n=r&&r.constructor,i=typeof n=="function"&&n.prototype||e;return r===i}return Eu=t,Eu}var ju,ld;function xb(){if(ld)return ju;ld=1;function e(t,r){return function(n){return t(r(n))}}return ju=e,ju}var Mu,fd;function j1(){if(fd)return Mu;fd=1;var e=xb(),t=e(Object.keys,Object);return Mu=t,Mu}var Cu,hd;function M1(){if(hd)return Cu;hd=1;var e=E1(),t=j1(),r=Object.prototype,n=r.hasOwnProperty;function i(a){if(!e(a))return t(a);var o=[];for(var u in Object(a))n.call(a,u)&&u!="constructor"&&o.push(u);return o}return Cu=i,Cu}var $u,pd;function qn(){if(pd)return $u;pd=1;var e=Jl(),t=vf();function r(n){return n!=null&&t(n.length)&&!e(n)}return $u=r,$u}var Iu,dd;function ha(){if(dd)return Iu;dd=1;var e=T1(),t=M1(),r=qn();function n(i){return r(i)?e(i):t(i)}return Iu=n,Iu}var Ru,vd;function C1(){if(vd)return Ru;vd=1;var e=m1(),t=w1(),r=ha();function n(i){return e(i,r,t)}return Ru=n,Ru}var ku,yd;function $1(){if(yd)return ku;yd=1;var e=C1(),t=1,r=Object.prototype,n=r.hasOwnProperty;function i(a,o,u,c,s,f){var l=u&t,h=e(a),d=h.length,g=e(o),v=g.length;if(d!=v&&!l)return!1;for(var p=d;p--;){var m=h[p];if(!(l?m in o:n.call(o,m)))return!1}var x=f.get(a),w=f.get(o);if(x&&w)return x==o&&w==a;var O=!0;f.set(a,o),f.set(o,a);for(var y=l;++p-1}return uc=t,uc}var cc,Wd;function J1(){if(Wd)return cc;Wd=1;function e(t,r,n){for(var i=-1,a=t==null?0:t.length;++i=o){var m=s?null:i(c);if(m)return a(m);g=!1,h=n,p=new e}else p=s?[]:v;e:for(;++l=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function p_(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function d_(e){return e.value}function v_(e,t){if(T.isValidElement(e))return T.cloneElement(e,t);if(typeof e=="function")return T.createElement(e,t);t.ref;var r=h_(t,i_);return T.createElement(ff,r)}var Zd=1,ur=(function(e){function t(){var r;a_(this,t);for(var n=arguments.length,i=new Array(n),a=0;aZd||Math.abs(i.height-this.lastBoundingBox.height)>Zd)&&(this.lastBoundingBox.width=i.width,this.lastBoundingBox.height=i.height,n&&n(i)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,n&&n(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?at({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(n){var i=this.props,a=i.layout,o=i.align,u=i.verticalAlign,c=i.margin,s=i.chartWidth,f=i.chartHeight,l,h;if(!n||(n.left===void 0||n.left===null)&&(n.right===void 0||n.right===null))if(o==="center"&&a==="vertical"){var d=this.getBBoxSnapshot();l={left:((s||0)-d.width)/2}}else l=o==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!n||(n.top===void 0||n.top===null)&&(n.bottom===void 0||n.bottom===null))if(u==="middle"){var g=this.getBBoxSnapshot();h={top:((f||0)-g.height)/2}}else h=u==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return at(at({},l),h)}},{key:"render",value:function(){var n=this,i=this.props,a=i.content,o=i.width,u=i.height,c=i.wrapperStyle,s=i.payloadUniqBy,f=i.payload,l=at(at({position:"absolute",width:o||"auto",height:u||"auto"},this.getDefaultPosition(c)),c);return T.createElement("div",{className:"recharts-legend-wrapper",style:l,ref:function(d){n.wrapperNode=d}},v_(a,at(at({},this.props),{},{payload:Ab(f,s,d_)})))}}],[{key:"getWithHeight",value:function(n,i){var a=at(at({},this.defaultProps),n.props),o=a.layout;return o==="vertical"&&q(n.props.height)?{height:n.props.height}:o==="horizontal"?{width:n.props.width||i}:null}}])})(N.PureComponent);pa(ur,"displayName","Legend");pa(ur,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var pc,Jd;function y_(){if(Jd)return pc;Jd=1;var e=Dn(),t=pf(),r=Re(),n=e?e.isConcatSpreadable:void 0;function i(a){return r(a)||t(a)||!!(n&&a&&a[n])}return pc=i,pc}var dc,Qd;function Eb(){if(Qd)return dc;Qd=1;var e=yb(),t=y_();function r(n,i,a,o,u){var c=-1,s=n.length;for(a||(a=t),u||(u=[]);++c0&&a(f)?i>1?r(f,i-1,a,o,u):e(u,f):o||(u[u.length]=f)}return u}return dc=r,dc}var vc,ev;function g_(){if(ev)return vc;ev=1;function e(t){return function(r,n,i){for(var a=-1,o=Object(r),u=i(r),c=u.length;c--;){var s=u[t?c:++a];if(n(o[s],s,o)===!1)break}return r}}return vc=e,vc}var yc,tv;function m_(){if(tv)return yc;tv=1;var e=g_(),t=e();return yc=t,yc}var gc,rv;function jb(){if(rv)return gc;rv=1;var e=m_(),t=ha();function r(n,i){return n&&e(n,i,t)}return gc=r,gc}var mc,nv;function b_(){if(nv)return mc;nv=1;var e=qn();function t(r,n){return function(i,a){if(i==null)return i;if(!e(i))return r(i,a);for(var o=i.length,u=n?o:-1,c=Object(i);(n?u--:++un||u&&c&&f&&!s&&!l||a&&c&&f||!i&&f||!o)return 1;if(!a&&!u&&!l&&r=s)return f;var l=i[a];return f*(l=="desc"?-1:1)}}return r.index-n.index}return _c=t,_c}var Sc,sv;function __(){if(sv)return Sc;sv=1;var e=rf(),t=nf(),r=Tt(),n=Mb(),i=x_(),a=mb(),o=O_(),u=Ir(),c=Re();function s(f,l,h){l.length?l=e(l,function(v){return c(v)?function(p){return t(p,v.length===1?v[0]:v)}:v}):l=[u];var d=-1;l=e(l,a(r));var g=n(f,function(v,p,m){var x=e(l,function(w){return w(v)});return{criteria:x,index:++d,value:v}});return i(g,function(v,p){return o(v,p,h)})}return Sc=s,Sc}var Ac,lv;function S_(){if(lv)return Ac;lv=1;function e(t,r,n){switch(n.length){case 0:return t.call(r);case 1:return t.call(r,n[0]);case 2:return t.call(r,n[0],n[1]);case 3:return t.call(r,n[0],n[1],n[2])}return t.apply(r,n)}return Ac=e,Ac}var Pc,fv;function A_(){if(fv)return Pc;fv=1;var e=S_(),t=Math.max;function r(n,i,a){return i=t(i===void 0?n.length-1:i,0),function(){for(var o=arguments,u=-1,c=t(o.length-i,0),s=Array(c);++u0){if(++a>=e)return arguments[0]}else a=0;return i.apply(void 0,arguments)}}return Mc=n,Mc}var Cc,yv;function j_(){if(yv)return Cc;yv=1;var e=T_(),t=E_(),r=t(e);return Cc=r,Cc}var $c,gv;function M_(){if(gv)return $c;gv=1;var e=Ir(),t=A_(),r=j_();function n(i,a){return r(t(i,a,e),i+"")}return $c=n,$c}var Ic,mv;function da(){if(mv)return Ic;mv=1;var e=Ql(),t=qn(),r=df(),n=Pt();function i(a,o,u){if(!n(u))return!1;var c=typeof o;return(c=="number"?t(u)&&r(o,u.length):c=="string"&&o in u)?e(u[o],a):!1}return Ic=i,Ic}var Rc,bv;function C_(){if(bv)return Rc;bv=1;var e=Eb(),t=__(),r=M_(),n=da(),i=r(function(a,o){if(a==null)return[];var u=o.length;return u>1&&n(a,o[0],o[1])?o=[]:u>2&&n(o[0],o[1],o[2])&&(o=[o[0]]),t(a,e(o,1),[])});return Rc=i,Rc}var $_=C_();const mf=ue($_);function rn(e){"@babel/helpers - typeof";return rn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},rn(e)}function Ys(){return Ys=Object.assign?Object.assign.bind():function(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=new Array(t);r=t.x),"".concat(qr,"-left"),q(r)&&t&&q(t.x)&&r=t.y),"".concat(qr,"-top"),q(n)&&t&&q(t.y)&&nv?Math.max(f,c[n]):Math.max(l,c[n])}function K_(e){var t=e.translateX,r=e.translateY,n=e.useTranslate3d;return{transform:n?"translate3d(".concat(t,"px, ").concat(r,"px, 0)"):"translate(".concat(t,"px, ").concat(r,"px)")}}function X_(e){var t=e.allowEscapeViewBox,r=e.coordinate,n=e.offsetTopLeft,i=e.position,a=e.reverseDirection,o=e.tooltipBox,u=e.useTranslate3d,c=e.viewBox,s,f,l;return o.height>0&&o.width>0&&r?(f=Ov({allowEscapeViewBox:t,coordinate:r,key:"x",offsetTopLeft:n,position:i,reverseDirection:a,tooltipDimension:o.width,viewBox:c,viewBoxDimension:c.width}),l=Ov({allowEscapeViewBox:t,coordinate:r,key:"y",offsetTopLeft:n,position:i,reverseDirection:a,tooltipDimension:o.height,viewBox:c,viewBoxDimension:c.height}),s=K_({translateX:f,translateY:l,useTranslate3d:u})):s=H_,{cssProperties:s,cssClasses:G_({translateX:f,translateY:l,coordinate:r})}}function pr(e){"@babel/helpers - typeof";return pr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},pr(e)}function _v(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Sv(e){for(var t=1;tAv||Math.abs(n.height-this.state.lastBoundingBox.height)>Av)&&this.setState({lastBoundingBox:{width:n.width,height:n.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var n,i;this.props.active&&this.updateBBox(),this.state.dismissed&&(((n=this.props.coordinate)===null||n===void 0?void 0:n.x)!==this.state.dismissedAtCoordinate.x||((i=this.props.coordinate)===null||i===void 0?void 0:i.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var n=this,i=this.props,a=i.active,o=i.allowEscapeViewBox,u=i.animationDuration,c=i.animationEasing,s=i.children,f=i.coordinate,l=i.hasPayload,h=i.isAnimationActive,d=i.offset,g=i.position,v=i.reverseDirection,p=i.useTranslate3d,m=i.viewBox,x=i.wrapperStyle,w=X_({allowEscapeViewBox:o,coordinate:f,offsetTopLeft:d,position:g,reverseDirection:v,tooltipBox:this.state.lastBoundingBox,useTranslate3d:p,viewBox:m}),O=w.cssClasses,y=w.cssProperties,b=Sv(Sv({transition:h&&a?"transform ".concat(u,"ms ").concat(c):void 0},y),{},{pointerEvents:"none",visibility:!this.state.dismissed&&a&&l?"visible":"hidden",position:"absolute",top:0,left:0},x);return T.createElement("div",{tabIndex:-1,className:O,style:b,ref:function(S){n.wrapperNode=S}},s)}}])})(N.PureComponent),iS=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},Bn={isSsr:iS()};function dr(e){"@babel/helpers - typeof";return dr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},dr(e)}function Pv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Tv(e){for(var t=1;t0;return T.createElement(nS,{allowEscapeViewBox:o,animationDuration:u,animationEasing:c,isAnimationActive:h,active:a,coordinate:f,hasPayload:b,offset:d,position:p,reverseDirection:m,useTranslate3d:x,viewBox:w,wrapperStyle:O},dS(s,Tv(Tv({},this.props),{},{payload:y})))}}])})(N.PureComponent);bf(ot,"displayName","Tooltip");bf(ot,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!Bn.isSsr,itemStyle:{},labelStyle:{},offset:10,reverseDirection:{x:!1,y:!1},separator:" : ",trigger:"hover",useTranslate3d:!1,viewBox:{x:0,y:0,height:0,width:0},wrapperStyle:{}});var Dc,Ev;function vS(){if(Ev)return Dc;Ev=1;var e=it(),t=function(){return e.Date.now()};return Dc=t,Dc}var Nc,jv;function yS(){if(jv)return Nc;jv=1;var e=/\s/;function t(r){for(var n=r.length;n--&&e.test(r.charAt(n)););return n}return Nc=t,Nc}var qc,Mv;function gS(){if(Mv)return qc;Mv=1;var e=yS(),t=/^\s+/;function r(n){return n&&n.slice(0,e(n)+1).replace(t,"")}return qc=r,qc}var Bc,Cv;function Db(){if(Cv)return Bc;Cv=1;var e=gS(),t=Pt(),r=Cr(),n=NaN,i=/^[-+]0x[0-9a-f]+$/i,a=/^0b[01]+$/i,o=/^0o[0-7]+$/i,u=parseInt;function c(s){if(typeof s=="number")return s;if(r(s))return n;if(t(s)){var f=typeof s.valueOf=="function"?s.valueOf():s;s=t(f)?f+"":f}if(typeof s!="string")return s===0?s:+s;s=e(s);var l=a.test(s);return l||o.test(s)?u(s.slice(2),l?2:8):i.test(s)?n:+s}return Bc=c,Bc}var Lc,$v;function mS(){if($v)return Lc;$v=1;var e=Pt(),t=vS(),r=Db(),n="Expected a function",i=Math.max,a=Math.min;function o(u,c,s){var f,l,h,d,g,v,p=0,m=!1,x=!1,w=!0;if(typeof u!="function")throw new TypeError(n);c=r(c)||0,e(s)&&(m=!!s.leading,x="maxWait"in s,h=x?i(r(s.maxWait)||0,c):h,w="trailing"in s?!!s.trailing:w);function O(j){var I=f,$=l;return f=l=void 0,p=j,d=u.apply($,I),d}function y(j){return p=j,g=setTimeout(S,c),m?O(j):d}function b(j){var I=j-v,$=j-p,R=c-I;return x?a(R,h-$):R}function _(j){var I=j-v,$=j-p;return v===void 0||I>=c||I<0||x&&$>=h}function S(){var j=t();if(_(j))return P(j);g=setTimeout(S,b(j))}function P(j){return g=void 0,w&&f?O(j):(f=l=void 0,d)}function M(){g!==void 0&&clearTimeout(g),p=0,f=v=l=g=void 0}function A(){return g===void 0?d:P(t())}function E(){var j=t(),I=_(j);if(f=arguments,l=this,v=j,I){if(g===void 0)return y(v);if(x)return clearTimeout(g),g=setTimeout(S,c),O(v)}return g===void 0&&(g=setTimeout(S,c)),d}return E.cancel=M,E.flush=A,E}return Lc=o,Lc}var Fc,Iv;function bS(){if(Iv)return Fc;Iv=1;var e=mS(),t=Pt(),r="Expected a function";function n(i,a,o){var u=!0,c=!0;if(typeof i!="function")throw new TypeError(r);return t(o)&&(u="leading"in o?!!o.leading:u,c="trailing"in o?!!o.trailing:c),e(i,a,{leading:u,maxWait:a,trailing:c})}return Fc=n,Fc}var xS=bS();const Nb=ue(xS);function an(e){"@babel/helpers - typeof";return an=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},an(e)}function Rv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Vn(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=new Array(t);r0&&(j=Nb(j,v,{trailing:!0,leading:!1}));var I=new ResizeObserver(j),$=y.current.getBoundingClientRect(),R=$.width,D=$.height;return A(R,D),I.observe(y.current),function(){I.disconnect()}},[A,v]);var E=N.useMemo(function(){var j=P.containerWidth,I=P.containerHeight;if(j<0||I<0)return null;ht(Nt(o)||Nt(c),`The width(%s) and height(%s) are both fixed numbers, + maybe you don't need to use a ResponsiveContainer.`,o,c),ht(!r||r>0,"The aspect(%s) must be greater than zero.",r);var $=Nt(o)?j:o,R=Nt(c)?I:c;r&&r>0&&($?R=$/r:R&&($=R*r),h&&R>h&&(R=h)),ht($>0||R>0,`The width(%s) and height(%s) of chart should be greater than 0, + please check the style of container, or the props width(%s) and height(%s), + or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the + height and width.`,$,R,o,c,f,l,r);var D=!Array.isArray(d)&&ft(d.type).endsWith("Chart");return T.Children.map(d,function(B){return T.isValidElement(B)?N.cloneElement(B,Vn({width:$,height:R},D?{style:Vn({height:"100%",width:"100%",maxHeight:R,maxWidth:$},B.props.style)}:{})):B})},[r,d,c,h,l,f,P,o]);return T.createElement("div",{id:p?"".concat(p):void 0,className:te("recharts-responsive-container",m),style:Vn(Vn({},O),{},{width:o,height:c,minWidth:f,minHeight:l,maxHeight:h}),ref:y},E)}),qb=function(t){return null};qb.displayName="Cell";function on(e){"@babel/helpers - typeof";return on=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},on(e)}function Dv(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function el(e){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||Bn.isSsr)return{width:0,height:0};var n=RS(r),i=JSON.stringify({text:t,copyStyle:n});if(er.widthCache[i])return er.widthCache[i];try{var a=document.getElementById(Nv);a||(a=document.createElement("span"),a.setAttribute("id",Nv),a.setAttribute("aria-hidden","true"),document.body.appendChild(a));var o=el(el({},IS),n);Object.assign(a.style,o),a.textContent="".concat(t);var u=a.getBoundingClientRect(),c={width:u.width,height:u.height};return er.widthCache[i]=c,++er.cacheCount>$S&&(er.cacheCount=0,er.widthCache={}),c}catch{return{width:0,height:0}}},kS=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function un(e){"@babel/helpers - typeof";return un=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},un(e)}function mi(e,t){return BS(e)||qS(e,t)||NS(e,t)||DS()}function DS(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function NS(e,t){if(e){if(typeof e=="string")return qv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return qv(e,t)}}function qv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function QS(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function zv(e,t){return nA(e)||rA(e,t)||tA(e,t)||eA()}function eA(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function tA(e,t){if(e){if(typeof e=="string")return Hv(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Hv(e,t)}}function Hv(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r0&&arguments[0]!==void 0?arguments[0]:[];return $.reduce(function(R,D){var B=D.word,L=D.width,z=R[R.length-1];if(z&&(i==null||a||z.width+L+nD.width?R:D})};if(!f)return d;for(var v="…",p=function($){var R=l.slice(0,$),D=Ub({breakAll:s,style:c,children:R+v}).wordsWithComputedWidth,B=h(D),L=B.length>o||g(B).width>Number(i);return[L,B]},m=0,x=l.length-1,w=0,O;m<=x&&w<=l.length-1;){var y=Math.floor((m+x)/2),b=y-1,_=p(b),S=zv(_,2),P=S[0],M=S[1],A=p(y),E=zv(A,1),j=E[0];if(!P&&!j&&(m=y+1),P&&j&&(x=y-1),!P&&j){O=M;break}w++}return O||d},Gv=function(t){var r=Z(t)?[]:t.toString().split(Fb);return[{words:r}]},aA=function(t){var r=t.width,n=t.scaleToFit,i=t.children,a=t.style,o=t.breakAll,u=t.maxLines;if((r||n)&&!Bn.isSsr){var c,s,f=Ub({breakAll:o,children:i,style:a});if(f){var l=f.wordsWithComputedWidth,h=f.spaceWidth;c=l,s=h}else return Gv(i);return iA({breakAll:o,children:i,maxLines:u,style:a},c,s,r,n)}return Gv(i)},Kv="#808080",bi=function(t){var r=t.x,n=r===void 0?0:r,i=t.y,a=i===void 0?0:i,o=t.lineHeight,u=o===void 0?"1em":o,c=t.capHeight,s=c===void 0?"0.71em":c,f=t.scaleToFit,l=f===void 0?!1:f,h=t.textAnchor,d=h===void 0?"start":h,g=t.verticalAnchor,v=g===void 0?"end":g,p=t.fill,m=p===void 0?Kv:p,x=Wv(t,ZS),w=N.useMemo(function(){return aA({breakAll:x.breakAll,children:x.children,maxLines:x.maxLines,scaleToFit:l,style:x.style,width:x.width})},[x.breakAll,x.children,x.maxLines,l,x.style,x.width]),O=x.dx,y=x.dy,b=x.angle,_=x.className,S=x.breakAll,P=Wv(x,JS);if(!xe(n)||!xe(a))return null;var M=n+(q(O)?O:0),A=a+(q(y)?y:0),E;switch(v){case"start":E=Uc("calc(".concat(s,")"));break;case"middle":E=Uc("calc(".concat((w.length-1)/2," * -").concat(u," + (").concat(s," / 2))"));break;default:E=Uc("calc(".concat(w.length-1," * -").concat(u,")"));break}var j=[];if(l){var I=w[0].width,$=x.width;j.push("scale(".concat((q($)?$/I:1)/I,")"))}return b&&j.push("rotate(".concat(b,", ").concat(M,", ").concat(A,")")),j.length&&(P.transform=j.join(" ")),T.createElement("text",tl({},ee(P,!0),{x:M,y:A,className:te("recharts-text",_),textAnchor:d,fill:m.includes("url")?Kv:m}),w.map(function(R,D){var B=R.words.join(S?"":" ");return T.createElement("tspan",{x:M,dy:D===0?E:u,key:"".concat(B,"-").concat(D)},B)}))};function St(e,t){return e==null||t==null?NaN:et?1:e>=t?0:NaN}function oA(e,t){return e==null||t==null?NaN:te?1:t>=e?0:NaN}function xf(e){let t,r,n;e.length!==2?(t=St,r=(u,c)=>St(e(u),c),n=(u,c)=>e(u)-c):(t=e===St||e===oA?e:uA,r=e,n=e);function i(u,c,s=0,f=u.length){if(s>>1;r(u[l],c)<0?s=l+1:f=l}while(s>>1;r(u[l],c)<=0?s=l+1:f=l}while(ss&&n(u[l-1],c)>-n(u[l],c)?l-1:l}return{left:i,center:o,right:a}}function uA(){return 0}function Wb(e){return e===null?NaN:+e}function*cA(e,t){for(let r of e)r!=null&&(r=+r)>=r&&(yield r)}const sA=xf(St),Ln=sA.right;xf(Wb).center;class Xv extends Map{constructor(t,r=hA){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:r}}),t!=null)for(const[n,i]of t)this.set(n,i)}get(t){return super.get(Vv(this,t))}has(t){return super.has(Vv(this,t))}set(t,r){return super.set(lA(this,t),r)}delete(t){return super.delete(fA(this,t))}}function Vv({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):r}function lA({_intern:e,_key:t},r){const n=t(r);return e.has(n)?e.get(n):(e.set(n,r),r)}function fA({_intern:e,_key:t},r){const n=t(r);return e.has(n)&&(r=e.get(n),e.delete(n)),r}function hA(e){return e!==null&&typeof e=="object"?e.valueOf():e}function pA(e=St){if(e===St)return zb;if(typeof e!="function")throw new TypeError("compare is not a function");return(t,r)=>{const n=e(t,r);return n||n===0?n:(e(r,r)===0)-(e(t,t)===0)}}function zb(e,t){return(e==null||!(e>=e))-(t==null||!(t>=t))||(et?1:0)}const dA=Math.sqrt(50),vA=Math.sqrt(10),yA=Math.sqrt(2);function xi(e,t,r){const n=(t-e)/Math.max(0,r),i=Math.floor(Math.log10(n)),a=n/Math.pow(10,i),o=a>=dA?10:a>=vA?5:a>=yA?2:1;let u,c,s;return i<0?(s=Math.pow(10,-i)/o,u=Math.round(e*s),c=Math.round(t*s),u/st&&--c,s=-s):(s=Math.pow(10,i)*o,u=Math.round(e/s),c=Math.round(t/s),u*st&&--c),c0))return[];if(e===t)return[e];const n=t=i))return[];const u=a-i+1,c=new Array(u);if(n)if(o<0)for(let s=0;s=n)&&(r=n);return r}function Zv(e,t){let r;for(const n of e)n!=null&&(r>n||r===void 0&&n>=n)&&(r=n);return r}function Hb(e,t,r=0,n=1/0,i){if(t=Math.floor(t),r=Math.floor(Math.max(0,r)),n=Math.floor(Math.min(e.length-1,n)),!(r<=t&&t<=n))return e;for(i=i===void 0?zb:pA(i);n>r;){if(n-r>600){const c=n-r+1,s=t-r+1,f=Math.log(c),l=.5*Math.exp(2*f/3),h=.5*Math.sqrt(f*l*(c-l)/c)*(s-c/2<0?-1:1),d=Math.max(r,Math.floor(t-s*l/c+h)),g=Math.min(n,Math.floor(t+(c-s)*l/c+h));Hb(e,t,d,g,i)}const a=e[t];let o=r,u=n;for(Br(e,r,t),i(e[n],a)>0&&Br(e,r,n);o0;)--u}i(e[r],a)===0?Br(e,r,u):(++u,Br(e,u,n)),u<=t&&(r=u+1),t<=u&&(n=u-1)}return e}function Br(e,t,r){const n=e[t];e[t]=e[r],e[r]=n}function gA(e,t,r){if(e=Float64Array.from(cA(e)),!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return Zv(e);if(t>=1)return Yv(e);var n,i=(n-1)*t,a=Math.floor(i),o=Yv(Hb(e,a).subarray(0,a+1)),u=Zv(e.subarray(a+1));return o+(u-o)*(i-a)}}function mA(e,t,r=Wb){if(!(!(n=e.length)||isNaN(t=+t))){if(t<=0||n<2)return+r(e[0],0,e);if(t>=1)return+r(e[n-1],n-1,e);var n,i=(n-1)*t,a=Math.floor(i),o=+r(e[a],a,e),u=+r(e[a+1],a+1,e);return o+(u-o)*(i-a)}}function bA(e,t,r){e=+e,t=+t,r=(i=arguments.length)<2?(t=e,e=0,1):i<3?1:+r;for(var n=-1,i=Math.max(0,Math.ceil((t-e)/r))|0,a=new Array(i);++n>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):r===8?Zn(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):r===4?Zn(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=wA.exec(e))?new Ie(t[1],t[2],t[3],1):(t=OA.exec(e))?new Ie(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=_A.exec(e))?Zn(t[1],t[2],t[3],t[4]):(t=SA.exec(e))?Zn(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=AA.exec(e))?iy(t[1],t[2]/100,t[3]/100,1):(t=PA.exec(e))?iy(t[1],t[2]/100,t[3]/100,t[4]):Jv.hasOwnProperty(e)?ty(Jv[e]):e==="transparent"?new Ie(NaN,NaN,NaN,0):null}function ty(e){return new Ie(e>>16&255,e>>8&255,e&255,1)}function Zn(e,t,r,n){return n<=0&&(e=t=r=NaN),new Ie(e,t,r,n)}function jA(e){return e instanceof Fn||(e=fn(e)),e?(e=e.rgb(),new Ie(e.r,e.g,e.b,e.opacity)):new Ie}function ol(e,t,r,n){return arguments.length===1?jA(e):new Ie(e,t,r,n??1)}function Ie(e,t,r,n){this.r=+e,this.g=+t,this.b=+r,this.opacity=+n}Of(Ie,ol,Kb(Fn,{brighter(e){return e=e==null?wi:Math.pow(wi,e),new Ie(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?sn:Math.pow(sn,e),new Ie(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Ie(Ft(this.r),Ft(this.g),Ft(this.b),Oi(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:ry,formatHex:ry,formatHex8:MA,formatRgb:ny,toString:ny}));function ry(){return`#${qt(this.r)}${qt(this.g)}${qt(this.b)}`}function MA(){return`#${qt(this.r)}${qt(this.g)}${qt(this.b)}${qt((isNaN(this.opacity)?1:this.opacity)*255)}`}function ny(){const e=Oi(this.opacity);return`${e===1?"rgb(":"rgba("}${Ft(this.r)}, ${Ft(this.g)}, ${Ft(this.b)}${e===1?")":`, ${e})`}`}function Oi(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function Ft(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function qt(e){return e=Ft(e),(e<16?"0":"")+e.toString(16)}function iy(e,t,r,n){return n<=0?e=t=r=NaN:r<=0||r>=1?e=t=NaN:t<=0&&(e=NaN),new Xe(e,t,r,n)}function Xb(e){if(e instanceof Xe)return new Xe(e.h,e.s,e.l,e.opacity);if(e instanceof Fn||(e=fn(e)),!e)return new Xe;if(e instanceof Xe)return e;e=e.rgb();var t=e.r/255,r=e.g/255,n=e.b/255,i=Math.min(t,r,n),a=Math.max(t,r,n),o=NaN,u=a-i,c=(a+i)/2;return u?(t===a?o=(r-n)/u+(r0&&c<1?0:o,new Xe(o,u,c,e.opacity)}function CA(e,t,r,n){return arguments.length===1?Xb(e):new Xe(e,t,r,n??1)}function Xe(e,t,r,n){this.h=+e,this.s=+t,this.l=+r,this.opacity=+n}Of(Xe,CA,Kb(Fn,{brighter(e){return e=e==null?wi:Math.pow(wi,e),new Xe(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?sn:Math.pow(sn,e),new Xe(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,r=this.l,n=r+(r<.5?r:1-r)*t,i=2*r-n;return new Ie(Wc(e>=240?e-240:e+120,i,n),Wc(e,i,n),Wc(e<120?e+240:e-120,i,n),this.opacity)},clamp(){return new Xe(ay(this.h),Jn(this.s),Jn(this.l),Oi(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=Oi(this.opacity);return`${e===1?"hsl(":"hsla("}${ay(this.h)}, ${Jn(this.s)*100}%, ${Jn(this.l)*100}%${e===1?")":`, ${e})`}`}}));function ay(e){return e=(e||0)%360,e<0?e+360:e}function Jn(e){return Math.max(0,Math.min(1,e||0))}function Wc(e,t,r){return(e<60?t+(r-t)*e/60:e<180?r:e<240?t+(r-t)*(240-e)/60:t)*255}const _f=e=>()=>e;function $A(e,t){return function(r){return e+r*t}}function IA(e,t,r){return e=Math.pow(e,r),t=Math.pow(t,r)-e,r=1/r,function(n){return Math.pow(e+n*t,r)}}function RA(e){return(e=+e)==1?Vb:function(t,r){return r-t?IA(t,r,e):_f(isNaN(t)?r:t)}}function Vb(e,t){var r=t-e;return r?$A(e,r):_f(isNaN(e)?t:e)}const oy=(function e(t){var r=RA(t);function n(i,a){var o=r((i=ol(i)).r,(a=ol(a)).r),u=r(i.g,a.g),c=r(i.b,a.b),s=Vb(i.opacity,a.opacity);return function(f){return i.r=o(f),i.g=u(f),i.b=c(f),i.opacity=s(f),i+""}}return n.gamma=e,n})(1);function kA(e,t){t||(t=[]);var r=e?Math.min(t.length,e.length):0,n=t.slice(),i;return function(a){for(i=0;ir&&(a=t.slice(r,a),u[o]?u[o]+=a:u[++o]=a),(n=n[0])===(i=i[0])?u[o]?u[o]+=i:u[++o]=i:(u[++o]=null,c.push({i:o,x:_i(n,i)})),r=zc.lastIndex;return rt&&(r=e,e=t,t=r),function(n){return Math.max(e,Math.min(t,n))}}function GA(e,t,r){var n=e[0],i=e[1],a=t[0],o=t[1];return i2?KA:GA,c=s=null,l}function l(h){return h==null||isNaN(h=+h)?a:(c||(c=u(e.map(n),t,r)))(n(o(h)))}return l.invert=function(h){return o(i((s||(s=u(t,e.map(n),_i)))(h)))},l.domain=function(h){return arguments.length?(e=Array.from(h,Si),f()):e.slice()},l.range=function(h){return arguments.length?(t=Array.from(h),f()):t.slice()},l.rangeRound=function(h){return t=Array.from(h),r=Sf,f()},l.clamp=function(h){return arguments.length?(o=h?!0:Me,f()):o!==Me},l.interpolate=function(h){return arguments.length?(r=h,f()):r},l.unknown=function(h){return arguments.length?(a=h,l):a},function(h,d){return n=h,i=d,f()}}function Af(){return va()(Me,Me)}function XA(e){return Math.abs(e=Math.round(e))>=1e21?e.toLocaleString("en").replace(/,/g,""):e.toString(10)}function Ai(e,t){if((r=(e=t?e.toExponential(t-1):e.toExponential()).indexOf("e"))<0)return null;var r,n=e.slice(0,r);return[n.length>1?n[0]+n.slice(2):n,+e.slice(r+1)]}function vr(e){return e=Ai(Math.abs(e)),e?e[1]:NaN}function VA(e,t){return function(r,n){for(var i=r.length,a=[],o=0,u=e[0],c=0;i>0&&u>0&&(c+u+1>n&&(u=Math.max(1,n-c)),a.push(r.substring(i-=u,i+u)),!((c+=u+1)>n));)u=e[o=(o+1)%e.length];return a.reverse().join(t)}}function YA(e){return function(t){return t.replace(/[0-9]/g,function(r){return e[+r]})}}var ZA=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function hn(e){if(!(t=ZA.exec(e)))throw new Error("invalid format: "+e);var t;return new Pf({fill:t[1],align:t[2],sign:t[3],symbol:t[4],zero:t[5],width:t[6],comma:t[7],precision:t[8]&&t[8].slice(1),trim:t[9],type:t[10]})}hn.prototype=Pf.prototype;function Pf(e){this.fill=e.fill===void 0?" ":e.fill+"",this.align=e.align===void 0?">":e.align+"",this.sign=e.sign===void 0?"-":e.sign+"",this.symbol=e.symbol===void 0?"":e.symbol+"",this.zero=!!e.zero,this.width=e.width===void 0?void 0:+e.width,this.comma=!!e.comma,this.precision=e.precision===void 0?void 0:+e.precision,this.trim=!!e.trim,this.type=e.type===void 0?"":e.type+""}Pf.prototype.toString=function(){return this.fill+this.align+this.sign+this.symbol+(this.zero?"0":"")+(this.width===void 0?"":Math.max(1,this.width|0))+(this.comma?",":"")+(this.precision===void 0?"":"."+Math.max(0,this.precision|0))+(this.trim?"~":"")+this.type};function JA(e){e:for(var t=e.length,r=1,n=-1,i;r0&&(n=0);break}return n>0?e.slice(0,n)+e.slice(i+1):e}var Yb;function QA(e,t){var r=Ai(e,t);if(!r)return e+"";var n=r[0],i=r[1],a=i-(Yb=Math.max(-8,Math.min(8,Math.floor(i/3)))*3)+1,o=n.length;return a===o?n:a>o?n+new Array(a-o+1).join("0"):a>0?n.slice(0,a)+"."+n.slice(a):"0."+new Array(1-a).join("0")+Ai(e,Math.max(0,t+a-1))[0]}function cy(e,t){var r=Ai(e,t);if(!r)return e+"";var n=r[0],i=r[1];return i<0?"0."+new Array(-i).join("0")+n:n.length>i+1?n.slice(0,i+1)+"."+n.slice(i+1):n+new Array(i-n.length+2).join("0")}const sy={"%":(e,t)=>(e*100).toFixed(t),b:e=>Math.round(e).toString(2),c:e=>e+"",d:XA,e:(e,t)=>e.toExponential(t),f:(e,t)=>e.toFixed(t),g:(e,t)=>e.toPrecision(t),o:e=>Math.round(e).toString(8),p:(e,t)=>cy(e*100,t),r:cy,s:QA,X:e=>Math.round(e).toString(16).toUpperCase(),x:e=>Math.round(e).toString(16)};function ly(e){return e}var fy=Array.prototype.map,hy=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function eP(e){var t=e.grouping===void 0||e.thousands===void 0?ly:VA(fy.call(e.grouping,Number),e.thousands+""),r=e.currency===void 0?"":e.currency[0]+"",n=e.currency===void 0?"":e.currency[1]+"",i=e.decimal===void 0?".":e.decimal+"",a=e.numerals===void 0?ly:YA(fy.call(e.numerals,String)),o=e.percent===void 0?"%":e.percent+"",u=e.minus===void 0?"−":e.minus+"",c=e.nan===void 0?"NaN":e.nan+"";function s(l){l=hn(l);var h=l.fill,d=l.align,g=l.sign,v=l.symbol,p=l.zero,m=l.width,x=l.comma,w=l.precision,O=l.trim,y=l.type;y==="n"?(x=!0,y="g"):sy[y]||(w===void 0&&(w=12),O=!0,y="g"),(p||h==="0"&&d==="=")&&(p=!0,h="0",d="=");var b=v==="$"?r:v==="#"&&/[boxX]/.test(y)?"0"+y.toLowerCase():"",_=v==="$"?n:/[%p]/.test(y)?o:"",S=sy[y],P=/[defgprs%]/.test(y);w=w===void 0?6:/[gprs]/.test(y)?Math.max(1,Math.min(21,w)):Math.max(0,Math.min(20,w));function M(A){var E=b,j=_,I,$,R;if(y==="c")j=S(A)+j,A="";else{A=+A;var D=A<0||1/A<0;if(A=isNaN(A)?c:S(Math.abs(A),w),O&&(A=JA(A)),D&&+A==0&&g!=="+"&&(D=!1),E=(D?g==="("?g:u:g==="-"||g==="("?"":g)+E,j=(y==="s"?hy[8+Yb/3]:"")+j+(D&&g==="("?")":""),P){for(I=-1,$=A.length;++I<$;)if(R=A.charCodeAt(I),48>R||R>57){j=(R===46?i+A.slice(I+1):A.slice(I))+j,A=A.slice(0,I);break}}}x&&!p&&(A=t(A,1/0));var B=E.length+A.length+j.length,L=B>1)+E+A+j+L.slice(B);break;default:A=L+E+A+j;break}return a(A)}return M.toString=function(){return l+""},M}function f(l,h){var d=s((l=hn(l),l.type="f",l)),g=Math.max(-8,Math.min(8,Math.floor(vr(h)/3)))*3,v=Math.pow(10,-g),p=hy[8+g/3];return function(m){return d(v*m)+p}}return{format:s,formatPrefix:f}}var Qn,Tf,Zb;tP({thousands:",",grouping:[3],currency:["$",""]});function tP(e){return Qn=eP(e),Tf=Qn.format,Zb=Qn.formatPrefix,Qn}function rP(e){return Math.max(0,-vr(Math.abs(e)))}function nP(e,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(vr(t)/3)))*3-vr(Math.abs(e)))}function iP(e,t){return e=Math.abs(e),t=Math.abs(t)-e,Math.max(0,vr(t)-vr(e))+1}function Jb(e,t,r,n){var i=il(e,t,r),a;switch(n=hn(n??",f"),n.type){case"s":{var o=Math.max(Math.abs(e),Math.abs(t));return n.precision==null&&!isNaN(a=nP(i,o))&&(n.precision=a),Zb(n,o)}case"":case"e":case"g":case"p":case"r":{n.precision==null&&!isNaN(a=iP(i,Math.max(Math.abs(e),Math.abs(t))))&&(n.precision=a-(n.type==="e"));break}case"f":case"%":{n.precision==null&&!isNaN(a=rP(i))&&(n.precision=a-(n.type==="%")*2);break}}return Tf(n)}function Et(e){var t=e.domain;return e.ticks=function(r){var n=t();return rl(n[0],n[n.length-1],r??10)},e.tickFormat=function(r,n){var i=t();return Jb(i[0],i[i.length-1],r??10,n)},e.nice=function(r){r==null&&(r=10);var n=t(),i=0,a=n.length-1,o=n[i],u=n[a],c,s,f=10;for(u0;){if(s=nl(o,u,r),s===c)return n[i]=o,n[a]=u,t(n);if(s>0)o=Math.floor(o/s)*s,u=Math.ceil(u/s)*s;else if(s<0)o=Math.ceil(o*s)/s,u=Math.floor(u*s)/s;else break;c=s}return e},e}function Pi(){var e=Af();return e.copy=function(){return Un(e,Pi())},He.apply(e,arguments),Et(e)}function Qb(e){var t;function r(n){return n==null||isNaN(n=+n)?t:n}return r.invert=r,r.domain=r.range=function(n){return arguments.length?(e=Array.from(n,Si),r):e.slice()},r.unknown=function(n){return arguments.length?(t=n,r):t},r.copy=function(){return Qb(e).unknown(t)},e=arguments.length?Array.from(e,Si):[0,1],Et(r)}function e0(e,t){e=e.slice();var r=0,n=e.length-1,i=e[r],a=e[n],o;return aMath.pow(e,t)}function sP(e){return e===Math.E?Math.log:e===10&&Math.log10||e===2&&Math.log2||(e=Math.log(e),t=>Math.log(t)/e)}function vy(e){return(t,r)=>-e(-t,r)}function Ef(e){const t=e(py,dy),r=t.domain;let n=10,i,a;function o(){return i=sP(n),a=cP(n),r()[0]<0?(i=vy(i),a=vy(a),e(aP,oP)):e(py,dy),t}return t.base=function(u){return arguments.length?(n=+u,o()):n},t.domain=function(u){return arguments.length?(r(u),o()):r()},t.ticks=u=>{const c=r();let s=c[0],f=c[c.length-1];const l=f0){for(;h<=d;++h)for(g=1;gf)break;m.push(v)}}else for(;h<=d;++h)for(g=n-1;g>=1;--g)if(v=h>0?g/a(-h):g*a(h),!(vf)break;m.push(v)}m.length*2{if(u==null&&(u=10),c==null&&(c=n===10?"s":","),typeof c!="function"&&(!(n%1)&&(c=hn(c)).precision==null&&(c.trim=!0),c=Tf(c)),u===1/0)return c;const s=Math.max(1,n*u/t.ticks().length);return f=>{let l=f/a(Math.round(i(f)));return l*nr(e0(r(),{floor:u=>a(Math.floor(i(u))),ceil:u=>a(Math.ceil(i(u)))})),t}function t0(){const e=Ef(va()).domain([1,10]);return e.copy=()=>Un(e,t0()).base(e.base()),He.apply(e,arguments),e}function yy(e){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/e))}}function gy(e){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*e}}function jf(e){var t=1,r=e(yy(t),gy(t));return r.constant=function(n){return arguments.length?e(yy(t=+n),gy(t)):t},Et(r)}function r0(){var e=jf(va());return e.copy=function(){return Un(e,r0()).constant(e.constant())},He.apply(e,arguments)}function my(e){return function(t){return t<0?-Math.pow(-t,e):Math.pow(t,e)}}function lP(e){return e<0?-Math.sqrt(-e):Math.sqrt(e)}function fP(e){return e<0?-e*e:e*e}function Mf(e){var t=e(Me,Me),r=1;function n(){return r===1?e(Me,Me):r===.5?e(lP,fP):e(my(r),my(1/r))}return t.exponent=function(i){return arguments.length?(r=+i,n()):r},Et(t)}function Cf(){var e=Mf(va());return e.copy=function(){return Un(e,Cf()).exponent(e.exponent())},He.apply(e,arguments),e}function hP(){return Cf.apply(null,arguments).exponent(.5)}function by(e){return Math.sign(e)*e*e}function pP(e){return Math.sign(e)*Math.sqrt(Math.abs(e))}function n0(){var e=Af(),t=[0,1],r=!1,n;function i(a){var o=pP(e(a));return isNaN(o)?n:r?Math.round(o):o}return i.invert=function(a){return e.invert(by(a))},i.domain=function(a){return arguments.length?(e.domain(a),i):e.domain()},i.range=function(a){return arguments.length?(e.range((t=Array.from(a,Si)).map(by)),i):t.slice()},i.rangeRound=function(a){return i.range(a).round(!0)},i.round=function(a){return arguments.length?(r=!!a,i):r},i.clamp=function(a){return arguments.length?(e.clamp(a),i):e.clamp()},i.unknown=function(a){return arguments.length?(n=a,i):n},i.copy=function(){return n0(e.domain(),t).round(r).clamp(e.clamp()).unknown(n)},He.apply(i,arguments),Et(i)}function i0(){var e=[],t=[],r=[],n;function i(){var o=0,u=Math.max(1,t.length);for(r=new Array(u-1);++o0?r[u-1]:e[0],u=r?[n[r-1],t]:[n[s-1],n[s]]},o.unknown=function(c){return arguments.length&&(a=c),o},o.thresholds=function(){return n.slice()},o.copy=function(){return a0().domain([e,t]).range(i).unknown(a)},He.apply(Et(o),arguments)}function o0(){var e=[.5],t=[0,1],r,n=1;function i(a){return a!=null&&a<=a?t[Ln(e,a,0,n)]:r}return i.domain=function(a){return arguments.length?(e=Array.from(a),n=Math.min(e.length,t.length-1),i):e.slice()},i.range=function(a){return arguments.length?(t=Array.from(a),n=Math.min(e.length,t.length-1),i):t.slice()},i.invertExtent=function(a){var o=t.indexOf(a);return[e[o-1],e[o]]},i.unknown=function(a){return arguments.length?(r=a,i):r},i.copy=function(){return o0().domain(e).range(t).unknown(r)},He.apply(i,arguments)}const Hc=new Date,Gc=new Date;function we(e,t,r,n){function i(a){return e(a=arguments.length===0?new Date:new Date(+a)),a}return i.floor=a=>(e(a=new Date(+a)),a),i.ceil=a=>(e(a=new Date(a-1)),t(a,1),e(a),a),i.round=a=>{const o=i(a),u=i.ceil(a);return a-o(t(a=new Date(+a),o==null?1:Math.floor(o)),a),i.range=(a,o,u)=>{const c=[];if(a=i.ceil(a),u=u==null?1:Math.floor(u),!(a0))return c;let s;do c.push(s=new Date(+a)),t(a,u),e(a);while(swe(o=>{if(o>=o)for(;e(o),!a(o);)o.setTime(o-1)},(o,u)=>{if(o>=o)if(u<0)for(;++u<=0;)for(;t(o,-1),!a(o););else for(;--u>=0;)for(;t(o,1),!a(o););}),r&&(i.count=(a,o)=>(Hc.setTime(+a),Gc.setTime(+o),e(Hc),e(Gc),Math.floor(r(Hc,Gc))),i.every=a=>(a=Math.floor(a),!isFinite(a)||!(a>0)?null:a>1?i.filter(n?o=>n(o)%a===0:o=>i.count(0,o)%a===0):i)),i}const Ti=we(()=>{},(e,t)=>{e.setTime(+e+t)},(e,t)=>t-e);Ti.every=e=>(e=Math.floor(e),!isFinite(e)||!(e>0)?null:e>1?we(t=>{t.setTime(Math.floor(t/e)*e)},(t,r)=>{t.setTime(+t+r*e)},(t,r)=>(r-t)/e):Ti);Ti.range;const ct=1e3,Ue=ct*60,st=Ue*60,dt=st*24,$f=dt*7,xy=dt*30,Kc=dt*365,Bt=we(e=>{e.setTime(e-e.getMilliseconds())},(e,t)=>{e.setTime(+e+t*ct)},(e,t)=>(t-e)/ct,e=>e.getUTCSeconds());Bt.range;const If=we(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*ct)},(e,t)=>{e.setTime(+e+t*Ue)},(e,t)=>(t-e)/Ue,e=>e.getMinutes());If.range;const Rf=we(e=>{e.setUTCSeconds(0,0)},(e,t)=>{e.setTime(+e+t*Ue)},(e,t)=>(t-e)/Ue,e=>e.getUTCMinutes());Rf.range;const kf=we(e=>{e.setTime(e-e.getMilliseconds()-e.getSeconds()*ct-e.getMinutes()*Ue)},(e,t)=>{e.setTime(+e+t*st)},(e,t)=>(t-e)/st,e=>e.getHours());kf.range;const Df=we(e=>{e.setUTCMinutes(0,0,0)},(e,t)=>{e.setTime(+e+t*st)},(e,t)=>(t-e)/st,e=>e.getUTCHours());Df.range;const Wn=we(e=>e.setHours(0,0,0,0),(e,t)=>e.setDate(e.getDate()+t),(e,t)=>(t-e-(t.getTimezoneOffset()-e.getTimezoneOffset())*Ue)/dt,e=>e.getDate()-1);Wn.range;const ya=we(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/dt,e=>e.getUTCDate()-1);ya.range;const u0=we(e=>{e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCDate(e.getUTCDate()+t)},(e,t)=>(t-e)/dt,e=>Math.floor(e/dt));u0.range;function Vt(e){return we(t=>{t.setDate(t.getDate()-(t.getDay()+7-e)%7),t.setHours(0,0,0,0)},(t,r)=>{t.setDate(t.getDate()+r*7)},(t,r)=>(r-t-(r.getTimezoneOffset()-t.getTimezoneOffset())*Ue)/$f)}const ga=Vt(0),Ei=Vt(1),dP=Vt(2),vP=Vt(3),yr=Vt(4),yP=Vt(5),gP=Vt(6);ga.range;Ei.range;dP.range;vP.range;yr.range;yP.range;gP.range;function Yt(e){return we(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-e)%7),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCDate(t.getUTCDate()+r*7)},(t,r)=>(r-t)/$f)}const ma=Yt(0),ji=Yt(1),mP=Yt(2),bP=Yt(3),gr=Yt(4),xP=Yt(5),wP=Yt(6);ma.range;ji.range;mP.range;bP.range;gr.range;xP.range;wP.range;const Nf=we(e=>{e.setDate(1),e.setHours(0,0,0,0)},(e,t)=>{e.setMonth(e.getMonth()+t)},(e,t)=>t.getMonth()-e.getMonth()+(t.getFullYear()-e.getFullYear())*12,e=>e.getMonth());Nf.range;const qf=we(e=>{e.setUTCDate(1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCMonth(e.getUTCMonth()+t)},(e,t)=>t.getUTCMonth()-e.getUTCMonth()+(t.getUTCFullYear()-e.getUTCFullYear())*12,e=>e.getUTCMonth());qf.range;const vt=we(e=>{e.setMonth(0,1),e.setHours(0,0,0,0)},(e,t)=>{e.setFullYear(e.getFullYear()+t)},(e,t)=>t.getFullYear()-e.getFullYear(),e=>e.getFullYear());vt.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:we(t=>{t.setFullYear(Math.floor(t.getFullYear()/e)*e),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,r)=>{t.setFullYear(t.getFullYear()+r*e)});vt.range;const yt=we(e=>{e.setUTCMonth(0,1),e.setUTCHours(0,0,0,0)},(e,t)=>{e.setUTCFullYear(e.getUTCFullYear()+t)},(e,t)=>t.getUTCFullYear()-e.getUTCFullYear(),e=>e.getUTCFullYear());yt.every=e=>!isFinite(e=Math.floor(e))||!(e>0)?null:we(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/e)*e),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,r)=>{t.setUTCFullYear(t.getUTCFullYear()+r*e)});yt.range;function c0(e,t,r,n,i,a){const o=[[Bt,1,ct],[Bt,5,5*ct],[Bt,15,15*ct],[Bt,30,30*ct],[a,1,Ue],[a,5,5*Ue],[a,15,15*Ue],[a,30,30*Ue],[i,1,st],[i,3,3*st],[i,6,6*st],[i,12,12*st],[n,1,dt],[n,2,2*dt],[r,1,$f],[t,1,xy],[t,3,3*xy],[e,1,Kc]];function u(s,f,l){const h=fp).right(o,h);if(d===o.length)return e.every(il(s/Kc,f/Kc,l));if(d===0)return Ti.every(Math.max(il(s,f,l),1));const[g,v]=o[h/o[d-1][2]53)return null;"w"in k||(k.w=1),"Z"in k?(J=Vc(Lr(k.y,0,1)),ye=J.getUTCDay(),J=ye>4||ye===0?ji.ceil(J):ji(J),J=ya.offset(J,(k.V-1)*7),k.y=J.getUTCFullYear(),k.m=J.getUTCMonth(),k.d=J.getUTCDate()+(k.w+6)%7):(J=Xc(Lr(k.y,0,1)),ye=J.getDay(),J=ye>4||ye===0?Ei.ceil(J):Ei(J),J=Wn.offset(J,(k.V-1)*7),k.y=J.getFullYear(),k.m=J.getMonth(),k.d=J.getDate()+(k.w+6)%7)}else("W"in k||"U"in k)&&("w"in k||(k.w="u"in k?k.u%7:"W"in k?1:0),ye="Z"in k?Vc(Lr(k.y,0,1)).getUTCDay():Xc(Lr(k.y,0,1)).getDay(),k.m=0,k.d="W"in k?(k.w+6)%7+k.W*7-(ye+5)%7:k.w+k.U*7-(ye+6)%7);return"Z"in k?(k.H+=k.Z/100|0,k.M+=k.Z%100,Vc(k)):Xc(k)}}function S(F,X,V,k){for(var fe=0,J=X.length,ye=V.length,ge,$e;fe=ye)return-1;if(ge=X.charCodeAt(fe++),ge===37){if(ge=X.charAt(fe++),$e=y[ge in wy?X.charAt(fe++):ge],!$e||(k=$e(F,V,k))<0)return-1}else if(ge!=V.charCodeAt(k++))return-1}return k}function P(F,X,V){var k=s.exec(X.slice(V));return k?(F.p=f.get(k[0].toLowerCase()),V+k[0].length):-1}function M(F,X,V){var k=d.exec(X.slice(V));return k?(F.w=g.get(k[0].toLowerCase()),V+k[0].length):-1}function A(F,X,V){var k=l.exec(X.slice(V));return k?(F.w=h.get(k[0].toLowerCase()),V+k[0].length):-1}function E(F,X,V){var k=m.exec(X.slice(V));return k?(F.m=x.get(k[0].toLowerCase()),V+k[0].length):-1}function j(F,X,V){var k=v.exec(X.slice(V));return k?(F.m=p.get(k[0].toLowerCase()),V+k[0].length):-1}function I(F,X,V){return S(F,t,X,V)}function $(F,X,V){return S(F,r,X,V)}function R(F,X,V){return S(F,n,X,V)}function D(F){return o[F.getDay()]}function B(F){return a[F.getDay()]}function L(F){return c[F.getMonth()]}function z(F){return u[F.getMonth()]}function G(F){return i[+(F.getHours()>=12)]}function U(F){return 1+~~(F.getMonth()/3)}function K(F){return o[F.getUTCDay()]}function ce(F){return a[F.getUTCDay()]}function pe(F){return c[F.getUTCMonth()]}function ke(F){return u[F.getUTCMonth()]}function Ct(F){return i[+(F.getUTCHours()>=12)]}function Ce(F){return 1+~~(F.getUTCMonth()/3)}return{format:function(F){var X=b(F+="",w);return X.toString=function(){return F},X},parse:function(F){var X=_(F+="",!1);return X.toString=function(){return F},X},utcFormat:function(F){var X=b(F+="",O);return X.toString=function(){return F},X},utcParse:function(F){var X=_(F+="",!0);return X.toString=function(){return F},X}}}var wy={"-":"",_:" ",0:"0"},Se=/^\s*\d+/,TP=/^%/,EP=/[\\^$*+?|[\]().{}]/g;function Q(e,t,r){var n=e<0?"-":"",i=(n?-e:e)+"",a=i.length;return n+(a[t.toLowerCase(),r]))}function MP(e,t,r){var n=Se.exec(t.slice(r,r+1));return n?(e.w=+n[0],r+n[0].length):-1}function CP(e,t,r){var n=Se.exec(t.slice(r,r+1));return n?(e.u=+n[0],r+n[0].length):-1}function $P(e,t,r){var n=Se.exec(t.slice(r,r+2));return n?(e.U=+n[0],r+n[0].length):-1}function IP(e,t,r){var n=Se.exec(t.slice(r,r+2));return n?(e.V=+n[0],r+n[0].length):-1}function RP(e,t,r){var n=Se.exec(t.slice(r,r+2));return n?(e.W=+n[0],r+n[0].length):-1}function Oy(e,t,r){var n=Se.exec(t.slice(r,r+4));return n?(e.y=+n[0],r+n[0].length):-1}function _y(e,t,r){var n=Se.exec(t.slice(r,r+2));return n?(e.y=+n[0]+(+n[0]>68?1900:2e3),r+n[0].length):-1}function kP(e,t,r){var n=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(r,r+6));return n?(e.Z=n[1]?0:-(n[2]+(n[3]||"00")),r+n[0].length):-1}function DP(e,t,r){var n=Se.exec(t.slice(r,r+1));return n?(e.q=n[0]*3-3,r+n[0].length):-1}function NP(e,t,r){var n=Se.exec(t.slice(r,r+2));return n?(e.m=n[0]-1,r+n[0].length):-1}function Sy(e,t,r){var n=Se.exec(t.slice(r,r+2));return n?(e.d=+n[0],r+n[0].length):-1}function qP(e,t,r){var n=Se.exec(t.slice(r,r+3));return n?(e.m=0,e.d=+n[0],r+n[0].length):-1}function Ay(e,t,r){var n=Se.exec(t.slice(r,r+2));return n?(e.H=+n[0],r+n[0].length):-1}function BP(e,t,r){var n=Se.exec(t.slice(r,r+2));return n?(e.M=+n[0],r+n[0].length):-1}function LP(e,t,r){var n=Se.exec(t.slice(r,r+2));return n?(e.S=+n[0],r+n[0].length):-1}function FP(e,t,r){var n=Se.exec(t.slice(r,r+3));return n?(e.L=+n[0],r+n[0].length):-1}function UP(e,t,r){var n=Se.exec(t.slice(r,r+6));return n?(e.L=Math.floor(n[0]/1e3),r+n[0].length):-1}function WP(e,t,r){var n=TP.exec(t.slice(r,r+1));return n?r+n[0].length:-1}function zP(e,t,r){var n=Se.exec(t.slice(r));return n?(e.Q=+n[0],r+n[0].length):-1}function HP(e,t,r){var n=Se.exec(t.slice(r));return n?(e.s=+n[0],r+n[0].length):-1}function Py(e,t){return Q(e.getDate(),t,2)}function GP(e,t){return Q(e.getHours(),t,2)}function KP(e,t){return Q(e.getHours()%12||12,t,2)}function XP(e,t){return Q(1+Wn.count(vt(e),e),t,3)}function s0(e,t){return Q(e.getMilliseconds(),t,3)}function VP(e,t){return s0(e,t)+"000"}function YP(e,t){return Q(e.getMonth()+1,t,2)}function ZP(e,t){return Q(e.getMinutes(),t,2)}function JP(e,t){return Q(e.getSeconds(),t,2)}function QP(e){var t=e.getDay();return t===0?7:t}function eT(e,t){return Q(ga.count(vt(e)-1,e),t,2)}function l0(e){var t=e.getDay();return t>=4||t===0?yr(e):yr.ceil(e)}function tT(e,t){return e=l0(e),Q(yr.count(vt(e),e)+(vt(e).getDay()===4),t,2)}function rT(e){return e.getDay()}function nT(e,t){return Q(Ei.count(vt(e)-1,e),t,2)}function iT(e,t){return Q(e.getFullYear()%100,t,2)}function aT(e,t){return e=l0(e),Q(e.getFullYear()%100,t,2)}function oT(e,t){return Q(e.getFullYear()%1e4,t,4)}function uT(e,t){var r=e.getDay();return e=r>=4||r===0?yr(e):yr.ceil(e),Q(e.getFullYear()%1e4,t,4)}function cT(e){var t=e.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Q(t/60|0,"0",2)+Q(t%60,"0",2)}function Ty(e,t){return Q(e.getUTCDate(),t,2)}function sT(e,t){return Q(e.getUTCHours(),t,2)}function lT(e,t){return Q(e.getUTCHours()%12||12,t,2)}function fT(e,t){return Q(1+ya.count(yt(e),e),t,3)}function f0(e,t){return Q(e.getUTCMilliseconds(),t,3)}function hT(e,t){return f0(e,t)+"000"}function pT(e,t){return Q(e.getUTCMonth()+1,t,2)}function dT(e,t){return Q(e.getUTCMinutes(),t,2)}function vT(e,t){return Q(e.getUTCSeconds(),t,2)}function yT(e){var t=e.getUTCDay();return t===0?7:t}function gT(e,t){return Q(ma.count(yt(e)-1,e),t,2)}function h0(e){var t=e.getUTCDay();return t>=4||t===0?gr(e):gr.ceil(e)}function mT(e,t){return e=h0(e),Q(gr.count(yt(e),e)+(yt(e).getUTCDay()===4),t,2)}function bT(e){return e.getUTCDay()}function xT(e,t){return Q(ji.count(yt(e)-1,e),t,2)}function wT(e,t){return Q(e.getUTCFullYear()%100,t,2)}function OT(e,t){return e=h0(e),Q(e.getUTCFullYear()%100,t,2)}function _T(e,t){return Q(e.getUTCFullYear()%1e4,t,4)}function ST(e,t){var r=e.getUTCDay();return e=r>=4||r===0?gr(e):gr.ceil(e),Q(e.getUTCFullYear()%1e4,t,4)}function AT(){return"+0000"}function Ey(){return"%"}function jy(e){return+e}function My(e){return Math.floor(+e/1e3)}var tr,p0,d0;PT({dateTime:"%x, %X",date:"%-m/%-d/%Y",time:"%-I:%M:%S %p",periods:["AM","PM"],days:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],shortDays:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],months:["January","February","March","April","May","June","July","August","September","October","November","December"],shortMonths:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"]});function PT(e){return tr=PP(e),p0=tr.format,tr.parse,d0=tr.utcFormat,tr.utcParse,tr}function TT(e){return new Date(e)}function ET(e){return e instanceof Date?+e:+new Date(+e)}function Bf(e,t,r,n,i,a,o,u,c,s){var f=Af(),l=f.invert,h=f.domain,d=s(".%L"),g=s(":%S"),v=s("%I:%M"),p=s("%I %p"),m=s("%a %d"),x=s("%b %d"),w=s("%B"),O=s("%Y");function y(b){return(c(b)t(i/(e.length-1)))},r.quantiles=function(n){return Array.from({length:n+1},(i,a)=>gA(e,a/n))},r.copy=function(){return m0(t).domain(e)},bt.apply(r,arguments)}function xa(){var e=0,t=.5,r=1,n=1,i,a,o,u,c,s=Me,f,l=!1,h;function d(v){return isNaN(v=+v)?h:(v=.5+((v=+f(v))-a)*(n*vr}return Zc=e,Zc}var Jc,Ry;function RT(){if(Ry)return Jc;Ry=1;var e=O0(),t=IT(),r=Ir();function n(i){return i&&i.length?e(i,r,t):void 0}return Jc=n,Jc}var kT=RT();const wa=ue(kT);var Qc,ky;function DT(){if(ky)return Qc;ky=1;function e(t,r){return te.e^a.s<0?1:-1;for(n=a.d.length,i=e.d.length,t=0,r=ne.d[t]^a.s<0?1:-1;return n===i?0:n>i^a.s<0?1:-1};W.decimalPlaces=W.dp=function(){var e=this,t=e.d.length-1,r=(t-e.e)*se;if(t=e.d[t],t)for(;t%10==0;t/=10)r--;return r<0?0:r};W.dividedBy=W.div=function(e){return pt(this,new this.constructor(e))};W.dividedToIntegerBy=W.idiv=function(e){var t=this,r=t.constructor;return ae(pt(t,new r(e),0,1),r.precision)};W.equals=W.eq=function(e){return!this.cmp(e)};W.exponent=function(){return ve(this)};W.greaterThan=W.gt=function(e){return this.cmp(e)>0};W.greaterThanOrEqualTo=W.gte=function(e){return this.cmp(e)>=0};W.isInteger=W.isint=function(){return this.e>this.d.length-2};W.isNegative=W.isneg=function(){return this.s<0};W.isPositive=W.ispos=function(){return this.s>0};W.isZero=function(){return this.s===0};W.lessThan=W.lt=function(e){return this.cmp(e)<0};W.lessThanOrEqualTo=W.lte=function(e){return this.cmp(e)<1};W.logarithm=W.log=function(e){var t,r=this,n=r.constructor,i=n.precision,a=i+5;if(e===void 0)e=new n(10);else if(e=new n(e),e.s<1||e.eq(qe))throw Error(ze+"NaN");if(r.s<1)throw Error(ze+(r.s?"NaN":"-Infinity"));return r.eq(qe)?new n(0):(le=!1,t=pt(pn(r,a),pn(e,a),a),le=!0,ae(t,i))};W.minus=W.sub=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?P0(t,e):S0(t,(e.s=-e.s,e))};W.modulo=W.mod=function(e){var t,r=this,n=r.constructor,i=n.precision;if(e=new n(e),!e.s)throw Error(ze+"NaN");return r.s?(le=!1,t=pt(r,e,0,1).times(e),le=!0,r.minus(t)):ae(new n(r),i)};W.naturalExponential=W.exp=function(){return A0(this)};W.naturalLogarithm=W.ln=function(){return pn(this)};W.negated=W.neg=function(){var e=new this.constructor(this);return e.s=-e.s||0,e};W.plus=W.add=function(e){var t=this;return e=new t.constructor(e),t.s==e.s?S0(t,e):P0(t,(e.s=-e.s,e))};W.precision=W.sd=function(e){var t,r,n,i=this;if(e!==void 0&&e!==!!e&&e!==1&&e!==0)throw Error(Ut+e);if(t=ve(i)+1,n=i.d.length-1,r=n*se+1,n=i.d[n],n){for(;n%10==0;n/=10)r--;for(n=i.d[0];n>=10;n/=10)r++}return e&&t>r?t:r};W.squareRoot=W.sqrt=function(){var e,t,r,n,i,a,o,u=this,c=u.constructor;if(u.s<1){if(!u.s)return new c(0);throw Error(ze+"NaN")}for(e=ve(u),le=!1,i=Math.sqrt(+u),i==0||i==1/0?(t=et(u.d),(t.length+e)%2==0&&(t+="0"),i=Math.sqrt(t),e=Dr((e+1)/2)-(e<0||e%2),i==1/0?t="5e"+e:(t=i.toExponential(),t=t.slice(0,t.indexOf("e")+1)+e),n=new c(t)):n=new c(i.toString()),r=c.precision,i=o=r+3;;)if(a=n,n=a.plus(pt(u,a,o+2)).times(.5),et(a.d).slice(0,o)===(t=et(n.d)).slice(0,o)){if(t=t.slice(o-3,o+1),i==o&&t=="4999"){if(ae(a,r+1,0),a.times(a).eq(u)){n=a;break}}else if(t!="9999")break;o+=4}return le=!0,ae(n,r)};W.times=W.mul=function(e){var t,r,n,i,a,o,u,c,s,f=this,l=f.constructor,h=f.d,d=(e=new l(e)).d;if(!f.s||!e.s)return new l(0);for(e.s*=f.s,r=f.e+e.e,c=h.length,s=d.length,c=0;){for(t=0,i=c+n;i>n;)u=a[i]+d[n]*h[i-n-1]+t,a[i--]=u%Oe|0,t=u/Oe|0;a[i]=(a[i]+t)%Oe|0}for(;!a[--o];)a.pop();return t?++r:a.shift(),e.d=a,e.e=r,le?ae(e,l.precision):e};W.toDecimalPlaces=W.todp=function(e,t){var r=this,n=r.constructor;return r=new n(r),e===void 0?r:(nt(e,0,kr),t===void 0?t=n.rounding:nt(t,0,8),ae(r,e+ve(r)+1,t))};W.toExponential=function(e,t){var r,n=this,i=n.constructor;return e===void 0?r=Ht(n,!0):(nt(e,0,kr),t===void 0?t=i.rounding:nt(t,0,8),n=ae(new i(n),e+1,t),r=Ht(n,!0,e+1)),r};W.toFixed=function(e,t){var r,n,i=this,a=i.constructor;return e===void 0?Ht(i):(nt(e,0,kr),t===void 0?t=a.rounding:nt(t,0,8),n=ae(new a(i),e+ve(i)+1,t),r=Ht(n.abs(),!1,e+ve(n)+1),i.isneg()&&!i.isZero()?"-"+r:r)};W.toInteger=W.toint=function(){var e=this,t=e.constructor;return ae(new t(e),ve(e)+1,t.rounding)};W.toNumber=function(){return+this};W.toPower=W.pow=function(e){var t,r,n,i,a,o,u=this,c=u.constructor,s=12,f=+(e=new c(e));if(!e.s)return new c(qe);if(u=new c(u),!u.s){if(e.s<1)throw Error(ze+"Infinity");return u}if(u.eq(qe))return u;if(n=c.precision,e.eq(qe))return ae(u,n);if(t=e.e,r=e.d.length-1,o=t>=r,a=u.s,o){if((r=f<0?-f:f)<=_0){for(i=new c(qe),t=Math.ceil(n/se+4),le=!1;r%2&&(i=i.times(u),Fy(i.d,t)),r=Dr(r/2),r!==0;)u=u.times(u),Fy(u.d,t);return le=!0,e.s<0?new c(qe).div(i):ae(i,n)}}else if(a<0)throw Error(ze+"NaN");return a=a<0&&e.d[Math.max(t,r)]&1?-1:1,u.s=1,le=!1,i=e.times(pn(u,n+s)),le=!0,i=A0(i),i.s=a,i};W.toPrecision=function(e,t){var r,n,i=this,a=i.constructor;return e===void 0?(r=ve(i),n=Ht(i,r<=a.toExpNeg||r>=a.toExpPos)):(nt(e,1,kr),t===void 0?t=a.rounding:nt(t,0,8),i=ae(new a(i),e,t),r=ve(i),n=Ht(i,e<=r||r<=a.toExpNeg,e)),n};W.toSignificantDigits=W.tosd=function(e,t){var r=this,n=r.constructor;return e===void 0?(e=n.precision,t=n.rounding):(nt(e,1,kr),t===void 0?t=n.rounding:nt(t,0,8)),ae(new n(r),e,t)};W.toString=W.valueOf=W.val=W.toJSON=W[Symbol.for("nodejs.util.inspect.custom")]=function(){var e=this,t=ve(e),r=e.constructor;return Ht(e,t<=r.toExpNeg||t>=r.toExpPos)};function S0(e,t){var r,n,i,a,o,u,c,s,f=e.constructor,l=f.precision;if(!e.s||!t.s)return t.s||(t=new f(e)),le?ae(t,l):t;if(c=e.d,s=t.d,o=e.e,i=t.e,c=c.slice(),a=o-i,a){for(a<0?(n=c,a=-a,u=s.length):(n=s,i=o,u=c.length),o=Math.ceil(l/se),u=o>u?o+1:u+1,a>u&&(a=u,n.length=1),n.reverse();a--;)n.push(0);n.reverse()}for(u=c.length,a=s.length,u-a<0&&(a=u,n=s,s=c,c=n),r=0;a;)r=(c[--a]=c[a]+s[a]+r)/Oe|0,c[a]%=Oe;for(r&&(c.unshift(r),++i),u=c.length;c[--u]==0;)c.pop();return t.d=c,t.e=i,le?ae(t,l):t}function nt(e,t,r){if(e!==~~e||er)throw Error(Ut+e)}function et(e){var t,r,n,i=e.length-1,a="",o=e[0];if(i>0){for(a+=o,t=1;to?1:-1;else for(u=c=0;ui[u]?1:-1;break}return c}function r(n,i,a){for(var o=0;a--;)n[a]-=o,o=n[a]1;)n.shift()}return function(n,i,a,o){var u,c,s,f,l,h,d,g,v,p,m,x,w,O,y,b,_,S,P=n.constructor,M=n.s==i.s?1:-1,A=n.d,E=i.d;if(!n.s)return new P(n);if(!i.s)throw Error(ze+"Division by zero");for(c=n.e-i.e,_=E.length,y=A.length,d=new P(M),g=d.d=[],s=0;E[s]==(A[s]||0);)++s;if(E[s]>(A[s]||0)&&--c,a==null?x=a=P.precision:o?x=a+(ve(n)-ve(i))+1:x=a,x<0)return new P(0);if(x=x/se+2|0,s=0,_==1)for(f=0,E=E[0],x++;(s1&&(E=e(E,f),A=e(A,f),_=E.length,y=A.length),O=_,v=A.slice(0,_),p=v.length;p<_;)v[p++]=0;S=E.slice(),S.unshift(0),b=E[0],E[1]>=Oe/2&&++b;do f=0,u=t(E,v,_,p),u<0?(m=v[0],_!=p&&(m=m*Oe+(v[1]||0)),f=m/b|0,f>1?(f>=Oe&&(f=Oe-1),l=e(E,f),h=l.length,p=v.length,u=t(l,v,h,p),u==1&&(f--,r(l,_16)throw Error(Wf+ve(e));if(!e.s)return new f(qe);for(le=!1,u=l,o=new f(.03125);e.abs().gte(.1);)e=e.times(o),s+=5;for(n=Math.log(Dt(2,s))/Math.LN10*2+5|0,u+=n,r=i=a=new f(qe),f.precision=u;;){if(i=ae(i.times(e),u),r=r.times(++c),o=a.plus(pt(i,r,u)),et(o.d).slice(0,u)===et(a.d).slice(0,u)){for(;s--;)a=ae(a.times(a),u);return f.precision=l,t==null?(le=!0,ae(a,l)):a}a=o}}function ve(e){for(var t=e.e*se,r=e.d[0];r>=10;r/=10)t++;return t}function is(e,t,r){if(t>e.LN10.sd())throw le=!0,r&&(e.precision=r),Error(ze+"LN10 precision limit exceeded");return ae(new e(e.LN10),t)}function wt(e){for(var t="";e--;)t+="0";return t}function pn(e,t){var r,n,i,a,o,u,c,s,f,l=1,h=10,d=e,g=d.d,v=d.constructor,p=v.precision;if(d.s<1)throw Error(ze+(d.s?"NaN":"-Infinity"));if(d.eq(qe))return new v(0);if(t==null?(le=!1,s=p):s=t,d.eq(10))return t==null&&(le=!0),is(v,s);if(s+=h,v.precision=s,r=et(g),n=r.charAt(0),a=ve(d),Math.abs(a)<15e14){for(;n<7&&n!=1||n==1&&r.charAt(1)>3;)d=d.times(e),r=et(d.d),n=r.charAt(0),l++;a=ve(d),n>1?(d=new v("0."+r),a++):d=new v(n+"."+r.slice(1))}else return c=is(v,s+2,p).times(a+""),d=pn(new v(n+"."+r.slice(1)),s-h).plus(c),v.precision=p,t==null?(le=!0,ae(d,p)):d;for(u=o=d=pt(d.minus(qe),d.plus(qe),s),f=ae(d.times(d),s),i=3;;){if(o=ae(o.times(f),s),c=u.plus(pt(o,new v(i),s)),et(c.d).slice(0,s)===et(u.d).slice(0,s))return u=u.times(2),a!==0&&(u=u.plus(is(v,s+2,p).times(a+""))),u=pt(u,new v(l),s),v.precision=p,t==null?(le=!0,ae(u,p)):u;u=c,i+=2}}function Ly(e,t){var r,n,i;for((r=t.indexOf("."))>-1&&(t=t.replace(".","")),(n=t.search(/e/i))>0?(r<0&&(r=n),r+=+t.slice(n+1),t=t.substring(0,n)):r<0&&(r=t.length),n=0;t.charCodeAt(n)===48;)++n;for(i=t.length;t.charCodeAt(i-1)===48;)--i;if(t=t.slice(n,i),t){if(i-=n,r=r-n-1,e.e=Dr(r/se),e.d=[],n=(r+1)%se,r<0&&(n+=se),nMi||e.e<-Mi))throw Error(Wf+r)}else e.s=0,e.e=0,e.d=[0];return e}function ae(e,t,r){var n,i,a,o,u,c,s,f,l=e.d;for(o=1,a=l[0];a>=10;a/=10)o++;if(n=t-o,n<0)n+=se,i=t,s=l[f=0];else{if(f=Math.ceil((n+1)/se),a=l.length,f>=a)return e;for(s=a=l[f],o=1;a>=10;a/=10)o++;n%=se,i=n-se+o}if(r!==void 0&&(a=Dt(10,o-i-1),u=s/a%10|0,c=t<0||l[f+1]!==void 0||s%a,c=r<4?(u||c)&&(r==0||r==(e.s<0?3:2)):u>5||u==5&&(r==4||c||r==6&&(n>0?i>0?s/Dt(10,o-i):0:l[f-1])%10&1||r==(e.s<0?8:7))),t<1||!l[0])return c?(a=ve(e),l.length=1,t=t-a-1,l[0]=Dt(10,(se-t%se)%se),e.e=Dr(-t/se)||0):(l.length=1,l[0]=e.e=e.s=0),e;if(n==0?(l.length=f,a=1,f--):(l.length=f+1,a=Dt(10,se-n),l[f]=i>0?(s/Dt(10,o-i)%Dt(10,i)|0)*a:0),c)for(;;)if(f==0){(l[0]+=a)==Oe&&(l[0]=1,++e.e);break}else{if(l[f]+=a,l[f]!=Oe)break;l[f--]=0,a=1}for(n=l.length;l[--n]===0;)l.pop();if(le&&(e.e>Mi||e.e<-Mi))throw Error(Wf+ve(e));return e}function P0(e,t){var r,n,i,a,o,u,c,s,f,l,h=e.constructor,d=h.precision;if(!e.s||!t.s)return t.s?t.s=-t.s:t=new h(e),le?ae(t,d):t;if(c=e.d,l=t.d,n=t.e,s=e.e,c=c.slice(),o=s-n,o){for(f=o<0,f?(r=c,o=-o,u=l.length):(r=l,n=s,u=c.length),i=Math.max(Math.ceil(d/se),u)+2,o>i&&(o=i,r.length=1),r.reverse(),i=o;i--;)r.push(0);r.reverse()}else{for(i=c.length,u=l.length,f=i0;--i)c[u++]=0;for(i=l.length;i>o;){if(c[--i]0?a=a.charAt(0)+"."+a.slice(1)+wt(n):o>1&&(a=a.charAt(0)+"."+a.slice(1)),a=a+(i<0?"e":"e+")+i):i<0?(a="0."+wt(-i-1)+a,r&&(n=r-o)>0&&(a+=wt(n))):i>=o?(a+=wt(i+1-o),r&&(n=r-i-1)>0&&(a=a+"."+wt(n))):((n=i+1)0&&(i+1===o&&(a+="."),a+=wt(n))),e.s<0?"-"+a:a}function Fy(e,t){if(e.length>t)return e.length=t,!0}function T0(e){var t,r,n;function i(a){var o=this;if(!(o instanceof i))return new i(a);if(o.constructor=i,a instanceof i){o.s=a.s,o.e=a.e,o.d=(a=a.d)?a.slice():a;return}if(typeof a=="number"){if(a*0!==0)throw Error(Ut+a);if(a>0)o.s=1;else if(a<0)a=-a,o.s=-1;else{o.s=0,o.e=0,o.d=[0];return}if(a===~~a&&a<1e7){o.e=0,o.d=[a];return}return Ly(o,a.toString())}else if(typeof a!="string")throw Error(Ut+a);if(a.charCodeAt(0)===45?(a=a.slice(1),o.s=-1):o.s=1,GT.test(a))Ly(o,a);else throw Error(Ut+a)}if(i.prototype=W,i.ROUND_UP=0,i.ROUND_DOWN=1,i.ROUND_CEIL=2,i.ROUND_FLOOR=3,i.ROUND_HALF_UP=4,i.ROUND_HALF_DOWN=5,i.ROUND_HALF_EVEN=6,i.ROUND_HALF_CEIL=7,i.ROUND_HALF_FLOOR=8,i.clone=T0,i.config=i.set=KT,e===void 0&&(e={}),e)for(n=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t=i[t+1]&&n<=i[t+2])this[r]=n;else throw Error(Ut+r+": "+n);if((n=e[r="LN10"])!==void 0)if(n==Math.LN10)this[r]=new this(n);else throw Error(Ut+r+": "+n);return this}var zf=T0(HT);qe=new zf(1);const ie=zf;function XT(e){return JT(e)||ZT(e)||YT(e)||VT()}function VT(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function YT(e,t){if(e){if(typeof e=="string")return sl(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return sl(e,t)}}function ZT(e){if(typeof Symbol<"u"&&Symbol.iterator in Object(e))return Array.from(e)}function JT(e){if(Array.isArray(e))return sl(e)}function sl(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=t?r.apply(void 0,i):e(t-o,Uy(function(){for(var u=arguments.length,c=new Array(u),s=0;se.length)&&(t=e.length);for(var r=0,n=new Array(t);r"u"||!(Symbol.iterator in Object(e)))){var r=[],n=!0,i=!1,a=void 0;try{for(var o=e[Symbol.iterator](),u;!(n=(u=o.next()).done)&&(r.push(u.value),!(t&&r.length===t));n=!0);}catch(c){i=!0,a=c}finally{try{!n&&o.return!=null&&o.return()}finally{if(i)throw a}}return r}}function pE(e){if(Array.isArray(e))return e}function $0(e){var t=dn(e,2),r=t[0],n=t[1],i=r,a=n;return r>n&&(i=n,a=r),[i,a]}function I0(e,t,r){if(e.lte(0))return new ie(0);var n=Sa.getDigitCount(e.toNumber()),i=new ie(10).pow(n),a=e.div(i),o=n!==1?.05:.1,u=new ie(Math.ceil(a.div(o).toNumber())).add(r).mul(o),c=u.mul(i);return t?c:new ie(Math.ceil(c))}function dE(e,t,r){var n=1,i=new ie(e);if(!i.isint()&&r){var a=Math.abs(e);a<1?(n=new ie(10).pow(Sa.getDigitCount(e)-1),i=new ie(Math.floor(i.div(n).toNumber())).mul(n)):a>1&&(i=new ie(Math.floor(e)))}else e===0?i=new ie(Math.floor((t-1)/2)):r||(i=new ie(Math.floor(e)));var o=Math.floor((t-1)/2),u=rE(tE(function(c){return i.add(new ie(c-o).mul(n)).toNumber()}),ll);return u(0,t)}function R0(e,t,r,n){var i=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-e)/(r-1)))return{step:new ie(0),tickMin:new ie(0),tickMax:new ie(0)};var a=I0(new ie(t).sub(e).div(r-1),n,i),o;e<=0&&t>=0?o=new ie(0):(o=new ie(e).add(t).div(2),o=o.sub(new ie(o).mod(a)));var u=Math.ceil(o.sub(e).div(a).toNumber()),c=Math.ceil(new ie(t).sub(o).div(a).toNumber()),s=u+c+1;return s>r?R0(e,t,r,n,i+1):(s0?c+(r-s):c,u=t>0?u:u+(r-s)),{step:a,tickMin:o.sub(new ie(u).mul(a)),tickMax:o.add(new ie(c).mul(a))})}function vE(e){var t=dn(e,2),r=t[0],n=t[1],i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=Math.max(i,2),u=$0([r,n]),c=dn(u,2),s=c[0],f=c[1];if(s===-1/0||f===1/0){var l=f===1/0?[s].concat(hl(ll(0,i-1).map(function(){return 1/0}))):[].concat(hl(ll(0,i-1).map(function(){return-1/0})),[f]);return r>n?fl(l):l}if(s===f)return dE(s,i,a);var h=R0(s,f,o,a),d=h.step,g=h.tickMin,v=h.tickMax,p=Sa.rangeStep(g,v.add(new ie(.1).mul(d)),d);return r>n?fl(p):p}function yE(e,t){var r=dn(e,2),n=r[0],i=r[1],a=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,o=$0([n,i]),u=dn(o,2),c=u[0],s=u[1];if(c===-1/0||s===1/0)return[n,i];if(c===s)return[c];var f=Math.max(t,2),l=I0(new ie(s).sub(c).div(f-1),a,0),h=[].concat(hl(Sa.rangeStep(new ie(c),new ie(s).sub(new ie(.99).mul(l)),l)),[s]);return n>i?fl(h):h}var gE=M0(vE),mE=M0(yE),bE="Invariant failed";function Gt(e,t){throw new Error(bE)}var xE=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function mr(e){"@babel/helpers - typeof";return mr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},mr(e)}function Ci(){return Ci=Object.assign?Object.assign.bind():function(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function TE(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function EE(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function jE(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=new Array(t);r1&&arguments[1]!==void 0?arguments[1]:[],i=arguments.length>2?arguments[2]:void 0,a=arguments.length>3?arguments[3]:void 0,o=-1,u=(r=n?.length)!==null&&r!==void 0?r:0;if(u<=1)return 0;if(a&&a.axisType==="angleAxis"&&Math.abs(Math.abs(a.range[1]-a.range[0])-360)<=1e-6)for(var c=a.range,s=0;s0?i[s-1].coordinate:i[u-1].coordinate,l=i[s].coordinate,h=s>=u-1?i[0].coordinate:i[s+1].coordinate,d=void 0;if(Ve(l-f)!==Ve(h-l)){var g=[];if(Ve(h-l)===Ve(c[1]-c[0])){d=h;var v=l+c[1]-c[0];g[0]=Math.min(v,(v+f)/2),g[1]=Math.max(v,(v+f)/2)}else{d=f;var p=h+c[1]-c[0];g[0]=Math.min(l,(p+l)/2),g[1]=Math.max(l,(p+l)/2)}var m=[Math.min(l,(d+l)/2),Math.max(l,(d+l)/2)];if(t>m[0]&&t<=m[1]||t>=g[0]&&t<=g[1]){o=i[s].index;break}}else{var x=Math.min(f,h),w=Math.max(f,h);if(t>(x+l)/2&&t<=(w+l)/2){o=i[s].index;break}}}else for(var O=0;O0&&O(n[O].coordinate+n[O-1].coordinate)/2&&t<=(n[O].coordinate+n[O+1].coordinate)/2||O===u-1&&t>(n[O].coordinate+n[O-1].coordinate)/2){o=n[O].index;break}return o},Hf=function(t){var r,n=t,i=n.type.displayName,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?he(he({},t.type.defaultProps),t.props):t.props,o=a.stroke,u=a.fill,c;switch(i){case"Line":c=o;break;case"Area":case"Radar":c=o&&o!=="none"?o:u;break;default:c=u;break}return c},GE=function(t){var r=t.barSize,n=t.totalSize,i=t.stackGroups,a=i===void 0?{}:i;if(!a)return{};for(var o={},u=Object.keys(a),c=0,s=u.length;c=0});if(m&&m.length){var x=m[0].type.defaultProps,w=x!==void 0?he(he({},x),m[0].props):m[0].props,O=w.barSize,y=w[p];o[y]||(o[y]=[]);var b=Z(O)?r:O;o[y].push({item:m[0],stackList:m.slice(1),barSize:Z(b)?void 0:Ye(b,n,0)})}}return o},KE=function(t){var r=t.barGap,n=t.barCategoryGap,i=t.bandSize,a=t.sizeList,o=a===void 0?[]:a,u=t.maxBarSize,c=o.length;if(c<1)return null;var s=Ye(r,i,0,!0),f,l=[];if(o[0].barSize===+o[0].barSize){var h=!1,d=i/c,g=o.reduce(function(O,y){return O+y.barSize||0},0);g+=(c-1)*s,g>=i&&(g-=(c-1)*s,s=0),g>=i&&d>0&&(h=!0,d*=.9,g=c*d);var v=(i-g)/2>>0,p={offset:v-s,size:0};f=o.reduce(function(O,y){var b={item:y.item,position:{offset:p.offset+p.size+s,size:h?d:y.barSize}},_=[].concat(Hy(O),[b]);return p=_[_.length-1].position,y.stackList&&y.stackList.length&&y.stackList.forEach(function(S){_.push({item:S,position:p})}),_},l)}else{var m=Ye(n,i,0,!0);i-2*m-(c-1)*s<=0&&(s=0);var x=(i-2*m-(c-1)*s)/c;x>1&&(x>>=0);var w=u===+u?Math.min(x,u):x;f=o.reduce(function(O,y,b){var _=[].concat(Hy(O),[{item:y.item,position:{offset:m+(x+s)*b+(x-w)/2,size:w}}]);return y.stackList&&y.stackList.length&&y.stackList.forEach(function(S){_.push({item:S,position:_[_.length-1].position})}),_},l)}return f},XE=function(t,r,n,i){var a=n.children,o=n.width,u=n.margin,c=o-(u.left||0)-(u.right||0),s=q0({children:a,legendWidth:c});if(s){var f=i||{},l=f.width,h=f.height,d=s.align,g=s.verticalAlign,v=s.layout;if((v==="vertical"||v==="horizontal"&&g==="middle")&&d!=="center"&&q(t[d]))return he(he({},t),{},sr({},d,t[d]+(l||0)));if((v==="horizontal"||v==="vertical"&&d==="center")&&g!=="middle"&&q(t[g]))return he(he({},t),{},sr({},g,t[g]+(h||0)))}return t},VE=function(t,r,n){return Z(r)?!0:t==="horizontal"?r==="yAxis":t==="vertical"||n==="x"?r==="xAxis":n==="y"?r==="yAxis":!0},B0=function(t,r,n,i,a){var o=r.props.children,u=Ze(o,Aa).filter(function(s){return VE(i,a,s.props.direction)});if(u&&u.length){var c=u.map(function(s){return s.props.dataKey});return t.reduce(function(s,f){var l=Je(f,n);if(Z(l))return s;var h=Array.isArray(l)?[Oa(l),wa(l)]:[l,l],d=c.reduce(function(g,v){var p=Je(f,v,0),m=h[0]-Math.abs(Array.isArray(p)?p[0]:p),x=h[1]+Math.abs(Array.isArray(p)?p[1]:p);return[Math.min(m,g[0]),Math.max(x,g[1])]},[1/0,-1/0]);return[Math.min(d[0],s[0]),Math.max(d[1],s[1])]},[1/0,-1/0])}return null},YE=function(t,r,n,i,a){var o=r.map(function(u){return B0(t,u,n,a,i)}).filter(function(u){return!Z(u)});return o&&o.length?o.reduce(function(u,c){return[Math.min(u[0],c[0]),Math.max(u[1],c[1])]},[1/0,-1/0]):null},L0=function(t,r,n,i,a){var o=r.map(function(c){var s=c.props.dataKey;return n==="number"&&s&&B0(t,c,s,i)||Jr(t,s,n,a)});if(n==="number")return o.reduce(function(c,s){return[Math.min(c[0],s[0]),Math.max(c[1],s[1])]},[1/0,-1/0]);var u={};return o.reduce(function(c,s){for(var f=0,l=s.length;f=2?Ve(u[0]-u[1])*2*s:s,r&&(t.ticks||t.niceTicks)){var f=(t.ticks||t.niceTicks).map(function(l){var h=a?a.indexOf(l):l;return{coordinate:i(h)+s,value:l,offset:s}});return f.filter(function(l){return!Nn(l.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(l,h){return{coordinate:i(l)+s,value:l,index:h,offset:s}}):i.ticks&&!n?i.ticks(t.tickCount).map(function(l){return{coordinate:i(l)+s,value:l,offset:s}}):i.domain().map(function(l,h){return{coordinate:i(l)+s,value:a?a[l]:l,index:h,offset:s}})},as=new WeakMap,ei=function(t,r){if(typeof r!="function")return t;as.has(t)||as.set(t,new WeakMap);var n=as.get(t);if(n.has(r))return n.get(r);var i=function(){t.apply(void 0,arguments),r.apply(void 0,arguments)};return n.set(r,i),i},W0=function(t,r,n){var i=t.scale,a=t.type,o=t.layout,u=t.axisType;if(i==="auto")return o==="radial"&&u==="radiusAxis"?{scale:cn(),realScaleType:"band"}:o==="radial"&&u==="angleAxis"?{scale:Pi(),realScaleType:"linear"}:a==="category"&&r&&(r.indexOf("LineChart")>=0||r.indexOf("AreaChart")>=0||r.indexOf("ComposedChart")>=0&&!n)?{scale:Zr(),realScaleType:"point"}:a==="category"?{scale:cn(),realScaleType:"band"}:{scale:Pi(),realScaleType:"linear"};if(zt(i)){var c="scale".concat(ca(i));return{scale:(Cy[c]||Zr)(),realScaleType:Cy[c]?c:"point"}}return Y(i)?{scale:i}:{scale:Zr(),realScaleType:"point"}},Ky=1e-4,z0=function(t){var r=t.domain();if(!(!r||r.length<=2)){var n=r.length,i=t.range(),a=Math.min(i[0],i[1])-Ky,o=Math.max(i[0],i[1])+Ky,u=t(r[0]),c=t(r[n-1]);(uo||co)&&t.domain([r[0],r[n-1]])}},ZE=function(t,r){if(!t)return null;for(var n=0,i=t.length;ni)&&(a[1]=i),a[0]>i&&(a[0]=i),a[1]=0?(t[u][n][0]=a,t[u][n][1]=a+c,a=t[u][n][1]):(t[u][n][0]=o,t[u][n][1]=o+c,o=t[u][n][1])}},ej=function(t){var r=t.length;if(!(r<=0))for(var n=0,i=t[0].length;n=0?(t[o][n][0]=a,t[o][n][1]=a+u,a=t[o][n][1]):(t[o][n][0]=0,t[o][n][1]=0)}},tj={sign:QE,expand:LO,none:lr,silhouette:FO,wiggle:UO,positive:ej},rj=function(t,r,n){var i=r.map(function(u){return u.props.dataKey}),a=tj[n],o=BO().keys(i).value(function(u,c){return+Je(u,c,0)}).order(Hs).offset(a);return o(t)},nj=function(t,r,n,i,a,o){if(!t)return null;var u=o?r.reverse():r,c={},s=u.reduce(function(l,h){var d,g=(d=h.type)!==null&&d!==void 0&&d.defaultProps?he(he({},h.type.defaultProps),h.props):h.props,v=g.stackId,p=g.hide;if(p)return l;var m=g[n],x=l[m]||{hasStack:!1,stackGroups:{}};if(xe(v)){var w=x.stackGroups[v]||{numericAxisId:n,cateAxisId:i,items:[]};w.items.push(h),x.hasStack=!0,x.stackGroups[v]=w}else x.stackGroups[ua("_stackId_")]={numericAxisId:n,cateAxisId:i,items:[h]};return he(he({},l),{},sr({},m,x))},c),f={};return Object.keys(s).reduce(function(l,h){var d=s[h];if(d.hasStack){var g={};d.stackGroups=Object.keys(d.stackGroups).reduce(function(v,p){var m=d.stackGroups[p];return he(he({},v),{},sr({},p,{numericAxisId:n,cateAxisId:i,items:m.items,stackedData:rj(t,m.items,a)}))},g)}return he(he({},l),{},sr({},h,d))},f)},H0=function(t,r){var n=r.realScaleType,i=r.type,a=r.tickCount,o=r.originalDomain,u=r.allowDecimals,c=n||r.scale;if(c!=="auto"&&c!=="linear")return null;if(a&&i==="number"&&o&&(o[0]==="auto"||o[1]==="auto")){var s=t.domain();if(!s.length)return null;var f=gE(s,a,u);return t.domain([Oa(f),wa(f)]),{niceTicks:f}}if(a&&i==="number"){var l=t.domain(),h=mE(l,a,u);return{niceTicks:h}}return null};function kD(e){var t=e.axis,r=e.ticks,n=e.bandSize,i=e.entry,a=e.index,o=e.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!Z(i[t.dataKey])){var u=oi(r,"value",i[t.dataKey]);if(u)return u.coordinate+n/2}return r[a]?r[a].coordinate+n/2:null}var c=Je(i,Z(o)?t.dataKey:o);return Z(c)?null:t.scale(c)}var Xy=function(t){var r=t.axis,n=t.ticks,i=t.offset,a=t.bandSize,o=t.entry,u=t.index;if(r.type==="category")return n[u]?n[u].coordinate+i:null;var c=Je(o,r.dataKey,r.domain[u]);return Z(c)?null:r.scale(c)-a/2+i},ij=function(t){var r=t.numericAxis,n=r.scale.domain();if(r.type==="number"){var i=Math.min(n[0],n[1]),a=Math.max(n[0],n[1]);return i<=0&&a>=0?0:a<0?a:i}return n[0]},aj=function(t,r){var n,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?he(he({},t.type.defaultProps),t.props):t.props,a=i.stackId;if(xe(a)){var o=r[a];if(o){var u=o.items.indexOf(t);return u>=0?o.stackedData[u]:null}}return null},oj=function(t){return t.reduce(function(r,n){return[Oa(n.concat([r[0]]).filter(q)),wa(n.concat([r[1]]).filter(q))]},[1/0,-1/0])},G0=function(t,r,n){return Object.keys(t).reduce(function(i,a){var o=t[a],u=o.stackedData,c=u.reduce(function(s,f){var l=oj(f.slice(r,n+1));return[Math.min(s[0],l[0]),Math.max(s[1],l[1])]},[1/0,-1/0]);return[Math.min(c[0],i[0]),Math.max(c[1],i[1])]},[1/0,-1/0]).map(function(i){return i===1/0||i===-1/0?0:i})},Vy=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Yy=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,yl=function(t,r,n){if(Y(t))return t(r,n);if(!Array.isArray(t))return r;var i=[];if(q(t[0]))i[0]=n?t[0]:Math.min(t[0],r[0]);else if(Vy.test(t[0])){var a=+Vy.exec(t[0])[1];i[0]=r[0]-a}else Y(t[0])?i[0]=t[0](r[0]):i[0]=r[0];if(q(t[1]))i[1]=n?t[1]:Math.max(t[1],r[1]);else if(Yy.test(t[1])){var o=+Yy.exec(t[1])[1];i[1]=r[1]+o}else Y(t[1])?i[1]=t[1](r[1]):i[1]=r[1];return i},Ii=function(t,r,n){if(t&&t.scale&&t.scale.bandwidth){var i=t.scale.bandwidth();if(!n||i>0)return i}if(t&&r&&r.length>=2){for(var a=mf(r,function(l){return l.coordinate}),o=1/0,u=1,c=a.length;ue.length)&&(t=e.length);for(var r=0,n=new Array(t);r2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(n.left||0)-(n.right||0)),Math.abs(r-(n.top||0)-(n.bottom||0)))/2},DD=function(t,r,n,i,a){var o=t.width,u=t.height,c=t.startAngle,s=t.endAngle,f=Ye(t.cx,o,o/2),l=Ye(t.cy,u,u/2),h=vj(o,u,n),d=Ye(t.innerRadius,h,0),g=Ye(t.outerRadius,h,h*.8),v=Object.keys(r);return v.reduce(function(p,m){var x=r[m],w=x.domain,O=x.reversed,y;if(Z(x.range))i==="angleAxis"?y=[c,s]:i==="radiusAxis"&&(y=[d,g]),O&&(y=[y[1],y[0]]);else{y=x.range;var b=y,_=sj(b,2);c=_[0],s=_[1]}var S=W0(x,a),P=S.realScaleType,M=S.scale;M.domain(w).range(y),z0(M);var A=H0(M,ut(ut({},x),{},{realScaleType:P})),E=ut(ut(ut({},x),A),{},{range:y,radius:g,realScaleType:P,scale:M,cx:f,cy:l,innerRadius:d,outerRadius:g,startAngle:c,endAngle:s});return ut(ut({},p),{},X0({},m,E))},{})},yj=function(t,r){var n=t.x,i=t.y,a=r.x,o=r.y;return Math.sqrt(Math.pow(n-a,2)+Math.pow(i-o,2))},gj=function(t,r){var n=t.x,i=t.y,a=r.cx,o=r.cy,u=yj({x:n,y:i},{x:a,y:o});if(u<=0)return{radius:u};var c=(n-a)/u,s=Math.acos(c);return i>o&&(s=2*Math.PI-s),{radius:u,angle:dj(s),angleInRadian:s}},mj=function(t){var r=t.startAngle,n=t.endAngle,i=Math.floor(r/360),a=Math.floor(n/360),o=Math.min(i,a);return{startAngle:r-o*360,endAngle:n-o*360}},bj=function(t,r){var n=r.startAngle,i=r.endAngle,a=Math.floor(n/360),o=Math.floor(i/360),u=Math.min(a,o);return t+u*360},eg=function(t,r){var n=t.x,i=t.y,a=gj({x:n,y:i},r),o=a.radius,u=a.angle,c=r.innerRadius,s=r.outerRadius;if(os)return!1;if(o===0)return!0;var f=mj(r),l=f.startAngle,h=f.endAngle,d=u,g;if(l<=h){for(;d>h;)d-=360;for(;d=l&&d<=h}else{for(;d>l;)d-=360;for(;d=h&&d<=l}return g?ut(ut({},r),{},{radius:o,angle:bj(d,r)}):null},ND=function(t){return!N.isValidElement(t)&&!Y(t)&&typeof t!="boolean"?t.className:""};function mn(e){"@babel/helpers - typeof";return mn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},mn(e)}var xj=["offset"];function wj(e){return Aj(e)||Sj(e)||_j(e)||Oj()}function Oj(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function _j(e,t){if(e){if(typeof e=="string")return gl(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return gl(e,t)}}function Sj(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Aj(e){if(Array.isArray(e))return gl(e)}function gl(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function Tj(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function tg(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function be(e){for(var t=1;t=0?1:-1,w,O;i==="insideStart"?(w=d+x*o,O=v):i==="insideEnd"?(w=g-x*o,O=!v):i==="end"&&(w=g+x*o,O=v),O=m<=0?O:!O;var y=Pe(s,f,p,w),b=Pe(s,f,p,w+(O?1:-1)*359),_="M".concat(y.x,",").concat(y.y,` + A`).concat(p,",").concat(p,",0,1,").concat(O?0:1,`, + `).concat(b.x,",").concat(b.y),S=Z(t.id)?ua("recharts-radial-line-"):t.id;return T.createElement("text",bn({},n,{dominantBaseline:"central",className:te("recharts-radial-bar-label",u)}),T.createElement("defs",null,T.createElement("path",{id:S,d:_})),T.createElement("textPath",{xlinkHref:"#".concat(S)},r))},Rj=function(t){var r=t.viewBox,n=t.offset,i=t.position,a=r,o=a.cx,u=a.cy,c=a.innerRadius,s=a.outerRadius,f=a.startAngle,l=a.endAngle,h=(f+l)/2;if(i==="outside"){var d=Pe(o,u,s+n,h),g=d.x,v=d.y;return{x:g,y:v,textAnchor:g>=o?"start":"end",verticalAnchor:"middle"}}if(i==="center")return{x:o,y:u,textAnchor:"middle",verticalAnchor:"middle"};if(i==="centerTop")return{x:o,y:u,textAnchor:"middle",verticalAnchor:"start"};if(i==="centerBottom")return{x:o,y:u,textAnchor:"middle",verticalAnchor:"end"};var p=(c+s)/2,m=Pe(o,u,p,h),x=m.x,w=m.y;return{x,y:w,textAnchor:"middle",verticalAnchor:"middle"}},kj=function(t){var r=t.viewBox,n=t.parentViewBox,i=t.offset,a=t.position,o=r,u=o.x,c=o.y,s=o.width,f=o.height,l=f>=0?1:-1,h=l*i,d=l>0?"end":"start",g=l>0?"start":"end",v=s>=0?1:-1,p=v*i,m=v>0?"end":"start",x=v>0?"start":"end";if(a==="top"){var w={x:u+s/2,y:c-l*i,textAnchor:"middle",verticalAnchor:d};return be(be({},w),n?{height:Math.max(c-n.y,0),width:s}:{})}if(a==="bottom"){var O={x:u+s/2,y:c+f+h,textAnchor:"middle",verticalAnchor:g};return be(be({},O),n?{height:Math.max(n.y+n.height-(c+f),0),width:s}:{})}if(a==="left"){var y={x:u-p,y:c+f/2,textAnchor:m,verticalAnchor:"middle"};return be(be({},y),n?{width:Math.max(y.x-n.x,0),height:f}:{})}if(a==="right"){var b={x:u+s+p,y:c+f/2,textAnchor:x,verticalAnchor:"middle"};return be(be({},b),n?{width:Math.max(n.x+n.width-b.x,0),height:f}:{})}var _=n?{width:s,height:f}:{};return a==="insideLeft"?be({x:u+p,y:c+f/2,textAnchor:x,verticalAnchor:"middle"},_):a==="insideRight"?be({x:u+s-p,y:c+f/2,textAnchor:m,verticalAnchor:"middle"},_):a==="insideTop"?be({x:u+s/2,y:c+h,textAnchor:"middle",verticalAnchor:g},_):a==="insideBottom"?be({x:u+s/2,y:c+f-h,textAnchor:"middle",verticalAnchor:d},_):a==="insideTopLeft"?be({x:u+p,y:c+h,textAnchor:x,verticalAnchor:g},_):a==="insideTopRight"?be({x:u+s-p,y:c+h,textAnchor:m,verticalAnchor:g},_):a==="insideBottomLeft"?be({x:u+p,y:c+f-h,textAnchor:x,verticalAnchor:d},_):a==="insideBottomRight"?be({x:u+s-p,y:c+f-h,textAnchor:m,verticalAnchor:d},_):$r(a)&&(q(a.x)||Nt(a.x))&&(q(a.y)||Nt(a.y))?be({x:u+Ye(a.x,s),y:c+Ye(a.y,f),textAnchor:"end",verticalAnchor:"end"},_):be({x:u+s/2,y:c+f/2,textAnchor:"middle",verticalAnchor:"middle"},_)},Dj=function(t){return"cx"in t&&q(t.cx)};function Ee(e){var t=e.offset,r=t===void 0?5:t,n=Pj(e,xj),i=be({offset:r},n),a=i.viewBox,o=i.position,u=i.value,c=i.children,s=i.content,f=i.className,l=f===void 0?"":f,h=i.textBreakAll;if(!a||Z(u)&&Z(c)&&!N.isValidElement(s)&&!Y(s))return null;if(N.isValidElement(s))return N.cloneElement(s,i);var d;if(Y(s)){if(d=N.createElement(s,i),N.isValidElement(d))return d}else d=Cj(i);var g=Dj(a),v=ee(i,!0);if(g&&(o==="insideStart"||o==="insideEnd"||o==="end"))return Ij(i,d,v);var p=g?Rj(i):kj(i);return T.createElement(bi,bn({className:te("recharts-label",l)},v,p,{breakAll:h}),d)}Ee.displayName="Label";var V0=function(t){var r=t.cx,n=t.cy,i=t.angle,a=t.startAngle,o=t.endAngle,u=t.r,c=t.radius,s=t.innerRadius,f=t.outerRadius,l=t.x,h=t.y,d=t.top,g=t.left,v=t.width,p=t.height,m=t.clockWise,x=t.labelViewBox;if(x)return x;if(q(v)&&q(p)){if(q(l)&&q(h))return{x:l,y:h,width:v,height:p};if(q(d)&&q(g))return{x:d,y:g,width:v,height:p}}return q(l)&&q(h)?{x:l,y:h,width:0,height:0}:q(r)&&q(n)?{cx:r,cy:n,startAngle:a||i||0,endAngle:o||i||0,innerRadius:s||0,outerRadius:f||c||u||0,clockWise:m}:t.viewBox?t.viewBox:{}},Nj=function(t,r){return t?t===!0?T.createElement(Ee,{key:"label-implicit",viewBox:r}):xe(t)?T.createElement(Ee,{key:"label-implicit",viewBox:r,value:t}):N.isValidElement(t)?t.type===Ee?N.cloneElement(t,{key:"label-implicit",viewBox:r}):T.createElement(Ee,{key:"label-implicit",content:t,viewBox:r}):Y(t)?T.createElement(Ee,{key:"label-implicit",content:t,viewBox:r}):$r(t)?T.createElement(Ee,bn({viewBox:r},t,{key:"label-implicit"})):null:null},qj=function(t,r){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&n&&!t.label)return null;var i=t.children,a=V0(t),o=Ze(i,Ee).map(function(c,s){return N.cloneElement(c,{viewBox:r||a,key:"label-".concat(s)})});if(!n)return o;var u=Nj(t.label,r||a);return[u].concat(wj(o))};Ee.parseViewBox=V0;Ee.renderCallByParent=qj;var os,rg;function Bj(){if(rg)return os;rg=1;function e(t){var r=t==null?0:t.length;return r?t[r-1]:void 0}return os=e,os}var Lj=Bj();const Fj=ue(Lj);function xn(e){"@babel/helpers - typeof";return xn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xn(e)}var Uj=["valueAccessor"],Wj=["data","dataKey","clockWise","id","textBreakAll"];function zj(e){return Xj(e)||Kj(e)||Gj(e)||Hj()}function Hj(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Gj(e,t){if(e){if(typeof e=="string")return ml(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return ml(e,t)}}function Kj(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function Xj(e){if(Array.isArray(e))return ml(e)}function ml(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function Jj(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var Qj=function(t){return Array.isArray(t.value)?Fj(t.value):t.value};function Wt(e){var t=e.valueAccessor,r=t===void 0?Qj:t,n=ag(e,Uj),i=n.data,a=n.dataKey,o=n.clockWise,u=n.id,c=n.textBreakAll,s=ag(n,Wj);return!i||!i.length?null:T.createElement(_e,{className:"recharts-label-list"},i.map(function(f,l){var h=Z(a)?r(f,l):Je(f&&f.payload,a),d=Z(u)?{}:{id:"".concat(u,"-").concat(l)};return T.createElement(Ee,ki({},ee(f,!0),s,d,{parentViewBox:f.parentViewBox,value:h,textBreakAll:c,viewBox:Ee.parseViewBox(Z(o)?f:ig(ig({},f),{},{clockWise:o})),key:"label-".concat(l),index:l}))}))}Wt.displayName="LabelList";function eM(e,t){return e?e===!0?T.createElement(Wt,{key:"labelList-implicit",data:t}):T.isValidElement(e)||Y(e)?T.createElement(Wt,{key:"labelList-implicit",data:t,content:e}):$r(e)?T.createElement(Wt,ki({data:t},e,{key:"labelList-implicit"})):null:null}function tM(e,t){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!e||!e.children&&r&&!e.label)return null;var n=e.children,i=Ze(n,Wt).map(function(o,u){return N.cloneElement(o,{data:t,key:"labelList-".concat(u)})});if(!r)return i;var a=eM(e.label,t);return[a].concat(zj(i))}Wt.renderCallByParent=tM;function wn(e){"@babel/helpers - typeof";return wn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},wn(e)}function bl(){return bl=Object.assign?Object.assign.bind():function(e){for(var t=1;t180),",").concat(+(o>s),`, + `).concat(l.x,",").concat(l.y,` + `);if(i>0){var d=Pe(r,n,i,o),g=Pe(r,n,i,s);h+="L ".concat(g.x,",").concat(g.y,` + A `).concat(i,",").concat(i,`,0, + `).concat(+(Math.abs(c)>180),",").concat(+(o<=s),`, + `).concat(d.x,",").concat(d.y," Z")}else h+="L ".concat(r,",").concat(n," Z");return h},oM=function(t){var r=t.cx,n=t.cy,i=t.innerRadius,a=t.outerRadius,o=t.cornerRadius,u=t.forceCornerRadius,c=t.cornerIsExternal,s=t.startAngle,f=t.endAngle,l=Ve(f-s),h=ti({cx:r,cy:n,radius:a,angle:s,sign:l,cornerRadius:o,cornerIsExternal:c}),d=h.circleTangency,g=h.lineTangency,v=h.theta,p=ti({cx:r,cy:n,radius:a,angle:f,sign:-l,cornerRadius:o,cornerIsExternal:c}),m=p.circleTangency,x=p.lineTangency,w=p.theta,O=c?Math.abs(s-f):Math.abs(s-f)-v-w;if(O<0)return u?"M ".concat(g.x,",").concat(g.y,` + a`).concat(o,",").concat(o,",0,0,1,").concat(o*2,`,0 + a`).concat(o,",").concat(o,",0,0,1,").concat(-o*2,`,0 + `):Y0({cx:r,cy:n,innerRadius:i,outerRadius:a,startAngle:s,endAngle:f});var y="M ".concat(g.x,",").concat(g.y,` + A`).concat(o,",").concat(o,",0,0,").concat(+(l<0),",").concat(d.x,",").concat(d.y,` + A`).concat(a,",").concat(a,",0,").concat(+(O>180),",").concat(+(l<0),",").concat(m.x,",").concat(m.y,` + A`).concat(o,",").concat(o,",0,0,").concat(+(l<0),",").concat(x.x,",").concat(x.y,` + `);if(i>0){var b=ti({cx:r,cy:n,radius:i,angle:s,sign:l,isExternal:!0,cornerRadius:o,cornerIsExternal:c}),_=b.circleTangency,S=b.lineTangency,P=b.theta,M=ti({cx:r,cy:n,radius:i,angle:f,sign:-l,isExternal:!0,cornerRadius:o,cornerIsExternal:c}),A=M.circleTangency,E=M.lineTangency,j=M.theta,I=c?Math.abs(s-f):Math.abs(s-f)-P-j;if(I<0&&o===0)return"".concat(y,"L").concat(r,",").concat(n,"Z");y+="L".concat(E.x,",").concat(E.y,` + A`).concat(o,",").concat(o,",0,0,").concat(+(l<0),",").concat(A.x,",").concat(A.y,` + A`).concat(i,",").concat(i,",0,").concat(+(I>180),",").concat(+(l>0),",").concat(_.x,",").concat(_.y,` + A`).concat(o,",").concat(o,",0,0,").concat(+(l<0),",").concat(S.x,",").concat(S.y,"Z")}else y+="L".concat(r,",").concat(n,"Z");return y},uM={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},Z0=function(t){var r=ug(ug({},uM),t),n=r.cx,i=r.cy,a=r.innerRadius,o=r.outerRadius,u=r.cornerRadius,c=r.forceCornerRadius,s=r.cornerIsExternal,f=r.startAngle,l=r.endAngle,h=r.className;if(o0&&Math.abs(f-l)<360?p=oM({cx:n,cy:i,innerRadius:a,outerRadius:o,cornerRadius:Math.min(v,g/2),forceCornerRadius:c,cornerIsExternal:s,startAngle:f,endAngle:l}):p=Y0({cx:n,cy:i,innerRadius:a,outerRadius:o,startAngle:f,endAngle:l}),T.createElement("path",bl({},ee(r,!0),{className:d,d:p,role:"img"}))};function On(e){"@babel/helpers - typeof";return On=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},On(e)}function xl(){return xl=Object.assign?Object.assign.bind():function(e){for(var t=1;tbM.call(e,t));function Zt(e,t){return e===t||!e&&!t&&e!==e&&t!==t}const OM="__v",_M="__o",SM="_owner",{getOwnPropertyDescriptor:yg,keys:gg}=Object;function AM(e,t){return e.byteLength===t.byteLength&&Di(new Uint8Array(e),new Uint8Array(t))}function PM(e,t,r){let n=e.length;if(t.length!==n)return!1;for(;n-- >0;)if(!r.equals(e[n],t[n],n,n,e,t,r))return!1;return!0}function TM(e,t){return e.byteLength===t.byteLength&&Di(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function EM(e,t){return Zt(e.getTime(),t.getTime())}function jM(e,t){return e.name===t.name&&e.message===t.message&&e.cause===t.cause&&e.stack===t.stack}function MM(e,t){return e===t}function mg(e,t,r){const n=e.size;if(n!==t.size)return!1;if(!n)return!0;const i=new Array(n),a=e.entries();let o,u,c=0;for(;(o=a.next())&&!o.done;){const s=t.entries();let f=!1,l=0;for(;(u=s.next())&&!u.done;){if(i[l]){l++;continue}const h=o.value,d=u.value;if(r.equals(h[0],d[0],c,l,e,t,r)&&r.equals(h[1],d[1],h[0],d[0],e,t,r)){f=i[l]=!0;break}l++}if(!f)return!1;c++}return!0}const CM=Zt;function $M(e,t,r){const n=gg(e);let i=n.length;if(gg(t).length!==i)return!1;for(;i-- >0;)if(!J0(e,t,r,n[i]))return!1;return!0}function Hr(e,t,r){const n=vg(e);let i=n.length;if(vg(t).length!==i)return!1;let a,o,u;for(;i-- >0;)if(a=n[i],!J0(e,t,r,a)||(o=yg(e,a),u=yg(t,a),(o||u)&&(!o||!u||o.configurable!==u.configurable||o.enumerable!==u.enumerable||o.writable!==u.writable)))return!1;return!0}function IM(e,t){return Zt(e.valueOf(),t.valueOf())}function RM(e,t){return e.source===t.source&&e.flags===t.flags}function bg(e,t,r){const n=e.size;if(n!==t.size)return!1;if(!n)return!0;const i=new Array(n),a=e.values();let o,u;for(;(o=a.next())&&!o.done;){const c=t.values();let s=!1,f=0;for(;(u=c.next())&&!u.done;){if(!i[f]&&r.equals(o.value,u.value,o.value,u.value,e,t,r)){s=i[f]=!0;break}f++}if(!s)return!1}return!0}function Di(e,t){let r=e.byteLength;if(t.byteLength!==r||e.byteOffset!==t.byteOffset)return!1;for(;r-- >0;)if(e[r]!==t[r])return!1;return!0}function kM(e,t){return e.hostname===t.hostname&&e.pathname===t.pathname&&e.protocol===t.protocol&&e.port===t.port&&e.hash===t.hash&&e.username===t.username&&e.password===t.password}function J0(e,t,r,n){return(n===SM||n===_M||n===OM)&&(e.$$typeof||t.$$typeof)?!0:wM(t,n)&&r.equals(e[n],t[n],n,n,e,t,r)}const DM="[object ArrayBuffer]",NM="[object Arguments]",qM="[object Boolean]",BM="[object DataView]",LM="[object Date]",FM="[object Error]",UM="[object Map]",WM="[object Number]",zM="[object Object]",HM="[object RegExp]",GM="[object Set]",KM="[object String]",XM={"[object Int8Array]":!0,"[object Uint8Array]":!0,"[object Uint8ClampedArray]":!0,"[object Int16Array]":!0,"[object Uint16Array]":!0,"[object Int32Array]":!0,"[object Uint32Array]":!0,"[object Float16Array]":!0,"[object Float32Array]":!0,"[object Float64Array]":!0,"[object BigInt64Array]":!0,"[object BigUint64Array]":!0},VM="[object URL]",YM=Object.prototype.toString;function ZM({areArrayBuffersEqual:e,areArraysEqual:t,areDataViewsEqual:r,areDatesEqual:n,areErrorsEqual:i,areFunctionsEqual:a,areMapsEqual:o,areNumbersEqual:u,areObjectsEqual:c,arePrimitiveWrappersEqual:s,areRegExpsEqual:f,areSetsEqual:l,areTypedArraysEqual:h,areUrlsEqual:d,unknownTagComparators:g}){return function(p,m,x){if(p===m)return!0;if(p==null||m==null)return!1;const w=typeof p;if(w!==typeof m)return!1;if(w!=="object")return w==="number"?u(p,m,x):w==="function"?a(p,m,x):!1;const O=p.constructor;if(O!==m.constructor)return!1;if(O===Object)return c(p,m,x);if(Array.isArray(p))return t(p,m,x);if(O===Date)return n(p,m,x);if(O===RegExp)return f(p,m,x);if(O===Map)return o(p,m,x);if(O===Set)return l(p,m,x);const y=YM.call(p);if(y===LM)return n(p,m,x);if(y===HM)return f(p,m,x);if(y===UM)return o(p,m,x);if(y===GM)return l(p,m,x);if(y===zM)return typeof p.then!="function"&&typeof m.then!="function"&&c(p,m,x);if(y===VM)return d(p,m,x);if(y===FM)return i(p,m,x);if(y===NM)return c(p,m,x);if(XM[y])return h(p,m,x);if(y===DM)return e(p,m,x);if(y===BM)return r(p,m,x);if(y===qM||y===WM||y===KM)return s(p,m,x);if(g){let b=g[y];if(!b){const _=xM(p);_&&(b=g[_])}if(b)return b(p,m,x)}return!1}}function JM({circular:e,createCustomConfig:t,strict:r}){let n={areArrayBuffersEqual:AM,areArraysEqual:r?Hr:PM,areDataViewsEqual:TM,areDatesEqual:EM,areErrorsEqual:jM,areFunctionsEqual:MM,areMapsEqual:r?ls(mg,Hr):mg,areNumbersEqual:CM,areObjectsEqual:r?Hr:$M,arePrimitiveWrappersEqual:IM,areRegExpsEqual:RM,areSetsEqual:r?ls(bg,Hr):bg,areTypedArraysEqual:r?ls(Di,Hr):Di,areUrlsEqual:kM,unknownTagComparators:void 0};if(t&&(n=Object.assign({},n,t(n))),e){const i=ni(n.areArraysEqual),a=ni(n.areMapsEqual),o=ni(n.areObjectsEqual),u=ni(n.areSetsEqual);n=Object.assign({},n,{areArraysEqual:i,areMapsEqual:a,areObjectsEqual:o,areSetsEqual:u})}return n}function QM(e){return function(t,r,n,i,a,o,u){return e(t,r,u)}}function eC({circular:e,comparator:t,createState:r,equals:n,strict:i}){if(r)return function(u,c){const{cache:s=e?new WeakMap:void 0,meta:f}=r();return t(u,c,{cache:s,equals:n,meta:f,strict:i})};if(e)return function(u,c){return t(u,c,{cache:new WeakMap,equals:n,meta:void 0,strict:i})};const a={cache:void 0,equals:n,meta:void 0,strict:i};return function(u,c){return t(u,c,a)}}const tC=Mt();Mt({strict:!0});Mt({circular:!0});Mt({circular:!0,strict:!0});Mt({createInternalComparator:()=>Zt});Mt({strict:!0,createInternalComparator:()=>Zt});Mt({circular:!0,createInternalComparator:()=>Zt});Mt({circular:!0,createInternalComparator:()=>Zt,strict:!0});function Mt(e={}){const{circular:t=!1,createInternalComparator:r,createState:n,strict:i=!1}=e,a=JM(e),o=ZM(a),u=r?r(o):QM(o);return eC({circular:t,comparator:o,createState:n,equals:u,strict:i})}function rC(e){typeof requestAnimationFrame<"u"&&requestAnimationFrame(e)}function xg(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,r=-1,n=function i(a){r<0&&(r=a),a-r>t?(e(a),r=-1):rC(i)};requestAnimationFrame(n)}function wl(e){"@babel/helpers - typeof";return wl=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},wl(e)}function nC(e){return uC(e)||oC(e)||aC(e)||iC()}function iC(){throw new TypeError(`Invalid attempt to destructure non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function aC(e,t){if(e){if(typeof e=="string")return wg(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return wg(e,t)}}function wg(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);re.length)&&(t=e.length);for(var r=0,n=new Array(t);r1?1:m<0?0:m},v=function(m){for(var x=m>1?1:m,w=x,O=0;O<8;++O){var y=l(w)-x,b=d(w);if(Math.abs(y-x)0&&arguments[0]!==void 0?arguments[0]:{},r=t.stiff,n=r===void 0?100:r,i=t.damping,a=i===void 0?8:i,o=t.dt,u=o===void 0?17:o,c=function(f,l,h){var d=-(f-l)*n,g=h*a,v=h+(d-g)*u/1e3,p=h*u/1e3+f;return Math.abs(p-l)e.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function qC(e,t){if(e==null)return{};var r={},n=Object.keys(e),i,a;for(a=0;a=0)&&(r[i]=e[i]);return r}function fs(e){return UC(e)||FC(e)||LC(e)||BC()}function BC(){throw new TypeError(`Invalid attempt to spread non-iterable instance. +In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function LC(e,t){if(e){if(typeof e=="string")return Pl(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);if(r==="Object"&&e.constructor&&(r=e.constructor.name),r==="Map"||r==="Set")return Array.from(e);if(r==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return Pl(e,t)}}function FC(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function UC(e){if(Array.isArray(e))return Pl(e)}function Pl(e,t){(t==null||t>e.length)&&(t=e.length);for(var r=0,n=new Array(t);r"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function Bi(e){return Bi=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(r){return r.__proto__||Object.getPrototypeOf(r)},Bi(e)}var At=(function(e){KC(r,e);var t=XC(r);function r(n,i){var a;WC(this,r),a=t.call(this,n,i);var o=a.props,u=o.isActive,c=o.attributeName,s=o.from,f=o.to,l=o.steps,h=o.children,d=o.duration;if(a.handleStyleChange=a.handleStyleChange.bind(jl(a)),a.changeStyle=a.changeStyle.bind(jl(a)),!u||d<=0)return a.state={style:{}},typeof h=="function"&&(a.state={style:f}),El(a);if(l&&l.length)a.state={style:l[0].style};else if(s){if(typeof h=="function")return a.state={style:s},El(a);a.state={style:c?Vr({},c,s):s}}else a.state={style:{}};return a}return HC(r,[{key:"componentDidMount",value:function(){var i=this.props,a=i.isActive,o=i.canBegin;this.mounted=!0,!(!a||!o)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(i){var a=this.props,o=a.isActive,u=a.canBegin,c=a.attributeName,s=a.shouldReAnimate,f=a.to,l=a.from,h=this.state.style;if(u){if(!o){var d={style:c?Vr({},c,f):f};this.state&&h&&(c&&h[c]!==f||!c&&h!==f)&&this.setState(d);return}if(!(tC(i.to,f)&&i.canBegin&&i.isActive)){var g=!i.canBegin||!i.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var v=g||s?l:i.to;if(this.state&&h){var p={style:c?Vr({},c,v):v};(c&&h[c]!==v||!c&&h!==v)&&this.setState(p)}this.runAnimation(Ge(Ge({},this.props),{},{from:v,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var i=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),i&&i()}},{key:"handleStyleChange",value:function(i){this.changeStyle(i)}},{key:"changeStyle",value:function(i){this.mounted&&this.setState({style:i})}},{key:"runJSAnimation",value:function(i){var a=this,o=i.from,u=i.to,c=i.duration,s=i.easing,f=i.begin,l=i.onAnimationEnd,h=i.onAnimationStart,d=kC(o,u,SC(s),c,this.changeStyle),g=function(){a.stopJSAnimation=d()};this.manager.start([h,f,g,c,l])}},{key:"runStepAnimation",value:function(i){var a=this,o=i.steps,u=i.begin,c=i.onAnimationStart,s=o[0],f=s.style,l=s.duration,h=l===void 0?0:l,d=function(v,p,m){if(m===0)return v;var x=p.duration,w=p.easing,O=w===void 0?"ease":w,y=p.style,b=p.properties,_=p.onAnimationEnd,S=m>0?o[m-1]:p,P=b||Object.keys(y);if(typeof O=="function"||O==="spring")return[].concat(fs(v),[a.runJSAnimation.bind(a,{from:S.style,to:y,duration:x,easing:O}),x]);var M=Sg(P,x,O),A=Ge(Ge(Ge({},S.style),y),{},{transition:M});return[].concat(fs(v),[A,x,_]).filter(hC)};return this.manager.start([c].concat(fs(o.reduce(d,[f,Math.max(h,u)])),[i.onAnimationEnd]))}},{key:"runAnimation",value:function(i){this.manager||(this.manager=cC());var a=i.begin,o=i.duration,u=i.attributeName,c=i.to,s=i.easing,f=i.onAnimationStart,l=i.onAnimationEnd,h=i.steps,d=i.children,g=this.manager;if(this.unSubscribe=g.subscribe(this.handleStyleChange),typeof s=="function"||typeof d=="function"||s==="spring"){this.runJSAnimation(i);return}if(h.length>1){this.runStepAnimation(i);return}var v=u?Vr({},u,c):c,p=Sg(Object.keys(v),o,s);g.start([f,a,Ge(Ge({},v),{},{transition:p}),o,l])}},{key:"render",value:function(){var i=this.props,a=i.children;i.begin;var o=i.duration;i.attributeName,i.easing;var u=i.isActive;i.steps,i.from,i.to,i.canBegin,i.onAnimationEnd,i.shouldReAnimate,i.onAnimationReStart;var c=NC(i,DC),s=N.Children.count(a),f=this.state.style;if(typeof a=="function")return a(f);if(!u||s===0||o<=0)return a;var l=function(d){var g=d.props,v=g.style,p=v===void 0?{}:v,m=g.className,x=N.cloneElement(d,Ge(Ge({},c),{},{style:Ge(Ge({},p),f),className:m}));return x};return s===1?l(N.Children.only(a)):T.createElement("div",null,N.Children.map(a,function(h){return l(h)}))}}]),r})(N.PureComponent);At.displayName="Animate";At.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};At.propTypes={from:ne.oneOfType([ne.object,ne.string]),to:ne.oneOfType([ne.object,ne.string]),attributeName:ne.string,duration:ne.number,begin:ne.number,easing:ne.oneOfType([ne.string,ne.func]),steps:ne.arrayOf(ne.shape({duration:ne.number.isRequired,style:ne.object.isRequired,easing:ne.oneOfType([ne.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),ne.func]),properties:ne.arrayOf("string"),onAnimationEnd:ne.func})),children:ne.oneOfType([ne.node,ne.func]),isActive:ne.bool,canBegin:ne.bool,onAnimationEnd:ne.func,shouldReAnimate:ne.bool,onAnimationStart:ne.func,onAnimationReStart:ne.func};function An(e){"@babel/helpers - typeof";return An=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},An(e)}function Li(){return Li=Object.assign?Object.assign.bind():function(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0?1:-1,c=n>=0?1:-1,s=i>=0&&n>=0||i<0&&n<0?1:0,f;if(o>0&&a instanceof Array){for(var l=[0,0,0,0],h=0,d=4;ho?o:a[h];f="M".concat(t,",").concat(r+u*l[0]),l[0]>0&&(f+="A ".concat(l[0],",").concat(l[0],",0,0,").concat(s,",").concat(t+c*l[0],",").concat(r)),f+="L ".concat(t+n-c*l[1],",").concat(r),l[1]>0&&(f+="A ".concat(l[1],",").concat(l[1],",0,0,").concat(s,`, + `).concat(t+n,",").concat(r+u*l[1])),f+="L ".concat(t+n,",").concat(r+i-u*l[2]),l[2]>0&&(f+="A ".concat(l[2],",").concat(l[2],",0,0,").concat(s,`, + `).concat(t+n-c*l[2],",").concat(r+i)),f+="L ".concat(t+c*l[3],",").concat(r+i),l[3]>0&&(f+="A ".concat(l[3],",").concat(l[3],",0,0,").concat(s,`, + `).concat(t,",").concat(r+i-u*l[3])),f+="Z"}else if(o>0&&a===+a&&a>0){var g=Math.min(o,a);f="M ".concat(t,",").concat(r+u*g,` + A `).concat(g,",").concat(g,",0,0,").concat(s,",").concat(t+c*g,",").concat(r,` + L `).concat(t+n-c*g,",").concat(r,` + A `).concat(g,",").concat(g,",0,0,").concat(s,",").concat(t+n,",").concat(r+u*g,` + L `).concat(t+n,",").concat(r+i-u*g,` + A `).concat(g,",").concat(g,",0,0,").concat(s,",").concat(t+n-c*g,",").concat(r+i,` + L `).concat(t+c*g,",").concat(r+i,` + A `).concat(g,",").concat(g,",0,0,").concat(s,",").concat(t,",").concat(r+i-u*g," Z")}else f="M ".concat(t,",").concat(r," h ").concat(n," v ").concat(i," h ").concat(-n," Z");return f},i$=function(t,r){if(!t||!r)return!1;var n=t.x,i=t.y,a=r.x,o=r.y,u=r.width,c=r.height;if(Math.abs(u)>0&&Math.abs(c)>0){var s=Math.min(a,a+u),f=Math.max(a,a+u),l=Math.min(o,o+c),h=Math.max(o,o+c);return n>=s&&n<=f&&i>=l&&i<=h}return!1},a$={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},Gf=function(t){var r=$g($g({},a$),t),n=N.useRef(),i=N.useState(-1),a=YC(i,2),o=a[0],u=a[1];N.useEffect(function(){if(n.current&&n.current.getTotalLength)try{var O=n.current.getTotalLength();O&&u(O)}catch{}},[]);var c=r.x,s=r.y,f=r.width,l=r.height,h=r.radius,d=r.className,g=r.animationEasing,v=r.animationDuration,p=r.animationBegin,m=r.isAnimationActive,x=r.isUpdateAnimationActive;if(c!==+c||s!==+s||f!==+f||l!==+l||f===0||l===0)return null;var w=te("recharts-rectangle",d);return x?T.createElement(At,{canBegin:o>0,from:{width:f,height:l,x:c,y:s},to:{width:f,height:l,x:c,y:s},duration:v,animationEasing:g,isActive:x},function(O){var y=O.width,b=O.height,_=O.x,S=O.y;return T.createElement(At,{canBegin:o>0,from:"0px ".concat(o===-1?1:o,"px"),to:"".concat(o,"px 0px"),attributeName:"strokeDasharray",begin:p,duration:v,isActive:m,easing:g},T.createElement("path",Li({},ee(r,!0),{className:w,d:Ig(_,S,y,b,h),ref:n})))}):T.createElement("path",Li({},ee(r,!0),{className:w,d:Ig(c,s,f,l,h)}))};function Ml(){return Ml=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function h$(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var p$=function(t,r,n,i,a,o){return"M".concat(t,",").concat(a,"v").concat(i,"M").concat(o,",").concat(r,"h").concat(n)},d$=function(t){var r=t.x,n=r===void 0?0:r,i=t.y,a=i===void 0?0:i,o=t.top,u=o===void 0?0:o,c=t.left,s=c===void 0?0:c,f=t.width,l=f===void 0?0:f,h=t.height,d=h===void 0?0:h,g=t.className,v=f$(t,o$),p=u$({x:n,y:a,top:u,left:s,width:l,height:d},v);return!q(n)||!q(a)||!q(l)||!q(d)||!q(u)||!q(s)?null:T.createElement("path",Cl({},ee(p,!0),{className:te("recharts-cross",g),d:p$(n,a,l,d,u,s)}))},hs,kg;function v$(){if(kg)return hs;kg=1;var e=xb(),t=e(Object.getPrototypeOf,Object);return hs=t,hs}var ps,Dg;function y$(){if(Dg)return ps;Dg=1;var e=gt(),t=v$(),r=mt(),n="[object Object]",i=Function.prototype,a=Object.prototype,o=i.toString,u=a.hasOwnProperty,c=o.call(Object);function s(f){if(!r(f)||e(f)!=n)return!1;var l=t(f);if(l===null)return!0;var h=u.call(l,"constructor")&&l.constructor;return typeof h=="function"&&h instanceof h&&o.call(h)==c}return ps=s,ps}var g$=y$();const m$=ue(g$);var ds,Ng;function b$(){if(Ng)return ds;Ng=1;var e=gt(),t=mt(),r="[object Boolean]";function n(i){return i===!0||i===!1||t(i)&&e(i)==r}return ds=n,ds}var x$=b$();const w$=ue(x$);function Tn(e){"@babel/helpers - typeof";return Tn=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Tn(e)}function Fi(){return Fi=Object.assign?Object.assign.bind():function(e){for(var t=1;te.length)&&(t=e.length);for(var r=0,n=new Array(t);r0,from:{upperWidth:0,lowerWidth:0,height:h,x:c,y:s},to:{upperWidth:f,lowerWidth:l,height:h,x:c,y:s},duration:v,animationEasing:g,isActive:m},function(w){var O=w.upperWidth,y=w.lowerWidth,b=w.height,_=w.x,S=w.y;return T.createElement(At,{canBegin:o>0,from:"0px ".concat(o===-1?1:o,"px"),to:"".concat(o,"px 0px"),attributeName:"strokeDasharray",begin:p,duration:v,easing:g},T.createElement("path",Fi({},ee(r,!0),{className:x,d:Fg(_,S,O,y,b),ref:n})))}):T.createElement("g",null,T.createElement("path",Fi({},ee(r,!0),{className:x,d:Fg(c,s,f,l,h)})))},$$=["option","shapeType","propTransformer","activeClassName","isActive"];function En(e){"@babel/helpers - typeof";return En=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},En(e)}function I$(e,t){if(e==null)return{};var r=R$(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function R$(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Ug(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Ui(e){for(var t=1;t0&&n.handleDrag(i.changedTouches[0])}),De(n,"handleDragEnd",function(){n.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var i=n.props,a=i.endIndex,o=i.onDragEnd,u=i.startIndex;o?.({endIndex:a,startIndex:u})}),n.detachDragEndListener()}),De(n,"handleLeaveWrapper",function(){(n.state.isTravellerMoving||n.state.isSlideMoving)&&(n.leaveTimer=window.setTimeout(n.handleDragEnd,n.props.leaveTimeOut))}),De(n,"handleEnterSlideOrTraveller",function(){n.setState({isTextActive:!0})}),De(n,"handleLeaveSlideOrTraveller",function(){n.setState({isTextActive:!1})}),De(n,"handleSlideDragStart",function(i){var a=Jg(i)?i.changedTouches[0]:i;n.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:a.pageX}),n.attachDragEndListener()}),n.travellerDragStartHandlers={startX:n.handleTravellerDragStart.bind(n,"startX"),endX:n.handleTravellerDragStart.bind(n,"endX")},n.state={},n}return cI(t,e),iI(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(n){var i=n.startX,a=n.endX,o=this.state.scaleValues,u=this.props,c=u.gap,s=u.data,f=s.length-1,l=Math.min(i,a),h=Math.max(i,a),d=t.getIndexInRange(o,l),g=t.getIndexInRange(o,h);return{startIndex:d-d%c,endIndex:g===f?f:g-g%c}}},{key:"getTextOfTick",value:function(n){var i=this.props,a=i.data,o=i.tickFormatter,u=i.dataKey,c=Je(a[n],u,n);return Y(o)?o(c,n):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(n){var i=this.state,a=i.slideMoveStartX,o=i.startX,u=i.endX,c=this.props,s=c.x,f=c.width,l=c.travellerWidth,h=c.startIndex,d=c.endIndex,g=c.onChange,v=n.pageX-a;v>0?v=Math.min(v,s+f-l-u,s+f-l-o):v<0&&(v=Math.max(v,s-o,s-u));var p=this.getIndex({startX:o+v,endX:u+v});(p.startIndex!==h||p.endIndex!==d)&&g&&g(p),this.setState({startX:o+v,endX:u+v,slideMoveStartX:n.pageX})}},{key:"handleTravellerDragStart",value:function(n,i){var a=Jg(i)?i.changedTouches[0]:i;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:n,brushMoveStartX:a.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(n){var i=this.state,a=i.brushMoveStartX,o=i.movingTravellerId,u=i.endX,c=i.startX,s=this.state[o],f=this.props,l=f.x,h=f.width,d=f.travellerWidth,g=f.onChange,v=f.gap,p=f.data,m={startX:this.state.startX,endX:this.state.endX},x=n.pageX-a;x>0?x=Math.min(x,l+h-d-s):x<0&&(x=Math.max(x,l-s)),m[o]=s+x;var w=this.getIndex(m),O=w.startIndex,y=w.endIndex,b=function(){var S=p.length-1;return o==="startX"&&(u>c?O%v===0:y%v===0)||uc?y%v===0:O%v===0)||u>c&&y===S};this.setState(De(De({},o,s+x),"brushMoveStartX",n.pageX),function(){g&&b()&&g(w)})}},{key:"handleTravellerMoveKeyboard",value:function(n,i){var a=this,o=this.state,u=o.scaleValues,c=o.startX,s=o.endX,f=this.state[i],l=u.indexOf(f);if(l!==-1){var h=l+n;if(!(h===-1||h>=u.length)){var d=u[h];i==="startX"&&d>=s||i==="endX"&&d<=c||this.setState(De({},i,d),function(){a.props.onChange(a.getIndex({startX:a.state.startX,endX:a.state.endX}))})}}}},{key:"renderBackground",value:function(){var n=this.props,i=n.x,a=n.y,o=n.width,u=n.height,c=n.fill,s=n.stroke;return T.createElement("rect",{stroke:s,fill:c,x:i,y:a,width:o,height:u})}},{key:"renderPanorama",value:function(){var n=this.props,i=n.x,a=n.y,o=n.width,u=n.height,c=n.data,s=n.children,f=n.padding,l=N.Children.only(s);return l?T.cloneElement(l,{x:i,y:a,width:o,height:u,margin:f,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(n,i){var a,o,u=this,c=this.props,s=c.y,f=c.travellerWidth,l=c.height,h=c.traveller,d=c.ariaLabel,g=c.data,v=c.startIndex,p=c.endIndex,m=Math.max(n,this.props.x),x=bs(bs({},ee(this.props,!1)),{},{x:m,y:s,width:f,height:l}),w=d||"Min value: ".concat((a=g[v])===null||a===void 0?void 0:a.name,", Max value: ").concat((o=g[p])===null||o===void 0?void 0:o.name);return T.createElement(_e,{tabIndex:0,role:"slider","aria-label":w,"aria-valuenow":n,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[i],onTouchStart:this.travellerDragStartHandlers[i],onKeyDown:function(y){["ArrowLeft","ArrowRight"].includes(y.key)&&(y.preventDefault(),y.stopPropagation(),u.handleTravellerMoveKeyboard(y.key==="ArrowRight"?1:-1,i))},onFocus:function(){u.setState({isTravellerFocused:!0})},onBlur:function(){u.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(h,x))}},{key:"renderSlide",value:function(n,i){var a=this.props,o=a.y,u=a.height,c=a.stroke,s=a.travellerWidth,f=Math.min(n,i)+s,l=Math.max(Math.abs(i-n)-s,0);return T.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:f,y:o,width:l,height:u})}},{key:"renderText",value:function(){var n=this.props,i=n.startIndex,a=n.endIndex,o=n.y,u=n.height,c=n.travellerWidth,s=n.stroke,f=this.state,l=f.startX,h=f.endX,d=5,g={pointerEvents:"none",fill:s};return T.createElement(_e,{className:"recharts-brush-texts"},T.createElement(bi,zi({textAnchor:"end",verticalAnchor:"middle",x:Math.min(l,h)-d,y:o+u/2},g),this.getTextOfTick(i)),T.createElement(bi,zi({textAnchor:"start",verticalAnchor:"middle",x:Math.max(l,h)+c+d,y:o+u/2},g),this.getTextOfTick(a)))}},{key:"render",value:function(){var n=this.props,i=n.data,a=n.className,o=n.children,u=n.x,c=n.y,s=n.width,f=n.height,l=n.alwaysShowText,h=this.state,d=h.startX,g=h.endX,v=h.isTextActive,p=h.isSlideMoving,m=h.isTravellerMoving,x=h.isTravellerFocused;if(!i||!i.length||!q(u)||!q(c)||!q(s)||!q(f)||s<=0||f<=0)return null;var w=te("recharts-brush",a),O=T.Children.count(o)===1,y=rI("userSelect","none");return T.createElement(_e,{className:w,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:y},this.renderBackground(),O&&this.renderPanorama(),this.renderSlide(d,g),this.renderTravellerLayer(d,"startX"),this.renderTravellerLayer(g,"endX"),(v||p||m||x||l)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(n){var i=n.x,a=n.y,o=n.width,u=n.height,c=n.stroke,s=Math.floor(a+u/2)-1;return T.createElement(T.Fragment,null,T.createElement("rect",{x:i,y:a,width:o,height:u,fill:c,stroke:"none"}),T.createElement("line",{x1:i+1,y1:s,x2:i+o-1,y2:s,fill:"none",stroke:"#fff"}),T.createElement("line",{x1:i+1,y1:s+2,x2:i+o-1,y2:s+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(n,i){var a;return T.isValidElement(n)?a=T.cloneElement(n,i):Y(n)?a=n(i):a=t.renderDefaultTraveller(i),a}},{key:"getDerivedStateFromProps",value:function(n,i){var a=n.data,o=n.width,u=n.x,c=n.travellerWidth,s=n.updateId,f=n.startIndex,l=n.endIndex;if(a!==i.prevData||s!==i.prevUpdateId)return bs({prevData:a,prevTravellerWidth:c,prevUpdateId:s,prevX:u,prevWidth:o},a&&a.length?lI({data:a,width:o,x:u,travellerWidth:c,startIndex:f,endIndex:l}):{scale:null,scaleValues:null});if(i.scale&&(o!==i.prevWidth||u!==i.prevX||c!==i.prevTravellerWidth)){i.scale.range([u,u+o-c]);var h=i.scale.domain().map(function(d){return i.scale(d)});return{prevData:a,prevTravellerWidth:c,prevUpdateId:s,prevX:u,prevWidth:o,startX:i.scale(n.startIndex),endX:i.scale(n.endIndex),scaleValues:h}}return null}},{key:"getIndexInRange",value:function(n,i){for(var a=n.length,o=0,u=a-1;u-o>1;){var c=Math.floor((o+u)/2);n[c]>i?u=c:o=c}return i>=n[u]?u:o}}])})(N.PureComponent);De(wr,"displayName","Brush");De(wr,"defaultProps",{height:40,travellerWidth:5,gap:1,fill:"#fff",stroke:"#666",padding:{top:1,right:1,bottom:1,left:1},leaveTimeOut:1e3,alwaysShowText:!1});var xs,Qg;function fI(){if(Qg)return xs;Qg=1;var e=gf();function t(r,n){var i;return e(r,function(a,o,u){return i=n(a,o,u),!i}),!!i}return xs=t,xs}var ws,em;function hI(){if(em)return ws;em=1;var e=pb(),t=Tt(),r=fI(),n=Re(),i=da();function a(o,u,c){var s=n(o)?e:r;return c&&i(o,u,c)&&(u=void 0),s(o,t(u,3))}return ws=a,ws}var pI=hI();const dI=ue(pI);var rt=function(t,r){var n=t.alwaysShow,i=t.ifOverflow;return n&&(i="extendDomain"),i===r},Os,tm;function vI(){if(tm)return Os;tm=1;var e=Cb();function t(r,n,i){n=="__proto__"&&e?e(r,n,{configurable:!0,enumerable:!0,value:i,writable:!0}):r[n]=i}return Os=t,Os}var _s,rm;function yI(){if(rm)return _s;rm=1;var e=vI(),t=jb(),r=Tt();function n(i,a){var o={};return a=r(a,3),t(i,function(u,c,s){e(o,c,a(u,c,s))}),o}return _s=n,_s}var gI=yI();const mI=ue(gI);var Ss,nm;function bI(){if(nm)return Ss;nm=1;function e(t,r){for(var n=-1,i=t==null?0:t.length;++n=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function EI(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function jI(e,t){var r=e.x,n=e.y,i=TI(e,_I),a="".concat(r),o=parseInt(a,10),u="".concat(n),c=parseInt(u,10),s="".concat(t.height||i.height),f=parseInt(s,10),l="".concat(t.width||i.width),h=parseInt(l,10);return Gr(Gr(Gr(Gr(Gr({},t),i),o?{x:o}:{}),c?{y:c}:{}),{},{height:f,width:h,name:t.name,radius:t.radius})}function um(e){return T.createElement(F$,Il({shapeType:"rectangle",propTransformer:jI,activeClassName:"recharts-active-bar"},e))}var MI=function(t){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(n,i){if(typeof t=="number")return t;var a=q(n)||kw(n);return a?t(n,i):(a||Gt(),r)}},CI=["value","background"],fx;function Or(e){"@babel/helpers - typeof";return Or=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Or(e)}function $I(e,t){if(e==null)return{};var r=II(e,t),n,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function II(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function Gi(){return Gi=Object.assign?Object.assign.bind():function(e){for(var t=1;t0&&Math.abs($)0&&Math.abs(I)0&&(j=Math.min((ce||0)-(I[pe-1]||0),j))}),Number.isFinite(j)){var $=j/E,R=v.layout==="vertical"?n.height:n.width;if(v.padding==="gap"&&(_=$*R/2),v.padding==="no-gap"){var D=Ye(t.barCategoryGap,$*R),B=$*R/2;_=B-D-(B-D)/R*D}}}i==="xAxis"?S=[n.left+(w.left||0)+(_||0),n.left+n.width-(w.right||0)-(_||0)]:i==="yAxis"?S=c==="horizontal"?[n.top+n.height-(w.bottom||0),n.top+(w.top||0)]:[n.top+(w.top||0)+(_||0),n.top+n.height-(w.bottom||0)-(_||0)]:S=v.range,y&&(S=[S[1],S[0]]);var L=W0(v,a,h),z=L.scale,G=L.realScaleType;z.domain(m).range(S),z0(z);var U=H0(z,Ke(Ke({},v),{},{realScaleType:G}));i==="xAxis"?(A=p==="top"&&!O||p==="bottom"&&O,P=n.left,M=l[b]-A*v.height):i==="yAxis"&&(A=p==="left"&&!O||p==="right"&&O,P=l[b]-A*v.width,M=n.top);var K=Ke(Ke(Ke({},v),U),{},{realScaleType:G,x:P,y:M,scale:z,width:i==="xAxis"?n.width:v.width,height:i==="yAxis"?n.height:v.height});return K.bandSize=Ii(K,U),!v.hide&&i==="xAxis"?l[b]+=(A?-1:1)*K.height:v.hide||(l[b]+=(A?-1:1)*K.width),Ke(Ke({},d),{},Ea({},g,K))},{})},vx=function(t,r){var n=t.x,i=t.y,a=r.x,o=r.y;return{x:Math.min(n,a),y:Math.min(i,o),width:Math.abs(a-n),height:Math.abs(o-i)}},zI=function(t){var r=t.x1,n=t.y1,i=t.x2,a=t.y2;return vx({x:r,y:n},{x:i,y:a})},yx=(function(){function e(t){FI(this,e),this.scale=t}return UI(e,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(r){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},i=n.bandAware,a=n.position;if(r!==void 0){if(a)switch(a){case"start":return this.scale(r);case"middle":{var o=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+o}case"end":{var u=this.bandwidth?this.bandwidth():0;return this.scale(r)+u}default:return this.scale(r)}if(i){var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(r)+c}return this.scale(r)}}},{key:"isInRange",value:function(r){var n=this.range(),i=n[0],a=n[n.length-1];return i<=a?r>=i&&r<=a:r>=a&&r<=i}}],[{key:"create",value:function(r){return new e(r)}}])})();Ea(yx,"EPS",1e-4);var Kf=function(t){var r=Object.keys(t).reduce(function(n,i){return Ke(Ke({},n),{},Ea({},i,yx.create(t[i])))},{});return Ke(Ke({},r),{},{apply:function(i){var a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},o=a.bandAware,u=a.position;return mI(i,function(c,s){return r[s].apply(c,{bandAware:o,position:u})})},isInRange:function(i){return lx(i,function(a,o){return r[o].isInRange(a)})}})};function HI(e){return(e%180+180)%180}var GI=function(t){var r=t.width,n=t.height,i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,a=HI(i),o=a*Math.PI/180,u=Math.atan(n/r),c=o>u&&o-1?c[s?a[f]:f]:void 0}}return Ts=n,Ts}var Es,pm;function XI(){if(pm)return Es;pm=1;var e=ox();function t(r){var n=e(r),i=n%1;return n===n?i?n-i:n:0}return Es=t,Es}var js,dm;function VI(){if(dm)return js;dm=1;var e=Sb(),t=Tt(),r=XI(),n=Math.max;function i(a,o,u){var c=a==null?0:a.length;if(!c)return-1;var s=u==null?0:r(u);return s<0&&(s=n(c+s,0)),e(a,t(o,3),s)}return js=i,js}var Ms,vm;function YI(){if(vm)return Ms;vm=1;var e=KI(),t=VI(),r=e(t);return Ms=r,Ms}var ZI=YI();const JI=ue(ZI);var QI=Lm();const eR=ue(QI);var tR=eR(function(e){return{x:e.left,y:e.top,width:e.width,height:e.height}},function(e){return["l",e.left,"t",e.top,"w",e.width,"h",e.height].join("")}),Xf=N.createContext(void 0),Vf=N.createContext(void 0),gx=N.createContext(void 0),mx=N.createContext({}),bx=N.createContext(void 0),xx=N.createContext(0),wx=N.createContext(0),ym=function(t){var r=t.state,n=r.xAxisMap,i=r.yAxisMap,a=r.offset,o=t.clipPathId,u=t.children,c=t.width,s=t.height,f=tR(a);return T.createElement(Xf.Provider,{value:n},T.createElement(Vf.Provider,{value:i},T.createElement(mx.Provider,{value:a},T.createElement(gx.Provider,{value:f},T.createElement(bx.Provider,{value:o},T.createElement(xx.Provider,{value:s},T.createElement(wx.Provider,{value:c},u)))))))},rR=function(){return N.useContext(bx)},Ox=function(t){var r=N.useContext(Xf);r==null&&Gt();var n=r[t];return n==null&&Gt(),n},nR=function(){var t=N.useContext(Xf);return Ot(t)},iR=function(){var t=N.useContext(Vf),r=JI(t,function(n){return lx(n.domain,Number.isFinite)});return r||Ot(t)},_x=function(t){var r=N.useContext(Vf);r==null&&Gt();var n=r[t];return n==null&&Gt(),n},aR=function(){var t=N.useContext(gx);return t},oR=function(){return N.useContext(mx)},Yf=function(){return N.useContext(wx)},Zf=function(){return N.useContext(xx)};function _r(e){"@babel/helpers - typeof";return _r=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},_r(e)}function uR(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function cR(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=new Array(t);re*i)return!1;var a=r();return e*(t-e*a/2-n)>=0&&e*(t+e*a/2-i)<=0}function WR(e,t){return Mx(e,t+1)}function zR(e,t,r,n,i){for(var a=(n||[]).slice(),o=t.start,u=t.end,c=0,s=1,f=o,l=function(){var g=n?.[c];if(g===void 0)return{v:Mx(n,s)};var v=c,p,m=function(){return p===void 0&&(p=r(g,v)),p},x=g.coordinate,w=c===0||Zi(e,x,m,f,u);w||(c=0,f=o,s+=1),w&&(f=x+e*(m()/2+i),c+=s)},h;s<=a.length;)if(h=l(),h)return h.v;return[]}function In(e){"@babel/helpers - typeof";return In=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},In(e)}function Sm(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function Te(e){for(var t=1;t0?d.coordinate-p*e:d.coordinate})}else a[h]=d=Te(Te({},d),{},{tickCoord:d.coordinate});var m=Zi(e,d.tickCoord,v,u,c);m&&(c=d.tickCoord-e*(v()/2+i),a[h]=Te(Te({},d),{},{isShow:!0}))},f=o-1;f>=0;f--)s(f);return a}function VR(e,t,r,n,i,a){var o=(n||[]).slice(),u=o.length,c=t.start,s=t.end;if(a){var f=n[u-1],l=r(f,u-1),h=e*(f.coordinate+e*l/2-s);o[u-1]=f=Te(Te({},f),{},{tickCoord:h>0?f.coordinate-h*e:f.coordinate});var d=Zi(e,f.tickCoord,function(){return l},c,s);d&&(s=f.tickCoord-e*(l/2+i),o[u-1]=Te(Te({},f),{},{isShow:!0}))}for(var g=a?u-1:u,v=function(x){var w=o[x],O,y=function(){return O===void 0&&(O=r(w,x)),O};if(x===0){var b=e*(w.coordinate-e*y()/2-c);o[x]=w=Te(Te({},w),{},{tickCoord:b<0?w.coordinate-b*e:w.coordinate})}else o[x]=w=Te(Te({},w),{},{tickCoord:w.coordinate});var _=Zi(e,w.tickCoord,y,c,s);_&&(c=w.tickCoord+e*(y()/2+i),o[x]=Te(Te({},w),{},{isShow:!0}))},p=0;p=2?Ve(i[1].coordinate-i[0].coordinate):1,m=UR(a,p,d);return c==="equidistantPreserveStart"?zR(p,m,v,i,o):(c==="preserveStart"||c==="preserveStartEnd"?h=VR(p,m,v,i,o,c==="preserveStartEnd"):h=XR(p,m,v,i,o),h.filter(function(x){return x.isShow}))}var YR=["viewBox"],ZR=["viewBox"],JR=["ticks"];function Pr(e){"@babel/helpers - typeof";return Pr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Pr(e)}function ir(){return ir=Object.assign?Object.assign.bind():function(e){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function QR(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function ek(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Pm(e,t){for(var r=0;r0?c(this.props):c(d)),o<=0||u<=0||!g||!g.length?null:T.createElement(_e,{className:te("recharts-cartesian-axis",s),ref:function(p){n.layerReference=p}},a&&this.renderAxisLine(),this.renderTicks(g,this.state.fontSize,this.state.letterSpacing),Ee.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(n,i,a){var o,u=te(i.className,"recharts-cartesian-axis-tick-value");return T.isValidElement(n)?o=T.cloneElement(n,me(me({},i),{},{className:u})):Y(n)?o=n(me(me({},i),{},{className:u})):o=T.createElement(bi,ir({},i,{className:"recharts-cartesian-axis-tick-value"}),a),o}}])})(N.Component);th(Nr,"displayName","CartesianAxis");th(Nr,"defaultProps",{x:0,y:0,width:0,height:0,viewBox:{x:0,y:0,width:0,height:0},orientation:"bottom",ticks:[],stroke:"#666",tickLine:!0,axisLine:!0,tick:!0,mirror:!1,minTickGap:5,tickSize:6,tickMargin:2,interval:"preserveEnd"});var uk=["x1","y1","x2","y2","key"],ck=["offset"];function Kt(e){"@babel/helpers - typeof";return Kt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Kt(e)}function Tm(e,t){var r=Object.keys(e);if(Object.getOwnPropertySymbols){var n=Object.getOwnPropertySymbols(e);t&&(n=n.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),r.push.apply(r,n)}return r}function je(e){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function hk(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}var pk=function(t){var r=t.fill;if(!r||r==="none")return null;var n=t.fillOpacity,i=t.x,a=t.y,o=t.width,u=t.height,c=t.ry;return T.createElement("rect",{x:i,y:a,ry:c,width:o,height:u,stroke:"none",fill:r,fillOpacity:n,className:"recharts-cartesian-grid-bg"})};function Ix(e,t){var r;if(T.isValidElement(e))r=T.cloneElement(e,t);else if(Y(e))r=e(t);else{var n=t.x1,i=t.y1,a=t.x2,o=t.y2,u=t.key,c=Em(t,uk),s=ee(c,!1);s.offset;var f=Em(s,ck);r=T.createElement("line",Lt({},f,{x1:n,y1:i,x2:a,y2:o,fill:"none",key:u}))}return r}function dk(e){var t=e.x,r=e.width,n=e.horizontal,i=n===void 0?!0:n,a=e.horizontalPoints;if(!i||!a||!a.length)return null;var o=a.map(function(u,c){var s=je(je({},e),{},{x1:t,y1:u,x2:t+r,y2:u,key:"line-".concat(c),index:c});return Ix(i,s)});return T.createElement("g",{className:"recharts-cartesian-grid-horizontal"},o)}function vk(e){var t=e.y,r=e.height,n=e.vertical,i=n===void 0?!0:n,a=e.verticalPoints;if(!i||!a||!a.length)return null;var o=a.map(function(u,c){var s=je(je({},e),{},{x1:u,y1:t,x2:u,y2:t+r,key:"line-".concat(c),index:c});return Ix(i,s)});return T.createElement("g",{className:"recharts-cartesian-grid-vertical"},o)}function yk(e){var t=e.horizontalFill,r=e.fillOpacity,n=e.x,i=e.y,a=e.width,o=e.height,u=e.horizontalPoints,c=e.horizontal,s=c===void 0?!0:c;if(!s||!t||!t.length)return null;var f=u.map(function(h){return Math.round(h+i-i)}).sort(function(h,d){return h-d});i!==f[0]&&f.unshift(0);var l=f.map(function(h,d){var g=!f[d+1],v=g?i+o-h:f[d+1]-h;if(v<=0)return null;var p=d%t.length;return T.createElement("rect",{key:"react-".concat(d),y:h,x:n,height:v,width:a,stroke:"none",fill:t[p],fillOpacity:r,className:"recharts-cartesian-grid-bg"})});return T.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},l)}function gk(e){var t=e.vertical,r=t===void 0?!0:t,n=e.verticalFill,i=e.fillOpacity,a=e.x,o=e.y,u=e.width,c=e.height,s=e.verticalPoints;if(!r||!n||!n.length)return null;var f=s.map(function(h){return Math.round(h+a-a)}).sort(function(h,d){return h-d});a!==f[0]&&f.unshift(0);var l=f.map(function(h,d){var g=!f[d+1],v=g?a+u-h:f[d+1]-h;if(v<=0)return null;var p=d%n.length;return T.createElement("rect",{key:"react-".concat(d),x:h,y:o,width:v,height:c,stroke:"none",fill:n[p],fillOpacity:i,className:"recharts-cartesian-grid-bg"})});return T.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},l)}var mk=function(t,r){var n=t.xAxis,i=t.width,a=t.height,o=t.offset;return U0(eh(je(je(je({},Nr.defaultProps),n),{},{ticks:lt(n,!0),viewBox:{x:0,y:0,width:i,height:a}})),o.left,o.left+o.width,r)},bk=function(t,r){var n=t.yAxis,i=t.width,a=t.height,o=t.offset;return U0(eh(je(je(je({},Nr.defaultProps),n),{},{ticks:lt(n,!0),viewBox:{x:0,y:0,width:i,height:a}})),o.top,o.top+o.height,r)},rr={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function xk(e){var t,r,n,i,a,o,u=Yf(),c=Zf(),s=oR(),f=je(je({},e),{},{stroke:(t=e.stroke)!==null&&t!==void 0?t:rr.stroke,fill:(r=e.fill)!==null&&r!==void 0?r:rr.fill,horizontal:(n=e.horizontal)!==null&&n!==void 0?n:rr.horizontal,horizontalFill:(i=e.horizontalFill)!==null&&i!==void 0?i:rr.horizontalFill,vertical:(a=e.vertical)!==null&&a!==void 0?a:rr.vertical,verticalFill:(o=e.verticalFill)!==null&&o!==void 0?o:rr.verticalFill,x:q(e.x)?e.x:s.left,y:q(e.y)?e.y:s.top,width:q(e.width)?e.width:s.width,height:q(e.height)?e.height:s.height}),l=f.x,h=f.y,d=f.width,g=f.height,v=f.syncWithTicks,p=f.horizontalValues,m=f.verticalValues,x=nR(),w=iR();if(!q(d)||d<=0||!q(g)||g<=0||!q(l)||l!==+l||!q(h)||h!==+h)return null;var O=f.verticalCoordinatesGenerator||mk,y=f.horizontalCoordinatesGenerator||bk,b=f.horizontalPoints,_=f.verticalPoints;if((!b||!b.length)&&Y(y)){var S=p&&p.length,P=y({yAxis:w?je(je({},w),{},{ticks:S?p:w.ticks}):void 0,width:u,height:c,offset:s},S?!0:v);ht(Array.isArray(P),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(Kt(P),"]")),Array.isArray(P)&&(b=P)}if((!_||!_.length)&&Y(O)){var M=m&&m.length,A=O({xAxis:x?je(je({},x),{},{ticks:M?m:x.ticks}):void 0,width:u,height:c,offset:s},M?!0:v);ht(Array.isArray(A),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(Kt(A),"]")),Array.isArray(A)&&(_=A)}return T.createElement("g",{className:"recharts-cartesian-grid"},T.createElement(pk,{fill:f.fill,fillOpacity:f.fillOpacity,x:f.x,y:f.y,width:f.width,height:f.height,ry:f.ry}),T.createElement(dk,Lt({},f,{offset:s,horizontalPoints:b,xAxis:x,yAxis:w})),T.createElement(vk,Lt({},f,{offset:s,verticalPoints:_,xAxis:x,yAxis:w})),T.createElement(yk,Lt({},f,{horizontalPoints:b})),T.createElement(gk,Lt({},f,{verticalPoints:_})))}xk.displayName="CartesianGrid";function Tr(e){"@babel/helpers - typeof";return Tr=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Tr(e)}function wk(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Ok(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=new Array(t);r=0)&&Object.prototype.propertyIsEnumerable.call(e,n)&&(r[n]=e[n])}return r}function sD(e,t){if(e==null)return{};var r={};for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){if(t.indexOf(n)>=0)continue;r[n]=e[n]}return r}function lD(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function fD(e,t){for(var r=0;re.length)&&(t=e.length);for(var r=0,n=new Array(t);r0?o:t&&t.length&&q(i)&&q(a)?t.slice(i,a+1):[]};function Xx(e){return e==="number"?[0,"auto"]:void 0}var Yl=function(t,r,n,i){var a=t.graphicalItems,o=t.tooltipAxis,u=Ia(r,t);return n<0||!a||!a.length||n>=u.length?null:a.reduce(function(c,s){var f,l=(f=s.props.data)!==null&&f!==void 0?f:r;l&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=n&&(l=l.slice(t.dataStartIndex,t.dataEndIndex+1));var h;if(o.dataKey&&!o.allowDuplicatedCategory){var d=l===void 0?u:l;h=oi(d,o.dataKey,i)}else h=l&&l[n]||u[n];return h?[].concat(Mr(c),[K0(s,h)]):c},[])},km=function(t,r,n,i){var a=i||{x:t.chartX,y:t.chartY},o=_D(a,n),u=t.orderedTooltipTicks,c=t.tooltipAxis,s=t.tooltipTicks,f=HE(o,u,s,c);if(f>=0&&s){var l=s[f]&&s[f].value,h=Yl(t,r,f,l),d=SD(n,u,f,a);return{activeTooltipIndex:f,activeLabel:l,activePayload:h,activeCoordinate:d}}return null},AD=function(t,r){var n=r.axes,i=r.graphicalItems,a=r.axisType,o=r.axisIdKey,u=r.stackGroups,c=r.dataStartIndex,s=r.dataEndIndex,f=t.layout,l=t.children,h=t.stackOffset,d=F0(f,a);return n.reduce(function(g,v){var p,m=v.type.defaultProps!==void 0?C(C({},v.type.defaultProps),v.props):v.props,x=m.type,w=m.dataKey,O=m.allowDataOverflow,y=m.allowDuplicatedCategory,b=m.scale,_=m.ticks,S=m.includeHidden,P=m[o];if(g[P])return g;var M=Ia(t.data,{graphicalItems:i.filter(function(U){var K,ce=o in U.props?U.props[o]:(K=U.type.defaultProps)===null||K===void 0?void 0:K[o];return ce===P}),dataStartIndex:c,dataEndIndex:s}),A=M.length,E,j,I;Zk(m.domain,O,x)&&(E=yl(m.domain,null,O),d&&(x==="number"||b!=="auto")&&(I=Jr(M,w,"category")));var $=Xx(x);if(!E||E.length===0){var R,D=(R=m.domain)!==null&&R!==void 0?R:$;if(w){if(E=Jr(M,w,x),x==="category"&&d){var B=Nw(E);y&&B?(j=E,E=Wi(0,A)):y||(E=Zy(D,E,v).reduce(function(U,K){return U.indexOf(K)>=0?U:[].concat(Mr(U),[K])},[]))}else if(x==="category")y?E=E.filter(function(U){return U!==""&&!Z(U)}):E=Zy(D,E,v).reduce(function(U,K){return U.indexOf(K)>=0||K===""||Z(K)?U:[].concat(Mr(U),[K])},[]);else if(x==="number"){var L=YE(M,i.filter(function(U){var K,ce,pe=o in U.props?U.props[o]:(K=U.type.defaultProps)===null||K===void 0?void 0:K[o],ke="hide"in U.props?U.props.hide:(ce=U.type.defaultProps)===null||ce===void 0?void 0:ce.hide;return pe===P&&(S||!ke)}),w,a,f);L&&(E=L)}d&&(x==="number"||b!=="auto")&&(I=Jr(M,w,"category"))}else d?E=Wi(0,A):u&&u[P]&&u[P].hasStack&&x==="number"?E=h==="expand"?[0,1]:G0(u[P].stackGroups,c,s):E=L0(M,i.filter(function(U){var K=o in U.props?U.props[o]:U.type.defaultProps[o],ce="hide"in U.props?U.props.hide:U.type.defaultProps.hide;return K===P&&(S||!ce)}),x,f,!0);if(x==="number")E=Kl(l,E,P,a,_),D&&(E=yl(D,E,O));else if(x==="category"&&D){var z=D,G=E.every(function(U){return z.indexOf(U)>=0});G&&(E=z)}}return C(C({},g),{},H({},P,C(C({},m),{},{axisType:a,domain:E,categoricalDomain:I,duplicateDomain:j,originalDomain:(p=m.domain)!==null&&p!==void 0?p:$,isCategorical:d,layout:f})))},{})},PD=function(t,r){var n=r.graphicalItems,i=r.Axis,a=r.axisType,o=r.axisIdKey,u=r.stackGroups,c=r.dataStartIndex,s=r.dataEndIndex,f=t.layout,l=t.children,h=Ia(t.data,{graphicalItems:n,dataStartIndex:c,dataEndIndex:s}),d=h.length,g=F0(f,a),v=-1;return n.reduce(function(p,m){var x=m.type.defaultProps!==void 0?C(C({},m.type.defaultProps),m.props):m.props,w=x[o],O=Xx("number");if(!p[w]){v++;var y;return g?y=Wi(0,d):u&&u[w]&&u[w].hasStack?(y=G0(u[w].stackGroups,c,s),y=Kl(l,y,w,a)):(y=yl(O,L0(h,n.filter(function(b){var _,S,P=o in b.props?b.props[o]:(_=b.type.defaultProps)===null||_===void 0?void 0:_[o],M="hide"in b.props?b.props.hide:(S=b.type.defaultProps)===null||S===void 0?void 0:S.hide;return P===w&&!M}),"number",f),i.defaultProps.allowDataOverflow),y=Kl(l,y,w,a)),C(C({},p),{},H({},w,C(C({axisType:a},i.defaultProps),{},{hide:!0,orientation:We(wD,"".concat(a,".").concat(v%2),null),domain:y,originalDomain:O,isCategorical:g,layout:f})))}return p},{})},TD=function(t,r){var n=r.axisType,i=n===void 0?"xAxis":n,a=r.AxisComp,o=r.graphicalItems,u=r.stackGroups,c=r.dataStartIndex,s=r.dataEndIndex,f=t.children,l="".concat(i,"Id"),h=Ze(f,a),d={};return h&&h.length?d=AD(t,{axes:h,graphicalItems:o,axisType:i,axisIdKey:l,stackGroups:u,dataStartIndex:c,dataEndIndex:s}):o&&o.length&&(d=PD(t,{Axis:a,graphicalItems:o,axisType:i,axisIdKey:l,stackGroups:u,dataStartIndex:c,dataEndIndex:s})),d},ED=function(t){var r=Ot(t),n=lt(r,!1,!0);return{tooltipTicks:n,orderedTooltipTicks:mf(n,function(i){return i.coordinate}),tooltipAxis:r,tooltipAxisBandSize:Ii(r,n)}},Dm=function(t){var r=t.children,n=t.defaultShowTooltip,i=Ne(r,wr),a=0,o=0;return t.data&&t.data.length!==0&&(o=t.data.length-1),i&&i.props&&(i.props.startIndex>=0&&(a=i.props.startIndex),i.props.endIndex>=0&&(o=i.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:a,dataEndIndex:o,activeTooltipIndex:-1,isTooltipActive:!!n}},jD=function(t){return!t||!t.length?!1:t.some(function(r){var n=ft(r&&r.type);return n&&n.indexOf("Bar")>=0})},Nm=function(t){return t==="horizontal"?{numericAxisName:"yAxis",cateAxisName:"xAxis"}:t==="vertical"?{numericAxisName:"xAxis",cateAxisName:"yAxis"}:t==="centric"?{numericAxisName:"radiusAxis",cateAxisName:"angleAxis"}:{numericAxisName:"angleAxis",cateAxisName:"radiusAxis"}},MD=function(t,r){var n=t.props,i=t.graphicalItems,a=t.xAxisMap,o=a===void 0?{}:a,u=t.yAxisMap,c=u===void 0?{}:u,s=n.width,f=n.height,l=n.children,h=n.margin||{},d=Ne(l,wr),g=Ne(l,ur),v=Object.keys(c).reduce(function(y,b){var _=c[b],S=_.orientation;return!_.mirror&&!_.hide?C(C({},y),{},H({},S,y[S]+_.width)):y},{left:h.left||0,right:h.right||0}),p=Object.keys(o).reduce(function(y,b){var _=o[b],S=_.orientation;return!_.mirror&&!_.hide?C(C({},y),{},H({},S,We(y,"".concat(S))+_.height)):y},{top:h.top||0,bottom:h.bottom||0}),m=C(C({},p),v),x=m.bottom;d&&(m.bottom+=d.props.height||wr.defaultProps.height),g&&r&&(m=XE(m,i,n,r));var w=s-m.left-m.right,O=f-m.top-m.bottom;return C(C({brushBottom:x},m),{},{width:Math.max(w,0),height:Math.max(O,0)})},CD=function(t,r){if(r==="xAxis")return t[r].width;if(r==="yAxis")return t[r].height},BD=function(t){var r=t.chartName,n=t.GraphicalChild,i=t.defaultTooltipEventType,a=i===void 0?"axis":i,o=t.validateTooltipEventTypes,u=o===void 0?["axis"]:o,c=t.axisComponents,s=t.legendContent,f=t.formatAxisMap,l=t.defaultProps,h=function(m,x){var w=x.graphicalItems,O=x.stackGroups,y=x.offset,b=x.updateId,_=x.dataStartIndex,S=x.dataEndIndex,P=m.barSize,M=m.layout,A=m.barGap,E=m.barCategoryGap,j=m.maxBarSize,I=Nm(M),$=I.numericAxisName,R=I.cateAxisName,D=jD(w),B=[];return w.forEach(function(L,z){var G=Ia(m.data,{graphicalItems:[L],dataStartIndex:_,dataEndIndex:S}),U=L.type.defaultProps!==void 0?C(C({},L.type.defaultProps),L.props):L.props,K=U.dataKey,ce=U.maxBarSize,pe=U["".concat($,"Id")],ke=U["".concat(R,"Id")],Ct={},Ce=c.reduce(function($t,It){var Ra=x["".concat(It.axisType,"Map")],rh=U["".concat(It.axisType,"Id")];Ra&&Ra[rh]||It.axisType==="zAxis"||Gt();var nh=Ra[rh];return C(C({},$t),{},H(H({},It.axisType,nh),"".concat(It.axisType,"Ticks"),lt(nh)))},Ct),F=Ce[R],X=Ce["".concat(R,"Ticks")],V=O&&O[pe]&&O[pe].hasStack&&aj(L,O[pe].stackGroups),k=ft(L.type).indexOf("Bar")>=0,fe=Ii(F,X),J=[],ye=D&&GE({barSize:P,stackGroups:O,totalSize:CD(Ce,R)});if(k){var ge,$e,xt=Z(ce)?j:ce,Jt=(ge=($e=Ii(F,X,!0))!==null&&$e!==void 0?$e:xt)!==null&&ge!==void 0?ge:0;J=KE({barGap:A,barCategoryGap:E,bandSize:Jt!==fe?Jt:fe,sizeList:ye[ke],maxBarSize:xt}),Jt!==fe&&(J=J.map(function($t){return C(C({},$t),{},{position:C(C({},$t.position),{},{offset:$t.position.offset-Jt/2})})}))}var Hn=L&&L.type&&L.type.getComposedData;Hn&&B.push({props:C(C({},Hn(C(C({},Ce),{},{displayedData:G,props:m,dataKey:K,item:L,bandSize:fe,barPosition:J,offset:y,stackedData:V,layout:M,dataStartIndex:_,dataEndIndex:S}))),{},H(H(H({key:L.key||"item-".concat(z)},$,Ce[$]),R,Ce[R]),"animationId",b)),childIndex:Vw(L,m.children),item:L})}),B},d=function(m,x){var w=m.props,O=m.dataStartIndex,y=m.dataEndIndex,b=m.updateId;if(!hp({props:w}))return null;var _=w.children,S=w.layout,P=w.stackOffset,M=w.data,A=w.reverseStackOrder,E=Nm(S),j=E.numericAxisName,I=E.cateAxisName,$=Ze(_,n),R=nj(M,$,"".concat(j,"Id"),"".concat(I,"Id"),P,A),D=c.reduce(function(U,K){var ce="".concat(K.axisType,"Map");return C(C({},U),{},H({},ce,TD(w,C(C({},K),{},{graphicalItems:$,stackGroups:K.axisType===j&&R,dataStartIndex:O,dataEndIndex:y}))))},{}),B=MD(C(C({},D),{},{props:w,graphicalItems:$}),x?.legendBBox);Object.keys(D).forEach(function(U){D[U]=f(w,D[U],B,U.replace("Map",""),r)});var L=D["".concat(I,"Map")],z=ED(L),G=h(w,C(C({},D),{},{dataStartIndex:O,dataEndIndex:y,updateId:b,graphicalItems:$,stackGroups:R,offset:B}));return C(C({formattedGraphicalItems:G,graphicalItems:$,offset:B,stackGroups:R},z),D)},g=(function(p){function m(x){var w,O,y;return lD(this,m),y=pD(this,m,[x]),H(y,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),H(y,"accessibilityManager",new Yk),H(y,"handleLegendBBoxUpdate",function(b){if(b){var _=y.state,S=_.dataStartIndex,P=_.dataEndIndex,M=_.updateId;y.setState(C({legendBBox:b},d({props:y.props,dataStartIndex:S,dataEndIndex:P,updateId:M},C(C({},y.state),{},{legendBBox:b}))))}}),H(y,"handleReceiveSyncEvent",function(b,_,S){if(y.props.syncId===b){if(S===y.eventEmitterSymbol&&typeof y.props.syncMethod!="function")return;y.applySyncEvent(_)}}),H(y,"handleBrushChange",function(b){var _=b.startIndex,S=b.endIndex;if(_!==y.state.dataStartIndex||S!==y.state.dataEndIndex){var P=y.state.updateId;y.setState(function(){return C({dataStartIndex:_,dataEndIndex:S},d({props:y.props,dataStartIndex:_,dataEndIndex:S,updateId:P},y.state))}),y.triggerSyncEvent({dataStartIndex:_,dataEndIndex:S})}}),H(y,"handleMouseEnter",function(b){var _=y.getMouseInfo(b);if(_){var S=C(C({},_),{},{isTooltipActive:!0});y.setState(S),y.triggerSyncEvent(S);var P=y.props.onMouseEnter;Y(P)&&P(S,b)}}),H(y,"triggeredAfterMouseMove",function(b){var _=y.getMouseInfo(b),S=_?C(C({},_),{},{isTooltipActive:!0}):{isTooltipActive:!1};y.setState(S),y.triggerSyncEvent(S);var P=y.props.onMouseMove;Y(P)&&P(S,b)}),H(y,"handleItemMouseEnter",function(b){y.setState(function(){return{isTooltipActive:!0,activeItem:b,activePayload:b.tooltipPayload,activeCoordinate:b.tooltipPosition||{x:b.cx,y:b.cy}}})}),H(y,"handleItemMouseLeave",function(){y.setState(function(){return{isTooltipActive:!1}})}),H(y,"handleMouseMove",function(b){b.persist(),y.throttleTriggeredAfterMouseMove(b)}),H(y,"handleMouseLeave",function(b){y.throttleTriggeredAfterMouseMove.cancel();var _={isTooltipActive:!1};y.setState(_),y.triggerSyncEvent(_);var S=y.props.onMouseLeave;Y(S)&&S(_,b)}),H(y,"handleOuterEvent",function(b){var _=Xw(b),S=We(y.props,"".concat(_));if(_&&Y(S)){var P,M;/.*touch.*/i.test(_)?M=y.getMouseInfo(b.changedTouches[0]):M=y.getMouseInfo(b),S((P=M)!==null&&P!==void 0?P:{},b)}}),H(y,"handleClick",function(b){var _=y.getMouseInfo(b);if(_){var S=C(C({},_),{},{isTooltipActive:!0});y.setState(S),y.triggerSyncEvent(S);var P=y.props.onClick;Y(P)&&P(S,b)}}),H(y,"handleMouseDown",function(b){var _=y.props.onMouseDown;if(Y(_)){var S=y.getMouseInfo(b);_(S,b)}}),H(y,"handleMouseUp",function(b){var _=y.props.onMouseUp;if(Y(_)){var S=y.getMouseInfo(b);_(S,b)}}),H(y,"handleTouchMove",function(b){b.changedTouches!=null&&b.changedTouches.length>0&&y.throttleTriggeredAfterMouseMove(b.changedTouches[0])}),H(y,"handleTouchStart",function(b){b.changedTouches!=null&&b.changedTouches.length>0&&y.handleMouseDown(b.changedTouches[0])}),H(y,"handleTouchEnd",function(b){b.changedTouches!=null&&b.changedTouches.length>0&&y.handleMouseUp(b.changedTouches[0])}),H(y,"handleDoubleClick",function(b){var _=y.props.onDoubleClick;if(Y(_)){var S=y.getMouseInfo(b);_(S,b)}}),H(y,"handleContextMenu",function(b){var _=y.props.onContextMenu;if(Y(_)){var S=y.getMouseInfo(b);_(S,b)}}),H(y,"triggerSyncEvent",function(b){y.props.syncId!==void 0&&Is.emit(Rs,y.props.syncId,b,y.eventEmitterSymbol)}),H(y,"applySyncEvent",function(b){var _=y.props,S=_.layout,P=_.syncMethod,M=y.state.updateId,A=b.dataStartIndex,E=b.dataEndIndex;if(b.dataStartIndex!==void 0||b.dataEndIndex!==void 0)y.setState(C({dataStartIndex:A,dataEndIndex:E},d({props:y.props,dataStartIndex:A,dataEndIndex:E,updateId:M},y.state)));else if(b.activeTooltipIndex!==void 0){var j=b.chartX,I=b.chartY,$=b.activeTooltipIndex,R=y.state,D=R.offset,B=R.tooltipTicks;if(!D)return;if(typeof P=="function")$=P(B,b);else if(P==="value"){$=-1;for(var L=0;L=0){var V,k;if(j.dataKey&&!j.allowDuplicatedCategory){var fe=typeof j.dataKey=="function"?X:"payload.".concat(j.dataKey.toString());V=oi(L,fe,$),k=z&&G&&oi(G,fe,$)}else V=L?.[I],k=z&&G&&G[I];if(ke||pe){var J=b.props.activeIndex!==void 0?b.props.activeIndex:I;return[N.cloneElement(b,C(C(C({},P.props),Ce),{},{activeIndex:J})),null,null]}if(!Z(V))return[F].concat(Mr(y.renderActivePoints({item:P,activePoint:V,basePoint:k,childIndex:I,isRange:z})))}else{var ye,ge=(ye=y.getItemByXY(y.state.activeCoordinate))!==null&&ye!==void 0?ye:{graphicalItem:F},$e=ge.graphicalItem,xt=$e.item,Jt=xt===void 0?b:xt,Hn=$e.childIndex,$t=C(C(C({},P.props),Ce),{},{activeIndex:Hn});return[N.cloneElement(Jt,$t),null,null]}return z?[F,null,null]:[F,null]}),H(y,"renderCustomized",function(b,_,S){return N.cloneElement(b,C(C({key:"recharts-customized-".concat(S)},y.props),y.state))}),H(y,"renderMap",{CartesianGrid:{handler:ai,once:!0},ReferenceArea:{handler:y.renderReferenceElement},ReferenceLine:{handler:ai},ReferenceDot:{handler:y.renderReferenceElement},XAxis:{handler:ai},YAxis:{handler:ai},Brush:{handler:y.renderBrush,once:!0},Bar:{handler:y.renderGraphicChild},Line:{handler:y.renderGraphicChild},Area:{handler:y.renderGraphicChild},Radar:{handler:y.renderGraphicChild},RadialBar:{handler:y.renderGraphicChild},Scatter:{handler:y.renderGraphicChild},Pie:{handler:y.renderGraphicChild},Funnel:{handler:y.renderGraphicChild},Tooltip:{handler:y.renderCursor,once:!0},PolarGrid:{handler:y.renderPolarGrid,once:!0},PolarAngleAxis:{handler:y.renderPolarAxis},PolarRadiusAxis:{handler:y.renderPolarAxis},Customized:{handler:y.renderCustomized}}),y.clipPathId="".concat((w=x.id)!==null&&w!==void 0?w:ua("recharts"),"-clip"),y.throttleTriggeredAfterMouseMove=Nb(y.triggeredAfterMouseMove,(O=x.throttleDelay)!==null&&O!==void 0?O:1e3/60),y.state={},y}return yD(m,p),hD(m,[{key:"componentDidMount",value:function(){var w,O;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(w=this.props.margin.left)!==null&&w!==void 0?w:0,top:(O=this.props.margin.top)!==null&&O!==void 0?O:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var w=this.props,O=w.children,y=w.data,b=w.height,_=w.layout,S=Ne(O,ot);if(S){var P=S.props.defaultIndex;if(!(typeof P!="number"||P<0||P>this.state.tooltipTicks.length-1)){var M=this.state.tooltipTicks[P]&&this.state.tooltipTicks[P].value,A=Yl(this.state,y,P,M),E=this.state.tooltipTicks[P].coordinate,j=(this.state.offset.top+b)/2,I=_==="horizontal",$=I?{x:E,y:j}:{y:E,x:j},R=this.state.formattedGraphicalItems.find(function(B){var L=B.item;return L.type.name==="Scatter"});R&&($=C(C({},$),R.props.points[P].tooltipPosition),A=R.props.points[P].tooltipPayload);var D={activeTooltipIndex:P,isTooltipActive:!0,activeLabel:M,activePayload:A,activeCoordinate:$};this.setState(D),this.renderCursor(S),this.accessibilityManager.setIndex(P)}}}},{key:"getSnapshotBeforeUpdate",value:function(w,O){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==O.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==w.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==w.margin){var y,b;this.accessibilityManager.setDetails({offset:{left:(y=this.props.margin.left)!==null&&y!==void 0?y:0,top:(b=this.props.margin.top)!==null&&b!==void 0?b:0}})}return null}},{key:"componentDidUpdate",value:function(w){qs([Ne(w.children,ot)],[Ne(this.props.children,ot)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var w=Ne(this.props.children,ot);if(w&&typeof w.props.shared=="boolean"){var O=w.props.shared?"axis":"item";return u.indexOf(O)>=0?O:a}return a}},{key:"getMouseInfo",value:function(w){if(!this.container)return null;var O=this.container,y=O.getBoundingClientRect(),b=kS(y),_={chartX:Math.round(w.pageX-b.left),chartY:Math.round(w.pageY-b.top)},S=y.width/O.offsetWidth||1,P=this.inRange(_.chartX,_.chartY,S);if(!P)return null;var M=this.state,A=M.xAxisMap,E=M.yAxisMap,j=this.getTooltipEventType(),I=km(this.state,this.props.data,this.props.layout,P);if(j!=="axis"&&A&&E){var $=Ot(A).scale,R=Ot(E).scale,D=$&&$.invert?$.invert(_.chartX):null,B=R&&R.invert?R.invert(_.chartY):null;return C(C({},_),{},{xValue:D,yValue:B},I)}return I?C(C({},_),I):null}},{key:"inRange",value:function(w,O){var y=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,b=this.props.layout,_=w/y,S=O/y;if(b==="horizontal"||b==="vertical"){var P=this.state.offset,M=_>=P.left&&_<=P.left+P.width&&S>=P.top&&S<=P.top+P.height;return M?{x:_,y:S}:null}var A=this.state,E=A.angleAxisMap,j=A.radiusAxisMap;if(E&&j){var I=Ot(E);return eg({x:_,y:S},I)}return null}},{key:"parseEventsOfWrapper",value:function(){var w=this.props.children,O=this.getTooltipEventType(),y=Ne(w,ot),b={};y&&O==="axis"&&(y.props.trigger==="click"?b={onClick:this.handleClick}:b={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var _=ui(this.props,this.handleOuterEvent);return C(C({},_),b)}},{key:"addListener",value:function(){Is.on(Rs,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){Is.removeListener(Rs,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(w,O,y){for(var b=this.state.formattedGraphicalItems,_=0,S=b.length;_:not([hidden])~:not([hidden]){--tw-space-x-reverse: 0;margin-right:calc(.75rem * var(--tw-space-x-reverse));margin-left:calc(.75rem * calc(1 - var(--tw-space-x-reverse)))}.space-y-0\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.125rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.125rem * var(--tw-space-y-reverse))}.space-y-1>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.25rem * var(--tw-space-y-reverse))}.space-y-1\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.375rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.375rem * var(--tw-space-y-reverse))}.space-y-2>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.5rem * var(--tw-space-y-reverse))}.space-y-2\.5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.625rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.625rem * var(--tw-space-y-reverse))}.space-y-3>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(.75rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(.75rem * var(--tw-space-y-reverse))}.space-y-4>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1rem * var(--tw-space-y-reverse))}.space-y-5>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.25rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.25rem * var(--tw-space-y-reverse))}.space-y-6>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.divide-y>:not([hidden])~:not([hidden]){--tw-divide-y-reverse: 0;border-top-width:calc(1px * calc(1 - var(--tw-divide-y-reverse)));border-bottom-width:calc(1px * var(--tw-divide-y-reverse))}.divide-\[var\(--dg-border\)\]>:not([hidden])~:not([hidden]){border-color:var(--dg-border)}.divide-slate-800>:not([hidden])~:not([hidden]){--tw-divide-opacity: 1;border-color:rgb(30 41 59 / var(--tw-divide-opacity, 1))}.self-start{align-self:flex-start}.self-center{align-self:center}.self-stretch{align-self:stretch}.justify-self-end{justify-self:end}.overflow-auto{overflow:auto}.overflow-hidden{overflow:hidden}.overflow-x-auto{overflow-x:auto}.overflow-y-auto{overflow-y:auto}.overflow-x-hidden{overflow-x:hidden}.truncate{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.whitespace-normal{white-space:normal}.whitespace-nowrap{white-space:nowrap}.whitespace-pre-wrap{white-space:pre-wrap}.text-balance{text-wrap:balance}.break-words{overflow-wrap:break-word}.break-all{word-break:break-all}.\!rounded-none{border-radius:0!important}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:1rem}.rounded-\[2px\]{border-radius:2px}.rounded-\[4px\]{border-radius:4px}.rounded-\[calc\(var\(--radius\)-5px\)\]{border-radius:calc(var(--radius) - 5px)}.rounded-\[inherit\]{border-radius:inherit}.rounded-full{border-radius:9999px}.rounded-lg{border-radius:var(--radius)}.rounded-md{border-radius:calc(var(--radius) - 2px)}.rounded-none{border-radius:0}.rounded-sm{border-radius:calc(var(--radius) - 4px)}.rounded-xl{border-radius:calc(var(--radius) + 4px)}.rounded-xs{border-radius:calc(var(--radius) - 6px)}.rounded-b-md{border-bottom-right-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.rounded-l-full{border-top-left-radius:9999px;border-bottom-left-radius:9999px}.rounded-l-md{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.rounded-r{border-top-right-radius:.25rem;border-bottom-right-radius:.25rem}.rounded-r-full{border-top-right-radius:9999px;border-bottom-right-radius:9999px}.rounded-r-md{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.rounded-t{border-top-left-radius:.25rem;border-top-right-radius:.25rem}.rounded-t-md{border-top-left-radius:calc(var(--radius) - 2px);border-top-right-radius:calc(var(--radius) - 2px)}.rounded-t-sm{border-top-left-radius:calc(var(--radius) - 4px);border-top-right-radius:calc(var(--radius) - 4px)}.rounded-tl-sm{border-top-left-radius:calc(var(--radius) - 4px)}.border{border-width:1px}.border-0{border-width:0px}.border-2{border-width:2px}.border-\[1\.5px\]{border-width:1.5px}.border-y{border-top-width:1px;border-bottom-width:1px}.border-b{border-bottom-width:1px}.border-b-0{border-bottom-width:0px}.border-b-2{border-bottom-width:2px}.border-l{border-left-width:1px}.border-l-2{border-left-width:2px}.border-l-4{border-left-width:4px}.border-r{border-right-width:1px}.border-t{border-top-width:1px}.border-dashed{border-style:dashed}.border-none{border-style:none}.border-\[var\(--dg-blue\)\]{border-color:var(--dg-blue)}.border-\[var\(--dg-border\)\]{border-color:var(--dg-border)}.border-amber-500{--tw-border-opacity: 1;border-color:rgb(245 158 11 / var(--tw-border-opacity, 1))}.border-amber-500\/20{border-color:#f59e0b33}.border-amber-500\/30{border-color:#f59e0b4d}.border-amber-500\/50{border-color:#f59e0b80}.border-amber-600{--tw-border-opacity: 1;border-color:rgb(217 119 6 / var(--tw-border-opacity, 1))}.border-amber-700\/50{border-color:#b4530980}.border-amber-800\/30{border-color:#92400e4d}.border-amber-800\/40{border-color:#92400e66}.border-amber-800\/50{border-color:#92400e80}.border-blue-400{--tw-border-opacity: 1;border-color:rgb(96 165 250 / var(--tw-border-opacity, 1))}.border-blue-400\/20{border-color:#60a5fa33}.border-blue-500{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-blue-500\/20{border-color:#3b82f633}.border-blue-500\/30{border-color:#3b82f64d}.border-blue-500\/50{border-color:#3b82f680}.border-blue-600{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.border-blue-600\/50{border-color:#2563eb80}.border-blue-700{--tw-border-opacity: 1;border-color:rgb(29 78 216 / var(--tw-border-opacity, 1))}.border-blue-700\/50{border-color:#1d4ed880}.border-blue-800\/50{border-color:#1e40af80}.border-border{border-color:hsl(var(--border))}.border-border\/50{border-color:hsl(var(--border) / .5)}.border-current{border-color:currentColor}.border-cyan-500{--tw-border-opacity: 1;border-color:rgb(6 182 212 / var(--tw-border-opacity, 1))}.border-cyan-500\/30{border-color:#06b6d44d}.border-emerald-400\/20{border-color:#34d39933}.border-emerald-400\/50{border-color:#34d39980}.border-emerald-500{--tw-border-opacity: 1;border-color:rgb(16 185 129 / var(--tw-border-opacity, 1))}.border-emerald-500\/20{border-color:#10b98133}.border-emerald-500\/30{border-color:#10b9814d}.border-emerald-600{--tw-border-opacity: 1;border-color:rgb(5 150 105 / var(--tw-border-opacity, 1))}.border-emerald-600\/30{border-color:#0596694d}.border-emerald-700\/50{border-color:#04785780}.border-emerald-900\/40{border-color:#064e3b66}.border-gray-500\/30{border-color:#6b72804d}.border-green-500\/30{border-color:#22c55e4d}.border-indigo-400\/50{border-color:#818cf880}.border-indigo-500{--tw-border-opacity: 1;border-color:rgb(99 102 241 / var(--tw-border-opacity, 1))}.border-input{border-color:hsl(var(--input))}.border-orange-500\/30{border-color:#f973164d}.border-primary{border-color:hsl(var(--primary))}.border-purple-500{--tw-border-opacity: 1;border-color:rgb(168 85 247 / var(--tw-border-opacity, 1))}.border-purple-500\/20{border-color:#a855f733}.border-purple-500\/30{border-color:#a855f74d}.border-purple-700\/50{border-color:#7e22ce80}.border-purple-800\/50{border-color:#6b21a880}.border-red-500{--tw-border-opacity: 1;border-color:rgb(239 68 68 / var(--tw-border-opacity, 1))}.border-red-500\/20{border-color:#ef444433}.border-red-500\/30{border-color:#ef44444d}.border-red-500\/40{border-color:#ef444466}.border-red-600{--tw-border-opacity: 1;border-color:rgb(220 38 38 / var(--tw-border-opacity, 1))}.border-red-600\/30{border-color:#dc26264d}.border-red-700\/50{border-color:#b91c1c80}.border-red-900\/30{border-color:#7f1d1d4d}.border-red-900\/40{border-color:#7f1d1d66}.border-rose-500\/30{border-color:#f43f5e4d}.border-sidebar-border{border-color:hsl(var(--sidebar-border))}.border-slate-500{--tw-border-opacity: 1;border-color:rgb(100 116 139 / var(--tw-border-opacity, 1))}.border-slate-500\/30{border-color:#64748b4d}.border-slate-600{--tw-border-opacity: 1;border-color:rgb(71 85 105 / var(--tw-border-opacity, 1))}.border-slate-600\/30{border-color:#4755694d}.border-slate-700{--tw-border-opacity: 1;border-color:rgb(51 65 85 / var(--tw-border-opacity, 1))}.border-slate-700\/50{border-color:#33415580}.border-slate-800{--tw-border-opacity: 1;border-color:rgb(30 41 59 / var(--tw-border-opacity, 1))}.border-slate-800\/30{border-color:#1e293b4d}.border-slate-800\/50{border-color:#1e293b80}.border-slate-800\/60{border-color:#1e293b99}.border-transparent{border-color:transparent}.border-violet-500\/30{border-color:#8b5cf64d}.border-yellow-500\/20{border-color:#eab30833}.border-yellow-500\/30{border-color:#eab3084d}.border-l-transparent{border-left-color:transparent}.border-t-\[var\(--dg-blue\)\]{border-top-color:var(--dg-blue)}.border-t-blue-500{--tw-border-opacity: 1;border-top-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.border-t-transparent{border-top-color:transparent}.bg-\[\#0a0e14\]{--tw-bg-opacity: 1;background-color:rgb(10 14 20 / var(--tw-bg-opacity, 1))}.bg-\[\#0d1117\]{--tw-bg-opacity: 1;background-color:rgb(13 17 23 / var(--tw-bg-opacity, 1))}.bg-\[\#0f172a\]{--tw-bg-opacity: 1;background-color:rgb(15 23 42 / var(--tw-bg-opacity, 1))}.bg-\[var\(--dg-bg-hover\)\]{background-color:var(--dg-bg-hover)}.bg-\[var\(--dg-bg-primary\)\]{background-color:var(--dg-bg-primary)}.bg-\[var\(--dg-bg-secondary\)\]{background-color:var(--dg-bg-secondary)}.bg-\[var\(--dg-bg-tertiary\)\]{background-color:var(--dg-bg-tertiary)}.bg-\[var\(--dg-blue\)\]{background-color:var(--dg-blue)}.bg-\[var\(--dg-border\)\]{background-color:var(--dg-border)}.bg-\[var\(--dg-green\)\]{background-color:var(--dg-green)}.bg-\[var\(--dg-purple\)\]{background-color:var(--dg-purple)}.bg-\[var\(--dg-red\)\]{background-color:var(--dg-red)}.bg-\[var\(--dg-text-secondary\)\]{background-color:var(--dg-text-secondary)}.bg-\[var\(--dg-yellow\)\]{background-color:var(--dg-yellow)}.bg-accent{background-color:hsl(var(--accent))}.bg-amber-400{--tw-bg-opacity: 1;background-color:rgb(251 191 36 / var(--tw-bg-opacity, 1))}.bg-amber-400\/10{background-color:#fbbf241a}.bg-amber-400\/40{background-color:#fbbf2466}.bg-amber-500{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.bg-amber-500\/10{background-color:#f59e0b1a}.bg-amber-500\/15{background-color:#f59e0b26}.bg-amber-500\/20{background-color:#f59e0b33}.bg-amber-500\/5{background-color:#f59e0b0d}.bg-amber-500\/60{background-color:#f59e0b99}.bg-amber-600{--tw-bg-opacity: 1;background-color:rgb(217 119 6 / var(--tw-bg-opacity, 1))}.bg-amber-600\/40{background-color:#d9770666}.bg-amber-950\/30{background-color:#451a034d}.bg-background{background-color:hsl(var(--background))}.bg-black{--tw-bg-opacity: 1;background-color:rgb(0 0 0 / var(--tw-bg-opacity, 1))}.bg-black\/40{background-color:#0006}.bg-black\/50{background-color:#00000080}.bg-black\/60{background-color:#0009}.bg-black\/70{background-color:#000000b3}.bg-blue-100{--tw-bg-opacity: 1;background-color:rgb(219 234 254 / var(--tw-bg-opacity, 1))}.bg-blue-400{--tw-bg-opacity: 1;background-color:rgb(96 165 250 / var(--tw-bg-opacity, 1))}.bg-blue-400\/10{background-color:#60a5fa1a}.bg-blue-500{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.bg-blue-500\/10{background-color:#3b82f61a}.bg-blue-500\/15{background-color:#3b82f626}.bg-blue-500\/20{background-color:#3b82f633}.bg-blue-500\/5{background-color:#3b82f60d}.bg-blue-600{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.bg-blue-600\/20{background-color:#2563eb33}.bg-blue-950\/20{background-color:#17255433}.bg-border{background-color:hsl(var(--border))}.bg-card{background-color:hsl(var(--card))}.bg-cyan-400\/10{background-color:#22d3ee1a}.bg-cyan-500\/10{background-color:#06b6d41a}.bg-cyan-500\/20{background-color:#06b6d433}.bg-destructive{--tw-bg-opacity: 1;background-color:hsl(var(--destructive) / var(--tw-bg-opacity, 1))}.bg-emerald-400{--tw-bg-opacity: 1;background-color:rgb(52 211 153 / var(--tw-bg-opacity, 1))}.bg-emerald-400\/10{background-color:#34d3991a}.bg-emerald-500{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.bg-emerald-500\/10{background-color:#10b9811a}.bg-emerald-500\/15{background-color:#10b98126}.bg-emerald-500\/20{background-color:#10b98133}.bg-emerald-500\/30{background-color:#10b9814d}.bg-emerald-500\/5{background-color:#10b9810d}.bg-emerald-500\/60{background-color:#10b98199}.bg-emerald-500\/90{background-color:#10b981e6}.bg-emerald-600{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.bg-emerald-600\/20{background-color:#05966933}.bg-emerald-600\/30{background-color:#0596694d}.bg-foreground{background-color:hsl(var(--foreground))}.bg-gray-100{--tw-bg-opacity: 1;background-color:rgb(243 244 246 / var(--tw-bg-opacity, 1))}.bg-gray-500{--tw-bg-opacity: 1;background-color:rgb(107 114 128 / var(--tw-bg-opacity, 1))}.bg-gray-500\/15{background-color:#6b728026}.bg-gray-500\/20{background-color:#6b728033}.bg-green-100{--tw-bg-opacity: 1;background-color:rgb(220 252 231 / var(--tw-bg-opacity, 1))}.bg-green-500{--tw-bg-opacity: 1;background-color:rgb(34 197 94 / var(--tw-bg-opacity, 1))}.bg-green-500\/10{background-color:#22c55e1a}.bg-green-500\/20{background-color:#22c55e33}.bg-green-600{--tw-bg-opacity: 1;background-color:rgb(22 163 74 / var(--tw-bg-opacity, 1))}.bg-indigo-400\/10{background-color:#818cf81a}.bg-indigo-500\/10{background-color:#6366f11a}.bg-input{background-color:hsl(var(--input))}.bg-muted{background-color:hsl(var(--muted))}.bg-muted\/40{background-color:hsl(var(--muted) / .4)}.bg-muted\/50{background-color:hsl(var(--muted) / .5)}.bg-orange-100{--tw-bg-opacity: 1;background-color:rgb(255 237 213 / var(--tw-bg-opacity, 1))}.bg-orange-500{--tw-bg-opacity: 1;background-color:rgb(249 115 22 / var(--tw-bg-opacity, 1))}.bg-orange-500\/20{background-color:#f9731633}.bg-orange-600{--tw-bg-opacity: 1;background-color:rgb(234 88 12 / var(--tw-bg-opacity, 1))}.bg-popover{background-color:hsl(var(--popover))}.bg-primary{background-color:hsl(var(--primary))}.bg-primary\/20{background-color:hsl(var(--primary) / .2)}.bg-purple-100{--tw-bg-opacity: 1;background-color:rgb(243 232 255 / var(--tw-bg-opacity, 1))}.bg-purple-400{--tw-bg-opacity: 1;background-color:rgb(192 132 252 / var(--tw-bg-opacity, 1))}.bg-purple-500{--tw-bg-opacity: 1;background-color:rgb(168 85 247 / var(--tw-bg-opacity, 1))}.bg-purple-500\/10{background-color:#a855f71a}.bg-purple-500\/20{background-color:#a855f733}.bg-purple-500\/5{background-color:#a855f70d}.bg-purple-600{--tw-bg-opacity: 1;background-color:rgb(147 51 234 / var(--tw-bg-opacity, 1))}.bg-purple-950\/20{background-color:#3b076433}.bg-red-100{--tw-bg-opacity: 1;background-color:rgb(254 226 226 / var(--tw-bg-opacity, 1))}.bg-red-400{--tw-bg-opacity: 1;background-color:rgb(248 113 113 / var(--tw-bg-opacity, 1))}.bg-red-500{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.bg-red-500\/10{background-color:#ef44441a}.bg-red-500\/15{background-color:#ef444426}.bg-red-500\/20{background-color:#ef444433}.bg-red-500\/5{background-color:#ef44440d}.bg-red-600{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.bg-red-600\/20{background-color:#dc262633}.bg-red-600\/40{background-color:#dc262666}.bg-red-900\/30{background-color:#7f1d1d4d}.bg-red-950\/20{background-color:#450a0a33}.bg-rose-500\/10{background-color:#f43f5e1a}.bg-rose-500\/20{background-color:#f43f5e33}.bg-secondary{background-color:hsl(var(--secondary))}.bg-sidebar{background-color:hsl(var(--sidebar-background))}.bg-sidebar-border{background-color:hsl(var(--sidebar-border))}.bg-sky-500{--tw-bg-opacity: 1;background-color:rgb(14 165 233 / var(--tw-bg-opacity, 1))}.bg-slate-100{--tw-bg-opacity: 1;background-color:rgb(241 245 249 / var(--tw-bg-opacity, 1))}.bg-slate-500{--tw-bg-opacity: 1;background-color:rgb(100 116 139 / var(--tw-bg-opacity, 1))}.bg-slate-500\/10{background-color:#64748b1a}.bg-slate-500\/15{background-color:#64748b26}.bg-slate-500\/20{background-color:#64748b33}.bg-slate-600{--tw-bg-opacity: 1;background-color:rgb(71 85 105 / var(--tw-bg-opacity, 1))}.bg-slate-600\/10{background-color:#4755691a}.bg-slate-600\/30{background-color:#4755694d}.bg-slate-700{--tw-bg-opacity: 1;background-color:rgb(51 65 85 / var(--tw-bg-opacity, 1))}.bg-slate-700\/50{background-color:#33415580}.bg-slate-800{--tw-bg-opacity: 1;background-color:rgb(30 41 59 / var(--tw-bg-opacity, 1))}.bg-slate-800\/20{background-color:#1e293b33}.bg-slate-800\/30{background-color:#1e293b4d}.bg-slate-800\/50{background-color:#1e293b80}.bg-slate-800\/60{background-color:#1e293b99}.bg-slate-900{--tw-bg-opacity: 1;background-color:rgb(15 23 42 / var(--tw-bg-opacity, 1))}.bg-slate-900\/30{background-color:#0f172a4d}.bg-slate-900\/40{background-color:#0f172a66}.bg-slate-900\/50{background-color:#0f172a80}.bg-slate-900\/60{background-color:#0f172a99}.bg-slate-900\/80{background-color:#0f172acc}.bg-slate-950{--tw-bg-opacity: 1;background-color:rgb(2 6 23 / var(--tw-bg-opacity, 1))}.bg-slate-950\/30{background-color:#0206174d}.bg-slate-950\/50{background-color:#02061780}.bg-slate-950\/80{background-color:#020617cc}.bg-transparent{background-color:transparent}.bg-violet-500\/20{background-color:#8b5cf633}.bg-white{--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity, 1))}.bg-yellow-400{--tw-bg-opacity: 1;background-color:rgb(250 204 21 / var(--tw-bg-opacity, 1))}.bg-yellow-500{--tw-bg-opacity: 1;background-color:rgb(234 179 8 / var(--tw-bg-opacity, 1))}.bg-yellow-500\/10{background-color:#eab3081a}.bg-yellow-500\/20{background-color:#eab30833}.bg-yellow-500\/5{background-color:#eab3080d}.bg-gradient-to-br{background-image:linear-gradient(to bottom right,var(--tw-gradient-stops))}.bg-gradient-to-r{background-image:linear-gradient(to right,var(--tw-gradient-stops))}.bg-gradient-to-t{background-image:linear-gradient(to top,var(--tw-gradient-stops))}.from-\[var\(--dg-blue\)\]{--tw-gradient-from: var(--dg-blue) var(--tw-gradient-from-position);--tw-gradient-to: rgb(255 255 255 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-amber-500{--tw-gradient-from: #f59e0b var(--tw-gradient-from-position);--tw-gradient-to: rgb(245 158 11 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500{--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-500\/50{--tw-gradient-from: rgb(59 130 246 / .5) var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-blue-600\/60{--tw-gradient-from: rgb(37 99 235 / .6) var(--tw-gradient-from-position);--tw-gradient-to: rgb(37 99 235 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-indigo-500{--tw-gradient-from: #6366f1 var(--tw-gradient-from-position);--tw-gradient-to: rgb(99 102 241 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.from-purple-500{--tw-gradient-from: #a855f7 var(--tw-gradient-from-position);--tw-gradient-to: rgb(168 85 247 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.to-\[var\(--dg-cyan\)\]{--tw-gradient-to: var(--dg-cyan) var(--tw-gradient-to-position)}.to-\[var\(--dg-purple\)\]{--tw-gradient-to: var(--dg-purple) var(--tw-gradient-to-position)}.to-amber-500{--tw-gradient-to: #f59e0b var(--tw-gradient-to-position)}.to-blue-400\/80{--tw-gradient-to: rgb(96 165 250 / .8) var(--tw-gradient-to-position)}.to-cyan-500{--tw-gradient-to: #06b6d4 var(--tw-gradient-to-position)}.to-orange-500{--tw-gradient-to: #f97316 var(--tw-gradient-to-position)}.to-pink-500{--tw-gradient-to: #ec4899 var(--tw-gradient-to-position)}.to-purple-500{--tw-gradient-to: #a855f7 var(--tw-gradient-to-position)}.fill-current{fill:currentColor}.fill-foreground{fill:hsl(var(--foreground))}.fill-primary{fill:hsl(var(--primary))}.p-0{padding:0}.p-0\.5{padding:.125rem}.p-1{padding:.25rem}.p-1\.5{padding:.375rem}.p-12{padding:3rem}.p-2{padding:.5rem}.p-2\.5{padding:.625rem}.p-3{padding:.75rem}.p-3\.5{padding:.875rem}.p-4{padding:1rem}.p-5{padding:1.25rem}.p-6{padding:1.5rem}.p-8{padding:2rem}.p-\[3px\]{padding:3px}.p-px{padding:1px}.px-0\.5{padding-left:.125rem;padding-right:.125rem}.px-1{padding-left:.25rem;padding-right:.25rem}.px-1\.5{padding-left:.375rem;padding-right:.375rem}.px-2{padding-left:.5rem;padding-right:.5rem}.px-2\.5{padding-left:.625rem;padding-right:.625rem}.px-3{padding-left:.75rem;padding-right:.75rem}.px-4{padding-left:1rem;padding-right:1rem}.px-6{padding-left:1.5rem;padding-right:1.5rem}.py-0{padding-top:0;padding-bottom:0}.py-0\.5{padding-top:.125rem;padding-bottom:.125rem}.py-1{padding-top:.25rem;padding-bottom:.25rem}.py-1\.5{padding-top:.375rem;padding-bottom:.375rem}.py-10{padding-top:2.5rem;padding-bottom:2.5rem}.py-12{padding-top:3rem;padding-bottom:3rem}.py-16{padding-top:4rem;padding-bottom:4rem}.py-2{padding-top:.5rem;padding-bottom:.5rem}.py-2\.5{padding-top:.625rem;padding-bottom:.625rem}.py-20{padding-top:5rem;padding-bottom:5rem}.py-3{padding-top:.75rem;padding-bottom:.75rem}.py-4{padding-top:1rem;padding-bottom:1rem}.py-6{padding-top:1.5rem;padding-bottom:1.5rem}.py-8{padding-top:2rem;padding-bottom:2rem}.py-px{padding-top:1px;padding-bottom:1px}.pb-0{padding-bottom:0}.pb-1{padding-bottom:.25rem}.pb-2{padding-bottom:.5rem}.pb-3{padding-bottom:.75rem}.pb-4{padding-bottom:1rem}.pb-px{padding-bottom:1px}.pl-1{padding-left:.25rem}.pl-1\.5{padding-left:.375rem}.pl-10{padding-left:2.5rem}.pl-2{padding-left:.5rem}.pl-3{padding-left:.75rem}.pl-4{padding-left:1rem}.pl-7{padding-left:1.75rem}.pl-8{padding-left:2rem}.pl-9{padding-left:2.25rem}.pl-\[88px\]{padding-left:88px}.pr-1{padding-right:.25rem}.pr-10{padding-right:2.5rem}.pr-12{padding-right:3rem}.pr-2{padding-right:.5rem}.pr-2\.5{padding-right:.625rem}.pr-3{padding-right:.75rem}.pr-4{padding-right:1rem}.pr-8{padding-right:2rem}.pt-0{padding-top:0}.pt-0\.5{padding-top:.125rem}.pt-1{padding-top:.25rem}.pt-1\.5{padding-top:.375rem}.pt-2{padding-top:.5rem}.pt-3{padding-top:.75rem}.pt-4{padding-top:1rem}.pt-5{padding-top:1.25rem}.pt-6{padding-top:1.5rem}.pt-\[var\(--header-height\)\]{padding-top:var(--header-height)}.pt-px{padding-top:1px}.text-left{text-align:left}.text-center{text-align:center}.text-right{text-align:right}.align-middle{vertical-align:middle}.font-mono{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace}.font-sans{font-family:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji",Segoe UI Symbol,"Noto Color Emoji"}.text-2xl{font-size:1.5rem;line-height:2rem}.text-3xl{font-size:1.875rem;line-height:2.25rem}.text-4xl{font-size:2.25rem;line-height:2.5rem}.text-\[0\.8rem\]{font-size:.8rem}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.text-\[12px\]{font-size:12px}.text-\[15px\]{font-size:15px}.text-\[9px\]{font-size:9px}.text-base{font-size:1rem;line-height:1.5rem}.text-lg{font-size:1.125rem;line-height:1.75rem}.text-sm{font-size:.875rem;line-height:1.25rem}.text-sm\/relaxed{font-size:.875rem;line-height:1.625}.text-xl{font-size:1.25rem;line-height:1.75rem}.text-xs{font-size:.75rem;line-height:1rem}.font-bold{font-weight:700}.font-medium{font-weight:500}.font-normal{font-weight:400}.font-semibold{font-weight:600}.uppercase{text-transform:uppercase}.capitalize{text-transform:capitalize}.italic{font-style:italic}.tabular-nums{--tw-numeric-spacing: tabular-nums;font-variant-numeric:var(--tw-ordinal) var(--tw-slashed-zero) var(--tw-numeric-figure) var(--tw-numeric-spacing) var(--tw-numeric-fraction)}.leading-5{line-height:1.25rem}.leading-none{line-height:1}.leading-normal{line-height:1.5}.leading-relaxed{line-height:1.625}.leading-snug{line-height:1.375}.leading-tight{line-height:1.25}.tracking-tight{letter-spacing:-.025em}.tracking-wide{letter-spacing:.025em}.tracking-wider{letter-spacing:.05em}.tracking-widest{letter-spacing:.1em}.text-\[var\(--dg-blue\)\]{color:var(--dg-blue)}.text-\[var\(--dg-border\)\]{color:var(--dg-border)}.text-\[var\(--dg-cyan\)\]{color:var(--dg-cyan)}.text-\[var\(--dg-green\)\]{color:var(--dg-green)}.text-\[var\(--dg-orange\)\]{color:var(--dg-orange)}.text-\[var\(--dg-purple\)\]{color:var(--dg-purple)}.text-\[var\(--dg-red\)\]{color:var(--dg-red)}.text-\[var\(--dg-text-muted\)\]{color:var(--dg-text-muted)}.text-\[var\(--dg-text-primary\)\]{color:var(--dg-text-primary)}.text-\[var\(--dg-text-secondary\)\]{color:var(--dg-text-secondary)}.text-\[var\(--dg-yellow\)\]{color:var(--dg-yellow)}.text-accent-foreground{color:hsl(var(--accent-foreground))}.text-amber-200{--tw-text-opacity: 1;color:rgb(253 230 138 / var(--tw-text-opacity, 1))}.text-amber-300{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.text-amber-300\/80{color:#fcd34dcc}.text-amber-400{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.text-amber-400\/80{color:#fbbf24cc}.text-amber-500{--tw-text-opacity: 1;color:rgb(245 158 11 / var(--tw-text-opacity, 1))}.text-amber-500\/30{color:#f59e0b4d}.text-amber-500\/70{color:#f59e0bb3}.text-background{color:hsl(var(--background))}.text-blue-300{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.text-blue-500{--tw-text-opacity: 1;color:rgb(59 130 246 / var(--tw-text-opacity, 1))}.text-blue-600{--tw-text-opacity: 1;color:rgb(37 99 235 / var(--tw-text-opacity, 1))}.text-card-foreground{color:hsl(var(--card-foreground))}.text-current{color:currentColor}.text-cyan-400{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.text-cyan-500{--tw-text-opacity: 1;color:rgb(6 182 212 / var(--tw-text-opacity, 1))}.text-destructive{--tw-text-opacity: 1;color:hsl(var(--destructive) / var(--tw-text-opacity, 1))}.text-emerald-200{--tw-text-opacity: 1;color:rgb(167 243 208 / var(--tw-text-opacity, 1))}.text-emerald-300{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.text-emerald-400{--tw-text-opacity: 1;color:rgb(52 211 153 / var(--tw-text-opacity, 1))}.text-emerald-400\/60{color:#34d39999}.text-emerald-500{--tw-text-opacity: 1;color:rgb(16 185 129 / var(--tw-text-opacity, 1))}.text-emerald-500\/30{color:#10b9814d}.text-foreground{color:hsl(var(--foreground))}.text-gray-400{--tw-text-opacity: 1;color:rgb(156 163 175 / var(--tw-text-opacity, 1))}.text-gray-600{--tw-text-opacity: 1;color:rgb(75 85 99 / var(--tw-text-opacity, 1))}.text-green-400{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.text-green-400\/70{color:#4ade80b3}.text-green-500{--tw-text-opacity: 1;color:rgb(34 197 94 / var(--tw-text-opacity, 1))}.text-green-600{--tw-text-opacity: 1;color:rgb(22 163 74 / var(--tw-text-opacity, 1))}.text-indigo-400{--tw-text-opacity: 1;color:rgb(129 140 248 / var(--tw-text-opacity, 1))}.text-muted-foreground{color:hsl(var(--muted-foreground))}.text-orange-300{--tw-text-opacity: 1;color:rgb(253 186 116 / var(--tw-text-opacity, 1))}.text-orange-400{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.text-orange-600{--tw-text-opacity: 1;color:rgb(234 88 12 / var(--tw-text-opacity, 1))}.text-popover-foreground{color:hsl(var(--popover-foreground))}.text-primary{color:hsl(var(--primary))}.text-primary-foreground{color:hsl(var(--primary-foreground))}.text-purple-300{--tw-text-opacity: 1;color:rgb(216 180 254 / var(--tw-text-opacity, 1))}.text-purple-400{--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1))}.text-purple-500{--tw-text-opacity: 1;color:rgb(168 85 247 / var(--tw-text-opacity, 1))}.text-purple-600{--tw-text-opacity: 1;color:rgb(147 51 234 / var(--tw-text-opacity, 1))}.text-red-200{--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity, 1))}.text-red-300{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.text-red-400{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.text-red-400\/70{color:#f87171b3}.text-red-500{--tw-text-opacity: 1;color:rgb(239 68 68 / var(--tw-text-opacity, 1))}.text-red-500\/30{color:#ef44444d}.text-red-600{--tw-text-opacity: 1;color:rgb(220 38 38 / var(--tw-text-opacity, 1))}.text-rose-400{--tw-text-opacity: 1;color:rgb(251 113 133 / var(--tw-text-opacity, 1))}.text-secondary-foreground{color:hsl(var(--secondary-foreground))}.text-sidebar-foreground{color:hsl(var(--sidebar-foreground))}.text-sidebar-foreground\/70{color:hsl(var(--sidebar-foreground) / .7)}.text-sky-400{--tw-text-opacity: 1;color:rgb(56 189 248 / var(--tw-text-opacity, 1))}.text-sky-500{--tw-text-opacity: 1;color:rgb(14 165 233 / var(--tw-text-opacity, 1))}.text-slate-100{--tw-text-opacity: 1;color:rgb(241 245 249 / var(--tw-text-opacity, 1))}.text-slate-200{--tw-text-opacity: 1;color:rgb(226 232 240 / var(--tw-text-opacity, 1))}.text-slate-300{--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1))}.text-slate-400{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.text-slate-500{--tw-text-opacity: 1;color:rgb(100 116 139 / var(--tw-text-opacity, 1))}.text-slate-600{--tw-text-opacity: 1;color:rgb(71 85 105 / var(--tw-text-opacity, 1))}.text-slate-700{--tw-text-opacity: 1;color:rgb(51 65 85 / var(--tw-text-opacity, 1))}.text-teal-400{--tw-text-opacity: 1;color:rgb(45 212 191 / var(--tw-text-opacity, 1))}.text-violet-400{--tw-text-opacity: 1;color:rgb(167 139 250 / var(--tw-text-opacity, 1))}.text-white{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.text-yellow-400{--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1))}.text-yellow-400\/80{color:#facc15cc}.text-yellow-500{--tw-text-opacity: 1;color:rgb(234 179 8 / var(--tw-text-opacity, 1))}.underline{text-decoration-line:underline}.underline-offset-4{text-underline-offset:4px}.accent-blue-500{accent-color:#3b82f6}.accent-blue-600{accent-color:#2563eb}.accent-cyan-500{accent-color:#06b6d4}.opacity-0{opacity:0}.opacity-100{opacity:1}.opacity-20{opacity:.2}.opacity-30{opacity:.3}.opacity-40{opacity:.4}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.opacity-70{opacity:.7}.opacity-80{opacity:.8}.shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-2xl{--tw-shadow: 0 25px 50px -12px rgb(0 0 0 / .25);--tw-shadow-colored: 0 25px 50px -12px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-\[0_0_0_1px_hsl\(var\(--sidebar-border\)\)\]{--tw-shadow: 0 0 0 1px hsl(var(--sidebar-border));--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-lg{--tw-shadow: 0 10px 15px -3px rgb(0 0 0 / .1), 0 4px 6px -4px rgb(0 0 0 / .1);--tw-shadow-colored: 0 10px 15px -3px var(--tw-shadow-color), 0 4px 6px -4px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-md{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-none{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xl{--tw-shadow: 0 20px 25px -5px rgb(0 0 0 / .1), 0 8px 10px -6px rgb(0 0 0 / .1);--tw-shadow-colored: 0 20px 25px -5px var(--tw-shadow-color), 0 8px 10px -6px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.shadow-xs{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.outline-none{outline:2px solid transparent;outline-offset:2px}.outline{outline-style:solid}.ring-0{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-1{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-2{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.ring-amber-500\/30{--tw-ring-color: rgb(245 158 11 / .3)}.ring-blue-500\/30{--tw-ring-color: rgb(59 130 246 / .3)}.ring-ring\/50{--tw-ring-color: hsl(var(--ring) / .5)}.ring-sidebar-ring{--tw-ring-color: hsl(var(--sidebar-ring))}.ring-offset-0{--tw-ring-offset-width: 0px}.ring-offset-background{--tw-ring-offset-color: hsl(var(--background))}.blur{--tw-blur: blur(8px);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.backdrop-blur{--tw-backdrop-blur: blur(8px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-blur-md{--tw-backdrop-blur: blur(12px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.backdrop-filter{-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia)}.\!transition-none{transition-property:none!important}.transition{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke,opacity,box-shadow,transform,filter,backdrop-filter;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[color\,box-shadow\]{transition-property:color,box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[left\,right\,width\]{transition-property:left,right,width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[margin\,opacity\]{transition-property:margin,opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[margin\]{transition-property:margin;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[width\,height\,padding\]{transition-property:width,height,padding;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-\[width\]{transition-property:width;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-all{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-colors{transition-property:color,background-color,border-color,text-decoration-color,fill,stroke;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-none{transition-property:none}.transition-opacity{transition-property:opacity;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-shadow{transition-property:box-shadow;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.transition-transform{transition-property:transform;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.15s}.\!duration-0{transition-duration:0s!important}.duration-100{transition-duration:.1s}.duration-1000{transition-duration:1s}.duration-200{transition-duration:.2s}.duration-300{transition-duration:.3s}.duration-500{transition-duration:.5s}.ease-in-out{transition-timing-function:cubic-bezier(.4,0,.2,1)}.ease-linear{transition-timing-function:linear}.ease-out{transition-timing-function:cubic-bezier(0,0,.2,1)}@keyframes enter{0%{opacity:var(--tw-enter-opacity, 1);transform:translate3d(var(--tw-enter-translate-x, 0),var(--tw-enter-translate-y, 0),0) scale3d(var(--tw-enter-scale, 1),var(--tw-enter-scale, 1),var(--tw-enter-scale, 1)) rotate(var(--tw-enter-rotate, 0))}}@keyframes exit{to{opacity:var(--tw-exit-opacity, 1);transform:translate3d(var(--tw-exit-translate-x, 0),var(--tw-exit-translate-y, 0),0) scale3d(var(--tw-exit-scale, 1),var(--tw-exit-scale, 1),var(--tw-exit-scale, 1)) rotate(var(--tw-exit-rotate, 0))}}.animate-in{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.fade-in,.fade-in-0{--tw-enter-opacity: 0}.zoom-in-95{--tw-enter-scale: .95}.\!duration-0{animation-duration:0s!important}.duration-100{animation-duration:.1s}.duration-1000{animation-duration:1s}.duration-200{animation-duration:.2s}.duration-300{animation-duration:.3s}.duration-500{animation-duration:.5s}.ease-in-out{animation-timing-function:cubic-bezier(.4,0,.2,1)}.ease-linear{animation-timing-function:linear}.ease-out{animation-timing-function:cubic-bezier(0,0,.2,1)}.running{animation-play-state:running}.\!paused{animation-play-state:paused!important}.paused{animation-play-state:paused}.dg-card{border-radius:calc(var(--radius) + 4px);border-width:1px;border-color:var(--dg-border);background-color:var(--dg-bg-secondary);box-shadow:var(--shadow-card);transition:background-color .3s ease,border-color .3s ease,box-shadow .3s ease,transform .3s ease}.dg-card-hover{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.3s;animation-duration:.3s}.dg-card-hover:hover{border-color:var(--dg-card-hover-border);box-shadow:var(--shadow-card-hover);transform:translateY(-2px)}.dg-input{border-radius:var(--radius);border-color:var(--dg-border);background-color:var(--dg-bg-tertiary);color:var(--dg-text-primary)}.dg-input::-moz-placeholder{color:var(--dg-text-muted)}.dg-input::placeholder{color:var(--dg-text-muted)}.dg-input:focus{border-color:var(--dg-blue);--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.dg-input{transition:border-color .2s ease,box-shadow .2s ease}.dg-input:focus{--tw-ring-color: var(--dg-input-focus-ring);box-shadow:0 0 0 3px var(--dg-input-focus-ring)}.dg-gradient-text{background:linear-gradient(to right,var(--dg-gradient-text-start),var(--dg-gradient-text-end));-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text}.dg-gradient-bg{background:linear-gradient(to right,var(--dg-gradient-start),var(--dg-gradient-end))}.dg-page>:not([hidden])~:not([hidden]){--tw-space-y-reverse: 0;margin-top:calc(1.5rem * calc(1 - var(--tw-space-y-reverse)));margin-bottom:calc(1.5rem * var(--tw-space-y-reverse))}.dg-page{animation:fade-in .35s cubic-bezier(.16,1,.3,1) forwards}.dg-page-header{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:1rem}.dg-page-title{font-size:1.5rem;line-height:2rem;font-weight:700;letter-spacing:-.025em;color:var(--dg-text-primary)}.dg-page-subtitle{margin-top:.25rem;font-size:.875rem;line-height:1.25rem;color:var(--dg-text-muted)}.dg-page-actions{display:flex;flex-wrap:wrap;align-items:center;gap:.5rem}.dg-btn-primary{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1));background:linear-gradient(to right,var(--dg-gradient-start),var(--dg-gradient-end));display:inline-flex;align-items:center;justify-content:center;gap:.5rem;border-radius:var(--radius);padding:.5rem 1rem;font-size:.875rem;line-height:1.25rem;font-weight:500;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.2s;animation-duration:.2s}.dg-btn-primary:hover{opacity:.9}.dg-btn-primary:active{--tw-scale-x: .98;--tw-scale-y: .98;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dg-btn-primary{box-shadow:0 4px 16px color-mix(in srgb,var(--dg-gradient-start) 25%,transparent)}.dg-btn-primary:hover{box-shadow:0 6px 24px color-mix(in srgb,var(--dg-gradient-start) 35%,transparent)}.dg-btn-secondary{border-width:1px;border-color:var(--dg-border);background-color:var(--dg-bg-tertiary);color:var(--dg-text-primary);display:inline-flex;align-items:center;justify-content:center;gap:.5rem;border-radius:var(--radius);padding:.5rem 1rem;font-size:.875rem;line-height:1.25rem;font-weight:500;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.2s;animation-duration:.2s}.dg-btn-secondary:hover{border-color:var(--dg-border-hover);background-color:var(--dg-bg-hover)}.dg-btn-secondary:active{--tw-scale-x: .98;--tw-scale-y: .98;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.dg-btn-ghost{color:var(--dg-text-secondary);display:inline-flex;align-items:center;justify-content:center;gap:.5rem;border-radius:var(--radius);padding:.5rem 1rem;font-size:.875rem;line-height:1.25rem;font-weight:500;transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.2s;animation-duration:.2s}.dg-btn-ghost:hover{background-color:var(--dg-bg-hover);color:var(--dg-text-primary)}.dg-badge-blue{background-color:#3b82f61a;--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1));display:inline-flex;align-items:center;border-radius:calc(var(--radius) - 2px);padding:.125rem .5rem;font-size:.75rem;line-height:1rem;font-weight:500}.dg-badge-green{background-color:#22c55e1a;--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1));display:inline-flex;align-items:center;border-radius:calc(var(--radius) - 2px);padding:.125rem .5rem;font-size:.75rem;line-height:1rem;font-weight:500}.dg-badge-red{background-color:#ef44441a;--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1));display:inline-flex;align-items:center;border-radius:calc(var(--radius) - 2px);padding:.125rem .5rem;font-size:.75rem;line-height:1rem;font-weight:500}.dg-badge-yellow{background-color:#eab3081a;--tw-text-opacity: 1;color:rgb(250 204 21 / var(--tw-text-opacity, 1));display:inline-flex;align-items:center;border-radius:calc(var(--radius) - 2px);padding:.125rem .5rem;font-size:.75rem;line-height:1rem;font-weight:500}.dg-badge-purple{background-color:#a855f71a;--tw-text-opacity: 1;color:rgb(192 132 252 / var(--tw-text-opacity, 1));display:inline-flex;align-items:center;border-radius:calc(var(--radius) - 2px);padding:.125rem .5rem;font-size:.75rem;line-height:1rem;font-weight:500}.scrollbar-thin{scrollbar-width:thin;scrollbar-color:var(--dg-border) transparent}.scrollbar-thin::-webkit-scrollbar{width:6px;height:6px}.scrollbar-thin::-webkit-scrollbar-track{background:transparent}.scrollbar-thin::-webkit-scrollbar-thumb{background:var(--dg-border);border-radius:3px}.scrollbar-thin::-webkit-scrollbar-thumb:hover{background:var(--dg-text-muted)}@keyframes fade-in{0%{opacity:0;transform:translateY(8px)}to{opacity:1;transform:translateY(0)}}.animate-fade-in{animation:fade-in .35s cubic-bezier(.16,1,.3,1) forwards}.animate-fade-in-delay-1{animation:fade-in .35s cubic-bezier(.16,1,.3,1) .05s both}.animate-fade-in-delay-2{animation:fade-in .35s cubic-bezier(.16,1,.3,1) .1s both}.animate-fade-in-delay-3{animation:fade-in .35s cubic-bezier(.16,1,.3,1) .15s both}.animate-fade-in-delay-4{animation:fade-in .35s cubic-bezier(.16,1,.3,1) .2s both}@keyframes scale-in{0%{opacity:0;transform:scale(.95)}to{opacity:1;transform:scale(1)}}.animate-scale-in{animation:scale-in .25s cubic-bezier(.16,1,.3,1) forwards}@keyframes slide-in-right{0%{opacity:0;transform:translate(20px)}to{opacity:1;transform:translate(0)}}@keyframes pulse-ring{0%{transform:scale(.8);opacity:.5}to{transform:scale(1.2);opacity:0}}@keyframes shimmer{0%{background-position:-200% 0}to{background-position:200% 0}}.dg-skeleton{background:linear-gradient(90deg,var(--skeleton-base) 25%,var(--skeleton-highlight) 50%,var(--skeleton-base) 75%);background-size:200% 100%;animation:shimmer 1.5s ease-in-out infinite;border-radius:.5rem}.glass{background:color-mix(in srgb,var(--dg-bg-secondary) 75%,transparent);backdrop-filter:blur(16px);-webkit-backdrop-filter:blur(16px);border:1px solid var(--dg-border)}.chart-grid-stroke{stroke:var(--chart-grid)}.chart-tooltip{background-color:var(--chart-tooltip-bg)!important;border:1px solid var(--chart-tooltip-border)!important;border-radius:6px!important;color:var(--dg-text-primary)!important;box-shadow:var(--shadow-dropdown)!important}.\[--cell-size\:--spacing\(8\)\]{--cell-size: var(--spacing(8))}pre{overflow-x:auto;border-radius:var(--radius);padding:1rem;background-color:var(--dg-bg-tertiary);border:1px solid var(--dg-border)}code{font-family:JetBrains Mono,Fira Code,Consolas,SF Mono,monospace;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:.875rem;line-height:1.25rem}table{width:100%}th{text-align:left;font-size:.75rem;line-height:1rem;font-weight:500;text-transform:uppercase;letter-spacing:.05em;color:var(--dg-text-secondary)}td{font-size:.875rem;line-height:1.25rem;color:var(--dg-text-primary)}input:focus,textarea:focus,select:focus{outline:none;box-shadow:0 0 0 2px var(--dg-bg-primary),0 0 0 4px var(--dg-blue);border-color:var(--dg-blue)}button{transition-property:all;transition-timing-function:cubic-bezier(.4,0,.2,1);transition-duration:.2s;animation-duration:.2s}.terminal{font-family:JetBrains Mono,Fira Code,Consolas,SF Mono,monospace;font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-size:.875rem;line-height:1.25rem;background-color:var(--dg-bg-primary);color:var(--dg-text-secondary)}.terminal .prompt{color:var(--dg-green)}.terminal .command{color:var(--dg-text-primary)}.terminal .output{color:var(--dg-text-muted)}.recharts-tooltip-wrapper{z-index:50}.recharts-default-tooltip{background-color:var(--chart-tooltip-bg)!important;border-color:var(--chart-tooltip-border)!important;color:var(--dg-text-primary)!important;border-radius:6px!important;box-shadow:var(--shadow-dropdown)!important}[data-state=open]>[data-radix-dialog-overlay]{--tw-backdrop-blur: blur(4px);-webkit-backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);backdrop-filter:var(--tw-backdrop-blur) var(--tw-backdrop-brightness) var(--tw-backdrop-contrast) var(--tw-backdrop-grayscale) var(--tw-backdrop-hue-rotate) var(--tw-backdrop-invert) var(--tw-backdrop-opacity) var(--tw-backdrop-saturate) var(--tw-backdrop-sepia);background-color:color-mix(in srgb,var(--dg-bg-primary) 80%,transparent)}[role=menuitem]{cursor:pointer}@keyframes progress-indeterminate{0%{transform:translate(-100%)}to{transform:translate(100%)}}.progress-indeterminate:after{content:"";position:absolute;inset:0;background-color:currentColor;animation:progress-indeterminate 1.5s ease-in-out infinite}@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation-duration:.01ms!important;animation-iteration-count:1!important;transition-duration:.01ms!important}.dg-skeleton{animation:none;background:var(--skeleton-base)}}.selection\:bg-primary *::-moz-selection{background-color:hsl(var(--primary))}.selection\:bg-primary *::selection{background-color:hsl(var(--primary))}.selection\:text-primary-foreground *::-moz-selection{color:hsl(var(--primary-foreground))}.selection\:text-primary-foreground *::selection{color:hsl(var(--primary-foreground))}.selection\:bg-primary::-moz-selection{background-color:hsl(var(--primary))}.selection\:bg-primary::selection{background-color:hsl(var(--primary))}.selection\:text-primary-foreground::-moz-selection{color:hsl(var(--primary-foreground))}.selection\:text-primary-foreground::selection{color:hsl(var(--primary-foreground))}.file\:inline-flex::file-selector-button{display:inline-flex}.file\:h-7::file-selector-button{height:1.75rem}.file\:border-0::file-selector-button{border-width:0px}.file\:bg-transparent::file-selector-button{background-color:transparent}.file\:text-sm::file-selector-button{font-size:.875rem;line-height:1.25rem}.file\:font-medium::file-selector-button{font-weight:500}.file\:text-foreground::file-selector-button{color:hsl(var(--foreground))}.placeholder\:text-\[var\(--dg-text-muted\)\]::-moz-placeholder{color:var(--dg-text-muted)}.placeholder\:text-\[var\(--dg-text-muted\)\]::placeholder{color:var(--dg-text-muted)}.placeholder\:text-muted-foreground::-moz-placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-muted-foreground::placeholder{color:hsl(var(--muted-foreground))}.placeholder\:text-slate-500::-moz-placeholder{--tw-text-opacity: 1;color:rgb(100 116 139 / var(--tw-text-opacity, 1))}.placeholder\:text-slate-500::placeholder{--tw-text-opacity: 1;color:rgb(100 116 139 / var(--tw-text-opacity, 1))}.placeholder\:text-slate-600::-moz-placeholder{--tw-text-opacity: 1;color:rgb(71 85 105 / var(--tw-text-opacity, 1))}.placeholder\:text-slate-600::placeholder{--tw-text-opacity: 1;color:rgb(71 85 105 / var(--tw-text-opacity, 1))}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:-inset-2:after{content:var(--tw-content);inset:-.5rem}.after\:inset-y-0:after{content:var(--tw-content);top:0;bottom:0}.after\:left-1\/2:after{content:var(--tw-content);left:50%}.after\:w-1:after{content:var(--tw-content);width:.25rem}.after\:w-\[2px\]:after{content:var(--tw-content);width:2px}.after\:-translate-x-1\/2:after{content:var(--tw-content);--tw-translate-x: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.first\:rounded-l-md:first-child{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.first\:border-l:first-child{border-left-width:1px}.last\:mt-0:last-child{margin-top:0}.last\:rounded-r-md:last-child{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.last\:border-0:last-child{border-width:0px}.last\:border-b-0:last-child{border-bottom-width:0px}.hover\:scale-105:hover{--tw-scale-x: 1.05;--tw-scale-y: 1.05;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.hover\:border-\[var\(--dg-border\)\]:hover{border-color:var(--dg-border)}.hover\:border-\[var\(--dg-border-hover\)\]:hover{border-color:var(--dg-border-hover)}.hover\:border-blue-500:hover{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.hover\:border-blue-500\/50:hover{border-color:#3b82f680}.hover\:border-orange-500\/30:hover{border-color:#f973164d}.hover\:border-primary\/50:hover{border-color:hsl(var(--primary) / .5)}.hover\:border-slate-400:hover{--tw-border-opacity: 1;border-color:rgb(148 163 184 / var(--tw-border-opacity, 1))}.hover\:border-slate-600:hover{--tw-border-opacity: 1;border-color:rgb(71 85 105 / var(--tw-border-opacity, 1))}.hover\:border-slate-700:hover{--tw-border-opacity: 1;border-color:rgb(51 65 85 / var(--tw-border-opacity, 1))}.hover\:bg-\[var\(--dg-bg-hover\)\]:hover{background-color:var(--dg-bg-hover)}.hover\:bg-\[var\(--dg-bg-primary\)\]:hover{background-color:var(--dg-bg-primary)}.hover\:bg-\[var\(--dg-bg-tertiary\)\]:hover{background-color:var(--dg-bg-tertiary)}.hover\:bg-\[var\(--dg-blue-hover\)\]:hover{background-color:var(--dg-blue-hover)}.hover\:bg-accent:hover{background-color:hsl(var(--accent))}.hover\:bg-amber-500\/10:hover{background-color:#f59e0b1a}.hover\:bg-amber-600\/20:hover{background-color:#d9770633}.hover\:bg-amber-700:hover{--tw-bg-opacity: 1;background-color:rgb(180 83 9 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-500:hover{--tw-bg-opacity: 1;background-color:rgb(59 130 246 / var(--tw-bg-opacity, 1))}.hover\:bg-blue-500\/10:hover{background-color:#3b82f61a}.hover\:bg-blue-600\/10:hover{background-color:#2563eb1a}.hover\:bg-blue-600\/20:hover{background-color:#2563eb33}.hover\:bg-blue-700:hover{--tw-bg-opacity: 1;background-color:rgb(29 78 216 / var(--tw-bg-opacity, 1))}.hover\:bg-cyan-500\/20:hover{background-color:#06b6d433}.hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}.hover\:bg-emerald-500:hover{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.hover\:bg-emerald-500\/10:hover{background-color:#10b9811a}.hover\:bg-emerald-600\/10:hover{background-color:#0596691a}.hover\:bg-emerald-600\/20:hover{background-color:#05966933}.hover\:bg-emerald-700:hover{--tw-bg-opacity: 1;background-color:rgb(4 120 87 / var(--tw-bg-opacity, 1))}.hover\:bg-muted:hover{background-color:hsl(var(--muted))}.hover\:bg-muted\/50:hover{background-color:hsl(var(--muted) / .5)}.hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}.hover\:bg-purple-700:hover{--tw-bg-opacity: 1;background-color:rgb(126 34 206 / var(--tw-bg-opacity, 1))}.hover\:bg-red-500\/10:hover{background-color:#ef44441a}.hover\:bg-red-600:hover{--tw-bg-opacity: 1;background-color:rgb(220 38 38 / var(--tw-bg-opacity, 1))}.hover\:bg-red-600\/20:hover{background-color:#dc262633}.hover\:bg-red-700:hover{--tw-bg-opacity: 1;background-color:rgb(185 28 28 / var(--tw-bg-opacity, 1))}.hover\:bg-red-950\/10:hover{background-color:#450a0a1a}.hover\:bg-secondary\/80:hover{background-color:hsl(var(--secondary) / .8)}.hover\:bg-sidebar-accent:hover{background-color:hsl(var(--sidebar-accent))}.hover\:bg-slate-700:hover{--tw-bg-opacity: 1;background-color:rgb(51 65 85 / var(--tw-bg-opacity, 1))}.hover\:bg-slate-800:hover{--tw-bg-opacity: 1;background-color:rgb(30 41 59 / var(--tw-bg-opacity, 1))}.hover\:bg-slate-800\/30:hover{background-color:#1e293b4d}.hover\:bg-slate-800\/40:hover{background-color:#1e293b66}.hover\:bg-slate-800\/50:hover{background-color:#1e293b80}.hover\:bg-transparent:hover{background-color:transparent}.hover\:bg-white\/5:hover{background-color:#ffffff0d}.hover\:bg-white\/\[0\.03\]:hover{background-color:#ffffff08}.hover\:stroke-blue-500:hover{stroke:#3b82f6}.hover\:text-\[var\(--dg-blue\)\]:hover{color:var(--dg-blue)}.hover\:text-\[var\(--dg-text-primary\)\]:hover{color:var(--dg-text-primary)}.hover\:text-\[var\(--dg-text-secondary\)\]:hover{color:var(--dg-text-secondary)}.hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))}.hover\:text-amber-300:hover{--tw-text-opacity: 1;color:rgb(252 211 77 / var(--tw-text-opacity, 1))}.hover\:text-amber-400:hover{--tw-text-opacity: 1;color:rgb(251 191 36 / var(--tw-text-opacity, 1))}.hover\:text-blue-300:hover{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.hover\:text-blue-400:hover{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.hover\:text-cyan-400:hover{--tw-text-opacity: 1;color:rgb(34 211 238 / var(--tw-text-opacity, 1))}.hover\:text-emerald-300:hover{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.hover\:text-emerald-400:hover{--tw-text-opacity: 1;color:rgb(52 211 153 / var(--tw-text-opacity, 1))}.hover\:text-foreground:hover{color:hsl(var(--foreground))}.hover\:text-green-400:hover{--tw-text-opacity: 1;color:rgb(74 222 128 / var(--tw-text-opacity, 1))}.hover\:text-muted-foreground:hover{color:hsl(var(--muted-foreground))}.hover\:text-red-300:hover{--tw-text-opacity: 1;color:rgb(252 165 165 / var(--tw-text-opacity, 1))}.hover\:text-red-400:hover{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.hover\:text-sidebar-accent-foreground:hover{color:hsl(var(--sidebar-accent-foreground))}.hover\:text-slate-100:hover{--tw-text-opacity: 1;color:rgb(241 245 249 / var(--tw-text-opacity, 1))}.hover\:text-slate-200:hover{--tw-text-opacity: 1;color:rgb(226 232 240 / var(--tw-text-opacity, 1))}.hover\:text-slate-300:hover{--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1))}.hover\:text-white:hover{--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity, 1))}.hover\:underline:hover{text-decoration-line:underline}.hover\:opacity-100:hover{opacity:1}.hover\:opacity-80:hover{opacity:.8}.hover\:opacity-90:hover{opacity:.9}.hover\:shadow-\[0_0_0_1px_hsl\(var\(--sidebar-accent\)\)\]:hover{--tw-shadow: 0 0 0 1px hsl(var(--sidebar-accent));--tw-shadow-colored: 0 0 0 1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:shadow-md:hover{--tw-shadow: 0 4px 6px -1px rgb(0 0 0 / .1), 0 2px 4px -2px rgb(0 0 0 / .1);--tw-shadow-colored: 0 4px 6px -1px var(--tw-shadow-color), 0 2px 4px -2px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.hover\:ring-4:hover{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.hover\:brightness-110:hover{--tw-brightness: brightness(1.1);filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}.hover\:after\:bg-sidebar-border:hover:after{content:var(--tw-content);background-color:hsl(var(--sidebar-border))}.focus\:z-10:focus{z-index:10}.focus\:border-\[var\(--dg-blue\)\]:focus{border-color:var(--dg-blue)}.focus\:border-amber-600:focus{--tw-border-opacity: 1;border-color:rgb(217 119 6 / var(--tw-border-opacity, 1))}.focus\:border-blue-500:focus{--tw-border-opacity: 1;border-color:rgb(59 130 246 / var(--tw-border-opacity, 1))}.focus\:bg-\[var\(--dg-bg-hover\)\]:focus{background-color:var(--dg-bg-hover)}.focus\:bg-accent:focus{background-color:hsl(var(--accent))}.focus\:bg-red-500\/10:focus{background-color:#ef44441a}.focus\:bg-slate-700:focus{--tw-bg-opacity: 1;background-color:rgb(51 65 85 / var(--tw-bg-opacity, 1))}.focus\:text-\[var\(--dg-text-primary\)\]:focus{color:var(--dg-text-primary)}.focus\:text-accent-foreground:focus{color:hsl(var(--accent-foreground))}.focus\:text-blue-300:focus{--tw-text-opacity: 1;color:rgb(147 197 253 / var(--tw-text-opacity, 1))}.focus\:text-cyan-300:focus{--tw-text-opacity: 1;color:rgb(103 232 249 / var(--tw-text-opacity, 1))}.focus\:text-emerald-300:focus{--tw-text-opacity: 1;color:rgb(110 231 183 / var(--tw-text-opacity, 1))}.focus\:text-red-400:focus{--tw-text-opacity: 1;color:rgb(248 113 113 / var(--tw-text-opacity, 1))}.focus\:text-slate-100:focus{--tw-text-opacity: 1;color:rgb(241 245 249 / var(--tw-text-opacity, 1))}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}.focus\:ring-1:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-2:focus{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus\:ring-blue-500:focus{--tw-ring-opacity: 1;--tw-ring-color: rgb(59 130 246 / var(--tw-ring-opacity, 1))}.focus\:ring-ring:focus{--tw-ring-color: hsl(var(--ring))}.focus\:ring-offset-2:focus{--tw-ring-offset-width: 2px}.focus-visible\:z-10:focus-visible{z-index:10}.focus-visible\:border-ring:focus-visible{border-color:hsl(var(--ring))}.focus-visible\:outline-1:focus-visible{outline-width:1px}.focus-visible\:outline-ring:focus-visible{outline-color:hsl(var(--ring))}.focus-visible\:ring-0:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(0px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-1:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(1px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-2:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-4:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-\[3px\]:focus-visible{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.focus-visible\:ring-destructive\/20:focus-visible{--tw-ring-color: hsl(var(--destructive) / .2)}.focus-visible\:ring-ring:focus-visible{--tw-ring-color: hsl(var(--ring))}.focus-visible\:ring-ring\/50:focus-visible{--tw-ring-color: hsl(var(--ring) / .5)}.focus-visible\:ring-offset-1:focus-visible{--tw-ring-offset-width: 1px}.active\:scale-95:active{--tw-scale-x: .95;--tw-scale-y: .95;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.active\:scale-\[0\.98\]:active{--tw-scale-x: .98;--tw-scale-y: .98;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.active\:bg-sidebar-accent:active{background-color:hsl(var(--sidebar-accent))}.active\:text-sidebar-accent-foreground:active{color:hsl(var(--sidebar-accent-foreground))}.disabled\:pointer-events-none:disabled{pointer-events:none}.disabled\:cursor-not-allowed:disabled{cursor:not-allowed}.disabled\:opacity-30:disabled{opacity:.3}.disabled\:opacity-40:disabled{opacity:.4}.disabled\:opacity-50:disabled{opacity:.5}.disabled\:opacity-60:disabled{opacity:.6}.group\/menu-item:focus-within .group-focus-within\/menu-item\:opacity-100{opacity:1}.group:hover .group-hover\:block{display:block}.group:hover .group-hover\:from-blue-500{--tw-gradient-from: #3b82f6 var(--tw-gradient-from-position);--tw-gradient-to: rgb(59 130 246 / 0) var(--tw-gradient-to-position);--tw-gradient-stops: var(--tw-gradient-from), var(--tw-gradient-to)}.group:hover .group-hover\:to-blue-300{--tw-gradient-to: #93c5fd var(--tw-gradient-to-position)}.group:hover .group-hover\:text-blue-400{--tw-text-opacity: 1;color:rgb(96 165 250 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:text-slate-100{--tw-text-opacity: 1;color:rgb(241 245 249 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:text-slate-300{--tw-text-opacity: 1;color:rgb(203 213 225 / var(--tw-text-opacity, 1))}.group:hover .group-hover\:text-slate-400{--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity, 1))}.group\/cmd:hover .group-hover\/cmd\:opacity-100,.group\/menu-item:hover .group-hover\/menu-item\:opacity-100,.group:hover .group-hover\:opacity-100{opacity:1}.peer\/menu-button:hover~.peer-hover\/menu-button\:text-sidebar-accent-foreground{color:hsl(var(--sidebar-accent-foreground))}.peer:disabled~.peer-disabled\:cursor-not-allowed{cursor:not-allowed}.peer:disabled~.peer-disabled\:opacity-50{opacity:.5}.has-\[\>button\]\:ml-\[-0\.45rem\]:has(>button){margin-left:-.45rem}.has-\[\>button\]\:mr-\[-0\.45rem\]:has(>button){margin-right:-.45rem}.has-\[\>kbd\]\:ml-\[-0\.35rem\]:has(>kbd){margin-left:-.35rem}.has-\[\>kbd\]\:mr-\[-0\.35rem\]:has(>kbd){margin-right:-.35rem}.has-\[\>\[data-align\=block-end\]\]\:h-auto:has(>[data-align=block-end]){height:auto}.has-\[\>\[data-align\=block-start\]\]\:h-auto:has(>[data-align=block-start]){height:auto}.has-\[\>textarea\]\:h-auto:has(>textarea){height:auto}.has-\[\>\[data-slot\=field\]\]\:w-full:has(>[data-slot=field]){width:100%}.has-\[\>svg\]\:grid-cols-\[calc\(var\(--spacing\)\*4\)_1fr\]:has(>svg){grid-template-columns:calc(var(--spacing) * 4) 1fr}.has-\[\>\[data-align\=block-end\]\]\:flex-col:has(>[data-align=block-end]){flex-direction:column}.has-\[\>\[data-align\=block-start\]\]\:flex-col:has(>[data-align=block-start]){flex-direction:column}.has-\[\>\[data-slot\=field\]\]\:flex-col:has(>[data-slot=field]){flex-direction:column}.has-\[\>\[data-slot\=field-content\]\]\:items-start:has(>[data-slot=field-content]){align-items:flex-start}.has-\[\>\[data-slot\=button-group\]\]\:gap-2:has(>[data-slot=button-group]){gap:.5rem}.has-\[\>\[data-slot\=checkbox-group\]\]\:gap-3:has(>[data-slot=checkbox-group]){gap:.75rem}.has-\[\>\[data-slot\=radio-group\]\]\:gap-3:has(>[data-slot=radio-group]){gap:.75rem}.has-\[\>svg\]\:gap-x-3:has(>svg){-moz-column-gap:.75rem;column-gap:.75rem}.has-\[\>\[data-slot\=field\]\]\:rounded-md:has(>[data-slot=field]){border-radius:calc(var(--radius) - 2px)}.has-\[\>\[data-slot\=field\]\]\:border:has(>[data-slot=field]){border-width:1px}.has-\[\[data-slot\=input-group-control\]\:focus-visible\]\:border-ring:has([data-slot=input-group-control]:focus-visible){border-color:hsl(var(--ring))}.has-\[\[data-slot\]\[aria-invalid\=true\]\]\:border-destructive:has([data-slot][aria-invalid=true]){--tw-border-opacity: 1;border-color:hsl(var(--destructive) / var(--tw-border-opacity, 1))}.has-\[\>svg\]\:p-0:has(>svg){padding:0}.has-\[\>svg\]\:px-2:has(>svg){padding-left:.5rem;padding-right:.5rem}.has-\[\>svg\]\:px-2\.5:has(>svg){padding-left:.625rem;padding-right:.625rem}.has-\[\>svg\]\:px-3:has(>svg){padding-left:.75rem;padding-right:.75rem}.has-\[\>svg\]\:px-4:has(>svg){padding-left:1rem;padding-right:1rem}.has-\[\[data-slot\=input-group-control\]\:focus-visible\]\:ring-\[3px\]:has([data-slot=input-group-control]:focus-visible){--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.has-\[\[data-slot\=input-group-control\]\:focus-visible\]\:ring-ring\/50:has([data-slot=input-group-control]:focus-visible){--tw-ring-color: hsl(var(--ring) / .5)}.has-\[\[data-slot\]\[aria-invalid\=true\]\]\:ring-destructive\/20:has([data-slot][aria-invalid=true]){--tw-ring-color: hsl(var(--destructive) / .2)}.group\/item:has([data-slot=item-description]) .group-has-\[\[data-slot\=item-description\]\]\/item\:translate-y-0\.5{--tw-translate-y: .125rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group\/item:has([data-slot=item-description]) .group-has-\[\[data-slot\=item-description\]\]\/item\:self-start{align-self:flex-start}.group\/field:has([data-orientation=horizontal]) .group-has-\[\[data-orientation\=horizontal\]\]\/field\:text-balance{text-wrap:balance}.group\/input-group:has(>input) .group-has-\[\>input\]\/input-group\:pb-2\.5{padding-bottom:.625rem}.group\/input-group:has(>input) .group-has-\[\>input\]\/input-group\:pt-2\.5{padding-top:.625rem}.aria-disabled\:pointer-events-none[aria-disabled=true]{pointer-events:none}.aria-disabled\:opacity-50[aria-disabled=true]{opacity:.5}.aria-selected\:text-muted-foreground[aria-selected=true]{color:hsl(var(--muted-foreground))}.data-\[disabled\=true\]\:pointer-events-none[data-disabled=true],.data-\[disabled\]\:pointer-events-none[data-disabled]{pointer-events:none}.data-\[vaul-drawer-direction\=bottom\]\:inset-x-0[data-vaul-drawer-direction=bottom]{left:0;right:0}.data-\[vaul-drawer-direction\=left\]\:inset-y-0[data-vaul-drawer-direction=left],.data-\[vaul-drawer-direction\=right\]\:inset-y-0[data-vaul-drawer-direction=right]{top:0;bottom:0}.data-\[vaul-drawer-direction\=top\]\:inset-x-0[data-vaul-drawer-direction=top]{left:0;right:0}.data-\[vaul-drawer-direction\=bottom\]\:bottom-0[data-vaul-drawer-direction=bottom]{bottom:0}.data-\[vaul-drawer-direction\=left\]\:left-0[data-vaul-drawer-direction=left]{left:0}.data-\[vaul-drawer-direction\=right\]\:right-0[data-vaul-drawer-direction=right]{right:0}.data-\[vaul-drawer-direction\=top\]\:top-0[data-vaul-drawer-direction=top]{top:0}.data-\[active\=true\]\:z-10[data-active=true]{z-index:10}.data-\[vaul-drawer-direction\=bottom\]\:mt-24[data-vaul-drawer-direction=bottom]{margin-top:6rem}.data-\[vaul-drawer-direction\=top\]\:mb-24[data-vaul-drawer-direction=top]{margin-bottom:6rem}.data-\[orientation\=horizontal\]\:h-1\.5[data-orientation=horizontal]{height:.375rem}.data-\[orientation\=horizontal\]\:h-full[data-orientation=horizontal]{height:100%}.data-\[orientation\=horizontal\]\:h-px[data-orientation=horizontal]{height:1px}.data-\[orientation\=vertical\]\:h-auto[data-orientation=vertical]{height:auto}.data-\[orientation\=vertical\]\:h-full[data-orientation=vertical]{height:100%}.data-\[panel-group-direction\=vertical\]\:h-px[data-panel-group-direction=vertical]{height:1px}.data-\[size\=default\]\:h-9[data-size=default]{height:2.25rem}.data-\[size\=sm\]\:h-8[data-size=sm]{height:2rem}.data-\[vaul-drawer-direction\=bottom\]\:max-h-\[80vh\][data-vaul-drawer-direction=bottom],.data-\[vaul-drawer-direction\=top\]\:max-h-\[80vh\][data-vaul-drawer-direction=top]{max-height:80vh}.data-\[orientation\=vertical\]\:min-h-44[data-orientation=vertical]{min-height:11rem}.data-\[orientation\=horizontal\]\:w-full[data-orientation=horizontal]{width:100%}.data-\[orientation\=vertical\]\:w-1\.5[data-orientation=vertical]{width:.375rem}.data-\[orientation\=vertical\]\:w-auto[data-orientation=vertical]{width:auto}.data-\[orientation\=vertical\]\:w-full[data-orientation=vertical]{width:100%}.data-\[orientation\=vertical\]\:w-px[data-orientation=vertical]{width:1px}.data-\[panel-group-direction\=vertical\]\:w-full[data-panel-group-direction=vertical]{width:100%}.data-\[vaul-drawer-direction\=left\]\:w-3\/4[data-vaul-drawer-direction=left],.data-\[vaul-drawer-direction\=right\]\:w-3\/4[data-vaul-drawer-direction=right]{width:75%}.data-\[side\=bottom\]\:translate-y-1[data-side=bottom]{--tw-translate-y: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=left\]\:-translate-x-1[data-side=left]{--tw-translate-x: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=right\]\:translate-x-1[data-side=right]{--tw-translate-x: .25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[side\=top\]\:-translate-y-1[data-side=top]{--tw-translate-y: -.25rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=checked\]\:translate-x-\[calc\(100\%-2px\)\][data-state=checked]{--tw-translate-x: calc(100% - 2px) ;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[state\=unchecked\]\:translate-x-0[data-state=unchecked]{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@keyframes accordion-up{0%{height:var(--radix-accordion-content-height)}to{height:0}}.data-\[state\=closed\]\:animate-accordion-up[data-state=closed]{animation:accordion-up .2s ease-out}@keyframes accordion-down{0%{height:0}to{height:var(--radix-accordion-content-height)}}.data-\[state\=open\]\:animate-accordion-down[data-state=open]{animation:accordion-down .2s ease-out}.data-\[orientation\=vertical\]\:flex-col[data-orientation=vertical],.data-\[panel-group-direction\=vertical\]\:flex-col[data-panel-group-direction=vertical]{flex-direction:column}.data-\[slot\=checkbox-group\]\:gap-3[data-slot=checkbox-group]{gap:.75rem}.data-\[range-end\=true\]\:rounded-md[data-range-end=true]{border-radius:calc(var(--radius) - 2px)}.data-\[range-middle\=true\]\:rounded-none[data-range-middle=true]{border-radius:0}.data-\[range-start\=true\]\:rounded-md[data-range-start=true]{border-radius:calc(var(--radius) - 2px)}.data-\[selected\=true\]\:rounded-none[data-selected=true],.data-\[spacing\=0\]\:rounded-none[data-spacing="0"]{border-radius:0}.data-\[range-end\=true\]\:rounded-r-md[data-range-end=true]{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.data-\[range-start\=true\]\:rounded-l-md[data-range-start=true]{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.data-\[vaul-drawer-direction\=bottom\]\:rounded-t-lg[data-vaul-drawer-direction=bottom]{border-top-left-radius:var(--radius);border-top-right-radius:var(--radius)}.data-\[vaul-drawer-direction\=top\]\:rounded-b-lg[data-vaul-drawer-direction=top]{border-bottom-right-radius:var(--radius);border-bottom-left-radius:var(--radius)}.data-\[spacing\=0\]\:data-\[variant\=outline\]\:border-l-0[data-variant=outline][data-spacing="0"]{border-left-width:0px}.data-\[vaul-drawer-direction\=bottom\]\:border-t[data-vaul-drawer-direction=bottom]{border-top-width:1px}.data-\[vaul-drawer-direction\=left\]\:border-r[data-vaul-drawer-direction=left]{border-right-width:1px}.data-\[vaul-drawer-direction\=right\]\:border-l[data-vaul-drawer-direction=right]{border-left-width:1px}.data-\[vaul-drawer-direction\=top\]\:border-b[data-vaul-drawer-direction=top]{border-bottom-width:1px}.data-\[active\=true\]\:border-ring[data-active=true]{border-color:hsl(var(--ring))}.data-\[state\=checked\]\:border-blue-600[data-state=checked]{--tw-border-opacity: 1;border-color:rgb(37 99 235 / var(--tw-border-opacity, 1))}.data-\[state\=checked\]\:border-primary[data-state=checked]{border-color:hsl(var(--primary))}.data-\[active\=true\]\:bg-accent\/50[data-active=true]{background-color:hsl(var(--accent) / .5)}.data-\[active\=true\]\:bg-sidebar-accent[data-active=true]{background-color:hsl(var(--sidebar-accent))}.data-\[range-end\=true\]\:bg-primary[data-range-end=true]{background-color:hsl(var(--primary))}.data-\[range-middle\=true\]\:bg-accent[data-range-middle=true]{background-color:hsl(var(--accent))}.data-\[range-start\=true\]\:bg-primary[data-range-start=true],.data-\[selected-single\=true\]\:bg-primary[data-selected-single=true]{background-color:hsl(var(--primary))}.data-\[selected\=true\]\:bg-accent[data-selected=true]{background-color:hsl(var(--accent))}.data-\[state\=active\]\:bg-\[var\(--dg-bg-primary\)\][data-state=active]{background-color:var(--dg-bg-primary)}.data-\[state\=active\]\:bg-\[var\(--dg-bg-tertiary\)\][data-state=active]{background-color:var(--dg-bg-tertiary)}.data-\[state\=active\]\:bg-background[data-state=active]{background-color:hsl(var(--background))}.data-\[state\=active\]\:bg-orange-500\/10[data-state=active]{background-color:#f973161a}.data-\[state\=active\]\:bg-slate-700[data-state=active]{--tw-bg-opacity: 1;background-color:rgb(51 65 85 / var(--tw-bg-opacity, 1))}.data-\[state\=checked\]\:bg-blue-600[data-state=checked]{--tw-bg-opacity: 1;background-color:rgb(37 99 235 / var(--tw-bg-opacity, 1))}.data-\[state\=checked\]\:bg-emerald-600[data-state=checked]{--tw-bg-opacity: 1;background-color:rgb(5 150 105 / var(--tw-bg-opacity, 1))}.data-\[state\=checked\]\:bg-primary[data-state=checked]{background-color:hsl(var(--primary))}.data-\[state\=on\]\:bg-accent[data-state=on],.data-\[state\=open\]\:bg-accent[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:bg-accent\/50[data-state=open]{background-color:hsl(var(--accent) / .5)}.data-\[state\=open\]\:bg-secondary[data-state=open]{background-color:hsl(var(--secondary))}.data-\[state\=selected\]\:bg-muted[data-state=selected]{background-color:hsl(var(--muted))}.data-\[state\=unchecked\]\:bg-input[data-state=unchecked]{background-color:hsl(var(--input))}.data-\[inset\]\:pl-8[data-inset]{padding-left:2rem}.data-\[variant\=label\]\:text-sm[data-variant=label]{font-size:.875rem;line-height:1.25rem}.data-\[variant\=legend\]\:text-base[data-variant=legend]{font-size:1rem;line-height:1.5rem}.data-\[active\=true\]\:font-medium[data-active=true]{font-weight:500}.data-\[active\=true\]\:text-accent-foreground[data-active=true]{color:hsl(var(--accent-foreground))}.data-\[active\=true\]\:text-sidebar-accent-foreground[data-active=true]{color:hsl(var(--sidebar-accent-foreground))}.data-\[error\=true\]\:text-destructive[data-error=true],.data-\[invalid\=true\]\:text-destructive[data-invalid=true]{--tw-text-opacity: 1;color:hsl(var(--destructive) / var(--tw-text-opacity, 1))}.data-\[placeholder\]\:text-muted-foreground[data-placeholder]{color:hsl(var(--muted-foreground))}.data-\[range-end\=true\]\:text-primary-foreground[data-range-end=true]{color:hsl(var(--primary-foreground))}.data-\[range-middle\=true\]\:text-accent-foreground[data-range-middle=true]{color:hsl(var(--accent-foreground))}.data-\[range-start\=true\]\:text-primary-foreground[data-range-start=true],.data-\[selected-single\=true\]\:text-primary-foreground[data-selected-single=true]{color:hsl(var(--primary-foreground))}.data-\[selected\=true\]\:text-accent-foreground[data-selected=true]{color:hsl(var(--accent-foreground))}.data-\[state\=active\]\:text-orange-400[data-state=active]{--tw-text-opacity: 1;color:rgb(251 146 60 / var(--tw-text-opacity, 1))}.data-\[state\=checked\]\:text-primary-foreground[data-state=checked]{color:hsl(var(--primary-foreground))}.data-\[state\=on\]\:text-accent-foreground[data-state=on],.data-\[state\=open\]\:text-accent-foreground[data-state=open]{color:hsl(var(--accent-foreground))}.data-\[state\=open\]\:text-muted-foreground[data-state=open]{color:hsl(var(--muted-foreground))}.data-\[variant\=destructive\]\:text-destructive[data-variant=destructive]{--tw-text-opacity: 1;color:hsl(var(--destructive) / var(--tw-text-opacity, 1))}.data-\[disabled\=true\]\:opacity-50[data-disabled=true],.data-\[disabled\]\:opacity-50[data-disabled]{opacity:.5}.data-\[state\=open\]\:opacity-100[data-state=open]{opacity:1}.data-\[spacing\=0\]\:shadow-none[data-spacing="0"]{--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[spacing\=default\]\:data-\[variant\=outline\]\:shadow-xs[data-variant=outline][data-spacing=default],.data-\[state\=active\]\:shadow-sm[data-state=active]{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.data-\[active\=true\]\:ring-\[3px\][data-active=true]{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.data-\[active\=true\]\:ring-ring\/50[data-active=true]{--tw-ring-color: hsl(var(--ring) / .5)}.data-\[state\=closed\]\:duration-300[data-state=closed]{transition-duration:.3s}.data-\[state\=open\]\:duration-500[data-state=open]{transition-duration:.5s}.data-\[motion\^\=from-\]\:animate-in[data-motion^=from-],.data-\[state\=open\]\:animate-in[data-state=open],.data-\[state\=visible\]\:animate-in[data-state=visible]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.data-\[motion\^\=to-\]\:animate-out[data-motion^=to-],.data-\[state\=closed\]\:animate-out[data-state=closed],.data-\[state\=hidden\]\:animate-out[data-state=hidden]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.data-\[motion\^\=from-\]\:fade-in[data-motion^=from-]{--tw-enter-opacity: 0}.data-\[motion\^\=to-\]\:fade-out[data-motion^=to-],.data-\[state\=closed\]\:fade-out-0[data-state=closed],.data-\[state\=hidden\]\:fade-out[data-state=hidden]{--tw-exit-opacity: 0}.data-\[state\=open\]\:fade-in-0[data-state=open],.data-\[state\=visible\]\:fade-in[data-state=visible]{--tw-enter-opacity: 0}.data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.data-\[state\=open\]\:zoom-in-90[data-state=open]{--tw-enter-scale: .9}.data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.data-\[motion\=from-end\]\:slide-in-from-right-52[data-motion=from-end]{--tw-enter-translate-x: 13rem}.data-\[motion\=from-start\]\:slide-in-from-left-52[data-motion=from-start]{--tw-enter-translate-x: -13rem}.data-\[motion\=to-end\]\:slide-out-to-right-52[data-motion=to-end]{--tw-exit-translate-x: 13rem}.data-\[motion\=to-start\]\:slide-out-to-left-52[data-motion=to-start]{--tw-exit-translate-x: -13rem}.data-\[side\=bottom\]\:slide-in-from-top-2[data-side=bottom]{--tw-enter-translate-y: -.5rem}.data-\[side\=left\]\:slide-in-from-right-2[data-side=left]{--tw-enter-translate-x: .5rem}.data-\[side\=right\]\:slide-in-from-left-2[data-side=right]{--tw-enter-translate-x: -.5rem}.data-\[side\=top\]\:slide-in-from-bottom-2[data-side=top]{--tw-enter-translate-y: .5rem}.data-\[state\=closed\]\:slide-out-to-bottom[data-state=closed]{--tw-exit-translate-y: 100%}.data-\[state\=closed\]\:slide-out-to-left[data-state=closed]{--tw-exit-translate-x: -100%}.data-\[state\=closed\]\:slide-out-to-right[data-state=closed]{--tw-exit-translate-x: 100%}.data-\[state\=closed\]\:slide-out-to-top[data-state=closed]{--tw-exit-translate-y: -100%}.data-\[state\=open\]\:slide-in-from-bottom[data-state=open]{--tw-enter-translate-y: 100%}.data-\[state\=open\]\:slide-in-from-left[data-state=open]{--tw-enter-translate-x: -100%}.data-\[state\=open\]\:slide-in-from-right[data-state=open]{--tw-enter-translate-x: 100%}.data-\[state\=open\]\:slide-in-from-top[data-state=open]{--tw-enter-translate-y: -100%}.data-\[state\=closed\]\:duration-300[data-state=closed]{animation-duration:.3s}.data-\[state\=open\]\:duration-500[data-state=open]{animation-duration:.5s}.\*\:data-\[slot\=select-value\]\:line-clamp-1[data-slot=select-value]>*{overflow:hidden;display:-webkit-box;-webkit-box-orient:vertical;-webkit-line-clamp:1}.\*\:data-\[slot\=select-value\]\:flex[data-slot=select-value]>*{display:flex}.\*\:data-\[slot\=select-value\]\:items-center[data-slot=select-value]>*{align-items:center}.\*\:data-\[slot\=select-value\]\:gap-2[data-slot=select-value]>*{gap:.5rem}.\*\:data-\[slot\=alert-description\]\:text-destructive\/90[data-slot=alert-description]>*{color:hsl(var(--destructive) / .9)}.data-\[panel-group-direction\=vertical\]\:after\:left-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);left:0}.data-\[panel-group-direction\=vertical\]\:after\:h-1[data-panel-group-direction=vertical]:after{content:var(--tw-content);height:.25rem}.data-\[panel-group-direction\=vertical\]\:after\:w-full[data-panel-group-direction=vertical]:after{content:var(--tw-content);width:100%}.data-\[panel-group-direction\=vertical\]\:after\:-translate-y-1\/2[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-y: -50%;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[panel-group-direction\=vertical\]\:after\:translate-x-0[data-panel-group-direction=vertical]:after{content:var(--tw-content);--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.data-\[spacing\=0\]\:first\:rounded-l-md:first-child[data-spacing="0"]{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.data-\[spacing\=0\]\:data-\[variant\=outline\]\:first\:border-l:first-child[data-variant=outline][data-spacing="0"]{border-left-width:1px}.data-\[spacing\=0\]\:last\:rounded-r-md:last-child[data-spacing="0"]{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.data-\[active\=true\]\:hover\:bg-accent:hover[data-active=true],.data-\[state\=open\]\:hover\:bg-accent:hover[data-state=open]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:hover\:bg-sidebar-accent:hover[data-state=open]{background-color:hsl(var(--sidebar-accent))}.data-\[state\=open\]\:hover\:text-sidebar-accent-foreground:hover[data-state=open]{color:hsl(var(--sidebar-accent-foreground))}.data-\[active\=true\]\:focus\:bg-accent:focus[data-active=true]{background-color:hsl(var(--accent))}.data-\[state\=open\]\:focus\:bg-accent:focus[data-state=open]{background-color:hsl(var(--accent))}.data-\[variant\=destructive\]\:focus\:bg-destructive\/10:focus[data-variant=destructive]{background-color:hsl(var(--destructive) / .1)}.data-\[variant\=destructive\]\:focus\:text-destructive:focus[data-variant=destructive]{--tw-text-opacity: 1;color:hsl(var(--destructive) / var(--tw-text-opacity, 1))}.group[data-disabled=true] .group-data-\[disabled\=true\]\:pointer-events-none{pointer-events:none}.group\/day[data-focused=true] .group-data-\[focused\=true\]\/day\:relative{position:relative}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:left-\[calc\(var\(--sidebar-width\)\*-1\)\]{left:calc(var(--sidebar-width) * -1)}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:right-\[calc\(var\(--sidebar-width\)\*-1\)\]{right:calc(var(--sidebar-width) * -1)}.group[data-side=left] .group-data-\[side\=left\]\:-right-4{right:-1rem}.group[data-side=right] .group-data-\[side\=right\]\:left-0{left:0}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:top-full{top:100%}.group\/day[data-focused=true] .group-data-\[focused\=true\]\/day\:z-10{z-index:10}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:-mt-8{margin-top:-2rem}.group\/field-group[data-variant=outline] .group-data-\[variant\=outline\]\/field-group\:-mb-2{margin-bottom:-.5rem}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:mt-1\.5{margin-top:.375rem}.group\/drawer-content[data-vaul-drawer-direction=bottom] .group-data-\[vaul-drawer-direction\=bottom\]\/drawer-content\:block{display:block}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:hidden{display:none}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)\+\(--spacing\(4\)\)\)\]{width:calc(var(--sidebar-width-icon) + (--spacing(4)))}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:w-\[calc\(var\(--sidebar-width-icon\)\+\(--spacing\(4\)\)\+2px\)\]{width:calc(var(--sidebar-width-icon) + (--spacing(4)) + 2px)}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:w-0{width:0px}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:translate-x-0{--tw-translate-x: 0px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group[data-side=right] .group-data-\[side\=right\]\:rotate-180,.group[data-state=open] .group-data-\[state\=open\]\:rotate-180{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:overflow-hidden,.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:overflow-hidden{overflow:hidden}.group[data-variant=floating] .group-data-\[variant\=floating\]\:rounded-lg{border-radius:var(--radius)}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:rounded-md{border-radius:calc(var(--radius) - 2px)}.group[data-variant=floating] .group-data-\[variant\=floating\]\:border,.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:border{border-width:1px}.group[data-side=left] .group-data-\[side\=left\]\:border-r{border-right-width:1px}.group[data-side=right] .group-data-\[side\=right\]\:border-l{border-left-width:1px}.group\/day[data-focused=true] .group-data-\[focused\=true\]\/day\:border-ring{border-color:hsl(var(--ring))}.group[data-variant=floating] .group-data-\[variant\=floating\]\:border-sidebar-border{border-color:hsl(var(--sidebar-border))}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:bg-popover{background-color:hsl(var(--popover))}.group\/drawer-content[data-vaul-drawer-direction=bottom] .group-data-\[vaul-drawer-direction\=bottom\]\/drawer-content\:text-center,.group\/drawer-content[data-vaul-drawer-direction=top] .group-data-\[vaul-drawer-direction\=top\]\/drawer-content\:text-center{text-align:center}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:text-popover-foreground{color:hsl(var(--popover-foreground))}.group[data-collapsible=icon] .group-data-\[collapsible\=icon\]\:opacity-0{opacity:0}.group\/field[data-disabled=true] .group-data-\[disabled\=true\]\/field\:opacity-50,.group\/input-group[data-disabled=true] .group-data-\[disabled\=true\]\/input-group\:opacity-50,.group[data-disabled=true] .group-data-\[disabled\=true\]\:opacity-50{opacity:.5}.group[data-variant=floating] .group-data-\[variant\=floating\]\:shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:shadow{--tw-shadow: 0 1px 3px 0 rgb(0 0 0 / .1), 0 1px 2px -1px rgb(0 0 0 / .1);--tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}.group\/day[data-focused=true] .group-data-\[focused\=true\]\/day\:ring-\[3px\]{--tw-ring-offset-shadow: var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(3px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow, 0 0 #0000)}.group\/day[data-focused=true] .group-data-\[focused\=true\]\/day\:ring-ring\/50{--tw-ring-color: hsl(var(--ring) / .5)}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:duration-200{transition-duration:.2s;animation-duration:.2s}.group[data-collapsible=offcanvas] .group-data-\[collapsible\=offcanvas\]\:after\:left-full:after{content:var(--tw-content);left:100%}.group[data-collapsible=offcanvas] .hover\:group-data-\[collapsible\=offcanvas\]\:bg-sidebar:hover{background-color:hsl(var(--sidebar-background))}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:animate-in[data-state=open]{animation-name:enter;animation-duration:.15s;--tw-enter-opacity: initial;--tw-enter-scale: initial;--tw-enter-rotate: initial;--tw-enter-translate-x: initial;--tw-enter-translate-y: initial}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:animate-out[data-state=closed]{animation-name:exit;animation-duration:.15s;--tw-exit-opacity: initial;--tw-exit-scale: initial;--tw-exit-rotate: initial;--tw-exit-translate-x: initial;--tw-exit-translate-y: initial}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:fade-out-0[data-state=closed]{--tw-exit-opacity: 0}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:fade-in-0[data-state=open]{--tw-enter-opacity: 0}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=closed\]\:zoom-out-95[data-state=closed]{--tw-exit-scale: .95}.group\/navigation-menu[data-viewport=false] .group-data-\[viewport\=false\]\/navigation-menu\:data-\[state\=open\]\:zoom-in-95[data-state=open]{--tw-enter-scale: .95}.peer\/menu-button[data-size=default]~.peer-data-\[size\=default\]\/menu-button\:top-1\.5{top:.375rem}.peer\/menu-button[data-size=lg]~.peer-data-\[size\=lg\]\/menu-button\:top-2\.5{top:.625rem}.peer\/menu-button[data-size=sm]~.peer-data-\[size\=sm\]\/menu-button\:top-1{top:.25rem}.peer\/menu-button[data-active=true]~.peer-data-\[active\=true\]\/menu-button\:text-sidebar-accent-foreground{color:hsl(var(--sidebar-accent-foreground))}.dark\:border-input:is(.dark *){border-color:hsl(var(--input))}.dark\:bg-destructive\/60:is(.dark *){background-color:hsl(var(--destructive) / .6)}.dark\:bg-input\/30:is(.dark *){background-color:hsl(var(--input) / .3)}.dark\:bg-slate-800:is(.dark *){--tw-bg-opacity: 1;background-color:rgb(30 41 59 / var(--tw-bg-opacity, 1))}.dark\:bg-transparent:is(.dark *){background-color:transparent}.dark\:text-muted-foreground:is(.dark *){color:hsl(var(--muted-foreground))}.dark\:hover\:bg-accent\/50:hover:is(.dark *){background-color:hsl(var(--accent) / .5)}.dark\:hover\:bg-input\/50:hover:is(.dark *){background-color:hsl(var(--input) / .5)}.dark\:hover\:text-accent-foreground:hover:is(.dark *){color:hsl(var(--accent-foreground))}.dark\:focus-visible\:ring-destructive\/40:focus-visible:is(.dark *){--tw-ring-color: hsl(var(--destructive) / .4)}.dark\:has-\[\[data-slot\]\[aria-invalid\=true\]\]\:ring-destructive\/40:has([data-slot][aria-invalid=true]):is(.dark *){--tw-ring-color: hsl(var(--destructive) / .4)}.dark\:data-\[state\=active\]\:border-input[data-state=active]:is(.dark *){border-color:hsl(var(--input))}.dark\:data-\[state\=active\]\:bg-input\/30[data-state=active]:is(.dark *){background-color:hsl(var(--input) / .3)}.dark\:data-\[state\=checked\]\:bg-primary[data-state=checked]:is(.dark *){background-color:hsl(var(--primary))}.dark\:data-\[state\=checked\]\:bg-primary-foreground[data-state=checked]:is(.dark *){background-color:hsl(var(--primary-foreground))}.dark\:data-\[state\=unchecked\]\:bg-foreground[data-state=unchecked]:is(.dark *){background-color:hsl(var(--foreground))}.dark\:data-\[state\=unchecked\]\:bg-input\/80[data-state=unchecked]:is(.dark *){background-color:hsl(var(--input) / .8)}.dark\:data-\[state\=active\]\:text-foreground[data-state=active]:is(.dark *){color:hsl(var(--foreground))}.dark\:data-\[variant\=destructive\]\:focus\:bg-destructive\/20:focus[data-variant=destructive]:is(.dark *){background-color:hsl(var(--destructive) / .2)}@media(min-width:640px){.sm\:block{display:block}.sm\:inline-block{display:inline-block}.sm\:inline{display:inline}.sm\:flex{display:flex}.sm\:table-cell{display:table-cell}.sm\:max-w-\[300px\]{max-width:300px}.sm\:max-w-\[480px\]{max-width:480px}.sm\:max-w-\[620px\]{max-width:620px}.sm\:max-w-\[680px\]{max-width:680px}.sm\:max-w-lg{max-width:32rem}.sm\:max-w-md{max-width:28rem}.sm\:max-w-sm{max-width:24rem}.sm\:flex-row{flex-direction:row}.sm\:justify-end{justify-content:flex-end}.sm\:gap-2{gap:.5rem}.sm\:gap-2\.5{gap:.625rem}.sm\:pl-2\.5{padding-left:.625rem}.sm\:pr-2\.5{padding-right:.625rem}.sm\:text-left{text-align:left}.data-\[vaul-drawer-direction\=left\]\:sm\:max-w-sm[data-vaul-drawer-direction=left],.data-\[vaul-drawer-direction\=right\]\:sm\:max-w-sm[data-vaul-drawer-direction=right]{max-width:24rem}}@media(min-width:768px){.md\:absolute{position:absolute}.md\:block{display:block}.md\:inline{display:inline}.md\:flex{display:flex}.md\:table-cell{display:table-cell}.md\:w-\[var\(--radix-navigation-menu-viewport-width\)\]{width:var(--radix-navigation-menu-viewport-width)}.md\:w-auto{width:auto}.md\:max-w-\[400px\]{max-width:400px}.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.md\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.md\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.md\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.md\:flex-row{flex-direction:row}.md\:gap-1\.5{gap:.375rem}.md\:p-12{padding:3rem}.md\:text-left{text-align:left}.md\:text-sm{font-size:.875rem;line-height:1.25rem}.md\:opacity-0{opacity:0}.md\:after\:hidden:after{content:var(--tw-content);display:none}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:m-2{margin:.5rem}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:ml-0{margin-left:0}.peer[data-variant=inset][data-state=collapsed]~.md\:peer-data-\[variant\=inset\]\:peer-data-\[state\=collapsed\]\:ml-2{margin-left:.5rem}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:rounded-xl{border-radius:calc(var(--radius) + 4px)}.peer[data-variant=inset]~.md\:peer-data-\[variant\=inset\]\:shadow-sm{--tw-shadow: 0 1px 2px 0 rgb(0 0 0 / .05);--tw-shadow-colored: 0 1px 2px 0 var(--tw-shadow-color);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000),var(--tw-ring-shadow, 0 0 #0000),var(--tw-shadow)}}@media(min-width:1024px){.lg\:col-span-1{grid-column:span 1 / span 1}.lg\:col-span-2{grid-column:span 2 / span 2}.lg\:col-span-3{grid-column:span 3 / span 3}.lg\:table-cell{display:table-cell}.lg\:w-\[360px\]{width:360px}.lg\:w-\[400px\]{width:400px}.lg\:w-\[480px\]{width:480px}.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.lg\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}.lg\:grid-cols-4{grid-template-columns:repeat(4,minmax(0,1fr))}.lg\:grid-cols-5{grid-template-columns:repeat(5,minmax(0,1fr))}.lg\:grid-cols-6{grid-template-columns:repeat(6,minmax(0,1fr))}}@media(min-width:1280px){.xl\:table-cell{display:table-cell}.xl\:grid-cols-3{grid-template-columns:repeat(3,minmax(0,1fr))}}.\[\&\+\[data-slot\=item-content\]\]\:flex-none+[data-slot=item-content]{flex:none}.\[\&\:first-child\[data-selected\=true\]_button\]\:rounded-l-md:first-child[data-selected=true] button{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.\[\&\:has\(\[role\=checkbox\]\)\]\:pr-0:has([role=checkbox]){padding-right:0}.\[\&\:last-child\[data-selected\=true\]_button\]\:rounded-r-md:last-child[data-selected=true] button{border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\[\&\:nth-child\(2\)\[data-selected\=true\]_button\]\:rounded-l-md:nth-child(2)[data-selected=true] button{border-top-left-radius:calc(var(--radius) - 2px);border-bottom-left-radius:calc(var(--radius) - 2px)}.\[\&\>\*\:not\(\:first-child\)\]\:rounded-l-none>*:not(:first-child){border-top-left-radius:0;border-bottom-left-radius:0}.\[\&\>\*\:not\(\:first-child\)\]\:rounded-t-none>*:not(:first-child){border-top-left-radius:0;border-top-right-radius:0}.\[\&\>\*\:not\(\:first-child\)\]\:border-l-0>*:not(:first-child){border-left-width:0px}.\[\&\>\*\:not\(\:first-child\)\]\:border-t-0>*:not(:first-child){border-top-width:0px}.\[\&\>\*\:not\(\:last-child\)\]\:rounded-b-none>*:not(:last-child){border-bottom-right-radius:0;border-bottom-left-radius:0}.\[\&\>\*\:not\(\:last-child\)\]\:rounded-r-none>*:not(:last-child){border-top-right-radius:0;border-bottom-right-radius:0}.\[\&\>\*\]\:w-full>*{width:100%}.\[\&\>\*\]\:focus-visible\:relative:focus-visible>*{position:relative}.\[\&\>\*\]\:focus-visible\:z-10:focus-visible>*{z-index:10}.\[\&\>\*\]\:data-\[slot\=field\]\:p-4[data-slot=field]>*{padding:1rem}.\[\&\>\.sr-only\]\:w-auto>.sr-only{width:auto}.\[\&\>\[data-slot\=field-group\]\]\:gap-4>[data-slot=field-group]{gap:1rem}.\[\&\>\[data-slot\=field-label\]\]\:flex-auto>[data-slot=field-label]{flex:1 1 auto}.\[\&\>\[data-slot\=progress-indicator\]\]\:bg-amber-500>[data-slot=progress-indicator]{--tw-bg-opacity: 1;background-color:rgb(245 158 11 / var(--tw-bg-opacity, 1))}.\[\&\>\[data-slot\=progress-indicator\]\]\:bg-emerald-500>[data-slot=progress-indicator]{--tw-bg-opacity: 1;background-color:rgb(16 185 129 / var(--tw-bg-opacity, 1))}.\[\&\>\[data-slot\=progress-indicator\]\]\:bg-red-500>[data-slot=progress-indicator]{--tw-bg-opacity: 1;background-color:rgb(239 68 68 / var(--tw-bg-opacity, 1))}.has-\[select\[aria-hidden\=true\]\:last-child\]\:\[\&\>\[data-slot\=select-trigger\]\:last-of-type\]\:rounded-r-md>[data-slot=select-trigger]:last-of-type:has(select[aria-hidden=true]:last-child){border-top-right-radius:calc(var(--radius) - 2px);border-bottom-right-radius:calc(var(--radius) - 2px)}.\[\&\>\[data-slot\=select-trigger\]\:not\(\[class\*\=\'w-\'\]\)\]\:w-fit>[data-slot=select-trigger]:not([class*=w-]){width:-moz-fit-content;width:fit-content}.\[\&\>\[role\=checkbox\]\]\:translate-y-\[2px\]>[role=checkbox]{--tw-translate-y: 2px;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\>a\:hover\]\:text-primary>a:hover{color:hsl(var(--primary))}.\[\&\>a\]\:underline>a{text-decoration-line:underline}.\[\&\>a\]\:underline-offset-4>a{text-underline-offset:4px}.\[\&\>button\]\:hidden>button{display:none}.\[\&\>input\]\:flex-1>input{flex:1 1 0%}.has-\[\>\[data-align\=block-end\]\]\:\[\&\>input\]\:pt-3>input:has(>[data-align=block-end]){padding-top:.75rem}.has-\[\>\[data-align\=block-start\]\]\:\[\&\>input\]\:pb-3>input:has(>[data-align=block-start]){padding-bottom:.75rem}.has-\[\>\[data-align\=inline-end\]\]\:\[\&\>input\]\:pr-2>input:has(>[data-align=inline-end]){padding-right:.5rem}.has-\[\>\[data-align\=inline-start\]\]\:\[\&\>input\]\:pl-2>input:has(>[data-align=inline-start]){padding-left:.5rem}.\[\&\>kbd\]\:rounded-\[calc\(var\(--radius\)-5px\)\]>kbd{border-radius:calc(var(--radius) - 5px)}.\[\&\>span\:last-child\]\:truncate>span:last-child{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.\[\&\>span\]\:text-xs>span{font-size:.75rem;line-height:1rem}.\[\&\>span\]\:opacity-70>span{opacity:.7}.\[\&\>svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-3\.5>svg:not([class*=size-]){width:.875rem;height:.875rem}.\[\&\>svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-4>svg:not([class*=size-]){width:1rem;height:1rem}.\[\&\>svg\]\:pointer-events-none>svg{pointer-events:none}.\[\&\>svg\]\:size-3>svg{width:.75rem;height:.75rem}.\[\&\>svg\]\:size-3\.5>svg{width:.875rem;height:.875rem}.\[\&\>svg\]\:size-4>svg{width:1rem;height:1rem}.\[\&\>svg\]\:h-2\.5>svg{height:.625rem}.\[\&\>svg\]\:h-3>svg{height:.75rem}.\[\&\>svg\]\:w-2\.5>svg{width:.625rem}.\[\&\>svg\]\:w-3>svg{width:.75rem}.\[\&\>svg\]\:shrink-0>svg{flex-shrink:0}.\[\&\>svg\]\:translate-y-0\.5>svg{--tw-translate-y: .125rem;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\>svg\]\:text-current>svg{color:currentColor}.\[\&\>svg\]\:text-muted-foreground>svg{color:hsl(var(--muted-foreground))}.\[\&\>svg\]\:text-sidebar-accent-foreground>svg{color:hsl(var(--sidebar-accent-foreground))}.\[\&\>tr\]\:last\:border-b-0:last-child>tr{border-bottom-width:0px}.\[\&\[data-panel-group-direction\=vertical\]\>div\]\:rotate-90[data-panel-group-direction=vertical]>div{--tw-rotate: 90deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&\[data-state\=open\]\>svg\]\:rotate-180[data-state=open]>svg{--tw-rotate: 180deg;transform:translate(var(--tw-translate-x),var(--tw-translate-y)) rotate(var(--tw-rotate)) skew(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}.\[\&_\.recharts-cartesian-axis-tick_text\]\:fill-muted-foreground .recharts-cartesian-axis-tick text{fill:hsl(var(--muted-foreground))}.\[\&_\.recharts-cartesian-grid_line\[stroke\=\'\#ccc\'\]\]\:stroke-border\/50 .recharts-cartesian-grid line[stroke="#ccc"]{stroke:hsl(var(--border) / .5)}.\[\&_\.recharts-curve\.recharts-tooltip-cursor\]\:stroke-border .recharts-curve.recharts-tooltip-cursor{stroke:hsl(var(--border))}.\[\&_\.recharts-dot\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-dot[stroke="#fff"]{stroke:transparent}.\[\&_\.recharts-polar-grid_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-polar-grid [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-radial-bar-background-sector\]\:fill-muted .recharts-radial-bar-background-sector,.\[\&_\.recharts-rectangle\.recharts-tooltip-cursor\]\:fill-muted .recharts-rectangle.recharts-tooltip-cursor{fill:hsl(var(--muted))}.\[\&_\.recharts-reference-line_\[stroke\=\'\#ccc\'\]\]\:stroke-border .recharts-reference-line [stroke="#ccc"]{stroke:hsl(var(--border))}.\[\&_\.recharts-sector\[stroke\=\'\#fff\'\]\]\:stroke-transparent .recharts-sector[stroke="#fff"]{stroke:transparent}.\[\&_\[cmdk-group-heading\]\]\:px-2 [cmdk-group-heading]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-group-heading\]\]\:py-1\.5 [cmdk-group-heading]{padding-top:.375rem;padding-bottom:.375rem}.\[\&_\[cmdk-group-heading\]\]\:text-xs [cmdk-group-heading]{font-size:.75rem;line-height:1rem}.\[\&_\[cmdk-group-heading\]\]\:font-medium [cmdk-group-heading]{font-weight:500}.\[\&_\[cmdk-group-heading\]\]\:text-muted-foreground [cmdk-group-heading]{color:hsl(var(--muted-foreground))}.\[\&_\[cmdk-group\]\:not\(\[hidden\]\)_\~\[cmdk-group\]\]\:pt-0 [cmdk-group]:not([hidden])~[cmdk-group]{padding-top:0}.\[\&_\[cmdk-group\]\]\:px-2 [cmdk-group]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:h-5 [cmdk-input-wrapper] svg{height:1.25rem}.\[\&_\[cmdk-input-wrapper\]_svg\]\:w-5 [cmdk-input-wrapper] svg{width:1.25rem}.\[\&_\[cmdk-input\]\]\:h-12 [cmdk-input]{height:3rem}.\[\&_\[cmdk-item\]\]\:px-2 [cmdk-item]{padding-left:.5rem;padding-right:.5rem}.\[\&_\[cmdk-item\]\]\:py-3 [cmdk-item]{padding-top:.75rem;padding-bottom:.75rem}.\[\&_\[cmdk-item\]_svg\]\:h-5 [cmdk-item] svg{height:1.25rem}.\[\&_\[cmdk-item\]_svg\]\:w-5 [cmdk-item] svg{width:1.25rem}.\[\&_img\]\:size-full img{width:100%;height:100%}.\[\&_img\]\:object-cover img{-o-object-fit:cover;object-fit:cover}.\[\&_p\]\:leading-relaxed p{line-height:1.625}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-3 svg:not([class*=size-]){width:.75rem;height:.75rem}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-4 svg:not([class*=size-]){width:1rem;height:1rem}.\[\&_svg\:not\(\[class\*\=\'size-\'\]\)\]\:size-6 svg:not([class*=size-]){width:1.5rem;height:1.5rem}.\[\&_svg\:not\(\[class\*\=\'text-\'\]\)\]\:text-muted-foreground svg:not([class*=text-]){color:hsl(var(--muted-foreground))}.\[\&_svg\]\:pointer-events-none svg{pointer-events:none}.\[\&_svg\]\:shrink-0 svg{flex-shrink:0}.\[\&_tr\:last-child\]\:border-0 tr:last-child{border-width:0px}.\[\&_tr\]\:border-b tr{border-bottom-width:1px}[data-side=left][data-collapsible=offcanvas] .\[\[data-side\=left\]\[data-collapsible\=offcanvas\]_\&\]\:-right-2{right:-.5rem}[data-side=left][data-state=collapsed] .\[\[data-side\=left\]\[data-state\=collapsed\]_\&\]\:cursor-e-resize{cursor:e-resize}[data-side=right][data-collapsible=offcanvas] .\[\[data-side\=right\]\[data-collapsible\=offcanvas\]_\&\]\:-left-2{left:-.5rem}[data-side=right][data-state=collapsed] .\[\[data-side\=right\]\[data-state\=collapsed\]_\&\]\:cursor-w-resize{cursor:w-resize}[data-slot=card-content] .\[\[data-slot\=card-content\]_\&\]\:bg-transparent,[data-slot=popover-content] .\[\[data-slot\=popover-content\]_\&\]\:bg-transparent{background-color:transparent}[data-slot=tooltip-content] .\[\[data-slot\=tooltip-content\]_\&\]\:bg-background\/20{background-color:hsl(var(--background) / .2)}[data-slot=tooltip-content] .\[\[data-slot\=tooltip-content\]_\&\]\:text-background{color:hsl(var(--background))}[data-slot=tooltip-content] .dark\:\[\[data-slot\=tooltip-content\]_\&\]\:bg-background\/10:is(.dark *){background-color:hsl(var(--background) / .1)}[data-variant=legend]+.\[\[data-variant\=legend\]\+\&\]\:-mt-1\.5{margin-top:-.375rem}a.\[a\&\]\:hover\:bg-accent:hover{background-color:hsl(var(--accent))}a.\[a\&\]\:hover\:bg-destructive\/90:hover{background-color:hsl(var(--destructive) / .9)}a.\[a\&\]\:hover\:bg-primary\/90:hover{background-color:hsl(var(--primary) / .9)}a.\[a\&\]\:hover\:bg-secondary\/90:hover{background-color:hsl(var(--secondary) / .9)}a.\[a\&\]\:hover\:text-accent-foreground:hover{color:hsl(var(--accent-foreground))} diff --git a/backend/static/assets/index-CHhHmizP.js b/backend/static/assets/index-CHhHmizP.js new file mode 100644 index 0000000..40b29bb --- /dev/null +++ b/backend/static/assets/index-CHhHmizP.js @@ -0,0 +1 @@ +import{l as s,u as i}from"./index-DfyorCky.js";import{d as e}from"./dashboard-BjQPIG2G.js";import{r as t,s as A}from"./server-CjDPBaTN.js";import{k as m}from"./kubernetes-J8O09fK7.js";import{c as d,d as x,p as f,s as c}from"./deploy-B3Sg3N1U.js";import{c as u,s as g,t as k}from"./automation-mtL167W_.js";import{a as C,b as h,d as z,p as D,s as S,t as y,z as E}from"./monitor-BAaBXIsC.js";import{a as L}from"./agent-DqqIRCQX.js";import{b as q,c as w,p as B}from"./cloud-Dzoer-2i.js";import{b as G,a as H,l as I,s as K,t as M}from"./system-BgtMMm0X.js";import{a as O}from"./ai-BTgmlP5Q.js";export{L as agentApi,O as aiApi,C as alertApi,h as alertCenterApi,G as approvalApi,H as auditApi,q as billingApi,w as cloudApi,d as credentialApi,u as cronJobApi,z as dashboardApi,e as dashboardStatsApi,x as deployApi,m as kubernetesApi,s as ldapApi,I as loginLogApi,f as pipelineApi,B as platformApi,D as promDatasourceApi,t as regionApi,g as scriptApi,A as serverApi,c as serverCredentialApi,K as sessionCommandApi,S as siteApi,k as taskExecutionApi,M as terminalSessionApi,y as traceApi,i as userApi,E as zabbixDatasourceApi}; diff --git a/backend/static/assets/index-CWVNW_qu.js b/backend/static/assets/index-CWVNW_qu.js new file mode 100644 index 0000000..ddedb13 --- /dev/null +++ b/backend/static/assets/index-CWVNW_qu.js @@ -0,0 +1 @@ +import{r as u}from"./index-DfyorCky.js";function o(r){const e=u.useRef({value:r,previous:r});return u.useMemo(()=>(e.current.value!==r&&(e.current.previous=e.current.value,e.current.value=r),e.current.previous),[r])}export{o as u}; diff --git a/backend/static/assets/index-DfyorCky.js b/backend/static/assets/index-DfyorCky.js new file mode 100644 index 0000000..27c4d56 --- /dev/null +++ b/backend/static/assets/index-DfyorCky.js @@ -0,0 +1,103 @@ +const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./Dashboard-iCzLAtNG.js","./dashboard-BjQPIG2G.js","./server-CjDPBaTN.js","./kubernetes-J8O09fK7.js","./card-C55cvSHg.js","./trending-up-CdusV6gc.js","./trending-down-BGTWG_dA.js","./minus-UVrx3jLc.js","./badge-xNW8x0G1.js","./hard-drive-BbPmnARR.js","./generateCategoricalChart-6v9BPbG2.js","./AreaChart-B2zlWfdX.js","./BarChart-DlFprovY.js","./memory-stick-QMV-0CnU.js","./arrow-right-DyIltvNZ.js","./circle-DOZr6_68.js","./ServerManager-JxMW-hQt.js","./checkbox-CH0bpj6b.js","./index-CWVNW_qu.js","./table-5sHV4Akp.js","./select-D5qUzdAs.js","./rotate-cw-5qcj_h_q.js","./index-a3ybMjbR.js","./cloud-Dzoer-2i.js","./refresh-cw-DUB_tAG-.js","./xterm-DSqgeKvr.js","./xterm-DXOU9pbP.css","./deploy-B3Sg3N1U.js","./minimize-2-CiCQYRfn.js","./folder-open-IMBifk-r.js","./upload-Ba6rlaGS.js","./folder-DoMwqvzv.js","./arrow-left-BDgGyrD0.js","./download-DoZfYs2h.js","./trash-2-Dx32pOzT.js","./label-BK0h2apY.js","./textarea-NXY8u32k.js","./save-DoGGjfwC.js","./ellipsis-DU5enAwm.js","./square-pen-BxUFAe0F.js","./plus-CUG-9kpu.js","./CloudAccountManager-DU9759_X.js","./circle-check-DWcXrx2k.js","./circle-x-DK79Dhg2.js","./pencil-BqUotcjf.js","./DomainManager-CIA5bu9u.js","./RegionManager-Bj8EPK6w.js","./PlatformManager-DvSL1hbm.js","./external-link-CzIpMNu1.js","./CloudBilling-BUyc8wKP.js","./switch-CGiGgOnh.js","./KubernetesClusters-CsRHjVkA.js","./tabs-CIh_yD4s.js","./ClusterOverviewPage-CYcNLUM0.js","./use-toast-CrSOP4cJ.js","./NodeDetailPage-MBEvAdV0.js","./NamespaceOverviewPage-qjFlj_lA.js","./file-text-C9G5abwR.js","./NamespaceManagementPage-Do5kDmHW.js","./NamespaceResourcePage-Byljvm8v.js","./PodFileBrowser-BySN2XGN.js","./copy-DXW4LnkN.js","./sparkles-Bld4NX5y.js","./box-TTGA1p57.js","./DeploymentDetailPage--48QYro1.js","./history-D_9jPUQg.js","./play-cdPayOtJ.js","./zap-D2uWSK32.js","./disc-EsE6x5Oh.js","./pause-D_famo9P.js","./WorkloadViewPage-Koq6nkyo.js","./tag-0HCfq8kH.js","./TopologyView-scPjlVYA.js","./KubernetesNodes-DNrQwI__.js","./PodMetricsPage-DjvvN_IG.js","./EventsPage-Dbw7LuoJ.js","./layers-FW4KKJMi.js","./CapacityPage-Dz7l4ubk.js","./AlertManager-BaUrn6Bk.js","./monitor-BAaBXIsC.js","./AlertRuleDialog-DnF-_Zoj.js","./message-square-DyxabBvb.js","./phone-DgvWDdJl.js","./ApprovalFlow-5mIFjuJZ.js","./system-BgtMMm0X.js","./funnel-D2FHr15I.js","./ScriptManager-BFWlhlzw.js","./automation-mtL167W_.js","./SystemManager-D4SbaG04.js","./user-plus-BwUWtcQl.js","./AuditPage-BdPy-cgE.js","./CredentialManager-DlhOOSIa.js","./PipelineManager-C1vaTQ2Z.js","./shield-check-Dcx486cW.js","./code-L62jFLTC.js","./circle-stop-s4wxdTEV.js","./DeployCredentials-XbkP4xDn.js","./wrench-KfbhOOJm.js","./PipelineEditor-DrEZIuvh.js","./PipelineRunDetail-CwWLRhgo.js","./square-9TIYDO_t.js","./DeployRBAC-QV1xM1Jn.js","./UserGroupsManager-nOJ7di7Y.js","./CronJobManager-BMfKpm0z.js","./package-open-CUXo2Tda.js","./AIOpsAssistant-DFQDT-tz.js","./agent-DqqIRCQX.js","./ai-BTgmlP5Q.js","./wifi-FqsslTyA.js","./AIAlertAnalyzer-B9ptAIV7.js","./AIPredictiveAnalytics-Dr8sfqna.js","./AlertCenter-C3WMw6jA.js","./TraceManager-D4FRDBfs.js","./HostMonitor-C63FMElJ.js","./GrafanaDashboard-BoB6WmDi.js","./arrow-up-down-DnvTt5VG.js","./MonitorCenter-Cdfxw79h.js","./MetricsExplorer-CQYGy4Dt.js","./DatasourcePage-brk0z6d8.js"])))=>i.map(i=>d[i]); +function PS(n,r){for(var l=0;ls[i]})}}}return Object.freeze(Object.defineProperty(n,Symbol.toStringTag,{value:"Module"}))}(function(){const r=document.createElement("link").relList;if(r&&r.supports&&r.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))s(i);new MutationObserver(i=>{for(const u of i)if(u.type==="childList")for(const f of u.addedNodes)f.tagName==="LINK"&&f.rel==="modulepreload"&&s(f)}).observe(document,{childList:!0,subtree:!0});function l(i){const u={};return i.integrity&&(u.integrity=i.integrity),i.referrerPolicy&&(u.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?u.credentials="include":i.crossOrigin==="anonymous"?u.credentials="omit":u.credentials="same-origin",u}function s(i){if(i.ep)return;i.ep=!0;const u=l(i);fetch(i.href,u)}})();var IO=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ly(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}var nd={exports:{}},Xo={};var Lg;function qS(){if(Lg)return Xo;Lg=1;var n=Symbol.for("react.transitional.element"),r=Symbol.for("react.fragment");function l(s,i,u){var f=null;if(u!==void 0&&(f=""+u),i.key!==void 0&&(f=""+i.key),"key"in i){u={};for(var p in i)p!=="key"&&(u[p]=i[p])}else u=i;return i=u.ref,{$$typeof:n,type:s,key:f,ref:i!==void 0?i:null,props:u}}return Xo.Fragment=r,Xo.jsx=l,Xo.jsxs=l,Xo}var Hg;function VS(){return Hg||(Hg=1,nd.exports=qS()),nd.exports}var h=VS(),ad={exports:{}},ye={};var Ug;function GS(){if(Ug)return ye;Ug=1;var n=Symbol.for("react.transitional.element"),r=Symbol.for("react.portal"),l=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),u=Symbol.for("react.consumer"),f=Symbol.for("react.context"),p=Symbol.for("react.forward_ref"),g=Symbol.for("react.suspense"),v=Symbol.for("react.memo"),x=Symbol.for("react.lazy"),b=Symbol.for("react.activity"),w=Symbol.iterator;function A(T){return T===null||typeof T!="object"?null:(T=w&&T[w]||T["@@iterator"],typeof T=="function"?T:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C=Object.assign,E={};function M(T,Y,F){this.props=T,this.context=Y,this.refs=E,this.updater=F||_}M.prototype.isReactComponent={},M.prototype.setState=function(T,Y){if(typeof T!="object"&&typeof T!="function"&&T!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,T,Y,"setState")},M.prototype.forceUpdate=function(T){this.updater.enqueueForceUpdate(this,T,"forceUpdate")};function H(){}H.prototype=M.prototype;function D(T,Y,F){this.props=T,this.context=Y,this.refs=E,this.updater=F||_}var j=D.prototype=new H;j.constructor=D,C(j,M.prototype),j.isPureReactComponent=!0;var q=Array.isArray;function Z(){}var G={H:null,A:null,T:null,S:null},K=Object.prototype.hasOwnProperty;function W(T,Y,F){var J=F.ref;return{$$typeof:n,type:T,key:Y,ref:J!==void 0?J:null,props:F}}function se(T,Y){return W(T.type,Y,T.props)}function he(T){return typeof T=="object"&&T!==null&&T.$$typeof===n}function ge(T){var Y={"=":"=0",":":"=2"};return"$"+T.replace(/[=:]/g,function(F){return Y[F]})}var Ae=/\/+/g;function xe(T,Y){return typeof T=="object"&&T!==null&&T.key!=null?ge(""+T.key):Y.toString(36)}function ve(T){switch(T.status){case"fulfilled":return T.value;case"rejected":throw T.reason;default:switch(typeof T.status=="string"?T.then(Z,Z):(T.status="pending",T.then(function(Y){T.status==="pending"&&(T.status="fulfilled",T.value=Y)},function(Y){T.status==="pending"&&(T.status="rejected",T.reason=Y)})),T.status){case"fulfilled":return T.value;case"rejected":throw T.reason}}throw T}function z(T,Y,F,J,ce){var me=typeof T;(me==="undefined"||me==="boolean")&&(T=null);var te=!1;if(T===null)te=!0;else switch(me){case"bigint":case"string":case"number":te=!0;break;case"object":switch(T.$$typeof){case n:case r:te=!0;break;case x:return te=T._init,z(te(T._payload),Y,F,J,ce)}}if(te)return ce=ce(T),te=J===""?"."+xe(T,0):J,q(ce)?(F="",te!=null&&(F=te.replace(Ae,"$&/")+"/"),z(ce,Y,F,"",function(qt){return qt})):ce!=null&&(he(ce)&&(ce=se(ce,F+(ce.key==null||T&&T.key===ce.key?"":(""+ce.key).replace(Ae,"$&/")+"/")+te)),Y.push(ce)),1;te=0;var Qe=J===""?".":J+":";if(q(T))for(var Le=0;Le>>1,pe=z[I];if(0>>1;Ii(F,P))Ji(ce,F)?(z[I]=ce,z[J]=P,I=J):(z[I]=F,z[Y]=P,I=Y);else if(Ji(ce,P))z[I]=ce,z[J]=P,I=J;else break e}}return $}function i(z,$){var P=z.sortIndex-$.sortIndex;return P!==0?P:z.id-$.id}if(n.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var u=performance;n.unstable_now=function(){return u.now()}}else{var f=Date,p=f.now();n.unstable_now=function(){return f.now()-p}}var g=[],v=[],x=1,b=null,w=3,A=!1,_=!1,C=!1,E=!1,M=typeof setTimeout=="function"?setTimeout:null,H=typeof clearTimeout=="function"?clearTimeout:null,D=typeof setImmediate<"u"?setImmediate:null;function j(z){for(var $=l(v);$!==null;){if($.callback===null)s(v);else if($.startTime<=z)s(v),$.sortIndex=$.expirationTime,r(g,$);else break;$=l(v)}}function q(z){if(C=!1,j(z),!_)if(l(g)!==null)_=!0,Z||(Z=!0,ge());else{var $=l(v);$!==null&&ve(q,$.startTime-z)}}var Z=!1,G=-1,K=5,W=-1;function se(){return E?!0:!(n.unstable_now()-Wz&&se());){var I=b.callback;if(typeof I=="function"){b.callback=null,w=b.priorityLevel;var pe=I(b.expirationTime<=z);if(z=n.unstable_now(),typeof pe=="function"){b.callback=pe,j(z),$=!0;break t}b===l(g)&&s(g),j(z)}else s(g);b=l(g)}if(b!==null)$=!0;else{var T=l(v);T!==null&&ve(q,T.startTime-z),$=!1}}break e}finally{b=null,w=P,A=!1}$=void 0}}finally{$?ge():Z=!1}}}var ge;if(typeof D=="function")ge=function(){D(he)};else if(typeof MessageChannel<"u"){var Ae=new MessageChannel,xe=Ae.port2;Ae.port1.onmessage=he,ge=function(){xe.postMessage(null)}}else ge=function(){M(he,0)};function ve(z,$){G=M(function(){z(n.unstable_now())},$)}n.unstable_IdlePriority=5,n.unstable_ImmediatePriority=1,n.unstable_LowPriority=4,n.unstable_NormalPriority=3,n.unstable_Profiling=null,n.unstable_UserBlockingPriority=2,n.unstable_cancelCallback=function(z){z.callback=null},n.unstable_forceFrameRate=function(z){0>z||125I?(z.sortIndex=P,r(v,z),l(g)===null&&z===l(v)&&(C?(H(G),G=-1):C=!0,ve(q,P-I))):(z.sortIndex=pe,r(g,z),_||A||(_=!0,Z||(Z=!0,ge()))),z},n.unstable_shouldYield=se,n.unstable_wrapCallback=function(z){var $=w;return function(){var P=w;w=$;try{return z.apply(this,arguments)}finally{w=P}}}})(ld)),ld}var qg;function XS(){return qg||(qg=1,od.exports=YS()),od.exports}var sd={exports:{}},ft={};var Vg;function QS(){if(Vg)return ft;Vg=1;var n=Zd();function r(g){var v="https://react.dev/errors/"+g;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(r){console.error(r)}}return n(),sd.exports=QS(),sd.exports}var Yg;function KS(){if(Yg)return Qo;Yg=1;var n=XS(),r=Zd(),l=sy();function s(e){var t="https://react.dev/errors/"+e;if(1pe||(e.current=I[pe],I[pe]=null,pe--)}function F(e,t){pe++,I[pe]=e.current,e.current=t}var J=T(null),ce=T(null),me=T(null),te=T(null);function Qe(e,t){switch(F(me,t),F(ce,e),F(J,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?og(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=og(t),e=lg(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}Y(J),F(J,e)}function Le(){Y(J),Y(ce),Y(me)}function qt(e){e.memoizedState!==null&&F(te,e);var t=J.current,a=lg(t,e.type);t!==a&&(F(ce,e),F(J,a))}function dn(e){ce.current===e&&(Y(J),Y(ce)),te.current===e&&(Y(te),qo._currentValue=P)}var fn,Ca;function _a(e){if(fn===void 0)try{throw Error()}catch(a){var t=a.stack.trim().match(/\n( *(at )?)/);fn=t&&t[1]||"",Ca=-1)":-1c||R[o]!==L[c]){var V=` +`+R[o].replace(" at new "," at ");return e.displayName&&V.includes("")&&(V=V.replace("",e.displayName)),V}while(1<=o&&0<=c);break}}}finally{Bi=!1,Error.prepareStackTrace=a}return(a=e?e.displayName||e.name:"")?_a(a):""}function v0(e,t){switch(e.tag){case 26:case 27:case 5:return _a(e.type);case 16:return _a("Lazy");case 13:return e.child!==t&&t!==null?_a("Suspense Fallback"):_a("Suspense");case 19:return _a("SuspenseList");case 0:case 15:return Pi(e.type,!1);case 11:return Pi(e.type.render,!1);case 1:return Pi(e.type,!0);case 31:return _a("Activity");default:return""}}function Lf(e){try{var t="",a=null;do t+=v0(e,a),a=e,e=e.return;while(e);return t}catch(o){return` +Error generating stack: `+o.message+` +`+o.stack}}var qi=Object.prototype.hasOwnProperty,Vi=n.unstable_scheduleCallback,Gi=n.unstable_cancelCallback,y0=n.unstable_shouldYield,x0=n.unstable_requestPaint,Rt=n.unstable_now,b0=n.unstable_getCurrentPriorityLevel,Hf=n.unstable_ImmediatePriority,Uf=n.unstable_UserBlockingPriority,pl=n.unstable_NormalPriority,S0=n.unstable_LowPriority,Bf=n.unstable_IdlePriority,w0=n.log,E0=n.unstable_setDisableYieldValue,Jr=null,Tt=null;function $n(e){if(typeof w0=="function"&&E0(e),Tt&&typeof Tt.setStrictMode=="function")try{Tt.setStrictMode(Jr,e)}catch{}}var Mt=Math.clz32?Math.clz32:_0,A0=Math.log,C0=Math.LN2;function _0(e){return e>>>=0,e===0?32:31-(A0(e)/C0|0)|0}var ml=256,gl=262144,vl=4194304;function Ra(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function yl(e,t,a){var o=e.pendingLanes;if(o===0)return 0;var c=0,d=e.suspendedLanes,y=e.pingedLanes;e=e.warmLanes;var S=o&134217727;return S!==0?(o=S&~d,o!==0?c=Ra(o):(y&=S,y!==0?c=Ra(y):a||(a=S&~e,a!==0&&(c=Ra(a))))):(S=o&~d,S!==0?c=Ra(S):y!==0?c=Ra(y):a||(a=o&~e,a!==0&&(c=Ra(a)))),c===0?0:t!==0&&t!==c&&(t&d)===0&&(d=c&-c,a=t&-t,d>=a||d===32&&(a&4194048)!==0)?t:c}function Wr(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function R0(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function Pf(){var e=vl;return vl<<=1,(vl&62914560)===0&&(vl=4194304),e}function Yi(e){for(var t=[],a=0;31>a;a++)t.push(e);return t}function eo(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function T0(e,t,a,o,c,d){var y=e.pendingLanes;e.pendingLanes=a,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=a,e.entangledLanes&=a,e.errorRecoveryDisabledLanes&=a,e.shellSuspendCounter=0;var S=e.entanglements,R=e.expirationTimes,L=e.hiddenUpdates;for(a=y&~a;0"u")return null;try{return e.activeElement||e.body}catch{return e.body}}var z0=/[\n"\\]/g;function Gt(e){return e.replace(z0,function(t){return"\\"+t.charCodeAt(0).toString(16)+" "})}function Zi(e,t,a,o,c,d,y,S){e.name="",y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"?e.type=y:e.removeAttribute("type"),t!=null?y==="number"?(t===0&&e.value===""||e.value!=t)&&(e.value=""+Vt(t)):e.value!==""+Vt(t)&&(e.value=""+Vt(t)):y!=="submit"&&y!=="reset"||e.removeAttribute("value"),t!=null?Ii(e,y,Vt(t)):a!=null?Ii(e,y,Vt(a)):o!=null&&e.removeAttribute("value"),c==null&&d!=null&&(e.defaultChecked=!!d),c!=null&&(e.checked=c&&typeof c!="function"&&typeof c!="symbol"),S!=null&&typeof S!="function"&&typeof S!="symbol"&&typeof S!="boolean"?e.name=""+Vt(S):e.removeAttribute("name")}function Wf(e,t,a,o,c,d,y,S){if(d!=null&&typeof d!="function"&&typeof d!="symbol"&&typeof d!="boolean"&&(e.type=d),t!=null||a!=null){if(!(d!=="submit"&&d!=="reset"||t!=null)){Fi(e);return}a=a!=null?""+Vt(a):"",t=t!=null?""+Vt(t):a,S||t===e.value||(e.value=t),e.defaultValue=t}o=o??c,o=typeof o!="function"&&typeof o!="symbol"&&!!o,e.checked=S?e.checked:!!o,e.defaultChecked=!!o,y!=null&&typeof y!="function"&&typeof y!="symbol"&&typeof y!="boolean"&&(e.name=y),Fi(e)}function Ii(e,t,a){t==="number"&&Sl(e.ownerDocument)===e||e.defaultValue===""+a||(e.defaultValue=""+a)}function nr(e,t,a,o){if(e=e.options,t){t={};for(var c=0;c"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),nc=!1;if(Rn)try{var ro={};Object.defineProperty(ro,"passive",{get:function(){nc=!0}}),window.addEventListener("test",ro,ro),window.removeEventListener("test",ro,ro)}catch{nc=!1}var Zn=null,ac=null,El=null;function lh(){if(El)return El;var e,t=ac,a=t.length,o,c="value"in Zn?Zn.value:Zn.textContent,d=c.length;for(e=0;e=so),fh=" ",hh=!1;function ph(e,t){switch(e){case"keyup":return ib.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function mh(e){return e=e.detail,typeof e=="object"&&"data"in e?e.data:null}var lr=!1;function ub(e,t){switch(e){case"compositionend":return mh(t);case"keypress":return t.which!==32?null:(hh=!0,fh);case"textInput":return e=t.data,e===fh&&hh?null:e;default:return null}}function db(e,t){if(lr)return e==="compositionend"||!ic&&ph(e,t)?(e=lh(),El=ac=Zn=null,lr=!1,e):null;switch(e){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:a,offset:t-e};e=o}e:{for(;a;){if(a.nextSibling){a=a.nextSibling;break e}a=a.parentNode}a=void 0}a=Eh(a)}}function Ch(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ch(e,t.parentNode):"contains"in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function _h(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Sl(e.document);t instanceof e.HTMLIFrameElement;){try{var a=typeof t.contentWindow.location.href=="string"}catch{a=!1}if(a)e=t.contentWindow;else break;t=Sl(e.document)}return t}function dc(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t==="input"&&(e.type==="text"||e.type==="search"||e.type==="tel"||e.type==="url"||e.type==="password")||t==="textarea"||e.contentEditable==="true")}var xb=Rn&&"documentMode"in document&&11>=document.documentMode,sr=null,fc=null,fo=null,hc=!1;function Rh(e,t,a){var o=a.window===a?a.document:a.nodeType===9?a:a.ownerDocument;hc||sr==null||sr!==Sl(o)||(o=sr,"selectionStart"in o&&dc(o)?o={start:o.selectionStart,end:o.selectionEnd}:(o=(o.ownerDocument&&o.ownerDocument.defaultView||window).getSelection(),o={anchorNode:o.anchorNode,anchorOffset:o.anchorOffset,focusNode:o.focusNode,focusOffset:o.focusOffset}),fo&&uo(fo,o)||(fo=o,o=gs(fc,"onSelect"),0>=y,c-=y,hn=1<<32-Mt(t)+c|a<we?(Me=le,le=null):Me=le.sibling;var Ne=U(N,le,k[we],X);if(Ne===null){le===null&&(le=Me);break}e&&le&&Ne.alternate===null&&t(N,le),O=d(Ne,O,we),je===null?ie=Ne:je.sibling=Ne,je=Ne,le=Me}if(we===k.length)return a(N,le),Oe&&Mn(N,we),ie;if(le===null){for(;wewe?(Me=le,le=null):Me=le.sibling;var ya=U(N,le,Ne.value,X);if(ya===null){le===null&&(le=Me);break}e&&le&&ya.alternate===null&&t(N,le),O=d(ya,O,we),je===null?ie=ya:je.sibling=ya,je=ya,le=Me}if(Ne.done)return a(N,le),Oe&&Mn(N,we),ie;if(le===null){for(;!Ne.done;we++,Ne=k.next())Ne=Q(N,Ne.value,X),Ne!==null&&(O=d(Ne,O,we),je===null?ie=Ne:je.sibling=Ne,je=Ne);return Oe&&Mn(N,we),ie}for(le=o(le);!Ne.done;we++,Ne=k.next())Ne=B(le,N,we,Ne.value,X),Ne!==null&&(e&&Ne.alternate!==null&&le.delete(Ne.key===null?we:Ne.key),O=d(Ne,O,we),je===null?ie=Ne:je.sibling=Ne,je=Ne);return e&&le.forEach(function(BS){return t(N,BS)}),Oe&&Mn(N,we),ie}function Be(N,O,k,X){if(typeof k=="object"&&k!==null&&k.type===C&&k.key===null&&(k=k.props.children),typeof k=="object"&&k!==null){switch(k.$$typeof){case A:e:{for(var ie=k.key;O!==null;){if(O.key===ie){if(ie=k.type,ie===C){if(O.tag===7){a(N,O.sibling),X=c(O,k.props.children),X.return=N,N=X;break e}}else if(O.elementType===ie||typeof ie=="object"&&ie!==null&&ie.$$typeof===K&&Ua(ie)===O.type){a(N,O.sibling),X=c(O,k.props),yo(X,k),X.return=N,N=X;break e}a(N,O);break}else t(N,O);O=O.sibling}k.type===C?(X=Da(k.props.children,N.mode,X,k.key),X.return=N,N=X):(X=Dl(k.type,k.key,k.props,null,N.mode,X),yo(X,k),X.return=N,N=X)}return y(N);case _:e:{for(ie=k.key;O!==null;){if(O.key===ie)if(O.tag===4&&O.stateNode.containerInfo===k.containerInfo&&O.stateNode.implementation===k.implementation){a(N,O.sibling),X=c(O,k.children||[]),X.return=N,N=X;break e}else{a(N,O);break}else t(N,O);O=O.sibling}X=bc(k,N.mode,X),X.return=N,N=X}return y(N);case K:return k=Ua(k),Be(N,O,k,X)}if(ve(k))return ne(N,O,k,X);if(ge(k)){if(ie=ge(k),typeof ie!="function")throw Error(s(150));return k=ie.call(k),de(N,O,k,X)}if(typeof k.then=="function")return Be(N,O,Pl(k),X);if(k.$$typeof===D)return Be(N,O,Ll(N,k),X);ql(N,k)}return typeof k=="string"&&k!==""||typeof k=="number"||typeof k=="bigint"?(k=""+k,O!==null&&O.tag===6?(a(N,O.sibling),X=c(O,k),X.return=N,N=X):(a(N,O),X=xc(k,N.mode,X),X.return=N,N=X),y(N)):a(N,O)}return function(N,O,k,X){try{vo=0;var ie=Be(N,O,k,X);return yr=null,ie}catch(le){if(le===vr||le===Ul)throw le;var je=jt(29,le,null,N.mode);return je.lanes=X,je.return=N,je}}}var Pa=Zh(!0),Ih=Zh(!1),ta=!1;function Nc(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Dc(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function na(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function aa(e,t,a){var o=e.updateQueue;if(o===null)return null;if(o=o.shared,(De&2)!==0){var c=o.pending;return c===null?t.next=t:(t.next=c.next,c.next=t),o.pending=t,t=Nl(e),zh(e,null,a),t}return jl(e,o,t,a),Nl(e)}function xo(e,t,a){if(t=t.updateQueue,t!==null&&(t=t.shared,(a&4194048)!==0)){var o=t.lanes;o&=e.pendingLanes,a|=o,t.lanes=a,Vf(e,a)}}function zc(e,t){var a=e.updateQueue,o=e.alternate;if(o!==null&&(o=o.updateQueue,a===o)){var c=null,d=null;if(a=a.firstBaseUpdate,a!==null){do{var y={lane:a.lane,tag:a.tag,payload:a.payload,callback:null,next:null};d===null?c=d=y:d=d.next=y,a=a.next}while(a!==null);d===null?c=d=t:d=d.next=t}else c=d=t;a={baseState:o.baseState,firstBaseUpdate:c,lastBaseUpdate:d,shared:o.shared,callbacks:o.callbacks},e.updateQueue=a;return}e=a.lastBaseUpdate,e===null?a.firstBaseUpdate=t:e.next=t,a.lastBaseUpdate=t}var kc=!1;function bo(){if(kc){var e=gr;if(e!==null)throw e}}function So(e,t,a,o){kc=!1;var c=e.updateQueue;ta=!1;var d=c.firstBaseUpdate,y=c.lastBaseUpdate,S=c.shared.pending;if(S!==null){c.shared.pending=null;var R=S,L=R.next;R.next=null,y===null?d=L:y.next=L,y=R;var V=e.alternate;V!==null&&(V=V.updateQueue,S=V.lastBaseUpdate,S!==y&&(S===null?V.firstBaseUpdate=L:S.next=L,V.lastBaseUpdate=R))}if(d!==null){var Q=c.baseState;y=0,V=L=R=null,S=d;do{var U=S.lane&-536870913,B=U!==S.lane;if(B?(Te&U)===U:(o&U)===U){U!==0&&U===mr&&(kc=!0),V!==null&&(V=V.next={lane:0,tag:S.tag,payload:S.payload,callback:null,next:null});e:{var ne=e,de=S;U=t;var Be=a;switch(de.tag){case 1:if(ne=de.payload,typeof ne=="function"){Q=ne.call(Be,Q,U);break e}Q=ne;break e;case 3:ne.flags=ne.flags&-65537|128;case 0:if(ne=de.payload,U=typeof ne=="function"?ne.call(Be,Q,U):ne,U==null)break e;Q=b({},Q,U);break e;case 2:ta=!0}}U=S.callback,U!==null&&(e.flags|=64,B&&(e.flags|=8192),B=c.callbacks,B===null?c.callbacks=[U]:B.push(U))}else B={lane:U,tag:S.tag,payload:S.payload,callback:S.callback,next:null},V===null?(L=V=B,R=Q):V=V.next=B,y|=U;if(S=S.next,S===null){if(S=c.shared.pending,S===null)break;B=S,S=B.next,B.next=null,c.lastBaseUpdate=B,c.shared.pending=null}}while(!0);V===null&&(R=Q),c.baseState=R,c.firstBaseUpdate=L,c.lastBaseUpdate=V,d===null&&(c.shared.lanes=0),ia|=y,e.lanes=y,e.memoizedState=Q}}function Jh(e,t){if(typeof e!="function")throw Error(s(191,e));e.call(t)}function Wh(e,t){var a=e.callbacks;if(a!==null)for(e.callbacks=null,e=0;ed?d:8;var y=z.T,S={};z.T=S,eu(e,!1,t,a);try{var R=c(),L=z.S;if(L!==null&&L(S,R),R!==null&&typeof R=="object"&&typeof R.then=="function"){var V=Tb(R,o);Ao(e,t,V,Lt(e))}else Ao(e,t,o,Lt(e))}catch(Q){Ao(e,t,{then:function(){},status:"rejected",reason:Q},Lt())}finally{$.p=d,y!==null&&S.types!==null&&(y.types=S.types),z.T=y}}function zb(){}function Jc(e,t,a,o){if(e.tag!==5)throw Error(s(476));var c=jp(e).queue;Op(e,c,t,P,a===null?zb:function(){return Np(e),a(o)})}function jp(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:P,baseState:P,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Dn,lastRenderedState:P},next:null};var a={};return t.next={memoizedState:a,baseState:a,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Dn,lastRenderedState:a},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Np(e){var t=jp(e);t.next===null&&(t=e.alternate.memoizedState),Ao(e,t.next.queue,{},Lt())}function Wc(){return ct(qo)}function Dp(){return Je().memoizedState}function zp(){return Je().memoizedState}function kb(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var a=Lt();e=na(a);var o=aa(t,e,a);o!==null&&(Et(o,t,a),xo(o,t,a)),t={cache:Tc()},e.payload=t;return}t=t.return}}function Lb(e,t,a){var o=Lt();a={lane:o,revertLane:0,gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null},Il(e)?Lp(t,a):(a=vc(e,t,a,o),a!==null&&(Et(a,e,o),Hp(a,t,o)))}function kp(e,t,a){var o=Lt();Ao(e,t,a,o)}function Ao(e,t,a,o){var c={lane:o,revertLane:0,gesture:null,action:a,hasEagerState:!1,eagerState:null,next:null};if(Il(e))Lp(t,c);else{var d=e.alternate;if(e.lanes===0&&(d===null||d.lanes===0)&&(d=t.lastRenderedReducer,d!==null))try{var y=t.lastRenderedState,S=d(y,a);if(c.hasEagerState=!0,c.eagerState=S,Ot(S,y))return jl(e,t,c,0),Pe===null&&Ol(),!1}catch{}if(a=vc(e,t,c,o),a!==null)return Et(a,e,o),Hp(a,t,o),!0}return!1}function eu(e,t,a,o){if(o={lane:2,revertLane:Nu(),gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Il(e)){if(t)throw Error(s(479))}else t=vc(e,a,o,2),t!==null&&Et(t,e,2)}function Il(e){var t=e.alternate;return e===Se||t!==null&&t===Se}function Lp(e,t){br=Yl=!0;var a=e.pending;a===null?t.next=t:(t.next=a.next,a.next=t),e.pending=t}function Hp(e,t,a){if((a&4194048)!==0){var o=t.lanes;o&=e.pendingLanes,a|=o,t.lanes=a,Vf(e,a)}}var Co={readContext:ct,use:Kl,useCallback:Fe,useContext:Fe,useEffect:Fe,useImperativeHandle:Fe,useLayoutEffect:Fe,useInsertionEffect:Fe,useMemo:Fe,useReducer:Fe,useRef:Fe,useState:Fe,useDebugValue:Fe,useDeferredValue:Fe,useTransition:Fe,useSyncExternalStore:Fe,useId:Fe,useHostTransitionStatus:Fe,useFormState:Fe,useActionState:Fe,useOptimistic:Fe,useMemoCache:Fe,useCacheRefresh:Fe};Co.useEffectEvent=Fe;var Up={readContext:ct,use:Kl,useCallback:function(e,t){return pt().memoizedState=[e,t===void 0?null:t],e},useContext:ct,useEffect:Sp,useImperativeHandle:function(e,t,a){a=a!=null?a.concat([e]):null,Fl(4194308,4,Cp.bind(null,t,e),a)},useLayoutEffect:function(e,t){return Fl(4194308,4,e,t)},useInsertionEffect:function(e,t){Fl(4,2,e,t)},useMemo:function(e,t){var a=pt();t=t===void 0?null:t;var o=e();if(qa){$n(!0);try{e()}finally{$n(!1)}}return a.memoizedState=[o,t],o},useReducer:function(e,t,a){var o=pt();if(a!==void 0){var c=a(t);if(qa){$n(!0);try{a(t)}finally{$n(!1)}}}else c=t;return o.memoizedState=o.baseState=c,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:c},o.queue=e,e=e.dispatch=Lb.bind(null,Se,e),[o.memoizedState,e]},useRef:function(e){var t=pt();return e={current:e},t.memoizedState=e},useState:function(e){e=Kc(e);var t=e.queue,a=kp.bind(null,Se,t);return t.dispatch=a,[e.memoizedState,a]},useDebugValue:Zc,useDeferredValue:function(e,t){var a=pt();return Ic(a,e,t)},useTransition:function(){var e=Kc(!1);return e=Op.bind(null,Se,e.queue,!0,!1),pt().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,a){var o=Se,c=pt();if(Oe){if(a===void 0)throw Error(s(407));a=a()}else{if(a=t(),Pe===null)throw Error(s(349));(Te&127)!==0||op(o,t,a)}c.memoizedState=a;var d={value:a,getSnapshot:t};return c.queue=d,Sp(sp.bind(null,o,d,e),[e]),o.flags|=2048,wr(9,{destroy:void 0},lp.bind(null,o,d,a,t),null),a},useId:function(){var e=pt(),t=Pe.identifierPrefix;if(Oe){var a=pn,o=hn;a=(o&~(1<<32-Mt(o)-1)).toString(32)+a,t="_"+t+"R_"+a,a=Xl++,0<\/script>",d=d.removeChild(d.firstChild);break;case"select":d=typeof o.is=="string"?y.createElement("select",{is:o.is}):y.createElement("select"),o.multiple?d.multiple=!0:o.size&&(d.size=o.size);break;default:d=typeof o.is=="string"?y.createElement(c,{is:o.is}):y.createElement(c)}}d[st]=t,d[vt]=o;e:for(y=t.child;y!==null;){if(y.tag===5||y.tag===6)d.appendChild(y.stateNode);else if(y.tag!==4&&y.tag!==27&&y.child!==null){y.child.return=y,y=y.child;continue}if(y===t)break e;for(;y.sibling===null;){if(y.return===null||y.return===t)break e;y=y.return}y.sibling.return=y.return,y=y.sibling}t.stateNode=d;e:switch(dt(d,c,o),c){case"button":case"input":case"select":case"textarea":o=!!o.autoFocus;break e;case"img":o=!0;break e;default:o=!1}o&&kn(t)}}return Ge(t),pu(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,a),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==o&&kn(t);else{if(typeof o!="string"&&t.stateNode===null)throw Error(s(166));if(e=me.current,hr(t)){if(e=t.stateNode,a=t.memoizedProps,o=null,c=it,c!==null)switch(c.tag){case 27:case 5:o=c.memoizedProps}e[st]=t,e=!!(e.nodeValue===a||o!==null&&o.suppressHydrationWarning===!0||ag(e.nodeValue,a)),e||Wn(t,!0)}else e=vs(e).createTextNode(o),e[st]=t,t.stateNode=e}return Ge(t),null;case 31:if(a=t.memoizedState,e===null||e.memoizedState!==null){if(o=hr(t),a!==null){if(e===null){if(!o)throw Error(s(318));if(e=t.memoizedState,e=e!==null?e.dehydrated:null,!e)throw Error(s(557));e[st]=t}else za(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Ge(t),e=!1}else a=Ac(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),e=!0;if(!e)return t.flags&256?(Dt(t),t):(Dt(t),null);if((t.flags&128)!==0)throw Error(s(558))}return Ge(t),null;case 13:if(o=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(c=hr(t),o!==null&&o.dehydrated!==null){if(e===null){if(!c)throw Error(s(318));if(c=t.memoizedState,c=c!==null?c.dehydrated:null,!c)throw Error(s(317));c[st]=t}else za(),(t.flags&128)===0&&(t.memoizedState=null),t.flags|=4;Ge(t),c=!1}else c=Ac(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=c),c=!0;if(!c)return t.flags&256?(Dt(t),t):(Dt(t),null)}return Dt(t),(t.flags&128)!==0?(t.lanes=a,t):(a=o!==null,e=e!==null&&e.memoizedState!==null,a&&(o=t.child,c=null,o.alternate!==null&&o.alternate.memoizedState!==null&&o.alternate.memoizedState.cachePool!==null&&(c=o.alternate.memoizedState.cachePool.pool),d=null,o.memoizedState!==null&&o.memoizedState.cachePool!==null&&(d=o.memoizedState.cachePool.pool),d!==c&&(o.flags|=2048)),a!==e&&a&&(t.child.flags|=8192),ns(t,t.updateQueue),Ge(t),null);case 4:return Le(),e===null&&Lu(t.stateNode.containerInfo),Ge(t),null;case 10:return jn(t.type),Ge(t),null;case 19:if(Y(Ie),o=t.memoizedState,o===null)return Ge(t),null;if(c=(t.flags&128)!==0,d=o.rendering,d===null)if(c)Ro(o,!1);else{if(Ze!==0||e!==null&&(e.flags&128)!==0)for(e=t.child;e!==null;){if(d=Gl(e),d!==null){for(t.flags|=128,Ro(o,!1),e=d.updateQueue,t.updateQueue=e,ns(t,e),t.subtreeFlags=0,e=a,a=t.child;a!==null;)kh(a,e),a=a.sibling;return F(Ie,Ie.current&1|2),Oe&&Mn(t,o.treeForkCount),t.child}e=e.sibling}o.tail!==null&&Rt()>ss&&(t.flags|=128,c=!0,Ro(o,!1),t.lanes=4194304)}else{if(!c)if(e=Gl(d),e!==null){if(t.flags|=128,c=!0,e=e.updateQueue,t.updateQueue=e,ns(t,e),Ro(o,!0),o.tail===null&&o.tailMode==="hidden"&&!d.alternate&&!Oe)return Ge(t),null}else 2*Rt()-o.renderingStartTime>ss&&a!==536870912&&(t.flags|=128,c=!0,Ro(o,!1),t.lanes=4194304);o.isBackwards?(d.sibling=t.child,t.child=d):(e=o.last,e!==null?e.sibling=d:t.child=d,o.last=d)}return o.tail!==null?(e=o.tail,o.rendering=e,o.tail=e.sibling,o.renderingStartTime=Rt(),e.sibling=null,a=Ie.current,F(Ie,c?a&1|2:a&1),Oe&&Mn(t,o.treeForkCount),e):(Ge(t),null);case 22:case 23:return Dt(t),Hc(),o=t.memoizedState!==null,e!==null?e.memoizedState!==null!==o&&(t.flags|=8192):o&&(t.flags|=8192),o?(a&536870912)!==0&&(t.flags&128)===0&&(Ge(t),t.subtreeFlags&6&&(t.flags|=8192)):Ge(t),a=t.updateQueue,a!==null&&ns(t,a.retryQueue),a=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(a=e.memoizedState.cachePool.pool),o=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(o=t.memoizedState.cachePool.pool),o!==a&&(t.flags|=2048),e!==null&&Y(Ha),null;case 24:return a=null,e!==null&&(a=e.memoizedState.cache),t.memoizedState.cache!==a&&(t.flags|=2048),jn(We),Ge(t),null;case 25:return null;case 30:return null}throw Error(s(156,t.tag))}function qb(e,t){switch(wc(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return jn(We),Le(),e=t.flags,(e&65536)!==0&&(e&128)===0?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return dn(t),null;case 31:if(t.memoizedState!==null){if(Dt(t),t.alternate===null)throw Error(s(340));za()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(Dt(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(s(340));za()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return Y(Ie),null;case 4:return Le(),null;case 10:return jn(t.type),null;case 22:case 23:return Dt(t),Hc(),e!==null&&Y(Ha),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return jn(We),null;case 25:return null;default:return null}}function im(e,t){switch(wc(t),t.tag){case 3:jn(We),Le();break;case 26:case 27:case 5:dn(t);break;case 4:Le();break;case 31:t.memoizedState!==null&&Dt(t);break;case 13:Dt(t);break;case 19:Y(Ie);break;case 10:jn(t.type);break;case 22:case 23:Dt(t),Hc(),e!==null&&Y(Ha);break;case 24:jn(We)}}function To(e,t){try{var a=t.updateQueue,o=a!==null?a.lastEffect:null;if(o!==null){var c=o.next;a=c;do{if((a.tag&e)===e){o=void 0;var d=a.create,y=a.inst;o=d(),y.destroy=o}a=a.next}while(a!==c)}}catch(S){ke(t,t.return,S)}}function la(e,t,a){try{var o=t.updateQueue,c=o!==null?o.lastEffect:null;if(c!==null){var d=c.next;o=d;do{if((o.tag&e)===e){var y=o.inst,S=y.destroy;if(S!==void 0){y.destroy=void 0,c=t;var R=a,L=S;try{L()}catch(V){ke(c,R,V)}}}o=o.next}while(o!==d)}}catch(V){ke(t,t.return,V)}}function cm(e){var t=e.updateQueue;if(t!==null){var a=e.stateNode;try{Wh(t,a)}catch(o){ke(e,e.return,o)}}}function um(e,t,a){a.props=Va(e.type,e.memoizedProps),a.state=e.memoizedState;try{a.componentWillUnmount()}catch(o){ke(e,t,o)}}function Mo(e,t){try{var a=e.ref;if(a!==null){switch(e.tag){case 26:case 27:case 5:var o=e.stateNode;break;case 30:o=e.stateNode;break;default:o=e.stateNode}typeof a=="function"?e.refCleanup=a(o):a.current=o}}catch(c){ke(e,t,c)}}function mn(e,t){var a=e.ref,o=e.refCleanup;if(a!==null)if(typeof o=="function")try{o()}catch(c){ke(e,t,c)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof a=="function")try{a(null)}catch(c){ke(e,t,c)}else a.current=null}function dm(e){var t=e.type,a=e.memoizedProps,o=e.stateNode;try{e:switch(t){case"button":case"input":case"select":case"textarea":a.autoFocus&&o.focus();break e;case"img":a.src?o.src=a.src:a.srcSet&&(o.srcset=a.srcSet)}}catch(c){ke(e,e.return,c)}}function mu(e,t,a){try{var o=e.stateNode;cS(o,e.type,a,t),o[vt]=t}catch(c){ke(e,e.return,c)}}function fm(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&ha(e.type)||e.tag===4}function gu(e){e:for(;;){for(;e.sibling===null;){if(e.return===null||fm(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&ha(e.type)||e.flags&2||e.child===null||e.tag===4)continue e;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function vu(e,t,a){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?(a.nodeType===9?a.body:a.nodeName==="HTML"?a.ownerDocument.body:a).insertBefore(e,t):(t=a.nodeType===9?a.body:a.nodeName==="HTML"?a.ownerDocument.body:a,t.appendChild(e),a=a._reactRootContainer,a!=null||t.onclick!==null||(t.onclick=_n));else if(o!==4&&(o===27&&ha(e.type)&&(a=e.stateNode,t=null),e=e.child,e!==null))for(vu(e,t,a),e=e.sibling;e!==null;)vu(e,t,a),e=e.sibling}function as(e,t,a){var o=e.tag;if(o===5||o===6)e=e.stateNode,t?a.insertBefore(e,t):a.appendChild(e);else if(o!==4&&(o===27&&ha(e.type)&&(a=e.stateNode),e=e.child,e!==null))for(as(e,t,a),e=e.sibling;e!==null;)as(e,t,a),e=e.sibling}function hm(e){var t=e.stateNode,a=e.memoizedProps;try{for(var o=e.type,c=t.attributes;c.length;)t.removeAttributeNode(c[0]);dt(t,o,a),t[st]=e,t[vt]=a}catch(d){ke(e,e.return,d)}}var Ln=!1,nt=!1,yu=!1,pm=typeof WeakSet=="function"?WeakSet:Set,lt=null;function Vb(e,t){if(e=e.containerInfo,Bu=As,e=_h(e),dc(e)){if("selectionStart"in e)var a={start:e.selectionStart,end:e.selectionEnd};else e:{a=(a=e.ownerDocument)&&a.defaultView||window;var o=a.getSelection&&a.getSelection();if(o&&o.rangeCount!==0){a=o.anchorNode;var c=o.anchorOffset,d=o.focusNode;o=o.focusOffset;try{a.nodeType,d.nodeType}catch{a=null;break e}var y=0,S=-1,R=-1,L=0,V=0,Q=e,U=null;t:for(;;){for(var B;Q!==a||c!==0&&Q.nodeType!==3||(S=y+c),Q!==d||o!==0&&Q.nodeType!==3||(R=y+o),Q.nodeType===3&&(y+=Q.nodeValue.length),(B=Q.firstChild)!==null;)U=Q,Q=B;for(;;){if(Q===e)break t;if(U===a&&++L===c&&(S=y),U===d&&++V===o&&(R=y),(B=Q.nextSibling)!==null)break;Q=U,U=Q.parentNode}Q=B}a=S===-1||R===-1?null:{start:S,end:R}}else a=null}a=a||{start:0,end:0}}else a=null;for(Pu={focusedElem:e,selectionRange:a},As=!1,lt=t;lt!==null;)if(t=lt,e=t.child,(t.subtreeFlags&1028)!==0&&e!==null)e.return=t,lt=e;else for(;lt!==null;){switch(t=lt,d=t.alternate,e=t.flags,t.tag){case 0:if((e&4)!==0&&(e=t.updateQueue,e=e!==null?e.events:null,e!==null))for(a=0;a title"))),dt(d,o,a),d[st]=e,ot(d),o=d;break e;case"link":var y=bg("link","href",c).get(o+(a.href||""));if(y){for(var S=0;SBe&&(y=Be,Be=de,de=y);var N=Ah(S,de),O=Ah(S,Be);if(N&&O&&(B.rangeCount!==1||B.anchorNode!==N.node||B.anchorOffset!==N.offset||B.focusNode!==O.node||B.focusOffset!==O.offset)){var k=Q.createRange();k.setStart(N.node,N.offset),B.removeAllRanges(),de>Be?(B.addRange(k),B.extend(O.node,O.offset)):(k.setEnd(O.node,O.offset),B.addRange(k))}}}}for(Q=[],B=S;B=B.parentNode;)B.nodeType===1&&Q.push({element:B,left:B.scrollLeft,top:B.scrollTop});for(typeof S.focus=="function"&&S.focus(),S=0;Sa?32:a,z.T=null,a=Cu,Cu=null;var d=ua,y=qn;if(at=0,Rr=ua=null,qn=0,(De&6)!==0)throw Error(s(331));var S=De;if(De|=4,Cm(d.current),wm(d,d.current,y,a),De=S,ko(0,!1),Tt&&typeof Tt.onPostCommitFiberRoot=="function")try{Tt.onPostCommitFiberRoot(Jr,d)}catch{}return!0}finally{$.p=c,z.T=o,Gm(e,t)}}function Xm(e,t,a){t=Xt(a,t),t=ru(e.stateNode,t,2),e=aa(e,t,2),e!==null&&(eo(e,2),gn(e))}function ke(e,t,a){if(e.tag===3)Xm(e,e,a);else for(;t!==null;){if(t.tag===3){Xm(t,e,a);break}else if(t.tag===1){var o=t.stateNode;if(typeof t.type.getDerivedStateFromError=="function"||typeof o.componentDidCatch=="function"&&(ca===null||!ca.has(o))){e=Xt(a,e),a=Qp(2),o=aa(t,a,2),o!==null&&(Kp(a,o,t,e),eo(o,2),gn(o));break}}t=t.return}}function Mu(e,t,a){var o=e.pingCache;if(o===null){o=e.pingCache=new Xb;var c=new Set;o.set(t,c)}else c=o.get(t),c===void 0&&(c=new Set,o.set(t,c));c.has(a)||(Su=!0,c.add(a),e=Zb.bind(null,e,t,a),t.then(e,e))}function Zb(e,t,a){var o=e.pingCache;o!==null&&o.delete(t),e.pingedLanes|=e.suspendedLanes&a,e.warmLanes&=~a,Pe===e&&(Te&a)===a&&(Ze===4||Ze===3&&(Te&62914560)===Te&&300>Rt()-ls?(De&2)===0&&Tr(e,0):wu|=a,_r===Te&&(_r=0)),gn(e)}function Qm(e,t){t===0&&(t=Pf()),e=Na(e,t),e!==null&&(eo(e,t),gn(e))}function Ib(e){var t=e.memoizedState,a=0;t!==null&&(a=t.retryLane),Qm(e,a)}function Jb(e,t){var a=0;switch(e.tag){case 31:case 13:var o=e.stateNode,c=e.memoizedState;c!==null&&(a=c.retryLane);break;case 19:o=e.stateNode;break;case 22:o=e.stateNode._retryCache;break;default:throw Error(s(314))}o!==null&&o.delete(t),Qm(e,a)}function Wb(e,t){return Vi(e,t)}var hs=null,Or=null,Ou=!1,ps=!1,ju=!1,fa=0;function gn(e){e!==Or&&e.next===null&&(Or===null?hs=Or=e:Or=Or.next=e),ps=!0,Ou||(Ou=!0,tS())}function ko(e,t){if(!ju&&ps){ju=!0;do for(var a=!1,o=hs;o!==null;){if(e!==0){var c=o.pendingLanes;if(c===0)var d=0;else{var y=o.suspendedLanes,S=o.pingedLanes;d=(1<<31-Mt(42|e)+1)-1,d&=c&~(y&~S),d=d&201326741?d&201326741|1:d?d|2:0}d!==0&&(a=!0,Zm(o,d))}else d=Te,d=yl(o,o===Pe?d:0,o.cancelPendingCommit!==null||o.timeoutHandle!==-1),(d&3)===0||Wr(o,d)||(a=!0,Zm(o,d));o=o.next}while(a);ju=!1}}function eS(){Km()}function Km(){ps=Ou=!1;var e=0;fa!==0&&dS()&&(e=fa);for(var t=Rt(),a=null,o=hs;o!==null;){var c=o.next,d=$m(o,t);d===0?(o.next=null,a===null?hs=c:a.next=c,c===null&&(Or=a)):(a=o,(e!==0||(d&3)!==0)&&(ps=!0)),o=c}at!==0&&at!==5||ko(e),fa!==0&&(fa=0)}function $m(e,t){for(var a=e.suspendedLanes,o=e.pingedLanes,c=e.expirationTimes,d=e.pendingLanes&-62914561;0S)break;var V=R.transferSize,Q=R.initiatorType;V&&rg(Q)&&(R=R.responseEnd,y+=V*(R"u"?null:document;function gg(e,t,a){var o=jr;if(o&&typeof t=="string"&&t){var c=Gt(t);c='link[rel="'+e+'"][href="'+c+'"]',typeof a=="string"&&(c+='[crossorigin="'+a+'"]'),mg.has(c)||(mg.add(c),e={rel:e,crossOrigin:a,href:t},o.querySelector(c)===null&&(t=o.createElement("link"),dt(t,"link",e),ot(t),o.head.appendChild(t)))}}function bS(e){Vn.D(e),gg("dns-prefetch",e,null)}function SS(e,t){Vn.C(e,t),gg("preconnect",e,t)}function wS(e,t,a){Vn.L(e,t,a);var o=jr;if(o&&e&&t){var c='link[rel="preload"][as="'+Gt(t)+'"]';t==="image"&&a&&a.imageSrcSet?(c+='[imagesrcset="'+Gt(a.imageSrcSet)+'"]',typeof a.imageSizes=="string"&&(c+='[imagesizes="'+Gt(a.imageSizes)+'"]')):c+='[href="'+Gt(e)+'"]';var d=c;switch(t){case"style":d=Nr(e);break;case"script":d=Dr(e)}It.has(d)||(e=b({rel:"preload",href:t==="image"&&a&&a.imageSrcSet?void 0:e,as:t},a),It.set(d,e),o.querySelector(c)!==null||t==="style"&&o.querySelector(Bo(d))||t==="script"&&o.querySelector(Po(d))||(t=o.createElement("link"),dt(t,"link",e),ot(t),o.head.appendChild(t)))}}function ES(e,t){Vn.m(e,t);var a=jr;if(a&&e){var o=t&&typeof t.as=="string"?t.as:"script",c='link[rel="modulepreload"][as="'+Gt(o)+'"][href="'+Gt(e)+'"]',d=c;switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":d=Dr(e)}if(!It.has(d)&&(e=b({rel:"modulepreload",href:e},t),It.set(d,e),a.querySelector(c)===null)){switch(o){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(a.querySelector(Po(d)))return}o=a.createElement("link"),dt(o,"link",e),ot(o),a.head.appendChild(o)}}}function AS(e,t,a){Vn.S(e,t,a);var o=jr;if(o&&e){var c=er(o).hoistableStyles,d=Nr(e);t=t||"default";var y=c.get(d);if(!y){var S={loading:0,preload:null};if(y=o.querySelector(Bo(d)))S.loading=5;else{e=b({rel:"stylesheet",href:e,"data-precedence":t},a),(a=It.get(d))&&Ku(e,a);var R=y=o.createElement("link");ot(R),dt(R,"link",e),R._p=new Promise(function(L,V){R.onload=L,R.onerror=V}),R.addEventListener("load",function(){S.loading|=1}),R.addEventListener("error",function(){S.loading|=2}),S.loading|=4,xs(y,t,o)}y={type:"stylesheet",instance:y,count:1,state:S},c.set(d,y)}}}function CS(e,t){Vn.X(e,t);var a=jr;if(a&&e){var o=er(a).hoistableScripts,c=Dr(e),d=o.get(c);d||(d=a.querySelector(Po(c)),d||(e=b({src:e,async:!0},t),(t=It.get(c))&&$u(e,t),d=a.createElement("script"),ot(d),dt(d,"link",e),a.head.appendChild(d)),d={type:"script",instance:d,count:1,state:null},o.set(c,d))}}function _S(e,t){Vn.M(e,t);var a=jr;if(a&&e){var o=er(a).hoistableScripts,c=Dr(e),d=o.get(c);d||(d=a.querySelector(Po(c)),d||(e=b({src:e,async:!0,type:"module"},t),(t=It.get(c))&&$u(e,t),d=a.createElement("script"),ot(d),dt(d,"link",e),a.head.appendChild(d)),d={type:"script",instance:d,count:1,state:null},o.set(c,d))}}function vg(e,t,a,o){var c=(c=me.current)?ys(c):null;if(!c)throw Error(s(446));switch(e){case"meta":case"title":return null;case"style":return typeof a.precedence=="string"&&typeof a.href=="string"?(t=Nr(a.href),a=er(c).hoistableStyles,o=a.get(t),o||(o={type:"style",instance:null,count:0,state:null},a.set(t,o)),o):{type:"void",instance:null,count:0,state:null};case"link":if(a.rel==="stylesheet"&&typeof a.href=="string"&&typeof a.precedence=="string"){e=Nr(a.href);var d=er(c).hoistableStyles,y=d.get(e);if(y||(c=c.ownerDocument||c,y={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},d.set(e,y),(d=c.querySelector(Bo(e)))&&!d._p&&(y.instance=d,y.state.loading=5),It.has(e)||(a={rel:"preload",as:"style",href:a.href,crossOrigin:a.crossOrigin,integrity:a.integrity,media:a.media,hrefLang:a.hrefLang,referrerPolicy:a.referrerPolicy},It.set(e,a),d||RS(c,e,a,y.state))),t&&o===null)throw Error(s(528,""));return y}if(t&&o!==null)throw Error(s(529,""));return null;case"script":return t=a.async,a=a.src,typeof a=="string"&&t&&typeof t!="function"&&typeof t!="symbol"?(t=Dr(a),a=er(c).hoistableScripts,o=a.get(t),o||(o={type:"script",instance:null,count:0,state:null},a.set(t,o)),o):{type:"void",instance:null,count:0,state:null};default:throw Error(s(444,e))}}function Nr(e){return'href="'+Gt(e)+'"'}function Bo(e){return'link[rel="stylesheet"]['+e+"]"}function yg(e){return b({},e,{"data-precedence":e.precedence,precedence:null})}function RS(e,t,a,o){e.querySelector('link[rel="preload"][as="style"]['+t+"]")?o.loading=1:(t=e.createElement("link"),o.preload=t,t.addEventListener("load",function(){return o.loading|=1}),t.addEventListener("error",function(){return o.loading|=2}),dt(t,"link",a),ot(t),e.head.appendChild(t))}function Dr(e){return'[src="'+Gt(e)+'"]'}function Po(e){return"script[async]"+e}function xg(e,t,a){if(t.count++,t.instance===null)switch(t.type){case"style":var o=e.querySelector('style[data-href~="'+Gt(a.href)+'"]');if(o)return t.instance=o,ot(o),o;var c=b({},a,{"data-href":a.href,"data-precedence":a.precedence,href:null,precedence:null});return o=(e.ownerDocument||e).createElement("style"),ot(o),dt(o,"style",c),xs(o,a.precedence,e),t.instance=o;case"stylesheet":c=Nr(a.href);var d=e.querySelector(Bo(c));if(d)return t.state.loading|=4,t.instance=d,ot(d),d;o=yg(a),(c=It.get(c))&&Ku(o,c),d=(e.ownerDocument||e).createElement("link"),ot(d);var y=d;return y._p=new Promise(function(S,R){y.onload=S,y.onerror=R}),dt(d,"link",o),t.state.loading|=4,xs(d,a.precedence,e),t.instance=d;case"script":return d=Dr(a.src),(c=e.querySelector(Po(d)))?(t.instance=c,ot(c),c):(o=a,(c=It.get(d))&&(o=b({},a),$u(o,c)),e=e.ownerDocument||e,c=e.createElement("script"),ot(c),dt(c,"link",o),e.head.appendChild(c),t.instance=c);case"void":return null;default:throw Error(s(443,t.type))}else t.type==="stylesheet"&&(t.state.loading&4)===0&&(o=t.instance,t.state.loading|=4,xs(o,a.precedence,e));return t.instance}function xs(e,t,a){for(var o=a.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),c=o.length?o[o.length-1]:null,d=c,y=0;y title"):null)}function TS(e,t,a){if(a===1||t.itemProp!=null)return!1;switch(e){case"meta":case"title":return!0;case"style":if(typeof t.precedence!="string"||typeof t.href!="string"||t.href==="")break;return!0;case"link":if(typeof t.rel!="string"||typeof t.href!="string"||t.href===""||t.onLoad||t.onError)break;return t.rel==="stylesheet"?(e=t.disabled,typeof t.precedence=="string"&&e==null):!0;case"script":if(t.async&&typeof t.async!="function"&&typeof t.async!="symbol"&&!t.onLoad&&!t.onError&&t.src&&typeof t.src=="string")return!0}return!1}function wg(e){return!(e.type==="stylesheet"&&(e.state.loading&3)===0)}function MS(e,t,a,o){if(a.type==="stylesheet"&&(typeof o.media!="string"||matchMedia(o.media).matches!==!1)&&(a.state.loading&4)===0){if(a.instance===null){var c=Nr(o.href),d=t.querySelector(Bo(c));if(d){t=d._p,t!==null&&typeof t=="object"&&typeof t.then=="function"&&(e.count++,e=Ss.bind(e),t.then(e,e)),a.state.loading|=4,a.instance=d,ot(d);return}d=t.ownerDocument||t,o=yg(o),(c=It.get(c))&&Ku(o,c),d=d.createElement("link"),ot(d);var y=d;y._p=new Promise(function(S,R){y.onload=S,y.onerror=R}),dt(d,"link",o),a.instance=d}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(a,t),(t=a.state.preload)&&(a.state.loading&3)===0&&(e.count++,a=Ss.bind(e),t.addEventListener("load",a),t.addEventListener("error",a))}}var Fu=0;function OS(e,t){return e.stylesheets&&e.count===0&&Es(e,e.stylesheets),0Fu?50:800)+t);return e.unsuspend=a,function(){e.unsuspend=null,clearTimeout(o),clearTimeout(c)}}:null}function Ss(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)Es(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var ws=null;function Es(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,ws=new Map,t.forEach(jS,e),ws=null,Ss.call(e))}function jS(e,t){if(!(t.state.loading&4)){var a=ws.get(e);if(a)var o=a.get(null);else{a=new Map,ws.set(e,a);for(var c=e.querySelectorAll("link[data-precedence],style[data-precedence]"),d=0;d"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(r){console.error(r)}}return n(),rd.exports=KS(),rd.exports}var FS=$S();const ZS="modulepreload",IS=function(n,r){return new URL(n,r).href},Qg={},be=function(r,l,s){let i=Promise.resolve();if(l&&l.length>0){let v=function(x){return Promise.all(x.map(b=>Promise.resolve(b).then(w=>({status:"fulfilled",value:w}),w=>({status:"rejected",reason:w}))))};const f=document.getElementsByTagName("link"),p=document.querySelector("meta[property=csp-nonce]"),g=p?.nonce||p?.getAttribute("nonce");i=v(l.map(x=>{if(x=IS(x,s),x in Qg)return;Qg[x]=!0;const b=x.endsWith(".css"),w=b?'[rel="stylesheet"]':"";if(s)for(let _=f.length-1;_>=0;_--){const C=f[_];if(C.href===x&&(!b||C.rel==="stylesheet"))return}else if(document.querySelector(`link[href="${x}"]${w}`))return;const A=document.createElement("link");if(A.rel=b?"stylesheet":ZS,b||(A.as="script"),A.crossOrigin="",A.href=x,g&&A.setAttribute("nonce",g),document.head.appendChild(A),b)return new Promise((_,C)=>{A.addEventListener("load",_),A.addEventListener("error",()=>C(new Error(`Unable to preload CSS for ${x}`)))})}))}function u(f){const p=new Event("vite:preloadError",{cancelable:!0});if(p.payload=f,window.dispatchEvent(p),!p.defaultPrevented)throw f}return i.then(f=>{for(const p of f||[])p.status==="rejected"&&u(p.reason);return r().catch(u)})};var Kg="popstate";function $g(n){return typeof n=="object"&&n!=null&&"pathname"in n&&"search"in n&&"hash"in n&&"state"in n&&"key"in n}function JS(n={}){function r(s,i){let u=i.state?.masked,{pathname:f,search:p,hash:g}=u||s.location;return Md("",{pathname:f,search:p,hash:g},i.state&&i.state.usr||null,i.state&&i.state.key||"default",u?{pathname:s.location.pathname,search:s.location.search,hash:s.location.hash}:void 0)}function l(s,i){return typeof i=="string"?i:Jo(i)}return e2(r,l,null,n)}function $e(n,r){if(n===!1||n===null||typeof n>"u")throw new Error(r)}function en(n,r){if(!n){typeof console<"u"&&console.warn(r);try{throw new Error(r)}catch{}}}function WS(){return Math.random().toString(36).substring(2,10)}function Fg(n,r){return{usr:n.state,key:n.key,idx:r,masked:n.unstable_mask?{pathname:n.pathname,search:n.search,hash:n.hash}:void 0}}function Md(n,r,l=null,s,i){return{pathname:typeof n=="string"?n:n.pathname,search:"",hash:"",...typeof r=="string"?Yr(r):r,state:l,key:r&&r.key||s||WS(),unstable_mask:i}}function Jo({pathname:n="/",search:r="",hash:l=""}){return r&&r!=="?"&&(n+=r.charAt(0)==="?"?r:"?"+r),l&&l!=="#"&&(n+=l.charAt(0)==="#"?l:"#"+l),n}function Yr(n){let r={};if(n){let l=n.indexOf("#");l>=0&&(r.hash=n.substring(l),n=n.substring(0,l));let s=n.indexOf("?");s>=0&&(r.search=n.substring(s),n=n.substring(0,s)),n&&(r.pathname=n)}return r}function e2(n,r,l,s={}){let{window:i=document.defaultView,v5Compat:u=!1}=s,f=i.history,p="POP",g=null,v=x();v==null&&(v=0,f.replaceState({...f.state,idx:v},""));function x(){return(f.state||{idx:null}).idx}function b(){p="POP";let E=x(),M=E==null?null:E-v;v=E,g&&g({action:p,location:C.location,delta:M})}function w(E,M){p="PUSH";let H=$g(E)?E:Md(C.location,E,M);v=x()+1;let D=Fg(H,v),j=C.createHref(H.unstable_mask||H);try{f.pushState(D,"",j)}catch(q){if(q instanceof DOMException&&q.name==="DataCloneError")throw q;i.location.assign(j)}u&&g&&g({action:p,location:C.location,delta:1})}function A(E,M){p="REPLACE";let H=$g(E)?E:Md(C.location,E,M);v=x();let D=Fg(H,v),j=C.createHref(H.unstable_mask||H);f.replaceState(D,"",j),u&&g&&g({action:p,location:C.location,delta:0})}function _(E){return t2(E)}let C={get action(){return p},get location(){return n(i,f)},listen(E){if(g)throw new Error("A history only accepts one active listener");return i.addEventListener(Kg,b),g=E,()=>{i.removeEventListener(Kg,b),g=null}},createHref(E){return r(i,E)},createURL:_,encodeLocation(E){let M=_(E);return{pathname:M.pathname,search:M.search,hash:M.hash}},push:w,replace:A,go(E){return f.go(E)}};return C}function t2(n,r=!1){let l="http://localhost";typeof window<"u"&&(l=window.location.origin!=="null"?window.location.origin:window.location.href),$e(l,"No window.location.(origin|href) available to create URL");let s=typeof n=="string"?n:Jo(n);return s=s.replace(/ $/,"%20"),!r&&s.startsWith("//")&&(s=l+s),new URL(s,l)}function iy(n,r,l="/"){return n2(n,r,l,!1)}function n2(n,r,l,s){let i=typeof r=="string"?Yr(r):r,u=Yn(i.pathname||"/",l);if(u==null)return null;let f=cy(n);a2(f);let p=null;for(let g=0;p==null&&g{let x={relativePath:v===void 0?f.path||"":v,caseSensitive:f.caseSensitive===!0,childrenIndex:p,route:f};if(x.relativePath.startsWith("/")){if(!x.relativePath.startsWith(s)&&g)return;$e(x.relativePath.startsWith(s),`Absolute route path "${x.relativePath}" nested under path "${s}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),x.relativePath=x.relativePath.slice(s.length)}let b=bn([s,x.relativePath]),w=l.concat(x);f.children&&f.children.length>0&&($e(f.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${b}".`),cy(f.children,r,w,b,g)),!(f.path==null&&!f.index)&&r.push({path:b,score:u2(b,f.index),routesMeta:w})};return n.forEach((f,p)=>{if(f.path===""||!f.path?.includes("?"))u(f,p);else for(let g of uy(f.path))u(f,p,!0,g)}),r}function uy(n){let r=n.split("/");if(r.length===0)return[];let[l,...s]=r,i=l.endsWith("?"),u=l.replace(/\?$/,"");if(s.length===0)return i?[u,""]:[u];let f=uy(s.join("/")),p=[];return p.push(...f.map(g=>g===""?u:[u,g].join("/"))),i&&p.push(...f),p.map(g=>n.startsWith("/")&&g===""?"/":g)}function a2(n){n.sort((r,l)=>r.score!==l.score?l.score-r.score:d2(r.routesMeta.map(s=>s.childrenIndex),l.routesMeta.map(s=>s.childrenIndex)))}var r2=/^:[\w-]+$/,o2=3,l2=2,s2=1,i2=10,c2=-2,Zg=n=>n==="*";function u2(n,r){let l=n.split("/"),s=l.length;return l.some(Zg)&&(s+=c2),r&&(s+=l2),l.filter(i=>!Zg(i)).reduce((i,u)=>i+(r2.test(u)?o2:u===""?s2:i2),s)}function d2(n,r){return n.length===r.length&&n.slice(0,-1).every((s,i)=>s===r[i])?n[n.length-1]-r[r.length-1]:0}function f2(n,r,l=!1){let{routesMeta:s}=n,i={},u="/",f=[];for(let p=0;p{if(x==="*"){let _=p[w]||"";f=u.slice(0,u.length-_.length).replace(/(.)\/+$/,"$1")}const A=p[w];return b&&!A?v[x]=void 0:v[x]=(A||"").replace(/%2F/g,"/"),v},{}),pathname:u,pathnameBase:f,pattern:n}}function h2(n,r=!1,l=!0){en(n==="*"||!n.endsWith("*")||n.endsWith("/*"),`Route path "${n}" will be treated as if it were "${n.replace(/\*$/,"/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${n.replace(/\*$/,"/*")}".`);let s=[],i="^"+n.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(f,p,g,v,x)=>{if(s.push({paramName:p,isOptional:g!=null}),g){let b=x.charAt(v+f.length);return b&&b!=="/"?"/([^\\/]*)":"(?:/([^\\/]*))?"}return"/([^\\/]+)"}).replace(/\/([\w-]+)\?(\/|$)/g,"(/$1)?$2");return n.endsWith("*")?(s.push({paramName:"*"}),i+=n==="*"||n==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):l?i+="\\/*$":n!==""&&n!=="/"&&(i+="(?:(?=\\/|$))"),[new RegExp(i,r?void 0:"i"),s]}function p2(n){try{return n.split("/").map(r=>decodeURIComponent(r).replace(/\//g,"%2F")).join("/")}catch(r){return en(!1,`The URL path "${n}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${r}).`),n}}function Yn(n,r){if(r==="/")return n;if(!n.toLowerCase().startsWith(r.toLowerCase()))return null;let l=r.endsWith("/")?r.length-1:r.length,s=n.charAt(l);return s&&s!=="/"?null:n.slice(l)||"/"}var m2=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i;function g2(n,r="/"){let{pathname:l,search:s="",hash:i=""}=typeof n=="string"?Yr(n):n,u;return l?(l=l.replace(/\/\/+/g,"/"),l.startsWith("/")?u=Ig(l.substring(1),"/"):u=Ig(l,r)):u=r,{pathname:u,search:x2(s),hash:b2(i)}}function Ig(n,r){let l=r.replace(/\/+$/,"").split("/");return n.split("/").forEach(i=>{i===".."?l.length>1&&l.pop():i!=="."&&l.push(i)}),l.length>1?l.join("/"):"/"}function id(n,r,l,s){return`Cannot include a '${n}' character in a manually specified \`to.${r}\` field [${JSON.stringify(s)}]. Please separate it out to the \`to.${l}\` field. Alternatively you may provide the full path as a string in and the router will parse it for you.`}function v2(n){return n.filter((r,l)=>l===0||r.route.path&&r.route.path.length>0)}function Jd(n){let r=v2(n);return r.map((l,s)=>s===r.length-1?l.pathname:l.pathnameBase)}function vi(n,r,l,s=!1){let i;typeof n=="string"?i=Yr(n):(i={...n},$e(!i.pathname||!i.pathname.includes("?"),id("?","pathname","search",i)),$e(!i.pathname||!i.pathname.includes("#"),id("#","pathname","hash",i)),$e(!i.search||!i.search.includes("#"),id("#","search","hash",i)));let u=n===""||i.pathname==="",f=u?"/":i.pathname,p;if(f==null)p=l;else{let b=r.length-1;if(!s&&f.startsWith("..")){let w=f.split("/");for(;w[0]==="..";)w.shift(),b-=1;i.pathname=w.join("/")}p=b>=0?r[b]:"/"}let g=g2(i,p),v=f&&f!=="/"&&f.endsWith("/"),x=(u||f===".")&&l.endsWith("/");return!g.pathname.endsWith("/")&&(v||x)&&(g.pathname+="/"),g}var bn=n=>n.join("/").replace(/\/\/+/g,"/"),y2=n=>n.replace(/\/+$/,"").replace(/^\/*/,"/"),x2=n=>!n||n==="?"?"":n.startsWith("?")?n:"?"+n,b2=n=>!n||n==="#"?"":n.startsWith("#")?n:"#"+n,S2=class{constructor(n,r,l,s=!1){this.status=n,this.statusText=r||"",this.internal=s,l instanceof Error?(this.data=l.toString(),this.error=l):this.data=l}};function w2(n){return n!=null&&typeof n.status=="number"&&typeof n.statusText=="string"&&typeof n.internal=="boolean"&&"data"in n}function E2(n){return n.map(r=>r.route.path).filter(Boolean).join("/").replace(/\/\/*/g,"/")||"/"}var dy=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function fy(n,r){let l=n;if(typeof l!="string"||!m2.test(l))return{absoluteURL:void 0,isExternal:!1,to:l};let s=l,i=!1;if(dy)try{let u=new URL(window.location.href),f=l.startsWith("//")?new URL(u.protocol+l):new URL(l),p=Yn(f.pathname,r);f.origin===u.origin&&p!=null?l=p+f.search+f.hash:i=!0}catch{en(!1,` contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:s,isExternal:i,to:l}}Object.getOwnPropertyNames(Object.prototype).sort().join("\0");var hy=["POST","PUT","PATCH","DELETE"];new Set(hy);var A2=["GET",...hy];new Set(A2);var Xr=m.createContext(null);Xr.displayName="DataRouter";var yi=m.createContext(null);yi.displayName="DataRouterState";var C2=m.createContext(!1),py=m.createContext({isTransitioning:!1});py.displayName="ViewTransition";var _2=m.createContext(new Map);_2.displayName="Fetchers";var R2=m.createContext(null);R2.displayName="Await";var Pt=m.createContext(null);Pt.displayName="Navigation";var ll=m.createContext(null);ll.displayName="Location";var tn=m.createContext({outlet:null,matches:[],isDataRoute:!1});tn.displayName="Route";var Wd=m.createContext(null);Wd.displayName="RouteError";var my="REACT_ROUTER_ERROR",T2="REDIRECT",M2="ROUTE_ERROR_RESPONSE";function O2(n){if(n.startsWith(`${my}:${T2}:{`))try{let r=JSON.parse(n.slice(28));if(typeof r=="object"&&r&&typeof r.status=="number"&&typeof r.statusText=="string"&&typeof r.location=="string"&&typeof r.reloadDocument=="boolean"&&typeof r.replace=="boolean")return r}catch{}}function j2(n){if(n.startsWith(`${my}:${M2}:{`))try{let r=JSON.parse(n.slice(40));if(typeof r=="object"&&r&&typeof r.status=="number"&&typeof r.statusText=="string")return new S2(r.status,r.statusText,r.data)}catch{}}function N2(n,{relative:r}={}){$e(Qr(),"useHref() may be used only in the context of a component.");let{basename:l,navigator:s}=m.useContext(Pt),{hash:i,pathname:u,search:f}=sl(n,{relative:r}),p=u;return l!=="/"&&(p=u==="/"?l:bn([l,u])),s.createHref({pathname:p,search:f,hash:i})}function Qr(){return m.useContext(ll)!=null}function Ct(){return $e(Qr(),"useLocation() may be used only in the context of a component."),m.useContext(ll).location}var gy="You should call navigate() in a React.useEffect(), not when your component is first rendered.";function vy(n){m.useContext(Pt).static||m.useLayoutEffect(n)}function Kr(){let{isDataRoute:n}=m.useContext(tn);return n?K2():D2()}function D2(){$e(Qr(),"useNavigate() may be used only in the context of a component.");let n=m.useContext(Xr),{basename:r,navigator:l}=m.useContext(Pt),{matches:s}=m.useContext(tn),{pathname:i}=Ct(),u=JSON.stringify(Jd(s)),f=m.useRef(!1);return vy(()=>{f.current=!0}),m.useCallback((g,v={})=>{if(en(f.current,gy),!f.current)return;if(typeof g=="number"){l.go(g);return}let x=vi(g,JSON.parse(u),i,v.relative==="path");n==null&&r!=="/"&&(x.pathname=x.pathname==="/"?r:bn([r,x.pathname])),(v.replace?l.replace:l.push)(x,v.state,v)},[r,l,u,i,n])}var z2=m.createContext(null);function k2(n){let r=m.useContext(tn).outlet;return m.useMemo(()=>r&&m.createElement(z2.Provider,{value:n},r),[r,n])}function JO(){let{matches:n}=m.useContext(tn),r=n[n.length-1];return r?r.params:{}}function sl(n,{relative:r}={}){let{matches:l}=m.useContext(tn),{pathname:s}=Ct(),i=JSON.stringify(Jd(l));return m.useMemo(()=>vi(n,JSON.parse(i),s,r==="path"),[n,i,s,r])}function L2(n,r){return yy(n,r)}function yy(n,r,l){$e(Qr(),"useRoutes() may be used only in the context of a component.");let{navigator:s}=m.useContext(Pt),{matches:i}=m.useContext(tn),u=i[i.length-1],f=u?u.params:{},p=u?u.pathname:"/",g=u?u.pathnameBase:"/",v=u&&u.route;{let E=v&&v.path||"";by(p,!v||E.endsWith("*")||E.endsWith("*?"),`You rendered descendant (or called \`useRoutes()\`) at "${p}" (under ) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render. + +Please change the parent to .`)}let x=Ct(),b;if(r){let E=typeof r=="string"?Yr(r):r;$e(g==="/"||E.pathname?.startsWith(g),`When overriding the location using \`\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${g}" but pathname "${E.pathname}" was given in the \`location\` prop.`),b=E}else b=x;let w=b.pathname||"/",A=w;if(g!=="/"){let E=g.replace(/^\//,"").split("/");A="/"+w.replace(/^\//,"").split("/").slice(E.length).join("/")}let _=iy(n,{pathname:A});en(v||_!=null,`No routes matched location "${b.pathname}${b.search}${b.hash}" `),en(_==null||_[_.length-1].route.element!==void 0||_[_.length-1].route.Component!==void 0||_[_.length-1].route.lazy!==void 0,`Matched leaf route at location "${b.pathname}${b.search}${b.hash}" does not have an element or Component. This means it will render an with a null value by default resulting in an "empty" page.`);let C=q2(_&&_.map(E=>Object.assign({},E,{params:Object.assign({},f,E.params),pathname:bn([g,s.encodeLocation?s.encodeLocation(E.pathname.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:E.pathname]),pathnameBase:E.pathnameBase==="/"?g:bn([g,s.encodeLocation?s.encodeLocation(E.pathnameBase.replace(/%/g,"%25").replace(/\?/g,"%3F").replace(/#/g,"%23")).pathname:E.pathnameBase])})),i,l);return r&&C?m.createElement(ll.Provider,{value:{location:{pathname:"/",search:"",hash:"",state:null,key:"default",unstable_mask:void 0,...b},navigationType:"POP"}},C):C}function H2(){let n=Q2(),r=w2(n)?`${n.status} ${n.statusText}`:n instanceof Error?n.message:JSON.stringify(n),l=n instanceof Error?n.stack:null,s="rgba(200,200,200, 0.5)",i={padding:"0.5rem",backgroundColor:s},u={padding:"2px 4px",backgroundColor:s},f=null;return console.error("Error handled by React Router default ErrorBoundary:",n),f=m.createElement(m.Fragment,null,m.createElement("p",null,"💿 Hey developer 👋"),m.createElement("p",null,"You can provide a way better UX than this when your app throws errors by providing your own ",m.createElement("code",{style:u},"ErrorBoundary")," or"," ",m.createElement("code",{style:u},"errorElement")," prop on your route.")),m.createElement(m.Fragment,null,m.createElement("h2",null,"Unexpected Application Error!"),m.createElement("h3",{style:{fontStyle:"italic"}},r),l?m.createElement("pre",{style:i},l):null,f)}var U2=m.createElement(H2,null),xy=class extends m.Component{constructor(n){super(n),this.state={location:n.location,revalidation:n.revalidation,error:n.error}}static getDerivedStateFromError(n){return{error:n}}static getDerivedStateFromProps(n,r){return r.location!==n.location||r.revalidation!=="idle"&&n.revalidation==="idle"?{error:n.error,location:n.location,revalidation:n.revalidation}:{error:n.error!==void 0?n.error:r.error,location:r.location,revalidation:n.revalidation||r.revalidation}}componentDidCatch(n,r){this.props.onError?this.props.onError(n,r):console.error("React Router caught the following error during render",n)}render(){let n=this.state.error;if(this.context&&typeof n=="object"&&n&&"digest"in n&&typeof n.digest=="string"){const l=j2(n.digest);l&&(n=l)}let r=n!==void 0?m.createElement(tn.Provider,{value:this.props.routeContext},m.createElement(Wd.Provider,{value:n,children:this.props.component})):this.props.children;return this.context?m.createElement(B2,{error:n},r):r}};xy.contextType=C2;var cd=new WeakMap;function B2({children:n,error:r}){let{basename:l}=m.useContext(Pt);if(typeof r=="object"&&r&&"digest"in r&&typeof r.digest=="string"){let s=O2(r.digest);if(s){let i=cd.get(r);if(i)throw i;let u=fy(s.location,l);if(dy&&!cd.get(r))if(u.isExternal||s.reloadDocument)window.location.href=u.absoluteURL||u.to;else{const f=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(u.to,{replace:s.replace}));throw cd.set(r,f),f}return m.createElement("meta",{httpEquiv:"refresh",content:`0;url=${u.absoluteURL||u.to}`})}}return n}function P2({routeContext:n,match:r,children:l}){let s=m.useContext(Xr);return s&&s.static&&s.staticContext&&(r.route.errorElement||r.route.ErrorBoundary)&&(s.staticContext._deepestRenderedBoundaryId=r.route.id),m.createElement(tn.Provider,{value:n},l)}function q2(n,r=[],l){let s=l?.state;if(n==null){if(!s)return null;if(s.errors)n=s.matches;else if(r.length===0&&!s.initialized&&s.matches.length>0)n=s.matches;else return null}let i=n,u=s?.errors;if(u!=null){let x=i.findIndex(b=>b.route.id&&u?.[b.route.id]!==void 0);$e(x>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(u).join(",")}`),i=i.slice(0,Math.min(i.length,x+1))}let f=!1,p=-1;if(l&&s){f=s.renderFallback;for(let x=0;x=0?i=i.slice(0,p+1):i=[i[0]];break}}}}let g=l?.onError,v=s&&g?(x,b)=>{g(x,{location:s.location,params:s.matches?.[0]?.params??{},unstable_pattern:E2(s.matches),errorInfo:b})}:void 0;return i.reduceRight((x,b,w)=>{let A,_=!1,C=null,E=null;s&&(A=u&&b.route.id?u[b.route.id]:void 0,C=b.route.errorElement||U2,f&&(p<0&&w===0?(by("route-fallback",!1,"No `HydrateFallback` element provided to render during initial hydration"),_=!0,E=null):p===w&&(_=!0,E=b.route.hydrateFallbackElement||null)));let M=r.concat(i.slice(0,w+1)),H=()=>{let D;return A?D=C:_?D=E:b.route.Component?D=m.createElement(b.route.Component,null):b.route.element?D=b.route.element:D=x,m.createElement(P2,{match:b,routeContext:{outlet:x,matches:M,isDataRoute:s!=null},children:D})};return s&&(b.route.ErrorBoundary||b.route.errorElement||w===0)?m.createElement(xy,{location:s.location,revalidation:s.revalidation,component:C,error:A,children:H(),routeContext:{outlet:null,matches:M,isDataRoute:!0},onError:v}):H()},null)}function ef(n){return`${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function V2(n){let r=m.useContext(Xr);return $e(r,ef(n)),r}function G2(n){let r=m.useContext(yi);return $e(r,ef(n)),r}function Y2(n){let r=m.useContext(tn);return $e(r,ef(n)),r}function tf(n){let r=Y2(n),l=r.matches[r.matches.length-1];return $e(l.route.id,`${n} can only be used on routes that contain a unique "id"`),l.route.id}function X2(){return tf("useRouteId")}function Q2(){let n=m.useContext(Wd),r=G2("useRouteError"),l=tf("useRouteError");return n!==void 0?n:r.errors?.[l]}function K2(){let{router:n}=V2("useNavigate"),r=tf("useNavigate"),l=m.useRef(!1);return vy(()=>{l.current=!0}),m.useCallback(async(i,u={})=>{en(l.current,gy),l.current&&(typeof i=="number"?await n.navigate(i):await n.navigate(i,{fromRouteId:r,...u}))},[n,r])}var Jg={};function by(n,r,l){!r&&!Jg[n]&&(Jg[n]=!0,en(!1,l))}m.memo($2);function $2({routes:n,future:r,state:l,isStatic:s,onError:i}){return yy(n,void 0,{state:l,isStatic:s,onError:i})}function Sy({to:n,replace:r,state:l,relative:s}){$e(Qr()," may be used only in the context of a component.");let{static:i}=m.useContext(Pt);en(!i," must not be used on the initial render in a . This is a no-op, but you should modify your code so the is only ever rendered in response to some user interaction or state change.");let{matches:u}=m.useContext(tn),{pathname:f}=Ct(),p=Kr(),g=vi(n,Jd(u),f,s==="path"),v=JSON.stringify(g);return m.useEffect(()=>{p(JSON.parse(v),{replace:r,state:l,relative:s})},[p,v,s,r,l]),null}function F2(n){return k2(n.context)}function ee(n){$e(!1,"A is only ever to be used as the child of element, never rendered directly. Please wrap your in a .")}function Z2({basename:n="/",children:r=null,location:l,navigationType:s="POP",navigator:i,static:u=!1,unstable_useTransitions:f}){$e(!Qr(),"You cannot render a inside another . You should never have more than one in your app.");let p=n.replace(/^\/*/,"/"),g=m.useMemo(()=>({basename:p,navigator:i,static:u,unstable_useTransitions:f,future:{}}),[p,i,u,f]);typeof l=="string"&&(l=Yr(l));let{pathname:v="/",search:x="",hash:b="",state:w=null,key:A="default",unstable_mask:_}=l,C=m.useMemo(()=>{let E=Yn(v,p);return E==null?null:{location:{pathname:E,search:x,hash:b,state:w,key:A,unstable_mask:_},navigationType:s}},[p,v,x,b,w,A,s,_]);return en(C!=null,` is not able to match the URL "${v}${x}${b}" because it does not start with the basename, so the won't render anything.`),C==null?null:m.createElement(Pt.Provider,{value:g},m.createElement(ll.Provider,{children:r,value:C}))}function I2({children:n,location:r}){return L2(Od(n),r)}function Od(n,r=[]){let l=[];return m.Children.forEach(n,(s,i)=>{if(!m.isValidElement(s))return;let u=[...r,i];if(s.type===m.Fragment){l.push.apply(l,Od(s.props.children,u));return}$e(s.type===ee,`[${typeof s.type=="string"?s.type:s.type.name}] is not a component. All component children of must be a or `),$e(!s.props.index||!s.props.children,"An index route cannot have child routes.");let f={id:s.props.id||u.join("-"),caseSensitive:s.props.caseSensitive,element:s.props.element,Component:s.props.Component,index:s.props.index,path:s.props.path,middleware:s.props.middleware,loader:s.props.loader,action:s.props.action,hydrateFallbackElement:s.props.hydrateFallbackElement,HydrateFallback:s.props.HydrateFallback,errorElement:s.props.errorElement,ErrorBoundary:s.props.ErrorBoundary,hasErrorBoundary:s.props.hasErrorBoundary===!0||s.props.ErrorBoundary!=null||s.props.errorElement!=null,shouldRevalidate:s.props.shouldRevalidate,handle:s.props.handle,lazy:s.props.lazy};s.props.children&&(f.children=Od(s.props.children,u)),l.push(f)}),l}var Ys="get",Xs="application/x-www-form-urlencoded";function xi(n){return typeof HTMLElement<"u"&&n instanceof HTMLElement}function J2(n){return xi(n)&&n.tagName.toLowerCase()==="button"}function W2(n){return xi(n)&&n.tagName.toLowerCase()==="form"}function ew(n){return xi(n)&&n.tagName.toLowerCase()==="input"}function tw(n){return!!(n.metaKey||n.altKey||n.ctrlKey||n.shiftKey)}function nw(n,r){return n.button===0&&(!r||r==="_self")&&!tw(n)}function jd(n=""){return new URLSearchParams(typeof n=="string"||Array.isArray(n)||n instanceof URLSearchParams?n:Object.keys(n).reduce((r,l)=>{let s=n[l];return r.concat(Array.isArray(s)?s.map(i=>[l,i]):[[l,s]])},[]))}function aw(n,r){let l=jd(n);return r&&r.forEach((s,i)=>{l.has(i)||r.getAll(i).forEach(u=>{l.append(i,u)})}),l}var js=null;function rw(){if(js===null)try{new FormData(document.createElement("form"),0),js=!1}catch{js=!0}return js}var ow=new Set(["application/x-www-form-urlencoded","multipart/form-data","text/plain"]);function ud(n){return n!=null&&!ow.has(n)?(en(!1,`"${n}" is not a valid \`encType\` for \`
\`/\`\` and will default to "${Xs}"`),null):n}function lw(n,r){let l,s,i,u,f;if(W2(n)){let p=n.getAttribute("action");s=p?Yn(p,r):null,l=n.getAttribute("method")||Ys,i=ud(n.getAttribute("enctype"))||Xs,u=new FormData(n)}else if(J2(n)||ew(n)&&(n.type==="submit"||n.type==="image")){let p=n.form;if(p==null)throw new Error('Cannot submit a - - {/* Global Search */} -
- - setSearchValue(e.target.value)} - onFocus={() => setSearchFocused(true)} - onBlur={() => setTimeout(() => setSearchFocused(false), 200)} - className={cn( - 'pl-9 h-9 text-sm transition-all duration-300', - 'bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]', - 'text-[var(--dg-text-primary)] placeholder:text-[var(--dg-text-muted)]', - 'focus:border-[var(--dg-blue)] focus:ring-1 focus:ring-[var(--dg-blue)]/30', - 'hover:border-[var(--dg-border-hover)]', - )} - /> - - ⌘K - - - {/* Search Dropdown */} - {searchFocused && searchValue && ( -
-
- 快速导航 -
- {quickNavItems - .filter((item) => - item.name.toLowerCase().includes(searchValue.toLowerCase()) - ) - .map((item) => ( - - ))} - {quickNavItems.filter((item) => - item.name.toLowerCase().includes(searchValue.toLowerCase()) - ).length === 0 && ( -
- 未找到匹配的结果 -
- )} -
- )} -
{/* Right: Actions */} diff --git a/frontend/src/components/layout/Sidebar.tsx b/frontend/src/components/layout/Sidebar.tsx index e805cf7..8822bab 100644 --- a/frontend/src/components/layout/Sidebar.tsx +++ b/frontend/src/components/layout/Sidebar.tsx @@ -35,6 +35,9 @@ import { Boxes, Clock, Rocket, + ShieldCheck, + FileSearch, + LogIn, } from 'lucide-react'; import { Button } from '@/components/ui/button'; @@ -132,14 +135,26 @@ const menuItems: MenuItem[] = [ { id: 'ai-predictive', name: '容量预测', icon: BarChart3, path: '/ai-predictive' }, ], }, - { id: 'approval', name: '资源申请', icon: CheckSquare, path: '/approval' }, + { id: 'approval', name: '资源申请', icon: CheckSquare, + children: [ + { id: 'approval-resource', name: '资源申请', icon: Server, path: '/approval/resource' }, + { id: 'approval-app', name: '应用申请', icon: Rocket, path: '/approval/app' }, + { id: 'approval-permission', name: '权限审批', icon: ShieldCheck, path: '/approval/permission' }, + ], + }, + { + id: 'audit', name: '安全审计', icon: FileSearch, + children: [ + { id: 'audit-terminal', name: '终端审计', icon: Terminal, path: '/audit/terminal' }, + { id: 'audit-operations', name: '操作审计', icon: FileCode, path: '/audit/operations' }, + { id: 'audit-login', name: '登录日志', icon: LogIn, path: '/audit/login-logs' }, + ], + }, { id: 'system', name: '系统管理', icon: Settings, children: [ { id: 'users', name: '用户管理', icon: Users, path: '/users' }, { id: 'roles', name: '角色权限', icon: Shield, path: '/roles' }, - { id: 'logs-audit', name: '操作审计', icon: FileCode, path: '/logs-audit' }, - { id: 'terminal-audit', name: '终端审计', icon: Terminal, path: '/terminal-audit' }, { id: 'credentials', name: '凭证配置', icon: Shield, path: '/credentials' }, { id: 'settings', name: '系统设置', icon: Settings, path: '/settings' }, ], diff --git a/frontend/src/components/monitor/alert-center/AlertCenter.tsx b/frontend/src/components/monitor/alert-center/AlertCenter.tsx index 232bd7c..afa13a3 100644 --- a/frontend/src/components/monitor/alert-center/AlertCenter.tsx +++ b/frontend/src/components/monitor/alert-center/AlertCenter.tsx @@ -8,6 +8,7 @@ import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Badge } from '@/components/ui/badge'; import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'; +import { StatStrip } from '@/components/ui/stat-strip'; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from '@/components/ui/select'; @@ -24,6 +25,7 @@ import { AlertDetailDialog, AlertSilenceDialog } from './AlertCenterDetail'; import { AlertRuleDialog } from '@/components/monitor/AlertRuleDialog'; import { ContactDialog } from './ContactDialog'; import { ContactGroupDialog } from './ContactGroupDialog'; +import SilenceRuleTab from './SilenceRuleTab'; import type { Contact, ContactGroup } from './alert-center-helpers'; const AlertCenter: React.FC = () => { @@ -151,8 +153,21 @@ const AlertCenter: React.FC = () => { const handleSilence = async (id: string, duration: string) => { try { - await alertCenterApi.silence(id, duration); - toast.success('告警已静默'); + const alert = alerts.find(a => a.id === id); + const now = new Date(); + const match = duration.match(/^(\d+)([hd])$/); + const num = match ? parseInt(match[1]) : 1; + const unit = match?.[2] || 'h'; + const hours = unit === 'd' ? num * 24 : num; + const endTime = new Date(now.getTime() + hours * 3600_000); + await alertCenterApi.createSilence({ + name: `静默: ${alert?.title || id} (${duration})`, + description: `从告警列表快速静默 — ${alert?.source || ''}`, + silence_type: 'onetime', + start_time: now.toISOString(), + end_time: endTime.toISOString(), + }); + toast.success(`告警已静默 ${duration}`); setSilenceOpen(false); fetchAlerts(); } catch { @@ -205,66 +220,21 @@ const AlertCenter: React.FC = () => { return (
- {/* 统计卡片 — 紧凑 */} -
- 0 ? 'border-red-500 border-2' : ''}> - -
-
-

触发中

-

0 ? 'text-red-600' : ''}`}>{stats.firing}

-
-
0 ? 'bg-red-100' : 'bg-gray-100'}`}> - 0 ? 'text-red-600' : 'text-gray-600'}`} /> -
-
-
-
- - -
-
-

严重告警

-

{stats.critical}

-
-
- -
-
-
-
- - -
-
-

警告告警

-

{stats.warning}

-
-
- -
-
-
-
- - -
-
-

今日已解决

-

{stats.resolved}

-
-
- -
-
-
-
-
+ {/* 统计 — 紧凑条 */} + 0 ? 'red' : 'muted' }, + { label: '严重', value: stats.critical, color: 'red' }, + { label: '警告', value: stats.warning, color: 'amber' }, + { label: '已解决', value: stats.resolved, color: 'emerald' }, + ]} + /> - + 告警列表 告警规则 + 静默规则 报警联系人 报警联系组 @@ -501,6 +471,11 @@ const AlertCenter: React.FC = () => { )} + {/* 静默规则 Tab */} + + + + {/* 报警联系人 Tab */}
diff --git a/frontend/src/components/monitor/alert-center/SilenceDialog.tsx b/frontend/src/components/monitor/alert-center/SilenceDialog.tsx new file mode 100644 index 0000000..404d3d7 --- /dev/null +++ b/frontend/src/components/monitor/alert-center/SilenceDialog.tsx @@ -0,0 +1,255 @@ +// 告警静默规则创建/编辑弹框 // Logan.Li +import React, { useState, useEffect } from 'react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Badge } from '@/components/ui/badge'; +import { + Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, +} from '@/components/ui/dialog'; +import { + Select, SelectContent, SelectItem, SelectTrigger, SelectValue, +} from '@/components/ui/select'; +import { toast } from 'sonner'; +import { alertCenterApi } from '@/services/api'; + +// 静默类型中文标签 +const SILENCE_TYPE_LABELS: Record = { + onetime: '一次性', + daily: '每天循环', + weekly: '每周循环', +}; + +const WEEKDAY_LABELS = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']; + +export interface SilenceData { + id?: number; + name: string; + description: string; + silence_type: string; + start_time: string; + end_time: string; + weekdays: number[]; +} + +function toLocalDateTimeInput(d: Date): string { + const off = d.getTimezoneOffset(); + const local = new Date(d.getTime() - off * 60000); + return local.toISOString().slice(0, 16); +} + +function addHours(d: Date, hours: number): Date { + return new Date(d.getTime() + hours * 3600_000); +} + +export function SilenceDialog({ + open, + onOpenChange, + editingSilence, + onSaved, +}: { + open: boolean; + onOpenChange: (open: boolean) => void; + editingSilence: any; + onSaved: () => void; +}) { + const [saving, setSaving] = useState(false); + const [name, setName] = useState(''); + const [description, setDescription] = useState(''); + const [silenceType, setSilenceType] = useState('onetime'); + const [startTime, setStartTime] = useState(''); + const [endTime, setEndTime] = useState(''); + const [weekdays, setWeekdays] = useState([]); + + // 编辑时回填 + useEffect(() => { + if (editingSilence) { + setName(editingSilence.name || ''); + setDescription(editingSilence.description || ''); + setSilenceType(editingSilence.silence_type || 'onetime'); + // 解析时间 + const st = editingSilence.start_time ? new Date(editingSilence.start_time) : new Date(); + const et = editingSilence.end_time ? new Date(editingSilence.end_time) : addHours(new Date(), 1); + setStartTime(toLocalDateTimeInput(st)); + setEndTime(toLocalDateTimeInput(et)); + // 解析 weekdays + let wds: number[] = []; + if (editingSilence.weekday_list) { + wds = editingSilence.weekday_list; + } else if (editingSilence.weekdays) { + try { wds = JSON.parse(editingSilence.weekdays); } catch { /* ignore */ } + } + setWeekdays(wds); + } else { + setName(''); + setDescription(''); + setSilenceType('onetime'); + const now = new Date(); + setStartTime(toLocalDateTimeInput(now)); + setEndTime(toLocalDateTimeInput(addHours(now, 2))); + setWeekdays([]); + } + }, [editingSilence, open]); + + const toggleWeekday = (day: number) => { + setWeekdays(prev => + prev.includes(day) ? prev.filter(d => d !== day) : [...prev, day] + ); + }; + + const handleSave = async () => { + if (!name.trim()) { + toast.error('请填写规则名称'); + return; + } + if (!endTime) { + toast.error('请设置结束时间'); + return; + } + if (silenceType === 'weekly' && weekdays.length === 0) { + toast.error('每周静默需要选择至少一个星期'); + return; + } + + const payload: Record = { + name: name.trim(), + description: description.trim(), + silence_type: silenceType, + start_time: startTime, + end_time: endTime, + weekdays: silenceType === 'weekly' ? weekdays : [], + }; + + setSaving(true); + try { + if (editingSilence) { + await alertCenterApi.updateSilence(editingSilence.id, payload); + toast.success('静默规则已更新'); + } else { + await alertCenterApi.createSilence(payload); + toast.success('静默规则已创建'); + } + onOpenChange(false); + onSaved(); + } catch { + toast.error('保存失败'); + } finally { + setSaving(false); + } + }; + + return ( + + + + + {editingSilence ? '编辑静默规则' : '创建静默规则'} + + + 静默期间匹配的告警将不会触发通知 + + +
+ {/* 名称 */} +
+ + setName(e.target.value)} + placeholder="如:维护窗口静默" + className="bg-[var(--dg-bg-primary)]" + /> +
+ + {/* 描述 */} +
+ + setDescription(e.target.value)} + placeholder="可选备注" + className="bg-[var(--dg-bg-primary)]" + /> +
+ + {/* 静默类型 */} +
+ + +
+ + {/* 时间窗口 */} +
+
+ + setStartTime(e.target.value)} + className="bg-[var(--dg-bg-primary)]" + /> +
+
+ + setEndTime(e.target.value)} + className="bg-[var(--dg-bg-primary)]" + /> +
+
+ + {/* 星期选择(仅 weekly) */} + {silenceType === 'weekly' && ( +
+ +
+ {WEEKDAY_LABELS.map((label, idx) => ( + + ))} +
+
+ )} + + {/* 提示 */} +
+ {silenceType === 'onetime' && '在指定时间窗口内,所有匹配条件的告警将被静默。窗口结束后自动恢复正常。'} + {silenceType === 'daily' && '每天在指定时段内静默告警,适合非工作时间免打扰。'} + {silenceType === 'weekly' && '仅在选定星期的指定时段内静默,适合周末维护窗口。'} +
+
+ + + + +
+
+ ); +} diff --git a/frontend/src/components/monitor/alert-center/SilenceRuleTab.tsx b/frontend/src/components/monitor/alert-center/SilenceRuleTab.tsx new file mode 100644 index 0000000..1b8d723 --- /dev/null +++ b/frontend/src/components/monitor/alert-center/SilenceRuleTab.tsx @@ -0,0 +1,226 @@ +// 告警静默规则管理 Tab — 列表 + 创建/编辑/删除/启停 // Logan.Li +import React, { useState, useEffect, useCallback } from 'react'; +import { VolumeX, Plus, RefreshCw, Clock, Calendar, Repeat, Edit, Trash2 } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Badge } from '@/components/ui/badge'; +import { Card, CardContent } from '@/components/ui/card'; +import { Switch } from '@/components/ui/switch'; +import { toast } from 'sonner'; +import { useConfirm } from '@/components/ui/confirm-dialog'; +import { alertCenterApi } from '@/services/api'; +import { SilenceDialog } from './SilenceDialog'; + +const SILENCE_TYPE_LABELS: Record = { + onetime: '一次性', + daily: '每天', + weekly: '每周', +}; + +const WEEKDAY_LABELS = ['日', '一', '二', '三', '四', '五', '六']; + +function formatTime(t: string | Date): string { + if (!t) return '—'; + const d = typeof t === 'string' ? new Date(t) : t; + if (isNaN(d.getTime())) return '—'; + return d.toLocaleString('zh-CN', { + month: '2-digit', day: '2-digit', + hour: '2-digit', minute: '2-digit', + }); +} + +const SilenceRuleTab: React.FC = () => { + const confirm = useConfirm(); + const [silences, setSilences] = useState([]); + const [loading, setLoading] = useState(false); + const [dialogOpen, setDialogOpen] = useState(false); + const [editing, setEditing] = useState(null); + + const fetchSilences = useCallback(async () => { + setLoading(true); + try { + const res: Record = await alertCenterApi.getSilences(); + const list = res?.list || res?.data?.list || []; + setSilences(list); + } catch { + toast.error('获取静默规则失败'); + } finally { + setLoading(false); + } + }, []); + + useEffect(() => { + fetchSilences(); + }, [fetchSilences]); + + const handleAdd = () => { + setEditing(null); + setDialogOpen(true); + }; + + const handleEdit = (silence: any) => { + setEditing(silence); + setDialogOpen(true); + }; + + const handleDelete = async (silence: any) => { + const ok = await confirm({ + title: '删除静默规则', + description: `确定删除「${silence.name}」?删除后该规则匹配的告警将恢复通知。`, + confirmText: '删除', + variant: 'destructive', + }); + if (!ok) return; + try { + await alertCenterApi.deleteSilence(silence.id); + toast.success('已删除'); + fetchSilences(); + } catch { + toast.error('删除失败'); + } + }; + + const handleToggle = async (silence: any) => { + try { + await alertCenterApi.toggleSilence(silence.id); + toast.success(silence.status === 1 ? '已禁用' : '已启用'); + fetchSilences(); + } catch { + toast.error('操作失败'); + } + }; + + const isCurrentlyActive = (s: any): boolean => { + if (s.is_active !== undefined) return s.is_active; + if (s.status !== 1) return false; + const now = new Date(); + const st = new Date(s.start_time); + const et = new Date(s.end_time); + return now >= st && now <= et; + }; + + return ( +
+ {/* 操作栏 */} +
+
+ + 共 {silences.length} 条规则 +
+
+ + +
+
+ + {/* 规则列表 */} + {loading && silences.length === 0 ? ( +
+

加载中...

+
+ ) : silences.length === 0 ? ( +
+ +

暂无静默规则

+

点击「添加静默规则」创建维护窗口或免打扰时段

+
+ ) : ( +
+ {silences.map((s) => { + const active = isCurrentlyActive(s); + const enabled = s.status === 1; + const sType = s.silence_type || 'onetime'; + const weekdayList: number[] = s.weekday_list || (() => { + try { return JSON.parse(s.weekdays || '[]'); } catch { return []; } + })(); + return ( + + +
+ {/* 左侧信息 */} +
+
+ {s.name} + {/* 类型 Badge */} + + {sType === 'onetime' && } + {sType === 'daily' && } + {sType === 'weekly' && } + {SILENCE_TYPE_LABELS[sType] || sType} + + {/* 活跃状态 */} + {active && ( + 生效中 + )} + {!enabled && ( + 已禁用 + )} +
+ + {s.description && ( +

{s.description}

+ )} + + {/* 时间窗口 */} +
+ + {sType === 'onetime' + ? `${formatTime(s.start_time)} — ${formatTime(s.end_time)}` + : `每日 ${formatTime(s.start_time)} — ${formatTime(s.end_time)}` + } + + {sType === 'weekly' && weekdayList.length > 0 && ( + + {weekdayList.sort((a,b)=>a-b).map(d => ( + + {WEEKDAY_LABELS[d]} + + ))} + + )} +
+ + {/* 创建时间 */} +
+ 创建于 {formatTime(s.created_at)} +
+
+ + {/* 右侧操作 */} +
+ handleToggle(s)} + /> + + +
+
+
+
+ ); + })} +
+ )} + + {/* 创建/编辑弹框 */} + +
+ ); +}; + +export default SilenceRuleTab; diff --git a/frontend/src/components/monitor/dashboard/PrometheusDashboard.tsx b/frontend/src/components/monitor/dashboard/PrometheusDashboard.tsx index 1799038..29c75c4 100644 --- a/frontend/src/components/monitor/dashboard/PrometheusDashboard.tsx +++ b/frontend/src/components/monitor/dashboard/PrometheusDashboard.tsx @@ -4,6 +4,7 @@ import { Server, Loader2, Activity, Cpu, RefreshCw, AlertTriangle, Container, Za import { Button } from '@/components/ui/button'; import { Badge } from '@/components/ui/badge'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; +import { StatStrip } from '@/components/ui/stat-strip'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { http } from '@/services/http'; @@ -47,12 +48,14 @@ const Box = ( p: any) => }> = ({ d }) => (
-
-
{d.podCount?.[0]?.value || 0}
Pods
-
{d.deployCount?.[0]?.value || 0}
Deployments
-
{d.nodeCount?.[0]?.value || 0}
Nodes
-
{d.nsPods?.length || 0}
Namespaces
-
+
节点 CPU / 内存利用率
{(d.nodeCPU || []).map(( n: any, i: number) => { @@ -93,10 +96,12 @@ const NodePanel: React.FC<{ d: Record}> = ({ d }) => ( const PodPanel: React.FC<{ d: Record}> = ({ d }) => (
-
-
{d.running?.[0]?.value||0}
Running
-
{d.pending?.[0]?.value||0}
Pending
-
+
CPU Top 10
{(d.cpuTop||[]).map(( p: any,i:number)=>
{i+1}{p.pod}
)}
内存 Top 10
{(d.memTop||[]).map(( p: any,i:number)=>
{i+1}{p.pod}{fmtBytes(Number(p.value||0))}
)}
diff --git a/frontend/src/components/monitor/trace/TraceManager.tsx b/frontend/src/components/monitor/trace/TraceManager.tsx index be868f5..5d4e049 100644 --- a/frontend/src/components/monitor/trace/TraceManager.tsx +++ b/frontend/src/components/monitor/trace/TraceManager.tsx @@ -26,6 +26,7 @@ import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Badge } from '@/components/ui/badge'; import { Card, CardContent, CardHeader, CardTitle} from '@/components/ui/card'; +import { StatStrip } from '@/components/ui/stat-strip'; import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog'; @@ -260,64 +261,14 @@ const TraceManager: React.FC = () => { return (
{/* 统计卡片 */} -
- - -
-
-

总请求数

-

{services.reduce((sum, s) => sum + s.requestCount, 0).toLocaleString()}

-
-
- -
-
-
-
- - -
-
-

平均错误率

-

- {(services.reduce((sum, s) => sum + s.errorRate, 0) / (services.length || 1)).toFixed(2)}% -

-
-
- -
-
-
-
- - -
-
-

平均延迟

-

- {formatDuration(services.reduce((sum, s) => sum + s.avgDuration, 0) / (services.length || 1))} -

-
-
- -
-
-
-
- - -
-
-

服务数量

-

{services.length}

-
-
- -
-
-
-
-
+ sum + s.requestCount, 0).toLocaleString(), color: 'blue' }, + { label: '错误率', value: `${(services.reduce((sum, s) => sum + s.errorRate, 0) / (services.length || 1)).toFixed(2)}%`, color: 'red' }, + { label: '平均延迟', value: formatDuration(services.reduce((sum, s) => sum + s.avgDuration, 0) / (services.length || 1)), color: 'amber' }, + { label: '服务数', value: services.length, color: 'purple' }, + ]} + /> diff --git a/frontend/src/components/server/ServerFileBrowser.tsx b/frontend/src/components/server/ServerFileBrowser.tsx new file mode 100644 index 0000000..d96bdba --- /dev/null +++ b/frontend/src/components/server/ServerFileBrowser.tsx @@ -0,0 +1,338 @@ +// 服务器文件浏览器 — SFTP 浏览/上传/下载(参考 deployment FileBrowserDialog 设计) +import { useState, useEffect, useRef, useCallback } from 'react'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogTitle, +} from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { Badge } from '@/components/ui/badge'; +import { + Folder, + FolderOpen, + File, + Upload, + Download, + Trash2, + ArrowLeft, + Home, + RefreshCw, + Loader2, + FolderPlus, + ChevronRight, + X, + Maximize2, + Minimize2, +} from 'lucide-react'; +import { cn } from '@/lib/utils'; +import { serverApi } from '@/services/api'; + +interface FileItem { + name: string; + path: string; + size: number; + is_dir: boolean; + mod_time: string; + mode: string; +} + +interface Breadcrumb { + name: string; + path: string; +} + +const formatSize = (bytes: number) => { + if (bytes < 1024) return `${bytes} B`; + if (bytes < 1048576) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / 1048576).toFixed(2)} MB`; +}; + +interface Props { + open: boolean; + onOpenChange: (open: boolean) => void; + serverId: number | null; + serverName: string; +} + +export function ServerFileBrowser({ open, onOpenChange, serverId, serverName }: Props) { + const [items, setItems] = useState([]); + const [breadcrumbs, setBreadcrumbs] = useState([]); + const [currentPath, setCurrentPath] = useState('/'); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(''); + const [uploading, setUploading] = useState(false); + const [fullscreen, setFullscreen] = useState(false); + const inputRef = useRef(null); + + const fetchDir = useCallback(async (path: string) => { + if (!serverId) return; + setLoading(true); + setError(''); + try { + const resp = await serverApi.listFiles(serverId, path) as any; + const data = resp?.data || resp; + setItems(data.items || []); + setBreadcrumbs(data.breadcrumbs || []); + setCurrentPath(data.path || path); + } catch (err: any) { + setError(err?.message || '加载目录失败'); + setItems([]); + } finally { + setLoading(false); + } + }, [serverId]); + + useEffect(() => { + if (open && serverId) { + setFullscreen(false); + fetchDir('/'); + } + }, [open, serverId, fetchDir]); + + const handleDownload = async (filePath: string) => { + if (!serverId) return; + try { + await serverApi.downloadFile(serverId, filePath); + } catch (err) { + setError('下载失败: ' + ((err as any)?.message || '')); + } + }; + + const handleUpload = async (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file || !serverId) return; + setUploading(true); + try { + await serverApi.uploadFile(serverId, currentPath, file); + await fetchDir(currentPath); + } catch (err: any) { + setError(err?.message || '上传失败'); + } finally { + setUploading(false); + if (inputRef.current) inputRef.current.value = ''; + } + }; + + const handleDelete = async (filePath: string, isDir: boolean) => { + if (!serverId || !confirm(`确认删除 ${isDir ? '目录' : '文件'} "${filePath}"?`)) return; + try { + await serverApi.deleteFile(serverId, filePath); + await fetchDir(currentPath); + } catch (err: any) { + setError(err?.message || '删除失败'); + } + }; + + const handleMkdir = async () => { + const name = prompt('输入目录名:'); + if (!name || !serverId) return; + const newPath = currentPath === '/' ? `/${name}` : `${currentPath}/${name}`; + try { + await serverApi.mkdir(serverId, newPath); + await fetchDir(currentPath); + } catch (err: any) { + setError(err?.message || '创建失败'); + } + }; + + const sortedItems = [...items].sort((a, b) => { + if (a.is_dir !== b.is_dir) return a.is_dir ? -1 : 1; + return a.name.localeCompare(b.name); + }); + + return ( + + { + // 阻止点击外部关闭,上传中避免误关 + if (uploading) e.preventDefault(); + }} + className={cn( + 'bg-[var(--dg-bg-secondary)] border-[var(--dg-border)] p-0 gap-0', + '!duration-0 !transition-none', + fullscreen + ? '!max-w-none !w-screen !h-screen !rounded-none' + : '' + )} + style={fullscreen + ? { maxWidth: '100vw', width: '100vw', height: '100vh' } + : { maxWidth: '95vw', width: '1100px', maxHeight: '92vh' } + } + > + 文件浏览 — {serverName} + SFTP 文件管理 · 上传 · 下载 · 删除 + + {/* Header */} +
+
+ + + {serverName} + + · SFTP 文件管理 +
+
+ + +
+
+ + {/* Toolbar */} +
+ + + + {error && ( + + setError('')} /> + {error} + + )} +
+ + {/* Breadcrumbs */} +
+ {breadcrumbs.map((crumb, i) => ( + + {i === 0 ? ( + + ) : ( + + )} + {i < breadcrumbs.length - 1 && ( + + )} + + ))} +
+ + {/* File List */} +
+ {loading ? ( +
+ +
+ ) : sortedItems.length === 0 ? ( +
+ +

空目录

+
+ ) : ( + + + + + + + + + + + + + {currentPath !== '/' && ( + { + const parent = currentPath.split('/').slice(0, -1).join('/') || '/'; + fetchDir(parent); + }}> + + + + )} + {sortedItems.map((item) => ( + + + + + + + + + ))} + +
名称大小修改时间权限操作
..
+ {item.is_dir ? ( + + ) : ( + + )} + + {item.is_dir ? ( + + ) : ( + {item.name} + )} + + {item.is_dir ? '-' : formatSize(item.size)} + {item.mod_time}{item.mode} +
+ {!item.is_dir && ( + + )} + +
+
+ )} +
+
+
+ ); +} diff --git a/frontend/src/components/server/ServerManager.tsx b/frontend/src/components/server/ServerManager.tsx index 23662de..e3e3646 100644 --- a/frontend/src/components/server/ServerManager.tsx +++ b/frontend/src/components/server/ServerManager.tsx @@ -40,12 +40,13 @@ import { ChevronRight, } from 'lucide-react'; import { serverApi } from '@/services/api'; -import { ServerStatsCards } from './ServerStatsCards'; +import { ServerStatsStrip } from './ServerStatsStrip'; import { useConfirm } from '@/components/ui/confirm-dialog'; import { toast } from 'sonner'; import { useUserStore } from '@/store'; import { CloudServerImport } from './CloudServerImport'; import { TerminalDialog } from './TerminalDialog'; +import { ServerFileBrowser } from './ServerFileBrowser'; import { ExcelServerImport } from './ExcelServerImport'; import { ServerForm, EMPTY_FORM, type ServerFormData } from './ServerForm'; import { getTags } from './serverHelpers'; @@ -72,6 +73,10 @@ export function ServerManager() { const [terminalOpen, setTerminalOpen] = useState(false); const [terminalServer, setTerminalServer] = useState<{ id: number; name: string; ip: string; hasAuth?: boolean } | null>(null); + // 文件浏览 Dialog 状态 + const [fileBrowserOpen, setFileBrowserOpen] = useState(false); + const [fileBrowserServer, setFileBrowserServer] = useState<{ id: number; name: string } | null>(null); + // 分页状态 const [page, setPage] = useState(1); const [pageSize, setPageSize] = useState(10); @@ -82,6 +87,11 @@ export function ServerManager() { setTerminalOpen(true); }; + const openFileBrowser = ( server: any) => { + setFileBrowserServer({ id: server.id, name: server.hostname }); + setFileBrowserOpen(true); + }; + const loadData = async (kw?: string, st?: string) => { try { setLoading(true); @@ -421,7 +431,7 @@ export function ServerManager() {
{/* Stats Cards */} - + {/* Filters & Table */} @@ -512,6 +522,7 @@ export function ServerManager() { selected={selectedServers.includes(server.id)} onToggleSelect={toggleSelect} onOpenTerminal={openTerminal} + onOpenFiles={openFileBrowser} onOpenEdit={openEditForm} onDelete={handleDelete} /> @@ -603,6 +614,14 @@ export function ServerManager() { serverIp={terminalServer?.ip ?? ''} hasAuth={terminalServer?.hasAuth ?? true} /> + + {/* 文件浏览 Dialog */} +
); } diff --git a/frontend/src/components/server/ServerStatsCards.tsx b/frontend/src/components/server/ServerStatsCards.tsx deleted file mode 100644 index 45d0cd9..0000000 --- a/frontend/src/components/server/ServerStatsCards.tsx +++ /dev/null @@ -1,70 +0,0 @@ -// 服务器统计卡片组件 — 从 ServerManager 提取 // Logan.Li -import { Card, CardContent } from '@/components/ui/card'; -import { Server, Activity, RotateCw, Power } from 'lucide-react'; - -interface ServerStatsCardsProps { - servers: any[]; -} - -export function ServerStatsCards({ servers }: ServerStatsCardsProps) { - const runningCount = servers.filter((s) => s.status === 'running').length; - const maintenanceCount = servers.filter((s) => s.status === 'maintenance').length; - const stoppedCount = servers.filter((s) => s.status === 'stopped').length; - - return ( -
- - -
-
-

服务器总数

-

{servers.length}

-
-
- -
-
-
-
- - -
-
-

运行中

-

{runningCount}

-
-
- -
-
-
-
- - -
-
-

维护中

-

{maintenanceCount}

-
-
- -
-
-
-
- - -
-
-

已停止

-

{stoppedCount}

-
-
- -
-
-
-
-
- ); -} diff --git a/frontend/src/components/server/ServerStatsStrip.tsx b/frontend/src/components/server/ServerStatsStrip.tsx new file mode 100644 index 0000000..8b96e65 --- /dev/null +++ b/frontend/src/components/server/ServerStatsStrip.tsx @@ -0,0 +1,23 @@ +// 服务器统计条 — 紧凑型替代 4 张大卡片 +import { StatStrip } from '@/components/ui/stat-strip'; + +interface ServerStatsStripProps { + servers: any[]; +} + +export function ServerStatsStrip({ servers }: ServerStatsStripProps) { + const runningCount = servers.filter((s) => s.status === 'running').length; + const maintenanceCount = servers.filter((s) => s.status === 'maintenance').length; + const stoppedCount = servers.filter((s) => s.status === 'stopped').length; + + return ( + + ); +} diff --git a/frontend/src/components/server/ServerTableRow.tsx b/frontend/src/components/server/ServerTableRow.tsx index 0b30482..9476396 100644 --- a/frontend/src/components/server/ServerTableRow.tsx +++ b/frontend/src/components/server/ServerTableRow.tsx @@ -12,7 +12,7 @@ import { DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { TableCell, TableRow } from '@/components/ui/table'; -import { Edit, MoreHorizontal, Server as ServerIcon, Terminal, Trash2, Network, HardDrive } from 'lucide-react'; +import { Edit, MoreHorizontal, Server as ServerIcon, Terminal, Trash2, Network, HardDrive, FolderOpen } from 'lucide-react'; import { getStatusBadge, getTags, getUsageColor } from './serverHelpers'; interface ServerTableRowProps { @@ -21,6 +21,7 @@ interface ServerTableRowProps { onToggleSelect: (id: string) => void; onOpenTerminal: ( server: any) => void; onOpenEdit: ( server: any) => void; + onOpenFiles?: ( server: any) => void; onDelete: (id: string) => void; } @@ -30,6 +31,7 @@ export function ServerTableRow({ onToggleSelect, onOpenTerminal, onOpenEdit, + onOpenFiles, onDelete, }: ServerTableRowProps) { const cpuUsage = Number(server.cpu_usage || 0); @@ -145,7 +147,7 @@ export function ServerTableRow({
- @@ -171,6 +173,13 @@ export function ServerTableRow({ 终端 + onOpenFiles?.(server)} + > + + 文件 + { if (el) { containerRef.current.set(sessionId, el); @@ -248,19 +248,25 @@ export function WebShell() { try { entry.term.open(el); entry.opened = true; - requestAnimationFrame(() => { - try { - entry.fit.fit(); - entry.term.focus(); - } catch { - /* noop */ - } + // 延迟适配:等 DOM 布局完全确定 + setTimeout(() => { + try { entry.fit.fit(); entry.term.focus(); } catch { /* noop */ } + }, 100); + // ResizeObserver 持续监听容器大小变化 + const observer = new ResizeObserver(() => { + try { entry.fit.fit(); } catch { /* noop */ } }); + observer.observe(el); + (entry as any)._observer = observer; } catch (e) { console.error('打开终端失败:', e); } } } else { + const entry = termsRef.current.get(sessionId); + if (entry && (entry as any)._observer) { + (entry as any)._observer.disconnect(); + } containerRef.current.delete(sessionId); } }; @@ -399,9 +405,10 @@ export function WebShell() { key={session.id} ref={(el) => registerContainer(session.id, el)} className={cn( - 'absolute inset-0 p-1', + 'absolute inset-0', activeSession === session.id ? 'block' : 'hidden' )} + style={{ padding: 0 }} /> ))}
diff --git a/frontend/src/components/system/LiveMonitorDialog.tsx b/frontend/src/components/system/LiveMonitorDialog.tsx new file mode 100644 index 0000000..2855a51 --- /dev/null +++ b/frontend/src/components/system/LiveMonitorDialog.tsx @@ -0,0 +1,220 @@ +// 终端审计实时监控 Dialog — xterm.js 实时查看在线会话 // Logan.Li +import { useEffect, useRef, useState } from 'react'; +import { Terminal as XTerm } from 'xterm'; +import { FitAddon } from 'xterm-addon-fit'; +import 'xterm/css/xterm.css'; +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { Badge } from '@/components/ui/badge'; +import { Loader2, Monitor, Server, User as UserIcon, Clock } from 'lucide-react'; +import { useUserStore } from '@/store'; + +interface SessionInfo { + session_id: number; + username: string; + server_name: string; + server_ip: string; + start_time: string; + status: string; +} + +interface LiveMonitorProps { + open: boolean; + onOpenChange: (open: boolean) => void; + sessionId: number | null; + sessionInfo?: SessionInfo | null; +} + +export function LiveMonitorDialog({ open, onOpenChange, sessionId, sessionInfo }: LiveMonitorProps) { + const containerRef = useRef(null); + const termRef = useRef(null); + const wsRef = useRef(null); + const [connected, setConnected] = useState(false); + const [connectError, setConnectError] = useState(''); + const [meta, setMeta] = useState(sessionInfo || null); + + useEffect(() => { + if (!open || !sessionId) return; + + const container = containerRef.current; + if (!container) return; + + // Init xterm + const term = new XTerm({ + cursorBlink: false, + fontSize: 13, + fontFamily: 'Menlo, Monaco, "Courier New", monospace', + disableStdin: true, + theme: { + background: '#0a0e14', + foreground: '#d6d6d6', + cursor: '#d6d6d6', + selectionBackground: '#264f78', + black: '#1a1a2e', + red: '#ff6b6b', + green: '#69db7c', + yellow: '#ffd43b', + blue: '#4dabf7', + magenta: '#da77f2', + cyan: '#63e6be', + white: '#d6d6d6', + brightBlack: '#4a4a4a', + brightRed: '#ff8787', + brightGreen: '#8ce99a', + brightYellow: '#ffe066', + brightBlue: '#74c0fc', + brightMagenta: '#e599f7', + brightCyan: '#7ae5d5', + brightWhite: '#f8f9fa', + }, + }); + + const fitAddon = new FitAddon(); + term.loadAddon(fitAddon); + term.open(container); + fitAddon.fit(); + termRef.current = term; + + // Connect WebSocket — try zustand store first, fallback to localStorage + let token = useUserStore.getState().token; + if (!token) { + try { + const stored = JSON.parse(localStorage.getItem('user-storage') || ''); + token = stored?.state?.token || ''; + } catch { /* ignore */ } + } + const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'; + const wsUrl = `${protocol}//${window.location.host}/ws/audit/${sessionId}?token=${encodeURIComponent(token || '')}`; + console.log('[LiveMonitor] Connecting to:', wsUrl.replace(/token=[^&]+/, 'token=***')); + const ws = new WebSocket(wsUrl); + wsRef.current = ws; + + let didOpen = false; + + ws.onopen = () => { + console.log('[LiveMonitor] WS connected for session:', sessionId); + didOpen = true; + setConnected(true); + setConnectError(''); + term.writeln('\x1b[36m[审计监控] 已连接到会话...\x1b[0m'); + }; + + ws.onmessage = (event) => { + try { + const msg = JSON.parse(event.data); + switch (msg.type) { + case 'session_info': + setMeta(msg.payload); + term.writeln(`\x1b[36m用户: ${msg.payload.username} 服务器: ${msg.payload.server_name}\x1b[0m`); + break; + case 'history': + if (msg.data) { + term.write(msg.data); + } + break; + case 'output': + if (msg.data) { + term.write(msg.data); + } + break; + } + } catch { + // ignore parse errors + } + }; + + ws.onerror = (e) => { + console.log('[LiveMonitor] WS error:', e); + setConnectError('WebSocket 连接失败'); + }; + + ws.onclose = (e) => { + console.log('[LiveMonitor] WS closed code:', e.code, 'reason:', e.reason); + if (!didOpen) { + setConnectError(`连接失败 (code=${e.code}): ${e.reason || '认证失败或网络问题'}`); + } + setConnected(false); + term.writeln('\r\n\x1b[33m[审计监控] 连接已断开\x1b[0m'); + }; + + // 5s 超时:如果还没连上,显示错误 + const timeout = setTimeout(() => { + if (!didOpen) { + setConnectError('连接超时 — 请确认已登录且有活跃会话'); + ws.close(); + } + }, 5000); + + return () => { + clearTimeout(timeout); + ws.close(); + term.dispose(); + termRef.current = null; + wsRef.current = null; + setConnected(false); + }; + }, [open, sessionId]); + + const formatTime = (t: string) => { + if (!t) return '--'; + return new Date(t).toLocaleString(); + }; + + return ( + + + + + + 终端实时监控 + {connected && ( + + ● 在线 + + )} + {!connected && !connectError && ( + + + 连接中 + + )} + {connectError && ( + + 连接失败 + + )} + + + {meta && ( +
+ + + {meta.username} + + + + {meta.server_name} ({meta.server_ip}) + + + + {formatTime(meta.start_time)} + +
+ )} +
+
+ +
+ +
+ ); +} diff --git a/frontend/src/components/system/ReplayDialog.tsx b/frontend/src/components/system/ReplayDialog.tsx index c93c0b8..0516cc8 100644 --- a/frontend/src/components/system/ReplayDialog.tsx +++ b/frontend/src/components/system/ReplayDialog.tsx @@ -18,13 +18,22 @@ interface ReplayDialogProps { sessionId: number | null; } +interface AsciicastRow { + time: number; + eventType: string; + data: string; +} + /** - * 终端录制回放 Dialog — 用 xterm.js 重放录制的终端输出 // Logan.Li + * 终端录制回放 Dialog — asciicast v2 定时回放 (KoKo-compatible) */ export function ReplayDialog({ open, onOpenChange, sessionId }: ReplayDialogProps) { const containerRef = useRef(null); const termRef = useRef(null); + const timerRef = useRef | null>(null); const [loading, setLoading] = useState(false); + const [error, setError] = useState(''); + const [progress, setProgress] = useState(0); useEffect(() => { if (!open || !sessionId) return; @@ -34,7 +43,8 @@ export function ReplayDialog({ open, onOpenChange, sessionId }: ReplayDialogProp fontSize: 13, fontFamily: 'Menlo, Monaco, "Courier New", monospace', disableStdin: true, - allowProposedApi: true, + cols: 80, + rows: 24, theme: { background: '#0a0e14', foreground: '#d6d6d6', @@ -48,48 +58,108 @@ export function ReplayDialog({ open, onOpenChange, sessionId }: ReplayDialogProp let cancelled = false; setLoading(true); + setError(''); + setProgress(0); + terminalSessionApi .getRecord(sessionId) - .then(( data: any) => { + .then((raw: any) => { if (cancelled) return; + const data = typeof raw === 'string' ? raw : (raw?.data || raw?.record_data || ''); + + if (!data || data.trim() === '') { + setError('No recording data available for this session'); + setLoading(false); + return; + } + if (containerRef.current) { term.open(containerRef.current); + try { fit.fit(); } catch { /* noop */ } + } + + // Parse asciicast v2 format + const lines = data.split('\n').filter((l: string) => l.trim()); + const rows: AsciicastRow[] = []; + + for (const line of lines) { try { - fit.fit(); + const parsed = JSON.parse(line); + if (Array.isArray(parsed) && parsed.length >= 3) { + // asciicast v2 row: [time, "o", "data"] + rows.push({ time: parsed[0], eventType: parsed[1], data: parsed[2] }); + } + // Header is skipped (JSON object, not array) } catch { - /* noop */ + // Skip lines that can't be parsed } - const output = typeof data === 'string' ? data : ''; - term.write(output); } - }) - .catch(() => { - if (!cancelled && containerRef.current) { - term.open(containerRef.current); - term.write('\x1b[31m无录制数据\x1b[0m\r\n'); + + if (rows.length === 0) { + // Fallback: just write raw data (old format) + term.write(data); + setProgress(100); + setLoading(false); + return; } + + // Timed playback + setLoading(false); + const totalTime = rows[rows.length - 1].time; + let rowIndex = 0; + let lastTime = 0; + + const playNext = () => { + if (cancelled || rowIndex >= rows.length) { + setProgress(100); + return; + } + + const row = rows[rowIndex]; + const delay = (row.time - lastTime) * 1000; // convert to ms + lastTime = row.time; + rowIndex++; + + // Clamp delay to avoid extremely long waits (max 2s between chunks) + const clampedDelay = Math.min(delay, 2000); + + timerRef.current = setTimeout(() => { + if (cancelled) return; + term.write(row.data); + setProgress(Math.round((row.time / totalTime) * 100)); + playNext(); + }, clampedDelay); + }; + + playNext(); }) - .finally(() => { - if (!cancelled) setLoading(false); + .catch((err: any) => { + if (!cancelled) { + console.error('[Replay] Load failed:', err); + setError('Failed to load recording data'); + setLoading(false); + } }); return () => { cancelled = true; - try { - term.dispose(); - } catch { - /* noop */ - } + if (timerRef.current) clearTimeout(timerRef.current); + try { term.dispose(); } catch { /* noop */ } termRef.current = null; }; }, [open, sessionId]); return ( - + - 终端录制回放 #{sessionId ?? ''} - 重放该会话录制的终端输出 + + Terminal Replay #{sessionId ?? ''} + {progress > 0 && progress < 100 && ( + {progress}% + )} + + Replay recorded terminal output
{loading && ( @@ -97,6 +167,19 @@ export function ReplayDialog({ open, onOpenChange, sessionId }: ReplayDialogProp
)} + {error && ( +
+

{error}

+
+ )} + {progress > 0 && progress < 100 && ( +
+
+
+ )}
diff --git a/frontend/src/components/system/SystemManager.tsx b/frontend/src/components/system/SystemManager.tsx index 7f3d3eb..ba50e72 100644 --- a/frontend/src/components/system/SystemManager.tsx +++ b/frontend/src/components/system/SystemManager.tsx @@ -3,14 +3,12 @@ import { useLocation } from 'react-router-dom'; import { useConfirm } from '@/components/ui/confirm-dialog'; import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'; import { Badge } from '@/components/ui/badge'; -import { CheckCircle, XCircle, Users, Shield, FileCode, Settings, TerminalSquare } from 'lucide-react'; +import { CheckCircle, XCircle, Users, Shield, Settings } from 'lucide-react'; import { userApi } from '@/services/api'; import type { Role } from '@/types'; import { SystemUserTab } from './SystemUserTab'; import { SystemRolesTab } from './SystemRolesTab'; -import { SystemLogsTab } from './SystemLogsTab'; import { SystemSettingsTab } from './SystemSettingsTab'; -import { TerminalSessionsTab } from './TerminalSessionsTab'; import { useLdapManagement } from './useLdapManagement'; import type { UserFormData } from './UserFormDialog'; @@ -43,8 +41,6 @@ export function SystemManager() { const pathToTab: Record = { '/users': 'users', '/roles': 'roles', - '/logs-audit': 'logs', - '/terminal-audit': 'terminal', '/settings': 'settings', }; const [activeTab, setActiveTab] = useState(pathToTab[location.pathname] || 'users'); @@ -253,14 +249,6 @@ export function SystemManager() { 角色权限 - - - 操作审计 - - - - 终端审计 - 系统设置 @@ -315,17 +303,6 @@ export function SystemManager() { /> - - - - - - - - diff --git a/frontend/src/components/ui/stat-strip.tsx b/frontend/src/components/ui/stat-strip.tsx new file mode 100644 index 0000000..fed58aa --- /dev/null +++ b/frontend/src/components/ui/stat-strip.tsx @@ -0,0 +1,55 @@ +// 紧凑型统计条 — 替代 4~5 个大卡片的笨重布局 +// 一行显示所有统计项,带颜色区分 +import { cn } from '@/lib/utils'; + +interface StatItem { + label: string; + value: number | string; + color?: string; // tailwind text class or hex + icon?: React.ReactNode; +} + +interface StatStripProps { + items: StatItem[]; + className?: string; +} + +const colorMap: Record = { + blue: { text: 'text-blue-400', bg: 'bg-blue-500/20' }, + emerald: { text: 'text-emerald-400', bg: 'bg-emerald-500/20' }, + amber: { text: 'text-amber-400', bg: 'bg-amber-500/20' }, + red: { text: 'text-red-400', bg: 'bg-red-500/20' }, + purple: { text: 'text-purple-400', bg: 'bg-purple-500/20' }, + cyan: { text: 'text-cyan-400', bg: 'bg-cyan-500/20' }, + muted: { text: 'text-[var(--dg-text-secondary)]', bg: 'bg-[var(--dg-bg-tertiary)]' }, +}; + +export function StatStrip({ items, className }: StatStripProps) { + return ( +
+ {items.map((item, i) => { + const clr = colorMap[item.color || 'muted'] || colorMap.muted; + return ( +
+ {i > 0 && ( + + )} + + {item.label} + {item.value} +
+ ); + })} +
+ ); +} diff --git a/frontend/src/pages/ApprovalAppPage.tsx b/frontend/src/pages/ApprovalAppPage.tsx new file mode 100644 index 0000000..e91577a --- /dev/null +++ b/frontend/src/pages/ApprovalAppPage.tsx @@ -0,0 +1,25 @@ +// 应用申请子页面 — 应用部署、版本发布申请 +import { ApprovalCategoryPage, type FormField } from './ApprovalCategoryPage'; + +const APP_FIELDS: FormField[] = [ + { key: 'app_name', label: '应用名称', type: 'text', placeholder: '如 user-service', required: true }, + { key: 'git_url', label: 'Git 地址', type: 'text', placeholder: '如 https://github.com/org/repo.git', required: true }, + { key: 'branch', label: '分支', type: 'text', defaultValue: 'main', required: true }, + { key: 'language', label: '开发语言', type: 'select', options: ['Java', 'Go', 'Python', 'Node.js', 'C++'], required: true }, + { key: 'http_port', label: 'HTTP 端口', type: 'number', placeholder: '如 8080' }, + { key: 'env', label: '部署环境', type: 'select', options: ['dev', 'staging', 'prod'], required: true }, + { key: 'replicas', label: '副本数', type: 'number', defaultValue: 2, required: true }, + { key: 'remark', label: '备注', type: 'textarea' }, +]; + +export function ApprovalAppPage() { + return ( + + ); +} diff --git a/frontend/src/pages/ApprovalCategoryPage.tsx b/frontend/src/pages/ApprovalCategoryPage.tsx new file mode 100644 index 0000000..4506371 --- /dev/null +++ b/frontend/src/pages/ApprovalCategoryPage.tsx @@ -0,0 +1,273 @@ +// 审批分类通用页面 — 资源申请/应用申请/权限审批三个子页面共用 +import { useState, useEffect, useCallback } from 'react'; +import { Card, CardContent } from '@/components/ui/card'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Badge } from '@/components/ui/badge'; +import { Label } from '@/components/ui/label'; +import { + Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, +} from '@/components/ui/dialog'; +import { + Table, TableBody, TableCell, TableHead, TableHeader, TableRow, +} from '@/components/ui/table'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; +import { Plus, Search, RefreshCw, Clock, CheckCircle, XCircle, FileText, Loader2 } from 'lucide-react'; +import { approvalApi } from '@/services/api'; +import { toast } from 'sonner'; +import { cn } from '@/lib/utils'; + +export interface FormField { + key: string; + label: string; + type: 'text' | 'number' | 'select' | 'textarea'; + options?: string[]; + placeholder?: string; + defaultValue?: string | number; + required?: boolean; +} + +interface Props { + category: 'resource' | 'app' | 'permission'; + title: string; + description: string; + fields: FormField[]; + templateCode: string; +} + +interface ProcessItem { + id: number; + title: string; + status: string; + form_data: string; + created_at: string; +} + +const statusBadge = (status: string) => { + switch (status) { + case 'approved': return 已通过; + case 'rejected': return 已拒绝; + default: return 审批中; + } +}; + +export function ApprovalCategoryPage({ category, title, description, fields, templateCode }: Props) { + const [processes, setProcesses] = useState([]); + const [loading, setLoading] = useState(true); + const [keyword, setKeyword] = useState(''); + const [statusFilter, setStatusFilter] = useState(''); + const [dialogOpen, setDialogOpen] = useState(false); + const [submitting, setSubmitting] = useState(false); + const [templateId, setTemplateId] = useState(null); + const [formData, setFormData] = useState>({}); + + const fetchProcesses = useCallback(async () => { + setLoading(true); + try { + const params: Record = { page_size: '100' }; + if (category) params.category = category; + if (statusFilter) params.status = statusFilter; + const resp = (await approvalApi.getProcesses(params)) as any; + setProcesses(resp?.list ?? resp?.data?.list ?? []); + } catch { + setProcesses([]); + } finally { + setLoading(false); + } + }, [category, statusFilter]); + + const fetchTemplateId = useCallback(async () => { + try { + const resp = (await approvalApi.getTemplates({ type: templateCode })) as any; + const list = resp?.list ?? resp?.data?.list ?? []; + if (list.length > 0) setTemplateId(list[0].id); + } catch { /* ignore */ } + }, [templateCode]); + + useEffect(() => { fetchProcesses(); }, [fetchProcesses]); + useEffect(() => { fetchTemplateId(); }, [fetchTemplateId]); + + const handleCreate = async () => { + if (!templateId) { toast.error('模板未加载'); return; } + // Validate required fields + for (const f of fields) { + if (f.required && !formData[f.key]) { + toast.error(`请填写「${f.label}」`); + return; + } + } + setSubmitting(true); + try { + // Build title from first 2 fields + const firstVal = formData[fields[0]?.key] || ''; + const secondVal = fields[1] ? formData[fields[1].key] || '' : ''; + const autoTitle = `${title} - ${firstVal}${secondVal ? ' / ' + secondVal : ''}`; + + await approvalApi.createProcess({ + template_id: templateId, + title: autoTitle, + form_data: JSON.stringify(formData), + }); + toast.success('申请已提交'); + setDialogOpen(false); + setFormData({}); + fetchProcesses(); + } catch (err: any) { + toast.error(err?.message || '提交失败'); + } finally { + setSubmitting(false); + } + }; + + const openCreateDialog = () => { + const init: Record = {}; + fields.forEach((f) => { init[f.key] = f.defaultValue?.toString() || ''; }); + setFormData(init); + setDialogOpen(true); + }; + + const filtered = processes.filter((p) => { + return !keyword || (p.title || '').toLowerCase().includes(keyword.toLowerCase()); + }); + + return ( +
+ {/* Header */} +
+
+

{title}

+

{description}

+
+ +
+ + {/* Filters */} +
+
+ + setKeyword(e.target.value)} + className="pl-9 h-9 bg-[var(--dg-bg-tertiary)] border-[var(--dg-border)]" + /> +
+ + +
+ + {/* Table */} + + + {loading ? ( +
+ +
+ ) : filtered.length === 0 ? ( +
+ +

暂无申请记录

+ +
+ ) : ( + + + + ID + 申请标题 + 状态 + 提交时间 + + + + {filtered.map((p) => ( + + #{p.id} + {p.title} + {statusBadge(p.status)} + + {p.created_at ? new Date(p.created_at).toLocaleString('zh-CN') : '--'} + + + ))} + +
+ )} +
+
+ + {/* Create Dialog */} + + + + 新建{title} + {description} + +
+ {fields.map((field) => ( +
+ + {field.type === 'select' ? ( + + ) : field.type === 'textarea' ? ( +