Compare commits

...
27 Commits
Author SHA1 Message Date
yunyingk e512ee68dc Merge pull request #41 from yunyingk/codex/release-v0.10.13
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.13: Enforce material-pack scope isolation and strict path uniqueness
2026-09-08 10:01:04 +08:00
gitea 80e0dea178 Release v0.10.13: Enforce material-pack scope isolation and strict path uniqueness 2026-09-08 10:00:10 +08:00
yunyingk c60a7d0d18 Merge pull request #40 from yunyingk/codex/material-pack-path-declaration
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Refactor material-pack: [附件] column prefix + @ dir annotation + strict path validation
2026-09-07 18:31:32 +08:00
gitea 081ff0f8aa Refactor material-pack: [附件] column prefix + @ dir annotation + strict path validation
- Replace filename-heuristic attachment matching with explicit [附件] column declaration
- AttachmentGroup replaces MaterialAttachmentEntry: uses paths[] instead of entries[]
- parseMaterialWorkbook now exports DeclaredAttachment and full Parsed type including
  documentAttachments, expenseAttachments, personAttachments per row
- buildAttachmentPlans enforces strict bidirectional validation:
  1. Every Excel [附件] path must exist in ZIP
  2. Every ZIP file must be declared in some [附件] column
- validateDocIdDirectories now strips @annotation suffix when matching documentIds
- injectAttachmentPlan updated to work with new AttachmentGroup.paths API
- pushMaterialPack iterates group.paths for uploads, adding stderr diagnostics
- Key deduplication applied at parse time (deduplicateKeys)
- Tests updated: [附件] column fixtures, bidirectional validation error tests,
  @ annotation matching test, preview injection test
- Skill docs updated: Material Pack Workflow section in references/cli.md
- Version bumped to 0.10.12
2026-09-07 18:26:21 +08:00
yunyingk 2ab4e69122 Merge pull request #39 from yunyingk/codex/release-v0.10.11
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.11: Standard approval runs Excel export command and tool
2026-09-07 16:34:26 +08:00
gitea 06561bc893 Release v0.10.11: Standard approval runs Excel export command and tool 2026-09-07 16:33:12 +08:00
yunyingk b950e2b562 Merge pull request #38 from yunyingk/codex/release-v0.10.10
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.10: Remove default cwd enterprises loading and add global test-dir config
2026-09-07 15:27:25 +08:00
gitea b5cc7c874e Release v0.10.10: Remove default cwd enterprises loading and add global test-dir config 2026-09-07 15:26:21 +08:00
yunyingk 878e53ac81 Merge pull request #37 from yunyingk/codex/release-v0.10.9
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.9: Purge legacy MCP code, decouple CLI commands, and clean unused exports
2026-09-04 19:09:19 +08:00
gitea edafe033dc Release v0.10.9: Purge legacy MCP code, decouple CLI commands, and clean unused exports 2026-09-04 19:08:16 +08:00
yunyingk d525087b97 Merge pull request #36 from yunyingk/codex/release-v0.10.8
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.8: Approval run attachments extraction and download command
2026-09-04 18:50:05 +08:00
gitea c5381e2c66 Release v0.10.8: Approval run attachments extraction and download command 2026-09-04 18:48:40 +08:00
gitea e9b66f787b Add approval-runs attachments download and Hose format extraction 2026-09-04 18:48:03 +08:00
yunyingk f64f2b8385 Merge pull request #34 from yunyingk/codex/release-v0.10.7
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.7: Local rules workspace, daemon HTTP server, and global stop
2026-09-04 18:09:49 +08:00
gitea cba3098654 docs: document global stop command and shutdown route in changelog 2026-09-04 18:08:13 +08:00
gitea f9b8b06647 Add global seal-use stop command and shutdown HTTP route 2026-09-04 17:58:30 +08:00
gitea 37580dac44 Release v0.10.7: Local rules workspace and daemon HTTP server 2026-09-04 17:54:47 +08:00
gitea f183cc8294 Add persistent HTTP server to background service daemon 2026-09-04 17:53:40 +08:00
gitea 13ed555bbb Add local approval rules workspace and offline linting 2026-09-04 17:45:46 +08:00
yunyingk 39bbf4d7c0 Merge pull request #33 from yunyingk/codex/release-v0.10.6
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.6: Webhook material pack import
2026-09-03 15:32:08 +08:00
gitea 64819d86cb Release v0.10.6: Webhook material pack import 2026-09-03 15:30:43 +08:00
yunyingk 4b1833409e Merge pull request #32 from yunyingk/codex/issue-27-webhook-material-pack
Add Webhook material pack import
2026-09-03 15:27:44 +08:00
gitea 77ae7d4dca Add Webhook material pack import 2026-09-03 15:26:43 +08:00
yunyingk 1299d70777 Merge pull request #31 from yunyingk/codex/release-v0.10.5
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.5: Intelligent HoseCloud sync discovery, actionable guidance, and --auto support (Fixes #26)
2026-09-03 11:42:54 +08:00
gitea 0a3c984018 Release v0.10.5: Intelligent HoseCloud sync discovery, actionable guidance, and --auto support (Fixes #26) 2026-09-03 11:41:56 +08:00
yunyingk 923184e623 Merge pull request #29 from yunyingk/codex/release-v0.10.4
🧪 CI / 🧪 Test, Type-Check & Build Validation (push) Has been cancelled
🚀 Release / 🚀 Build & Publish GitHub Release (push) Has been cancelled
🚀 Release / 📦 Sync Gitea Mirror (push) Has been cancelled
Release v0.10.4: Built-in rule linter, dynamic TS plugin loader with fault-tolerant fallback, and default-disabled global config
2026-09-03 11:31:50 +08:00
gitea 1cf35dfd78 Release v0.10.4: Built-in rule linter, dynamic TS plugin loader with fault-tolerant fallback, and default-disabled global config 2026-09-03 11:30:52 +08:00
58 changed files with 5708 additions and 613 deletions

No files matched your search

+4
View File
@@ -14,4 +14,8 @@ enterprises/*.json
# Local generated reports and exported deliverables.
.local/
.apifox/
exports/
scripts/export-*.ts
# Local custom linters
linters/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.3",
"version": "0.10.13",
"description": "Seal Use tenant operations: approval-run diagnosis, minimal rule remediation, delegation links, Hose/合思 authorization, users, rules, billing, and search.",
"author": {
"name": "yingqing"
+105
View File
@@ -5,6 +5,111 @@ All notable changes to `seal-use` will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [0.10.13] - 2026-09-08
### Fixed & Enhanced
- **Material Pack Scope Isolation & Strict Path Uniqueness**:
- Enforced per-document directory scope isolation: all attachments declared for a document must strictly reside in its own folder (`<documentId>/` or `<documentId>@annotation/`), preventing cross-document file borrowing or path confusion.
- Enforced global declaration uniqueness: identical attachment file paths can no longer be declared more than once across the entire material pack (even within the same document or different line-items). Multiple uses require placing distinct physical files in independent paths.
- Added comprehensive unit tests covering cross-document directory violations, intra-document duplicate paths, and multi-document path collisions.
- Updated documentation in `cli.md` detailing the strict scope isolation and declaration uniqueness rules.
## [0.10.12] - 2026-09-07
### Added & Refactored
- **Material Pack Pure Path Declaration & Validation Refactor**:
- Replaced ambiguous filename heuristics with explicit `[附件]` Excel column headers and full ZIP-relative file paths.
- Added `@` annotation suffix support for ZIP root directories (`<documentId>@annotation/`) to bypass document idempotency blocks safely.
- Enforced bidirectional validation between Excel declarations and ZIP entries without fail-fast, collecting all errors together.
- Added automatic key collision deduplication with numeric suffixes (`-2`, `-3`).
## [0.10.11] - 2026-09-07
### Added & Enhanced
- **Standard Approval Runs Excel Export**:
- Added `seal-use approval-runs export` command to export tenant approval records into high-fidelity Excel workbooks with frozen headers, dynamic rule columns, and color-coded status badges.
- Automatically resolves document template names, manual approval statuses (`APPROVED`, `TERMINATED`, `PROCESSING`), and human reviewer reject comments from `manualApprovalRecord`.
- Dynamically fetches tenant active approval rules (`api.listApprovalRules`) and appends rule check results (`PASS`, `FAIL`, `TRIGGERED`) as individual column badges.
- Added `--downloads` flag to conveniently output directly to the user's `~/Downloads` folder.
- Added `seal_approval_runs_export` tool in MCP/agent tools for automated reporting and data inspection.
- Supports `--start`, `--end`, `--limit`, `--status`, `--manual-status`, and `--completed-only` filters with gentle pagination and progress reporting to `stderr`.
## [0.10.10] - 2026-09-07
### Changed & Fixed
- **Enterprise Config Resolution Isolation**:
- Removed default loading of `./enterprises` from the current working directory (`cwd`), ensuring local repo files never unintentionally leak or override user enterprise configs.
- Candidate enterprise directories now strictly default to user global configuration directories (`~/.config/seal-use/enterprises`, `~/.config/seal-home/enterprises`) unless an explicit environment variable or test directory is configured.
- **Global Test Enterprises Directory Configuration**:
- Added `testEnterprisesDir` field to `GlobalConfigSchema`.
- Added `seal-use config test-dir [<path>|--clear]` command to safely configure or clear a dedicated test enterprise directory without impacting normal user operations.
- Included `testEnterprisesDir` in global configuration summaries and candidate directory listings.
## [0.10.9] - 2026-09-04
### Refactored & Purged
- **MCP Legacy Code Purge & Strict CLI-First Architecture**:
- Removed obsolete intermediate MCP definitions (`sealMcpTools`, `mcpDirectToolNames`, `sealActionNames`, `sealActionAliases`, `runSealAction`, `sealActionHelp`, `findSealMcpTool`) from `src/domains/seal/tools.ts`.
- Removed mistakenly registered `seal_approval_run_attachments_download` tool definition and aliases from `tools.ts`.
- Decoupled `seal-use approval-runs attachments` (inspection & download) CLI commands to invoke pure domain functions in `src/domains/seal/attachments.ts` directly, bypassing the legacy tool runner.
- Purged obsolete "Fine-Grained Tools" lists from `README.md` and `skills/seal-use/references/cli.md`, reinforcing the CLI-First contract where agents execute `seal-use <command>` directly or via the single `seal_cli` MCP tool.
- **Repository-Wide Dead Code & Unused Export Cleanup**:
- Eliminated duplicate enterprise directory export aliases in `src/core/config/loader.ts`.
- Converted internal helpers in `src/core/embedded-skill.ts`, `src/cli/printer.ts`, `src/cli/commands/auth.ts`, `src/domains/seal/linter/loader.ts`, `src/domains/seal/material-pack/validate.ts`, and `src/core/auth/seal.ts` to private module functions.
## [0.10.8] - 2026-09-04
### Added & Enhanced
- **Approval Run Attachments Extraction Compatibility (Issue #35)**:
- Generalized `extractApprovalRunAttachments` to inspect `document.fields[].type === "ATTACHMENT"` arrays with nested `value[]` collections, properly recognizing HoseCloud/Seal 2026 flattened attachment fields that previously resolved to `count: 0`.
- Extracted comprehensive metadata including `ossSignedUrl`, `token` (automatically parsing embedded `fileId` and object `key`), `ossFileSize`, `mimeType`, and preserved parent field labels as `sourceField`.
- Added `hasSignedUrl` and `ossFileSize` to compact summary outputs without exposing raw signed URLs.
- **New Attachments Download Command (Issue #35)**:
- Added `seal-use approval-runs attachments download <recordId> [--name <pattern>] [--all] [--out-dir <path>]` CLI command.
- Prioritizes direct `ossSignedUrl` links from the run record and verifies downloaded file size against `ossFileSize`.
- Automatically sanitizes sensitive temporary signatures in CLI logging (`?[MASKED]`) to prevent credential leakage in build/agent transcripts.
- Implemented graceful error recovery for expired temporary URLs (HTTP 403) or missing links, reporting diagnostics for failed items while allowing valid attachments to complete without interruption.
## [0.10.7] - 2026-09-04
### Added & Enhanced
- **Local Approval Rules Workspace & Offline Linting**:
- Added `seal-use rules pull` (`seal_approval_rules_pull`) to export remote draft or published version rules to a local JSON file (defaults to `./rules.local.json`), eliminating unwanted mutations to remote drafts.
- Added `seal-use rules lint --file <path>` to execute rule quality and execution checks completely offline with zero network requests and zero dirty version records in the remote backend. Supports quality score gates (`--min-score`) and operates seamlessly even without configured enterprise credentials.
- Added `seal-use rules push` (`seal_approval_rules_push`) to apply refined local rules to the remote draft with preview (`--dry-run`), confirmation (`--yes`), and optional single-step formal release publishing (`--publish`).
- **Persistent HTTP Companion Daemon in Background Service**:
- Embedded the HTTP API server into `seal-use service run`, allowing `seal-use service start` to run as a detached background daemon with persistent HTTP service (serving `/docs`, `/openapi.json`, and `POST /api/cli`).
- Added `seal-use service logs` (`--lines <N>`) to easily inspect service background activity.
- Enhanced `seal-use service status` to track active host, port, and URL via daemon metadata state.
- Optimized `parseJsonBody` and CLI runner concurrency with standing command bypasses to prevent process queue blocks.
- Added top-level `seal-use stop` command, intuitive service aliases (`seal-use service kill|down|shutdown`), and `POST /shutdown` HTTP endpoint to gracefully terminate the background daemon from any terminal or script.
## [0.10.6] - 2026-09-03
### Added & Enhanced
- **Inbound Webhook Material Pack Import (Issue #27)**: Added local preview and push workflows for SealAI material packs, including strict ZIP/XLSX validation, normalized approval-document parsing, attachment upload, and HMAC-signed Webhook delivery.
- **CLI and MCP Support**: Added `seal-use webhook material-pack preview|push` and the `seal_webhook_material_pack` tool, while keeping the existing simulation `material_pack` flow separate.
- **Test-Enterprise Verification**: Verified the new push path against the configured test enterprise with official sample materials; customer enterprise data was not used.
## [0.10.5] - 2026-09-03
### Added & Enhanced
- **Intelligent HoseCloud Sync Discovery & Actionable Guidance (Issue #26)**: In `seal-use deploy hosecloud sync` and `deploy hosecloud get`, when `<sign-key>` is omitted, the CLI dynamically discovers all active HoseCloud integration configs for the tenant and renders structured cards on `stderr` with 1-click copy commands (e.g. `👉 同步命令: seal-use deploy hosecloud sync <signKey> --corp <corpId>`).
- **Single-Config Fast Track (`--auto`)**: Added `--auto` (and `--yes`) flag to `deploy hosecloud sync`. When a tenant has exactly one configured HoseCloud integration, `--auto` automatically locks and syncs without requiring manual `signKey` extraction.
- **Enhanced Empty State & Diagnostic Hints**: If a tenant has zero HoseCloud integrations configured, clearly prompts the user with next-step configuration command `seal-use deploy hosecloud configure ...`.
- **Updated Reference Documentation**: Updated `skills/seal-use/references/hose-enterprise-deploy.md` and CLI references with `--auto` and dynamic discovery patterns.
## [0.10.4] - 2026-09-03
### Added & Enhanced
- **Built-in Approval Rule Linter & Quality Validation Engine**: Introduced a pure TypeScript/heuristic rule quality validator (`seal-use rules lint` & `seal_approval_rules_lint`). Detects subjective fuzzy words (`原则上`, `尽量`, `适当`, `酌情`), hanging exception clauses lacking evidence keywords (`除非/特殊情况` 未指明 `备注/附件/截图` 凭证来源), and short invalid descriptions.
- **Plugin-as-Code Dynamic TS Linter Loader**: Supports loading custom enterprise TypeScript linter plugins dynamically from `~/.config/seal-use/linters/*.ts` or explicit paths (`--linter <name|path>`).
- **Fault-Tolerant Automatic Fallback (Anti-Crash Guarantee)**: If a user's custom `.ts` linter file contains syntax errors, throws runtime exceptions, or is missing, the engine automatically catches errors, logs diagnostic warnings to `stderr`, and seamlessly falls back to the built-in heuristic linter without failing or blocking CLI execution.
- **Global Config & Default-Disabled Policy**: Added `lint: { enabled: false, activeLinter: "builtin", minScore: 0 }` to global configuration (`~/.config/seal-use/config.json`). Linter is **disabled by default** to avoid unsolicited noise; can be enabled via `seal-use config lint enable`.
- **Real-time Diagnostic Hook on Rule Updates**: When linting is enabled, `seal_approval_rule_update` automatically inspects modified descriptions and outputs structured warnings on `stderr` while keeping clean machine JSON on `stdout`.
- **Comprehensive Scenarios & Gatekeeping**: `seal-use rules lint` supports full draft scanning, historical version review (`--version <num>`), rule filtering (`--code <code>`), summary mode (`--summary`), and quality gate scoring (`--min-score <score>`) with non-zero exit codes.
- **Dedicated Reference Documentation**: Added `skills/seal-use/references/rule-lint.md` and updated SKILL router.
## [0.10.3] - 2026-09-02
### Added & Enhanced
+12 -21
View File
@@ -257,29 +257,20 @@ The MCP server advertises exactly one tool, `seal_cli`:
It runs the same CLI dispatcher as the global binary, so read operations, write operations, `config`, `service`, and `update` remain available. Write-operation confirmations and explicit enterprise-ID rules continue to be defined by this skill.
## CLI Tools
## CLI-First Architecture
These tools remain available to the CLI:
All Agent and automation capabilities are accessed through standard `seal-use <command>` CLI invocations (or through the single `seal_cli` MCP tool passing the command string). Internal domain services output pure, parseable JSON on `stdout`, with human diagnostics and suggestions routed to `stderr`.
- `seal_source_config`: resolve current Seal enterprise config from the configured source.
- `seal_approval_runs_search`: search approval run history and optional bridge rows.
- `seal_session_get`: current Seal Bearer session and expiration.
- `seal_approval_rules_list`: current draft approval rules. Use `{"countOnly":true}` or `{"fields":["id"],"limit":0}` to return only `{"count":...}`; use `fields` for lightweight projections when rule descriptions are not needed.
- `seal_approval_rule_create`, `seal_approval_rule_update`, `seal_approval_rule_delete`: maintain approval rules.
- `seal_approval_rule_versions_list`, `seal_approval_rule_version_publish`: read and publish rule versions.
- `seal_approval_rule_get`: fetch one rule from a published version by `versionNumber` plus `code` such as `#0038`, or by `recordId` plus `runtimeId` such as `rule-205`.
- `seal_approval_documents_list`, `seal_approval_document_get`, `seal_approval_document_create`, `seal_approval_document_update`: maintain approval documents.
- `seal_approval_style_preferences_get`, `seal_approval_style_preferences_update`: read and update approval style preferences.
- `seal_approval_runs_summary`: summarize approval runs by local date and timezone. Use this for daily questions such as "what approval records did Tawen have today"; it returns status/task-mode counts and compact records.
- `seal_approval_run_get`: fetch one approval run. Pass `summary:true` or `fields` such as `"metadata"` or `"document.fields,result.summary"` to avoid returning full document, pipeline, and AI output payloads.
- `seal_approval_run_pick`: locate likely approval run records by document number, batch, latest flag, and optional field projection.
- `seal_approval_run_cited_rules_get`: extract rules cited or matched by the AI result, including runtime ID/code, version, scope, strictness, analysis, result, and findings when present.
- `seal_approval_run_document_summary_get`: return key document fields, invoice/attachment summary, AI result, and manual result.
- `seal_approval_run_attachments_get`: return attachment and invoice file metadata for one run without the full document or rule result; use `summary:true` for the smallest list.
- `seal_approval_run_result_get`: return one run result, with `{"summary":true}` for decision, summary, risk point count, matched rule count, trace ID, and record ID only.
- `seal_approval_run_url_get`: return the Hose enterprise assist URL, optionally with the original document URL for an approval run by `recordId`, `sourceDocumentSN`, or `sourceDocumentId`.
- `seal_simulation_batch_records_get`: read records from one simulation batch via `api/v1/simulation/batch/{batchId}/records`.
- `seal_approval_run_langfuse_bridge_get`: resolve approval run records to Langfuse lookup hints. It prefers `sourceExtendData._langfuseTraceId`; if that is missing, it returns `hosecloud-{sourceDocumentSN}` as the session fallback.
Key CLI command groups:
- **`seal-use corps ...`**: enterprise tenant management, onboarding, switching, and assistance link intake.
- **`seal-use auth ...`**: authentication diagnostics and Hose provisional authorization links.
- **`seal-use rules ...`**: rule listing, workspace pull/push, offline linting, version publishing, and clearing.
- **`seal-use approval-runs ...`**: run history search, summary by date, detail extraction, attachment inspection & download, cited rules, and Langfuse trace bridge.
- **`seal-use simulation ...`**: test simulation batch creation, polling wait, specifications, and cleanup.
- **`seal-use deploy ...`**: HoseCloud review node requirement inspection, status check, configuration, and sync.
- **`seal-use preference ...`**: decision preferences and thinking depth policies.
- **`seal-use webhook ...`**: webhook integration CRUD and material pack testing.
- **`seal-use service ...`**: persistent daemon service management with embedded HTTP server.
For rule list commands, prefer `seal-use rules count --corp <corpId>` or `seal-use rules list --corp <corpId> --summary` before requesting full rule descriptions. `seal-use rules list` protects large outputs and asks for `--summary`, `--count`, or explicit `--full` when the response would be too large.
+198 -1
View File
@@ -5,11 +5,16 @@
"": {
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"exceljs": "^4.4.0",
"iconv-lite": "^0.7.3",
"ky": "^2.0.2",
"pinyin-pro": "^3.29.3",
"yauzl": "^3.4.0",
"zod": "^4.4.3",
},
"devDependencies": {
"@types/bun": "^1.3.14",
"@types/yauzl": "^3.4.0",
"bun-types": "^1.3.14",
"typescript": "^5.9.3",
"yaml": "^2.9.0",
@@ -17,6 +22,10 @@
},
},
"packages": {
"@fast-csv/format": ["@fast-csv/format@4.3.5", "", { "dependencies": { "@types/node": "^14.0.1", "lodash.escaperegexp": "^4.1.2", "lodash.isboolean": "^3.0.3", "lodash.isequal": "^4.5.0", "lodash.isfunction": "^3.0.9", "lodash.isnil": "^4.0.0" } }, "sha512-8iRn6QF3I8Ak78lNAa+Gdl5MJJBM5vRHivFtMRUWINdevNo00K7OXxS2PshawLKTejVwieIlPmK5YlLu6w4u8A=="],
"@fast-csv/parse": ["@fast-csv/parse@4.3.6", "", { "dependencies": { "@types/node": "^14.0.1", "lodash.escaperegexp": "^4.1.2", "lodash.groupby": "^4.6.0", "lodash.isfunction": "^3.0.9", "lodash.isnil": "^4.0.0", "lodash.isundefined": "^3.0.1", "lodash.uniq": "^4.5.0" } }, "sha512-uRsLYksqpbDmWaSmzvJcuApSEe38+6NQZBUsuAyMZKqHxH0g1wcJgsKUvN3WC8tewaqFjBMMGrkHmC+T7k8LvA=="],
"@hono/node-server": ["@hono/node-server@1.19.14", "", { "peerDependencies": { "hono": "^4" } }, "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw=="],
"@modelcontextprotocol/sdk": ["@modelcontextprotocol/sdk@1.29.0", "", { "dependencies": { "@hono/node-server": "^1.19.9", "ajv": "^8.17.1", "ajv-formats": "^3.0.1", "content-type": "^1.0.5", "cors": "^2.8.5", "cross-spawn": "^7.0.5", "eventsource": "^3.0.2", "eventsource-parser": "^3.0.0", "express": "^5.2.1", "express-rate-limit": "^8.2.1", "hono": "^4.11.4", "jose": "^6.1.3", "json-schema-typed": "^8.0.2", "pkce-challenge": "^5.0.0", "raw-body": "^3.0.0", "zod": "^3.25 || ^4.0", "zod-to-json-schema": "^3.25.1" }, "peerDependencies": { "@cfworker/json-schema": "^4.1.1" }, "optionalPeers": ["@cfworker/json-schema"] }, "sha512-zo37mZA9hJWpULgkRpowewez1y6ML5GsXJPY8FI0tBBCd77HEvza4jDqRKOXgHNn867PVGCyTdzqpz0izu5ZjQ=="],
@@ -25,14 +34,44 @@
"@types/node": ["@types/node@25.9.1", "", { "dependencies": { "undici-types": ">=7.24.0 <7.24.7" } }, "sha512-xfrlY7UD5rMJk3ZVJP8BNzS28J36YJg+xp+LPXV1TdWxr8uMH5A860QNxYDGQe/ylDSgjxE52Q9VnO7p75tJxg=="],
"@types/yauzl": ["@types/yauzl@3.4.0", "", { "dependencies": { "@types/node": "*" } }, "sha512-NRPn5w6h8dhcnmx3YIRQcqMywY/+nND/uOkJessedcrowO3C0AssHp3tMJpxKAwOhFOo0OV1y9VtsC5hbKKBAw=="],
"accepts": ["accepts@2.0.0", "", { "dependencies": { "mime-types": "^3.0.0", "negotiator": "^1.0.0" } }, "sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng=="],
"ajv": ["ajv@8.20.0", "", { "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", "json-schema-traverse": "^1.0.0", "require-from-string": "^2.0.2" } }, "sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA=="],
"ajv-formats": ["ajv-formats@3.0.1", "", { "dependencies": { "ajv": "^8.0.0" } }, "sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ=="],
"archiver": ["archiver@5.3.2", "", { "dependencies": { "archiver-utils": "^2.1.0", "async": "^3.2.4", "buffer-crc32": "^0.2.1", "readable-stream": "^3.6.0", "readdir-glob": "^1.1.2", "tar-stream": "^2.2.0", "zip-stream": "^4.1.0" } }, "sha512-+25nxyyznAXF7Nef3y0EbBeqmGZgeN/BxHX29Rs39djAfaFalmQ89SE6CWyDCHzGL0yt/ycBtNOmGTW0FyGWNw=="],
"archiver-utils": ["archiver-utils@2.1.0", "", { "dependencies": { "glob": "^7.1.4", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^2.0.0" } }, "sha512-bEL/yUb/fNNiNTuUz979Z0Yg5L+LzLxGJz8x79lYmR54fmTIb6ob/hNQgkQnIUDWIFjZVQwl9Xs356I6BAMHfw=="],
"async": ["async@3.2.6", "", {}, "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA=="],
"balanced-match": ["balanced-match@1.0.2", "", {}, "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw=="],
"base64-js": ["base64-js@1.5.1", "", {}, "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA=="],
"big-integer": ["big-integer@1.6.52", "", {}, "sha512-QxD8cf2eVqJOOz63z6JIN9BzvVs/dlySa5HGSBH5xtR8dPteIRQnBxxKqkNTiT6jbDTF6jAfrd4oMcND9RGbQg=="],
"binary": ["binary@0.3.0", "", { "dependencies": { "buffers": "~0.1.1", "chainsaw": "~0.1.0" } }, "sha512-D4H1y5KYwpJgK8wk1Cue5LLPgmwHKYSChkbspQg5JtVuR5ulGckxfR62H3AE9UDkdMC8yyXlqYihuz3Aqg2XZg=="],
"bl": ["bl@4.1.0", "", { "dependencies": { "buffer": "^5.5.0", "inherits": "^2.0.4", "readable-stream": "^3.4.0" } }, "sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w=="],
"bluebird": ["bluebird@3.4.7", "", {}, "sha512-iD3898SR7sWVRHbiQv+sHUtHnMvC1o3nW5rAcqnq3uOn07DSAppZYUkIGslDz6gXC7HfunPe7YVBgoEJASPcHA=="],
"body-parser": ["body-parser@2.2.2", "", { "dependencies": { "bytes": "^3.1.2", "content-type": "^1.0.5", "debug": "^4.4.3", "http-errors": "^2.0.0", "iconv-lite": "^0.7.0", "on-finished": "^2.4.1", "qs": "^6.14.1", "raw-body": "^3.0.1", "type-is": "^2.0.1" } }, "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA=="],
"brace-expansion": ["brace-expansion@2.1.4", "", { "dependencies": { "balanced-match": "^1.0.0" } }, "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg=="],
"buffer": ["buffer@5.7.1", "", { "dependencies": { "base64-js": "^1.3.1", "ieee754": "^1.1.13" } }, "sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ=="],
"buffer-crc32": ["buffer-crc32@0.2.13", "", {}, "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ=="],
"buffer-indexof-polyfill": ["buffer-indexof-polyfill@1.0.2", "", {}, "sha512-I7wzHwA3t1/lwXQh+A5PbNvJxgfo5r3xulgpYDB5zckTu/Z9oUK9biouBKQUjEqzaz3HnAT6TYoovmE+GqSf7A=="],
"buffers": ["buffers@0.1.1", "", {}, "sha512-9q/rDEGSb/Qsvv2qvzIzdluL5k7AaJOTrw23z9reQthrbF7is4CtlT0DXyO1oei2DCp4uojjzQ7igaSHp1kAEQ=="],
"bun-types": ["bun-types@1.3.14", "", { "dependencies": { "@types/node": "*" } }, "sha512-4N0ig0fEomHt5R0KCFWjovxow98rIoRwKolrYdCcknNwMekCXRnWEUvgu5soYV8QXtVsrUD8B95MBOZGPvr6KQ=="],
"bytes": ["bytes@3.1.2", "", {}, "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg=="],
@@ -41,6 +80,12 @@
"call-bound": ["call-bound@1.0.4", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" } }, "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg=="],
"chainsaw": ["chainsaw@0.1.0", "", { "dependencies": { "traverse": ">=0.3.0 <0.4" } }, "sha512-75kWfWt6MEKNC8xYXIdRpDehRYY/tNSgwKaJq+dbbDcxORuVrrQ+SEHoWsniVn9XPYfP4gmdWIeDk/4YNp1rNQ=="],
"compress-commons": ["compress-commons@4.1.2", "", { "dependencies": { "buffer-crc32": "^0.2.13", "crc32-stream": "^4.0.2", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-D3uMHtGc/fcO1Gt1/L7i1e33VOvD4A9hfQLP+6ewd+BvG/gQ84Yh4oftEhAdjSMgBgwGL+jsppT7JYNpo6MHHg=="],
"concat-map": ["concat-map@0.0.1", "", {}, "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg=="],
"content-disposition": ["content-disposition@1.1.0", "", {}, "sha512-5jRCH9Z/+DRP7rkvY83B+yGIGX96OYdJmzngqnw2SBSxqCFPd0w2km3s5iawpGX8krnwSGmF0FW5Nhr0Hfai3g=="],
"content-type": ["content-type@1.0.5", "", {}, "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA=="],
@@ -49,20 +94,32 @@
"cookie-signature": ["cookie-signature@1.2.2", "", {}, "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="],
"core-util-is": ["core-util-is@1.0.3", "", {}, "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ=="],
"cors": ["cors@2.8.6", "", { "dependencies": { "object-assign": "^4", "vary": "^1" } }, "sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw=="],
"crc-32": ["crc-32@1.2.2", "", { "bin": { "crc32": "bin/crc32.njs" } }, "sha512-ROmzCKrTnOwybPcJApAA6WBWij23HVfGVNKqqrZpuyZOHqK2CwHSvpGuyt/UNNvaIjEd8X5IFGp4Mh+Ie1IHJQ=="],
"crc32-stream": ["crc32-stream@4.0.3", "", { "dependencies": { "crc-32": "^1.2.0", "readable-stream": "^3.4.0" } }, "sha512-NT7w2JVU7DFroFdYkeq8cywxrgjPHWkdX1wjpRQXPX5Asews3tA+Ght6lddQO5Mkumffp3X7GEqku3epj2toIw=="],
"cross-spawn": ["cross-spawn@7.0.6", "", { "dependencies": { "path-key": "^3.1.0", "shebang-command": "^2.0.0", "which": "^2.0.1" } }, "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA=="],
"dayjs": ["dayjs@1.11.23", "", {}, "sha512-QDTCU0M0MxR3hQfnlDJfwekQiaanm1ubOD231u73WBckQ/fsamwRLiE2GBz6D3a/xF1NgfiDLJjXBa1hYOYTtQ=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"depd": ["depd@2.0.0", "", {}, "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw=="],
"dunder-proto": ["dunder-proto@1.0.1", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.1", "es-errors": "^1.3.0", "gopd": "^1.2.0" } }, "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A=="],
"duplexer2": ["duplexer2@0.1.4", "", { "dependencies": { "readable-stream": "^2.0.2" } }, "sha512-asLFVfWWtJ90ZyOUHMqk7/S2w2guQKxUI2itj3d92ADHhxUSbCMGi1f1cBcJ7xM1To+pE/Khbwo1yuNbMEPKeA=="],
"ee-first": ["ee-first@1.1.1", "", {}, "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow=="],
"encodeurl": ["encodeurl@2.0.0", "", {}, "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg=="],
"end-of-stream": ["end-of-stream@1.4.5", "", { "dependencies": { "once": "^1.4.0" } }, "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg=="],
"es-define-property": ["es-define-property@1.0.1", "", {}, "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g=="],
"es-errors": ["es-errors@1.3.0", "", {}, "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw=="],
@@ -77,10 +134,14 @@
"eventsource-parser": ["eventsource-parser@3.1.0", "", {}, "sha512-kJezFj9YFAMLeORyi7aCLxLbD5/qWMQnoMVlVPyHIll7lgRJCc3JVln9Vgl9nwQi0YkMnhdGTMNn7CkRRAptMg=="],
"exceljs": ["exceljs@4.4.0", "", { "dependencies": { "archiver": "^5.0.0", "dayjs": "^1.8.34", "fast-csv": "^4.3.1", "jszip": "^3.10.1", "readable-stream": "^3.6.0", "saxes": "^5.0.1", "tmp": "^0.2.0", "unzipper": "^0.10.11", "uuid": "^8.3.0" } }, "sha512-XctvKaEMaj1Ii9oDOqbW/6e1gXknSY4g/aLCDicOXqBE4M0nRWkUu0PTp++UPNzoFY12BNHMfs/VadKIS6llvg=="],
"express": ["express@5.2.1", "", { "dependencies": { "accepts": "^2.0.0", "body-parser": "^2.2.1", "content-disposition": "^1.0.0", "content-type": "^1.0.5", "cookie": "^0.7.1", "cookie-signature": "^1.2.1", "debug": "^4.4.0", "depd": "^2.0.0", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "finalhandler": "^2.1.0", "fresh": "^2.0.0", "http-errors": "^2.0.0", "merge-descriptors": "^2.0.0", "mime-types": "^3.0.0", "on-finished": "^2.4.1", "once": "^1.4.0", "parseurl": "^1.3.3", "proxy-addr": "^2.0.7", "qs": "^6.14.0", "range-parser": "^1.2.1", "router": "^2.2.0", "send": "^1.1.0", "serve-static": "^2.2.0", "statuses": "^2.0.1", "type-is": "^2.0.1", "vary": "^1.1.2" } }, "sha512-hIS4idWWai69NezIdRt2xFVofaF4j+6INOpJlVOLDO8zXGpUVEVzIYk12UUi2JzjEzWL3IOAxcTubgz9Po0yXw=="],
"express-rate-limit": ["express-rate-limit@8.5.2", "", { "dependencies": { "ip-address": "^10.2.0" }, "peerDependencies": { "express": ">= 4.11" } }, "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A=="],
"fast-csv": ["fast-csv@4.3.6", "", { "dependencies": { "@fast-csv/format": "4.3.5", "@fast-csv/parse": "4.3.6" } }, "sha512-2RNSpuwwsJGP0frGsOmTb9oUF+VkFSM4SyLTDgwf2ciHWTarN0lQTC+F2f/t5J9QjW+c65VFIAAu85GsvMIusw=="],
"fast-deep-equal": ["fast-deep-equal@3.1.3", "", {}, "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q=="],
"fast-uri": ["fast-uri@3.1.2", "", {}, "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ=="],
@@ -91,14 +152,24 @@
"fresh": ["fresh@2.0.0", "", {}, "sha512-Rx/WycZ60HOaqLKAi6cHRKKI7zxWbJ31MhntmtwMoaTeF7XFH9hhBp8vITaMidfljRQ6eYWCKkaTK+ykVJHP2A=="],
"fs-constants": ["fs-constants@1.0.0", "", {}, "sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow=="],
"fs.realpath": ["fs.realpath@1.0.0", "", {}, "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="],
"fstream": ["fstream@1.0.12", "", { "dependencies": { "graceful-fs": "^4.1.2", "inherits": "~2.0.0", "mkdirp": ">=0.5 0", "rimraf": "2" } }, "sha512-WvJ193OHa0GHPEL+AycEJgxvBEwyfRkN1vhjca23OaPVMCaLCXTd5qAu82AjTcgP1UJmytkOKb63Ypde7raDIg=="],
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
"get-intrinsic": ["get-intrinsic@1.3.0", "", { "dependencies": { "call-bind-apply-helpers": "^1.0.2", "es-define-property": "^1.0.1", "es-errors": "^1.3.0", "es-object-atoms": "^1.1.1", "function-bind": "^1.1.2", "get-proto": "^1.0.1", "gopd": "^1.2.0", "has-symbols": "^1.1.0", "hasown": "^2.0.2", "math-intrinsics": "^1.1.0" } }, "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ=="],
"get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="],
"glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="],
"gopd": ["gopd@1.2.0", "", {}, "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg=="],
"graceful-fs": ["graceful-fs@4.2.11", "", {}, "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ=="],
"has-symbols": ["has-symbols@1.1.0", "", {}, "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ=="],
"hasown": ["hasown@2.0.4", "", { "dependencies": { "function-bind": "^1.1.2" } }, "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A=="],
@@ -107,7 +178,13 @@
"http-errors": ["http-errors@2.0.1", "", { "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", "setprototypeof": "~1.2.0", "statuses": "~2.0.2", "toidentifier": "~1.0.1" } }, "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ=="],
"iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"iconv-lite": ["iconv-lite@0.7.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ=="],
"ieee754": ["ieee754@1.2.1", "", {}, "sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA=="],
"immediate": ["immediate@3.0.6", "", {}, "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ=="],
"inflight": ["inflight@1.0.6", "", { "dependencies": { "once": "^1.3.0", "wrappy": "1" } }, "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA=="],
"inherits": ["inherits@2.0.4", "", {}, "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ=="],
@@ -117,6 +194,8 @@
"is-promise": ["is-promise@4.0.0", "", {}, "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ=="],
"isarray": ["isarray@1.0.0", "", {}, "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ=="],
"isexe": ["isexe@2.0.0", "", {}, "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="],
"jose": ["jose@6.2.3", "", {}, "sha512-YYVDInQKFJfR/xa3ojUTl8c2KoTwiL1R5Wg9YCydwH0x0B9grbzlg5HC7mMjCtUJjbQ/YnGEZIhI5tCgfTb4Hw=="],
@@ -125,8 +204,42 @@
"json-schema-typed": ["json-schema-typed@8.0.2", "", {}, "sha512-fQhoXdcvc3V28x7C7BMs4P5+kNlgUURe2jmUT1T//oBRMDrqy1QPelJimwZGo7Hg9VPV3EQV5Bnq4hbFy2vetA=="],
"jszip": ["jszip@3.10.1", "", { "dependencies": { "lie": "~3.3.0", "pako": "~1.0.2", "readable-stream": "~2.3.6", "setimmediate": "^1.0.5" } }, "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g=="],
"ky": ["ky@2.0.2", "", {}, "sha512-/GmXpo9F9W+f8n4Ivr2iH+7h7wL7jLbLKWkMlpflcCRb6kGjBfTlASEXaZ9qUgNTn4VgS0P2pwxxzQ4EM6Ulgg=="],
"lazystream": ["lazystream@1.0.1", "", { "dependencies": { "readable-stream": "^2.0.5" } }, "sha512-b94GiNHQNy6JNTrt5w6zNyffMrNkXZb3KTkCZJb2V1xaEGCk093vkZ2jk3tpaeP33/OiXC+WvK9AxUebnf5nbw=="],
"lie": ["lie@3.3.0", "", { "dependencies": { "immediate": "~3.0.5" } }, "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ=="],
"listenercount": ["listenercount@1.0.1", "", {}, "sha512-3mk/Zag0+IJxeDrxSgaDPy4zZ3w05PRZeJNnlWhzFz5OkX49J4krc+A8X2d2M69vGMBEX0uyl8M+W+8gH+kBqQ=="],
"lodash.defaults": ["lodash.defaults@4.2.0", "", {}, "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ=="],
"lodash.difference": ["lodash.difference@4.5.0", "", {}, "sha512-dS2j+W26TQ7taQBGN8Lbbq04ssV3emRw4NY58WErlTO29pIqS0HmoT5aJ9+TUQ1N3G+JOZSji4eugsWwGp9yPA=="],
"lodash.escaperegexp": ["lodash.escaperegexp@4.1.2", "", {}, "sha512-TM9YBvyC84ZxE3rgfefxUWiQKLilstD6k7PTGt6wfbtXF8ixIJLOL3VYyV/z+ZiPLsVxAsKAFVwWlWeb2Y8Yyw=="],
"lodash.flatten": ["lodash.flatten@4.4.0", "", {}, "sha512-C5N2Z3DgnnKr0LOpv/hKCgKdb7ZZwafIrsesve6lmzvZIRZRGaZ/l6Q8+2W7NaT+ZwO3fFlSCzCzrDCFdJfZ4g=="],
"lodash.groupby": ["lodash.groupby@4.6.0", "", {}, "sha512-5dcWxm23+VAoz+awKmBaiBvzox8+RqMgFhi7UvX9DHZr2HdxHXM/Wrf8cfKpsW37RNrvtPn6hSwNqurSILbmJw=="],
"lodash.isboolean": ["lodash.isboolean@3.0.3", "", {}, "sha512-Bz5mupy2SVbPHURB98VAcw+aHh4vRV5IPNhILUCsOzRmsTmSQ17jIuqopAentWoehktxGd9e/hbIXq980/1QJg=="],
"lodash.isequal": ["lodash.isequal@4.5.0", "", {}, "sha512-pDo3lu8Jhfjqls6GkMgpahsF9kCyayhgykjyLMNFTKWrpVdAQtYyB4muAMWozBB4ig/dtWAmsMxLEI8wuz+DYQ=="],
"lodash.isfunction": ["lodash.isfunction@3.0.9", "", {}, "sha512-AirXNj15uRIMMPihnkInB4i3NHeb4iBtNg9WRWuK2o31S+ePwwNmDPaTL3o7dTJ+VXNZim7rFs4rxN4YU1oUJw=="],
"lodash.isnil": ["lodash.isnil@4.0.0", "", {}, "sha512-up2Mzq3545mwVnMhTDMdfoG1OurpA/s5t88JmQX809eH3C8491iu2sfKhTfhQtKY78oPNhiaHJUpT/dUDAAtng=="],
"lodash.isplainobject": ["lodash.isplainobject@4.0.6", "", {}, "sha512-oSXzaWypCMHkPC3NvBEaPHf0KsA5mvPrOPgQWDsbg8n7orZ290M0BmC/jgRZ4vcJ6DTAhjrsSYgdsW/F+MFOBA=="],
"lodash.isundefined": ["lodash.isundefined@3.0.1", "", {}, "sha512-MXB1is3s899/cD8jheYYE2V9qTHwKvt+npCwpD+1Sxm3Q3cECXCiYHjeHWXNwr6Q0SOBPrYUDxendrO6goVTEA=="],
"lodash.union": ["lodash.union@4.6.0", "", {}, "sha512-c4pB2CdGrGdjMKYLA+XiRDO7Y0PRQbm/Gzg8qMj+QH+pFVAoTp5sBpO0odL3FjoPCGjK96p6qsP+yQoiLoOBcw=="],
"lodash.uniq": ["lodash.uniq@4.5.0", "", {}, "sha512-xfBaXQd9ryd9dlSDvnvI0lvxfLJlYAZzXomUYzLKtUeOQvOP5piqAWuGtrhWeqaXK9hhoM/iyJc5AV+XfsX3HQ=="],
"math-intrinsics": ["math-intrinsics@1.1.0", "", {}, "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g=="],
"media-typer": ["media-typer@1.1.0", "", {}, "sha512-aisnrDP4GNe06UcKFnV5bfMNPBUw4jsLGaWwWfnH3v02GnBuXX2MCVn5RbrWo0j3pczUilYblq7fQ7Nw2t5XKw=="],
@@ -137,10 +250,16 @@
"mime-types": ["mime-types@3.0.2", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A=="],
"minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="],
"mkdirp": ["mkdirp@3.0.1", "", { "bin": { "mkdirp": "dist/cjs/src/bin.js" } }, "sha512-+NsyUUAZDmo6YVHzL/stxSu3t9YS1iljliy3BSDrXJ/dkn1KYdmtZODGGjLcc9XLgVVpH4KshHB8XmZgMhaBXg=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"negotiator": ["negotiator@1.0.0", "", {}, "sha512-8Ofs/AUQh8MaEcrlq5xOX0CQ9ypTF5dl78mjlMNfOK08fzpgTHQRQPBxcPlEtIw0yRpws+Zo/3r+5WRby7u3Gg=="],
"normalize-path": ["normalize-path@3.0.0", "", {}, "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA=="],
"object-assign": ["object-assign@4.1.1", "", {}, "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg=="],
"object-inspect": ["object-inspect@1.13.4", "", {}, "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew=="],
@@ -149,14 +268,24 @@
"once": ["once@1.4.0", "", { "dependencies": { "wrappy": "1" } }, "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w=="],
"pako": ["pako@1.0.11", "", {}, "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw=="],
"parseurl": ["parseurl@1.3.3", "", {}, "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ=="],
"path-is-absolute": ["path-is-absolute@1.0.1", "", {}, "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg=="],
"path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="],
"path-to-regexp": ["path-to-regexp@8.4.2", "", {}, "sha512-qRcuIdP69NPm4qbACK+aDogI5CBDMi1jKe0ry5rSQJz8JVLsC7jV8XpiJjGRLLol3N+R5ihGYcrPLTno6pAdBA=="],
"pend": ["pend@1.2.0", "", {}, "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg=="],
"pinyin-pro": ["pinyin-pro@3.29.3", "", {}, "sha512-+UU9bx6vfDw8amOJGHm0TE0rdQl8VPylsDWviQ5OOQ3e+on1xRP4OqDbiDuMT5OISgvfl/Y6ez1BBRaIP80GLQ=="],
"pkce-challenge": ["pkce-challenge@5.0.1", "", {}, "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="],
"process-nextick-args": ["process-nextick-args@2.0.1", "", {}, "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag=="],
"proxy-addr": ["proxy-addr@2.0.7", "", { "dependencies": { "forwarded": "0.2.0", "ipaddr.js": "1.9.1" } }, "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg=="],
"qs": ["qs@6.15.2", "", { "dependencies": { "side-channel": "^1.1.0" } }, "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw=="],
@@ -165,16 +294,28 @@
"raw-body": ["raw-body@3.0.2", "", { "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", "iconv-lite": "~0.7.0", "unpipe": "~1.0.0" } }, "sha512-K5zQjDllxWkf7Z5xJdV0/B0WTNqx6vxG70zJE4N0kBs4LovmEYWJzQGxC9bS9RAKu3bgM40lrd5zoLJ12MQ5BA=="],
"readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
"readdir-glob": ["readdir-glob@1.1.3", "", { "dependencies": { "minimatch": "^5.1.0" } }, "sha512-v05I2k7xN8zXvPD9N+z/uhXPaj0sUFCe2rcWZIpBsqxfP7xXFQ0tipAd/wjj1YxWyWtUS5IDJpOG82JKt2EAVA=="],
"require-from-string": ["require-from-string@2.0.2", "", {}, "sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw=="],
"rimraf": ["rimraf@2.7.1", "", { "dependencies": { "glob": "^7.1.3" }, "bin": { "rimraf": "./bin.js" } }, "sha512-uWjbaKIK3T1OSVptzX7Nl6PvQ3qAGtKEtVRjRuazjfL3Bx5eI409VZSqgND+4UNnmzLVdPj9FqFJNPqBZFve4w=="],
"router": ["router@2.2.0", "", { "dependencies": { "debug": "^4.4.0", "depd": "^2.0.0", "is-promise": "^4.0.0", "parseurl": "^1.3.3", "path-to-regexp": "^8.0.0" } }, "sha512-nLTrUKm2UyiL7rlhapu/Zl45FwNgkZGaCpZbIHajDYgwlJCOzLSk+cIPAnsEqV955GjILJnKbdQC1nVPz+gAYQ=="],
"safe-buffer": ["safe-buffer@5.1.2", "", {}, "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g=="],
"safer-buffer": ["safer-buffer@2.1.2", "", {}, "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg=="],
"saxes": ["saxes@5.0.1", "", { "dependencies": { "xmlchars": "^2.2.0" } }, "sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw=="],
"send": ["send@1.2.1", "", { "dependencies": { "debug": "^4.4.3", "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "etag": "^1.8.1", "fresh": "^2.0.0", "http-errors": "^2.0.1", "mime-types": "^3.0.2", "ms": "^2.1.3", "on-finished": "^2.4.1", "range-parser": "^1.2.1", "statuses": "^2.0.2" } }, "sha512-1gnZf7DFcoIcajTjTwjwuDjzuz4PPcY2StKPlsGAQ1+YH20IRVrBaXSWmdjowTJ6u8Rc01PoYOGHXfP1mYcZNQ=="],
"serve-static": ["serve-static@2.2.1", "", { "dependencies": { "encodeurl": "^2.0.0", "escape-html": "^1.0.3", "parseurl": "^1.3.3", "send": "^1.2.0" } }, "sha512-xRXBn0pPqQTVQiC8wyQrKs2MOlX24zQ0POGaj0kultvoOCstBQM5yvOhAVSUwOMjQtTvsPWoNCHfPGwaaQJhTw=="],
"setimmediate": ["setimmediate@1.0.5", "", {}, "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA=="],
"setprototypeof": ["setprototypeof@1.2.0", "", {}, "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="],
"shebang-command": ["shebang-command@2.0.0", "", { "dependencies": { "shebang-regex": "^3.0.0" } }, "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA=="],
@@ -191,8 +332,16 @@
"statuses": ["statuses@2.0.2", "", {}, "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw=="],
"string_decoder": ["string_decoder@1.3.0", "", { "dependencies": { "safe-buffer": "~5.2.0" } }, "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA=="],
"tar-stream": ["tar-stream@2.2.0", "", { "dependencies": { "bl": "^4.0.3", "end-of-stream": "^1.4.1", "fs-constants": "^1.0.0", "inherits": "^2.0.3", "readable-stream": "^3.1.1" } }, "sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ=="],
"tmp": ["tmp@0.2.7", "", {}, "sha512-e0votIpp4Uo2AJYSzVHV6xCcawuiez3DzqDAbrTc3YxBkplN6e+dM13ZeIcZnDg/QpSuU2zfZ3rzwY8ukEnaXw=="],
"toidentifier": ["toidentifier@1.0.1", "", {}, "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA=="],
"traverse": ["traverse@0.3.9", "", {}, "sha512-iawgk0hLP3SxGKDfnDJf8wTz4p2qImnyihM5Hh/sGvQ3K37dPi/w8sRhdNIxYA1TwFwc5mDhIJq+O0RsvXBKdQ=="],
"type-is": ["type-is@2.1.0", "", { "dependencies": { "content-type": "^2.0.0", "media-typer": "^1.1.0", "mime-types": "^3.0.0" } }, "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA=="],
"typescript": ["typescript@5.9.3", "", { "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" } }, "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw=="],
@@ -201,18 +350,66 @@
"unpipe": ["unpipe@1.0.0", "", {}, "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ=="],
"unzipper": ["unzipper@0.10.14", "", { "dependencies": { "big-integer": "^1.6.17", "binary": "~0.3.0", "bluebird": "~3.4.1", "buffer-indexof-polyfill": "~1.0.0", "duplexer2": "~0.1.4", "fstream": "^1.0.12", "graceful-fs": "^4.2.2", "listenercount": "~1.0.1", "readable-stream": "~2.3.6", "setimmediate": "~1.0.4" } }, "sha512-ti4wZj+0bQTiX2KmKWuwj7lhV+2n//uXEotUmGuQqrbVZSEGFMbI68+c6JCQ8aAmUWYvtHEz2A8K6wXvueR/6g=="],
"util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="],
"uuid": ["uuid@8.3.2", "", { "bin": { "uuid": "dist/bin/uuid" } }, "sha512-+NYs2QeMWy+GWFOEm9xnn6HCDp0l7QBD7ml8zLUmJ+93Q5NF0NocErnwkTkXVFNiX3/fpC6afS8Dhb/gz7R7eg=="],
"vary": ["vary@1.1.2", "", {}, "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg=="],
"which": ["which@2.0.2", "", { "dependencies": { "isexe": "^2.0.0" }, "bin": { "node-which": "./bin/node-which" } }, "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA=="],
"wrappy": ["wrappy@1.0.2", "", {}, "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ=="],
"xmlchars": ["xmlchars@2.2.0", "", {}, "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw=="],
"yaml": ["yaml@2.9.0", "", { "bin": { "yaml": "bin.mjs" } }, "sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA=="],
"yauzl": ["yauzl@3.4.0", "", { "dependencies": { "pend": "~1.2.0" } }, "sha512-jIH9yLR9wqr0wOS0TpBvo/g/2UgZH5qePVbjgRliiF0BYvOZyaBknKsF+x9Iht0O6sqgnB93rCICdOZFecJuDw=="],
"zip-stream": ["zip-stream@4.1.1", "", { "dependencies": { "archiver-utils": "^3.0.4", "compress-commons": "^4.1.2", "readable-stream": "^3.6.0" } }, "sha512-9qv4rlDiopXg4E69k+vMHjNN63YFMe9sZMrdlvKnCjlCRWeCBswPPMPUfx+ipsAWq1LXHe70RcbaHdJJpS6hyQ=="],
"zod": ["zod@4.4.3", "", {}, "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ=="],
"zod-to-json-schema": ["zod-to-json-schema@3.25.2", "", { "peerDependencies": { "zod": "^3.25.28 || ^4" } }, "sha512-O/PgfnpT1xKSDeQYSCfRI5Gy3hPf91mKVDuYLUHZJMiDFptvP41MSnWofm8dnCm0256ZNfZIM7DSzuSMAFnjHA=="],
"@fast-csv/format/@types/node": ["@types/node@14.18.63", "", {}, "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ=="],
"@fast-csv/parse/@types/node": ["@types/node@14.18.63", "", {}, "sha512-fAtCfv4jJg+ExtXhvCkCqUKZ+4ok/JQk01qDKhL5BDDoS3AxKXhV5/MAVUZyQnSEd2GT92fkgZl0pz0Q0AzcIQ=="],
"archiver-utils/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"body-parser/iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"duplexer2/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"glob/minimatch": ["minimatch@3.1.5", "", { "dependencies": { "brace-expansion": "^1.1.7" } }, "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w=="],
"jszip/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"lazystream/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"raw-body/iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"string_decoder/safe-buffer": ["safe-buffer@5.2.1", "", {}, "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ=="],
"type-is/content-type": ["content-type@2.0.0", "", {}, "sha512-j/O/d7GcZCyNl7/hwZAb606rzqkyvaDctLmckbxLzHvFBzTJHuGEdodATcP3yIRoDrLHkIATJuvzbFlp/ki2cQ=="],
"unzipper/readable-stream": ["readable-stream@2.3.8", "", { "dependencies": { "core-util-is": "~1.0.0", "inherits": "~2.0.3", "isarray": "~1.0.0", "process-nextick-args": "~2.0.0", "safe-buffer": "~5.1.1", "string_decoder": "~1.1.1", "util-deprecate": "~1.0.1" } }, "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA=="],
"zip-stream/archiver-utils": ["archiver-utils@3.0.4", "", { "dependencies": { "glob": "^7.2.3", "graceful-fs": "^4.2.0", "lazystream": "^1.0.0", "lodash.defaults": "^4.2.0", "lodash.difference": "^4.5.0", "lodash.flatten": "^4.4.0", "lodash.isplainobject": "^4.0.6", "lodash.union": "^4.6.0", "normalize-path": "^3.0.0", "readable-stream": "^3.6.0" } }, "sha512-KVgf4XQVrTjhyWmx6cte4RxonPLR9onExufI1jhvw/MQ4BB6IsZD5gT8Lq+u/+pRkWna/6JoHpiQioaqFP5Rzw=="],
"archiver-utils/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"duplexer2/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"glob/minimatch/brace-expansion": ["brace-expansion@1.1.18", "", { "dependencies": { "balanced-match": "^1.0.0", "concat-map": "0.0.1" } }, "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw=="],
"jszip/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"lazystream/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
"unzipper/readable-stream/string_decoder": ["string_decoder@1.1.1", "", { "dependencies": { "safe-buffer": "~5.1.0" } }, "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg=="],
}
}
+343 -81
View File
@@ -1,82 +1,323 @@
import{createRequire as _y}from"node:module";var Qy=Object.create;var{getPrototypeOf:Py,defineProperty:O$,getOwnPropertyNames:Fy}=Object;var Ky=Object.prototype.hasOwnProperty;function By(n){return this[n]}var Ey,Ty,t0=(n,i,r)=>{var o=n!=null&&typeof n==="object";if(o){var t=i?Ey??=new WeakMap:Ty??=new WeakMap,u=t.get(n);if(u)return u}r=n!=null?Qy(Py(n)):{};let e=i||!n||!n.__esModule?O$(r,"default",{value:n,enumerable:!0}):r;for(let l of Fy(n))if(!Ky.call(e,l))O$(e,l,{get:By.bind(n,l),enumerable:!0});if(o)t.set(n,e);return e};var Y=(n,i)=>()=>(i||n((i={exports:{}}).exports,i),i.exports);var Vy=(n)=>n;function qy(n,i){this[n]=Vy.bind(null,i)}var Pi=(n,i)=>{for(var r in i)O$(n,r,{get:i[r],enumerable:!0,configurable:!0,set:qy.bind(i,r)})};var r0=_y(import.meta.url);var nu=Y((YD)=>{Object.defineProperty(YD,"__esModule",{value:!0});YD.regexpCode=YD.getEsmExportName=YD.getProperty=YD.safeStringify=YD.stringify=YD.strConcat=YD.addCodeArg=YD.str=YD._=YD.nil=YD._Code=YD.Name=YD.IDENTIFIER=YD._CodeOrName=void 0;class Tl{}YD._CodeOrName=Tl;YD.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class jr extends Tl{constructor(n){super();if(!YD.IDENTIFIER.test(n))throw Error("CodeGen: name must be a valid identifier");this.str=n}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}YD.Name=jr;class fi extends Tl{constructor(n){super();this._items=typeof n==="string"?[n]:n}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let n=this._items[0];return n===""||n==='""'}get str(){var n;return(n=this._str)!==null&&n!==void 0?n:this._str=this._items.reduce((i,r)=>`${i}${r}`,"")}get names(){var n;return(n=this._names)!==null&&n!==void 0?n:this._names=this._items.reduce((i,r)=>{if(r instanceof jr)i[r.str]=(i[r.str]||0)+1;return i},{})}}YD._Code=fi;YD.nil=new fi("");function XD(n,...i){let r=[n[0]],o=0;while(o<i.length)Qc(r,i[o]),r.push(n[++o]);return new fi(r)}YD._=XD;var pc=new fi("+");function HD(n,...i){let r=[so(n[0])],o=0;while(o<i.length)r.push(pc),Qc(r,i[o]),r.push(pc,so(n[++o]));return IX(r),new fi(r)}YD.str=HD;function Qc(n,i){if(i instanceof fi)n.push(...i._items);else if(i instanceof jr)n.push(i);else n.push(wX(i))}YD.addCodeArg=Qc;function IX(n){let i=1;while(i<n.length-1){if(n[i]===pc){let r=gX(n[i-1],n[i+1]);if(r!==void 0){n.splice(i-1,3,r);continue}n[i++]="+"}i++}}function gX(n,i){if(i==='""')return n;if(n==='""')return i;if(typeof n=="string"){if(i instanceof jr||n[n.length-1]!=='"')return;if(typeof i!="string")return`${n.slice(0,-1)}${i}"`;if(i[0]==='"')return n.slice(0,-1)+i.slice(1);return}if(typeof i=="string"&&i[0]==='"'&&!(n instanceof jr))return`"${n}${i.slice(1)}`;return}function bX(n,i){return i.emptyStr()?n:n.emptyStr()?i:HD`${n}${i}`}YD.strConcat=bX;function wX(n){return typeof n=="number"||typeof n=="boolean"||n===null?n:so(Array.isArray(n)?n.join(","):n)}function fX(n){return new fi(so(n))}YD.stringify=fX;function so(n){return JSON.stringify(n).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}YD.safeStringify=so;function cX(n){return typeof n=="string"&&YD.IDENTIFIER.test(n)?new fi(`.${n}`):XD`[${n}]`}YD.getProperty=cX;function UX(n){if(typeof n=="string"&&YD.IDENTIFIER.test(n))return new fi(`${n}`);throw Error(`CodeGen: invalid export name: ${n}, use explicit $id name mapping`)}YD.getEsmExportName=UX;function DX(n){return new fi(n.toString())}YD.regexpCode=DX});var Bc=Y((FD)=>{Object.defineProperty(FD,"__esModule",{value:!0});FD.ValueScope=FD.ValueScopeName=FD.Scope=FD.varKinds=FD.UsedValueState=void 0;var an=nu();class QD extends Error{constructor(n){super(`CodeGen: "code" for ${n} not defined`);this.value=n.value}}var ql;(function(n){n[n.Started=0]="Started",n[n.Completed=1]="Completed"})(ql||(FD.UsedValueState=ql={}));FD.varKinds={const:new an.Name("const"),let:new an.Name("let"),var:new an.Name("var")};class Fc{constructor({prefixes:n,parent:i}={}){this._names={},this._prefixes=n,this._parent=i}toName(n){return n instanceof an.Name?n:this.name(n)}name(n){return new an.Name(this._newName(n))}_newName(n){let i=this._names[n]||this._nameGroup(n);return`${n}${i.index++}`}_nameGroup(n){var i,r;if(((r=(i=this._parent)===null||i===void 0?void 0:i._prefixes)===null||r===void 0?void 0:r.has(n))||this._prefixes&&!this._prefixes.has(n))throw Error(`CodeGen: prefix "${n}" is not allowed in this scope`);return this._names[n]={prefix:n,index:0}}}FD.Scope=Fc;class Kc extends an.Name{constructor(n,i){super(i);this.prefix=n}setValue(n,{property:i,itemIndex:r}){this.value=n,this.scopePath=an._`.${new an.Name(i)}[${r}]`}}FD.ValueScopeName=Kc;var XX=an._`\n`;class PD extends Fc{constructor(n){super(n);this._values={},this._scope=n.scope,this.opts={...n,_n:n.lines?XX:an.nil}}get(){return this._scope}name(n){return new Kc(n,this._newName(n))}value(n,i){var r;if(i.ref===void 0)throw Error("CodeGen: ref must be passed in value");let o=this.toName(n),{prefix:t}=o,u=(r=i.key)!==null&&r!==void 0?r:i.ref,e=this._values[t];if(e){let I=e.get(u);if(I)return I}else e=this._values[t]=newLine truncated
`:""},this._extScope=n,this._scope=new ci.Scope({parent:n}),this._nodes=[new ZD]}toString(){return this._root.render(this.opts)}name(n){return this._scope.name(n)}scopeName(n){return this._extScope.name(n)}scopeValue(n,i){let r=this._extScope.value(n,i);return(this._values[r.prefix]||(this._values[r.prefix]=new Set)).add(r),r}getScopeValue(n,i){return this._extScope.getValue(n,i)}scopeRefs(n){return this._extScope.scopeRefs(n,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(n,i,r,o){let t=this._scope.toName(i);if(r!==void 0&&o)this._constants[t.str]=r;return this._leafNode(new BD(n,t,r)),t}const(n,i,r){return this._def(ci.varKinds.const,n,i,r)}let(n,i,r){return this._def(ci.varKinds.let,n,i,r)}var(n,i,r){return this._def(ci.varKinds.var,n,i,r)}assign(n,i,r){return this._leafNode(new Vc(n,i,r))}add(n,i){return this._leafNode(new ED(n,sn.operators.ADD,i))}code(n){if(typeof n=="function")n();else if(n!==s.nil)this._leafNode(new _D(n));return this}object(...n){let i=["{"];for(let[r,o]of n){if(i.length>1)i.push(",");if(i.push(r),r!==o||this.opts.es5)i.push(":"),(0,s.addCodeArg)(i,o)}return i.push("}"),new s._Code(i)}if(n,i,r){if(this._blockNode(new Ti(n)),i&&r)this.code(i).else().code(r).endIf();else if(i)this.code(i).endIf();else if(r)throw Error('CodeGen: "else" body without "then" body');return this}elseIf(n){return this._elseNode(new Ti(n))}else(){return this._elseNode(new iu)}endIf(){return this._endBlockNode(Ti,iu)}_for(n,i){if(this._blockNode(n),i)this.code(i).endFor();return this}for(n,i){return this._for(new MD(n),i)}forRange(n,i,r,o,t=this.opts.es5?ci.varKinds.var:ci.varKinds.let){let u=this._scope.toName(n);return this._for(new zD(t,u,i,r),()=>o(u))}forOf(n,i,r,o=ci.varKinds.const){let t=this._scope.toName(n);if(this.opts.es5){let u=i instanceof s.Name?i:this.var("_arr",i);return this.forRange("_i",0,s._`${u}.length`,(e)=>{this.var(t,s._`${u}[${e}]`),r(t)})}return this._for(new Ec("of",o,t,i),()=>r(t))}forIn(n,i,r,o=this.opts.es5?ci.varKinds.var:ci.varKinds.const){if(this.opts.ownProperties)return this.forOf(n,s._`Object.keys(${i})`,r);let t=this._scope.toName(n);return this._for(new Ec("in",o,t,i),()=>r(t))}endFor(){return this._endBlockNode(Jr)}label(n){return this._leafNode(new TD(n))}break(n){return this._leafNode(new VD(n))}return(n){let i=new Zl;if(this._blockNode(i),this.code(n),i.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(Zl)}try(n,i,r){if(!i&&!r)throw Error('CodeGen: "try" without "catch" and "finally"');let o=new CD;if(this._blockNode(o),this.code(n),i){let t=this.name("e");this._currNode=o.catch=new Ml(t),i(t)}if(r)this._currNode=o.finally=new zl,this.code(r);return this._endBlockNode(Ml,zl)}throw(n){return this._leafNode(new qD(n))}block(n,i){if(this._blockStarts.push(this._nodes.length),n)this.code(n).endBlock(i);return this}endBlock(n){let i=this._blockStarts.pop();if(i===void 0)throw Error("CodeGen: not in self-balancing block");let r=this._nodes.length-i;if(r<0||n!==void 0&&r!==n)throw Error(`CodeGen: wrong number of nodes: ${r} vs ${n} expected`);return this._nodes.length=i,this}func(n,i=s.nil,r,o){if(this._blockNode(new _l(n,i,r)),o)this.code(o).endFunc();return this}endFunc(){return this._endBlockNode(_l)}optimize(n=1){while(n-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(n){return this._currNode.nodes.push(n),this}_blockNode(n){this._currNode.nodes.push(n),this._nodes.push(n)}_endBlockNode(n,i){let r=this._currNode;if(r instanceof n||i&&r instanceof i)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${i?`${n.kind}/${i.kind}`:n.kind}"`)}_elseNode(n){let i=this._currNode;if(!(i instanceof Ti))throw Error('CodeGen: "else" without "if"');return this._currNode=i.else=n,this}get _root(){return this._nodes[0]}get _currNode(){let n=this._nodes;return n[n.length-1]}set _currNode(n){let i=this._nodes;i[i.length-1]=n}}sn.CodeGen=RD;function Xt(n,i){for(let r in i)n[r]=(n[r]||0)+(i[r]||0);return n}function Cl(n,i){return i instanceof s._CodeOrName?Xt(n,i.names):n}function Xr(n,i,r){if(n instanceof s.Name)return o(n);if(!t(n))return n;return new s._Code(n._items.reduce((u,e)=>{if(e instanceof s.Name)e=o(e);if(e instanceof s._Code)u.push(...e._items);else u.push(e);return u},[]));function o(u){let e=r[u.str];if(e===void 0||i[u.str]!==1)return u;return delete i[u.str],e}function t(u){return u instanceof s._Code&&u._items.some((e)=>e instanceof s.Name&&i[e.str]===1&&r[e.str]!==void 0)}}function QX(n,i){for(let r in i)n[r]=(n[r]||0)-(i[r]||0)}function hD(n){return typeof n=="boolean"||typeof n=="number"||n===null?!n:s._`!${Tc(n)}`}sn.not=hD;var PX=mD(sn.operators.AND);function FX(...n){return n.reduce(PX)}sn.and=FX;var KX=mD(sn.operators.OR);function BX(...n){return n.reduce(KX)}sn.or=BX;function mD(n){return(i,r)=>i===s.nil?r:r===s.nil?i:s._`${Tc(i)} ${n} ${Tc(r)}`}function Tc(n){return n instanceof s.Name?n:s._`(${n})`}});var tn=Y((u1)=>{Object Line truncated
|| (${e} == "string" && ${t} && ${t} == +${t})`).assign(l,C._`+${t}`);return;case"integer":o.elseIf(C._`${e} === "boolean" || ${t} === null
|| (${e} === "string" && ${t} && ${t} == +${t} && !(${t} % 1))`).assign(l,C._`+${t}`);return;case"boolean":o.elseIf(C._`${t} === "false" || ${t} === 0 || ${t} === null`).assign(l,!1).elseIf(C._`${t} === "true" || ${t} === 1`).assign(l,!0);return;case"null":o.elseIf(C._`${t} === "" || ${t} === 0 || ${t} === false`),o.assign(l,null);return;case"array":o.elseIf(C._`${e} === "string" || ${e} === "number"
|| ${e} === "boolean" || ${t} === null`).assign(l,C._`[${t}]`)}}}function x8({gen:n,parentData:i,parentDataProperty:r},o){n.if(C._`${i} !== undefined`,()=>n.assign(C._`${i}[${r}]`,o))}function Rc(n,i,r,o=Hr.Correct){let t=o===Hr.Correct?C.operators.EQ:C.operators.NEQ,u;switch(n){case"null":return C._`${i} ${t} null`;case"array":u=C._`Array.isArray(${i})`;break;case"object":u=C._`${i} && typeof ${i} == "object" && !Array.isArray(${i})`;break;case"integer":u=e(C._`!(${i} % 1) && !isNaN(${i})`);break;case"number":u=e();break;default:return C._`typeof ${i} ${t} ${n}`}return o===Hr.Correct?u:(0,C.not)(u);function e(l=C.nil){return(0,C.and)(C._`typeof ${i} == "number"`,l,r?C._`isFinite(${i})`:C.nil)}}G1.checkDataType=Rc;function hc(n,i,r,o){if(n.length===1)return Rc(n[0],i,r,o);let t,u=(0,N1.toHash)(n);if(u.array&&u.object){let e=C._`typeof ${i} != "object"`;t=u.null?e:C._`!${i} || ${e}`,delete u.null,delete u.array,delete u.object}else t=C.nil;if(u.number)delete u.integer;for(let e in u)t=(0,C.and)(t,Rc(e,i,r,o));return t}G1.checkDataTypes=hc;var a8={message:({schema:n})=>`must be ${n}`,params:({schema:n,schemaValue:i})=>typeof n=="string"?C._`{type: ${n}}`:C._`{type: ${i}}`};function mc(n){let i=s8(n);(0,z8.reportError)(i,a8)}G1.reportTypeError=mc;function s8(n){let{gen:i,data:r,schema:o}=n,t=(0,N1.schemaRefOrVal)(n,o,"type");return{gen:i,keyword:"type",data:r,schema:o.type,schemaCode:t,schemaValue:t,parentSchema:o,params:{},it:n}}});var H1=Y((J1)=>{Object.defineProperty(J1,"__esModule",{value:!0});J1.assignDefaults=void 0;var Yr=R(),e9=tn();function l9(n,i){let{properties:r,items:o}=n.schema;if(i==="object"&&r)for(let t in r)j1(n,t,r[t].default);else if(i==="array"&&Array.isArray(o))o.forEach((t,u)=>j1(n,u,t.default))}J1.assignDefaults=l9;function j1(n,i,r){let{gen:o,compositeRule:t,data:u,opts:e}=n;if(r===void 0)return;let l=Yr._`${u}${(0,Yr.getProperty)(i)}`;if(t){(0,e9.checkStrictMode)(n,`default is ignored for: ${l}`);return}let $=Yr._`${l} === undefined`;if(e.useDefaults==="empty")$=Yr._`${$} || ${l} === null || ${l} === ""`;o.if($,Yr._`${l} = ${(0,Yr.stringify)(r)}`)}});var Ii=Y((Q1)=>{Object.defineProperty(Q1,"__esModule",{value:!0});Q1.validateUnion=Q1.validateArray=Q1.usePattern=Q1.callValidateCode=Q1.schemaProperties=Q1.allSchemaProperties=Q1.noPropertyInData=Q1.propertyInData=Q1.isOwnProperty=Q1.hasPropFunc=Q1.reportMissingProp=Q1.checkMissingProp=Q1.checkReportMissingProp=void 0;var Dn=R(),xc=tn(),gt=Vi(),v9=tn();function $9(n,i){let{gen:r,data:o,it:t}=n;r.if(sc(r,o,i,t.opts.ownProperties),()=>{n.setParams({missingProperty:Dn._`${i}`},!0),n.error()})}Q1.checkReportMissingProp=$9;function I9({gen:n,data:i,it:{opts:r}},o,t){return(0,Dn.or)(...o.map((u)=>(0,Dn.and)(sc(n,i,u,r.ownProperties),Dn._`${t} = ${u}`)))}Q1.checkMissingProp=I9;function g9(n,i){n.setParams({missingProperty:i},!0),n.error()}Q1.reportMissingProp=g9;function Y1(n){return n.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:Dn._`Object.prototype.hasOwnProperty`})}Q1.hasPropFunc=Y1;function ac(n,i,r){return Dn._`${Y1(n)}.call(${i}, ${r})`}Q1.isOwnProperty=ac;function b9(n,i,r,o){let t=Dn._`${i}${(0,Dn.getProperty)(r)} !== undefined`;return o?Dn._`${t} && ${ac(n,i,r)}`:t}Q1.propertyInData=b9;function sc(n,i,r,o){let t=Dn._`${i}${(0,Dn.getProperty)(r)} === undefined`;return o?(0,Dn.or)(t,(0,Dn.not)(ac(n,i,r))):t}Q1.noPropertyInData=sc;function p1(n){return n?Object.keys(n).filter((i)=>i!=="__proto__"):[]}Q1.allSchemaProperties=p1;function w9(n,i){return p1(i).filter((r)=>!(0,xc.alwaysValidSchema)(n,i[r]))}Q1.schemaProperties=w9;function f9({schemaCode:n,data:i,it:{gen:r,topSchemaRef:o,schemaPath:t,errorPath:u},it:e},l,$,I){let g=I?Dn._`${n}, ${i}, ${o}${t}`:i,b=[[gt.default.instancePath,(0,Dn.strConcat)(gt.default.instancePath,u)],[gt.default.parentData,e.parentData],[gt.default.parentDataProperty,e.parentDataProperty],[gt.default.rootData,gt.default.rootData]];if(e.opts.dynamicRef)b.push([gt.default.dynamicAnchors,gt.default.dynamicAnchors]);let w=Dn._`${g}, ${r.object(...b)}`;return $!==Dn.nil?Dn._`${l}.call(${$}, ${w})`:Dn._`${l}(${w})`}Q1.callValidateCode=f9;var c9=Dn._`new RegExp`;function U9({gen:n,it:{opts:i}},r){let o=i.unicodeRegExp?"u":"",{regExp:t}=i.code,u=t(r,o);return n.scopeValue("pattern",{key:u.toString(),ref:u,code:Dn._`${t.code==="new RegExp"?c9:(0,v9.useFunc)(n,t)}(${r}, ${o})`})}Q1.usePattern=U9;function D9(n){let{gen:i,data:r,keyword:o,it:t}=n,u=i.name("valid");if(t.allErrors){let l=i.let("valid",!0);return e(()=>i.assign(l,!1)),l}return i.var(u,!0),e(()=>i.break()),u;function e(l){let $=i.const("len",Dn._`${r}.length`);i.forRange("i",0,$,(I)=>{n.subschema({keyword:o,dataProp:I,dataPropType:xc.Type.Num},u),i.if((0,Dn.not)(u),l)})}}Q1.validateArray=D9;function S9(n){let{gen:i,schema:r,keyword:o,it:t}=n;if(!Array.isArray(r))throw Error("ajv implementation error");if(r.some(($)=>(0,xc.alwaysValidSchema)(t,$))&&!t.opts.unevaluated)return;let e=i.let("valid",!1),l=i.name("_valid");i.block(()=>r. Line truncated
missingProperty: ${o},
depsCount: ${i},
deps: ${r}}`};var K7={keyword:"dependencies",type:"object",schemaType:"object",error:xA.error,code(n){let[i,r]=B7(n);hA(n,i),mA(n,r)}};function B7({schema:n}){let i={},r={};for(let o in n){if(o==="__proto__")continue;let t=Array.isArray(n[o])?i:r;t[o]=n[o]}return[i,r]}function hA(n,i=n.schema){let{gen:r,data:o,it:t}=n;if(Object.keys(i).length===0)return;let u=r.let("missing");for(let e in i){let l=i[e];if(l.length===0)continue;let $=(0,Au.propertyInData)(r,o,e,t.opts.ownProperties);if(n.setParams({property:e,depsCount:l.length,deps:l.join(", ")}),t.allErrors)r.if($,()=>{for(let I of l)(0,Au.checkReportMissingProp)(n,I)});else r.if(k6._`${$} && (${(0,Au.checkMissingProp)(n,l,u)})`),(0,Au.reportMissingProp)(n,u),r.else()}}xA.validatePropertyDeps=hA;function mA(n,i=n.schema){let{gen:r,data:o,keyword:t,it:u}=n,e=r.name("valid");for(let l in i){if((0,F7.alwaysValidSchema)(u,i[l]))continue;r.if((0,Au.propertyInData)(r,o,l,u.opts.ownProperties),()=>{let $=n.subschema({keyword:t,schemaProp:l},e);n.mergeValidEvaluated($,e)},()=>r.var(e,!0)),n.ok(e)}}xA.validateSchemaDeps=mA;xA.default=K7});var rO=Y((tO)=>{Object.defineProperty(tO,"__esModule",{value:!0});var iO=R(),V7=tn(),q7={message:"property name must be valid",params:({params:n})=>iO._`{propertyName: ${n.propertyName}}`},_7={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:q7,code(n){let{gen:i,schema:r,data:o,it:t}=n;if((0,V7.alwaysValidSchema)(t,r))return;let u=i.name("valid");i.forIn("key",o,(e)=>{n.setParams({propertyName:e}),n.subschema({keyword:"propertyNames",data:e,dataTypes:["string"],propertyName:e,compositeRule:!0},u),i.if((0,iO.not)(u),()=>{if(n.error(!0),!t.allErrors)i.break()})}),n.ok(u)}};tO.default=_7});var N6=Y((oO)=>{Object.defineProperty(oO,"__esModule",{value:!0});var cv=Ii(),Si=R(),M7=Vi(),Uv=tn(),z7={message:"must NOT have additional properties",params:({params:n})=>Si._`{additionalProperty: ${n.additionalProperty}}`},C7={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:z7,code(n){let{gen:i,schema:r,parentSchema:o,data:t,errsCount:u,it:e}=n;if(!u)throw Error("ajv implementation error");let{allErrors:l,opts:$}=e;if(e.props=!0,$.removeAdditional!=="all"&&(0,Uv.alwaysValidSchema)(e,r))return;let I=(0,cv.allSchemaProperties)(o.properties),g=(0,cv.allSchemaProperties)(o.patternProperties);b(),n.ok(Si._`${u} === ${M7.default.errors}`);function b(){i.forIn("key",t,(d)=>{if(!I.length&&!g.length)c(d);else i.if(w(d),()=>c(d))})}function w(d){let k;if(I.length>8){let P=(0,Uv.schemaRefOrVal)(e,o.properties,"properties");k=(0,cv.isOwnProperty)(i,P,d)}else if(I.length)k=(0,Si.or)(...I.map((P)=>Si._`${d} === ${P}`));else k=Si.nil;if(g.length)k=(0,Si.or)(k,...g.map((P)=>Si._`${(0,cv.usePattern)(n,P)}.test(${d})`));return(0,Si.not)(k)}function f(d){i.code(Si._`delete ${t}[${d}]`)}function c(d){if($.removeAdditional==="all"||$.removeAdditional&&r===!1){f(d);return}if(r===!1){if(n.setParams({additionalProperty:d}),n.error(),!l)i.break();return}if(typeof r=="object"&&!(0,Uv.alwaysValidSchema)(e,r)){let k=i.name("valid");if($.removeAdditional==="failing")S(d,k,!1),i.if((0,Si.not)(k),()=>{n.reset(),f(d)});else if(S(d,k),!l)i.if((0,Si.not)(k),()=>i.break())}}function S(d,k,P){let Q={keyword:"additionalProperties",dataProp:d,dataPropType:Uv.Type.Str};if(P===!1)Object.assign(Q,{compositeRule:!0,createErrors:!1,allErrors:!1});n.subschema(Q,k)}}};oO.default=C7});var vO=Y((lO)=>{Object.defineProperty(lO,"__esModule",{value:!0});var h7=lu(),uO=Ii(),L6=tn(),eO=N6(),m7={keyword:"properties",type:"object",schemaType:"object",code(n){let{gen:i,schema:r,parentSchema:o,data:t,it:u}=n;if(u.opts.removeAdditional==="all"&&o.additionalProperties===void 0)eO.default.code(new h7.KeywordCxt(u,eO.default,"additionalProperties"));let e=(0,uO.allSchemaProperties)(r);for(let b of e)u.definedProperties.add(b);if(u.opts.unevaluated&&e.length&&u.props!==!0)u.props=L6.mergeEvaluated.props(i,(0,L6.toHash)(e),u.props);let l=e.filter((b)=>!(0,L6.alwaysValidSchema)(u,r[b]));if(l.length===0)return;let $=i.name("valid");for(let b of l){if(I(b))g(b);else{if(i.if((0,uO.propertyInData)(i,t,b,u.opts.ownProperties)),g(b),!u.allErrors)i.else().var($,!0);i.endIf()}n.it.definedProperties.add(b),n.ok($)}function I(b){return u.opts.useDefaults&&!u.compositeRule&&r[b].default!==void 0}function g(b){n.subschema({keyword:"properties",schemaProp:b,dataProp:b},$)}}};lO.default=m7});var wO=Y((bO)=>{Object.defineProperty(bO,"__esModule",{value:!0});var $O=Ii(),Dv=R(),IO=tn(),gO=tn(),a7={keyword:"patternProperties",type:"object",schemaType:"object",code(n){let{gen:i,schema:r,data:o,parentSchema:t,it:u}=n,{opts:e}=u,l=(0,$O.allSchemaProperties)(r),$=l.filter((S)=>(0,IO.alwaysValidSchema)(u,r[S]));if(l.length===0||$.length===l.length&&(!u.opts.unevaluated||u.props===!0))return;let I=e.strictSchema&&!e.allowMatchingProperties&&t.properties,g=i.name("valid");if(u.props!==!0&&!(u.props instanceof Dv.Name))u.props=(0,gO. Line truncated
`)}var Rt=(n)=>(i,r,o,t)=>{let u=o?{...o,async:!1}:{async:!1},e=i._zod.run({value:r,issues:[]},u);if(e instanceof Promise)throw new Li;if(e.issues.length){let l=new(t?.Err??n)(e.issues.map(($)=>_n($,u,dn())));throw xu(l,t?.callee),l}return e.value},Io=Rt(mn),ht=(n)=>async(i,r,o,t)=>{let u=o?{...o,async:!0}:{async:!0},e=i._zod.run({value:r,issues:[]},u);if(e instanceof Promise)e=await e;if(e.issues.length){let l=new(t?.Err??n)(e.issues.map(($)=>_n($,u,dn())));throw xu(l,t?.callee),l}return e.value},go=ht(mn),mt=(n)=>(i,r,o)=>{let t=o?{...o,async:!1}:{async:!1},u=i._zod.run({value:r,issues:[]},t);if(u instanceof Promise)throw new Li;return u.issues.length?{success:!1,error:new(n??lo)(u.issues.map((e)=>_n(e,t,dn())))}:{success:!0,data:u.value}},xt=mt(mn),at=(n)=>async(i,r,o)=>{let t=o?{...o,async:!0}:{async:!0},u=i._zod.run({value:r,issues:[]},t);if(u instanceof Promise)u=await u;return u.issues.length?{success:!1,error:new n(u.issues.map((e)=>_n(e,t,dn())))}:{success:!0,data:u.value}},bo=at(mn),au=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return Rt(n)(i,r,t)},g0=au(mn),su=(n)=>(i,r,o)=>{return Rt(n)(i,r,o)},b0=su(mn),ne=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return ht(n)(i,r,t)},w0=ne(mn),ie=(n)=>async(i,r,o)=>{return ht(n)(i,r,o)},f0=ie(mn),te=(n)=>(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return mt(n)(i,r,t)},c0=te(mn),re=(n)=>(i,r,o)=>{return mt(n)(i,r,o)},U0=re(mn),oe=(n)=>async(i,r,o)=>{let t=o?{...o,direction:"backward"}:{direction:"backward"};return at(n)(i,r,t)},D0=oe(mn),ue=(n)=>async(i,r,o)=>{return at(n)(i,r,o)},S0=ue(mn);var oi={};Pi(oi,{xid:()=>B$,uuid7:()=>AG,uuid6:()=>SG,uuid4:()=>DG,uuid:()=>Lt,uppercase:()=>$I,unicodeEmail:()=>A0,undefined:()=>lI,ulid:()=>K$,time:()=>nI,string:()=>tI,sha512_hex:()=>TG,sha512_base64url:()=>qG,sha512_base64:()=>VG,sha384_hex:()=>KG,sha384_base64url:()=>EG,sha384_base64:()=>BG,sha256_hex:()=>QG,sha256_base64url:()=>FG,sha256_base64:()=>PG,sha1_hex:()=>HG,sha1_base64url:()=>pG,sha1_base64:()=>YG,rfc5322Email:()=>dG,number:()=>wo,null:()=>eI,nanoid:()=>T$,md5_hex:()=>jG,md5_base64url:()=>XG,md5_base64:()=>JG,mac:()=>C$,lowercase:()=>vI,ksuid:()=>E$,ipv6:()=>z$,ipv4:()=>M$,integer:()=>oI,idnEmail:()=>kG,httpProtocol:()=>x$,html5Email:()=>OG,hostname:()=>yG,hex:()=>WG,guid:()=>q$,extendedDuration:()=>UG,emoji:()=>Z$,email:()=>_$,e164:()=>a$,duration:()=>V$,domain:()=>GG,datetime:()=>iI,date:()=>s$,cuid2:()=>F$,cuid:()=>P$,cidrv6:()=>h$,cidrv4:()=>R$,browserEmail:()=>NG,boolean:()=>uI,bigint:()=>rI,base64url:()=>ee,base64:()=>m$});var P$=/^[cC][0-9a-z]{6,}$/,F$=/^[0-9a-z]+$/,K$=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,B$=/^[0-9a-vA-V]{20}$/,E$=/^[A-Za-z0-9]{27}$/,T$=/^[a-zA-Z0-9_-]{21}$/,V$=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,UG=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,q$=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Lt=(n)=>{if(!n)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${n}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},DG=Lt(4),SG=Lt(6),AG=Lt(7),_$=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,OG=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,dG=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,A0=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,kG=A0,NG=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,LG="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function Z$(){return new RegExp(LG,"u")}var M$=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,z$=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,C$=(n)=>{let i=li(n??":");return new RegExp(`^(?:[0-9A-F]{2}${i}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${i}){5}[0-9a-f]{2}$`)},R$=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-Line truncated
`).filter((u)=>u),o=Math.min(...r.map((u)=>u.length-u.trimStart().length)),t=r.map((u)=>u.slice(o)).map((u)=>" ".repeat(this.indent*2)+u);for(let u of t)this.content.push(u)}compile(){let n=Function,i=this?.args,o=[...(this?.content??[""]).map((t)=>` ${t}`)];return new n(...i,o.join(`
`))}}var jI={major:4,minor:4,patch:3};var E=U("$ZodType",(n,i)=>{var r;n??(n={}),n._zod.def=i,n._zod.bag=n._zod.bag||{},n._zod.version=jI;let o=[...n._zod.def.checks??[]];if(n._zod.traits.has("$ZodCheck"))o.unshift(n);for(let t of o)for(let u of t._zod.onattach)u(n);if(o.length===0)(r=n._zod).deferred??(r.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{let t=(e,l,$)=>{let I=ai(e),g;for(let b of l){if(b._zod.def.when){if(Y$(e))continue;if(!b._zod.def.when(e))continue}else if(I)continue;let w=e.issues.length,f=b._zod.check(e);if(f instanceof Promise&&$?.async===!1)throw new Li;if(g||f instanceof Promise)g=(g??Promise.resolve()).then(async()=>{if(await f,e.issues.length===w)return;if(!I)I=ai(e,w)});else{if(e.issues.length===w)continue;if(!I)I=ai(e,w)}}if(g)return g.then(()=>{return e});return e},u=(e,l,$)=>{if(ai(e))return e.aborted=!0,e;let I=t(l,o,$);if(I instanceof Promise){if($.async===!1)throw new Li;return I.then((g)=>n._zod.parse(g,$))}return n._zod.parse(I,$)};n._zod.run=(e,l)=>{if(l.skipChecks)return n._zod.parse(e,l);if(l.direction==="backward"){let I=n._zod.parse({value:e.value,issues:[]},{...l,skipChecks:!0});if(I instanceof Promise)return I.then((g)=>{return u(g,e,l)});return u(I,e,l)}let $=n._zod.parse(e,l);if($ instanceof Promise){if(l.async===!1)throw new Li;return $.then((I)=>t(I,o,l))}return t($,o,l)}}h(n,"~standard",()=>({validate:(t)=>{try{let u=xt(n,t);return u.success?{value:u.data}:{issues:u.error?.issues}}catch(u){return bo(n,t).then((e)=>e.success?{value:e.data}:{issues:e.error?.issues})}},vendor:"zod",version:1}))}),yt=U("$ZodString",(n,i)=>{E.init(n,i),n._zod.pattern=[...n?._zod.bag?.patterns??[]].pop()??tI(n._zod.bag),n._zod.parse=(r,o)=>{if(i.coerce)try{r.value=String(r.value)}catch(t){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:n}),r}}),$n=U("$ZodStringFormat",(n,i)=>{st.init(n,i),yt.init(n,i)}),XI=U("$ZodGUID",(n,i)=>{i.pattern??(i.pattern=q$),$n.init(n,i)}),HI=U("$ZodUUID",(n,i)=>{if(i.version){let o={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[i.version];if(o===void 0)throw Error(`Invalid UUID version: "${i.version}"`);i.pattern??(i.pattern=Lt(o))}else i.pattern??(i.pattern=Lt());$n.init(n,i)}),YI=U("$ZodEmail",(n,i)=>{i.pattern??(i.pattern=_$),$n.init(n,i)}),pI=U("$ZodURL",(n,i)=>{$n.init(n,i),n._zod.check=(r)=>{try{let o=r.value.trim();if(!i.normalize&&i.protocol?.source===x$.source){if(!/^https?:\/\//i.test(o)){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:n,continue:!i.abort});return}}let t=new URL(o);if(i.hostname){if(i.hostname.lastIndex=0,!i.hostname.test(t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:i.hostname.source,input:r.value,inst:n,continue:!i.abort})}if(i.protocol){if(i.protocol.lastIndex=0,!i.protocol.test(t.protocol.endsWith(":")?t.protocol.slice(0,-1):t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:i.protocol.source,input:r.value,inst:n,continue:!i.abort})}if(i.normalize)r.value=t.href;else r.value=o;return}catch(o){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:n,continue:!i.abort})}}}),QI=U("$ZodEmoji",(n,i)=>{i.pattern??(i.pattern=Z$()),$n.init(n,i)}),PI=U("$ZodNanoID",(n,i)=>{i.pattern??(i.pattern=T$),$n.init(n,i)}),FI=U("$ZodCUID",(n,i)=>{i.pattern??(i.pattern=P$),$n.init(n,i)}),KI=U("$ZodCUID2",(n,i)=>{i.pattern??(i.pattern=F$),$n.init(n,i)}),BI=U("$ZodULID",(n,i)=>{i.pattern??(i.pattern=K$),$n.init(n,i)}),EI=U("$ZodXID",(n,i)=>{i.pattern??(i.pattern=B$),$n.init(n,i)}),TI=U("$ZodKSUID",(n,i)=>{i.pattern??(i.pattern=E$),$n.init(n,i)}),VI=U("$ZodISODateTime",(n,i)=>{i.pattern??(i.pattern=iI(i)),$n.init(n,i)}),qI=U("$ZodISODate",(n,i)=>{i.pattern??(i.pattern=s$),$n.init(n,i)}),_I=U("$ZodISOTime",(n,i)=>{i.pattern??(i.pattern=nI(i)),$n.init(n,i)}),ZI=U("$ZodISODuration",(n,i)=>{i.pattern??(i.pattern=V$),$n.init(n,i)}),MI=U("$ZodIPv4",(n,i)=>{i.pattern??(i.pattern=M$),$n.init(n,i),n._zod.bag.format="ipv4"}),zI=U("$ZodIPv6",(n,i)=>{i.pattern??(i.pattern=z$),$n.init(n,i),n._zod.bag.format="ipv6",n._zod.check=(r)=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:n,continue:!i.abort})}}}),CI=U("$ZodMAC",(n,i)=>{i.pattern??(i.pattern=C$(i.delimiter)),$n.init(n,i),n._zod.bag.format="mac"}),RI=U("$ZodCIDRv4",(n,i)=>{i.pattern??(i.pattern=R$),$n.init(n,i)}),hI=U("$ZodCIDRv6",(n,i)=>{i.pattern??(i.pattern=h$),$n.init(n,i),n._zod.check=(r)=>{let o=r.value.split("/");try{if(o.length!==2)throw Error();let[t,u]=o;if(!u)throw Error();let e=Number(u);if(`${e}`!==u)throw Error();if(e<0||e>128)throw Error();new URL(`http://[${t}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:n,continue:!i.abort})}}});function mI(n){if(n==="")return!0;if(/\s/.test(n))return!1;if(n.length%4!==0)return!1;try{return atob(n),!0}catch{return!1}}var Line truncated
if (${W}.issues.length) {
if (${N} in input) {
payload.issues = payload.issues.concat(${W}.issues.map(iss => ({
import{createRequire as qw0}from"node:module";var sL0=Object.create;var{getPrototypeOf:eL0,defineProperty:PO,getOwnPropertyNames:$w0}=Object;var Iw0=Object.prototype.hasOwnProperty;function Uw0($){return this[$]}var Yw0,Jw0,WI=($,I,U)=>{var Y=$!=null&&typeof $==="object";if(Y){var J=I?Yw0??=new WeakMap:Jw0??=new WeakMap,Q=J.get($);if(Q)return Q}U=$!=null?sL0(eL0($)):{};let K=I||!$||!$.__esModule?PO(U,"default",{value:$,enumerable:!0}):U;for(let q of $w0($))if(!Iw0.call(K,q))PO(K,q,{get:Uw0.bind($,q),enumerable:!0});if(Y)J.set($,K);return K};var N=($,I)=>()=>(I||$((I={exports:{}}).exports,I),I.exports);var Qw0=($)=>$;function Kw0($,I){this[$]=Qw0.bind(null,I)}var m8=($,I)=>{for(var U in I)PO($,U,{get:I[U],enumerable:!0,configurable:!0,set:Kw0.bind(I,U)})};var r=qw0(import.meta.url);var CQ=N((Rf)=>{Object.defineProperty(Rf,"__esModule",{value:!0});Rf.regexpCode=Rf.getEsmExportName=Rf.getProperty=Rf.safeStringify=Rf.stringify=Rf.strConcat=Rf.addCodeArg=Rf.str=Rf._=Rf.nil=Rf._Code=Rf.Name=Rf.IDENTIFIER=Rf._CodeOrName=void 0;class EW{}Rf._CodeOrName=EW;Rf.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;class oI extends EW{constructor($){super();if(!Rf.IDENTIFIER.test($))throw Error("CodeGen: name must be a valid identifier");this.str=$}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}}Rf.Name=oI;class f$ extends EW{constructor($){super();this._items=typeof $==="string"?[$]:$}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let $=this._items[0];return $===""||$==='""'}get str(){var $;return($=this._str)!==null&&$!==void 0?$:this._str=this._items.reduce((I,U)=>`${I}${U}`,"")}get names(){var $;return($=this._names)!==null&&$!==void 0?$:this._names=this._items.reduce((I,U)=>{if(U instanceof oI)I[U.str]=(I[U.str]||0)+1;return I},{})}}Rf._Code=f$;Rf.nil=new f$("");function Ef($,...I){let U=[$[0]],Y=0;while(Y<I.length)xP(U,I[Y]),U.push($[++Y]);return new f$(U)}Rf._=Ef;var hP=new f$("+");function Bf($,...I){let U=[vQ($[0])],Y=0;while(Y<I.length)U.push(hP),xP(U,I[Y]),U.push(hP,vQ($[++Y]));return vF0(U),new f$(U)}Rf.str=Bf;function xP($,I){if(I instanceof f$)$.push(...I._items);else if(I instanceof oI)$.push(I);else $.push(_F0(I))}Rf.addCodeArg=xP;function vF0($){let I=1;while(I<$.length-1){if($[I]===hP){let U=CF0($[I-1],$[I+1]);if(U!==void 0){$.splice(I-1,3,U);continue}$[I++]="+"}I++}}function CF0($,I){if(I==='""')return $;if($==='""')return I;if(typeof $=="string"){if(I instanceof oI||$[$.length-1]!=='"')return;if(typeof I!="string")return`${$.slice(0,-1)}${I}"`;if(I[0]==='"')return $.slice(0,-1)+I.slice(1);return}if(typeof I=="string"&&I[0]==='"'&&!($ instanceof oI))return`"${$}${I.slice(1)}`;return}function jF0($,I){return I.emptyStr()?$:$.emptyStr()?I:Bf`${$}${I}`}Rf.strConcat=jF0;function _F0($){return typeof $=="number"||typeof $=="boolean"||$===null?$:vQ(Array.isArray($)?$.join(","):$)}function SF0($){return new f$(vQ($))}Rf.stringify=SF0;function vQ($){return JSON.stringify($).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}Rf.safeStringify=vQ;function gF0($){return typeof $=="string"&&Rf.IDENTIFIER.test($)?new f$(`.${$}`):Ef`[${$}]`}Rf.getProperty=gF0;function yF0($){if(typeof $=="string"&&Rf.IDENTIFIER.test($))return new f$(`${$}`);throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`)}Rf.getEsmExportName=yF0;function hF0($){return new f$($.toString())}Rf.regexpCode=hF0});var bP=N((_f)=>{Object.defineProperty(_f,"__esModule",{value:!0});_f.ValueScope=_f.ValueScopeName=_f.Scope=_f.varKinds=_f.UsedValueState=void 0;var k6=CQ();class Cf extends Error{constructor($){super(`CodeGen: "code" for ${$} not defined`);this.value=$.value}}var RW;(function($){$[$.Started=0]="Started",$[$.Completed=1]="Completed"})(RW||(_f.UsedValueState=RW={}));_f.varKinds={const:new k6.Name("const"),let:new k6.Name("let"),var:new k6.Name("var")};class uP{constructor({prefixes:$,parent:I}={}){this._names={},this._prefixes=$,this._parent=I}toName($){return $ instanceof k6.Name?$:this.name($)}name($){return new k6.Name(this._newName($))}_newName($){let I=this._names[$]||this._nameGroup($);return`${$}${I.index++}`}_nameGroup($){var I,U;if(((U=(I=this._parent)===null||I===void 0?void 0:I._prefixes)===null||U===void 0?void 0:U.has($))||this._prefixes&&!this._prefixes.has($))throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);return this._names[$]={prefix:$,index:0}}}_f.Scope=uP;class fP extends k6.Name{constructor($,I){super(I);this.prefix=$}setValue($,{property:I,itemIndex:U}){this.value=$,this.scopePath=k6._`.${new k6.Name(I)}[${U}]`}}_f.ValueScopeName=fP;var oF0=k6._`\n`;class jf extends uP{constructor($){super($);this._values={},this._scope=$.scope,this.opts={...$,_n:$.lines?oF0:k6.nil}}get(){return this._scope}name($){return new fP($,this._newName($))}value($,I){var U;if(I.ref===void 0)throw Error("CodeGen: ref must be passed in value");let Y=this.toName($),{prefix:J}=Y,Q=(U=I.key)!==null&&U!==void 0?U:I.ref,K=this._values[J];if(K){let H=K.get(Q);if(Line truncated
`:""},this._extScope=$,this._scope=new b$.Scope({parent:$}),this._nodes=[new ff]}toString(){return this._root.render(this.opts)}name($){return this._scope.name($)}scopeName($){return this._extScope.name($)}scopeValue($,I){let U=this._extScope.value($,I);return(this._values[U.prefix]||(this._values[U.prefix]=new Set)).add(U),U}getScopeValue($,I){return this._extScope.getValue($,I)}scopeRefs($){return this._extScope.scopeRefs($,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def($,I,U,Y){let J=this._scope.toName(I);if(U!==void 0&&Y)this._constants[J.str]=U;return this._leafNode(new gf($,J,U)),J}const($,I,U){return this._def(b$.varKinds.const,$,I,U)}let($,I,U){return this._def(b$.varKinds.let,$,I,U)}var($,I,U){return this._def(b$.varKinds.var,$,I,U)}assign($,I,U){return this._leafNode(new nP($,I,U))}add($,I){return this._leafNode(new yf($,u6.operators.ADD,I))}code($){if(typeof $=="function")$();else if($!==K1.nil)this._leafNode(new uf($));return this}object(...$){let I=["{"];for(let[U,Y]of $){if(I.length>1)I.push(",");if(I.push(U),U!==Y||this.opts.es5)I.push(":"),(0,K1.addCodeArg)(I,Y)}return I.push("}"),new K1._Code(I)}if($,I,U){if(this._blockNode(new a8($)),I&&U)this.code(I).else().code(U).endIf();else if(I)this.code(I).endIf();else if(U)throw Error('CodeGen: "else" body without "then" body');return this}elseIf($){return this._elseNode(new a8($))}else(){return this._elseNode(new jQ)}endIf(){return this._endBlockNode(a8,jQ)}_for($,I){if(this._blockNode($),I)this.code(I).endFor();return this}for($,I){return this._for(new bf($),I)}forRange($,I,U,Y,J=this.opts.es5?b$.varKinds.var:b$.varKinds.let){let Q=this._scope.toName($);return this._for(new pf(J,Q,I,U),()=>Y(Q))}forOf($,I,U,Y=b$.varKinds.const){let J=this._scope.toName($);if(this.opts.es5){let Q=I instanceof K1.Name?I:this.var("_arr",I);return this.forRange("_i",0,K1._`${Q}.length`,(K)=>{this.var(J,K1._`${Q}[${K}]`),U(J)})}return this._for(new iP("of",Y,J,I),()=>U(J))}forIn($,I,U,Y=this.opts.es5?b$.varKinds.var:b$.varKinds.const){if(this.opts.ownProperties)return this.forOf($,K1._`Object.keys(${I})`,U);let J=this._scope.toName($);return this._for(new iP("in",Y,J,I),()=>U(J))}endFor(){return this._endBlockNode(rI)}label($){return this._leafNode(new hf($))}break($){return this._leafNode(new xf($))}return($){let I=new CW;if(this._blockNode(I),this.code($),I.nodes.length!==1)throw Error('CodeGen: "return" should have one node');return this._endBlockNode(CW)}try($,I,U){if(!I&&!U)throw Error('CodeGen: "try" without "catch" and "finally"');let Y=new nf;if(this._blockNode(Y),this.code($),I){let J=this.name("e");this._currNode=Y.catch=new jW(J),I(J)}if(U)this._currNode=Y.finally=new _W,this.code(U);return this._endBlockNode(jW,_W)}throw($){return this._leafNode(new kf($))}block($,I){if(this._blockStarts.push(this._nodes.length),$)this.code($).endBlock(I);return this}endBlock($){let I=this._blockStarts.pop();if(I===void 0)throw Error("CodeGen: not in self-balancing block");let U=this._nodes.length-I;if(U<0||$!==void 0&&U!==$)throw Error(`CodeGen: wrong number of nodes: ${U} vs ${$} expected`);return this._nodes.length=I,this}func($,I=K1.nil,U,Y){if(this._blockNode(new vW($,I,U)),Y)this.code(Y).endFunc();return this}endFunc(){return this._endBlockNode(vW)}optimize($=1){while($-- >0)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode($){return this._currNode.nodes.push($),this}_blockNode($){this._currNode.nodes.push($),this._nodes.push($)}_endBlockNode($,I){let U=this._currNode;if(U instanceof $||I&&U instanceof I)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${I?`${$.kind}/${I.kind}`:$.kind}"`)}_elseNode($){let I=this._currNode;if(!(I instanceof a8))throw Error('CodeGen: "else" without "if"');return this._currNode=I.else=$,this}get _root(){return this._nodes[0]}get _currNode(){let $=this._nodes;return $[$.length-1]}set _currNode($){let I=this._nodes;I[I.length-1]=$}}u6.CodeGen=cf;function B7($,I){for(let U in I)$[U]=($[U]||0)+(I[U]||0);return $}function SW($,I){return I instanceof K1._CodeOrName?B7($,I.names):$}function tI($,I,U){if($ instanceof K1.Name)return Y($);if(!J($))return $;return new K1._Code($._items.reduce((Q,K)=>{if(K instanceof K1.Name)K=Y(K);if(K instanceof K1._Code)Q.push(...K._items);else Q.push(K);return Q},[]));function Y(Q){let K=U[Q.str];if(K===void 0||I[Q.str]!==1)return Q;return delete I[Q.str],K}function J(Q){return Q instanceof K1._Code&&Q._items.some((K)=>K instanceof K1.Name&&I[K.str]===1&&U[K.str]!==void 0)}}function sF0($,I){for(let U in I)$[U]=($[U]||0)-(I[U]||0)}function df($){return typeof $=="boolean"||typeof $=="number"||$===null?!$:K1._`!${pP($)}`}u6.not=df;var eF0=mf(u6.operators.AND);function $M0(...$){return $.reduce(eF0)}u6.and=$M0;var IM0=mf(u6.operators.OR);function UM0(...$){return $.reduce(IM0)}u6.or=UM0;function mf($){return(I,U)=>I===K1.nil?U:U===K1.nil?I:K1._`${pP(I)} ${$} ${pP(U)}`}function pP($){return $ instanceof K1.Name?$:K1._`(${Line truncated
|| (${K} == "string" && ${J} && ${J} == +${J})`).assign(q,r0._`+${J}`);return;case"integer":Y.elseIf(r0._`${K} === "boolean" || ${J} === null
|| (${K} === "string" && ${J} && ${J} == +${J} && !(${J} % 1))`).assign(q,r0._`+${J}`);return;case"boolean":Y.elseIf(r0._`${J} === "false" || ${J} === 0 || ${J} === null`).assign(q,!1).elseIf(r0._`${J} === "true" || ${J} === 1`).assign(q,!0);return;case"null":Y.elseIf(r0._`${J} === "" || ${J} === 0 || ${J} === false`),Y.assign(q,null);return;case"array":Y.elseIf(r0._`${K} === "string" || ${K} === "number"
|| ${K} === "boolean" || ${J} === null`).assign(q,r0._`[${J}]`)}}}function wz0({gen:$,parentData:I,parentDataProperty:U},Y){$.if(r0._`${I} !== undefined`,()=>$.assign(r0._`${I}[${U}]`,Y))}function tP($,I,U,Y=aI.Correct){let J=Y===aI.Correct?r0.operators.EQ:r0.operators.NEQ,Q;switch($){case"null":return r0._`${I} ${J} null`;case"array":Q=r0._`Array.isArray(${I})`;break;case"object":Q=r0._`${I} && typeof ${I} == "object" && !Array.isArray(${I})`;break;case"integer":Q=K(r0._`!(${I} % 1) && !isNaN(${I})`);break;case"number":Q=K();break;default:return r0._`typeof ${I} ${J} ${$}`}return Y===aI.Correct?Q:(0,r0.not)(Q);function K(q=r0.nil){return(0,r0.and)(r0._`typeof ${I} == "number"`,q,U?r0._`isFinite(${I})`:r0.nil)}}Ab.checkDataType=tP;function aP($,I,U,Y){if($.length===1)return tP($[0],I,U,Y);let J,Q=(0,Fb.toHash)($);if(Q.array&&Q.object){let K=r0._`typeof ${I} != "object"`;J=Q.null?K:r0._`!${I} || ${K}`,delete Q.null,delete Q.array,delete Q.object}else J=r0.nil;if(Q.number)delete Q.integer;for(let K in Q)J=(0,r0.and)(J,tP(K,I,U,Y));return J}Ab.checkDataTypes=aP;var Dz0={message:({schema:$})=>`must be ${$}`,params:({schema:$,schemaValue:I})=>typeof $=="string"?r0._`{type: ${$}}`:r0._`{type: ${I}}`};function sP($){let I=Oz0($);(0,Wz0.reportError)(I,Dz0)}Ab.reportTypeError=sP;function Oz0($){let{gen:I,data:U,schema:Y}=$,J=(0,Fb.schemaRefOrVal)($,Y,"type");return{gen:I,keyword:"type",data:U,schema:Y.type,schemaCode:J,schemaValue:J,parentSchema:Y,params:{},it:$}}});var Rb=N((Eb)=>{Object.defineProperty(Eb,"__esModule",{value:!0});Eb.assignDefaults=void 0;var sI=t0(),Tz0=V1();function Ez0($,I){let{properties:U,items:Y}=$.schema;if(I==="object"&&U)for(let J in U)Tb($,J,U[J].default);else if(I==="array"&&Array.isArray(Y))Y.forEach((J,Q)=>Tb($,Q,J.default))}Eb.assignDefaults=Ez0;function Tb($,I,U){let{gen:Y,compositeRule:J,data:Q,opts:K}=$;if(U===void 0)return;let q=sI._`${Q}${(0,sI.getProperty)(I)}`;if(J){(0,Tz0.checkStrictMode)($,`default is ignored for: ${q}`);return}let G=sI._`${q} === undefined`;if(K.useDefaults==="empty")G=sI._`${G} || ${q} === null || ${q} === ""`;Y.if(G,sI._`${q} = ${(0,sI.stringify)(U)}`)}});var O$=N((jb)=>{Object.defineProperty(jb,"__esModule",{value:!0});jb.validateUnion=jb.validateArray=jb.usePattern=jb.callValidateCode=jb.schemaProperties=jb.allSchemaProperties=jb.noPropertyInData=jb.propertyInData=jb.isOwnProperty=jb.hasPropFunc=jb.reportMissingProp=jb.checkMissingProp=jb.checkReportMissingProp=void 0;var m1=t0(),eP=V1(),q9=s8(),Bz0=V1();function Rz0($,I){let{gen:U,data:Y,it:J}=$;U.if(IT(U,Y,I,J.opts.ownProperties),()=>{$.setParams({missingProperty:m1._`${I}`},!0),$.error()})}jb.checkReportMissingProp=Rz0;function vz0({gen:$,data:I,it:{opts:U}},Y,J){return(0,m1.or)(...Y.map((Q)=>(0,m1.and)(IT($,I,Q,U.ownProperties),m1._`${J} = ${Q}`)))}jb.checkMissingProp=vz0;function Cz0($,I){$.setParams({missingProperty:I},!0),$.error()}jb.reportMissingProp=Cz0;function vb($){return $.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:m1._`Object.prototype.hasOwnProperty`})}jb.hasPropFunc=vb;function $T($,I,U){return m1._`${vb($)}.call(${I}, ${U})`}jb.isOwnProperty=$T;function jz0($,I,U,Y){let J=m1._`${I}${(0,m1.getProperty)(U)} !== undefined`;return Y?m1._`${J} && ${$T($,I,U)}`:J}jb.propertyInData=jz0;function IT($,I,U,Y){let J=m1._`${I}${(0,m1.getProperty)(U)} === undefined`;return Y?(0,m1.or)(J,(0,m1.not)($T($,I,U))):J}jb.noPropertyInData=IT;function Cb($){return $?Object.keys($).filter((I)=>I!=="__proto__"):[]}jb.allSchemaProperties=Cb;function _z0($,I){return Cb(I).filter((U)=>!(0,eP.alwaysValidSchema)($,I[U]))}jb.schemaProperties=_z0;function Sz0({schemaCode:$,data:I,it:{gen:U,topSchemaRef:Y,schemaPath:J,errorPath:Q},it:K},q,G,H){let W=H?m1._`${$}, ${I}, ${Y}${J}`:I,V=[[q9.default.instancePath,(0,m1.strConcat)(q9.default.instancePath,Q)],[q9.default.parentData,K.parentData],[q9.default.parentDataProperty,K.parentDataProperty],[q9.default.rootData,q9.default.rootData]];if(K.opts.dynamicRef)V.push([q9.default.dynamicAnchors,q9.default.dynamicAnchors]);let X=m1._`${W}, ${U.object(...V)}`;return G!==m1.nil?m1._`${q}.call(${G}, ${X})`:m1._`${q}(${X})`}jb.callValidateCode=Sz0;var gz0=m1._`new RegExp`;function yz0({gen:$,it:{opts:I}},U){let Y=I.unicodeRegExp?"u":"",{regExp:J}=I.code,Q=J(U,Y);return $.scopeValue("pattern",{key:Q.toString(),ref:Q,code:m1._`${J.code==="new RegExp"?gz0:(0,Bz0.useFunc)($,J)}(${U}, ${Y})`})}jb.usePattern=yz0;function hz0($){let{gen:I,data:U,keyword:Y,it:J}=$,Q=I.name("valid");if(J.allErrors){let q=I.let("valid",!0);return K(()=>I.assign(q,!1)),q}return I.var(Q,!0),K(()=>I.break()),Q;function K(q){let G=I.const("len",m1._`${U}.length`);I.forRange("i",0,G,(H)=>{$.subschema({keyword:Y,dataProp:H,dataPropType:eP.Type.Num},Q),I.if((0,m1.not)(Q),q)})}}jb.validateArray=hz0;function xz0($){let{gen:I,schema:U,keyword:Y,it:J}=$;if(!Array.isArray(U))throw Error("ajv implementation error");if(U.some((G)=>(0,eP.alwaysValidSchema)(J,G))&&!J.opts.unevaluated)return;le Line truncated
missingProperty: ${Y},
depsCount: ${I},
deps: ${U}}`};var IB0={keyword:"dependencies",type:"object",schemaType:"object",error:lp.error,code($){let[I,U]=UB0($);dp($,I),mp($,U)}};function UB0({schema:$}){let I={},U={};for(let Y in $){if(Y==="__proto__")continue;let J=Array.isArray($[Y])?I:U;J[Y]=$[Y]}return[I,U]}function dp($,I=$.schema){let{gen:U,data:Y,it:J}=$;if(Object.keys(I).length===0)return;let Q=U.let("missing");for(let K in I){let q=I[K];if(q.length===0)continue;let G=(0,oQ.propertyInData)(U,Y,K,J.opts.ownProperties);if($.setParams({property:K,depsCount:q.length,deps:q.join(", ")}),J.allErrors)U.if(G,()=>{for(let H of q)(0,oQ.checkReportMissingProp)($,H)});else U.if(TT._`${G} && (${(0,oQ.checkMissingProp)($,q,Q)})`),(0,oQ.reportMissingProp)($,Q),U.else()}}lp.validatePropertyDeps=dp;function mp($,I=$.schema){let{gen:U,data:Y,keyword:J,it:Q}=$,K=U.name("valid");for(let q in I){if((0,$B0.alwaysValidSchema)(Q,I[q]))continue;U.if((0,oQ.propertyInData)(U,Y,q,Q.opts.ownProperties),()=>{let G=$.subschema({keyword:J,schemaProp:q},K);$.mergeValidEvaluated(G,K)},()=>U.var(K,!0)),$.ok(K)}}lp.validateSchemaDeps=mp;lp.default=IB0});var ep=N((sp)=>{Object.defineProperty(sp,"__esModule",{value:!0});var ap=t0(),QB0=V1(),KB0={message:"property name must be valid",params:({params:$})=>ap._`{propertyName: ${$.propertyName}}`},qB0={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:KB0,code($){let{gen:I,schema:U,data:Y,it:J}=$;if((0,QB0.alwaysValidSchema)(J,U))return;let Q=I.name("valid");I.forIn("key",Y,(K)=>{$.setParams({propertyName:K}),$.subschema({keyword:"propertyNames",data:K,dataTypes:["string"],propertyName:K,compositeRule:!0},Q),I.if((0,ap.not)(Q),()=>{if($.error(!0),!J.allErrors)I.break()})}),$.ok(Q)}};sp.default=qB0});var ET=N(($n)=>{Object.defineProperty($n,"__esModule",{value:!0});var $V=O$(),n$=t0(),HB0=s8(),IV=V1(),WB0={message:"must NOT have additional properties",params:({params:$})=>n$._`{additionalProperty: ${$.additionalProperty}}`},VB0={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:WB0,code($){let{gen:I,schema:U,parentSchema:Y,data:J,errsCount:Q,it:K}=$;if(!Q)throw Error("ajv implementation error");let{allErrors:q,opts:G}=K;if(K.props=!0,G.removeAdditional!=="all"&&(0,IV.alwaysValidSchema)(K,U))return;let H=(0,$V.allSchemaProperties)(Y.properties),W=(0,$V.allSchemaProperties)(Y.patternProperties);V(),$.ok(n$._`${Q} === ${HB0.default.errors}`);function V(){I.forIn("key",J,(O)=>{if(!H.length&&!W.length)w(O);else I.if(X(O),()=>w(O))})}function X(O){let F;if(H.length>8){let E=(0,IV.schemaRefOrVal)(K,Y.properties,"properties");F=(0,$V.isOwnProperty)(I,E,O)}else if(H.length)F=(0,n$.or)(...H.map((E)=>n$._`${O} === ${E}`));else F=n$.nil;if(W.length)F=(0,n$.or)(F,...W.map((E)=>n$._`${(0,$V.usePattern)($,E)}.test(${O})`));return(0,n$.not)(F)}function Z(O){I.code(n$._`delete ${J}[${O}]`)}function w(O){if(G.removeAdditional==="all"||G.removeAdditional&&U===!1){Z(O);return}if(U===!1){if($.setParams({additionalProperty:O}),$.error(),!q)I.break();return}if(typeof U=="object"&&!(0,IV.alwaysValidSchema)(K,U)){let F=I.name("valid");if(G.removeAdditional==="failing")D(O,F,!1),I.if((0,n$.not)(F),()=>{$.reset(),Z(O)});else if(D(O,F),!q)I.if((0,n$.not)(F),()=>I.break())}}function D(O,F,E){let A={keyword:"additionalProperties",dataProp:O,dataPropType:IV.Type.Str};if(E===!1)Object.assign(A,{compositeRule:!0,createErrors:!1,allErrors:!1});$.subschema(A,F)}}};$n.default=VB0});var Jn=N((Yn)=>{Object.defineProperty(Yn,"__esModule",{value:!0});var XB0=xQ(),In=O$(),BT=V1(),Un=ET(),LB0={keyword:"properties",type:"object",schemaType:"object",code($){let{gen:I,schema:U,parentSchema:Y,data:J,it:Q}=$;if(Q.opts.removeAdditional==="all"&&Y.additionalProperties===void 0)Un.default.code(new XB0.KeywordCxt(Q,Un.default,"additionalProperties"));let K=(0,In.allSchemaProperties)(U);for(let V of K)Q.definedProperties.add(V);if(Q.opts.unevaluated&&K.length&&Q.props!==!0)Q.props=BT.mergeEvaluated.props(I,(0,BT.toHash)(K),Q.props);let q=K.filter((V)=>!(0,BT.alwaysValidSchema)(Q,U[V]));if(q.length===0)return;let G=I.name("valid");for(let V of q){if(H(V))W(V);else{if(I.if((0,In.propertyInData)(I,J,V,Q.opts.ownProperties)),W(V),!Q.allErrors)I.else().var(G,!0);I.endIf()}$.it.definedProperties.add(V),$.ok(G)}function H(V){return Q.opts.useDefaults&&!Q.compositeRule&&U[V].default!==void 0}function W(V){$.subschema({keyword:"properties",schemaProp:V,dataProp:V},G)}}};Yn.default=LB0});var Hn=N((Gn)=>{Object.defineProperty(Gn,"__esModule",{value:!0});var Qn=O$(),UV=t0(),Kn=V1(),qn=V1(),DB0={keyword:"patternProperties",type:"object",schemaType:"object",code($){let{gen:I,schema:U,data:Y,parentSchema:J,it:Q}=$,{opts:K}=Q,q=(0,Qn.allSchemaProperties)(U),G=q.filter((D)=>(0,Kn.alwaysValidSchema)(Q,U[D]));if(q.length===0||G.length===q.length&&(!Q.opts.unevaluated||Q.props===!0))return;let H=K.strictSchema&&!K.allowMatchingProperties&&J.properties,W=I.name("valid");if(Q.props!==!0&&!(Q.props instanceo Line truncated
\x00`,p+=n1(b,2),p+=q.magic,p+=n1(O,2),p+=n1(F,2),p+=n1(g.crc32,4),p+=n1(g.compressedSize,4),p+=n1(g.uncompressedSize,4),p+=n1(H.length,2),p+=n1(E.length,2);var S=RZ.LOCAL_FILE_HEADER+p+H+E,f=RZ.CENTRAL_FILE_HEADER+n1(n,2)+p+n1(X.length,2)+"\x00\x00\x00\x00"+n1(C,4)+n1(Y,4)+H+E+X;return{fileRecord:S,dirRecord:f}},bh0=function($,I,U,Y,J){var Q="",K=kU.transformTo("string",J(Y));return Q=RZ.CENTRAL_DIRECTORY_END+"\x00\x00\x00\x00"+n1($,2)+n1($,2)+n1(I,4)+n1(U,4)+n1(K.length,2)+K,Q},ih0=function($){var I="";return I=RZ.DATA_DESCRIPTOR+n1($.crc32,4)+n1($.compressedSize,4)+n1($.uncompressedSize,4),I};function t$($,I,U,Y){uU.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=I,this.zipPlatform=U,this.encodeFileName=Y,this.streamFiles=$,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}kU.inherits(t$,uU);t$.prototype.push=function($){var I=$.meta.percent||0,U=this.entriesCount,Y=this._sources.length;if(this.accumulate)this.contentBuffer.push($);else this.bytesWritten+=$.data.length,uU.prototype.push.call(this,{data:$.data,meta:{currentFile:this.currentFile,percent:U?(I+100*(U-Y-1))/U:100}})};t$.prototype.openedSource=function($){this.currentSourceOffset=this.bytesWritten,this.currentFile=$.file.name;var I=this.streamFiles&&!$.file.dir;if(I){var U=xt($,I,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:U.fileRecord,meta:{percent:0}})}else this.accumulate=!0};t$.prototype.closedSource=function($){this.accumulate=!1;var I=this.streamFiles&&!$.file.dir,U=xt($,I,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(U.dirRecord),I)this.push({data:ih0($),meta:{percent:100}});else{this.push({data:U.fileRecord,meta:{percent:0}});while(this.contentBuffer.length)this.push(this.contentBuffer.shift())}this.currentFile=null};t$.prototype.flush=function(){var $=this.bytesWritten;for(var I=0;I<this.dirRecords.length;I++)this.push({data:this.dirRecords[I],meta:{percent:100}});var U=this.bytesWritten-$,Y=bh0(this.dirRecords.length,U,$,this.zipComment,this.encodeFileName);this.push({data:Y,meta:{percent:100}})};t$.prototype.prepareNextSource=function(){if(this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused)this.previous.pause();else this.previous.resume()};t$.prototype.registerPrevious=function($){this._sources.push($);var I=this;return $.on("data",function(U){I.processChunk(U)}),$.on("end",function(){if(I.closedSource(I.previous.streamInfo),I._sources.length)I.prepareNextSource();else I.end()}),$.on("error",function(U){I.error(U)}),this};t$.prototype.resume=function(){if(!uU.prototype.resume.call(this))return!1;if(!this.previous&&this._sources.length)return this.prepareNextSource(),!0;if(!this.previous&&!this._sources.length&&!this.generatedError)return this.end(),!0};t$.prototype.error=function($){var I=this._sources;if(!uU.prototype.error.call(this,$))return!1;for(var U=0;U<I.length;U++)try{I[U].error($)}catch(Y){}return!0};t$.prototype.lock=function(){uU.prototype.lock.call(this);var $=this._sources;for(var I=0;I<$.length;I++)$[I].lock()};kt.exports=t$});var ft=N((dh0)=>{var ph0=YR(),nh0=ut(),ch0=function($,I){var U=$||I,Y=ph0[U];if(!Y)throw Error(U+" is not a valid compression method !");return Y};dh0.generateWorker=function($,I,U){var Y=new nh0(I.streamFiles,U,I.platform,I.encodeFileName),J=0;try{$.forEach(function(Q,K){J++;var q=ch0(K.options.compression,I.compression),G=K.options.compressionOptions||I.compressionOptions||{},H=K.dir,W=K.date;K._compressWorker(q,G).withStreamInfo("file",{name:Q,dir:H,date:W,comment:K.comment||"",unixPermissions:K.unixPermissions,dosPermissions:K.dosPermissions}).pipe(Y)}),Y.entriesCount=J}catch(Q){Y.error(Q)}return Y}});var it=N((zz1,bt)=>{var lh0=H4(),vZ=U$();function l2($,I){vZ.call(this,"Nodejs stream input adapter for "+$),this._upstreamEnded=!1,this._bindStream(I)}lh0.inherits(l2,vZ);l2.prototype._bindStream=function($){var I=this;this._stream=$,$.pause(),$.on("data",function(U){I.push({data:U,meta:{percent:0}})}).on("error",function(U){if(I.isPaused)this.generatedError=U;else I.error(U)}).on("end",function(){if(I.isPaused)I._upstreamEnded=!0;else I.end()})};l2.prototype.pause=function(){if(!vZ.prototype.pause.call(this))return!1;return this._stream.pause(),!0};l2.prototype.resume=function(){if(!vZ.prototype.resume.call(this))return!1;if(this._upstreamEnded)this.end();else this._stream.resume();return!0};bt.exports=l2});var at=N((Az1,tt)=>{var oh0=RU(),o2=H4(),dt=U$(),rh0=HB(),mt=WB(),pt=HZ(),th0=po(),ah0=ft(),nt=B2(),sh0=it(),lt=function($,I,U){var Y=o2.getTypeOf(I),J,Q=o2.extend(U||{},mt);if(Q.date=Q.date||new Date,Q.compression!==null)Q.compression=Q.compression.toUpperCase();if(typeof Q.unixPermissions==="string")Q.unixPermissions=parseInt(Q.unixPermissions,8);if(Q.unixPermissions&&Q.unixPermissions&16384)Q.dir=!0;if(Q.dosPermissions&&Q.dosPermissions&16)Q.dir=!0;if(Q. Line truncated
`)}openNode($,I){let U=this.tos,Y=this._xml;if(U&&this.open)Y.push(">");this._stack.push($),Y.push("<"),Y.push($),iR(Y,I),this.leaf=!0,this.open=!0}addAttribute($,I){if(!this.open)throw Error("Cannot write attributes to node if it is not open");if(I!==void 0)is(this._xml,$,I)}addAttributes($){if(!this.open)throw Error("Cannot write attributes to node if it is not open");iR(this._xml,$)}writeText($){let I=this._xml;if(this.open)I.push(">"),this.open=!1;this.leaf=!1,I.push(bs.xmlEncode($.toString()))}writeXml($){if(this.open)this._xml.push(">"),this.open=!1;this.leaf=!1,this._xml.push($)}closeNode(){let $=this._stack.pop(),I=this._xml;if(this.leaf)I.push("/>");else I.push("</"),I.push($),I.push(">");this.open=!1,this.leaf=!1}leafNode($,I,U){if(this.openNode($,I),U!==void 0)this.writeText(U);this.closeNode()}closeAll(){while(this._stack.length)this.closeNode()}addRollback(){return this._rollbacks.push({xml:this._xml.length,stack:this._stack.length,leaf:this.leaf,open:this.open}),this.cursor}commit(){this._rollbacks.pop()}rollback(){let $=this._rollbacks.pop();if(this._xml.length>$.xml)this._xml.splice($.xml,this._xml.length-$.xml);if(this._stack.length>$.stack)this._stack.splice($.stack,this._stack.length-$.stack);this.leaf=$.leaf,this.open=$.open}get xml(){return this.closeAll(),this._xml.join("")}}pR.StdDocAttributes={version:"1.0",encoding:"UTF-8",standalone:"yes"};ps.exports=pR});var nR=N((nu0)=>{var ns=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");function pu0($){if(typeof $==="string")return $;if(ns)return ns.decode($);return $.toString()}nu0.bufferToString=pu0});var os=N((ds)=>{Object.defineProperty(ds,"__esModule",{value:!0});ds.CHAR=`
\r -퟿-�\uD800\uDC00-\uDBFF\uDFFF`;ds.S=` \r
`;ds.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";ds.NAME_CHAR="-"+ds.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";ds.CHAR_RE=new RegExp("^["+ds.CHAR+"]$","u");ds.S_RE=new RegExp("^["+ds.S+"]+$","u");ds.NAME_START_CHAR_RE=new RegExp("^["+ds.NAME_START_CHAR+"]$","u");ds.NAME_CHAR_RE=new RegExp("^["+ds.NAME_CHAR+"]$","u");ds.NAME_RE=new RegExp("^["+ds.NAME_START_CHAR+"]["+ds.NAME_CHAR+"]*$","u");ds.NMTOKEN_RE=new RegExp("^["+ds.NAME_CHAR+"]+$","u");var cR=9,dR=10,mR=13,lR=32;ds.S_LIST=[lR,dR,mR,cR];function du0($){return $>=lR&&$<=55295||$===dR||$===mR||$===cR||$>=57344&&$<=65533||$>=65536&&$<=1114111}ds.isChar=du0;function mu0($){return $===lR||$===dR||$===mR||$===cR}ds.isS=mu0;function cs($){return $>=65&&$<=90||$>=97&&$<=122||$===58||$===95||$===8204||$===8205||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}ds.isNameStartChar=cs;function lu0($){return cs($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}ds.isNameChar=lu0});var Je=N(($e)=>{Object.defineProperty($e,"__esModule",{value:!0});$e.CHAR="\x01-퟿-�\uD800\uDC00-\uDBFF\uDFFF";$e.RESTRICTED_CHAR="\x01-\b\v\f\x0E-\x1F-„†-Ÿ";$e.S=` \r
`;$e.NAME_START_CHAR=":A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";$e.NAME_CHAR="-"+$e.NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";$e.CHAR_RE=new RegExp("^["+$e.CHAR+"]$","u");$e.RESTRICTED_CHAR_RE=new RegExp("^["+$e.RESTRICTED_CHAR+"]$","u");$e.S_RE=new RegExp("^["+$e.S+"]+$","u");$e.NAME_START_CHAR_RE=new RegExp("^["+$e.NAME_START_CHAR+"]$","u");$e.NAME_CHAR_RE=new RegExp("^["+$e.NAME_CHAR+"]$","u");$e.NAME_RE=new RegExp("^["+$e.NAME_START_CHAR+"]["+$e.NAME_CHAR+"]*$","u");$e.NMTOKEN_RE=new RegExp("^["+$e.NAME_CHAR+"]+$","u");var rs=9,ts=10,as=13,ss=32;$e.S_LIST=[ss,ts,as,rs];function Qf0($){return $>=1&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}$e.isChar=Qf0;function Kf0($){return $>=1&&$<=8||$===11||$===12||$>=14&&$<=31||$>=127&&$<=132||$>=134&&$<=159}$e.isRestrictedChar=Kf0;function qf0($){return $===9||$===10||$===13||$>31&&$<127||$===133||$>159&&$<=55295||$>=57344&&$<=65533||$>=65536&&$<=1114111}$e.isCharAndNotRestricted=qf0;function Gf0($){return $===ss||$===ts||$===as||$===rs}$e.isS=Gf0;function es($){return $>=65&&$<=90||$>=97&&$<=122||$===58||$===95||$===8204||$===8205||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}$e.isNameStartChar=es;function Hf0($){return es($)||$>=48&&$<=57||$===45||$===46||$===183||$>=768&&$<=879||$>=8255&&$<=8256}$e.isNameChar=Hf0});var qe=N((Ke)=>{Object.defineProperty(Ke,"__esModule",{value:!0});Ke.NC_NAME_START_CHAR="A-Z_a-zÀ-ÖØ-öø-˿Ͱ-ͽͿ-῿‌-‍⁰-↏Ⰰ-⿯、-퟿豈-﷏ﷰ-�\uD800\uDC00-\uDB7F\uDFFF";Ke.NC_NAME_CHAR="-"+Ke.NC_NAME_START_CHAR+".0-9·̀-ͯ‿-⁀";Ke.NC_NAME_START_CHAR_RE=new RegExp("^["+Ke.NC_NAME_START_CHAR+"]$","u");Ke.NC_NAME_CHAR_RE=new RegExp("^["+Ke.NC_NAME_CHAR+"]$","u");Ke.NC_NAME_RE=new RegExp("^["+Ke.NC_NAME_START_CHAR+"]["+Ke.NC_NAME_CHAR+"]*$","u");function Qe($){return $>=65&&$<=90||$===95||$>=97&&$<=122||$>=192&&$<=214||$>=216&&$<=246||$>=248&&$<=767||$>=880&&$<=893||$>=895&&$<=8191||$>=8204&&$<=8205||$>=8304&&$<=8591||$>=11264&&$<=12271||$>=12289&&$<=55295||$>=63744&&$<=64975||$>=65008&&$<=65533||$>=65536&&$<=983039}Ke.isNCNameStartChar=Qe;function Tf0($){return Qe($)||($===45||$===46||$>=48&&$<=57||$===183||$>=768&&$<=879||$>=8255&&$<=8256)}Ke.isNCNameChar=Tf0});var Ce=N((ve)=>{Object.defineProperty(ve,"__esModule",{value:!0});var rU=os(),jf0=Je(),qv=qe(),n6=rU.isS,_f0=rU.isChar,qK=rU.isNameStartChar,Ge=rU.isNameChar,Ae=rU.S_LIST,Sf0=rU.NAME_RE,gf0=jf0.isChar,yf0=qv.isNCNameStartChar,hf0=qv.isNCNameChar,xf0=qv.NC_NAME_RE,YX="http://www.w3.org/XML/1998/namespace",oU="http://www.w3.org/2000/xmlns/",kf0={__proto__:null,xml:YX,xmlns:oU},uf0={__proto__:null,amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},J4=-1,R8=-2,He=0,ff0=1,rR=2,bf0=3,dU=4,if0=5,pf0=6,nf0=7,tR=8,cf0=9,df0=10,mf0=11,lf0=12,v6=13,sZ=14,aR=15,of0=16,sR=17,rf0=18,tf0=19,eR=20,af0=21,sf0=22,ef0=23,We=24,$v=25,eZ=26,Ve=27,$b0=28,Ib0=29,Ze=30,Ub0=31,Yb0=32,$3=33,Jb0=34,Iv=35,GK=36,Uv=37,Qb0=38,Xe=39,Le=40,Kb0=41,we=42,qb0=43,Gb0=44,Yv=9,s$=10,Jv=13,De=32,Oe=33,Pe=34,HK=38,Te=39,$X=45,IX=47,Hb0=59,C9=60,mU=61,g4=62,I6=63,Ee=91,lU=93,Ne=133,Fe=8232,UX=($)=>$===Pe||$===Te,Be=[Pe,Te],Wb0=[...Be,Ee,g4],Vb0=[...Be,C9,lU],Zb0=[mU,I6,...Ae],Xb0=[...Ae,g4,HK,C9];function Kv($,I,U){switch(I){case"xml":if(U!==YX)$.fail(`xml prefix must be bound to ${YX}.`);break;case"xmlns":if(U!==oU)$.fail(`xmlns prefix must be bound to ${oU}.`);break;default:}switch(U){case oU:$.fail(I===""?`the default namespace may not be set to ${U}.`:`may not assign a prefix (even "xmlns") to the URI ${oU}.`);break;case YX:switch(I){case"xml":break;case"":$.fail(`the default namespace may not be set to ${U}.`);break;default:$.fail("may not assign the xml namespace to another prefix.")}break;default:}}function Lb0($,I){for(let U of Object.keys(I))Kv($,U,I[U])}var wb0=($)=>xf0.test($),Db0=($)=>Sf0.test($),I3=0,Me=1,Qv=2;ve.EVENTS=["xmldecl","text","processinginstruction","doctype","comment","opentagstart","attribute","opentag","closetag","cdata","error","end","ready"];var ze={xmldecl:"xmldeclHandler",text:"textHandler",processinginstruction:"piHandler",doctype:"doctypeHandler",comment:"commentHandler",opentagstart:"openTagStartHandler",attribute:"attributeHandler",opentag:"openTagHandler",closetag:"closeTagHandler",cdata:"cdataHandler",error:"errorHandler",end:"endHandler",ready:"readyHandler"};class Re{constructor($){this.opt=$!==null&&$!==void 0?$:{},this.fragmentOpt=!!this.opt.fragment;let I=this.xmlnsOpt=!!this.opt.xmlns;if(this.trackPosition=this.opt.position!==!1,this.fileName=this.opt.fileName,I){this.nameStartCheck=yf0,this.nameCheck=hf0,this.isName=wb0,this.processAttribs=this.processAttribsNS,this.pushAttrib=this.pushAttribNS,this.ns=Object.assign({__proto__:null},kf0);let U=this.opt.additionalNamespaces;if(U!=null)Lb0(this,U),Object.assign(this.ns,U)}else this.nameStartCheck=qK,this.nameChec Line truncated
`,I=this.i}}captureToChar($){let{i:I}=this,{chunk:U}=this;while(!0){let Y=this.getCode();switch(Y){case R8:this.text+=`${U.slice(I,this.prevI)}
`,I=this.i,Y=s$;break;case J4:return this.text+=U.slice(I),!1;default:}if(Y===$)return this.text+=U.slice(I,this.prevI),!0}}captureNameChars(){let{chunk:$,i:I}=this;while(!0){let U=this.getCode();if(U===J4)return this.name+=$.slice(I),J4;if(!Ge(U))return this.name+=$.slice(I,this.prevI),U===R8?s$:U}}skipSpaces(){while(!0){let $=this.getCodeNorm();if($===J4||!n6($))return $}}setXMLVersion($){if(this.currentXMLVersion=$,$==="1.0")this.isChar=_f0,this.getCode=this.getCode10;else this.isChar=gf0,this.getCode=this.getCode11}sBegin(){if(this.chunk.charCodeAt(0)===65279)this.i++,this.column++;this.state=ff0}sBeginWhitespace(){let $=this.i,I=this.skipSpaces();if(this.prevI!==$)this.xmlDeclPossible=!1;switch(I){case C9:if(this.state=aR,this.text.length!==0)throw Error("no-empty text at start");break;case J4:break;default:this.unget(),this.state=v6,this.xmlDeclPossible=!1}}sDoctype(){var $;let I=this.captureTo(Wb0);switch(I){case g4:{($=this.doctypeHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=v6,this.doctype=!0;break}case J4:break;default:if(this.text+=String.fromCodePoint(I),I===Ee)this.state=dU;else if(UX(I))this.state=bf0,this.q=I}}sDoctypeQuote(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.q=null,this.state=rR}sDTD(){let $=this.captureTo(Vb0);if($===J4)return;if(this.text+=String.fromCodePoint($),$===lU)this.state=rR;else if($===C9)this.state=pf0;else if(UX($))this.state=if0,this.q=$}sDTDQuoted(){let $=this.q;if(this.captureToChar($))this.text+=String.fromCodePoint($),this.state=dU,this.q=null}sDTDOpenWaka(){let $=this.getCodeNorm();switch(this.text+=String.fromCodePoint($),$){case Oe:this.state=nf0,this.openWakaBang="";break;case I6:this.state=mf0;break;default:this.state=dU}}sDTDOpenWakaBang(){let $=String.fromCodePoint(this.getCodeNorm()),I=this.openWakaBang+=$;if(this.text+=$,I!=="-")this.state=I==="--"?tR:dU,this.openWakaBang=""}sDTDComment(){if(this.captureToChar($X))this.text+="-",this.state=cf0}sDTDCommentEnding(){let $=this.getCodeNorm();this.text+=String.fromCodePoint($),this.state=$===$X?df0:tR}sDTDCommentEnded(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===g4)this.state=dU;else this.fail("malformed comment."),this.state=tR}sDTDPI(){if(this.captureToChar(I6))this.text+="?",this.state=lf0}sDTDPIEnding(){let $=this.getCodeNorm();if(this.text+=String.fromCodePoint($),$===g4)this.state=dU}sText(){if(this.tags.length!==0)this.handleTextInRoot();else this.handleTextOutsideRoot()}sEntity(){let{i:$}=this,{chunk:I}=this;$:while(!0)switch(this.getCode()){case R8:this.entity+=`${I.slice($,this.prevI)}
`,$=this.i;break;case Hb0:{let{entityReturnState:U}=this,Y=this.entity+I.slice($,this.prevI);this.state=U;let J;if(Y==="")this.fail("empty entity name."),J="&;";else J=this.parseEntity(Y),this.entity="";if(U!==v6||this.textHandler!==void 0)this.text+=J;break $}case J4:this.entity+=I.slice($);break $;default:}}sOpenWaka(){let $=this.getCode();if(qK($))this.state=Jb0,this.unget(),this.xmlDeclPossible=!1;else switch($){case IX:this.state=qb0,this.xmlDeclPossible=!1;break;case Oe:this.state=of0,this.openWakaBang="",this.xmlDeclPossible=!1;break;case I6:this.state=ef0;break;default:this.fail("disallowed character in tag name"),this.state=v6,this.xmlDeclPossible=!1}}sOpenWakaBang(){switch(this.openWakaBang+=String.fromCodePoint(this.getCodeNorm()),this.openWakaBang){case"[CDATA[":if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0;this.state=eR,this.openWakaBang="";break;case"--":this.state=sR,this.openWakaBang="";break;case"DOCTYPE":if(this.state=rR,this.doctype||this.sawRoot)this.fail("inappropriately located doctype declaration.");this.openWakaBang="";break;default:if(this.openWakaBang.length>=7)this.fail("incorrect syntax.")}}sComment(){if(this.captureToChar($X))this.state=rf0}sCommentEnding(){var $;let I=this.getCodeNorm();if(I===$X)this.state=tf0,($=this.commentHandler)===null||$===void 0||$.call(this,this.text),this.text="";else this.text+=`-${String.fromCodePoint(I)}`,this.state=sR}sCommentEnded(){let $=this.getCodeNorm();if($!==g4)this.fail("malformed comment."),this.text+=`--${String.fromCodePoint($)}`,this.state=sR;else this.state=v6}sCData(){if(this.captureToChar(lU))this.state=af0}sCDataEnding(){let $=this.getCodeNorm();if($===lU)this.state=sf0;else this.text+=`]${String.fromCodePoint($)}`,this.state=eR}sCDataEnding2(){var $;let I=this.getCodeNorm();switch(I){case g4:{($=this.cdataHandler)===null||$===void 0||$.call(this,this.text),this.text="",this.state=v6;break}case lU:this.text+="]";break;default:this.text+=`]]${String.fromCodePoint(I)}`,this.state=eR}}sPIFirstChar(){let $=this.getCodeNorm();if(this.nameStartCheck($))this.piTarget+=String.fromCodePoint($),this.state=We;else if($===I6||n6($))this.fail("processing instruction without a target."),this.state=$===I6?eZ:$v;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint($),this.state=We}sPIRest(){let{chunk:$,i:I}=this;while(!0){let U=this.getCodeNorm();if(U===J4){this.piTarget+=$.slice(I);return}if(!this.nameCheck(U)){this.piTarget+=$.slice(I,this.prevI);let Y=U===I6;if(Y||n6(U))if(this.piTarget==="xml"){if(!this.xmlDeclPossible)this.fail("an XML declaration must be at the start of the document.");this.state=Y?$3:Ve}else this.state=Y?eZ:$v;else this.fail("disallowed character in processing instruction name."),this.piTarget+=String.fromCodePoint(U);break}}}sPIBody(){if(this.text.length===0){let $=this.getCodeNorm();if($===I6)this.state=eZ;else if(!n6($))this.text=String.fromCodePoint($)}else if(this.captureToChar(I6))this.state=eZ}sPIEnding(){var $;let I=this.getCodeNorm();if(I===g4){let{piTarget:U}=this;if(U.toLowerCase()==="xml")this.fail("the XML declaration must appear at the start of the document.");($=this.piHandler)===null||$===void 0||$.call(this,{target:U,body:this.text}),this.piTarget=this.text="",this.state=v6}else if(I===I6)this.text+="?";else this.text+=`?${String.fromCodePoint(I)}`,this.state=$v;this.xmlDeclPossible=!1}sXMLDeclNameStart(){let $=this.skipSpaces();if($===I6){this.state=$3;return}if($!==J4)this.state=$b0,this.name=String.fromCodePoint($)}sXMLDeclName(){let $=this.captureTo(Zb0);if($===I6){this.state=$3,this.name+=this.text,this.text="",this.fail("XML declaration is incomplete.");return}if(!(n6($)||$===mU))return;if(this.name+=this.text,this.text="",!this.xmlDeclExpects.includes(this.name))switch(this.name.length){case 0:this.fail("did not expect any more name/value pairs.");break;case 1:this.fail(`expected the name ${this.xmlDeclExpects[0]}.`);break;default:this.fail(`expected one of ${this.xmlDeclExpects.join(", ")}`)}this.state=$===mU?Ze:Ib0}sXMLDeclEq(){let $=this.getCodeNorm();if($===I6){this.state=$3,this.fail("XML declaration is incomplete.");return}if(n6($))return;if($!==mU)this.fail("value required.");this.state=Ze}sXMLDeclValueStart(){let $=this.getCodeNorm();if($===I6){this.state=$3,this.fail("XML declaration is incomplete.");return}if(n6($))return;if(!UX($))this.fail("value must be quoted."),this.q=De;else this.q=$;this.state=Ub0}sXMLDeclValue(){let $=this.captureTo([this.q,I6]);if($===I6){this.state=$3,this.text="",this.fail("XML declaration is incomplete.");return}if($===J4)return;let I=this.text;switch(this.text="",this.name){case"version":{this.xmlDeclExpects=["encoding","standalone"];let U=I;if(this.xmlDecl.version=U,!/^1\.[0-9]+$/.test(U))this.fail("version nu Line truncated
`;$=this.i,I=I3;break;case J4:if(Y!==void 0)this.text+=U.slice($);break $;default:I=I3}this.forbiddenState=I}handleTextOutsideRoot(){let{i:$}=this,{chunk:I,textHandler:U}=this,Y=!1;$:while(!0){let J=this.getCode();switch(J){case C9:{if(this.state=aR,U!==void 0){let{text:Q}=this,K=I.slice($,this.prevI);if(Q.length!==0)U(Q+K),this.text="";else if(K.length!==0)U(K)}break $}case HK:if(this.state=sZ,this.entityReturnState=v6,U!==void 0)this.text+=I.slice($,this.prevI);Y=!0;break $;case R8:if(U!==void 0)this.text+=`${I.slice($,this.prevI)}
`;$=this.i;break;case J4:if(U!==void 0)this.text+=I.slice($);break $;default:if(!n6(J))Y=!0}}if(!Y)return;if(!this.sawRoot&&!this.reportedTextBeforeRoot)this.fail("text data outside of root node."),this.reportedTextBeforeRoot=!0;if(this.closedRoot&&!this.reportedTextAfterRoot)this.fail("text data outside of root node."),this.reportedTextAfterRoot=!0}pushAttribNS($,I){var U;let{prefix:Y,local:J}=this.qname($),Q={name:$,prefix:Y,local:J,value:I};if(this.attribList.push(Q),(U=this.attributeHandler)===null||U===void 0||U.call(this,Q),Y==="xmlns"){let K=I.trim();if(this.currentXMLVersion==="1.0"&&K==="")this.fail("invalid attempt to undefine prefix in XML 1.0");this.topNS[J]=K,Kv(this,J,K)}else if($==="xmlns"){let K=I.trim();this.topNS[""]=K,Kv(this,"",K)}}pushAttribPlain($,I){var U;let Y={name:$,value:I};this.attribList.push(Y),(U=this.attributeHandler)===null||U===void 0||U.call(this,Y)}end(){var $,I;if(!this.sawRoot)this.fail("document must contain a root element.");let{tags:U}=this;while(U.length>0){let J=U.pop();this.fail(`unclosed tag: ${J.name}`)}if(this.state!==He&&this.state!==v6)this.fail("unexpected end.");let{text:Y}=this;if(Y.length!==0)($=this.textHandler)===null||$===void 0||$.call(this,Y),this.text="";return this._closed=!0,(I=this.endHandler)===null||I===void 0||I.call(this),this._init(),this}resolve($){var I,U;let Y=this.topNS[$];if(Y!==void 0)return Y;let{tags:J}=this;for(let Q=J.length-1;Q>=0;Q--)if(Y=J[Q].ns[$],Y!==void 0)return Y;if(Y=this.ns[$],Y!==void 0)return Y;return(U=(I=this.opt).resolvePrefix)===null||U===void 0?void 0:U.call(I,$)}qname($){let I=$.indexOf(":");if(I===-1)return{prefix:"",local:$};let U=$.slice(I+1),Y=$.slice(0,I);if(Y===""||U===""||U.includes(":"))this.fail(`malformed name: ${$}.`);return{prefix:Y,local:U}}processAttribsNS(){var $;let{attribList:I}=this,U=this.tag;{let{prefix:Q,local:K}=this.qname(U.name);U.prefix=Q,U.local=K;let q=U.uri=($=this.resolve(Q))!==null&&$!==void 0?$:"";if(Q!==""){if(Q==="xmlns")this.fail('tags may not have "xmlns" as prefix.');if(q==="")this.fail(`unbound namespace prefix: ${JSON.stringify(Q)}.`),U.uri=Q}}if(I.length===0)return;let{attributes:Y}=U,J=new Set;for(let Q of I){let{name:K,prefix:q,local:G}=Q,H,W;if(q==="")H=K==="xmlns"?oU:"",W=K;else{if(H=this.resolve(q),H===void 0)this.fail(`unbound namespace prefix: ${JSON.stringify(q)}.`),H=q;W=`{${H}}${G}`}if(J.has(W))this.fail(`duplicate attribute: ${W}.`);J.add(W),Q.uri=H,Y[K]=Q}this.attribList=[]}processAttribsPlain(){let{attribList:$}=this,I=this.tag.attributes;for(let{name:U,value:Y}of $){if(I[U]!==void 0)this.fail(`duplicate attribute: ${U}.`);I[U]=Y}this.attribList=[]}openTag(){var $;this.processAttribs();let{tags:I}=this,U=this.tag;U.isSelfClosing=!1,($=this.openTagHandler)===null||$===void 0||$.call(this,U),I.push(U),this.state=v6,this.name=""}openSelfClosingTag(){var $,I,U;this.processAttribs();let{tags:Y}=this,J=this.tag;if(J.isSelfClosing=!0,($=this.openTagHandler)===null||$===void 0||$.call(this,J),(I=this.closeTagHandler)===null||I===void 0||I.call(this,J),(this.tag=(U=Y[Y.length-1])!==null&&U!==void 0?U:null)===null)this.closedRoot=!0;this.state=v6,this.name=""}closeTag(){let{tags:$,name:I}=this;if(this.state=v6,this.name="",I===""){this.fail("weird empty close tag."),this.text+="</>";return}let U=this.closeTagHandler,Y=$.length;while(Y-- >0){let J=this.tag=$.pop();if(this.topNS=J.ns,U===null||U===void 0||U(J),J.name===I)break;this.fail("unexpected close tag.")}if(Y===0)this.closedRoot=!0;else if(Y<0)this.fail(`unmatched closing tag: ${I}.`),this.text+=`</${I}>`}parseEntity($){if($[0]!=="#"){let U=this.ENTITIES[$];if(U!==void 0)return U;return this.fail(this.isName($)?"undefined entity.":"disallowed character in entity name."),`&${$};`}let I=NaN;if($[1]==="x"&&/^#x[0-9a-f]+$/i.test($))I=parseInt($.slice(2),16);else if(/^#[0-9]+$/.test($))I=parseInt($.slice(1),10);if(!this.isChar(I))return this.fail("malformed character entity."),`&${$};`;return String.fromCodePoint(I)}}ve.SaxesParser=Re});var WK=N((QA1,je)=>{var{SaxesParser:Fb0}=Ce(),{PassThrough:Mb0}=L6(),{bufferToString:zb0}=nR();je.exports=async function*($){if($.pipe&&!$[Symbol.asyncIterator])$=$.pipe(new Mb0);let I=new Fb0,U;I.on("error",(J)=>{U=J});let Y=[];I.on("opentag",(J)=>Y.push({eventType:"opentag",value:J})),I.on("text",(J)=>Y.push({eventType:"text",value:J})),I.on("closetag",(J)=>Y.push({eventType:"closetag",value:J}));for await(let J of $){if(I.write(zb0(J)),U)throw U;yield Y,Y=[]}}});var L0=N((KA1,_e)=>{var Ab0=WK(),Pb0=$6();class tU{prepare(){}render(){}parseOpen($){}parseText($){}parseClose($){}reconcile($,I){}reset(){if(this.model=null,this.map)Object.values(this.map).forEach(($)=>{if($ instanceof tU)$.reset();else if($.xform)$.xform.reset()})}mergeModel($){this.model=Object.assign(this.model||{},$)}async parse($){for await(let I of $)for(let{eventType:U,value:Y}of I)if(U==="opentag")this.parseOpen(Y);else if(U==="text")this.parseText(Y);else if(U==="closetag"){if(!this.parseClose(Y.name))return this.modeLine truncated
<a:theme xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" name="Office Theme"> <a:themeElements> <a:clrScheme name="Office"> <a:dk1> <a:sysClr val="windowText" lastClr="000000"/> </a:dk1> <a:lt1> <a:sysClr val="window" lastClr="FFFFFF"/> </a:lt1> <a:dk2> <a:srgbClr val="1F497D"/> </a:dk2> <a:lt2> <a:srgbClr val="EEECE1"/> </a:lt2> <a:accent1> <a:srgbClr val="4F81BD"/> </a:accent1> <a:accent2> <a:srgbClr val="C0504D"/> </a:accent2> <a:accent3> <a:srgbClr val="9BBB59"/> </a:accent3> <a:accent4> <a:srgbClr val="8064A2"/> </a:accent4> <a:accent5> <a:srgbClr val="4BACC6"/> </a:accent5> <a:accent6> <a:srgbClr val="F79646"/> </a:accent6> <a:hlink> <a:srgbClr val="0000FF"/> </a:hlink> <a:folHlink> <a:srgbClr val="800080"/> </a:folHlink> </a:clrScheme> <a:fontScheme name="Office"> <a:majorFont> <a:latin typeface="Cambria"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Times New Roman"/> <a:font script="Hebr" typeface="Times New Roman"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="MoolBoran"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Times New Roman"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:majorFont> <a:minorFont> <a:latin typeface="Calibri"/> <a:ea typeface=""/> <a:cs typeface=""/> <a:font script="Jpan" typeface="MS Pゴシック"/> <a:font script="Hang" typeface="맑은 고딕"/> <a:font script="Hans" typeface="宋体"/> <a:font script="Hant" typeface="新細明體"/> <a:font script="Arab" typeface="Arial"/> <a:font script="Hebr" typeface="Arial"/> <a:font script="Thai" typeface="Tahoma"/> <a:font script="Ethi" typeface="Nyala"/> <a:font script="Beng" typeface="Vrinda"/> <a:font script="Gujr" typeface="Shruti"/> <a:font script="Khmr" typeface="DaunPenh"/> <a:font script="Knda" typeface="Tunga"/> <a:font script="Guru" typeface="Raavi"/> <a:font script="Cans" typeface="Euphemia"/> <a:font script="Cher" typeface="Plantagenet Cherokee"/> <a:font script="Yiii" typeface="Microsoft Yi Baiti"/> <a:font script="Tibt" typeface="Microsoft Himalaya"/> <a:font script="Thaa" typeface="MV Boli"/> <a:font script="Deva" typeface="Mangal"/> <a:font script="Telu" typeface="Gautami"/> <a:font script="Taml" typeface="Latha"/> <a:font script="Syrc" typeface="Estrangelo Edessa"/> <a:font script="Orya" typeface="Kalinga"/> <a:font script="Mlym" typeface="Kartika"/> <a:font script="Laoo" typeface="DokChampa"/> <a:font script="Sinh" typeface="Iskoola Pota"/> <a:font script="Mong" typeface="Mongolian Baiti"/> <a:font script="Viet" typeface="Arial"/> <a:font script="Uigh" typeface="Microsoft Uighur"/> <a:font script="Geor" typeface="Sylfaen"/> </a:minorFont> </a:fontScheme> <a:fmtScheme name="Office"> <a:fillStyleLst> <a:solidFill> <a:schemeClr val="phClr"/> </a:solidFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="35000"> <a:schemeClr val="phClr"> <a:tint val="37000"/> <a:satMod val="300000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="15000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="1"/> </a:gradFill> <a:gradFill rotWithShape="1"> <a:gsLst> <a:gs pos="0"> <a:schemeClr val="phClr"> <a:tint val="100000"/> <a:shade val="100000"/> <a:satMod val="130000"/> </a:schemeClr> </a:gs> <a:gs pos="100000"> <a:schemeClr val="phClr"> <a:tint val="50000"/> <a:shade val="100000"/> <a:satMod val="350000"/> </a:schemeClr> </a:gs> </a:gsLst> <a:lin ang="16200000" scaled="0"/> </a:gradFill> </a:fillStyleLst> <a:lnStyleLst> <a:ln w="9525" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:schemeClr val="phClr"> <a:shade val="95000"/> <a:satMod val="105000"/> </a:schemeClr> </a:solidFill> <a:prstDash val="solid"/> </a:ln> <a:ln w="25400" cap="flat" cmpd="sng" algn="ctr"> <a:solidFill> <a:Line truncated
`,this.quote='"',this.escape=this.quote,this.quoteColumns=!1,this.quoteHeaders=this.quoteColumns,this.headers=null,this.includeEndRowDelimiter=!1,this.writeBOM=!1,this.BOM="\uFEFF",this.alwaysWriteHeaders=!1,Object.assign(this,$||{}),typeof($===null||$===void 0?void 0:$.quoteHeaders)>"u")this.quoteHeaders=this.quoteColumns;if(($===null||$===void 0?void 0:$.quote)===!0)this.quote='"';else if(($===null||$===void 0?void 0:$.quote)===!1)this.quote="";if(typeof($===null||$===void 0?void 0:$.escape)!=="string")this.escape=this.quote;this.shouldWriteHeaders=!!this.headers&&((I=$.writeHeaders)!==null&&I!==void 0?I:!0),this.headers=Array.isArray(this.headers)?this.headers:null,this.escapedQuote=`${this.escape}${this.quote}`}}q50.FormatterOptions=K50});var xX=N((_T1,Z50)=>{var gm0="[object AsyncFunction]",ym0="[object Function]",hm0="[object GeneratorFunction]",xm0="[object Null]",km0="[object Proxy]",um0="[object Undefined]",fm0=typeof global=="object"&&global&&global.Object===Object&&global,bm0=typeof self=="object"&&self&&self.Object===Object&&self,im0=fm0||bm0||Function("return this")(),W50=Object.prototype,pm0=W50.hasOwnProperty,V50=W50.toString,H50=im0.Symbol,G3=H50?H50.toStringTag:void 0;function nm0($){if($==null)return $===void 0?um0:xm0;return G3&&G3 in Object($)?cm0($):dm0($)}function cm0($){var I=pm0.call($,G3),U=$[G3];try{$[G3]=void 0;var Y=!0}catch(Q){}var J=V50.call($);if(Y)if(I)$[G3]=U;else delete $[G3];return J}function dm0($){return V50.call($)}function mm0($){if(!lm0($))return!1;var I=nm0($);return I==ym0||I==hm0||I==gm0||I==km0}function lm0($){var I=typeof $;return $!=null&&(I=="object"||I=="function")}Z50.exports=mm0});var l50=N((kX,KY)=>{var om0=200,jC="__lodash_hash_undefined__",dX=1,T50=2,E50=9007199254740991,uX="[object Arguments]",PC="[object Array]",rm0="[object AsyncFunction]",B50="[object Boolean]",R50="[object Date]",v50="[object Error]",C50="[object Function]",tm0="[object GeneratorFunction]",fX="[object Map]",j50="[object Number]",am0="[object Null]",QY="[object Object]",X50="[object Promise]",sm0="[object Proxy]",_50="[object RegExp]",bX="[object Set]",S50="[object String]",em0="[object Symbol]",$l0="[object Undefined]",TC="[object WeakMap]",g50="[object ArrayBuffer]",iX="[object DataView]",Il0="[object Float32Array]",Ul0="[object Float64Array]",Yl0="[object Int8Array]",Jl0="[object Int16Array]",Ql0="[object Int32Array]",Kl0="[object Uint8Array]",ql0="[object Uint8ClampedArray]",Gl0="[object Uint16Array]",Hl0="[object Uint32Array]",Wl0=/[\\^$.*+?()[\]{}|]/g,Vl0=/^\[object .+?Constructor\]$/,Zl0=/^(?:0|[1-9]\d*)$/,o1={};o1[Il0]=o1[Ul0]=o1[Yl0]=o1[Jl0]=o1[Ql0]=o1[Kl0]=o1[ql0]=o1[Gl0]=o1[Hl0]=!0;o1[uX]=o1[PC]=o1[g50]=o1[B50]=o1[iX]=o1[R50]=o1[v50]=o1[C50]=o1[fX]=o1[j50]=o1[QY]=o1[_50]=o1[bX]=o1[S50]=o1[TC]=!1;var y50=typeof global=="object"&&global&&global.Object===Object&&global,Xl0=typeof self=="object"&&self&&self.Object===Object&&self,O5=y50||Xl0||Function("return this")(),h50=typeof kX=="object"&&kX&&!kX.nodeType&&kX,L50=h50&&typeof KY=="object"&&KY&&!KY.nodeType&&KY,x50=L50&&L50.exports===h50,MC=x50&&y50.process,w50=function(){try{return MC&&MC.binding&&MC.binding("util")}catch($){}}(),D50=w50&&w50.isTypedArray;function Ll0($,I){var U=-1,Y=$==null?0:$.length,J=0,Q=[];while(++U<Y){var K=$[U];if(I(K,U,$))Q[J++]=K}return Q}function wl0($,I){var U=-1,Y=I.length,J=$.length;while(++U<Y)$[J+U]=I[U];return $}function Dl0($,I){var U=-1,Y=$==null?0:$.length;while(++U<Y)if(I($[U],U,$))return!0;return!1}function Ol0($,I){var U=-1,Y=Array($);while(++U<$)Y[U]=I(U);return Y}function Nl0($){return function(I){return $(I)}}function Fl0($,I){return $.has(I)}function Ml0($,I){return $==null?void 0:$[I]}function zl0($){var I=-1,U=Array($.size);return $.forEach(function(Y,J){U[++I]=[J,Y]}),U}function Al0($,I){return function(U){return $(I(U))}}function Pl0($){var I=-1,U=Array($.size);return $.forEach(function(Y){U[++I]=Y}),U}var Tl0=Array.prototype,El0=Function.prototype,mX=Object.prototype,zC=O5["__core-js_shared__"],k50=El0.toString,C8=mX.hasOwnProperty,O50=function(){var $=/[^.]+$/.exec(zC&&zC.keys&&zC.keys.IE_PROTO||"");return $?"Symbol(src)_1."+$:""}(),u50=mX.toString,Bl0=RegExp("^"+k50.call(C8).replace(Wl0,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),N50=x50?O5.Buffer:void 0,pX=O5.Symbol,F50=O5.Uint8Array,f50=mX.propertyIsEnumerable,Rl0=Tl0.splice,H3=pX?pX.toStringTag:void 0,M50=Object.getOwnPropertySymbols,vl0=N50?N50.isBuffer:void 0,Cl0=Al0(Object.keys,Object),EC=qY(O5,"DataView"),OK=qY(O5,"Map"),BC=qY(O5,"Promise"),RC=qY(O5,"Set"),vC=qY(O5,"WeakMap"),NK=qY(Object,"create"),jl0=Z3(EC),_l0=Z3(OK),Sl0=Z3(BC),gl0=Z3(RC),yl0=Z3(vC),z50=pX?pX.prototype:void 0,AC=z50?z50.valueOf:void 0;function W3($){var I=-1,U=$==null?0:$.length;this.clear();while(++I<U){var Y=$[I];this.set(Y[0],Y[1])}}function hl0(){this.__data__=NK?NK(null):{},this.size=0}function xl0($){var I=this.has($)&&delete this.__data__[$];return this.size-=I?1:0,I}function kl0($){var I=this.__data Line truncated
]`;this.ESCAPE_REGEXP=new RegExp(I)}set headers($){this._headers=$}shouldQuote($,I){let U=I?this.formatterOptions.quoteHeaders:this.formatterOptions.quoteColumns;if(no0.default(U))return U;if(Array.isArray(U))return U[$];if(this._headers!==null)return U[this._headers[$]];return!1}format($,I,U){let Y=`${co0.default($)?"":$}`.replace(/\0/g,""),{formatterOptions:J}=this;if(J.quote!==""){if(Y.indexOf(J.quote)!==-1)return this.quoteField(Y.replace(this.REPLACE_REGEXP,J.escapedQuote))}if(Y.search(this.ESCAPE_REGEXP)!==-1||this.shouldQuote(I,U))return this.quoteField(Y);return Y}quoteField($){let{quote:I}=this.formatterOptions;return`${I}${$}${I}`}}GY.FieldFormatter=U90});var hC=N((Y90)=>{Object.defineProperty(Y90,"__esModule",{value:!0});Y90.isSyncTransform=void 0;Y90.isSyncTransform=($)=>$.length===1});var K90=N((HY)=>{var Q90=HY&&HY.__importDefault||function($){return $&&$.__esModule?$:{default:$}};Object.defineProperty(HY,"__esModule",{value:!0});HY.RowFormatter=void 0;var mo0=Q90(xX()),lo0=Q90(l50()),oo0=yC(),ro0=hC();class X3{constructor($){if(this.rowCount=0,this.formatterOptions=$,this.fieldFormatter=new oo0.FieldFormatter($),this.headers=$.headers,this.shouldWriteHeaders=$.shouldWriteHeaders,this.hasWrittenHeaders=!1,this.headers!==null)this.fieldFormatter.headers=this.headers;if($.transform)this.rowTransform=$.transform}static isRowHashArray($){if(Array.isArray($))return Array.isArray($[0])&&$[0].length===2;return!1}static isRowArray($){return Array.isArray($)&&!this.isRowHashArray($)}static gatherHeaders($){if(X3.isRowHashArray($))return $.map((I)=>I[0]);if(Array.isArray($))return $;return Object.keys($)}static createTransform($){if(ro0.isSyncTransform($))return(I,U)=>{let Y=null;try{Y=$(I)}catch(J){return U(J)}return U(null,Y)};return(I,U)=>{$(I,U)}}set rowTransform($){if(!mo0.default($))throw TypeError("The transform should be a function");this._rowTransform=X3.createTransform($)}format($,I){this.callTransformer($,(U,Y)=>{if(U)return I(U);if(!$)return I(null);let J=[];if(Y){let{shouldFormatColumns:Q,headers:K}=this.checkHeaders(Y);if(this.shouldWriteHeaders&&K&&!this.hasWrittenHeaders)J.push(this.formatColumns(K,!0)),this.hasWrittenHeaders=!0;if(Q){let q=this.gatherColumns(Y);J.push(this.formatColumns(q,!1))}}return I(null,J)})}finish($){let I=[];if(this.formatterOptions.alwaysWriteHeaders&&this.rowCount===0){if(!this.headers)return $(Error("`alwaysWriteHeaders` option is set to true but `headers` option not provided."));I.push(this.formatColumns(this.headers,!0))}if(this.formatterOptions.includeEndRowDelimiter)I.push(this.formatterOptions.rowDelimiter);return $(null,I)}checkHeaders($){if(this.headers)return{shouldFormatColumns:!0,headers:this.headers};let I=X3.gatherHeaders($);if(this.headers=I,this.fieldFormatter.headers=I,!this.shouldWriteHeaders)return{shouldFormatColumns:!0,headers:null};return{shouldFormatColumns:!lo0.default(I,$),headers:I}}gatherColumns($){if(this.headers===null)throw Error("Headers is currently null");if(!Array.isArray($))return this.headers.map((I)=>$[I]);if(X3.isRowHashArray($))return this.headers.map((I,U)=>{let Y=$[U];if(Y)return Y[1];return""});if(X3.isRowArray($)&&!this.shouldWriteHeaders)return $;return this.headers.map((I,U)=>$[U])}callTransformer($,I){if(!this._rowTransform)return I(null,$);return this._rowTransform($,I)}formatColumns($,I){let U=$.map((J,Q)=>this.fieldFormatter.format(J,Q,I)).join(this.formatterOptions.delimiter),{rowCount:Y}=this;if(this.rowCount+=1,Y)return[this.formatterOptions.rowDelimiter,U].join("");return U}}HY.RowFormatter=X3});var q90=N((rX)=>{Object.defineProperty(rX,"__esModule",{value:!0});rX.FieldFormatter=rX.RowFormatter=void 0;var to0=K90();Object.defineProperty(rX,"RowFormatter",{enumerable:!0,get:function(){return to0.RowFormatter}});var ao0=yC();Object.defineProperty(rX,"FieldFormatter",{enumerable:!0,get:function(){return ao0.FieldFormatter}})});var xC=N((H90)=>{Object.defineProperty(H90,"__esModule",{value:!0});H90.CsvFormatterStream=void 0;var eo0=r("stream"),$r0=q90();class G90 extends eo0.Transform{constructor($){super({writableObjectMode:$.objectMode});this.hasWrittenBOM=!1,this.formatterOptions=$,this.rowFormatter=new $r0.RowFormatter($),this.hasWrittenBOM=!$.writeBOM}transform($){return this.rowFormatter.rowTransform=$,this}_transform($,I,U){let Y=!1;try{if(!this.hasWrittenBOM)this.push(this.formatterOptions.BOM),this.hasWrittenBOM=!0;this.rowFormatter.format($,(J,Q)=>{if(J)return Y=!0,U(J);if(Q)Q.forEach((K)=>{this.push(Buffer.from(K,"utf8"))});return Y=!0,U()})}catch(J){if(Y)throw J;U(J)}}_flush($){this.rowFormatter.finish((I,U)=>{if(I)return $(I);if(U)U.forEach((Y)=>{this.push(Buffer.from(Y,"utf8"))});return $()})}}H90.CsvFormatterStream=G90});var Z90=N((M1)=>{var V90=M1&&M1.__createBinding||(Object.create?function($,I,U,Y){if(Y===void 0)Y=U;Object.defineProperty($,Y,{enumerable:!0,get:function(){return I[U]}})}:function($,I,U,Y){if(Y===void 0)Y=U;$[Y]=I[U]}),Ir0=M1&&M1.__setModuleDefault||(Object.create?function($,I){Ob Line truncated
`||I===`\r
`}static isTokenCarriageReturn($,I){return $.token===I.carriageReturn}static isTokenComment($,I){return I.supportsComments&&!!$&&$.token===I.comment}static isTokenEscapeCharacter($,I){return $.token===I.escapeChar}static isTokenQuote($,I){return $.token===I.quote}static isTokenDelimiter($,I){return $.token===I.delimiter}}X70.Token=Z70});var Kj=N((O70)=>{Object.defineProperty(O70,"__esModule",{value:!0});O70.Scanner=void 0;var w70=b9(),Hs0=/((?:\r\n)|\n|\r)/;class D70{constructor($){this.cursor=0,this.line=$.line,this.lineLength=this.line.length,this.parserOptions=$.parserOptions,this.hasMoreData=$.hasMoreData,this.cursor=$.cursor||0}get hasMoreCharacters(){return this.lineLength>this.cursor}get nextNonSpaceToken(){let{lineFromCursor:$}=this,I=this.parserOptions.NEXT_TOKEN_REGEXP;if($.search(I)===-1)return null;let U=I.exec($);if(U==null)return null;let Y=U[1],J=this.cursor+(U.index||0);return new w70.Token({token:Y,startCursor:J,endCursor:J+Y.length-1})}get nextCharacterToken(){let{cursor:$,lineLength:I}=this;if(I<=$)return null;return new w70.Token({token:this.line[$],startCursor:$,endCursor:$})}get lineFromCursor(){return this.line.substr(this.cursor)}advancePastLine(){let $=Hs0.exec(this.lineFromCursor);if(!$){if(this.hasMoreData)return null;return this.cursor=this.lineLength,this}return this.cursor+=($.index||0)+$[0].length,this}advanceTo($){return this.cursor=$,this}advanceToToken($){return this.cursor=$.startCursor,this}advancePastToken($){return this.cursor=$.endCursor+1,this}truncateToCursor(){return this.line=this.lineFromCursor,this.lineLength=this.line.length,this.cursor=0,this}}O70.Scanner=D70});var NL=N((M70)=>{Object.defineProperty(M70,"__esModule",{value:!0});M70.ColumnFormatter=void 0;class F70{constructor($){if($.trim)this.format=(I)=>I.trim();else if($.ltrim)this.format=(I)=>I.trimLeft();else if($.rtrim)this.format=(I)=>I.trimRight();else this.format=(I)=>I}}M70.ColumnFormatter=F70});var qj=N((T70)=>{Object.defineProperty(T70,"__esModule",{value:!0});T70.NonQuotedColumnParser=void 0;var Ws0=NL(),A70=b9();class P70{constructor($){this.parserOptions=$,this.columnFormatter=new Ws0.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let{parserOptions:I}=this,U=[],Y=$.nextCharacterToken;for(;Y;Y=$.nextCharacterToken){if(A70.Token.isTokenDelimiter(Y,I)||A70.Token.isTokenRowDelimiter(Y))break;U.push(Y.token),$.advancePastToken(Y)}return this.columnFormatter.format(U.join(""))}}T70.NonQuotedColumnParser=P70});var Gj=N((R70)=>{Object.defineProperty(R70,"__esModule",{value:!0});R70.QuotedColumnParser=void 0;var Vs0=NL(),MY=b9();class B70{constructor($){this.parserOptions=$,this.columnFormatter=new Vs0.ColumnFormatter($)}parse($){if(!$.hasMoreCharacters)return null;let I=$.cursor,{foundClosingQuote:U,col:Y}=this.gatherDataBetweenQuotes($);if(!U){if($.advanceTo(I),!$.hasMoreData)throw Error(`Parse Error: missing closing: '${this.parserOptions.quote||""}' in line: at '${$.lineFromCursor.replace(/[\r\n]/g,"\\n'")}'`);return null}return this.checkForMalformedColumn($),Y}gatherDataBetweenQuotes($){let{parserOptions:I}=this,U=!1,Y=!1,J=[],Q=$.nextCharacterToken;for(;!Y&&Q!==null;Q=$.nextCharacterToken){let K=MY.Token.isTokenQuote(Q,I);if(!U&&K)U=!0;else if(U)if(MY.Token.isTokenEscapeCharacter(Q,I)){$.advancePastToken(Q);let q=$.nextCharacterToken;if(q!==null&&(MY.Token.isTokenQuote(q,I)||MY.Token.isTokenEscapeCharacter(q,I)))J.push(q.token),Q=q;else if(K)Y=!0;else J.push(Q.token)}else if(K)Y=!0;else J.push(Q.token);$.advancePastToken(Q)}return{col:this.columnFormatter.format(J.join("")),foundClosingQuote:Y}}checkForMalformedColumn($){let{parserOptions:I}=this,{nextNonSpaceToken:U}=$;if(U){let Y=MY.Token.isTokenDelimiter(U,I),J=MY.Token.isTokenRowDelimiter(U);if(!(Y||J)){let Q=$.lineFromCursor.substr(0,10).replace(/[\r\n]/g,"\\n'");throw Error(`Parse Error: expected: '${I.escapedDelimiter}' OR new line got: '${U.token}'. at '${Q}`)}$.advanceToToken(U)}else if(!$.hasMoreData)$.advancePastLine()}}R70.QuotedColumnParser=B70});var S70=N((j70)=>{Object.defineProperty(j70,"__esModule",{value:!0});j70.ColumnParser=void 0;var Zs0=qj(),Xs0=Gj(),Ls0=b9();class C70{constructor($){this.parserOptions=$,this.quotedColumnParser=new Xs0.QuotedColumnParser($),this.nonQuotedColumnParser=new Zs0.NonQuotedColumnParser($)}parse($){let{nextNonSpaceToken:I}=$;if(I!==null&&Ls0.Token.isTokenQuote(I,this.parserOptions))return $.advanceToToken(I),this.quotedColumnParser.parse($);return this.nonQuotedColumnParser.parse($)}}j70.ColumnParser=C70});var Hj=N((zY)=>{Object.defineProperty(zY,"__esModule",{value:!0});zY.ColumnFormatter=zY.QuotedColumnParser=zY.NonQuotedColumnParser=zY.ColumnParser=void 0;var ws0=S70();Object.defineProperty(zY,"ColumnParser",{enumerable:!0,get:function(){return ws0.ColumnParser}});var Ds0=qj();Object.defineProperty(zY,"NonQuotedColumnParser",{enumerable:!0,get:function(){return Ds0.NonQuotedColumnParser}});var Os0=Gj();Object.defineProperty(zY,"QuotedColumnParser",{enumerable:!0,get:function(){re Line truncated
%s`,u,u,Z,Y);let g=Z.type==="*"?Ej:Z.type==="?"?vj:"\\"+Z.type;J=!0,Y=Y.slice(0,Z.reStart)+g+"\\("+u}if(A(),Q)Y+="\\\\";let T=Ge0[Y.charAt(0)];for(let u=q.length-1;u>-1;u--){let g=q[u],b=Y.slice(0,g.reStart),C=Y.slice(g.reStart,g.reEnd-8),n=Y.slice(g.reEnd),p=Y.slice(g.reEnd-8,g.reEnd)+n,S=b.split(")").length,f=b.split("(").length-S,i=n;for(let B=0;B<f;B++)i=i.replace(/\)[+*?]?/,"");n=i;let Y0=n===""&&I!==Bj?"(?:$|\\/)":"";Y=b+C+n+Y0+p}if(Y!==""&&J)Y="(?=.)"+Y;if(T)Y=F()+Y;if(I===Bj)return[Y,J];if(U.nocase&&!J)J=$.toUpperCase()!==$.toLowerCase();if(!J)return We0($);let v=U.nocase?"i":"";try{return Object.assign(new RegExp("^"+Y+"$",v),{_glob:$,_src:Y})}catch(u){return new RegExp("$.")}}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let $=this.set;if(!$.length)return this.regexp=!1,this.regexp;let I=this.options,U=I.noglobstar?Ej:I.dot?Ke0:qe0,Y=I.nocase?"i":"",J=$.map((Q)=>{return Q=Q.map((K)=>typeof K==="string"?Ze0(K):K===C6?C6:K._src).reduce((K,q)=>{if(!(K[K.length-1]===C6&&q===C6))K.push(q);return K},[]),Q.forEach((K,q)=>{if(K!==C6||Q[q-1]===C6)return;if(q===0)if(Q.length>1)Q[q+1]="(?:\\/|"+U+"\\/)?"+Q[q+1];else Q[q]=U;else if(q===Q.length-1)Q[q-1]+="(?:\\/|"+U+")?";else Q[q-1]+="(?:\\/|\\/"+U+"\\/)"+Q[q+1],Q[q+1]=C6}),Q.filter((K)=>K!==C6).join("/")}).join("|");if(J="^(?:"+J+")$",this.negate)J="^(?!"+J+").*$";try{this.regexp=new RegExp(J,Y)}catch(Q){this.regexp=!1}return this.regexp}match($,I=this.partial){if(this.debug("match",$,this.pattern),this.comment)return!1;if(this.empty)return $==="";if($==="/"&&I)return!0;let U=this.options;if(Rj.sep!=="/")$=$.split(Rj.sep).join("/");$=$.split(T30),this.debug(this.pattern,"split",$);let Y=this.set;this.debug(this.pattern,"set",Y);let J;for(let Q=$.length-1;Q>=0;Q--)if(J=$[Q],J)break;for(let Q=0;Q<Y.length;Q++){let K=Y[Q],q=$;if(U.matchBase&&K.length===1)q=[J];if(this.matchOne(q,K,I)){if(U.flipNegate)return!0;return!this.negate}}if(U.flipNegate)return!1;return this.negate}static defaults($){return Q$.defaults($).Minimatch}}Q$.Minimatch=BK});var S30=N((bE1,_30)=>{_30.exports=j30;var _j=r("fs"),{EventEmitter:Le0}=r("events"),{Minimatch:jj}=R30(),{resolve:we0}=r("path");function De0($,I){return new Promise((U,Y)=>{_j.readdir($,{withFileTypes:!0},(J,Q)=>{if(J)switch(J.code){case"ENOTDIR":if(I)Y(J);else U([]);break;case"ENOTSUP":case"ENOENT":case"ENAMETOOLONG":case"UNKNOWN":U([]);break;case"ELOOP":default:Y(J);break}else U(Q)})})}function v30($,I){return new Promise((U,Y)=>{(I?_j.stat:_j.lstat)($,(Q,K)=>{if(Q)switch(Q.code){case"ENOENT":if(I)U(v30($,!1));else U(null);break;default:U(null);break}else U(K)})})}async function*C30($,I,U,Y,J,Q){let K=await De0(I+$,Q);for(let q of K){let G=q.name;if(G===void 0)G=q,Y=!0;let H=$+"/"+G,W=H.slice(1),V=I+"/"+W,X=null;if(Y||U)X=await v30(V,U);if(!X&&q.name!==void 0)X=q;if(X===null)X={isDirectory:()=>!1};if(X.isDirectory()){if(!J(W))yield{relative:W,absolute:V,stats:X},yield*C30(H,I,U,Y,J,!1)}else yield{relative:W,absolute:V,stats:X}}}async function*Oe0($,I,U,Y){yield*C30("",$,I,U,Y,!0)}function Ne0($){return{pattern:$.pattern,dot:!!$.dot,noglobstar:!!$.noglobstar,matchBase:!!$.matchBase,nocase:!!$.nocase,ignore:$.ignore,skip:$.skip,follow:!!$.follow,stat:!!$.stat,nodir:!!$.nodir,mark:!!$.mark,silent:!!$.silent,absolute:!!$.absolute}}class Sj extends Le0{constructor($,I,U){super();if(typeof I==="function")U=I,I=null;if(this.options=Ne0(I||{}),this.matchers=[],this.options.pattern){let Y=Array.isArray(this.options.pattern)?this.options.pattern:[this.options.pattern];this.matchers=Y.map((J)=>new jj(J,{dot:this.options.dot,noglobstar:this.options.noglobstar,matchBase:this.options.matchBase,nocase:this.options.nocase}))}if(this.ignoreMatchers=[],this.options.ignore){let Y=Array.isArray(this.options.ignore)?this.options.ignore:[this.options.ignore];this.ignoreMatchers=Y.map((J)=>new jj(J,{dot:!0}))}if(this.skipMatchers=[],this.options.skip){let Y=Array.isArray(this.options.skip)?this.options.skip:[this.options.skip];this.skipMatchers=Y.map((J)=>new jj(J,{dot:!0}))}if(this.iterator=Oe0(we0($||"."),this.options.follow,this.options.stat,this._shouldSkipDirectory.bind(this)),this.paused=!1,this.inactive=!1,this.aborted=!1,U)this._matches=[],this.on("match",(Y)=>this._matches.push(this.options.absolute?Y.absolute:Y.relative)),this.on("error",(Y)=>U(Y)),this.on("end",()=>U(null,this._matches));setTimeout(()=>this._next(),0)}_shouldSkipDirectory($){return this.skipMatchers.some((I)=>I.match($))}_fileMatches($,I){let U=$+(I?"/":"");return(this.matchers.length===0||this.matchers.some((Y)=>Y.match(U)))&&!this.ignoreMatchers.some((Y)=>Y.match(U))&&(!this.options.nodir||!I)}_next(){if(!this.paused&&!this.aborted)this.iterator.next().then(($)=>{if(!$.done){let I=$.value.stats.isDirectory();if(this._fileMatches($.value.relative,I)){let U=$.value.relative,Y=$.value.absolute;if(this.options.mark&&I)U+="/",Y+="/";if(this.options.stat)this.emit("match",{relative:U,absolute:Y,stat:$.value.stats});else this.emit("match",{relative:U,ab Line truncated
`,y);y=$0===-1?P.length:$0}else if(c!==-1&&P[y]==="/"&&P[y+1]==="*"){let $0=P.indexOf("*/",y);if($0!==-1)y=$0+2,c=P.indexOf("*/",y);else R+=P[y],y++}else R+=P[y],y++;return R}function d8(P){let R=V$(P.toString()),y=R.match(W$);if(!y)y=R.match(x$);if(!y)throw Error(`could not parse args in autoInject
Source:
`+R);let[,c]=y;return c.replace(/\s/g,"").split(c8).map(($0)=>$0.replace(k$,"").trim())}function a6(P,R){var y={};return Object.keys(P).forEach((c)=>{var $0=P[c],U0,q0=Z($0),G0=!q0&&$0.length===1||q0&&$0.length===0;if(Array.isArray($0))U0=[...$0],$0=U0.pop(),y[c]=U0.concat(U0.length>0?Z0:$0);else if(G0)y[c]=$0;else{if(U0=d8($0),$0.length===0&&!q0&&U0.length===0)throw Error("autoInject task functions require explicit parameters.");if(!q0)U0.pop();y[c]=U0.concat(Z0)}function Z0(C0,Q1){var D1=U0.map((H1)=>C0[H1]);D1.push(Q1),O($0)(...D1)}}),j4(y,R)}class L7{constructor(){this.head=this.tail=null,this.length=0}removeLink(P){if(P.prev)P.prev.next=P.next;else this.head=P.next;if(P.next)P.next.prev=P.prev;else this.tail=P.prev;return P.prev=P.next=null,this.length-=1,P}empty(){while(this.head)this.shift();return this}insertAfter(P,R){if(R.prev=P,R.next=P.next,P.next)P.next.prev=R;else this.tail=R;P.next=R,this.length+=1}insertBefore(P,R){if(R.prev=P.prev,R.next=P,P.prev)P.prev.next=R;else this.head=R;P.prev=R,this.length+=1}unshift(P){if(this.head)this.insertBefore(this.head,P);else s6(this,P)}push(P){if(this.tail)this.insertAfter(this.tail,P);else s6(this,P)}shift(){return this.head&&this.removeLink(this.head)}pop(){return this.tail&&this.removeLink(this.tail)}toArray(){return[...this]}*[Symbol.iterator](){var P=this.head;while(P)yield P.data,P=P.next}remove(P){var R=this.head;while(R){var{next:y}=R;if(P(R))this.removeLink(R);R=y}return this}}function s6(P,R){P.length=1,P.head=P.tail=R}function n5(P,R,y){if(R==null)R=1;else if(R===0)throw RangeError("Concurrency must not be zero");var c=O(P),$0=0,U0=[];let q0={error:[],drain:[],saturated:[],unsaturated:[],empty:[]};function G0(h0,R0){q0[h0].push(R0)}function Z0(h0,R0){let x0=(...W1)=>{C0(h0,x0),R0(...W1)};q0[h0].push(x0)}function C0(h0,R0){if(!h0)return Object.keys(q0).forEach((x0)=>q0[x0]=[]);if(!R0)return q0[h0]=[];q0[h0]=q0[h0].filter((x0)=>x0!==R0)}function Q1(h0,...R0){q0[h0].forEach((x0)=>x0(...R0))}var D1=!1;function H1(h0,R0,x0,W1){if(W1!=null&&typeof W1!=="function")throw Error("task callback must be a function");O1.started=!0;var I4,u4;function X$(D7,...jJ){if(D7)return x0?u4(D7):I4();if(jJ.length<=1)return I4(jJ[0]);I4(jJ)}var HI=O1._createTaskItem(h0,x0?X$:W1||X$);if(R0)O1._tasks.unshift(HI);else O1._tasks.push(HI);if(!D1)D1=!0,H(()=>{D1=!1,O1.process()});if(x0||!W1)return new Promise((D7,jJ)=>{I4=D7,u4=jJ})}function Z$(h0){return function(R0,...x0){$0-=1;for(var W1=0,I4=h0.length;W1<I4;W1++){var u4=h0[W1],X$=U0.indexOf(u4);if(X$===0)U0.shift();else if(X$>0)U0.splice(X$,1);if(u4.callback(R0,...x0),R0!=null)Q1("error",R0,u4.data)}if($0<=O1.concurrency-O1.buffer)Q1("unsaturated");if(O1.idle())Q1("drain");O1.process()}}function GI(h0){if(h0.length===0&&O1.idle())return H(()=>Q1("drain")),!0;return!1}let w7=(h0)=>(R0)=>{if(!R0)return new Promise((x0,W1)=>{Z0(h0,(I4,u4)=>{if(I4)return W1(I4);x0(u4)})});C0(h0),G0(h0,R0)};var CJ=!1,O1={_tasks:new L7,_createTaskItem(h0,R0){return{data:h0,callback:R0}},*[Symbol.iterator](){yield*O1._tasks[Symbol.iterator]()},concurrency:R,payload:y,buffer:R/4,started:!1,paused:!1,push(h0,R0){if(Array.isArray(h0)){if(GI(h0))return;return h0.map((x0)=>H1(x0,!1,!1,R0))}return H1(h0,!1,!1,R0)},pushAsync(h0,R0){if(Array.isArray(h0)){if(GI(h0))return;return h0.map((x0)=>H1(x0,!1,!0,R0))}return H1(h0,!1,!0,R0)},kill(){C0(),O1._tasks.empty()},unshift(h0,R0){if(Array.isArray(h0)){if(GI(h0))return;return h0.map((x0)=>H1(x0,!0,!1,R0))}return H1(h0,!0,!1,R0)},unshiftAsync(h0,R0){if(Array.isArray(h0)){if(GI(h0))return;return h0.map((x0)=>H1(x0,!0,!0,R0))}return H1(h0,!0,!0,R0)},remove(h0){O1._tasks.remove(h0)},process(){if(CJ)return;CJ=!0;while(!O1.paused&&$0<O1.concurrency&&O1._tasks.length){var h0=[],R0=[],x0=O1._tasks.length;if(O1.payload)x0=Math.min(x0,O1.payload);for(var W1=0;W1<x0;W1++){var I4=O1._tasks.shift();h0.push(I4),U0.push(I4),R0.push(I4.data)}if($0+=1,O1._tasks.length===0)Q1("empty");if($0===O1.concurrency)Q1("saturated");var u4=S(Z$(h0));c(R0,u4)}CJ=!1},length(){return O1._tasks.length},running(){return $0},workersList(){return U0},idle(){return O1._tasks.length+$0===0},pause(){O1.paused=!0},resume(){if(O1.paused===!1)return;O1.paused=!1,H(O1.process)}};return Object.defineProperties(O1,{saturated:{writable:!1,value:w7("saturated")},unsaturated:{writable:!1,value:w7("unsaturated")},empty:{writable:!1,value:w7("empty")},drain:{writable:!1,value:w7("drain")},error:{writable:!1,value:w7("error")}}),O1}function T0(P,R){return n5(P,1,R)}function a(P,R,y){return n5(P,R,y)}function M(P,R,y,c){c=u(c);var $0=O(y);return f0(P,(U0,q0,G0)=>{$0(R,U0,(Z0,C0)=>{R=C0,G0(Z0)})},(U0)=>c(U0,R))}var z=F(M,4);function j(...P){var R=P.map(O);return function(...y){var c=this,$0=y[y.length-1];if(typeof $0=="function")y.pop();else $0=Q4();return z(R,y,(U0,q0,G0)=>{q0.apply(c,U0.concat((Z0,...C0)=>{G0(Z0,C0)}))},(U0,q0)=>$0(U0,...q0)),$0[d0]}}function x(...P){return j(...P.reverse())}function s(P,R,y,c){return A(i(R),P,y,c)}var m=F(s,4);function e( Line truncated
GFS4: `),console.error($)};if(!V4[Y6]){if(gj=global[Y6]||[],n30(V4,gj),V4.close=function($){function I(U,Y){return $.call(V4,U,function(J){if(!J)p30();if(typeof Y==="function")Y.apply(this,arguments)})}return Object.defineProperty(I,vL,{value:$}),I}(V4.close),V4.closeSync=function($){function I(U){$.apply(V4,arguments),p30()}return Object.defineProperty(I,vL,{value:$}),I}(V4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){O3(V4[Y6]),r("assert").equal(V4[Y6].length,0)})}var gj;if(!global[Y6])n30(global,V4[Y6]);xj.exports=yj(Re0(V4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!V4.__patched)xj.exports=yj(V4),V4.__patched=!0;function yj($){Ee0($),$.gracefulify=yj,$.createReadStream=v,$.createWriteStream=u;var I=$.readFile;$.readFile=U;function U(C,n,p){if(typeof n==="function")p=n,n=null;return S(C,n,p);function S(f,i,Y0,B){return I(f,i,function(k){if(k&&(k.code==="EMFILE"||k.code==="ENFILE"))TY([S,[f,i,Y0],k,B||Date.now(),Date.now()]);else if(typeof Y0==="function")Y0.apply(this,arguments)})}}var Y=$.writeFile;$.writeFile=J;function J(C,n,p,S){if(typeof p==="function")S=p,p=null;return f(C,n,p,S);function f(i,Y0,B,k,d){return Y(i,Y0,B,function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))TY([f,[i,Y0,B,k],t,d||Date.now(),Date.now()]);else if(typeof k==="function")k.apply(this,arguments)})}}var Q=$.appendFile;if(Q)$.appendFile=K;function K(C,n,p,S){if(typeof p==="function")S=p,p=null;return f(C,n,p,S);function f(i,Y0,B,k,d){return Q(i,Y0,B,function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))TY([f,[i,Y0,B,k],t,d||Date.now(),Date.now()]);else if(typeof k==="function")k.apply(this,arguments)})}}var q=$.copyFile;if(q)$.copyFile=G;function G(C,n,p,S){if(typeof p==="function")S=p,p=0;return f(C,n,p,S);function f(i,Y0,B,k,d){return q(i,Y0,B,function(t){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))TY([f,[i,Y0,B,k],t,d||Date.now(),Date.now()]);else if(typeof k==="function")k.apply(this,arguments)})}}var H=$.readdir;$.readdir=V;var W=/^v[0-5]\./;function V(C,n,p){if(typeof n==="function")p=n,n=null;var S=W.test(process.version)?function(Y0,B,k,d){return H(Y0,f(Y0,B,k,d))}:function(Y0,B,k,d){return H(Y0,B,f(Y0,B,k,d))};return S(C,n,p);function f(i,Y0,B,k){return function(d,t){if(d&&(d.code==="EMFILE"||d.code==="ENFILE"))TY([S,[i,Y0,B],d,k||Date.now(),Date.now()]);else{if(t&&t.sort)t.sort();if(typeof B==="function")B.call(this,d,t)}}}}if(process.version.substr(0,4)==="v0.8"){var X=Be0($);F=X.ReadStream,A=X.WriteStream}var Z=$.ReadStream;if(Z)F.prototype=Object.create(Z.prototype),F.prototype.open=E;var w=$.WriteStream;if(w)A.prototype=Object.create(w.prototype),A.prototype.open=T;Object.defineProperty($,"ReadStream",{get:function(){return F},set:function(C){F=C},enumerable:!0,configurable:!0}),Object.defineProperty($,"WriteStream",{get:function(){return A},set:function(C){A=C},enumerable:!0,configurable:!0});var D=F;Object.defineProperty($,"FileReadStream",{get:function(){return D},set:function(C){D=C},enumerable:!0,configurable:!0});var O=A;Object.defineProperty($,"FileWriteStream",{get:function(){return O},set:function(C){O=C},enumerable:!0,configurable:!0});function F(C,n){if(this instanceof F)return Z.apply(this,arguments),this;else return F.apply(Object.create(F.prototype),arguments)}function E(){var C=this;b(C.path,C.flags,C.mode,function(n,p){if(n){if(C.autoClose)C.destroy();C.emit("error",n)}else C.fd=p,C.emit("open",p),C.read()})}function A(C,n){if(this instanceof A)return w.apply(this,arguments),this;else return A.apply(Object.create(A.prototype),arguments)}function T(){var C=this;b(C.path,C.flags,C.mode,function(n,p){if(n)C.destroy(),C.emit("error",n);else C.fd=p,C.emit("open",p)})}function v(C,n){return new $.ReadStream(C,n)}function u(C,n){return new $.WriteStream(C,n)}var g=$.open;$.open=b;function b(C,n,p,S){if(typeof p==="function")S=p,p=null;return f(C,n,p,S);function f(i,Y0,B,k,d){return g(i,Y0,B,function(t,K0){if(t&&(t.code==="EMFILE"||t.code==="ENFILE"))TY([f,[i,Y0,B,k],t,d||Date.now(),Date.now()]);else if(typeof k==="function")k.apply(this,arguments)})}}return $}function TY($){O3("ENQUEUE",$[0].name,$[1]),V4[Y6].push($),hj()}var RL;function p30(){var $=Date.now();for(var I=0;I<V4[Y6].length;++I)if(V4[Y6][I].length>2)V4[Y6][I][3]=$,V4[Y6][I][4]=$;hj()}function hj(){if(clearTimeout(RL),RL=void 0,V4[Y6].length===0)return;var $=V4[Y6].shift(),I=$[0],U=$[1],Y=$[2],J=$[3],Q=$[4];if(J===void 0)O3("RETRY",I.name,U),I.apply(null,U);else if(Date.now()-J>=60000){O3("TIMEOUT",I.name,U);var K=U.pop();if(typeof K==="function")K.call(null,Y)}else{var q=Date.now()-Q,G=Math.max(Q-J,1),H=Math.min(G*1.2,100);if(q>=H)O3("RETRY",I.name,U),I.apply(null,U.concat([J]));else V4[Y6].push($)}if(RL===void 0)RL=setTimeout(hj,0)}});var d30=N((dE1,kj)=>{function Ce0($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var c30=z4().Buffer,RK=r("util");function je0($,I,U){$.copy(I,U)}kj.exports=function(){function $(){Ce0(this,$),this.head=null,this.tail=null,th Line truncated
* normalize-path <https://github.com/jonschlinkert/normalize-path>
*
* Copyright (c) 2014-2018, Jon Schlinkert.
* Released under the MIT License.
*/_I0.exports=function($,I){if(typeof $!=="string")throw TypeError("expected path to be a string");if($==="\\"||$==="/")return"/";var U=$.length;if(U<=1)return $;var Y="";if(U>4&&$[3]==="\\"){var J=$[2];if((J==="?"||J===".")&&$.slice(0,2)==="\\\\")$=$.slice(2),Y="//"}var Q=$.split(/[/\\]+/);if(I!==!1&&Q[Q.length-1]==="")Q.pop();return Y+Q.join("/")}});var Y_=N((YB1,uI0)=>{var gI0=9007199254740991,x01="[object Arguments]",k01="[object Function]",u01="[object GeneratorFunction]",f01=/^(?:0|[1-9]\d*)$/;function yI0($,I,U){switch(U.length){case 0:return $.call(I);case 1:return $.call(I,U[0]);case 2:return $.call(I,U[0],U[1]);case 3:return $.call(I,U[0],U[1],U[2])}return $.apply(I,U)}function b01($,I){var U=-1,Y=Array($);while(++U<$)Y[U]=I(U);return Y}var xK=Object.prototype,kK=xK.hasOwnProperty,hI0=xK.toString,i01=xK.propertyIsEnumerable,SI0=Math.max;function p01($,I){var U=s01($)||a01($)?b01($.length,String):[],Y=U.length,J=!!Y;for(var Q in $)if((I||kK.call($,Q))&&!(J&&(Q=="length"||kI0(Q,Y))))U.push(Q);return U}function n01($,I,U,Y){if($===void 0||$_($,xK[U])&&!kK.call(Y,U))return I;return $}function c01($,I,U){var Y=$[I];if(!(kK.call($,I)&&$_(Y,U))||U===void 0&&!(I in $))$[I]=U}function d01($){if(!U_($))return t01($);var I=r01($),U=[];for(var Y in $)if(!(Y=="constructor"&&(I||!kK.call($,Y))))U.push(Y);return U}function xI0($,I){return I=SI0(I===void 0?$.length-1:I,0),function(){var U=arguments,Y=-1,J=SI0(U.length-I,0),Q=Array(J);while(++Y<J)Q[Y]=U[I+Y];Y=-1;var K=Array(I+1);while(++Y<I)K[Y]=U[Y];return K[I]=Q,yI0($,this,K)}}function m01($,I,U,Y){U||(U={});var J=-1,Q=I.length;while(++J<Q){var K=I[J],q=Y?Y(U[K],$[K],K,U,$):void 0;c01(U,K,q===void 0?$[K]:q)}return U}function l01($){return xI0(function(I,U){var Y=-1,J=U.length,Q=J>1?U[J-1]:void 0,K=J>2?U[2]:void 0;if(Q=$.length>3&&typeof Q=="function"?(J--,Q):void 0,K&&o01(U[0],U[1],K))Q=J<3?void 0:Q,J=1;I=Object(I);while(++Y<J){var q=U[Y];if(q)$(I,q,Y,Q)}return I})}function kI0($,I){return I=I==null?gI0:I,!!I&&(typeof $=="number"||f01.test($))&&($>-1&&$%1==0&&$<I)}function o01($,I,U){if(!U_(U))return!1;var Y=typeof I;if(Y=="number"?I_(U)&&kI0(I,U.length):Y=="string"&&(I in U))return $_(U[I],$);return!1}function r01($){var I=$&&$.constructor,U=typeof I=="function"&&I.prototype||xK;return $===U}function t01($){var I=[];if($!=null)for(var U in Object($))I.push(U);return I}function $_($,I){return $===I||$!==$&&I!==I}function a01($){return e01($)&&kK.call($,"callee")&&(!i01.call($,"callee")||hI0.call($)==x01)}var s01=Array.isArray;function I_($){return $!=null&&I11($.length)&&!$11($)}function e01($){return U11($)&&I_($)}function $11($){var I=U_($)?hI0.call($):"";return I==k01||I==u01}function I11($){return typeof $=="number"&&$>-1&&$%1==0&&$<=gI0}function U_($){var I=typeof $;return!!$&&(I=="object"||I=="function")}function U11($){return!!$&&typeof $=="object"}var Y11=l01(function($,I,U,Y){m01(I,Q11(I),$,Y)}),J11=xI0(function($){return $.push(void 0,n01),yI0(Y11,void 0,$)});function Q11($){return I_($)?p01($,!0):d01($)}uI0.exports=J11});var bI0=N((JB1,J_)=>{function K11($,I){if(!($ instanceof I))throw TypeError("Cannot call a class as a function")}var fI0=z4().Buffer,uK=r("util");function q11($,I,U){$.copy(I,U)}J_.exports=function(){function $(){K11(this,$),this.head=null,this.tail=null,this.length=0}return $.prototype.push=function(U){var Y={data:U,next:null};if(this.length>0)this.tail.next=Y;else this.head=Y;this.tail=Y,++this.length},$.prototype.unshift=function(U){var Y={data:U,next:this.head};if(this.length===0)this.tail=Y;this.head=Y,++this.length},$.prototype.shift=function(){if(this.length===0)return;var U=this.head.data;if(this.length===1)this.head=this.tail=null;else this.head=this.head.next;return--this.length,U},$.prototype.clear=function(){this.head=this.tail=null,this.length=0},$.prototype.join=function(U){if(this.length===0)return"";var Y=this.head,J=""+Y.data;while(Y=Y.next)J+=U+Y.data;return J},$.prototype.concat=function(U){if(this.length===0)return fI0.alloc(0);var Y=fI0.allocUnsafe(U>>>0),J=this.head,Q=0;while(J)q11(J.data,Y,Q),Q+=J.data.length,J=J.next;return Y},$}();if(uK&&uK.inspect&&uK.inspect.custom)J_.exports.prototype[uK.inspect.custom]=function(){var $=uK.inspect({length:this.length});return this.constructor.name+" "+$}});var Q_=N((QB1,iI0)=>{var iL=M4();function G11($,I){var U=this,Y=this._readableState&&this._readableState.destroyed,J=this._writableState&&this._writableState.destroyed;if(Y||J){if(I)I($);else if($){if(!this._writableState)iL.nextTick(pL,this,$);else if(!this._writableState.errorEmitted)this._writableState.errorEmitted=!0,iL.nextTick(pL,this,$)}return this}if(this._readableState)this._readableState.destroyed=!0;if(this._writableState)this._writableState.destroyed=!0;return this._destroy($||null,function(Q){if(!I&&Q){if(!U._writableState)iL.nextTick(pL,U,Q);else if(!U._writableState.errorEmitted)U._writableState.errorEmitted=!0,iL.nextTick(pL,U,Q)}else if(I)I(Q)}),this}function H11(){if(this._readableState)this._readable Line truncated
%s`,v,v,E,Y);var u=E.type==="*"?n_:E.type==="?"?p_:"\\"+E.type;J=!0,Y=Y.slice(0,E.reStart)+u+"\\("+v}if(w(),Q)Y+="\\\\";var g=!1;switch(Y.charAt(0)){case"[":case".":case"(":g=!0}for(var b=q.length-1;b>-1;b--){var C=q[b],n=Y.slice(0,C.reStart),p=Y.slice(C.reStart,C.reEnd-8),S=Y.slice(C.reEnd-8,C.reEnd),f=Y.slice(C.reEnd);S+=f;var i=n.split("(").length-1,Y0=f;for(D=0;D<i;D++)Y0=Y0.replace(/\)[+*?]?/,"");f=Y0;var B="";if(f===""&&I!==Jw)B="$";var k=n+p+f+B+S;Y=k}if(Y!==""&&J)Y="(?=.)"+Y;if(g)Y=X+Y;if(I===Jw)return[Y,J];if(!J)return v81($);var d=U.nocase?"i":"";try{var t=new RegExp("^"+Y+"$",d)}catch(K0){return new RegExp("$.")}return t._glob=$,t._src=Y,t}K$.makeRe=function($,I){return new B4($,I||{}).makeRe()};B4.prototype.makeRe=R81;function R81(){if(this.regexp||this.regexp===!1)return this.regexp;var $=this.set;if(!$.length)return this.regexp=!1,this.regexp;var I=this.options,U=I.noglobstar?n_:I.dot?F81:M81,Y=I.nocase?"i":"",J=$.map(function(Q){return Q.map(function(K){return K===E3?U:typeof K==="string"?C81(K):K._src}).join("\\/")}).join("|");if(J="^(?:"+J+")$",this.negate)J="^(?!"+J+").*$";try{this.regexp=new RegExp(J,Y)}catch(Q){this.regexp=!1}return this.regexp}K$.match=function($,I,U){U=U||{};var Y=new B4(I,U);if($=$.filter(function(J){return Y.match(J)}),Y.options.nonull&&!$.length)$.push(I);return $};B4.prototype.match=function(I,U){if(typeof U>"u")U=this.partial;if(this.debug("match",I,this.pattern),this.comment)return!1;if(this.empty)return I==="";if(I==="/"&&U)return!0;var Y=this.options;if(tK.sep!=="/")I=I.split(tK.sep).join("/");I=I.split(wY0),this.debug(this.pattern,"split",I);var J=this.set;this.debug(this.pattern,"set",J);var Q,K;for(K=I.length-1;K>=0;K--)if(Q=I[K],Q)break;for(K=0;K<J.length;K++){var q=J[K],G=I;if(Y.matchBase&&q.length===1)G=[Q];var H=this.matchOne(G,q,U);if(H){if(Y.flipNegate)return!0;return!this.negate}}if(Y.flipNegate)return!1;return this.negate};B4.prototype.matchOne=function($,I,U){if(I.indexOf(E3)!==-1)return this._matchGlobstar($,I,U,0,0);return this._matchOne($,I,U,0,0)};B4.prototype._matchGlobstar=function($,I,U,Y,J){var Q,K=-1;for(Q=J;Q<I.length;Q++)if(I[Q]===E3){K=Q;break}var q=-1;for(Q=I.length-1;Q>=0;Q--)if(I[Q]===E3){q=Q;break}var G=I.slice(J,K),H=U?I.slice(K+1):I.slice(K+1,q),W=U?[]:I.slice(q+1);if(G.length){var V=$.slice(Y,Y+G.length);if(!this._matchOne(V,G,U,0,0))return!1;Y+=G.length}var X=0;if(W.length){if(W.length+Y>$.length)return!1;var Z=$.length-W.length;if(this._matchOne($,W,U,Z,0))X=W.length;else{if($[$.length-1]!==""||Y+W.length===$.length)return!1;if(Z--,!this._matchOne($,W,U,Z,0))return!1;X=W.length+1}}if(!H.length){var w=!!X;for(Q=Y;Q<$.length-X;Q++){var D=String($[Q]);if(w=!0,D==="."||D===".."||!this.options.dot&&D.charAt(0)===".")return!1}return U||w}var O=[[[],0]],F=O[0],E=0,A=[0];for(var T=0;T<H.length;T++){var v=H[T];if(v===E3)A.push(E),F=[[],0],O.push(F);else F[0].push(v),E++}var u=O.length-1,g=$.length-X;for(var b=0;b<O.length;b++)O[b][1]=g-(A[u--]+O[b][0].length);return!!this._matchGlobStarBodySections($,O,Y,0,U,0,!!X)};B4.prototype._matchGlobStarBodySections=function($,I,U,Y,J,Q,K){var q=I[Y];if(!q){for(var G=U;G<$.length;G++){K=!0;var H=$[G];if(H==="."||H===".."||!this.options.dot&&H.charAt(0)===".")return!1}return K}var W=q[0],V=q[1];while(U<=V){var X=this._matchOne($.slice(0,U+W.length),W,J,U,0);if(X&&Q<this.maxGlobstarRecursion){var Z=this._matchGlobStarBodySections($,I,U+W.length,Y+1,J,Q+1,K);if(Z!==!1)return Z}var H=$[U];if(H==="."||H===".."||!this.options.dot&&H.charAt(0)===".")return!1;U++}return J||null};B4.prototype._matchOne=function($,I,U,Y,J){var Q,K,q,G;for(Q=Y,K=J,q=$.length,G=I.length;Q<q&&K<G;Q++,K++){this.debug("matchOne loop");var H=I[K],W=$[Q];if(this.debug(I,H,W),H===!1||H===E3)return!1;var V;if(typeof H==="string")V=W===H,this.debug("string match",H,W,V);else V=W.match(H),this.debug("pattern match",H,W,V);if(!V)return!1}if(Q===q&&K===G)return!0;else if(Q===q)return U;else if(K===G)return Q===q-1&&$[Q]==="";throw Error("wtf?")};function v81($){return $.replace(/\\(.)/g,"$1")}function C81($){return $.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&")}});var Gw=N((TB1,qw)=>{function NY0($){return $.charAt(0)==="/"}function FY0($){var I=/^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/,U=I.exec($),Y=U[1]||"",J=Boolean(Y&&Y.charAt(1)!==":");return Boolean(U[2]||J)}qw.exports=process.platform==="win32"?FY0:NY0;qw.exports.posix=NY0;qw.exports.win32=FY0});var d_=N((f81)=>{f81.setopts=h81;f81.ownProp=MY0;f81.makeAbs=aK;f81.finish=x81;f81.mark=k81;f81.isIgnored=AY0;f81.childrenIgnored=u81;function MY0($,I){return Object.prototype.hasOwnProperty.call($,I)}var j81=r("fs"),kY=r("path"),_81=Kw(),zY0=Gw(),c_=_81.Minimatch;function S81($,I){return $.localeCompare(I,"en")}function g81($,I){if($.ignore=I.ignore||[],!Array.isArray($.ignore))$.ignore=[$.ignore];if($.ignore.length)$.ignore=$.ignore.map(y81)}function y81($){var I=null;if($.slice(-3)==="/**"){var U=$.replace(/(\/\*\*)+$/,"");I=new c_(U,{dot:!0})}return{matcher Line truncated
See: https://github.com/isaacs/node-glob/issues/167`);return new y4($,I).found}function y4($,I){if(!$)throw Error("must provide pattern");if(typeof I==="function"||arguments.length===3)throw TypeError(`callback provided to sync glob
See: https://github.com/isaacs/node-glob/issues/167`);if(!(this instanceof y4))return new y4($,I);if(o81(this,$,I),this.noprocess)return this;var U=this.minimatch.set.length;this.matches=Array(U);for(var Y=0;Y<U;Y++)this._process(this.minimatch.set[Y],Y,!1);this._finish()}y4.prototype._finish=function(){if(TY0.ok(this instanceof y4),this.realpath){var $=this;this.matches.forEach(function(I,U){var Y=$.matches[U]=Object.create(null);for(var J in I)try{J=$._makeAbs(J);var Q=l81.realpathSync(J,$.realpathCache);Y[Q]=!0}catch(K){if(K.syscall==="stat")Y[$._makeAbs(J)]=!0;else throw K}})}B3.finish(this)};y4.prototype._process=function($,I,U){TY0.ok(this instanceof y4);var Y=0;while(typeof $[Y]==="string")Y++;var J;switch(Y){case $.length:this._processSimple($.join("/"),I);return;case 0:J=null;break;default:J=$.slice(0,Y).join("/");break}var Q=$.slice(Y),K;if(J===null)K=".";else if(Hw(J)||Hw($.map(function(H){return typeof H==="string"?H:"[*]"}).join("/"))){if(!J||!Hw(J))J="/"+J;K=J}else K=J;var q=this._makeAbs(K);if(r81(this,K))return;var G=Q[0]===PY0.GLOBSTAR;if(G)this._processGlobStar(J,K,q,Q,I,U);else this._processReaddir(J,K,q,Q,I,U)};y4.prototype._processReaddir=function($,I,U,Y,J,Q){var K=this._readdir(U,Q);if(!K)return;var q=Y[0],G=!!this.minimatch.negate,H=q._glob,W=this.dot||H.charAt(0)===".",V=[];for(var X=0;X<K.length;X++){var Z=K[X];if(Z.charAt(0)!=="."||W){var w;if(G&&!$)w=!Z.match(q);else w=Z.match(q);if(w)V.push(Z)}}var D=V.length;if(D===0)return;if(Y.length===1&&!this.mark&&!this.stat){if(!this.matches[J])this.matches[J]=Object.create(null);for(var X=0;X<D;X++){var Z=V[X];if($)if($.slice(-1)!=="/")Z=$+"/"+Z;else Z=$+Z;if(Z.charAt(0)==="/"&&!this.nomount)Z=m_.join(this.root,Z);this._emitMatch(J,Z)}return}Y.shift();for(var X=0;X<D;X++){var Z=V[X],O;if($)O=[$,Z];else O=[Z];this._process(O.concat(Y),J,Q)}};y4.prototype._emitMatch=function($,I){if(t81(this,I))return;var U=this._makeAbs(I);if(this.mark)I=this._mark(I);if(this.absolute)I=U;if(this.matches[$][I])return;if(this.nodir){var Y=this.cache[U];if(Y==="DIR"||Array.isArray(Y))return}if(this.matches[$][I]=!0,this.stat)this._stat(I)};y4.prototype._readdirInGlobStar=function($){if(this.follow)return this._readdir($,!1);var I,U,Y;try{U=this.fs.lstatSync($)}catch(Q){if(Q.code==="ENOENT")return null}var J=U&&U.isSymbolicLink();if(this.symlinks[$]=J,!J&&U&&!U.isDirectory())this.cache[$]="FILE";else I=this._readdir($,!1);return I};y4.prototype._readdir=function($,I){var U;if(I&&!l_(this.symlinks,$))return this._readdirInGlobStar($);if(l_(this.cache,$)){var Y=this.cache[$];if(!Y||Y==="FILE")return null;if(Array.isArray(Y))return Y}try{return this._readdirEntries($,this.fs.readdirSync($))}catch(J){return this._readdirError($,J),null}};y4.prototype._readdirEntries=function($,I){if(!this.mark&&!this.stat)for(var U=0;U<I.length;U++){var Y=I[U];if($==="/")Y=$+Y;else Y=$+"/"+Y;this.cache[Y]=!0}return this.cache[$]=I,I};y4.prototype._readdirError=function($,I){switch(I.code){case"ENOTSUP":case"ENOTDIR":var U=this._makeAbs($);if(this.cache[U]="FILE",U===this.cwdAbs){var Y=Error(I.code+" invalid cwd "+this.cwd);throw Y.path=this.cwd,Y.code=I.code,Y}break;case"ENOENT":case"ELOOP":case"ENAMETOOLONG":case"UNKNOWN":this.cache[this._makeAbs($)]=!1;break;default:if(this.cache[this._makeAbs($)]=!1,this.strict)throw I;if(!this.silent)console.error("glob error",I);break}};y4.prototype._processGlobStar=function($,I,U,Y,J,Q){var K=this._readdir(U,Q);if(!K)return;var q=Y.slice(1),G=$?[$]:[],H=G.concat(q);this._process(H,J,!1);var W=K.length,V=this.symlinks[U];if(V&&Q)return;for(var X=0;X<W;X++){var Z=K[X];if(Z.charAt(0)==="."&&!this.dot)continue;var w=G.concat(K[X],q);this._process(w,J,!0);var D=G.concat(K[X],Y);this._process(D,J,!0)}};y4.prototype._processSimple=function($,I){var U=this._stat($);if(!this.matches[I])this.matches[I]=Object.create(null);if(!U)return;if($&&Hw($)&&!this.nomount){var Y=/[\/\\]$/.test($);if($.charAt(0)==="/")$=m_.join(this.root,$);else if($=m_.resolve(this.root,$),Y)$+="/"}if(process.platform==="win32")$=$.replace(/\\/g,"/");this._emitMatch(I,$)};y4.prototype._stat=function($){var I=this._makeAbs($),U=$.slice(-1)==="/";if($.length>this.maxLength)return!1;if(!this.stat&&l_(this.cache,I)){var K=this.cache[I];if(Array.isArray(K))K="DIR";if(!U||K==="DIR")return K;if(U&&K==="FILE")return!1}var Y,J=this.statCache[I];if(!J){var Q;try{Q=this.fs.lstatSync(I)}catch(q){if(q&&(q.code==="ENOENT"||q.code==="ENOTDIR"))return this.statCache[I]=!1,!1}if(Q&&Q.isSymbolicLink())try{J=this.fs.statSync(I)}catch(q){J=Q}else J=Q}this.statCache[I]=J;var K=!0;if(J)K=J.isDirectory()?"DIR":"FILE";if(this.cache[I]=this.cache[I]||K,U&&K==="FILE")return!1;return K};y4.prototype._mark=function($){return B3.mark(this,$)};y4.prototype._makeAbs=function($){return B3.makeAbs(this,$)}});var o_=N((jB1,CY0)=>{CY0.exports=vY0;function vY0($,I){if($&&I)return vY0($)(I);if(typeof $!=="function")throw TypeError("need wrapper function");return Object.keys($).forEach(function(Y){U[Y]=$[Y]}),U;f Line truncated
`);if($.linkname)I+=BS(" linkpath="+$.linkname+`
`);var U=$.pax;if(U)for(var Y in U)I+=BS(" "+Y+"="+U[Y]+`
`);return Buffer.from(I)};Z91.decodePax=function($){var I={};while($.length){var U=0;while(U<$.length&&$[U]!==32)U++;var Y=parseInt($.slice(0,U).toString(),10);if(!Y)return I;var J=$.slice(U+1,Y-1).toString(),Q=J.indexOf("=");if(Q===-1)return I;I[J.slice(0,Q)]=J.slice(Q+1),$=$.slice(Y)}return I};Z91.encode=function($){var I=I91(512),U=$.name,Y="";if($.typeflag===5&&U[U.length-1]!=="/")U+="/";if(Buffer.byteLength(U)!==U.length)return null;while(Buffer.byteLength(U)>100){var J=U.indexOf("/");if(J===-1)return null;Y+=Y?"/"+U.slice(0,J):U.slice(0,J),U=U.slice(J+1)}if(Buffer.byteLength(U)>100||Buffer.byteLength(Y)>155)return null;if($.linkname&&Buffer.byteLength($.linkname)>100)return null;if(I.write(U),I.write(t9($.mode&q91,6),100),I.write(t9($.uid,6),108),I.write(t9($.gid,6),116),I.write(t9($.size,11),124),I.write(t9($.mtime.getTime()/1000|0,11),136),I[156]=lJ0+W91($.type),$.linkname)I.write($.linkname,157);if(oJ0.copy(I,Yq),J91.copy(I,RS),$.uname)I.write($.uname,265);if($.gname)I.write($.gname,297);if(I.write(t9($.devmajor||0,6),329),I.write(t9($.devminor||0,6),337),Y)I.write(Y,345);return I.write(t9(tJ0(I),6),148),I};Z91.decode=function($,I,U){var Y=$[156]===0?0:$[156]-lJ0,J=iY($,0,100,I),Q=a9($,100,8),K=a9($,108,8),q=a9($,116,8),G=a9($,124,12),H=a9($,136,12),W=H91(Y),V=$[157]===0?null:iY($,157,100,I),X=iY($,265,32),Z=iY($,297,32),w=a9($,329,8),D=a9($,337,8),O=tJ0($);if(O===256)return null;if(O!==a9($,148,8))throw Error("Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?");if(oJ0.compare($,Yq,Yq+6)===0){if($[345])J=iY($,345,155,I)+"/"+J}else if(Q91.compare($,Yq,Yq+6)===0&&K91.compare($,RS,RS+2)===0);else if(!U)throw Error("Invalid tar header: unknown format.");if(Y===0&&J&&J[J.length-1]==="/")Y=5;return{name:J,mode:Q,uid:K,gid:q,size:G,mtime:new Date(1000*H),type:W,linkname:V,uname:X,gname:Z,devmajor:w,devminor:D}}});var YQ0=N((VR1,UQ0)=>{var sJ0=r("util"),N91=mJ0(),Jq=vS(),eJ0=L6().Writable,$Q0=L6().PassThrough,IQ0=function(){},aJ0=function($){return $&=511,$&&512-$},F91=function($,I){var U=new Dw($,I);return U.end(),U},M91=function($,I){if(I.path)$.name=I.path;if(I.linkpath)$.linkname=I.linkpath;if(I.size)$.size=parseInt(I.size,10);return $.pax=I,$},Dw=function($,I){this._parent=$,this.offset=I,$Q0.call(this,{autoDestroy:!1})};sJ0.inherits(Dw,$Q0);Dw.prototype.destroy=function($){this._parent.destroy($)};var R5=function($){if(!(this instanceof R5))return new R5($);eJ0.call(this,$),$=$||{},this._offset=0,this._buffer=N91(),this._missing=0,this._partial=!1,this._onparse=IQ0,this._header=null,this._stream=null,this._overflow=null,this._cb=null,this._locked=!1,this._destroyed=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null;var I=this,U=I._buffer,Y=function(){I._continue()},J=function(X){if(I._locked=!1,X)return I.destroy(X);if(!I._stream)Y()},Q=function(){I._stream=null;var X=aJ0(I._header.size);if(X)I._parse(X,K);else I._parse(512,V);if(!I._locked)Y()},K=function(){I._buffer.consume(aJ0(I._header.size)),I._parse(512,V),Y()},q=function(){var X=I._header.size;I._paxGlobal=Jq.decodePax(U.slice(0,X)),U.consume(X),Q()},G=function(){var X=I._header.size;if(I._pax=Jq.decodePax(U.slice(0,X)),I._paxGlobal)I._pax=Object.assign({},I._paxGlobal,I._pax);U.consume(X),Q()},H=function(){var X=I._header.size;this._gnuLongPath=Jq.decodeLongPath(U.slice(0,X),$.filenameEncoding),U.consume(X),Q()},W=function(){var X=I._header.size;this._gnuLongLinkPath=Jq.decodeLongPath(U.slice(0,X),$.filenameEncoding),U.consume(X),Q()},V=function(){var X=I._offset,Z;try{Z=I._header=Jq.decode(U.slice(0,512),$.filenameEncoding,$.allowUnknownFormat)}catch(w){I.emit("error",w)}if(U.consume(512),!Z){I._parse(512,V),Y();return}if(Z.type==="gnu-long-path"){I._parse(Z.size,H),Y();return}if(Z.type==="gnu-long-link-path"){I._parse(Z.size,W),Y();return}if(Z.type==="pax-global-header"){I._parse(Z.size,q),Y();return}if(Z.type==="pax-header"){I._parse(Z.size,G),Y();return}if(I._gnuLongPath)Z.name=I._gnuLongPath,I._gnuLongPath=null;if(I._gnuLongLinkPath)Z.linkname=I._gnuLongLinkPath,I._gnuLongLinkPath=null;if(I._pax)I._header=Z=M91(Z,I._pax),I._pax=null;if(I._locked=!0,!Z.size||Z.type==="directory"){I._parse(512,V),I.emit("entry",Z,F91(I,X),J);return}I._stream=new Dw(I,X),I.emit("entry",Z,I._stream,J),I._parse(Z.size,Q),Y()};this._onheader=V,this._parse(512,V)};sJ0.inherits(R5,eJ0);R5.prototype.destroy=function($){if(this._destroyed)return;if(this._destroyed=!0,$)this.emit("error",$);if(this.emit("close"),this._stream)this._stream.emit("close")};R5.prototype._parse=function($,I){if(this._destroyed)return;if(this._offset+=$,this._missing=$,I===this._onheader)this._partial=!1;this._onparse=I};R5.prototype._continue=function(){if(this._destroyed)return;var $=this._cb;if(this._cb=IQ0,this._overflow)this._write(this._overflow,void 0,$);else $()};R5.prototype._write=function($,I,U){if(this._destroyed)return;var Y=this._stream,J=this._buffer,Q=this._missing;if($.length)this._partial=!0;if($.length<Q){ Line truncated
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`)}_writeRelationship($){if(!this.count)this._writeOpen();let I=`rId${++this.count}`;if($.TargetMode)this.stream.write(`<Relationship Id="${I}" Type="${$.Type}" Target="${f91.xmlEncode($.Target)}" TargetMode="${$.TargetMode}"/>`);else this.stream.write(`<Relationship Id="${I}" Type="${$.Type}" Target="${$.Target}"/>`);return I}_writeClose(){this.stream.write("</Relationships>")}}CQ0.exports=vQ0});var hQ0=N((zR1,yQ0)=>{var _Q0=$6(),SQ0=g9(),i91=G4(),p91=qC(),n91=HC();class gQ0{constructor($,I,U){this.id=U.id,this.count=0,this._worksheet=$,this._workbook=U.workbook,this._sheetRelsWriter=I}get commentsStream(){if(!this._commentsStream)this._commentsStream=this._workbook._openStream(`/xl/comments${this.id}.xml`);return this._commentsStream}get vmlStream(){if(!this._vmlStream)this._vmlStream=this._workbook._openStream(`xl/drawings/vmlDrawing${this.id}.vml`);return this._vmlStream}_addRelationships(){let $={Type:SQ0.Comments,Target:`../comments${this.id}.xml`};this._sheetRelsWriter.addRelationship($);let I={Type:SQ0.VmlDrawing,Target:`../drawings/vmlDrawing${this.id}.vml`};this.vmlRelId=this._sheetRelsWriter.addRelationship(I)}_addCommentRefs(){this._workbook.commentRefs.push({commentName:`comments${this.id}`,vmlDrawing:`vmlDrawing${this.id}`})}_writeOpen(){this.commentsStream.write('<?xml version="1.0" encoding="UTF-8" standalone="yes"?><comments xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"><authors><author>Author</author></authors><commentList>'),this.vmlStream.write('<?xml version="1.0" encoding="UTF-8"?><xml xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:x="urn:schemas-microsoft-com:office:excel"><o:shapelayout v:ext="edit"><o:idmap v:ext="edit" data="1" /></o:shapelayout><v:shapetype id="_x0000_t202" coordsize="21600,21600" o:spt="202" path="m,l,21600r21600,l21600,xe"><v:stroke joinstyle="miter" /><v:path gradientshapeok="t" o:connecttype="rect" /></v:shapetype>')}_writeComment($,I){let U=new p91,Y=new _Q0;U.render(Y,$),this.commentsStream.write(Y.xml);let J=new n91,Q=new _Q0;J.render(Q,$,I),this.vmlStream.write(Q.xml)}_writeClose(){this.commentsStream.write("</commentList></comments>"),this.vmlStream.write("</xml>")}addComments($){if($&&$.length){if(!this.startedData)this._worksheet.comments=[],this._writeOpen(),this._addRelationships(),this._addCommentRefs(),this.startedData=!0;$.forEach((I)=>{I.refAddress=i91.decodeAddress(I.ref)}),$.forEach((I)=>{this._writeComment(I,this.count),this.count+=1})}}commit(){if(this.count)this._writeClose(),this.commentsStream.end(),this.vmlStream.end()}}yQ0.exports=gQ0});var iQ0=N((AR1,bQ0)=>{var c91=X4(),d91=g9(),_S=G4(),xQ0=EE(),kQ0=Q5(),m91=bR(),uQ0=yV(),SS=xV(),l91=jQ0(),o91=hQ0(),r91=PE(),i4=new m91,gS=j9(),t91=hv(),a91=xv(),s91=kv(),e91=_v(),$71=Cv(),I71=Sv(),U71=uv(),Y71=fv(),J71=bv(),Q71=iv(),K71=pv(),q71=nv(),G71=ov(),H71=dv(),W71=cv(),p4={dataValidations:new t91,sheetProperties:new a91,sheetFormatProperties:new s91,columns:new gS({tag:"cols",length:!1,childXform:new e91}),row:new $71,hyperlinks:new gS({tag:"hyperlinks",length:!1,childXform:new I71}),sheetViews:new gS({tag:"sheetViews",length:!1,childXform:new U71}),sheetProtection:new Y71,pageMargins:new J71,pageSeteup:new Q71,autoFilter:new K71,picture:new q71,conditionalFormattings:new G71,headerFooter:new H71,rowBreaks:new W71};class fQ0{constructor($){this.id=$.id,this.name=$.name||`Sheet${this.id}`,this.state=$.state||"visible",this._rows=[],this._columns=null,this._keys={},this._merges=[],this._merges.add=function(){},this._sheetRelsWriter=new l91($),this._sheetCommentsWriter=new o91(this,this._sheetRelsWriter,$),this._dimensions=new kQ0,this._rowZero=1,this.committed=!1,this.dataValidations=new r91,this._formulae={},this._siFormulae=0,this.conditionalFormatting=[],this.rowBreaks=[],this.properties=Object.assign({},{defaultRowHeight:15,dyDescent:55,outlineLevelCol:0,outlineLevelRow:0},$.properties),this.headerFooter=Object.assign({},{differentFirst:!1,differentOddEven:!1,oddHeader:null,oddFooter:null,evenHeader:null,evenFooter:null,firstHeader:null,firstFooter:null},$.headerFooter),this.pageSetup=Object.assign({},{margins:{left:0.7,right:0.7,top:0.75,bottom:0.75,header:0.3,footer:0.3},orientation:"portrait",horizontalDpi:4294967295,verticalDpi:4294967295,fitToPage:!!($.pageSetup&&($.pageSetup.fitToWidth||$.pageSetup.fitToHeight)&&!$.pageSetup.scale),pageOrder:"downThenOver",blackAndWhite:!1,draft:!1,cellComments:"None",errors:"displayed",scale:100,fitToWidth:1,fitToHeight:1,paperSize:void 0,showRowColHeaders:!1,showGridLines:!1,horizontalCentered:!1,verticalCentered:!1,rowBreaks:null,colBreaks:null},$.pageSetup),this.useSharedStrings=$.useSharedStrings||!1,this._workbook=$.workbook,this.hasComments=!1,this._views=$.views||[],this.autoFilter=$.autoFilter||null,this._media=[],this.sheetProtection=null,this._writeOpenWorksheet(),this.startedData=!1}get Line truncated
See http://goo.gl/MqrFmX
`)},aS=sS.getNativePromise();if(sS.isNode&&typeof MutationObserver>"u")eS=global.setImmediate,$g=process.nextTick,y3=sS.isRecentNode?function($){eS.call(global,$)}:function($){$g.call(process,$)};else if(typeof aS==="function"&&typeof aS.resolve==="function")Ig=aS.resolve(),y3=function($){Ig.then($)};else if(typeof MutationObserver<"u"&&!(typeof window<"u"&&window.navigator&&(window.navigator.standalone||window.cordova)))y3=function(){var $=document.createElement("div"),I={attributes:!0},U=!1,Y=document.createElement("div"),J=new MutationObserver(function(){$.classList.toggle("foo"),U=!1});J.observe(Y,I);var Q=function(){if(U)return;U=!0,Y.classList.toggle("foo")};return function(q){var G=new MutationObserver(function(){G.disconnect(),q()});G.observe($,I),Q()}}();else if(typeof setImmediate<"u")y3=function($){setImmediate($)};else if(typeof setTimeout<"u")y3=function($){setTimeout($,0)};else y3=I31;var eS,$g,Ig;M20.exports=y3});var P20=N((yR1,A20)=>{function U31($,I,U,Y,J){for(var Q=0;Q<J;++Q)U[Q+Y]=$[Q+I],$[Q+I]=void 0}function $7($){this._capacity=$,this._length=0,this._front=0}$7.prototype._willBeOverCapacity=function($){return this._capacity<$};$7.prototype._pushOne=function($){var I=this.length();this._checkCapacity(I+1);var U=this._front+I&this._capacity-1;this[U]=$,this._length=I+1};$7.prototype.push=function($,I,U){var Y=this.length()+3;if(this._willBeOverCapacity(Y)){this._pushOne($),this._pushOne(I),this._pushOne(U);return}var J=this._front+Y-3;this._checkCapacity(Y);var Q=this._capacity-1;this[J+0&Q]=$,this[J+1&Q]=I,this[J+2&Q]=U,this._length=Y};$7.prototype.shift=function(){var $=this._front,I=this[$];return this[$]=void 0,this._front=$+1&this._capacity-1,this._length--,I};$7.prototype.length=function(){return this._length};$7.prototype._checkCapacity=function($){if(this._capacity<$)this._resizeTo(this._capacity<<1)};$7.prototype._resizeTo=function($){var I=this._capacity;this._capacity=$;var U=this._front,Y=this._length,J=U+Y&I-1;U31(this,0,this,I,J)};A20.exports=$7});var j20=N((hR1,Ug)=>{var v20;try{throw Error()}catch($){v20=$}var Y31=z20(),T20=P20(),C20=b1();function n4(){this._customScheduler=!1,this._isTickUsed=!1,this._lateQueue=new T20(16),this._normalQueue=new T20(16),this._haveDrainedQueues=!1,this._trampolineEnabled=!0;var $=this;this.drainQueues=function(){$._drainQueues()},this._schedule=Y31}n4.prototype.setScheduler=function($){var I=this._schedule;return this._schedule=$,this._customScheduler=!0,I};n4.prototype.hasCustomScheduler=function(){return this._customScheduler};n4.prototype.enableTrampoline=function(){this._trampolineEnabled=!0};n4.prototype.disableTrampolineIfNecessary=function(){if(C20.hasDevTools)this._trampolineEnabled=!1};n4.prototype.haveItemsQueued=function(){return this._isTickUsed||this._haveDrainedQueues};n4.prototype.fatalError=function($,I){if(I)process.stderr.write("Fatal "+($ instanceof Error?$.stack:$)+`
`),process.exit(2);else this.throwLater($)};n4.prototype.throwLater=function($,I){if(arguments.length===1)I=$,$=function(){throw I};if(typeof setTimeout<"u")setTimeout(function(){$(I)},0);else try{this._schedule(function(){$(I)})}catch(U){throw Error(`No async scheduler available
See http://goo.gl/MqrFmX
`)}};function E20($,I,U){this._lateQueue.push($,I,U),this._queueTick()}function B20($,I,U){this._normalQueue.push($,I,U),this._queueTick()}function R20($){this._normalQueue._pushOne($),this._queueTick()}if(!C20.hasDevTools)n4.prototype.invokeLater=E20,n4.prototype.invoke=B20,n4.prototype.settlePromises=R20;else n4.prototype.invokeLater=function($,I,U){if(this._trampolineEnabled)E20.call(this,$,I,U);else this._schedule(function(){setTimeout(function(){$.call(I,U)},100)})},n4.prototype.invoke=function($,I,U){if(this._trampolineEnabled)B20.call(this,$,I,U);else this._schedule(function(){$.call(I,U)})},n4.prototype.settlePromises=function($){if(this._trampolineEnabled)R20.call(this,$);else this._schedule(function(){$._settlePromises()})};n4.prototype._drainQueue=function($){while($.length()>0){var I=$.shift();if(typeof I!=="function"){I._settlePromises();continue}var U=$.shift(),Y=$.shift();I.call(U,Y)}};n4.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)};n4.prototype._queueTick=function(){if(!this._isTickUsed)this._isTickUsed=!0,this._schedule(this.drainQueues)};n4.prototype._reset=function(){this._isTickUsed=!1};Ug.exports=n4;Ug.exports.firstLineError=v20});var C5=N((xR1,g20)=>{var Qg=g3(),J31=Qg.freeze,_20=b1(),S20=_20.inherits,mY=_20.notEnumerableProp;function lY($,I){function U(Y){if(!(this instanceof U))return new U(Y);if(mY(this,"message",typeof Y==="string"?Y:I),mY(this,"name",$),Error.captureStackTrace)Error.captureStackTrace(this,this.constructor);else Error.call(this)}return S20(U,Error),U}var Yg,Jg,Q31=lY("Warning","warning"),K31=lY("CancellationError","cancellation error"),q31=lY("TimeoutError","timeout error"),Wq=lY("AggregateError","aggregate error");try{Yg=TypeError,Jg=RangeError}catch($){Yg=lY("TypeError","type error"),Jg=lY("RangeError","range error")}var Ew="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" ");for(h3=0;h3<Ew.length;++h3)if(typeof Array.prototype[Ew[h3]]==="function")Wq.prototype[Ew[h3]]=Array.prototype[Ew[h3]];var h3;Qg.defineProperty(Wq.prototype,"length",{value:0,configurable:!1,writable:!0,enumerable:!0});Wq.prototype.isOperational=!0;var Bw=0;Wq.prototype.toString=function(){var $=Array(Bw*4+1).join(" "),I=`
`+$+`AggregateError of:
`;Bw++,$=Array(Bw*4+1).join(" ");for(var U=0;U<this.length;++U){var Y=this[U]===this?"[Circular AggregateError]":this[U]+"",J=Y.split(`
`);for(var Q=0;Q<J.length;++Q)J[Q]=$+J[Q];Y=J.join(`
`),I+=Y+`
`}return Bw--,I};function Hq($){if(!(this instanceof Hq))return new Hq($);if(mY(this,"name","OperationalError"),mY(this,"message",$),this.cause=$,this.isOperational=!0,$ instanceof Error)mY(this,"message",$.message),mY(this,"stack",$.stack);else if(Error.captureStackTrace)Error.captureStackTrace(this,this.constructor)}S20(Hq,Error);var x3=Error.__BluebirdErrorTypes__;if(!x3)x3=J31({CancellationError:K31,TimeoutError:q31,OperationalError:Hq,RejectionError:Hq,AggregateError:Wq}),Qg.defineProperty(Error,"__BluebirdErrorTypes__",{value:x3,writable:!1,enumerable:!1,configurable:!1});g20.exports={Error,TypeError:Yg,RangeError:Jg,CancellationError:x3.CancellationError,OperationalError:x3.OperationalError,TimeoutError:x3.TimeoutError,AggregateError:x3.AggregateError,Warning:Q31}});var h20=N((kR1,y20)=>{y20.exports=function($,I){var U=b1(),Y=U.errorObj,J=U.isObject;function Q(V,X){if(J(V)){if(V instanceof $)return V;var Z=q(V);if(Z===Y){if(X)X._pushContext();var w=$.reject(Z.e);if(X)X._popContext();return w}else if(typeof Z==="function"){if(H(V)){var w=new $(I);return V._then(w._fulfill,w._reject,void 0,w,null),w}return W(V,Z,X)}}return V}function K(V){return V.then}function q(V){try{return K(V)}catch(X){return Y.e=X,Y}}var G={}.hasOwnProperty;function H(V){try{return G.call(V,"_promise0")}catch(X){return!1}}function W(V,X,Z){var w=new $(I),D=w;if(Z)Z._pushContext();if(w._captureStackTrace(),Z)Z._popContext();var O=!0,F=U.tryCatch(X).call(V,E,A);if(O=!1,w&&F===Y)w._rejectCallback(F.e,!0,!0),w=null;function E(T){if(!w)return;w._resolveCallback(T),w=null}function A(T){if(!w)return;w._rejectCallback(T,O,!0),w=null}return D}return Q}});var k20=N((uR1,x20)=>{x20.exports=function($,I,U,Y,J){var Q=b1(),K=Q.isArray;function q(H){switch(H){case-2:return[];case-3:return{}}}function G(H){var W=this._promise=new $(I);if(H instanceof $)W._propagateFrom(H,3);W._setOnCancel(this),this._values=H,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return Q.inherits(G,J),G.prototype.length=function(){return this._length},G.prototype.promise=function(){return this._promise},G.prototype._init=function H(W,V){var X=U(this._values,this._promise);if(X instanceof $){X=X._target();var Z=X._bitField;if(this._values=X,(Z&50397184)===0)return this._promise._setAsyncGuaranteed(),X._then(H,this._reject,void 0,this,V);else if((Z&33554432)!==0)X=X._value();else if((Z&16777216)!==0)return this._reject(X._reason());else return this._cancel()}if(X=Q.asArray(X),X===null){var w=Y("expecting an array or an iterable object but got "+Q.classString(X)).reason();this._promise._rejectCallback(w,!1);return}if(X.length===0){if(V===-5)this._resolveEmptyArray();else this._resolve(q(V));return}this._iterate(X)},G.prototype._iterate=function(H){var W=this.getActualLength(H.length);this._length=W,this._values=this.shouldCopyValues()?Array(W):this._values;var V=this._promise,X=!1,Z=null;for(var w=0;w<W;++w){var D=U(H[w],V);if(D instanceof $)D=D._target(),Z=D._bitField;else Z=null;if(X){if(Z!==null)D.suppressUnhandledRejections()}else if(Z!==null)if((Z&50397184)===0)D._proxy(this,w),this._values[w]=D;else if((Z&33554432)!==0)X=this._promiseFulfilled(D._value(),w);else if((Z&16777216)!==0)X=this._promiseRejected(D._reason(),w);else X=this._promiseCancelled(w);else X=this._promiseFulfilled(D,w)}if(!X)V._setAsyncGuaranteed()},G.prototype._isResolved=function(){return this._values===null},G.prototype._resolve=function(H){this._values=null,this._promise._fulfill(H)},G.prototype._cancel=function(){if(this._isResolved()||!this._promise._isCancellable())return;this._values=null,this._promise._cancel()},G.prototype._reject=function(H){this._values=null,this._promise._rejectCallback(H,!1)},G.prototype._promiseFulfilled=function(H,W){this._values[W]=H;var V=++this._totalResolved;if(V>=this._length)return this._resolve(this._values),!0;return!1},G.prototype._promiseCancelled=function(){return this._cancel(),!0},G.prototype._promiseRejected=function(H){return this._totalResolved++,this._reject(H),!0},G.prototype._resultCancelled=function(){if(this._isResolved())return;var H=this._values;if(this._cancel(),H instanceof $)H.cancel();else for(var W=0;W<H.length;++W)if(H[W]instanceof $)H[W].cancel()},G.prototype.shouldCopyValues=function(){return!0},G.prototype.getActualLength=function(H){return H},G}});var f20=N((fR1,u20)=>{u20.exports=function($){var I=!1,U=[];$.prototype._promiseCreated=function(){},$.prototype._pushContext=function(){},$.prototype._popContext=function(){return null},$._peekContext=$.prototype._peekContext=function(){};function Y(){this._trace=new Y.CapturedTrace(Q())}Y.prototype._pushContext=function(){if(this._trace!==void 0)this._trace._promiseCreated=null,U.push(this._trace)},Y.prototype._popContext=function(){if(this._trace!==void 0){var K=U.pop(),q=K._promiseCreated;return K._promiseCreated=null,q}return null};function J(){if(I)return new Y}function Q(){var K=U.length-1;if(K>=0)return U[K];return}return Y.CapturedTrace=null,Y.create=J,Y.deactivateLong Line truncated
See http://goo.gl/MqrFmX
`);if(!T0.longStackTraces&&k$()){var a=$.prototype._captureStackTrace,M=$.prototype._attachExtraTrace;T0.longStackTraces=!0,T=function(){if(Y.haveItemsQueued()&&!T0.longStackTraces)throw Error(`cannot enable long stack traces after promises have been created
See http://goo.gl/MqrFmX
`);$.prototype._captureStackTrace=a,$.prototype._attachExtraTrace=M,I.deactivateLongStackTraces(),Y.enableTrampoline(),T0.longStackTraces=!1},$.prototype._captureStackTrace=K0,$.prototype._attachExtraTrace=W0,I.activateLongStackTraces(),Y.disableTrampolineIfNecessary()}},$.hasLongStackTraces=function(){return T0.longStackTraces&&k$()};var v=function(){try{if(typeof CustomEvent==="function"){var a=new CustomEvent("CustomEvent");return Q.global.dispatchEvent(a),function(M,z){var j=new CustomEvent(M.toLowerCase(),{detail:z,cancelable:!0});return!Q.global.dispatchEvent(j)}}else if(typeof Event==="function"){var a=new Event("CustomEvent");return Q.global.dispatchEvent(a),function(z,j){var x=new Event(z.toLowerCase(),{cancelable:!0});return x.detail=j,!Q.global.dispatchEvent(x)}}else{var a=document.createEvent("CustomEvent");return a.initCustomEvent("testingtheevent",!1,!0,{}),Q.global.dispatchEvent(a),function(z,j){var x=document.createEvent("CustomEvent");return x.initCustomEvent(z.toLowerCase(),!1,!0,j),!Q.global.dispatchEvent(x)}}}catch(M){}return function(){return!1}}(),u=function(){if(Q.isNode)return function(){return process.emit.apply(process,arguments)};else{if(!Q.global)return function(){return!1};return function(a){var M="on"+a.toLowerCase(),z=Q.global[M];if(!z)return!1;return z.apply(Q.global,[].slice.call(arguments,1)),!0}}}();function g(a,M){return{promise:M}}var b={promiseCreated:g,promiseFulfilled:g,promiseRejected:g,promiseResolved:g,promiseCancelled:g,promiseChained:function(a,M,z){return{promise:M,child:z}},warning:function(a,M){return{warning:M}},unhandledRejection:function(a,M,z){return{reason:M,promise:z}},rejectionHandled:g},C=function(a){var M=!1;try{M=u.apply(null,arguments)}catch(j){Y.throwLater(j),M=!0}var z=!1;try{z=v(a,b[a].apply(null,arguments))}catch(j){Y.throwLater(j),z=!0}return z||M};$.config=function(a){if(a=Object(a),"longStackTraces"in a){if(a.longStackTraces)$.longStackTraces();else if(!a.longStackTraces&&$.hasLongStackTraces())T()}if("warnings"in a){var M=a.warnings;if(T0.warnings=!!M,A=T0.warnings,Q.isObject(M)){if("wForgottenReturn"in M)A=!!M.wForgottenReturn}}if("cancellation"in a&&a.cancellation&&!T0.cancellation){if(Y.haveItemsQueued())throw Error("cannot enable cancellation after promises are in use");$.prototype._clearCancellationData=Y0,$.prototype._propagateFrom=B,$.prototype._onCancel=f,$.prototype._setOnCancel=i,$.prototype._attachCancellationCallback=S,$.prototype._execute=p,d=B,T0.cancellation=!0}if("monitoring"in a){if(a.monitoring&&!T0.monitoring)T0.monitoring=!0,$.prototype._fireEvent=C;else if(!a.monitoring&&T0.monitoring)T0.monitoring=!1,$.prototype._fireEvent=n}return $};function n(){return!1}$.prototype._fireEvent=n,$.prototype._execute=function(a,M,z){try{a(M,z)}catch(j){return j}},$.prototype._onCancel=function(){},$.prototype._setOnCancel=function(a){},$.prototype._attachCancellationCallback=function(a){},$.prototype._captureStackTrace=function(){},$.prototype._attachExtraTrace=function(){},$.prototype._clearCancellationData=function(){},$.prototype._propagateFrom=function(a,M){};function p(a,M,z){var j=this;try{a(M,z,function(x){if(typeof x!=="function")throw TypeError("onCancel must be a function, got: "+Q.toString(x));j._attachCancellationCallback(x)})}catch(x){return x}}function S(a){if(!this._isCancellable())return this;var M=this._onCancel();if(M!==void 0)if(Q.isArray(M))M.push(a);else this._setOnCancel([M,a]);else this._setOnCancel(a)}function f(){return this._onCancelField}function i(a){this._onCancelField=a}function Y0(){this._cancellationParent=void 0,this._onCancelField=void 0}function B(a,M){if((M&1)!==0){this._cancellationParent=a;var z=a._branchesRemainingToCancel;if(z===void 0)z=0;a._branchesRemainingToCancel=z+1}if((M&2)!==0&&a._isBound())this._setBoundTo(a._boundTo)}function k(a,M){if((M&2)!==0&&a._isBound())this._setBoundTo(a._boundTo)}var d=k;function t(){var a=this._boundTo;if(a!==void 0){if(a instanceof $)if(a.isFulfilled())return a.value();else return}return a}function K0(){this._trace=new s6(this._peekContext())}function W0(a,M){if(K(a)){var z=this._trace;if(z!==void 0){if(M)z=z._parent}if(z!==void 0)z.attachExtraTrace(a);else if(!a.__stackCleaned__){var j=Q4(a);Q.notEnumerableProp(a,"stack",j.message+`
`+j.stack.join(`
`)),Q.notEnumerableProp(a,"__stackCleaned__",!0)}}}function z0(a,M,z,j,x){if(a===void 0&&M!==null&&A){if(x!==void 0&&x._returnedNonUndefined())return;if((j._bitField&65535)===0)return;if(z)z=z+" ";var s="",m="";if(M._trace){var e=M._trace.stack.split(`
`),J0=g0(e);for(var H0=J0.length-1;H0>=0;--H0){var v0=J0[H0];if(!W.test(v0)){var b0=v0.match(V);if(b0)s="at "+b0[1]+":"+b0[2]+":"+b0[3]+" ";break}}if(J0.length>0){var k0=J0[0];for(var H0=0;H0<e.length;++H0)if(e[H0]===k0){if(H0>0)m=`
`+e[H0-1];break}}}var J1="a promise was created in a "+z+"handler "+s+"but was not returned from it, see http://goo.gl/rRqMUw"+m;j._warn(J1,!0,M)}}function B0(a,M){var z=a+" is deprecated and will be removed in a future version.";if(M)z+=" Use "+M+" instead.";return w1(z)}function w1(a,M,z){if(!T0.warnings)return;var j=new J(a),x;if(M)z._attachExtraTrace(j);else if(T0.longStackTraces&&(x=$._peekContext()))x.attachExtraTrace(j);else{var s=Q4(j);j.stack=s.message+`
`+s.stack.join(`
`)}if(!C("warning",j))j4(j,"",!0)}function f0(a,M){for(var z=0;z<M.length-1;++z)M[z].push("From previous event:"),M[z]=M[z].join(`
`);if(z<M.length)M[z]=M[z].join(`
`);return a+`
`+M.join(`
`)}function G1(a){for(var M=0;M<a.length;++M)if(a[M].length===0||M+1<a.length&&a[M][0]===a[M+1][0])a.splice(M,1),M--}function N0(a){var M=a[0];for(var z=1;z<a.length;++z){var j=a[z],x=M.length-1,s=M[x],m=-1;for(var e=j.length-1;e>=0;--e)if(j[e]===s){m=e;break}for(var e=m;e>=0;--e){var J0=j[e];if(M[x]===J0)M.pop(),x--;else break}M=j}}function g0(a){var M=[];for(var z=0;z<a.length;++z){var j=a[z],x=j===" (No stack trace)"||X.test(j),s=x&&V$(j);if(x&&!s){if(w&&j.charAt(0)!==" ")j=" "+j;M.push(j)}}return M}function d0(a){var M=a.stack.replace(/\s+$/g,"").split(`
`);for(var z=0;z<M.length;++z){var j=M[z];if(j===" (No stack trace)"||X.test(j))break}if(z>0&&a.name!="SyntaxError")M=M.slice(z);return M}function Q4(a){var M=a.stack,z=a.toString();return M=typeof M==="string"&&M.length>0?d0(a):[" (No stack trace)"],{message:z,stack:a.name=="SyntaxError"?M:g0(M)}}function j4(a,M,z){if(typeof console<"u"){var j;if(Q.isObject(a)){var x=a.stack;j=M+Z(x,a)}else j=M+String(a);if(typeof D==="function")D(j,z);else if(typeof console.log==="function"||typeof console.log==="object")console.log(j)}}function W$(a,M,z,j){var x=!1;try{if(typeof M==="function")if(x=!0,a==="rejectionHandled")M(j);else M(z,j)}catch(s){Y.throwLater(s)}if(a==="unhandledRejection"){if(!C(a,z,j)&&!x)j4(z,"Unhandled rejection ")}else C(a,j)}function x$(a){var M;if(typeof a==="function")M="[function "+(a.name||"anonymous")+"]";else{M=a&&typeof a.toString==="function"?a.toString():Q.toString(a);var z=/\[object [a-zA-Z0-9$_]+\]/;if(z.test(M))try{var j=JSON.stringify(a);M=j}catch(x){}if(M.length===0)M="(empty array)"}return"(<"+c8(M)+">, no stack trace)"}function c8(a){var M=41;if(a.length<M)return a;return a.substr(0,M-3)+"..."}function k$(){return typeof n5==="function"}var V$=function(){return!1},d8=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function a6(a){var M=a.match(d8);if(M)return{fileName:M[1],line:parseInt(M[2],10)}}function L7(a,M){if(!k$())return;var z=a.stack.split(`
`),j=M.stack.split(`
`),x=-1,s=-1,m,e;for(var J0=0;J0<z.length;++J0){var H0=a6(z[J0]);if(H0){m=H0.fileName,x=H0.line;break}}for(var J0=0;J0<j.length;++J0){var H0=a6(j[J0]);if(H0){e=H0.fileName,s=H0.line;break}}if(x<0||s<0||!m||!e||m!==e||x>=s)return;V$=function(v0){if(H.test(v0))return!0;var b0=a6(v0);if(b0){if(b0.fileName===m&&(x<=b0.line&&b0.line<=s))return!0}return!1}}function s6(a){this._parent=a,this._promisesCreated=0;var M=this._length=1+(a===void 0?0:a._length);if(n5(this,s6),M>32)this.uncycle()}Q.inherits(s6,Error),I.CapturedTrace=s6,s6.prototype.uncycle=function(){var a=this._length;if(a<2)return;var M=[],z={};for(var j=0,x=this;x!==void 0;++j)M.push(x),x=x._parent;a=this._length=j;for(var j=a-1;j>=0;--j){var s=M[j].stack;if(z[s]===void 0)z[s]=j}for(var j=0;j<a;++j){var m=M[j].stack,e=z[m];if(e!==void 0&&e!==j){if(e>0)M[e-1]._parent=void 0,M[e-1]._length=1;M[j]._parent=void 0,M[j]._length=1;var J0=j>0?M[j-1]:this;if(e<a-1)J0._parent=M[e+1],J0._parent.uncycle(),J0._length=J0._parent._length+1;else J0._parent=void 0,J0._length=1;var H0=J0._length+1;for(var v0=j-2;v0>=0;--v0)M[v0]._length=H0,H0++;return}}},s6.prototype.attachExtraTrace=function(a){if(a.__stackCleaned__)return;this.uncycle();var M=Q4(a),z=M.message,j=[M.stack],x=this;while(x!==void 0)j.push(g0(x.stack.split(`
`))),x=x._parent;N0(j),G1(j),Q.notEnumerableProp(a,"stack",f0(z,j)),Q.notEnumerableProp(a,"__stackCleaned__",!0)};var n5=function(){var M=/^\s*at\s*/,z=function(m,e){if(typeof m==="string")return m;if(e.name!==void 0&&e.message!==void 0)return e.toString();return x$(e)};if(typeof Error.stackTraceLimit==="number"&&typeof Error.captureStackTrace==="function"){Error.stackTraceLimit+=6,X=M,Z=z;var j=Error.captureStackTrace;return V$=function(m){return H.test(m)},function(m,e){Error.stackTraceLimit+=6,j(m,e),Error.stackTraceLimit-=6}}var x=Error();if(typeof x.stack==="string"&&x.stack.split(`
`)[0].indexOf("stackDetection@")>=0)return X=/@/,Z=z,w=!0,function(e){e.stack=Error().stack};var s;try{throw Error()}catch(m){s="stack"in m}if(!("stack"in x)&&s&&typeof Error.stackTraceLimit==="number")return X=M,Z=z,function(e){Error.stackTraceLimit+=6;try{throw Error()}catch(J0){e.stack=J0.stack}Error.stackTraceLimit-=6};return Z=function(m,e){if(typeof m==="string")return m;if((typeof e==="object"||typeof e==="function")&&e.name!==void 0&&e.message!==void 0)return e.toString();return x$(e)},null}([]);if(typeof console<"u"&&typeof console.warn<"u"){if(D=function(a){console.warn(a)},Q.isNode&&process.stderr.isTTY)D=function(a,M){var z=M?"\x1B[33m":"\x1B[31m";console.warn(z+a+`\x1B[0m
`)};else if(!Q.isNode&&typeof Error().stack==="string")D=function(a,M){console.warn("%c"+a,M?"color: darkorange":"color: red")}}var T0={warnings:F,longStackTraces:!1,cancellation:!1,monitoring:!1};if(E)$.longStackTraces();return{longStackTraces:function(){return T0.longStackTraces},warnings:function(){return T0.warnings},cancellation:function(){return T0.cancellation},monitoring:function(){return T0.monitoring},propagateFromFunction:function(){return d},boundValueFunction:function(){return t},checkForgottenReturns:z0,setBounds:L7,warn:w1,deprecated:B0,CapturedTrace:s6,fireDomEvent:v,fireGlobalEvent:u}}});var n20=N((iR1,p20)=>{p20.exports=function($,I){var U=b1(),Y=$.CancellationError,J=U.errorObj;function Q(V,X,Z){this.promise=V,this.type=X,this.handler=Z,this.called=!1,this.cancelPromise=null}Q.prototype.isFinallyHandler=function(){return this.type===0};function K(V){this.finallyHandler=V}K.prototype._resultCancelled=function(){q(this.finallyHandler)};function q(V,X){if(V.cancelPromise!=null){if(arguments.length>1)V.cancelPromise._reject(X);else V.cancelPromise._cancel();return V.cancelPromise=null,!0}return!1}function G(){return W.call(this,this.promise._target()._settledValue())}function H(V){if(q(this,V))return;return J.e=V,J}function W(V){var X=this.promise,Z=this.handler;if(!this.called){this.called=!0;var w=this.isFinallyHandler()?Z.call(X._boundValue()):Z.call(X._boundValue(),V);if(w!==void 0){X._setReturnedNonUndefined();var D=I(w,X);if(D instanceof $){if(this.cancelPromise!=null){if(D._isCancelled()){var O=new Y("late cancellation observer");return X._attachExtraTrace(O),J.e=O,J}else if(D.isPending())D._attachCancellationCallback(new K(this))}return D._then(G,H,void 0,this,void 0)}}}if(X.isRejected())return q(this),J.e=V,J;else return q(this),V}return $.prototype._passThrough=function(V,X,Z,w){if(typeof V!=="function")return this.then();return this._then(Z,w,void 0,new Q(this,X,V),void 0)},$.prototype.lastly=$.prototype.finally=function(V){return this._passThrough(V,0,W,W)},$.prototype.tap=function(V){return this._passThrough(V,1,W)},Q}});var d20=N((pR1,c20)=>{c20.exports=function($){var I=b1(),U=g3().keys,Y=I.tryCatch,J=I.errorObj;function Q(K,q,G){return function(H){var W=G._boundValue();$:for(var V=0;V<K.length;++V){var X=K[V];if(X===Error||X!=null&&X.prototype instanceof Error){if(H instanceof X)return Y(q).call(W,H)}else if(typeof X==="function"){var Z=Y(X).call(W,H);if(Z===J)return Z;else if(Z)return Y(q).call(W,H)}else if(I.isObject(H)){var w=U(X);for(var D=0;D<w.length;++D){var O=w[D];if(X[O]!=H[O])continue $}return Y(q).call(W,H)}}return $}}return Q}});var Kg=N((nR1,o20)=>{var m20=b1(),G31=m20.maybeWrapAsError,H31=C5(),W31=H31.OperationalError,l20=g3();function V31($){return $ instanceof Error&&l20.getPrototypeOf($)===Error.prototype}var Z31=/^(?:name|message|stack|cause)$/;function X31($){var I;if(V31($)){I=new W31($),I.name=$.name,I.message=$.message,I.stack=$.stack;var U=l20.keys($);for(var Y=0;Y<U.length;++Y){var J=U[Y];if(!Z31.test(J))I[J]=$[J]}return I}return m20.markAsOriginatingFromRejection($),$}function L31($,I){return function(U,Y){if($===null)return;if(U){var J=X31(G31(U));$._attachExtraTrace(J),$._reject(J)}else if(!I)$._fulfill(Y);else{var Q=arguments.length,K=Array(Math.max(Q-1,0));for(var q=1;q<Q;++q)K[q-1]=arguments[q];$._fulfill(K)}$=null}}o20.exports=L31});var t20=N((cR1,r20)=>{r20.exports=function($,I,U,Y,J){var Q=b1(),K=Q.tryCatch;$.method=function(q){if(typeof q!=="function")throw new $.TypeError("expecting a function but got "+Q.classString(q));return function(){var G=new $(I);G._captureStackTrace(),G._pushContext();var H=K(q).apply(this,arguments),W=G._popContext();return J.checkForgottenReturns(H,W,"Promise.method",G),G._resolveFromSyncValue(H),G}},$.attempt=$.try=function(q){if(typeof q!=="function")return Y("expecting a function but got "+Q.classString(q));var G=new $(I);G._captureStackTrace(),G._pushContext();var H;if(arguments.length>1){J.deprecated("calling Promise.try with more than 1 argument");var W=arguments[1],V=arguments[2];H=Q.isArray(W)?K(q).apply(V,W):K(q).call(V,W)}else H=K(q)();var X=G._popContext();return J.checkForgottenReturns(H,X,"Promise.try",G),G._resolveFromSyncValue(H),G},$.prototype._resolveFromSyncValue=function(q){if(q===Q.errorObj)this._rejectCallback(q.e,!1);else this._resolveCallback(q,!0)}}});var s20=N((dR1,a20)=>{a20.exports=function($,I,U,Y){var J=!1,Q=function(H,W){this._reject(W)},K=function(H,W){W.promiseRejectionQueued=!0,W.bindingPromise._then(Q,Q,null,this,H)},q=function(H,W){if((this._bitField&50397184)===0)this._resolveCallback(W.target)},G=function(H,W){if(!W.promiseRejectionQueued)this._reject(H)};$.prototype.bind=function(H){if(!J)J=!0,$.prototype._propagateFrom=Y.propagateFromFunction(),$.prototype._boundValue=Y.boundValueFunction();var W=U(H),V=new $(I);V._propagateFrom(this,1);var X=this._target();if(V._setBoundTo(W),W instanceof $){var Z={promiseRejectionQueued:!1,promise:V,target:X,bindingPromise:W};X._then(I,K,voi Line truncated
See http://goo.gl/MqrFmX
`);return this._settledValue()},Y=I.prototype.error=I.prototype.reason=function(){if(!this.isRejected())throw TypeError(`cannot get rejection reason of a non-rejected promise
See http://goo.gl/MqrFmX
`);return this._settledValue()},J=I.prototype.isFulfilled=function(){return(this._bitField&33554432)!==0},Q=I.prototype.isRejected=function(){return(this._bitField&16777216)!==0},K=I.prototype.isPending=function(){return(this._bitField&50397184)===0},q=I.prototype.isResolved=function(){return(this._bitField&50331648)!==0};I.prototype.isCancelled=function(){return(this._bitField&8454144)!==0},$.prototype.__isCancelled=function(){return(this._bitField&65536)===65536},$.prototype._isCancelled=function(){return this._target().__isCancelled()},$.prototype.isCancelled=function(){return(this._target()._bitField&8454144)!==0},$.prototype.isPending=function(){return K.call(this._target())},$.prototype.isRejected=function(){return Q.call(this._target())},$.prototype.isFulfilled=function(){return J.call(this._target())},$.prototype.isResolved=function(){return q.call(this._target())},$.prototype.value=function(){return U.call(this._target())},$.prototype.reason=function(){var G=this._target();return G._unsetRejectionIsUnhandled(),Y.call(G)},$.prototype._value=function(){return this._settledValue()},$.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},$.PromiseInspection=I}});var KK0=N((rR1,QK0)=>{QK0.exports=function($,I,U,Y,J,Q){var K=b1(),q=K.canEvaluate,G=K.tryCatch,H=K.errorObj,W;if(q){var V=function(E){return Function("value","holder",`
'use strict';
holder.pIndex = value;
holder.checkFulfillment(this);
`.replace(/Index/g,E))},X=function(E){return Function("promise","holder",`
'use strict';
holder.pIndex = promise;
`.replace(/Index/g,E))},Z=function(E){var A=Array(E);for(var T=0;T<A.length;++T)A[T]="this.p"+(T+1);var v=A.join(" = ")+" = null;",u=`var promise;
`+A.map(function(n){return`
promise = `+n+`;
if (promise instanceof Promise) {
promise.cancel();
}
`}).join(`
`),g=A.join(", "),b="Holder$"+E,C=`return function(tryCatch, errorObj, Promise, async) {
'use strict';
function [TheName](fn) {
[TheProperties]
this.fn = fn;
this.asyncNeeded = true;
this.now = 0;
}
[TheName].prototype._callFunction = function(promise) {
promise._pushContext();
var ret = tryCatch(this.fn)([ThePassedArguments]);
promise._popContext();
if (ret === errorObj) {
promise._rejectCallback(ret.e, false);
} else {
promise._resolveCallback(ret);
}
};
[TheName].prototype.checkFulfillment = function(promise) {
var now = ++this.now;
if (now === [TheTotal]) {
if (this.asyncNeeded) {
async.invoke(this._callFunction, this, promise);
} else {
this._callFunction(promise);
}
}
};
[TheName].prototype._resultCancelled = function() {
[CancellationCode]
};
return [TheName];
}(tryCatch, errorObj, Promise, async);
`;return C=C.replace(/\[TheName\]/g,b).replace(/\[TheTotal\]/g,E).replace(/\[ThePassedArguments\]/g,g).replace(/\[TheProperties\]/g,v).replace(/\[CancellationCode\]/g,u),Function("tryCatch","errorObj","Promise","async",C)(G,H,$,J)},w=[],D=[],O=[];for(var F=0;F<8;++F)w.push(Z(F+1)),D.push(V(F+1)),O.push(X(F+1));W=function(E){this._reject(E)}}$.join=function(){var E=arguments.length-1,A;if(E>0&&typeof arguments[E]==="function"){if(A=arguments[E],E<=8&&q){var i=new $(Y);i._captureStackTrace();var T=w[E-1],v=new T(A),u=D;for(var g=0;g<E;++g){var b=U(arguments[g],i);if(b instanceof $){b=b._target();var C=b._bitField;if((C&50397184)===0)b._then(u[g],W,void 0,i,v),O[g](b,v),v.asyncNeeded=!1;else if((C&33554432)!==0)u[g].call(i,b._value(),v);else if((C&16777216)!==0)i._reject(b._reason());else i._cancel()}else u[g].call(i,b,v)}if(!i._isFateSealed()){if(v.asyncNeeded){var n=Q();if(n!==null)v.fn=K.domainBind(n,v.fn)}i._setAsyncGuaranteed(),i._setOnCancel(v)}return i}}var p=arguments.length,S=Array(p);for(var f=0;f<p;++f)S[f]=arguments[f];if(A)S.pop();var i=new I(S).promise();return A!==void 0?i.spread(A):i}}});var GK0=N((tR1,qK0)=>{qK0.exports=function($,I,U,Y,J,Q){var K=$._getDomain,q=b1(),G=q.tryCatch,H=q.errorObj,W=$._async;function V(Z,w,D,O){this.constructor$(Z),this._promise._captureStackTrace();var F=K();this._callback=F===null?w:q.domainBind(F,w),this._preservedValues=O===J?Array(this.length()):null,this._limit=D,this._inFlight=0,this._queue=[],W.invoke(this._asyncInit,this,void 0)}q.inherits(V,I),V.prototype._asyncInit=function(){this._init$(void 0,-2)},V.prototype._init=function(){},V.prototype._promiseFulfilled=function(Z,w){var D=this._values,O=this.length(),F=this._preservedValues,E=this._limit;if(w<0){if(w=w*-1-1,D[w]=Z,E>=1){if(this._inFlight--,this._drainQueue(),this._isResolved())return!0}}else{if(E>=1&&this._inFlight>=E)return D[w]=Z,this._queue.push(w),!1;if(F!==null)F[w]=Z;var A=this._promise,T=this._callback,v=A._boundValue();A._pushContext();var u=G(T).call(v,Z,w,O),g=A._popContext();if(Q.checkForgottenReturns(u,g,F!==null?"Promise.filter":"Promise.map",A),u===H)return this._reject(u.e),!0;var b=Y(u,this._promise);if(b instanceof $){b=b._target();var C=b._bitField;if((C&50397184)===0){if(E>=1)this._inFlight++;return D[w]=b,b._proxy(this,(w+1)*-1),!1}else if((C&33554432)!==0)u=b._value();else if((C&16777216)!==0)return this._reject(b._reason()),!0;else return this._cancel(),!0}D[w]=u}var n=++this._totalResolved;if(n>=O){if(F!==null)this._filter(D,F);else this._resolve(D);return!0}return!1},V.prototype._drainQueue=function(){var Z=this._queue,w=this._limit,D=this._values;while(Z.length>0&&this._inFlight<w){if(this._isResolved())return;var O=Z.pop();this._promiseFulfilled(D[O],O)}},V.prototype._filter=function(Z,w){var D=w.length,O=Array(D),F=0;for(var E=0;E<D;++E)if(Z[E])O[F++]=w[E];O.length=F,this._resolve(O)},V.prototype.preservedValues=function(){return this._preservedValues};function X(Z,w,D,O){if(typeof w!=="function")return U("expecting a function but got "+q.classString(w));var F=0;if(D!==void 0)if(typeof D==="object"&&D!==null){if(typeof D.concurrency!=="number")return $.reject(TypeError("'concurrency' must be a number but it is "+q.classString(D.concurrency)));F=D.concurrency}else return $.reject(TypeError("options argument must be an object but it is "+q.classString(D)));return F=typeof F==="number"&&isFinite(F)&&F>=1?F:0,new V(Z,w,F,O).promise()}$.prototype.map=function(Z,w){return X(this,Z,w,null)},$.map=function(Z,w,D,O){return X(Z,w,D,O)}}});var WK0=N((aR1,HK0)=>{var qg=Object.create;if(qg)Rw=qg(null),vw=qg(null),Rw[" size"]=vw[" size"]=0;var Rw,vw;HK0.exports=function($){var I=b1(),U=I.canEvaluate,Y=I.isIdentifier,J,Q,K=function(Z){return Function("ensureMethod",`
return function(obj) {
'use strict'
var len = this.length;
ensureMethod(obj, 'methodName');
switch(len) {
case 1: return obj.methodName(this[0]);
case 2: return obj.methodName(this[0], this[1]);
case 3: return obj.methodName(this[0], this[1], this[2]);
case 0: return obj.methodName();
default:
return obj.methodName.apply(obj, this);
}
};
`.replace(/methodName/g,Z))(H)},q=function(Z){return Function("obj",`
'use strict';
return obj.propertyName;
`.replace("propertyName",Z))},G=function(Z,w,D){var O=D[Z];if(typeof O!=="function"){if(!Y(Z))return null;if(O=w(Z),D[Z]=O,D[" size"]++,D[" size"]>512){var F=Object.keys(D);for(var E=0;E<256;++E)delete D[F[E]];D[" size"]=F.length-256}}return O};J=function(Z){return G(Z,K,Rw)},Q=function(Z){return G(Z,q,vw)};function H(Z,w){var D;if(Z!=null)D=Z[w];if(typeof D!=="function"){var O="Object "+I.classString(Z)+" has no method '"+I.toString(w)+"'";throw new $.TypeError(O)}return D}function W(Z){var w=this.pop(),D=H(Z,w);return D.apply(Z,this)}$.prototype.call=function(Z){var w=arguments.length,D=Array(Math.max(w-1,0));for(var O=1;O<w;++O)D[O-1]=arguments[O];if(U){var F=J(Z);if(F!==null)return this._then(F,void 0,void 0,D,void 0)}return D.push(Z),this._then(W,void 0,void 0,D,void 0)};function V(Z){return Z[this]}function X(Z){var w=+this;if(w<0)w=Math.max(0,w+Z.length);return Z[w]}$.prototype.get=function(Z){var w=typeof Z==="number",D;if(!w)if(U){var O=Q(Z);D=O!==null?O:V}else D=V;else D=X;return this._then(D,void 0,void 0,Z,void 0)}}});var ZK0=N((sR1,VK0)=>{VK0.exports=function($,I,U,Y,J,Q){var K=b1(),q=C5().TypeError,G=b1().inherits,H=K.errorObj,W=K.tryCatch,V={};function X(A){setTimeout(function(){throw A},0)}function Z(A){var T=U(A);if(T!==A&&typeof A._isDisposable==="function"&&typeof A._getDisposer==="function"&&A._isDisposable())T._setDisposable(A._getDisposer());return T}function w(A,T){var v=0,u=A.length,g=new $(J);function b(){if(v>=u)return g._fulfill();var C=Z(A[v++]);if(C instanceof $&&C._isDisposable()){try{C=U(C._getDisposer().tryDispose(T),A.promise)}catch(n){return X(n)}if(C instanceof $)return C._then(b,X,null,null,null)}b()}return b(),g}function D(A,T,v){this._data=A,this._promise=T,this._context=v}D.prototype.data=function(){return this._data},D.prototype.promise=function(){return this._promise},D.prototype.resource=function(){if(this.promise().isFulfilled())return this.promise().value();return V},D.prototype.tryDispose=function(A){var T=this.resource(),v=this._context;if(v!==void 0)v._pushContext();var u=T!==V?this.doDispose(T,A):null;if(v!==void 0)v._popContext();return this._promise._unsetDisposable(),this._data=null,u},D.isDisposer=function(A){return A!=null&&typeof A.resource==="function"&&typeof A.tryDispose==="function"};function O(A,T,v){this.constructor$(A,T,v)}G(O,D),O.prototype.doDispose=function(A,T){var v=this.data();return v.call(A,A,T)};function F(A){if(D.isDisposer(A))return this.resources[this.index]._setDisposable(A),A.promise();return A}function E(A){this.length=A,this.promise=null,this[A-1]=null}E.prototype._resultCancelled=function(){var A=this.length;for(var T=0;T<A;++T){var v=this[T];if(v instanceof $)v.cancel()}},$.using=function(){var A=arguments.length;if(A<2)return I("you must pass at least 2 arguments to Promise.using");var T=arguments[A-1];if(typeof T!=="function")return I("expecting a function but got "+K.classString(T));var v,u=!0;if(A===2&&Array.isArray(arguments[0]))v=arguments[0],A=v.length,u=!1;else v=arguments,A--;var g=new E(A);for(var b=0;b<A;++b){var C=v[b];if(D.isDisposer(C)){var n=C;C=C.promise(),C._setDisposable(n)}else{var p=U(C);if(p instanceof $)C=p._then(F,null,null,{resources:g,index:b},void 0)}g[b]=C}var S=Array(g.length);for(var b=0;b<S.length;++b)S[b]=$.resolve(g[b]).reflect();var f=$.all(S).then(function(Y0){for(var B=0;B<Y0.length;++B){var k=Y0[B];if(k.isRejected())return H.e=k.error(),H;else if(!k.isFulfilled()){f.cancel();return}Y0[B]=k.value()}i._pushContext(),T=W(T);var d=u?T.apply(void 0,Y0):T(Y0),t=i._popContext();return Q.checkForgottenReturns(d,t,"Promise.using",i),d}),i=f.lastly(function(){var Y0=new $.PromiseInspection(f);return w(g,Y0)});return g.promise=i,i._setOnCancel(g),i},$.prototype._setDisposable=function(A){this._bitField=this._bitField|131072,this._disposer=A},$.prototype._isDisposable=function(){return(this._bitField&131072)>0},$.prototype._getDisposer=function(){return this._disposer},$.prototype._unsetDisposable=function(){this._bitField=this._bitField&-131073,this._disposer=void 0},$.prototype.disposer=function(A){if(typeof A==="function")return new O(A,this,Y());throw new q}}});var LK0=N((eR1,XK0)=>{XK0.exports=function($,I,U){var Y=b1(),J=$.TimeoutError;function Q(V){this.handle=V}Q.prototype._resultCancelled=function(){clearTimeout(this.handle)};var K=function(V){return q(+this).thenReturn(V)},q=$.delay=function(V,X){var Z,w;if(X!==void 0){if(Z=$.resolve(X)._then(K,null,null,V,void 0),U.cancellation()&&X instanceof $)Z._setOnCancel(X)}else{if(Z=new $(I),w=setTimeout(function(){Z._fulfill()},+V),U.cancellation())Z._setOnCancel(new Q(w));Z._captureStackTrace()}return Z._setAsyncGuaranteed(),Z};$.prototype.delay=function(V){return q(V,this)};var G=function(V,X,Z){var w;if(typeof X!=="string")if(X instanceof Error)w=X;else w=new J("operation timed out");else w=new J(X);if(Y.markAsOriginatingFromRejection(w),V._attachExtraTrace(w),V._reject(w),Z!=null)Z.cancel()};function H(V){return clearTimeout(this.handle),V}f Line truncated
See http://goo.gl/MqrFmX
`.replace("%s",O)+`From coroutine:
`+this._stack.split(`
`).slice(1,-7).join(`
`)));return}}F=F._target();var E=F._bitField;if((E&50397184)===0)this._yieldedPromise=F,F._proxy(this,null);else if((E&33554432)!==0)$._async.invoke(this._promiseFulfilled,this,F._value());else if((E&16777216)!==0)$._async.invoke(this._promiseRejected,this,F._reason());else this._promiseCancelled()}},$.coroutine=function(w,D){if(typeof w!=="function")throw new q(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var O=Object(D).yieldHandler,F=Z,E=Error().stack;return function(){var A=w.apply(this,arguments),T=new F(void 0,void 0,O,E),v=T.promise();return T._generator=A,T._promiseFulfilled(void 0),v}},$.coroutine.addYieldHandler=function(w){if(typeof w!=="function")throw new q("expecting a function but got "+G.classString(w));V.push(w)},$.spawn=function(w){if(Q.deprecated("Promise.spawn()","Promise.coroutine()"),typeof w!=="function")return I(`generatorFunction must be a function
See http://goo.gl/MqrFmX
`);var D=new Z(w,this),O=D.promise();return D._run($.spawn),O}}});var NK0=N((Iv1,OK0)=>{OK0.exports=function($){var I=b1(),U=$._async,Y=I.tryCatch,J=I.errorObj;function Q(G,H){var W=this;if(!I.isArray(G))return K.call(W,G,H);var V=Y(H).apply(W._boundValue(),[null].concat(G));if(V===J)U.throwLater(V.e)}function K(G,H){var W=this,V=W._boundValue(),X=G===void 0?Y(H).call(V,null):Y(H).call(V,null,G);if(X===J)U.throwLater(X.e)}function q(G,H){var W=this;if(!G){var V=Error(G+"");V.cause=G,G=V}var X=Y(H).call(W._boundValue(),G);if(X===J)U.throwLater(X.e)}$.prototype.asCallback=$.prototype.nodeify=function(G,H){if(typeof G=="function"){var W=K;if(H!==void 0&&Object(H).spread)W=Q;this._then(W,q,void 0,this,G)}return this}}});var MK0=N((Uv1,FK0)=>{FK0.exports=function($,I){var U={},Y=b1(),J=Kg(),Q=Y.withAppended,K=Y.maybeWrapAsError,q=Y.canEvaluate,G=C5().TypeError,H="Async",W={__isPromisified__:!0},V=["arity","length","name","arguments","caller","callee","prototype","__isPromisified__"],X=new RegExp("^(?:"+V.join("|")+")$"),Z=function(f){return Y.isIdentifier(f)&&f.charAt(0)!=="_"&&f!=="constructor"};function w(f){return!X.test(f)}function D(f){try{return f.__isPromisified__===!0}catch(i){return!1}}function O(f,i,Y0){var B=Y.getDataPropertyOrDefault(f,i+Y0,W);return B?D(B):!1}function F(f,i,Y0){for(var B=0;B<f.length;B+=2){var k=f[B];if(Y0.test(k)){var d=k.replace(Y0,"");for(var t=0;t<f.length;t+=2)if(f[t]===d)throw new G(`Cannot promisify an API that has normal methods with '%s'-suffix
See http://goo.gl/MqrFmX
`.replace("%s",i))}}}function E(f,i,Y0,B){var k=Y.inheritedDataKeys(f),d=[];for(var t=0;t<k.length;++t){var K0=k[t],W0=f[K0],z0=B===Z?!0:Z(K0,W0,f);if(typeof W0==="function"&&!D(W0)&&!O(f,K0,i)&&B(K0,W0,f,z0))d.push(K0,W0)}return F(d,i,Y0),d}var A=function(f){return f.replace(/([$])/,"\\$")},T,v=function(f){var i=[f],Y0=Math.max(0,f-1-3);for(var B=f-1;B>=Y0;--B)i.push(B);for(var B=f+1;B<=3;++B)i.push(B);return i},u=function(f){return Y.filledRange(f,"_arg","")},g=function(f){return Y.filledRange(Math.max(f,3),"_arg","")},b=function(f){if(typeof f.length==="number")return Math.max(Math.min(f.length,1024),0);return 0};T=function(f,i,Y0,B,k,d){var t=Math.max(0,b(B)-1),K0=v(t),W0=typeof f==="string"||i===U;function z0(G1){var N0=u(G1).join(", "),g0=G1>0?", ":"",d0;if(W0)d0=`ret = callback.call(this, {{args}}, nodeback); break;
`;else d0=i===void 0?`ret = callback({{args}}, nodeback); break;
`:`ret = callback.call(receiver, {{args}}, nodeback); break;
`;return d0.replace("{{args}}",N0).replace(", ",g0)}function B0(){var G1="";for(var N0=0;N0<K0.length;++N0)G1+="case "+K0[N0]+":"+z0(K0[N0]);return G1+=`
default:
var args = new Array(len + 1);
var i = 0;
for (var i = 0; i < len; ++i) {
args[i] = arguments[i];
}
args[i] = nodeback;
[CodeForCall]
break;
`.replace("[CodeForCall]",W0?`ret = callback.apply(this, args);
`:`ret = callback.apply(receiver, args);
`),G1}var w1=typeof f==="string"?"this != null ? this['"+f+"'] : fn":"fn",f0=`'use strict';
var ret = function (Parameters) {
'use strict';
var len = arguments.length;
var promise = new Promise(INTERNAL);
promise._captureStackTrace();
var nodeback = nodebackForPromise(promise, `+d+`);
var ret;
var callback = tryCatch([GetFunctionCode]);
switch(len) {
[CodeForSwitchCase]
}
if (ret === errorObj) {
promise._rejectCallback(maybeWrapAsError(ret.e), true, true);
}
if (!promise._isFateSealed()) promise._setAsyncGuaranteed();
return promise;
};
notEnumerableProp(ret, '__isPromisified__', true);
return ret;
`.replace("[CodeForSwitchCase]",B0()).replace("[GetFunctionCode]",w1);return f0=f0.replace("Parameters",g(t)),Function("Promise","fn","receiver","withAppended","maybeWrapAsError","nodebackForPromise","tryCatch","errorObj","notEnumerableProp","INTERNAL",f0)($,B,i,Q,K,J,Y.tryCatch,Y.errorObj,Y.notEnumerableProp,I)};function C(f,i,Y0,B,k,d){var t=function(){return this}(),K0=f;if(typeof K0==="string")f=B;function W0(){var z0=i;if(i===U)z0=this;var B0=new $(I);B0._captureStackTrace();var w1=typeof K0==="string"&&this!==t?this[K0]:f,f0=J(B0,d);try{w1.apply(z0,Q(arguments,f0))}catch(G1){B0._rejectCallback(K(G1),!0,!0)}if(!B0._isFateSealed())B0._setAsyncGuaranteed();return B0}return Y.notEnumerableProp(W0,"__isPromisified__",!0),W0}var n=q?T:C;function p(f,i,Y0,B,k){var d=new RegExp(A(i)+"$"),t=E(f,i,d,Y0);for(var K0=0,W0=t.length;K0<W0;K0+=2){var z0=t[K0],B0=t[K0+1],w1=z0+i;if(B===n)f[w1]=n(z0,U,z0,B0,i,k);else{var f0=B(B0,function(){return n(z0,U,z0,B0,i,k)});Y.notEnumerableProp(f0,"__isPromisified__",!0),f[w1]=f0}}return Y.toFastProperties(f),f}function S(f,i,Y0){return n(f,i,void 0,f,null,Y0)}$.promisify=function(f,i){if(typeof f!=="function")throw new G("expecting a function but got "+Y.classString(f));if(D(f))return f;i=Object(i);var Y0=i.context===void 0?U:i.context,B=!!i.multiArgs,k=S(f,Y0,B);return Y.copyDescriptors(f,k,w),k},$.promisifyAll=function(f,i){if(typeof f!=="function"&&typeof f!=="object")throw new G(`the target of promisifyAll must be an object or a function
See http://goo.gl/MqrFmX
`);i=Object(i);var Y0=!!i.multiArgs,B=i.suffix;if(typeof B!=="string")B=H;var k=i.filter;if(typeof k!=="function")k=Z;var d=i.promisifier;if(typeof d!=="function")d=n;if(!Y.isIdentifier(B))throw RangeError(`suffix must be a valid identifier
See http://goo.gl/MqrFmX
`);var t=Y.inheritedDataKeys(f);for(var K0=0;K0<t.length;++K0){var W0=f[t[K0]];if(t[K0]!=="constructor"&&Y.isClass(W0))p(W0.prototype,B,k,d,Y0),p(W0,B,k,d,Y0)}return p(f,B,k,d,Y0)}}});var AK0=N((Yv1,zK0)=>{zK0.exports=function($,I,U,Y){var J=b1(),Q=J.isObject,K=g3(),q;if(typeof Map==="function")q=Map;var G=function(){var X=0,Z=0;function w(D,O){this[X]=D,this[X+Z]=O,X++}return function(O){Z=O.size,X=0;var F=Array(O.size*2);return O.forEach(w,F),F}}(),H=function(X){var Z=new q,w=X.length/2|0;for(var D=0;D<w;++D){var O=X[w+D],F=X[D];Z.set(O,F)}return Z};function W(X){var Z=!1,w;if(q!==void 0&&X instanceof q)w=G(X),Z=!0;else{var D=K.keys(X),O=D.length;w=Array(O*2);for(var F=0;F<O;++F){var E=D[F];w[F]=X[E],w[F+O]=E}}this.constructor$(w),this._isMap=Z,this._init$(void 0,-3)}J.inherits(W,I),W.prototype._init=function(){},W.prototype._promiseFulfilled=function(X,Z){this._values[Z]=X;var w=++this._totalResolved;if(w>=this._length){var D;if(this._isMap)D=H(this._values);else{D={};var O=this.length();for(var F=0,E=this.length();F<E;++F)D[this._values[F+O]]=this._values[F]}return this._resolve(D),!0}return!1},W.prototype.shouldCopyValues=function(){return!1},W.prototype.getActualLength=function(X){return X>>1};function V(X){var Z,w=U(X);if(!Q(w))return Y(`cannot await properties of a non-object
See http://goo.gl/MqrFmX
`);else if(w instanceof $)Z=w._then($.props,void 0,void 0,void 0,void 0);else Z=new W(w).promise();if(w instanceof $)Z._propagateFrom(w,2);return Z}$.prototype.props=function(){return V(this)},$.props=function(X){return V(X)}}});var TK0=N((Jv1,PK0)=>{PK0.exports=function($,I,U,Y){var J=b1(),Q=function(q){return q.then(function(G){return K(G,q)})};function K(q,G){var H=U(q);if(H instanceof $)return Q(H);else if(q=J.asArray(q),q===null)return Y("expecting an array or an iterable object but got "+J.classString(q));var W=new $(I);if(G!==void 0)W._propagateFrom(G,3);var{_fulfill:V,_reject:X}=W;for(var Z=0,w=q.length;Z<w;++Z){var D=q[Z];if(D===void 0&&!(Z in q))continue;$.cast(D)._then(V,X,void 0,W,null)}return W}$.race=function(q){return K(q,void 0)},$.prototype.race=function(){return K(this,void 0)}}});var BK0=N((Qv1,EK0)=>{EK0.exports=function($,I,U,Y,J,Q){var K=$._getDomain,q=b1(),G=q.tryCatch;function H(w,D,O,F){this.constructor$(w);var E=K();if(this._fn=E===null?D:q.domainBind(E,D),O!==void 0)O=$.resolve(O),O._attachCancellationCallback(this);if(this._initialValue=O,this._currentCancellable=null,F===J)this._eachValues=Array(this._length);else if(F===0)this._eachValues=null;else this._eachValues=void 0;this._promise._captureStackTrace(),this._init$(void 0,-5)}q.inherits(H,I),H.prototype._gotAccum=function(w){if(this._eachValues!==void 0&&this._eachValues!==null&&w!==J)this._eachValues.push(w)},H.prototype._eachComplete=function(w){if(this._eachValues!==null)this._eachValues.push(w);return this._eachValues},H.prototype._init=function(){},H.prototype._resolveEmptyArray=function(){this._resolve(this._eachValues!==void 0?this._eachValues:this._initialValue)},H.prototype.shouldCopyValues=function(){return!1},H.prototype._resolve=function(w){this._promise._resolveCallback(w),this._values=null},H.prototype._resultCancelled=function(w){if(w===this._initialValue)return this._cancel();if(this._isResolved())return;if(this._resultCancelled$(),this._currentCancellable instanceof $)this._currentCancellable.cancel();if(this._initialValue instanceof $)this._initialValue.cancel()},H.prototype._iterate=function(w){this._values=w;var D,O,F=w.length;if(this._initialValue!==void 0)D=this._initialValue,O=0;else D=$.resolve(w[0]),O=1;if(this._currentCancellable=D,!D.isRejected())for(;O<F;++O){var E={accum:null,value:w[O],index:O,length:F,array:this};D=D._then(X,void 0,void 0,E,void 0)}if(this._eachValues!==void 0)D=D._then(this._eachComplete,void 0,void 0,this,void 0);D._then(W,W,void 0,D,this)},$.prototype.reduce=function(w,D){return V(this,w,D,null)},$.reduce=function(w,D,O,F){return V(w,D,O,F)};function W(w,D){if(this.isFulfilled())D._resolve(w);else D._reject(w)}function V(w,D,O,F){if(typeof D!=="function")return U("expecting a function but got "+q.classString(D));var E=new H(w,D,O,F);return E.promise()}function X(w){this.accum=w,this.array._gotAccum(w);var D=Y(this.value,this.array._promise);if(D instanceof $)return this.array._currentCancellable=D,D._then(Z,void 0,void 0,this,void 0);else return Z.call(this,D)}function Z(w){var D=this.array,O=D._promise,F=G(D._fn);O._pushContext();var E;if(D._eachValues!==void 0)E=F.call(O._boundValue(),w,this.index,this.length);else E=F.call(O._boundValue(),this.accum,w,this.index,this.length);if(E instanceof $)D._currentCancellable=E;var A=O._popContext();return Q.checkForgottenReturns(E,A,D._eachValues!==void 0?"Promise.each":"Promise.reduce",O),E}}});var vK0=N((Kv1,RK0)=>{RK0.exports=function($,I,U){var Y=$.PromiseInspection,J=b1();function Q(K){this.constructor$(K)}J.inherits(Q,I),Q.prototype._promiseResolved=function(K,q){this._values[K]=q;var G=++this._totalResolved;if(G>=this._length)return this._resolve(this._values),!0;return!1},Q.prototype._promiseFulfilled=function(K,q){var G=new Y;return G._bitField=33554432,G._settledValueField=K,this._promiseResolved(q,G)},Q.prototype._promiseRejected=function(K,q){var G=new Y;return G._bitField=16777216,G._settledValueField=K,this._promiseResolved(q,G)},$.settle=function(K){return U.deprecated(".settle()",".reflect()"),new Q(K).promise()},$.prototype.settle=function(){return $.settle(this)}}});var jK0=N((qv1,CK0)=>{CK0.exports=function($,I,U){var Y=b1(),J=C5().RangeError,Q=C5().AggregateError,K=Y.isArray,q={};function G(W){this.constructor$(W),this._howMany=0,this._unwrap=!1,this._initialized=!1}Y.inherits(G,I),G.prototype._init=function(){if(!this._initialized)return;if(this._howMany===0){this._resolve([]);return}this._init$(void 0,-5);var W=K(this._values);if(!this._isResolved()&&W&&this._howMany>this._canPossiblyFulfill())this._reject(this._getRangeError(this.length()))},G.prototype.init=function(){this._initialized=!0,this._init()},G.prototype.setUnwrap=function(){this._unwrap=!0},G.prototype.howMany=function(){return this._howMany},G.prototype.setHowMany=function(W){this._howMany=W},G.prototype._promiseFulfilled=function(W){if(this._addFulfilled(W),this._fulfilled()===this.howMany()){if(this._values.length=this.howMany(),this.howMany()= Line truncated
See http://goo.gl/MqrFmX
`);var X=new G(W),Z=X.promise();return X.setHowMany(V),X.init(),Z}$.some=function(W,V){return H(W,V)},$.prototype.some=function(W){return H(this,W)},$._SomePromiseArray=G}});var SK0=N((Gv1,_K0)=>{_K0.exports=function($,I){var U=$.map;$.prototype.filter=function(Y,J){return U(this,Y,J,I)},$.filter=function(Y,J,Q){return U(Y,J,Q,I)}}});var yK0=N((Hv1,gK0)=>{gK0.exports=function($,I){var{reduce:U,all:Y}=$;function J(){return Y(this)}function Q(K,q){return U(K,q,I,I)}$.prototype.each=function(K){return U(this,K,I,0)._then(J,void 0,void 0,this,void 0)},$.prototype.mapSeries=function(K){return U(this,K,I,I)},$.each=function(K,q){return U(K,q,I,0)._then(J,void 0,void 0,K,void 0)},$.mapSeries=Q}});var xK0=N((Wv1,hK0)=>{hK0.exports=function($){var I=$._SomePromiseArray;function U(Y){var J=new I(Y),Q=J.promise();return J.setHowMany(1),J.setUnwrap(),J.init(),Q}$.any=function(Y){return U(Y)},$.prototype.any=function(){return U(this)}}});var kK0=N((Vv1,Gg)=>{Gg.exports=function(){var $=function(){return new V(`circular promise resolution chain
See http://goo.gl/MqrFmX
`)},I=function(){return new S.PromiseInspection(this._target())},U=function(B){return S.reject(new V(B))};function Y(){}var J={},Q=b1(),K;if(Q.isNode)K=function(){var B=process.domain;if(B===void 0)B=null;return B};else K=function(){return null};Q.notEnumerableProp(S,"_getDomain",K);var q=g3(),G=j20(),H=new G;q.defineProperty(S,"_async",{value:H});var W=C5(),V=S.TypeError=W.TypeError;S.RangeError=W.RangeError;var X=S.CancellationError=W.CancellationError;S.TimeoutError=W.TimeoutError,S.OperationalError=W.OperationalError,S.RejectionError=W.OperationalError,S.AggregateError=W.AggregateError;var Z=function(){},w={},D={},O=h20()(S,Z),F=k20()(S,Z,O,U,Y),E=f20()(S),A=E.create,T=i20()(S,E),v=T.CapturedTrace,u=n20()(S,O),g=d20()(D),b=Kg(),C=Q.errorObj,n=Q.tryCatch;function p(B,k){if(typeof k!=="function")throw new V("expecting a function but got "+Q.classString(k));if(B.constructor!==S)throw new V(`the promise constructor cannot be invoked directly
See http://goo.gl/MqrFmX
`)}function S(B){if(this._bitField=0,this._fulfillmentHandler0=void 0,this._rejectionHandler0=void 0,this._promise0=void 0,this._receiver0=void 0,B!==Z)p(this,B),this._resolveFromExecutor(B);this._promiseCreated(),this._fireEvent("promiseCreated",this)}S.prototype.toString=function(){return"[object Promise]"},S.prototype.caught=S.prototype.catch=function(B){var k=arguments.length;if(k>1){var d=Array(k-1),t=0,K0;for(K0=0;K0<k-1;++K0){var W0=arguments[K0];if(Q.isObject(W0))d[t++]=W0;else return U("expecting an object but got A catch statement predicate "+Q.classString(W0))}return d.length=t,B=arguments[K0],this.then(void 0,g(d,B,this))}return this.then(void 0,B)},S.prototype.reflect=function(){return this._then(I,I,void 0,this,void 0)},S.prototype.then=function(B,k){if(T.warnings()&&arguments.length>0&&typeof B!=="function"&&typeof k!=="function"){var d=".then() only accepts functions but was passed: "+Q.classString(B);if(arguments.length>1)d+=", "+Q.classString(k);this._warn(d)}return this._then(B,k,void 0,void 0,void 0)},S.prototype.done=function(B,k){var d=this._then(B,k,void 0,void 0,void 0);d._setIsFinal()},S.prototype.spread=function(B){if(typeof B!=="function")return U("expecting a function but got "+Q.classString(B));return this.all()._then(B,void 0,void 0,w,void 0)},S.prototype.toJSON=function(){var B={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};if(this.isFulfilled())B.fulfillmentValue=this.value(),B.isFulfilled=!0;else if(this.isRejected())B.rejectionReason=this.reason(),B.isRejected=!0;return B},S.prototype.all=function(){if(arguments.length>0)this._warn(".all() was passed arguments but it does not take any");return new F(this).promise()},S.prototype.error=function(B){return this.caught(Q.originatesFromRejection,B)},S.getNewLibraryCopy=Gg.exports,S.is=function(B){return B instanceof S},S.fromNode=S.fromCallback=function(B){var k=new S(Z);k._captureStackTrace();var d=arguments.length>1?!!Object(arguments[1]).multiArgs:!1,t=n(B)(b(k,d));if(t===C)k._rejectCallback(t.e,!0);if(!k._isFateSealed())k._setAsyncGuaranteed();return k},S.all=function(B){return new F(B).promise()},S.cast=function(B){var k=O(B);if(!(k instanceof S))k=new S(Z),k._captureStackTrace(),k._setFulfilled(),k._rejectionHandler0=B;return k},S.resolve=S.fulfilled=S.cast,S.reject=S.rejected=function(B){var k=new S(Z);return k._captureStackTrace(),k._rejectCallback(B,!0),k},S.setScheduler=function(B){if(typeof B!=="function")throw new V("expecting a function but got "+Q.classString(B));return H.setScheduler(B)},S.prototype._then=function(B,k,d,t,K0){var W0=K0!==void 0,z0=W0?K0:new S(Z),B0=this._target(),w1=B0._bitField;if(!W0){if(z0._propagateFrom(this,3),z0._captureStackTrace(),t===void 0&&(this._bitField&2097152)!==0)if((w1&50397184)!==0)t=this._boundValue();else t=B0===this?void 0:this._boundTo;this._fireEvent("promiseChained",this,z0)}var f0=K();if((w1&50397184)!==0){var G1,N0,g0=B0._settlePromiseCtx;if((w1&33554432)!==0)N0=B0._rejectionHandler0,G1=B;else if((w1&16777216)!==0)N0=B0._fulfillmentHandler0,G1=k,B0._unsetRejectionIsUnhandled();else g0=B0._settlePromiseLateCancellationObserver,N0=new X("late cancellation observer"),B0._attachExtraTrace(N0),G1=k;H.invoke(g0,B0,{handler:f0===null?G1:typeof G1==="function"&&Q.domainBind(f0,G1),promise:z0,receiver:t,value:N0})}else B0._addCallbacks(B,k,z0,t,f0);return z0},S.prototype._length=function(){return this._bitField&65535},S.prototype._isFateSealed=function(){return(this._bitField&117506048)!==0},S.prototype._isFollowing=function(){return(this._bitField&67108864)===67108864},S.prototype._setLength=function(B){this._bitField=this._bitField&-65536|B&65535},S.prototype._setFulfilled=function(){this._bitField=this._bitField|33554432,this._fireEvent("promiseFulfilled",this)},S.prototype._setRejected=function(){this._bitField=this._bitField|16777216,this._fireEvent("promiseRejected",this)},S.prototype._setFollowing=function(){this._bitField=this._bitField|67108864,this._fireEvent("promiseResolved",this)},S.prototype._setIsFinal=function(){this._bitField=this._bitField|4194304},S.prototype._isFinal=function(){return(this._bitField&4194304)>0},S.prototype._unsetCancelled=function(){this._bitField=this._bitField&-65537},S.prototype._setCancelled=function(){this._bitField=this._bitField|65536,this._fireEvent("promiseCancelled",this)},S.prototype._setWillBeCancelled=function(){this._bitField=this._bitField|8388608},S.prototype._setAsyncGuaranteed=function(){if(H.hasCustomScheduler())return;this._bitField=this._bitField|134217728},S.prototype._receiverAt=function(B){var k=B===0?this._receiver0:this[B*4-4+3];if(k===J)return;else if(k===void 0&&this._isBound())return this._boundValue();return k},S.prototype._promiseAt=function(B){return this[B*4-4+2]},S.prototype._fulfillmentHandlerAt=function(B){return this[B*4-4+0]},S.prototype._rejectionHandlerAt=function(B){return this[B*4-4+1]},S.prototype._boundValue=function(){},S.prototype._migrateCallback0=function(B){var{_bit Line truncated
path = %s
syscall = %s
fstream_type = %s
fstream_path = %s
fstream_unc_path = %s
fstream_class = %s
fstream_stack =
%s
`,I||"UNKNOWN",Y.stack,Y.path,Y.syscall,Y.fstream_type,Y.fstream_path,Y.fstream_unc_path,Y.fstream_class,Y.fstream_stack.join(`
`));else U.emit("warn",Y)};Y7.prototype.info=function($,I){this.emit("info",$,I)};Y7.prototype.error=function($,I,U){var Y=DG0($,I,this);if(U)throw Y;else this.emit("error",Y)};function DG0($,I,U){if(!($ instanceof Error))$=Error($);if($.code=$.code||I,$.path=$.path||U.path,$.fstream_type=$.fstream_type||U.type,$.fstream_path=$.fstream_path||U.path,U._path!==U.path)$.fstream_unc_path=$.fstream_unc_path||U._path;if(U.linkpath)$.fstream_linkpath=$.fstream_linkpath||U.linkpath;return $.fstream_class=$.fstream_class||U.constructor.name,$.fstream_stack=$.fstream_stack||Error().stack.split(/\n/).slice(3).map(function(Y){return Y.replace(/^ {4}at /,"")}),$}});var gq=N((iv1,NG0)=>{NG0.exports=lU1;function lU1($){var I=["Directory","File","SymbolicLink","Link","BlockDevice","CharacterDevice","FIFO","Socket"],U;if($.type&&I.indexOf($.type)!==-1)return $[$.type]=!0,$.type;for(var Y=0,J=I.length;Y<J;Y++){U=I[Y];var Q=$[U]||$["is"+U];if(typeof Q==="function")Q=Q.call($);if(Q)return $[U]=!0,$.type=U,U}return null}});var og=N((pv1,FG0)=>{FG0.exports=yq;var oU1=m6(),rU1=n0(),lg=p3();rU1(yq,lg);function yq($){var I=this;if(!(I instanceof yq))throw Error("LinkReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="SymbolicLink"&&$.SymbolicLink))throw Error("Non-link type "+$.type);lg.call(I,$)}yq.prototype._stat=function($){var I=this;oU1.readlink(I._path,function(U,Y){if(U)return I.error(U);I.linkpath=I.props.linkpath=Y,I.emit("linkpath",Y),lg.prototype._stat.call(I,$)})};yq.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var tg=N((nv1,AG0)=>{AG0.exports=u8;var zG0=m6(),tU1=n0(),hq=r("path"),rg=p3(),MG0=r("assert").ok;tU1(u8,rg);function u8($){var I=this;if(!(I instanceof u8))throw Error("DirReader must be called as constructor.");if($.type!=="Directory"||!$.Directory)throw Error("Non-directory type "+$.type);if(I.entries=null,I._index=-1,I._paused=!1,I._length=-1,$.sort)this.sort=$.sort;rg.call(this,$)}u8.prototype._getEntries=function(){var $=this;if($._gotEntries)return;$._gotEntries=!0,zG0.readdir($._path,function(I,U){if(I)return $.error(I);if($.entries=U,$.emit("entries",U),$._paused)$.once("resume",Y);else Y();function Y(){if($._length=$.entries.length,typeof $.sort==="function")$.entries=$.entries.sort($.sort.bind($));$._read()}})};u8.prototype._read=function(){var $=this;if(!$.entries)return $._getEntries();if($._paused||$._currentEntry||$._aborted)return;if($._index++,$._index>=$.entries.length){if(!$._ended)$._ended=!0,$.emit("end"),$.emit("close");return}var I=hq.resolve($._path,$.entries[$._index]);MG0(I!==$._path),MG0($.entries[$._index]),$._currentEntry=I,zG0[$.props.follow?"stat":"lstat"](I,function(U,Y){if(U)return $.error(U);var J=$._proxy||$;Y.path=I,Y.basename=hq.basename(I),Y.dirname=hq.dirname(I);var Q=$.getChildProps.call(J,Y);Q.path=I,Q.basename=hq.basename(I),Q.dirname=hq.dirname(I);var K=rg(Q,Y);$._currentEntry=K,K.on("pause",function(H){if(!$._paused&&!K._disowned)$.pause(H)}),K.on("resume",function(H){if($._paused&&!K._disowned)$.resume(H)}),K.on("stat",function(H){if($.emit("_entryStat",K,H),K._aborted)return;if(K._paused)K.once("resume",function(){$.emit("entryStat",K,H)});else $.emit("entryStat",K,H)}),K.on("ready",function H(){if($._paused)return K.pause($),$.once("resume",H);if(K.type==="Socket")$.emit("socket",K);else $.emitEntry(K)});var q=!1;K.on("close",G),K.on("disown",G);function G(){if(q)return;if(q=!0,$.emit("childEnd",K),$.emit("entryEnd",K),$._currentEntry=null,!$._paused)$._read()}K.on("error",function(H){if(K._swallowErrors)$.warn(H),K.emit("end"),K.emit("close");else $.emit("error",H)}),["child","childEnd","warn"].forEach(function(H){K.on(H,$.emit.bind($,H))})})};u8.prototype.disown=function($){if($.emit("beforeDisown"),$._disowned=!0,$.parent=$.root=null,$===this._currentEntry)this._currentEntry=null;$.emit("disown")};u8.prototype.getChildProps=function(){return{depth:this.depth+1,root:this.root||this,parent:this,follow:this.follow,filter:this.filter,sort:this.props.sort,hardlinks:this.props.hardlinks}};u8.prototype.pause=function($){var I=this;if(I._paused)return;if($=$||I,I._paused=!0,I._currentEntry&&I._currentEntry.pause)I._currentEntry.pause($);I.emit("pause",$)};u8.prototype.resume=function($){var I=this;if(!I._paused)return;if($=$||I,I._paused=!1,I.emit("resume",$),I._paused)return;if(I._currentEntry){if(I._currentEntry.resume)I._currentEntry.resume($)}else I._read()};u8.prototype.emitEntry=function($){this.emit("entry",$),this.emit("child",$)}});var ag=N((cv1,BG0)=>{BG0.exports=n3;var aU1=m6(),sU1=n0(),PG0=p3(),TG0={EOF:!0},EG0={CLOSE:!0};sU1(n3,PG0);function n3($){var I=this;if(!(I instanceof n3))throw Error("FileReader must be called as constructor.");if(!($.type==="Link"&&$.Link||$.type==="File"&&$.File))throw Error("Non-file type "+$.type);I._buffer=[],I._bytesEmitted=0,PG0.call(I,$)}n3.prototype._getStream=function(){var $=this,I=$._stream=aU1.createReadStream($._path,$.pro Line truncated
expect: `+$.props.size+`
actual: `+$._bytesEmitted)}),I.on("close",function(){if($._paused||$._buffer.length)$._buffer.push(EG0),$._read();else $.emit("close")}),I.on("error",function(U){$.emit("error",U)}),$._read()};n3.prototype._read=function(){var $=this;if($._paused)return;if(!$._stream)return $._getStream();if($._buffer.length){var I=$._buffer;for(var U=0,Y=I.length;U<Y;U++){var J=I[U];if(J===TG0)$.emit("end");else if(J===EG0)$.emit("close");else $.emit("data",J);if($._paused){$._buffer=I.slice(U);return}}$._buffer.length=0}};n3.prototype.pause=function($){var I=this;if(I._paused)return;if($=$||I,I._paused=!0,I._stream)I._stream.pause();I.emit("pause",$)};n3.prototype.resume=function($){var I=this;if(!I._paused)return;if($=$||I,I.emit("resume",$),I._paused=!1,I._stream)I._stream.resume();I._read()}});var CG0=N((dv1,vG0)=>{vG0.exports=$D;var eU1=n0(),RG0=p3();eU1($D,RG0);function $D($){var I=this;if(!(I instanceof $D))throw Error("SocketReader must be called as constructor.");if(!($.type==="Socket"&&$.Socket))throw Error("Non-socket type "+$.type);RG0.call(I,$)}$D.prototype._read=function(){var $=this;if($._paused)return;if(!$._ended)$.emit("end"),$.emit("close"),$._ended=!0}});var eg=N((mv1,jG0)=>{jG0.exports=c3;var sg=p3(),$Y1=gq(),IY1=n0(),UY1=m6();IY1(c3,sg);function c3($){var I=this;if(!(I instanceof c3))throw Error("ProxyReader must be called as constructor.");I.props=$,I._buffer=[],I.ready=!1,sg.call(I,$)}c3.prototype._stat=function(){var $=this,I=$.props,U=I.follow?"stat":"lstat";UY1[U](I.path,function(Y,J){var Q;if(Y||!J)Q="File";else Q=$Y1(J);I[Q]=!0,I.type=$.type=Q,$._old=J,$._addProxy(sg(I,J))})};c3.prototype._addProxy=function($){var I=this;if(I._proxyTarget)return I.error("proxy already set");I._proxyTarget=$,$._proxy=I,["error","data","end","close","linkpath","entry","entryEnd","child","childEnd","warn","stat"].forEach(function(Y){$.on(Y,I.emit.bind(I,Y))}),I.emit("proxy",$),$.on("ready",function(){I.ready=!0,I.emit("ready")});var U=I._buffer;I._buffer.length=0,U.forEach(function(Y){$[Y[0]].apply($,Y[1])})};c3.prototype.pause=function(){return this._proxyTarget?this._proxyTarget.pause():!1};c3.prototype.resume=function(){return this._proxyTarget?this._proxyTarget.resume():!1}});var p3=N((lv1,gG0)=>{gG0.exports=J8;var YY1=m6(),JY1=r("stream").Stream,QY1=n0(),$y=r("path"),Iy=gq(),ID=J8.hardLinks={},_G0=ew();QY1(J8,_G0);var SG0=og();function J8($,I){var U=this;if(!(U instanceof J8))return new J8($,I);if(typeof $==="string")$={path:$};var Y,J;if($.type&&typeof $.type==="function")Y=$.type,J=Y;else Y=Iy($),J=J8;if(I&&!Y)Y=Iy(I),$[Y]=!0,$.type=Y;switch(Y){case"Directory":J=tg();break;case"Link":case"File":J=ag();break;case"SymbolicLink":J=SG0;break;case"Socket":J=CG0();break;case null:J=eg();break}if(!(U instanceof J))return new J($);if(_G0.call(U),!$.path)U.error("Must provide a path",null,!0);if(U.readable=!0,U.writable=!1,U.type=Y,U.props=$,U.depth=$.depth=$.depth||0,U.parent=$.parent||null,U.root=$.root||$.parent&&$.parent.root||U,U._path=U.path=$y.resolve($.path),process.platform==="win32"){if(U.path=U._path=U.path.replace(/\?/g,"_"),U._path.length>=260)U._swallowErrors=!0,U._path="\\\\?\\"+U.path.replace(/\//g,"\\")}if(U.basename=$.basename=$y.basename(U.path),U.dirname=$.dirname=$y.dirname(U.path),$.parent=$.root=null,U.size=$.size,U.filter=typeof $.filter==="function"?$.filter:null,$.sort==="alpha")$.sort=KY1;U._stat(I)}function KY1($,I){return $===I?0:$.toLowerCase()>I.toLowerCase()?1:$.toLowerCase()<I.toLowerCase()?-1:$>I?1:-1}J8.prototype._stat=function($){var I=this,U=I.props,Y=U.follow?"stat":"lstat";if($)process.nextTick(J.bind(null,null,$));else YY1[Y](I._path,J);function J(Q,K){if(Q)return I.error(Q);if(Object.keys(K).forEach(function(Z){U[Z]=K[Z]}),I.size!==void 0&&U.size!==I.size)return I.error("incorrect size");I.size=U.size;var q=Iy(U),G=U.hardlinks!==!1;if(G&&q!=="Directory"&&U.nlink&&U.nlink>1){var H=U.dev+":"+U.ino;if(ID[H]===I._path||!ID[H])ID[H]=I._path;else q=I.type=I.props.type="Link",I.Link=I.props.Link=!0,I.linkpath=I.props.linkpath=ID[H],I._stat=I._read=SG0.prototype._read}if(I.type&&I.type!==q)I.error("Unexpected type: "+q);if(I.filter){var W=I._proxy||I;if(!I.filter.call(W,W,U)){if(!I._disowned)I.abort(),I.emit("end"),I.emit("close");return}}var V=["_stat","stat","ready"],X=0;(function Z(){if(I._aborted){I.emit("end"),I.emit("close");return}if(I._paused&&I.type!=="Directory"){I.once("resume",Z);return}var w=V[X++];if(!w)return I._read();I.emit(w,U),Z()})()}};J8.prototype.pipe=function($){var I=this;if(typeof $.add==="function")I.on("entry",function(U){var Y=$.add(U);if(Y===!1)I.pause()});return JY1.prototype.pipe.apply(this,arguments)};J8.prototype.pause=function($){if(this._paused=!0,$=$||this,this.emit("pause",$),this._stream)this._stream.pause($)};J8.prototype.resume=function($){if(this._paused=!1,$=$||this,this.emit("resume",$),this._stream)this._stream.resume($);this._read()};J8.prototype._read=function(){this.error("Cannot read unknown type: "+this.type)}});var Qy=N((ov1,iG0)=>{i Line truncated
expect: `+$.size+`
actual: `+$._bytesWritten);ZD.prototype._finish.call($)}});var Dy=N((ZC1,jH0)=>{jH0.exports=G7;var wy=QJ(),gY1=gq(),yY1=n0(),hY1=WD(),xY1=r("fs");yY1(G7,wy);function G7($){var I=this;if(!(I instanceof G7))throw Error("ProxyWriter must be called as constructor.");I.props=$,I._needDrain=!1,wy.call(I,$)}G7.prototype._stat=function(){var $=this,I=$.props,U=I.follow?"stat":"lstat";xY1[U](I.path,function(Y,J){var Q;if(Y||!J)Q="File";else Q=gY1(J);I[Q]=!0,I.type=$.type=Q,$._old=J,$._addProxy(wy(I,J))})};G7.prototype._addProxy=function($){var I=this;if(I._proxy)return I.error("proxy already set");I._proxy=$,["ready","error","close","pipe","drain","warn"].forEach(function(Y){$.on(Y,I.emit.bind(I,Y))}),I.emit("proxy",$);var U=I._buffer;if(U.forEach(function(Y){$[Y[0]].apply($,Y[1])}),I._buffer.length=0,I._needsDrain)I.emit("drain")};G7.prototype.add=function($){if(hY1($),!this._proxy)return this._buffer.push(["add",[$]]),this._needDrain=!0,!1;return this._proxy.add($)};G7.prototype.write=function($){if(!this._proxy)return this._buffer.push(["write",[$]]),this._needDrain=!0,!1;return this._proxy.write($)};G7.prototype.end=function($){if(!this._proxy)return this._buffer.push(["end",[$]]),!1;return this._proxy.end($)}});var QJ=N((XC1,fH0)=>{fH0.exports=_$;var j$=m6(),kY1=n0(),uY1=Qy(),fY1=Wy(),fq=r("path"),SH0=process.platform==="win32"?0:process.umask(),gH0=gq(),yH0=ew();kY1(_$,yH0);_$.dirmode=parseInt("0777",8)&~SH0;_$.filemode=parseInt("0666",8)&~SH0;var bY1=Zy(),iY1=Xy(),pY1=Ly(),nY1=Dy();function _$($,I){var U=this;if(typeof $==="string")$={path:$};var Y=gH0($),J=_$;switch(Y){case"Directory":J=bY1;break;case"File":J=pY1;break;case"Link":case"SymbolicLink":J=iY1;break;case null:default:J=nY1;break}if(!(U instanceof J))return new J($);if(yH0.call(U),!$.path)U.error("Must provide a path",null,!0);if(U.type=$.type,U.props=$,U.depth=$.depth||0,U.clobber=$.clobber===!1?$.clobber:!0,U.parent=$.parent||null,U.root=$.root||$.parent&&$.parent.root||U,U._path=U.path=fq.resolve($.path),process.platform==="win32"){if(U.path=U._path=U.path.replace(/\?/g,"_"),U._path.length>=260)U._swallowErrors=!0,U._path="\\\\?\\"+U.path.replace(/\//g,"\\")}if(U.basename=fq.basename($.path),U.dirname=fq.dirname($.path),U.linkpath=$.linkpath||null,$.parent=$.root=null,U.size=$.size,typeof $.mode==="string")$.mode=parseInt($.mode,8);U.readable=!1,U.writable=!0,U._buffer=[],U.ready=!1,U.filter=typeof $.filter==="function"?$.filter:null,U._stat(I)}_$.prototype._create=function(){var $=this;j$[$.props.follow?"stat":"lstat"]($._path,function(I){if(I)return $.warn("Cannot create "+$._path+`
Unsupported type: `+$.type,"ENOTSUP");$._finish()})};_$.prototype._stat=function($){var I=this,U=I.props,Y=U.follow?"stat":"lstat",J=I._proxy||I;if($)Q(null,$);else j$[Y](I._path,Q);function Q(K,q){if(I.filter&&!I.filter.call(J,J,q)){I._aborted=!0,I.emit("end"),I.emit("close");return}if(K||!q)return Oy(I);I._old=q;var G=gH0(q);if(G!==I.type||I.type==="File"&&q.nlink>1)return uY1(I._path,function(H){if(H)return I.error(H);I._old=null,Oy(I)});Oy(I)}};function Oy($){fY1(fq.dirname($._path),_$.dirmode,function(I,U){if(I)return $.error(I);return $._madeDir=U,$._create()})}function hH0($,I,U,Y,J){var Q=I.mode,K=I.follow||$.type!=="SymbolicLink"?"chmod":"lchmod";if(!j$[K])return J();if(typeof Q!=="number")return J();var q=U.mode&parseInt("0777",8);if(Q=Q&parseInt("0777",8),Q===q)return J();j$[K](Y,Q,J)}function xH0($,I,U,Y,J){if(process.platform==="win32")return J();if(!process.getuid||process.getuid()!==0)return J();if(typeof I.uid!=="number"&&typeof I.gid!=="number")return J();if(U.uid===I.uid&&U.gid===I.gid)return J();var Q=$.props.follow||$.type!=="SymbolicLink"?"chown":"lchown";if(!j$[Q])return J();if(typeof I.uid!=="number")I.uid=U.uid;if(typeof I.gid!=="number")I.gid=U.gid;j$[Q](Y,I.uid,I.gid,J)}function kH0($,I,U,Y,J){if(!j$.utimes||process.platform==="win32")return J();var Q=I.follow||$.type!=="SymbolicLink"?"utimes":"lutimes";if(Q==="lutimes"&&!j$[Q])Q="utimes";if(!j$[Q])return J();var{atime:K,mtime:q}=U,G=I.atime,H=I.mtime;if(G===void 0)G=K;if(H===void 0)H=q;if(!_H0(G))G=new Date(G);if(!_H0(H))G=new Date(H);if(G.getTime()===K.getTime()&&H.getTime()===q.getTime())return J();j$[Q](Y,G,H,J)}_$.prototype._finish=function(){var $=this;if($._finishing)return;$._finishing=!0;var I=0,U=null,Y=!1;if($._old)$._old.atime=new Date(0),$._old.mtime=new Date(0),Q($._old);else{var J=$.props.follow?"stat":"lstat";j$[J]($._path,function(q,G){if(q)if(q.code==="ENOENT"&&($.type==="Link"||$.type==="SymbolicLink")&&process.platform==="win32"){$.ready=!0,$.emit("ready"),$.emit("end"),$.emit("close"),$.end=$._finish=function(){};return}else return $.error(q);Q($._old=G)})}return;function Q(q){I+=3,hH0($,$.props,q,$._path,K("chmod")),xH0($,$.props,q,$._path,K("chown")),kH0($,$.props,q,$._path,K("utimes"))}function K(q){return function(G){if(U)return;if(G)return G.fstream_finish_call=q,$.error(U=G);if(--I>0)return;if(Y)return;if(Y=!0,!$._madeDir)return H();else uH0($,$._path,H);function H(W){if(W)return W.fstream_finish_call="setupMadeDir",$.error(W);$.emit("end"),$.emit("close")}}}};function uH0($,I,U){var Y=$._madeDir,J=fq.dirname(I);cY1($,J,function(Q){if(Q)return U(Q);if(J===Y)return U();uH0($,J,U)})}function cY1($,I,U){var Y={};Object.keys($.props).forEach(function(q){if(Y[q]=$.props[q],q==="mode"&&$.type!=="Directory")Y[q]=Y[q]|parseInt("0111",8)});var J=3,Q=null;j$.stat(I,function(q,G){if(q)return U(Q=q);hH0($,Y,G,I,K),xH0($,Y,G,I,K),kH0($,Y,G,I,K)});function K(q){if(Q)return;if(q)return U(Q=q);if(--J===0)return U()}}_$.prototype.pipe=function(){this.error("Can't pipe from writable stream")};_$.prototype.add=function(){this.error("Can't add to non-Directory type")};_$.prototype.write=function(){return!0};function dY1($){return Object.prototype.toString.call($)}function _H0($){return typeof $==="object"&&dY1($)==="[object Date]"}});var Ay=N((mY1)=>{mY1.Abstract=ew();mY1.Reader=p3();mY1.Writer=QJ();mY1.File={Reader:ag(),Writer:Ly()};mY1.Dir={Reader:tg(),Writer:Zy()};mY1.Link={Reader:og(),Writer:Xy()};mY1.Proxy={Reader:eg(),Writer:Dy()};mY1.Reader.Dir=mY1.DirReader=mY1.Dir.Reader;mY1.Reader.File=mY1.FileReader=mY1.File.Reader;mY1.Reader.Link=mY1.LinkReader=mY1.Link.Reader;mY1.Reader.Proxy=mY1.ProxyReader=mY1.Proxy.Reader;mY1.Writer.Dir=mY1.DirWriter=mY1.Dir.Writer;mY1.Writer.File=mY1.FileWriter=mY1.File.Writer;mY1.Writer.Link=mY1.LinkWriter=mY1.Link.Writer;mY1.Writer.Proxy=mY1.ProxyWriter=mY1.Proxy.Writer;mY1.collect=WD()});var iH0=N((PC1,bH0)=>{bH0.exports=$J1;var rY1=cw(),tY1=Ay().Writer,Py=r("path"),aY1=r("stream"),sY1=dg(),eY1=I7();function $J1($){$.path=Py.resolve(Py.normalize($.path));var I=new rY1($),U=new aY1.Writable({objectMode:!0});U._write=function(J,Q,K){if(J.type=="Directory")return K();var q=Py.join($.path,J.path);if(q.indexOf($.path)!=0)return K();let G=$.getWriter?$.getWriter({path:q}):tY1({path:q});J.pipe(G).on("error",K).on("close",K)};var Y=sY1(I,U);return I.once("crx-header",function(J){Y.crxHeader=J}),I.pipe(U).on("finish",function(){Y.emit("close")}),Y.promise=function(){return new eY1(function(J,Q){Y.on("close",J),Y.on("error",Q)})},Y}});var pH0=N((TC1,XD)=>{var h4=function($){var I=1e7,U=7,Y=9007199254740992,J=X(Y),Q="0123456789abcdefghijklmnopqrstuvwxyz",K=typeof BigInt==="function";function q(M,z,j,x){if(typeof M>"u")return q[0];if(typeof z<"u")return+z===10&&!j?T0(M):k$(M,z,j,x);return T0(M)}function G(M,z){this.value=M,this.sign=z,this.isSmall=!1}G.prototype=Object.create(q.prototype);function H(M){this.value=M,this.sign=M<0,this.isSmall=!0}H.prototype=Object.create(q.prototype);function W(M){th Line truncated
* Tmp
*
* Copyright (c) 2011-2017 KARASZI Istvan <github@spam.raszi.hu>
*
* MIT Licensed
*/var x1=r("fs"),FD=r("os"),x4=r("path"),IW0=r("crypto"),f8={fs:x1.constants,os:FD.constants},QW0=/XXXXXX/,KW0=(f8.O_CREAT||f8.fs.O_CREAT)|(f8.O_EXCL||f8.fs.O_EXCL)|(f8.O_RDWR||f8.fs.O_RDWR),TJ1=FD.platform()==="win32",EJ1=f8.EBADF||f8.os.errno.EBADF,BJ1=f8.ENOENT||f8.os.errno.ENOENT,qJ=[],qW0=x1.rmdirSync.bind(x1),GW0=!1;function RJ1($,I){return x1.rm($,{recursive:!0},I)}function HW0($){return x1.rmSync($,{recursive:!0})}function vy($,I){let U=GJ($,I),Y=U[0],J=U[1];kJ1(Y,function(Q,K){if(Q)return J(Q);let q=K.tries;(function G(){try{let H=VW0(K);x1.stat(H,function(W){if(!W){if(q-- >0)return G();return J(Error("Could not get a unique tmp filename, max tries reached "+H))}J(null,H)})}catch(H){J(H)}})()})}function Cy($){let I=GJ($),U=I[0],Y=uJ1(U),J=Y.tries;do{let Q=VW0(Y);try{x1.statSync(Q)}catch(K){return Q}}while(J-- >0);throw Error("Could not get a unique tmp filename, max tries reached")}function vJ1($,I){let U=GJ($,I),Y=U[0],J=U[1];vy(Y,function(K,q){if(K)return J(K);x1.open(q,KW0,Y.mode||384,function(H,W){if(H)return J(H);if(Y.discardDescriptor)return x1.close(W,function(X){return J(X,q,void 0,By(q,-1,Y,!1))});else{let V=Y.discardDescriptor||Y.detachDescriptor;J(null,q,W,By(q,V?-1:W,Y,!1))}})})}function CJ1($){let I=GJ($),U=I[0],Y=U.discardDescriptor||U.detachDescriptor,J=Cy(U),Q=x1.openSync(J,KW0,U.mode||384);if(U.discardDescriptor)x1.closeSync(Q),Q=void 0;return{name:J,fd:Q,removeCallback:By(J,Y?-1:Q,U,!0)}}function jJ1($,I){let U=GJ($,I),Y=U[0],J=U[1];vy(Y,function(K,q){if(K)return J(K);x1.mkdir(q,Y.mode||448,function(H){if(H)return J(H);J(null,q,WW0(q,Y,!1))})})}function _J1($){let I=GJ($),U=I[0],Y=Cy(U);return x1.mkdirSync(Y,U.mode||448),{name:Y,removeCallback:WW0(Y,U,!0)}}function SJ1($,I){let U=function(Y){if(Y&&!Ry(Y))return I(Y);I()};if(0<=$[0])x1.close($[0],function(){x1.unlink($[1],U)});else x1.unlink($[1],U)}function gJ1($){let I=null;try{if(0<=$[0])x1.closeSync($[0])}catch(U){if(!fJ1(U)&&!Ry(U))throw U}finally{try{x1.unlinkSync($[1])}catch(U){if(!Ry(U))I=U}}if(I!==null)throw I}function By($,I,U,Y){let J=ND(gJ1,[I,$],Y),Q=ND(SJ1,[I,$],Y,J);if(!U.keep)qJ.unshift(J);return Y?J:Q}function WW0($,I,U){let Y=I.unsafeCleanup?RJ1:x1.rmdir.bind(x1),J=I.unsafeCleanup?HW0:qW0,Q=ND(J,$,U),K=ND(Y,$,U,Q);if(!I.keep)qJ.unshift(Q);return U?Q:K}function ND($,I,U,Y){let J=!1;return function Q(K){if(!J){let q=Y||Q,G=qJ.indexOf(q);if(G>=0)qJ.splice(G,1);if(J=!0,U||$===qW0||$===HW0)return $(I);else return $(I,K||function(){})}}}function yJ1(){if(!GW0)return;while(qJ.length)try{qJ[0]()}catch($){}}function UW0($){let I=[],U=null;try{U=IW0.randomBytes($)}catch(Y){U=IW0.pseudoRandomBytes($)}for(let Y=0;Y<$;Y++)I.push("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"[U[Y]%62]);return I.join("")}function o6($){return typeof $>"u"}function GJ($,I){if(typeof $==="function")return[{},$];if(o6($))return[{},I];let U={};for(let Y of Object.getOwnPropertyNames($))U[Y]=$[Y];return[U,I]}function hJ1($,I,U){let Y=x4.isAbsolute($)?$:x4.join(I,$);x1.stat(Y,function(J){if(J)x1.realpath(x4.dirname(Y),function(Q,K){if(Q)return U(Q);U(null,x4.join(K,x4.basename(Y)))});else x1.realpath(Y,U)})}function xJ1($,I){let U=x4.isAbsolute($)?$:x4.join(I,$);try{return x1.statSync(U),x1.realpathSync(U)}catch(Y){let J=x1.realpathSync(x4.dirname(U));return x4.join(J,x4.basename(U))}}function VW0($){let I=$.tmpdir;if(!o6($.name))return x4.join(I,$.dir,$.name);if(!o6($.template))return x4.join(I,$.dir,$.template).replace(QW0,UW0(6));let U=[$.prefix?$.prefix:"tmp","-",process.pid,"-",UW0(12),$.postfix?"-"+$.postfix:""].join("");return x4.join(I,$.dir,U)}function Ey($,I){if(typeof I!=="string")throw Error(`${$} option must be a string, got "${typeof I}".`);if(I.includes(".."))throw Error("Relative value not allowed");return I}function ZW0($){if(!o6($.name)){let I=$.name;if(x4.isAbsolute(I))throw Error(`name option must not contain an absolute path, found "${I}".`);let U=x4.basename(I);if(U===".."||U==="."||U!==I)throw Error(`name option must not contain a path, found "${I}".`)}if(!o6($.template)){if(typeof $.template!=="string")throw Error(`template option must be a string, got "${typeof $.template}".`);if(!$.template.match(QW0))throw Error(`Invalid template, found "${$.template}".`)}if(!o6($.tries)&&isNaN($.tries)||$.tries<0)throw Error(`Invalid tries, found "${$.tries}".`);$.tries=o6($.name)?$.tries||3:1,$.keep=!!$.keep,$.detachDescriptor=!!$.detachDescriptor,$.discardDescriptor=!!$.discardDescriptor,$.unsafeCleanup=!!$.unsafeCleanup,$.prefix=o6($.prefix)?"":Ey("prefix",$.prefix),$.postfix=o6($.postfix)?"":Ey("postfix",$.postfix),$.template=o6($.template)?void 0:Ey("template",$.template)}function YW0($,I,U,Y){if(o6(I))return Y(null);hJ1(I,U,function(J,Q){if(J)return Y(J);let K=x4.relative(U,Q);if(K.startsWith("..")||x4.isAbsolute(K))return Y(Error(`${$} option must be relative to "${U}", found "${K}".`));Y(null,K)})}function JW0($,I,U){if(o6(I))return;let Y=xJ1(I,U),J=x4.relative(U,Y);if(J.startsWith("..")||x4.isAbsolute(J))throw ELine truncated
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�`},ibm864:"cp864",csibm864:"cp864",cp865:{type:"_sbcs",chars:"ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ "},ibm865:"cp865",csibm865:"cp865",cp866:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ "},ibm866:"cp866",csibm866:"cp866",cp869:{type:"_sbcs",chars:"������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ "},ibm869:"cp869",csibm869:"cp869",cp922:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖרÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ"},ibm922:"cp922",csibm922:"cp922",cp1046:{type:"_sbcs",chars:"ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�"},ibm1046:"cp1046",csibm1046:"cp1046",cp1124:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ"},ibm1124:"cp1124",csibm1124:"cp1124",cp1125:{type:"_sbcs",chars:"АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ "},ibm1125:"cp1125",csibm1125:"cp1125",cp1129:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1129:"cp1129",csibm1129:"cp1129",cp1133:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�"},ibm1133:"cp1133",csibm1133:"cp1133",cp1161:{type:"_sbcs",chars:"��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ "},ibm1161:"cp1161",csibm1161:"cp1161",cp1162:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"},ibm1162:"cp1162",csibm1162:"cp1162",cp1163:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖרÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ"},ibm1163:"cp1163",csiLine truncated
\v\f\r\x0E\x0F\x10ỨỰỲỶỸÝỴ\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ`},georgianacademy:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},georgianps:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ"},pt154:{type:"_sbcs",chars:"ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя"},viscii:{type:"_sbcs",chars:`\x00\x01Ẳ\x03\x04ẴẪ\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13Ỷ\x15\x16\x17\x18Ỹ\x1A\x1B\x1C\x1DỴ\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ`},iso646cn:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},iso646jp:{type:"_sbcs",chars:`\x00\x01\x02\x03\x04\x05\x06\x07\b
\v\f\r\x0E\x0F\x10\x11\x12\x13\x14\x15\x16\x17\x18\x19\x1A\x1B\x1C\x1D\x1E\x1F !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_\`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������`},hproman8:{type:"_sbcs",chars:"€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¾—¼½ªº«■»±�"},macintosh:{type:"_sbcs",chars:"ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ"},ascii:{type:"_sbcs",chars:"��������������������������������������������������������������������������������������������������������������������������������"},tis620:{type:"_sbcs",chars:"���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����"}}});var mV0=N((NK1)=>{var vh=k5().Buffer;NK1._dbcs=f5;var H6=-1,dV0=-2,h$=-10,S6=-1000,FJ=Array(256),aq=-1;for(tq=0;tq<256;tq++)FJ[tq]=H6;var tq;function f5($,I){if(this.encodingName=$.encodingName,!$)throw Error("DBCS codec is called without the data.");if(!$.table)throw Error("Encoding '"+this.encodingName+"' has no data.");var U=$.table();this.decodeTables=[],this.decodeTables[0]=FJ.slice(0),this.decodeTableSeq=[];for(var Y=0;Y<U.length;Y++)this._addDecodeChunk(U[Y]);if(typeof $.gb18030==="function"){this.gb18030=$.gb18030();var J=this.decodeTables.length;this.decodeTables.push(FJ.slice(0));var Q=this.decodeTables.length;this.decodeTables.push(FJ.slice(0));var K=this.decodeTables[0];for(var Y=129;Y<=254;Y++){var q=this.decodeTables[S6-K[Y]];for(var G=48;G<=57;G++){if(q[G]===H6)q[G]=S6-J;else if(q[G]>S6)throw Error("gb18030 decode tables conflict at byte 2");var H=this.decodeTables[S6-q[G]];for(var W=129;W<=254;W++){if(H[W]===H6)H[W]=S6-Q;else if(H[W]===S6-Q)continue;else if(H[W]>S6)throw Error("gb18030 decode tables conflict at byte 3");var V=this.decodeTables[S6-H[W]];for(var X=48;X<=57;X++)if(V[X]===H6)V[X]=dV0}}}}this.defaultCharUnicode=I.defaultCharUnicode,this.encodeTable=[],this.encodeTableSeq=[];var Z={};if($.encodeSkipVals)for(var Y=0;Y<$.encodeSkipVals.length;Y++){var w=$.encodeSkipVals[Y];if(typeof w==="number")Z[w]=!0;else for(var G=w.from;G<=w.to;G++)Z[G]=!0}if(this._fillEncodeTable(0,0,Z),$.encodeAdd){for(var D in $.encodeAdd)if(Object.prototype.hasOwnProperty.call($.encodeAdd,D))this._setEncodeChar(D.charCodeAt(0),$.encodeAdd[D])}if(this.defCharSB=this.encodeTable[0][I.defaultCharSingleByte.charCodeAt(0)],this.defCharSB===H6)this.defCharSB=this.encodeTable[0]["?"];if(this.defCharSB===H6)this.defCharSB=63}f5.prototype.encoder=pD;f5.prototype.decoder=Ch;f5.prototype._getDecodeTrieNode=function($){var I=[];for(;$>0;$>>>=8)I.push($&255);if(I.length==0)I.push(0);var U=this.decodeTables[0];for(var Y=I.length-1;Y>0;Y--){var J=U[I[Y]];if(J==H6)U[I[Y]]=S6-this.decodeTables.length,this.decodeTables.push(U=FJ.slice(0));else if(J<=S6)U=this.decodeTables[S6-J];else throw Error("Overwrite byte in "+this.encodingName+", addr: "+$.toString(16))}return U};f5.prototype._addDecodeChunk=function($){var I=parseInt($[0],16),U=this._getDecodeTrieNode(I);I=I&255;for(var Y=1;Y<$.length;Y++){var J=$[Y];if(typeof J==="string")for(var Q=0;Q<J.length;){var K=J.charCodeAt(Q++);if(K>=55296&&K<56320){var q=J.charCodeAt(Q++);if(q>=56320&&q<57344)U[I++]=65536+(K-55296)*1024+(q-56320);else throw Error("Incorrect surrogate pair in "+this.encodingName+" at chunk "+$[0])}else if(K>4080&&K<=4095){var G=4095-K+2,H=[];for(var W=0;W<G;W++)H.push(J.charCodeAt(Q++));U[I++]=h$-this.decodeTableSeq.length,this.decodeTableSeq.push(H)}else U[I++]=K}else if(typeof J==="number"){var V=U[I-1]+1;for(var Q=0;Q<J;Q++)U[I++]=V++}else throw Error("Incorrect type '"+typeof J+"' given in "+this.encodingName+" at chunk "+$[0])}if(I>255)throw Error("Incorrect chunk in "+this.encoLine truncated
`)}var LI=($)=>(I,U,Y,J)=>{let Q=Y?{...Y,async:!1}:{async:!1},K=I._zod.run({value:U,issues:[]},Q);if(K instanceof Promise)throw new Q8;if(K.issues.length){let q=new(J?.Err??$)(K.issues.map((G)=>A6(G,Q,Z4())));throw xG(q,J?.callee),q}return K.value},bJ=LI(h6),wI=($)=>async(I,U,Y,J)=>{let Q=Y?{...Y,async:!0}:{async:!0},K=I._zod.run({value:U,issues:[]},Q);if(K instanceof Promise)K=await K;if(K.issues.length){let q=new(J?.Err??$)(K.issues.map((G)=>A6(G,Q,Z4())));throw xG(q,J?.callee),q}return K.value},iJ=wI(h6),DI=($)=>(I,U,Y)=>{let J=Y?{...Y,async:!1}:{async:!1},Q=I._zod.run({value:U,issues:[]},J);if(Q instanceof Promise)throw new Q8;return Q.issues.length?{success:!1,error:new($??kJ)(Q.issues.map((K)=>A6(K,J,Z4())))}:{success:!0,data:Q.value}},OI=DI(h6),NI=($)=>async(I,U,Y)=>{let J=Y?{...Y,async:!0}:{async:!0},Q=I._zod.run({value:U,issues:[]},J);if(Q instanceof Promise)Q=await Q;return Q.issues.length?{success:!1,error:new $(Q.issues.map((K)=>A6(K,J,Z4())))}:{success:!0,data:Q.value}},pJ=NI(h6),kG=($)=>(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return LI($)(I,U,J)},Kk=kG(h6),uG=($)=>(I,U,Y)=>{return LI($)(I,U,Y)},qk=uG(h6),fG=($)=>async(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return wI($)(I,U,J)},Gk=fG(h6),bG=($)=>async(I,U,Y)=>{return wI($)(I,U,Y)},Hk=bG(h6),iG=($)=>(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return DI($)(I,U,J)},Wk=iG(h6),pG=($)=>(I,U,Y)=>{return DI($)(I,U,Y)},Vk=pG(h6),nG=($)=>async(I,U,Y)=>{let J=Y?{...Y,direction:"backward"}:{direction:"backward"};return NI($)(I,U,J)},Zk=nG(h6),cG=($)=>async(I,U,Y)=>{return NI($)(I,U,Y)},Xk=cG(h6);var e6={};m8(e6,{xid:()=>iO,uuid7:()=>kw0,uuid6:()=>xw0,uuid4:()=>hw0,uuid:()=>M7,uppercase:()=>ZN,unicodeEmail:()=>Lk,undefined:()=>WN,ulid:()=>bO,time:()=>YN,string:()=>QN,sha512_hex:()=>JD0,sha512_base64url:()=>KD0,sha512_base64:()=>QD0,sha384_hex:()=>ID0,sha384_base64url:()=>YD0,sha384_base64:()=>UD0,sha256_hex:()=>sw0,sha256_base64url:()=>$D0,sha256_base64:()=>ew0,sha1_hex:()=>rw0,sha1_base64url:()=>aw0,sha1_base64:()=>tw0,rfc5322Email:()=>fw0,number:()=>nJ,null:()=>HN,nanoid:()=>nO,md5_hex:()=>mw0,md5_base64url:()=>ow0,md5_base64:()=>lw0,mac:()=>tO,lowercase:()=>VN,ksuid:()=>pO,ipv6:()=>rO,ipv4:()=>oO,integer:()=>qN,idnEmail:()=>bw0,httpProtocol:()=>$N,html5Email:()=>uw0,hostname:()=>nw0,hex:()=>dw0,guid:()=>dO,extendedDuration:()=>yw0,emoji:()=>lO,email:()=>mO,e164:()=>IN,duration:()=>cO,domain:()=>cw0,datetime:()=>JN,date:()=>UN,cuid2:()=>fO,cuid:()=>uO,cidrv6:()=>sO,cidrv4:()=>aO,browserEmail:()=>iw0,boolean:()=>GN,bigint:()=>KN,base64url:()=>dG,base64:()=>eO});var uO=/^[cC][0-9a-z]{6,}$/,fO=/^[0-9a-z]+$/,bO=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,iO=/^[0-9a-vA-V]{20}$/,pO=/^[A-Za-z0-9]{27}$/,nO=/^[a-zA-Z0-9_-]{21}$/,cO=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,yw0=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,dO=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,M7=($)=>{if(!$)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},hw0=M7(4),xw0=M7(6),kw0=M7(7),mO=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,uw0=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,fw0=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,Lk=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,bw0=Lk,iw0=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,pw0="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function lO(){return new RegExp(pw0,"u")}var oO=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,rO=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,tO=($)=>{let I=L$($??":");return new RegExp(`^(?:[0-9A-F]{2}${I}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${I}){5}[0-9a-f]{2}$`)},aO=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0Line truncated
`).filter((Q)=>Q),Y=Math.min(...U.map((Q)=>Q.length-Q.trimStart().length)),J=U.map((Q)=>Q.slice(Y)).map((Q)=>" ".repeat(this.indent*2)+Q);for(let Q of J)this.content.push(Q)}compile(){let $=Function,I=this?.args,Y=[...(this?.content??[""]).map((J)=>` ${J}`)];return new $(...I,Y.join(`
`))}}var _N={major:4,minor:4,patch:3};var i0=o("$ZodType",($,I)=>{var U;$??($={}),$._zod.def=I,$._zod.bag=$._zod.bag||{},$._zod.version=_N;let Y=[...$._zod.def.checks??[]];if($._zod.traits.has("$ZodCheck"))Y.unshift($);for(let J of Y)for(let Q of J._zod.onattach)Q($);if(Y.length===0)(U=$._zod).deferred??(U.deferred=[]),$._zod.deferred?.push(()=>{$._zod.run=$._zod.parse});else{let J=(K,q,G)=>{let H=o5(K),W;for(let V of q){if(V._zod.def.when){if(hO(K))continue;if(!V._zod.def.when(K))continue}else if(H)continue;let X=K.issues.length,Z=V._zod.check(K);if(Z instanceof Promise&&G?.async===!1)throw new Q8;if(W||Z instanceof Promise)W=(W??Promise.resolve()).then(async()=>{if(await Z,K.issues.length===X)return;if(!H)H=o5(K,X)});else{if(K.issues.length===X)continue;if(!H)H=o5(K,X)}}if(W)return W.then(()=>{return K});return K},Q=(K,q,G)=>{if(o5(K))return K.aborted=!0,K;let H=J(q,Y,G);if(H instanceof Promise){if(G.async===!1)throw new Q8;return H.then((W)=>$._zod.parse(W,G))}return $._zod.parse(H,G)};$._zod.run=(K,q)=>{if(q.skipChecks)return $._zod.parse(K,q);if(q.direction==="backward"){let H=$._zod.parse({value:K.value,issues:[]},{...q,skipChecks:!0});if(H instanceof Promise)return H.then((W)=>{return Q(W,K,q)});return Q(H,K,q)}let G=$._zod.parse(K,q);if(G instanceof Promise){if(q.async===!1)throw new Q8;return G.then((H)=>J(H,Y,q))}return J(G,Y,q)}}a0($,"~standard",()=>({validate:(J)=>{try{let Q=OI($,J);return Q.success?{value:Q.data}:{issues:Q.error?.issues}}catch(Q){return pJ($,J).then((K)=>K.success?{value:K.data}:{issues:K.error?.issues})}},vendor:"zod",version:1}))}),z7=o("$ZodString",($,I)=>{i0.init($,I),$._zod.pattern=[...$?._zod.bag?.patterns??[]].pop()??QN($._zod.bag),$._zod.parse=(U,Y)=>{if(I.coerce)try{U.value=String(U.value)}catch(J){}if(typeof U.value==="string")return U;return U.issues.push({expected:"string",code:"invalid_type",input:U.value,inst:$}),U}}),S1=o("$ZodStringFormat",($,I)=>{FI.init($,I),z7.init($,I)}),gN=o("$ZodGUID",($,I)=>{I.pattern??(I.pattern=dO),S1.init($,I)}),yN=o("$ZodUUID",($,I)=>{if(I.version){let Y={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[I.version];if(Y===void 0)throw Error(`Invalid UUID version: "${I.version}"`);I.pattern??(I.pattern=M7(Y))}else I.pattern??(I.pattern=M7());S1.init($,I)}),hN=o("$ZodEmail",($,I)=>{I.pattern??(I.pattern=mO),S1.init($,I)}),xN=o("$ZodURL",($,I)=>{S1.init($,I),$._zod.check=(U)=>{try{let Y=U.value.trim();if(!I.normalize&&I.protocol?.source===$N.source){if(!/^https?:\/\//i.test(Y)){U.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:U.value,inst:$,continue:!I.abort});return}}let J=new URL(Y);if(I.hostname){if(I.hostname.lastIndex=0,!I.hostname.test(J.hostname))U.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:I.hostname.source,input:U.value,inst:$,continue:!I.abort})}if(I.protocol){if(I.protocol.lastIndex=0,!I.protocol.test(J.protocol.endsWith(":")?J.protocol.slice(0,-1):J.protocol))U.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:I.protocol.source,input:U.value,inst:$,continue:!I.abort})}if(I.normalize)U.value=J.href;else U.value=Y;return}catch(Y){U.issues.push({code:"invalid_format",format:"url",input:U.value,inst:$,continue:!I.abort})}}}),kN=o("$ZodEmoji",($,I)=>{I.pattern??(I.pattern=lO()),S1.init($,I)}),uN=o("$ZodNanoID",($,I)=>{I.pattern??(I.pattern=nO),S1.init($,I)}),fN=o("$ZodCUID",($,I)=>{I.pattern??(I.pattern=uO),S1.init($,I)}),bN=o("$ZodCUID2",($,I)=>{I.pattern??(I.pattern=fO),S1.init($,I)}),iN=o("$ZodULID",($,I)=>{I.pattern??(I.pattern=bO),S1.init($,I)}),pN=o("$ZodXID",($,I)=>{I.pattern??(I.pattern=iO),S1.init($,I)}),nN=o("$ZodKSUID",($,I)=>{I.pattern??(I.pattern=pO),S1.init($,I)}),cN=o("$ZodISODateTime",($,I)=>{I.pattern??(I.pattern=JN(I)),S1.init($,I)}),dN=o("$ZodISODate",($,I)=>{I.pattern??(I.pattern=UN),S1.init($,I)}),mN=o("$ZodISOTime",($,I)=>{I.pattern??(I.pattern=YN(I)),S1.init($,I)}),lN=o("$ZodISODuration",($,I)=>{I.pattern??(I.pattern=cO),S1.init($,I)}),oN=o("$ZodIPv4",($,I)=>{I.pattern??(I.pattern=oO),S1.init($,I),$._zod.bag.format="ipv4"}),rN=o("$ZodIPv6",($,I)=>{I.pattern??(I.pattern=rO),S1.init($,I),$._zod.bag.format="ipv6",$._zod.check=(U)=>{try{new URL(`http://[${U.value}]`)}catch{U.issues.push({code:"invalid_format",format:"ipv6",input:U.value,inst:$,continue:!I.abort})}}}),tN=o("$ZodMAC",($,I)=>{I.pattern??(I.pattern=tO(I.delimiter)),S1.init($,I),$._zod.bag.format="mac"}),aN=o("$ZodCIDRv4",($,I)=>{I.pattern??(I.pattern=aO),S1.init($,I)}),sN=o("$ZodCIDRv6",($,I)=>{I.pattern??(I.pattern=sO),S1.init($,I),$._zod.check=(U)=>{let Y=U.value.split("/");try{if(Y.length!==2)throw Error();let[J,Q]=Y;if(!Q)throw Error();let K=Number(Q);if(`${K}`!==Q)throw Error();if(K<0||K>128)throw Error();new URL(`http://[${J}]`)}catch{U.issues.push({code:"invalid_format",format:"cidrv6",input:U.value,inst:$,continue:!I.abort})}}});function eN($){if($==="")return!0;if(/\s/.test($))return!1;if($.length%4!==0)return!1;try{return atob($),!0}catch{return!1}} Line truncated
if (${T}.issues.length) {
if (${v} in input) {
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
...iss,
path: iss.path ? [${N}, ...iss.path] : [${N}]
path: iss.path ? [${v}, ...iss.path] : [${v}]
})));
}
}
if (${W}.value === undefined) {
if (${N} in input) {
newResult[${N}] = undefined;
if (${T}.value === undefined) {
if (${v} in input) {
newResult[${v}] = undefined;
}
} else {
newResult[${N}] = ${W}.value;
newResult[${v}] = ${T}.value;
}
`);else if(!q)f.write(`
const ${W}_present = ${N} in input;
if (${W}.issues.length) {
payload.issues = payload.issues.concat(${W}.issues.map(iss => ({
`);else if(!g)Z.write(`
const ${T}_present = ${v} in input;
if (${T}.issues.length) {
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
...iss,
path: iss.path ? [${N}, ...iss.path] : [${N}]
path: iss.path ? [${v}, ...iss.path] : [${v}]
})));
}
if (!${W}_present && !${W}.issues.length) {
if (!${T}_present && !${T}.issues.length) {
payload.issues.push({
code: "invalid_type",
expected: "nonoptional",
input: undefined,
path: [${N}]
path: [${v}]
});
}
if (${W}_present) {
if (${W}.value === undefined) {
newResult[${N}] = undefined;
if (${T}_present) {
if (${T}.value === undefined) {
newResult[${v}] = undefined;
} else {
newResult[${N}] = ${W}.value;
newResult[${v}] = ${T}.value;
}
}
`);else f.write(`
if (${W}.issues.length) {
payload.issues = payload.issues.concat(${W}.issues.map(iss => ({
`);else Z.write(`
if (${T}.issues.length) {
payload.issues = payload.issues.concat(${T}.issues.map(iss => ({
...iss,
path: iss.path ? [${N}, ...iss.path] : [${N}]
path: iss.path ? [${v}, ...iss.path] : [${v}]
})));
}
if (${W}.value === undefined) {
if (${N} in input) {
newResult[${N}] = undefined;
if (${T}.value === undefined) {
if (${v} in input) {
newResult[${v}] = undefined;
}
} else {
newResult[${N}] = ${W}.value;
newResult[${v}] = ${T}.value;
}
`)}f.write("payload.value = newResult;"),f.write("return payload;");let P=f.compile();return(Q,W)=>P(w,Q,W)},u,e=Nt,l=!dt.jitless,I=l&&G$.value,g=i.catchall,b;n._zod.parse=(w,f)=>{b??(b=o.value);let c=w.value;if(!e(c))return w.issues.push({expected:"object",code:"invalid_type",input:c,inst:n}),w;if(l&&I&&f?.async===!1&&f.jitless!==!0){if(!u)u=t(i.shape);if(w=u(w,f),!g)return w;return q0([],c,w,f,b,n)}return r(w,f)}});function G0(n,i,r,o){for(let u of n)if(u.issues.length===0)return i.value=u.value,i;let t=n.filter((u)=>!ai(u));if(t.length===1)return i.value=t[0].value,t[0];return i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:n.map((u)=>u.issues.map((e)=>_n(e,o,dn())))}),i}var Do=U("$ZodUnion",(n,i)=>{E.init(n,i),h(n._zod,"optin",()=>i.options.some((o)=>o._zod.optin==="optional")?"optional":void 0),h(n._zod,"optout",()=>i.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),h(n._zod,"values",()=>{if(i.options.every((o)=>o._zod.values))return new Set(i.options.flatMap((o)=>Array.from(o._zod.values)));return}),h(n._zod,"pattern",()=>{if(i.options.every((o)=>o._zod.pattern)){let o=i.options.map((t)=>t._zod.pattern);return new RegExp(`^(${o.map((t)=>ro(t.source)).join("|")})$`)}return});let r=i.options.length===1?i.options[0]._zod.run:null;n._zod.parse=(o,t)=>{if(r)return r(o,t);let u=!1,e=[];for(let l of i.options){let $=l._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)e.push($),u=!0;else{if($.issues.length===0)return $;e.push($)}}if(!u)return G0(e,o,n,t);return Promise.all(e).then((l)=>{return G0(l,o,n,t)})}});function W0(n,i,r,o){let t=n.filter((u)=>u.issues.length===0);if(t.length===1)return i.value=t[0].value,i;if(t.length===0)i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:n.map((u)=>u.issues.map((e)=>_n(e,o,dn())))});else i.issues.push({code:"invalid_union",input:i.value,inst:r,errors:[],inclusive:!1});return i}var fg=U("$ZodXor",(n,i)=>{Do.init(n,i),i.inclusive=!1;let r=i.options.length===1?i.options[0]._zod.run:null;n._zod.parse=(o,t)=>{if(r)return r(o,t);let u=!1,e=[];for(let l of i.options){let $=l._zod.run({value:o.value,issues:[]},t);if($ instanceof Promise)e.push($),u=!0;else e.push($)}if(!u)return W0(e,o,n,t);return Promise.all(e).then((l)=>{return W0(l,o,n,t)})}}),cg=U("$ZodDiscriminatedUnion",(n,i)=>{i.inclusive=!1,Do.init(n,i);let r=n._zod.parse;h(n._zod,"propValues",()=>{let t={};for(let u of i.options){let e=u._zod.propValues;if(!e||Object.keys(e).length===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(u)}"`);for(let[l,$]of Object.entries(e)){if(!t[l])t[l]=new Set;for(let I of $)t[l].add(I)}}return t});let o=zt(()=>{let t=i.options,u=new Map;for(let e of t){let l=e._zod.propValues?.[i.discriminator];if(!l||l.size===0)throw Error(`Invalid discriminated union option at index "${i.options.indexOf(e)}"`);for(let $ of l){if(u.has($))throw Error(`Duplicate discriminator value "${String($)}"`);u.set($,e)}}return u});n._zod.parse=(t,u)=>{let e=t.value;if(!Nt(e))return t.issues.push({code:"invalid_type",expected:"object",input:e,inst:n}),t;let l=o.value.get(e?.[i.discriminator]);if(l)return l._zod.run(t,u);if(i.unionFallback||u.direction==="backward")return r(t,u);return t.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:i.discriminator,options:Array.from(o.value.keys()),input:e,path:[i.discriminator],inst:n}),t}}),Ug=U("$ZodIntersection",(n,i)=>{E.init(n,i),n._zod.parse=(r,o)=>{let t=r.value,u=i.left._zod.run({value:t,issues:[]},o),e=i.right._zod.run({value:t,issues:[]},o);if(u instanceof Promise||e instanceof Promise)return Promise.all([u,e]).then(([$,I])=>{return j0(r,$,I)});return j0(r,u,e)}});function JI(n,i){if(n===i)return{valid:!0,data:n};if(n instanceof Date&&i instanceof Date&&+n===+i)return{valid:!0,data:n};if(xi(n)&&xi(i)){let r=Object.keys(i),o=Object.keys(n).filter((u)=>r.indexOf(u)!==-1),t={...n,...i};for(let u of o){let e=JI(n[u],i[u]);if(!e.valid)return{valid:!1,mergeErrorPath:[u,...e.mergeErrorPath]};t[u]=e.data}return{valid:!0,data:t}}if(Array.isArray(n)&&Array.isArray(i)){if(n.length!==i.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let o=0;o<n.length;o++){let t=n[o],u=i[o],e=JI(t,u);if(!e.valid)return{valid:!1,mergeErrorPath:[o,...e.mergeErrorPath]};r.push(e.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function j0(n,i,r){let o=new Map,t;for(let l of i.issues)if(l.code==="unrecognized_keys"){t??(t=l);for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).l=!0}}else n.issues.push(l);for(let l of r.issues)if(l.code==="unrecognized_keys")for(let $ of l.keys){if(!o.has($))o.set($,{});o.get($).r=!0}else n.issues.push(l);let u=[...o].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(u.length&&t)n.issues.push({...t,keys:u});if(ai(n))return n;let e=JI(i.value,r.value);if(!e.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(e.mergeErrorPath)}`);return n.value=e.data,n}var Ue=U("$ZodTuple",(n,i)=>{E.init(n,i Line truncated
`)}Z.write("payload.value = newResult;"),Z.write("return payload;");let E=Z.compile();return(A,T)=>E(X,A,T)},Q,K=F7,q=!O7.jitless,H=q&&CO.value,W=I.catchall,V;$._zod.parse=(X,Z)=>{V??(V=Y.value);let w=X.value;if(!K(w))return X.issues.push({expected:"object",code:"invalid_type",input:w,inst:$}),X;if(q&&H&&Z?.async===!1&&Z.jitless!==!0){if(!Q)Q=J(I.shape);if(X=Q(X,Z),!W)return X;return kk([],w,X,Z,V,$)}return U(X,Z)}});function zk($,I,U,Y){for(let Q of $)if(Q.issues.length===0)return I.value=Q.value,I;let J=$.filter((Q)=>!o5(Q));if(J.length===1)return I.value=J[0].value,J[0];return I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:$.map((Q)=>Q.issues.map((K)=>A6(K,Y,Z4())))}),I}var lJ=o("$ZodUnion",($,I)=>{i0.init($,I),a0($._zod,"optin",()=>I.options.some((Y)=>Y._zod.optin==="optional")?"optional":void 0),a0($._zod,"optout",()=>I.options.some((Y)=>Y._zod.optout==="optional")?"optional":void 0),a0($._zod,"values",()=>{if(I.options.every((Y)=>Y._zod.values))return new Set(I.options.flatMap((Y)=>Array.from(Y._zod.values)));return}),a0($._zod,"pattern",()=>{if(I.options.every((Y)=>Y._zod.pattern)){let Y=I.options.map((J)=>J._zod.pattern);return new RegExp(`^(${Y.map((J)=>gJ(J.source)).join("|")})$`)}return});let U=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(Y,J)=>{if(U)return U(Y,J);let Q=!1,K=[];for(let q of I.options){let G=q._zod.run({value:Y.value,issues:[]},J);if(G instanceof Promise)K.push(G),Q=!0;else{if(G.issues.length===0)return G;K.push(G)}}if(!Q)return zk(K,Y,$,J);return Promise.all(K).then((q)=>{return zk(q,Y,$,J)})}});function Ak($,I,U,Y){let J=$.filter((Q)=>Q.issues.length===0);if(J.length===1)return I.value=J[0].value,I;if(J.length===0)I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:$.map((Q)=>Q.issues.map((K)=>A6(K,Y,Z4())))});else I.issues.push({code:"invalid_union",input:I.value,inst:U,errors:[],inclusive:!1});return I}var OF=o("$ZodXor",($,I)=>{lJ.init($,I),I.inclusive=!1;let U=I.options.length===1?I.options[0]._zod.run:null;$._zod.parse=(Y,J)=>{if(U)return U(Y,J);let Q=!1,K=[];for(let q of I.options){let G=q._zod.run({value:Y.value,issues:[]},J);if(G instanceof Promise)K.push(G),Q=!0;else K.push(G)}if(!Q)return Ak(K,Y,$,J);return Promise.all(K).then((q)=>{return Ak(q,Y,$,J)})}}),NF=o("$ZodDiscriminatedUnion",($,I)=>{I.inclusive=!1,lJ.init($,I);let U=$._zod.parse;a0($._zod,"propValues",()=>{let J={};for(let Q of I.options){let K=Q._zod.propValues;if(!K||Object.keys(K).length===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(Q)}"`);for(let[q,G]of Object.entries(K)){if(!J[q])J[q]=new Set;for(let H of G)J[q].add(H)}}return J});let Y=ZI(()=>{let J=I.options,Q=new Map;for(let K of J){let q=K._zod.propValues?.[I.discriminator];if(!q||q.size===0)throw Error(`Invalid discriminated union option at index "${I.options.indexOf(K)}"`);for(let G of q){if(Q.has(G))throw Error(`Duplicate discriminator value "${String(G)}"`);Q.set(G,K)}}return Q});$._zod.parse=(J,Q)=>{let K=J.value;if(!F7(K))return J.issues.push({code:"invalid_type",expected:"object",input:K,inst:$}),J;let q=Y.value.get(K?.[I.discriminator]);if(q)return q._zod.run(J,Q);if(I.unionFallback||Q.direction==="backward")return U(J,Q);return J.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",discriminator:I.discriminator,options:Array.from(Y.value.keys()),input:K,path:[I.discriminator],inst:$}),J}}),FF=o("$ZodIntersection",($,I)=>{i0.init($,I),$._zod.parse=(U,Y)=>{let J=U.value,Q=I.left._zod.run({value:J,issues:[]},Y),K=I.right._zod.run({value:J,issues:[]},Y);if(Q instanceof Promise||K instanceof Promise)return Promise.all([Q,K]).then(([G,H])=>{return Pk(U,G,H)});return Pk(U,Q,K)}});function SN($,I){if($===I)return{valid:!0,data:$};if($ instanceof Date&&I instanceof Date&&+$===+I)return{valid:!0,data:$};if(l5($)&&l5(I)){let U=Object.keys(I),Y=Object.keys($).filter((Q)=>U.indexOf(Q)!==-1),J={...$,...I};for(let Q of Y){let K=SN($[Q],I[Q]);if(!K.valid)return{valid:!1,mergeErrorPath:[Q,...K.mergeErrorPath]};J[Q]=K.data}return{valid:!0,data:J}}if(Array.isArray($)&&Array.isArray(I)){if($.length!==I.length)return{valid:!1,mergeErrorPath:[]};let U=[];for(let Y=0;Y<$.length;Y++){let J=$[Y],Q=I[Y],K=SN(J,Q);if(!K.valid)return{valid:!1,mergeErrorPath:[Y,...K.mergeErrorPath]};U.push(K.data)}return{valid:!0,data:U}}return{valid:!1,mergeErrorPath:[]}}function Pk($,I,U){let Y=new Map,J;for(let q of I.issues)if(q.code==="unrecognized_keys"){J??(J=q);for(let G of q.keys){if(!Y.has(G))Y.set(G,{});Y.get(G).l=!0}}else $.issues.push(q);for(let q of U.issues)if(q.code==="unrecognized_keys")for(let G of q.keys){if(!Y.has(G))Y.set(G,{});Y.get(G).r=!0}else $.issues.push(q);let Q=[...Y].filter(([,q])=>q.l&&q.r).map(([q])=>q);if(Q.length&&J)$.issues.push({...J,keys:Q});if(o5($))return $;let K=SN(I.value,U.value);if(!K.valid)throw Error(`Unmergable intersection. Error path: ${JSON.stringify(K.mergeErrorPath)}`);return $.value=K.data,$}var IH=o("$ZodTuple",($,I)=>{i0. Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let e of n.seen.entries()){let l=e[1];if(i===e[0]){u(e);continue}if(n.external){let I=n.external.registry.get(e[0])?.id;if(i!==e[0]&&I){u(e);continue}}if(n.metadataRegistry.get(e[0])?.id){u(e);continue}if(l.cycle){u(e);continue}if(l.count>1){if(n.reused==="ref"){u(e);continue}}}}function rt(n,i){let r=n.seen.get(i);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let o=(l)=>{let $=n.seen.get(l);if($.ref===null)return;let I=$.def??$.schema,g={...I},b=$.ref;if($.ref=null,b){o(b);let f=n.seen.get(b),c=f.schema;if(c.$ref&&(n.target==="draft-07"||n.target==="draft-04"||n.target==="openapi-3.0"))I.allOf=I.allOf??[],I.allOf.push(c);else Object.assign(I,c);if(Object.assign(I,g),l._zod.parent===b)for(let d in I){if(d==="$ref"||d==="allOf")continue;if(!(d in g))delete I[d]}if(c.$ref&&f.def)for(let d in I){if(d==="$ref"||d==="allOf")continue;if(d in f.def&&JSON.stringify(I[d])===JSON.stringify(f.def[d]))delete I[d]}}let w=l._zod.parent;if(w&&w!==b){o(w);let f=n.seen.get(w);if(f?.schema.$ref){if(I.$ref=f.schema.$ref,f.def)for(let c in I){if(c==="$ref"||c==="allOf")continue;if(c in f.def&&JSON.stringify(I[c])===JSON.stringify(f.def[c]))delete I[c]}}}n.override({zodSchema:l,jsonSchema:I,path:$.path??[]})};for(let l of[...n.seen.entries()].reverse())o(l[0]);let t={};if(n.target==="draft-2020-12")t.$schema="https://json-schema.org/draft/2020-12/schema";else if(n.target==="draft-07")t.$schema="http://json-schema.org/draft-07/schema#";else if(n.target==="draft-04")t.$schema="http://json-schema.org/draft-04/schema#";else if(n.target==="openapi-3.0");if(n.external?.uri){let l=n.external.registry.get(i)?.id;if(!l)throw Error("Schema is missing an `id` property");t.$id=n.external.uri(l)}Object.assign(t,r.def??r.schema);let u=n.metadataRegistry.get(i)?.id;if(u!==void 0&&t.id===u)delete t.id;let e=n.external?.defs??{};for(let l of n.seen.entries()){let $=l[1];if($.def&&$.defId){if($.def.id===$.defId)delete $.def.id;e[$.defId]=$.def}}if(n.external);else if(Object.keys(e).length>0)if(n.target==="draft-2020-12")t.$defs=e;else t.definitions=e;try{let l=JSON.parse(JSON.stringify(t));return Object.defineProperty(l,"~standard",{value:{...i["~standard"],jsonSchema:{input:fr(i,"input",n.processors),output:fr(i,"output",n.processors)}},enumerable:!1,writable:!1}),l}catch(l){throw Error("Error converting schema to JSON.")}}function Mn(n,i){let r=i??{seen:new Set};if(r.seen.has(n))return!1;r.seen.add(n);let o=n._zod.def;if(o.type==="transform")return!0;if(o.type==="array")return Mn(o.element,r);if(o.type==="set")return Mn(o.valueType,r);if(o.type==="lazy")return Mn(o.getter(),r);if(o.type==="promise"||o.type==="optional"||o.type==="nonoptional"||o.type==="nullable"||o.type==="readonly"||o.type==="default"||o.type==="prefault")return Mn(o.innerType,r);if(o.type==="intersection")return Mn(o.left,r)||Mn(o.right,r);if(o.type==="record"||o.type==="map")return Mn(o.keyType,r)||Mn(o.valueType,r);if(o.type==="pipe"){if(n._zod.traits.has("$ZodCodec"))return!0;return Mn(o.in,r)||Mn(o.out,r)}if(o.type==="object"){for(let t in o.shape)if(Mn(o.shape[t],r))return!0;return!1}if(o.type==="union"){for(let t of o.options)if(Mn(t,r))return!0;return!1}if(o.type==="tuple"){for(let t of o.items)if(Mn(t,r))return!0;if(o.rest&&Mn(o.rest,r))return!0;return!1}return!1}var kw=(n,i={})=>(r)=>{let o=it({...r,processors:i});return en(n,o),tt(o,n),rt(o,n)},fr=(n,i,r={})=>(o)=>{let{libraryOptions:t,target:u}=o??{},e=it({...t??{},target:u,io:i,processors:r});return en(n,e),tt(e,n),rt(e,n)};var Ij={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Nw=(n,i,r,o)=>{let t=r;t.type="string";let{minimum:u,maximum:e,format:l,patterns:$,contentEncoding:I}=n._zod.bag;if(typeof u==="number")t.minLength=u;if(typeof e==="number")t.maxLength=e;if(l){if(t.format=Ij[l]??l,t.format==="")delete t.format;if(l==="time")delete t.format}if(I)t.contentEncoding=I;if($&&$.size>0){let g=[...$];if(g.length===1)t.pattern=g[0].source;else if(g.length>1)t.allOf=[...g.map((b)=>({...i.target==="draft-07"||i.target==="draft-04"||i.target==="openapi-3.0"?{type:"string"}:{},pattern:b.source}))]}},Lw=(n,i,r,o)=>{let t=r,{minimum:u,maximum:e,format:l,multipleOf:$,exclusiveMaximum:I,exclusiveMinimum:g}=n._zod.bag;if(typeof l==="string"&&l.includes("int"))t.type="integer";else t.type="number";let b=typeof g==="number"&&g>=(u??Number.NEGATIVE_INFINITY),w=typeof I==="number"&&I<=(e??Number.POSITIVE_INFINITY),f=i.target==="draft-04"||i.target==="openapi-3.0";if(b)if(f)t.minimum=g,t.exclusiveMinimum=!0;else t.exclusiveMinimum=g;else if(typeof u==="number")t.minimum=u;if(w)if(f)t.maximum=I,t.exclusiveMaximum=!0;else t.exclusiveMaximum=I;else if(typeof e==="number")t.maximum=e;if(typeof $==="number")t.multipleOf=$},yw=(n,i,r,o)=>{r.type="boolean"},Gw=(n,i,r,o)=>{if(i.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},Ww=(n,i,r,o)=>{if(i.unrepresentable==="Line truncated
`);if(n===-1)return null;let i=this._buffer.toString("utf8",0,n).replace(/\r$/,"");return this._buffer=this._buffer.subarray(n+1),YQ(i)}clear(){this._buffer=void 0}}function YQ(n){return AD.parse(JSON.parse(n))}function cd(n){return JSON.stringify(n)+`
`}class V6{constructor(n=Ud.stdin,i=Ud.stdout){this._stdin=n,this._stdout=i,this._readBuffer=new T6,this._started=!1,this._ondata=(r)=>{this._readBuffer.append(r),this.processReadBuffer()},this._onerror=(r)=>{this.onerror?.(r)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let n=this._readBuffer.readMessage();if(n===null)break;this.onmessage?.(n)}catch(n){this.onerror?.(n)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send(n){return new Promise((i)=>{let r=cd(n);if(this._stdout.write(r))i();else this._stdout.once("drain",i)})}}import{dirname as s4,join as MK}from"node:path";import{fileURLToPath as zK}from"node:url";class Zi extends Error{name="KyError";get isKyError(){return!0}}class ti extends Zi{name="HTTPError";response;request;options;data;constructor(n,i,r){let o=n.status||n.status===0?n.status:"",t=n.statusText??"",u=`${o} ${t}`.trim(),e=u?`status code ${u}`:"an unknown error";super(`Request failed with ${e}: ${i.method} ${i.url}`);this.response=n,this.request=i,this.options=r}}class ku extends Zi{name="NetworkError";request;constructor(n,i){super(`Request failed due to a network error: ${n.method} ${n.url}`,i);this.request=n}}class Nu extends Error{name="NonError";value;constructor(n){let i="Non-error value was thrown";try{if(typeof n==="string")i=n;else if(n&&typeof n==="object"&&"message"in n&&typeof n.message==="string")i=n.message}catch{}super(i);this.value=n}}class Vr extends Zi{name="ForceRetryError";customDelay;code;customRequest;constructor(n){let i=n?.cause?n.cause instanceof Error?n.cause:new Nu(n.cause):void 0;super(n?.code?`Forced retry: ${n.code}`:"Forced retry",i?{cause:i}:void 0);this.customDelay=n?.delay,this.code=n?.code,this.customRequest=n?.request}}class q6 extends Error{name="SchemaValidationError";issues;constructor(n){super("Response schema validation failed");this.issues=n}}class Oi extends Zi{name="TimeoutError";request;constructor(n){super(`Request timed out: ${n.method} ${n.url}`);this.request=n}}var _6=(()=>{let n=!1,i=!1,r=typeof globalThis.ReadableStream==="function",o=typeof globalThis.Request==="function";if(r&&o)try{i=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return n=!0,"half"}}).headers.has("Content-Type")}catch(t){if(t instanceof Error&&t.message==="unsupported BodyInit type")return!1;throw t}return n&&!i})(),Dd=typeof globalThis.AbortController==="function",kv=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",Sd=typeof globalThis.ReadableStream==="function",Ad=typeof globalThis.FormData==="function",Nv=["get","post","put","patch","head","delete"],pQ=()=>{return};pQ();var Od={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},qr=2147483647,dd=40,Lv=Symbol("stop");class yv{options;constructor(n){this.options=n}}var kd=(n)=>new yv(n),Nd={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},Ld={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var Gv=new TextEncoder,QQ=(n)=>{if(!n)return 0;if(n instanceof FormData){let i=0;for(let[r,o]of n)i+=dd,i+=Gv.encode(`Content-Disposition: form-data; name="${r}"`).byteLength,i+=typeof o==="string"?Gv.encode(o).byteLength:o.size;return i}if(n instanceof Blob)return n.size;if(n instanceof ArrayBuffer||ArrayBuffer.isView(n))return n.byteLength;if(typeof n==="string")return Gv.encode(n).byteLength;if(n instanceof URLSearchParams)return Gv.encode(n.toString()).byteLength;return 0},yd=(n,i,r)=>{let o,t=0;return n.pipeThrough(new TransformStream({transform(u,e){if(e.enqueue(u),o){t+=o.byteLength;let l=i===0?0:t/i;if(l>=1)l=1-Number.EPSILON;r?.({percent:l,totalBytes:Math.max(i,t),transferredBytes:t},o)}o=u},flush(){if(o)t+=o.byteLength,r?.({percent:1,totalBytes:Math.max(i,t),transferredBytes:t},o)}}))},Gd=(n,i)=>{if(!n.body)return n;let r={status:n.status,statusText:n.statusText,headers:n.headers};if(n.status===204)return new Response(null,r);let o=Math.max(0,Number(n.headers.get("content-length"))||0);return new Response(yd(n.body,o,i),r)},Wd=(n,i,r)=>{if(!n.body)return n;let o=QQ(r??n.body);return new Request(n,{duplex:"half",body:yd(n.body,o,i)})};var Hi=(n)=>n!==null&&typeof n==="object";var PQ=Symbol("replaceOption"),Z6=(n)=>Hi(n)&&n[PQ]===!0?{isReplace:!0,value:n.value}:{isReplace:!1,value:n};var yu=(...n)=>{for(let i of n)if((!Hi(i)| Line truncated
`,{mode:384}),i}function Rr(n,i,r=[]){let o=i.corpId?.trim()||void 0,t=i.stateful?i.defaultCorpId?.trim()||void 0:void 0,u=o??t;if(u){let l=n.find(($)=>$.id===u);if(l)return l;throw Error(`No enterprise config found for ${u}`)}if(!i.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-home config mode stateful` to enable a default enterprise.");let e=n[0];if(e)return e;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(r.length?r.join(", "):"the configured enterprise directories"))}import{readFileSync as gF}from"node:fs";import{randomBytes as bF}from"node:crypto";import{randomBytes as Tk}from"node:crypto";var JP=v.object({staffId:v.string(),name:v.string().optional(),code:v.string().default(""),bindTime:v.number().optional()}),XP=v.object({id:v.string(),tenantId:v.string(),name:v.string(),isAdmin:v.boolean().default(!1),permissions:v.array(v.string()).default([]),providerUserId:v.string().optional(),hosecloudStaff:JP.optional()}),HP=v.object({apiKey:v.string().optional(),corporationId:v.string().optional(),corporationName:v.string().optional()}),YP=v.object({id:v.string(),name:v.string(),tenantSlug:v.string().optional(),isDemo:v.boolean().default(!1),logoUrl:v.string().nullable().optional(),hoseCorpConfig:HP.optional()}),Sk=v.object({user:XP,tenant:YP}),pP=v.object({id:v.string(),name:v.string(),email:v.string().nullable().optional(),emailVerified:v.boolean().optional(),image:v.string().nullable().optional(),tenantId:v.string().optional(),provider:v.string().optional(),providerUserId:v.string().optional(),mobile:v.string().nullable().optional(),status:v.string().optional(),permissions:v.array(v.string()).default([]),isAdmin:v.boolean().default(!1),hosecloudStaff:v.unknown().optional()}).passthrough(),QP=v.object({id:v.string(),token:v.string().optional(),expiresAt:v.string(),createdAt:v.string().optional(),updatedAt:v.string().optional(),ipAddress:v.string().optional(),userAgent:v.string().optional(),userId:v.string(),delegationId:v.string().nullable().optional()}).passthrough(),Ak=v.object({user:pP,session:QP}),_v=v.object({id:v.string(),tenantId:v.string().optional(),code:v.number().optional(),description:v.string(),scope:v.string(),strictness:v.string(),status:v.string().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional()}),Ok=v.object({rules:v.array(_v),hasPendingDeletes:v.boolean().default(!1)}),PP=v.object({code:v.string().optional(),description:v.string(),scope:v.string(),strictness:v.string()}),Zv=v.object({id:v.string(),tenantId:v.string().optional(),versionNumber:v.number(),versionName:v.string().nullable().optional(),publishedBy:v.string().nullable().optional(),publishedByName:v.string().nullable().optional(),rules:v.array(PP).default([]),publishedAt:v.number().optional(),createdAt:v.number().optional()}),dk=v.object({version:Zv,rulesCount:v.number()}),pu=v.object({id:v.string(),tenantId:v.string().optional(),title:v.string(),purpose:v.string().default(""),contentType:v.string().default("policy"),content:v.string(),status:v.string().default("published"),enabled:v.boolean().default(!0),scenarios:v.array(v.string()).default([]),tags:v.array(v.string()).default([]),category:v.string().nullable().optional(),categoryTags:v.array(v.string()).default([]),createdBy:v.string().nullable().optional(),createdByName:v.string().nullable().optional(),createdAt:v.number().optional(),updatedAt:v.number().optional(),updatedBy:v.string().nullable().optional(),updatedByName:v.string().nullable().optional(),isDeleted:v.boolean().default(!1)}),kk=v.object({articles:v.array(pu),total:v.number().optional()}),FP=v.object({explicitApprove:v.string().default(""),explicitReject:v.string().default(""),exemptApprove:v.string().default(""),review:v.string().default("")}).passthrough(),KP=v.object({type:v.string(),signKey:v.string().optional(),outboundName:v.string().optional(),mode:v.string().optional(),autoApprovalRate:v.number().optional(),apiKey:v.string().optional(),apiSecret:v.string().optional(),apiOrigin:v.string().optional(),corporationId:v.string().optional(),ebotSignKey:v.string().optional(),completionSignKey:v.string().optional(),outboundMessageId:v.string().optional(),completionMessageId:v.string().optional()}).passthrough(),BP=v.enum(["assisted","semi_automatic","fully_automatic"]),Dk=v.object({id:v.string(),url:v.string().url()}).passthrough(),Qu=v.object({type:v.literal("webhook"),id:v.string(),name:v.string(),mode:BP,incomingDocumentWebhook:Dk,outgoingResultWebhook:v.string().url(),incomingManualResultWebhook:Dk,secret:v.string().min(1),autoApprovalRate:v.number().int().min(0).max(100).optional()}).passthrough(),v4=v.object({id:v.string().optional(),tenantId:v.string().optional(),tone:v.string().optional(),language:v.string().optional(),detailLevel:v.string().optional(),outputFormat:v.string().optional(),examples:v.array(v.string()).default([]),prohibitedPhrases:v.array(v.string()).default([]),cus Line truncated
`);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,document:Dt({id:i?.id,sn:i?.sn??i?.sourceDocumentSN??n.sourceDocumentSN,title:i?.title??i?.name,template:n$(i,["template.name","templateName","form.name","formName","formTitle"]),amount:av(r,["金额","报销金额","付款金额","合计","价税合计"])??n$(i,["amount","totalAmount","expenseAmount"]),expenseType:av(r,["费用类型","费用类别","报销类型"]),costCompany:av(r,["费用承担公司","承担公司","成本中心","费用归属"]),payee:av(r,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:r.slice(0,30)}),invoices:XF(n),attachments:CN(n,{summary:!0}).attachments,aiResult:t$(n),manualResult:qt(n)?.value,hints:Dt({amountMentions:PN(o,["金额","合计","税率"],8),partyMentions:PN(o,["买方","卖方","甲方","乙方","收款"],8)})}}function CN(n,i={}){let r=[["document",n.document],["result",n.result],["pipelineData",n.pipelineData],["sourceExtendData",n.sourceExtendData]],o=[],t=new Set;for(let[u,e]of r)G4(e,u,o,t);return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,count:o.length,attachments:i.summary?o.map((u)=>Dt({path:u.path,kind:u.kind,fileName:u.fileName,mimeType:u.mimeType,fileId:u.fileId,sourceField:u.sourceField})):o}}function LF(n){let i=[["result.citedRules",zi(n,"result.citedRules")],["result.matchedRules",zi(n,"result.matchedRules")],["result.ruleResults",zi(n,"result.ruleResults")],["result.rules",zi(n,"result.rules")],["pipelineData.citedRules",zi(n,"pipelineData.citedRules")],["pipelineData.matchedRules",zi(n,"pipelineData.matchedRules")]],r=[],o=new Set;for(let[t,u]of i)(Array.isArray(u)?u:u&&typeof u==="object"?Object.values(u):[]).forEach((l,$)=>{let I=mr(l);if(!I)return;let g=V(I.runtimeRuleId)??V(I.runtimeId)??V(I.id)??V(I.ruleId),b=V(I.ruleCode)??V(I.code)??(g?pF(g):void 0),w=Dt({runtimeRuleId:g,ruleCode:b,versionNumber:jF(I.versionNumber)??n.ruleSetVersionNumber,scope:V(I.scope),strictness:V(I.strictness),appliedAnalysis:I.appliedAnalysis??I.analysis??I.reasoning,checkResult:I.checkResult??I.result??I.decision,findings:I.findings??I.riskPoints??I.evidence,sourcePath:`${t}.${$}`}),f=JSON.stringify(w);if(!o.has(f))o.add(f),r.push(w)});return{recordId:n.id,sourceDocumentSN:n.sourceDocumentSN,sourceDocumentId:n.sourceDocumentId,ruleSetVersionNumber:n.ruleSetVersionNumber,count:r.length,rules:r}}function G4(n,i,r,o){if(Array.isArray(n)){n.forEach((u,e)=>G4(u,`${i}.${e}`,r,o));return}let t=mr(n);if(!t)return;if(yF(t,i)){let u=Dt({path:i,fieldPath:i,kind:GF(i,t),fileName:V(t.fileName)??V(t.filename)??V(t.name)??V(t.originalName),mimeType:V(t.mimeType)??V(t.mimetype)??V(t.contentType),fileId:V(t.fileId)??V(t.id)??V(t.attachmentId),ossPath:V(t.ossPath)??V(t.ossKey)??V(t.key),url:V(t.url)??V(t.signedUrl)??V(t.downloadUrl)??V(t.previewUrl),invoiceId:V(t.invoiceId),sourceField:V(t.fieldName)??V(t.label)}),e=JSON.stringify(u);if(!o.has(e))o.add(e),r.push(u)}for(let[u,e]of Object.entries(t))G4(e,`${i}.${u}`,r,o)}function yF(n,i){let r=Object.keys(n).map((u)=>u.toLowerCase());return/(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(i)&&["filename","fileName","mimeType","mimetype","contentType","fileId","ossPath","signedUrl","downloadUrl","previewUrl","attachmentId"].some((u)=>r.includes(u.toLowerCase()))}function GF(n,i){let r=`${n} ${V(i.type)??""}`.toLowerCase();if(r.includes("invoice")||r.includes("发票"))return"invoice";if(r.includes("receipt"))return"receipt";return"attachment"}function n$(n,i){if(!n)return;for(let r of i){let o=zi(n,r);if(o!==void 0)return o}return}function QN(n,i){if(!n)return 0;for(let r of i){let o=zi(n,r);if(Array.isArray(o))return o.length;if(o&&typeof o==="object")return Object.keys(o).length;if(typeof o==="number")return o}return 0}function zi(n,i){return i.split(".").reduce((r,o)=>{if(r===void 0||r===null)return;if(Array.isArray(r)){let t=Number(o);return Number.isInteger(t)?r[t]:void 0}if(typeof r==="object")return r[o];return},n)}function WF(n,i,r){let o=i.split("."),t=n;for(let u of o.slice(0,-1)){let e=t[u];if(!e||typeof e!=="object"||Array.isArray(e))t[u]={};t=t[u]}t[o[o.length-1]??i]=r}function Dt(n){return Object.fromEntries(Object.entries(n).filter(([,i])=>i!==void 0))}function mr(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:void 0}function jF(n){return typeof n==="number"&&Number.isFinite(n)?n:void 0}function JF(n){let i=[];return W4(n,"document",i),i}function W4(n,i,r){if(Array.isArray(n)){n.forEach((e,l)=>W4(e,`${i}.${l}`,r));return}let o=mr(n);if(!o)return;let t=V(o.label)??V(o.name)??V(o.title)??V(o.fieldName),u=o.value??o.displayValue??o.text??o.content;if(t&&u!==void 0&&typeof u!=="object")r.push(Dt({path:i,label:t,value:u,type:V(o.type)??V(o.fieldType)}));for(let[e,l]of Object.entries(o)){if(e==="attachments")continue;W4(l,`${i}.${e}`,r)}}function av(n,i){return n.find((o)=>{let t=V(o.label)??"";return i.some((u)=>t.includes(u)) Line truncated
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let K of $.seen.entries()){let q=K[1];if(I===K[0]){Q(K);continue}if($.external){let H=$.external.registry.get(K[0])?.id;if(I!==K[0]&&H){Q(K);continue}}if($.metadataRegistry.get(K[0])?.id){Q(K);continue}if(q.cycle){Q(K);continue}if(q.count>1){if($.reused==="ref"){Q(K);continue}}}}function e5($,I){let U=$.seen.get(I);if(!U)throw Error("Unprocessed schema. This is a bug in Zod.");let Y=(q)=>{let G=$.seen.get(q);if(G.ref===null)return;let H=G.def??G.schema,W={...H},V=G.ref;if(G.ref=null,V){Y(V);let Z=$.seen.get(V),w=Z.schema;if(w.$ref&&($.target==="draft-07"||$.target==="draft-04"||$.target==="openapi-3.0"))H.allOf=H.allOf??[],H.allOf.push(w);else Object.assign(H,w);if(Object.assign(H,W),q._zod.parent===V)for(let O in H){if(O==="$ref"||O==="allOf")continue;if(!(O in W))delete H[O]}if(w.$ref&&Z.def)for(let O in H){if(O==="$ref"||O==="allOf")continue;if(O in Z.def&&JSON.stringify(H[O])===JSON.stringify(Z.def[O]))delete H[O]}}let X=q._zod.parent;if(X&&X!==V){Y(X);let Z=$.seen.get(X);if(Z?.schema.$ref){if(H.$ref=Z.schema.$ref,Z.def)for(let w in H){if(w==="$ref"||w==="allOf")continue;if(w in Z.def&&JSON.stringify(H[w])===JSON.stringify(Z.def[w]))delete H[w]}}}$.override({zodSchema:q,jsonSchema:H,path:G.path??[]})};for(let q of[...$.seen.entries()].reverse())Y(q[0]);let J={};if($.target==="draft-2020-12")J.$schema="https://json-schema.org/draft/2020-12/schema";else if($.target==="draft-07")J.$schema="http://json-schema.org/draft-07/schema#";else if($.target==="draft-04")J.$schema="http://json-schema.org/draft-04/schema#";else if($.target==="openapi-3.0");if($.external?.uri){let q=$.external.registry.get(I)?.id;if(!q)throw Error("Schema is missing an `id` property");J.$id=$.external.uri(q)}Object.assign(J,U.def??U.schema);let Q=$.metadataRegistry.get(I)?.id;if(Q!==void 0&&J.id===Q)delete J.id;let K=$.external?.defs??{};for(let q of $.seen.entries()){let G=q[1];if(G.def&&G.defId){if(G.def.id===G.defId)delete G.def.id;K[G.defId]=G.def}}if($.external);else if(Object.keys(K).length>0)if($.target==="draft-2020-12")J.$defs=K;else J.definitions=K;try{let q=JSON.parse(JSON.stringify(J));return Object.defineProperty(q,"~standard",{value:{...I["~standard"],jsonSchema:{input:yI(I,"input",$.processors),output:yI(I,"output",$.processors)}},enumerable:!1,writable:!1}),q}catch(q){throw Error("Error converting schema to JSON.")}}function T6($,I){let U=I??{seen:new Set};if(U.seen.has($))return!1;U.seen.add($);let Y=$._zod.def;if(Y.type==="transform")return!0;if(Y.type==="array")return T6(Y.element,U);if(Y.type==="set")return T6(Y.valueType,U);if(Y.type==="lazy")return T6(Y.getter(),U);if(Y.type==="promise"||Y.type==="optional"||Y.type==="nonoptional"||Y.type==="nullable"||Y.type==="readonly"||Y.type==="default"||Y.type==="prefault")return T6(Y.innerType,U);if(Y.type==="intersection")return T6(Y.left,U)||T6(Y.right,U);if(Y.type==="record"||Y.type==="map")return T6(Y.keyType,U)||T6(Y.valueType,U);if(Y.type==="pipe"){if($._zod.traits.has("$ZodCodec"))return!0;return T6(Y.in,U)||T6(Y.out,U)}if(Y.type==="object"){for(let J in Y.shape)if(T6(Y.shape[J],U))return!0;return!1}if(Y.type==="union"){for(let J of Y.options)if(T6(J,U))return!0;return!1}if(Y.type==="tuple"){for(let J of Y.items)if(T6(J,U))return!0;if(Y.rest&&T6(Y.rest,U))return!0;return!1}return!1}var Ez=($,I={})=>(U)=>{let Y=a5({...U,processors:I});return C1($,Y),s5(Y,$),e5(Y,$)},yI=($,I,U={})=>(Y)=>{let{libraryOptions:J,target:Q}=Y??{},K=a5({...J??{},target:Q,io:I,processors:U});return C1($,K),s5(K,$),e5(K,$)};var vO0={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Bz=($,I,U,Y)=>{let J=U;J.type="string";let{minimum:Q,maximum:K,format:q,patterns:G,contentEncoding:H}=$._zod.bag;if(typeof Q==="number")J.minLength=Q;if(typeof K==="number")J.maxLength=K;if(q){if(J.format=vO0[q]??q,J.format==="")delete J.format;if(q==="time")delete J.format}if(H)J.contentEncoding=H;if(G&&G.size>0){let W=[...G];if(W.length===1)J.pattern=W[0].source;else if(W.length>1)J.allOf=[...W.map((V)=>({...I.target==="draft-07"||I.target==="draft-04"||I.target==="openapi-3.0"?{type:"string"}:{},pattern:V.source}))]}},Rz=($,I,U,Y)=>{let J=U,{minimum:Q,maximum:K,format:q,multipleOf:G,exclusiveMaximum:H,exclusiveMinimum:W}=$._zod.bag;if(typeof q==="string"&&q.includes("int"))J.type="integer";else J.type="number";let V=typeof W==="number"&&W>=(Q??Number.NEGATIVE_INFINITY),X=typeof H==="number"&&H<=(K??Number.POSITIVE_INFINITY),Z=I.target==="draft-04"||I.target==="openapi-3.0";if(V)if(Z)J.minimum=W,J.exclusiveMinimum=!0;else J.exclusiveMinimum=W;else if(typeof Q==="number")J.minimum=Q;if(X)if(Z)J.maximum=H,J.exclusiveMaximum=!0;else J.exclusiveMaximum=H;else if(typeof K==="number")J.maximum=K;if(typeof G==="number")J.multipleOf=G},vz=($,I,U,Y)=>{U.type="boolean"},Cz=($,I,U,Y)=>{if(I.unrepresentable==="throw")throw Error("BigInt cannot be represented in JSON Schema")},jz=($,I,U,Y)=>{if(I.unrepresentable==Line truncated
`);if($===-1)return null;let I=this._buffer.toString("utf8",0,$).replace(/\r$/,"");return this._buffer=this._buffer.subarray($+1),tR0(I)}clear(){this._buffer=void 0}}function tR0($){return Lf.parse(JSON.parse($))}function Zc($){return JSON.stringify($)+`
`}class nT{constructor($=Xc.stdin,I=Xc.stdout){this._stdin=$,this._stdout=I,this._readBuffer=new pT,this._started=!1,this._ondata=(U)=>{this._readBuffer.append(U),this.processReadBuffer()},this._onerror=(U)=>{this.onerror?.(U)}}async start(){if(this._started)throw Error("StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.");this._started=!0,this._stdin.on("data",this._ondata),this._stdin.on("error",this._onerror)}processReadBuffer(){while(!0)try{let $=this._readBuffer.readMessage();if($===null)break;this.onmessage?.($)}catch($){this.onerror?.($)}}async close(){if(this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0)this._stdin.pause();this._readBuffer.clear(),this.onclose?.()}send($){return new Promise((I)=>{let U=Zc($);if(this._stdout.write(U))I();else this._stdout.once("drain",I)})}}import{dirname as Dx,join as jG1}from"node:path";import{fileURLToPath as _G1}from"node:url";class I5 extends Error{name="KyError";get isKyError(){return!0}}class i6 extends I5{name="HTTPError";response;request;options;data;constructor($,I,U){let Y=$.status||$.status===0?$.status:"",J=$.statusText??"",Q=`${Y} ${J}`.trim(),K=Q?`status code ${Q}`:"an unknown error";super(`Request failed with ${K}: ${I.method} ${I.url}`);this.response=$,this.request=I,this.options=U}}class aQ extends I5{name="NetworkError";request;constructor($,I){super(`Request failed due to a network error: ${$.method} ${$.url}`,I);this.request=$}}class sQ extends Error{name="NonError";value;constructor($){let I="Non-error value was thrown";try{if(typeof $==="string")I=$;else if($&&typeof $==="object"&&"message"in $&&typeof $.message==="string")I=$.message}catch{}super(I);this.value=$}}class qU extends I5{name="ForceRetryError";customDelay;code;customRequest;constructor($){let I=$?.cause?$.cause instanceof Error?$.cause:new sQ($.cause):void 0;super($?.code?`Forced retry: ${$.code}`:"Forced retry",I?{cause:I}:void 0);this.customDelay=$?.delay,this.code=$?.code,this.customRequest=$?.request}}class cT extends Error{name="SchemaValidationError";issues;constructor($){super("Response schema validation failed");this.issues=$}}class d$ extends I5{name="TimeoutError";request;constructor($){super(`Request timed out: ${$.method} ${$.url}`);this.request=$}}var dT=(()=>{let $=!1,I=!1,U=typeof globalThis.ReadableStream==="function",Y=typeof globalThis.Request==="function";if(U&&Y)try{I=new globalThis.Request("https://empty.invalid",{body:new globalThis.ReadableStream,method:"POST",get duplex(){return $=!0,"half"}}).headers.has("Content-Type")}catch(J){if(J instanceof Error&&J.message==="unsupported BodyInit type")return!1;throw J}return $&&!I})(),Lc=typeof globalThis.AbortController==="function",qV=typeof globalThis.AbortSignal==="function"&&typeof globalThis.AbortSignal.any==="function",wc=typeof globalThis.ReadableStream==="function",Dc=typeof globalThis.FormData==="function",GV=["get","post","put","patch","head","delete"],aR0=()=>{return};aR0();var Oc={json:"application/json",text:"text/*",formData:"multipart/form-data",arrayBuffer:"*/*",blob:"*/*",bytes:"*/*"},GU=2147483647,Nc=40,HV=Symbol("stop");class WV{options;constructor($){this.options=$}}var Fc=($)=>new WV($),Mc={json:!0,parseJson:!0,stringifyJson:!0,searchParams:!0,baseUrl:!0,prefix:!0,retry:!0,timeout:!0,totalTimeout:!0,hooks:!0,throwHttpErrors:!0,onDownloadProgress:!0,onUploadProgress:!0,fetch:!0,context:!0},zc={method:!0,headers:!0,body:!0,mode:!0,credentials:!0,cache:!0,redirect:!0,referrer:!0,referrerPolicy:!0,integrity:!0,keepalive:!0,signal:!0,window:!0,duplex:!0};var VV=new TextEncoder,sR0=($)=>{if(!$)return 0;if($ instanceof FormData){let I=0;for(let[U,Y]of $)I+=Nc,I+=VV.encode(`Content-Disposition: form-data; name="${U}"`).byteLength,I+=typeof Y==="string"?VV.encode(Y).byteLength:Y.size;return I}if($ instanceof Blob)return $.size;if($ instanceof ArrayBuffer||ArrayBuffer.isView($))return $.byteLength;if(typeof $==="string")return VV.encode($).byteLength;if($ instanceof URLSearchParams)return VV.encode($.toString()).byteLength;return 0},Ac=($,I,U)=>{let Y,J=0;return $.pipeThrough(new TransformStream({transform(Q,K){if(K.enqueue(Q),Y){J+=Y.byteLength;let q=I===0?0:J/I;if(q>=1)q=1-Number.EPSILON;U?.({percent:q,totalBytes:Math.max(I,J),transferredBytes:J},Y)}Y=Q},flush(){if(Y)J+=Y.byteLength,U?.({percent:1,totalBytes:Math.max(I,J),transferredBytes:J},Y)}}))},Pc=($,I)=>{if(!$.body)return $;let U={status:$.status,statusText:$.statusText,headers:$.headers};if($.status===204)return new Response(null,U);let Y=Math.max(0,Number($.headers.get("content-length"))||0);return new Response(Ac($.body,Y,I),U)},Tc=($,I,U)=>{if(!$.body)return $;let Y=sR0(U??$.body);return new Request($,{duplex:"half",body:Ac($.body,Y,I)})};var Z8=($)=>$!==null&&typeof $==="object";var eR0=Symbol("replaceOption"),mT=($)=>Z8($)&&$[eR0]===!0?{isReplace:!0,value:$.value}:{isReplace:!1,value:$};var $2=(...$)=>{for(let I of $)if( Line truncated
`,{mode:384}),I}function WJ($,I,U=[]){let Y=I.corpId?.trim()||void 0,J=I.stateful?I.defaultCorpId?.trim()||void 0:void 0,Q=Y??J;if(Q){let q=$.find((G)=>G.id===Q);if(q)return q;throw Error(`No enterprise config found for ${Q}`)}if(!I.stateful)throw Error("Stateless mode is enabled. Every enterprise command requires --corp <corpId>. Use `seal-home config mode stateful` to enable a default enterprise.");let K=$[0];if(K)return K;throw Error("No enterprise config found. Add a non-example JSON file under one of: "+(U.length?U.join(", "):"the configured enterprise directories"))}import{readFileSync as Uq1}from"node:fs";import{randomBytes as Yq1}from"node:crypto";var sW0=300000,tW0=new Map;function bQ1($,I){return $.map((U)=>U.trim()).filter(Boolean).map((U)=>I?U:U.toLowerCase())}function iQ1($,I){return I?$:$.toLowerCase()}function pQ1($,I,U,Y){let J=iQ1($,Y),Q=I.filter((K)=>J.includes(K));if(U==="all"&&Q.length!==I.length)return[];return Q}function nQ1($){if(typeof $==="string")return $.split(/\r?\n/);return JSON.stringify($,null,2).split(/\r?\n/)}function cQ1($,I){if(I.fields&&!I.fields.has($.field))return[];let U=nQ1($.value),Y=[];return U.forEach((J,Q)=>{let K=pQ1(J,I.keywords,I.matchMode,I.caseSensitive);if(K.length===0)return;let q=Math.max(0,Q-I.contextLines),G=Math.min(U.length,Q+I.contextLines+1),H={area:$.area,entityType:$.entityType,entityId:$.entityId,title:$.title,field:$.field,lineNumber:Q+1,matchedKeywords:K,matchedText:RD(J,I.maxChars),context:{before:I.snippetOnly?[]:U.slice(q,Q).map((W)=>RD(W,I.maxChars)),line:RD(J,I.maxChars),after:I.snippetOnly?[]:U.slice(Q+1,G).map((W)=>RD(W,I.maxChars))},metadata:$.metadata};if(I.snippetOnly)H.context={before:[],line:H.context.line,after:[]};Y.push(H)}),Y}function RD($,I){if(!I||$.length<=I)return $;return`${$.slice(0,Math.max(0,I))}...`}function dQ1($){return[{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"description",value:$.description,metadata:{scope:$.scope,strictness:$.strictness,status:$.status}},{area:"rules",entityType:"rule",entityId:$.id,title:$.scope,field:"scope",value:$.scope,metadata:{strictness:$.strictness,status:$.status}}]}function aW0($){return $.rules.flatMap((I,U)=>{let Y=`${$.id}:${I.description.slice(0,32)}`,J={versionId:$.id,versionNumber:$.versionNumber,versionName:$.versionName,publishedByName:$.publishedByName,publishedAt:$.publishedAt,scope:I.scope,strictness:I.strictness,code:"code"in I?I.code:void 0,index:U};return[{area:"rules",entityType:"rule",entityId:Y,title:`${$.versionName} / ${I.scope}`,field:"history.description",value:I.description,metadata:J},{area:"rules",entityType:"rule",entityId:Y,title:`${$.versionName} / ${I.scope}`,field:"history.scope",value:I.scope,metadata:J}]})}function mQ1($){return[{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"title",value:$.title,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}},{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"purpose",value:$.purpose,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}},{area:"documents",entityType:"document",entityId:$.id,title:$.title,field:"content",value:$.content,metadata:{status:$.status,scenarios:$.scenarios,tags:$.tags}}]}function lQ1($){let I=[];if($.decisionPreferences)for(let[U,Y]of Object.entries($.decisionPreferences))I.push({area:"preferences",entityType:"preference",field:`decisionPreferences.${U}`,value:Y,metadata:{integrationSystem:$.integrationSystem}});return $.integrations.forEach((U,Y)=>{I.push({area:"preferences",entityType:"integration",title:U.outboundName,field:`integrations[${Y}]`,value:U,metadata:{type:U.type,outboundName:U.outboundName,mode:U.mode,corporationId:U.corporationId}})}),I}async function oQ1($,I,U){let Y=U.ruleVersionScope??"current",J=[I.id,`ruleVersionScope=${Y}`,`ruleVersionId=${U.ruleVersionId??""}`,`ruleVersionNumber=${U.ruleVersionNumber??""}`,`latestRuleVersion=${U.latestRuleVersion??!1}`,`documentLimit=${U.documentLimit??100}`].join("|"),Q=tW0.get(J);if(!U.refresh&&Q&&Date.now()<Q.expiresAt)return Q;let[K,q,G]=await Promise.all([rQ1($,{scope:Y,versionId:U.ruleVersionId,versionNumber:U.ruleVersionNumber,latest:U.latestRuleVersion}),W2($,{limit:U.documentLimit??100}),q4($,I.seal.endpoints.approvalStylePreferences)]),H=Date.now(),W={entries:[...K,...q.articles.flatMap(mQ1),...lQ1(G)],fetchedAt:H,expiresAt:H+sW0};return tW0.set(J,W),W}async function rQ1($,I){if(I.scope==="current")return(await M$($)).rules.flatMap(dQ1);if(I.scope==="version"){let Y=await tQ1($,I);return aW0(Y)}return(await Y5($)).flatMap(aW0)}async function tQ1($,I){if(I.versionId)return H2($,I.versionId);let U=await Y5($),Y=I.versionNumber?U.find((J)=>J.versionNumber===I.versionNumber):U[0];if(!Y)throw Error(I.versionNumber?`Rule version not found: ${I.versionNumber}`:"No rule versions found");return Y}async function eW0($,I,U){let Y=U.matchMode??"any",J=U.caseSensitive??!1,Q=U.contextLines??3,K=new Set(U.areas??["rules","documents","preferences"]), Line truncated
`,"utf8"),U}function QV0($){return $.map((I,U)=>{let Y;if(typeof I.code==="number")Y=`#${String(I.code).padStart(4,"0")}`;else if(typeof I.code==="string")Y=I.code.startsWith("#")?I.code:`#${I.code}`;else Y=`#${String(U+1).padStart(4,"0")}`;return{id:I.id,code:Y,name:I.name,description:I.description,scope:I.scope,strictness:I.strictness}})}class S$ extends Error{errors;warnings;constructor($,I=[]){super(`材料包校验失败:${$.length} 个错误`);this.errors=$;this.warnings=I;this.name="MaterialPackValidationError"}}import{createHmac as Z21,randomBytes as X21}from"node:crypto";function L21($,I,U,Y){return Z21("sha256",Y).update(`${$}.${I}.${JSON.stringify(U)}`).digest("hex")}function cy($,I){let U=Math.floor(Date.now()/1000),Y=X21(16).toString("hex");return{Authorization:`Bearer ${I}`,"x-webhook-signature":L21(U,Y,$,I),"x-webhook-timestamp":String(U),"x-webhook-nonce":Y}}var yh=WI(EV0(),1),LZ0=WI(XZ0(),1);var mD={maxEntries:1000,maxTotalSize:524288000,maxCompressionRatio:150};async function wZ0($){return new Promise((I,U)=>{yh.default.fromBuffer(Buffer.from($),{lazyEntries:!0,autoClose:!0,decodeStrings:!1},(Y,J)=>{if(Y||!J)return U(Y??Error("无法打开 ZIP"));let Q=[];J.readEntry(),J.on("entry",(K)=>{let q=DZ0(K);if(!q.endsWith("/")&&!nK1(q))Q.push({fileName:q,uncompressedSize:K.uncompressedSize,compressedSize:K.compressedSize,raw:K});J.readEntry()}),J.on("end",()=>I(Q)),J.on("error",U)})})}function DZ0($){let I=Buffer.isBuffer($.fileName)?$.fileName:Buffer.from(String($.fileName),"binary"),U=I.toString("utf8");if(!U.includes("�"))return U;let Y=LZ0.default.decode(I,"gbk");if(!Y.includes("�"))return Y;return U}function nK1($){let I=$.split("/").pop()??"";return $.split("/").includes("__MACOSX")||I===".DS_Store"||I.startsWith("._")||I.startsWith(".~")||I.startsWith("~$")}function OZ0($){let I=[];if($.length>mD.maxEntries)I.push(`文件数超过 ${mD.maxEntries}`);if($.reduce((J,Q)=>J+Q.uncompressedSize,0)>mD.maxTotalSize)I.push("解压后总大小超过 500MB");for(let J of $){if(J.fileName.startsWith("/")||J.fileName.split("/").includes(".."))I.push(`存在不安全路径: ${J.fileName}`);if(J.compressedSize>0&&J.uncompressedSize/J.compressedSize>mD.maxCompressionRatio)I.push(`压缩比超过 150: ${J.fileName}`)}if(!$.find((J)=>J.fileName==="信息表.xlsx"))I.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");if($.some((J)=>J.fileName.toLowerCase().endsWith(".zip")))I.push("不允许嵌套 ZIP");if(I.length)throw new S$(I)}function hh($,I){return new Promise((U,Y)=>{yh.default.fromBuffer(Buffer.from($),{lazyEntries:!0,autoClose:!0,decodeStrings:!1},(J,Q)=>{if(J||!Q)return Y(J??Error("无法打开 ZIP"));Q.readEntry(),Q.on("entry",(K)=>{if(DZ0(K)!==I.fileName)return Q.readEntry();Q.openReadStream(K,(q,G)=>{if(q||!G)return Y(q??Error(`无法读取 ${I.fileName}`));let H=[];G.on("data",(W)=>H.push(W)),G.on("end",()=>U(Buffer.concat(H))),G.on("error",Y)})}),Q.on("error",Y)})})}var FZ0=WI(Sy(),1);function cK1($){return $.startsWith("[附件]")}function MZ0($){return $.startsWith("[附件]")?$.slice(4):$}function dK1($){return MZ0($).toLowerCase().replace(/\s+/g,"_")||"attachment"}function mK1($){if($==null||$==="")return[];return String($).split(/[\n,;,;]/).map((I)=>I.trim()).filter(Boolean)}function xh($,I){let U=[];for(let[Y,J]of I.entries()){if(!cK1(Y))continue;let Q=$.getCell(J).value,K=mK1(Q);if(!K.length)continue;U.push({key:dK1(Y),label:MZ0(Y),paths:K})}return U}function kh($){let I=new Map;return $.map((U)=>{let Y=(I.get(U.key)??0)+1;return I.set(U.key,Y),Y===1?U:{...U,key:`${U.key}-${Y}`}})}function lD($,I,U,Y){return{key:$,label:I,type:U,value:Y}}function zZ0($,I,U){return lD($,I,"TEXT",U==null?"":String(U))}function AZ0($,I,U){return lD($,I,"AMOUNT",typeof U==="number"?{amount:U,currency:"CNY"}:null)}function PZ0($){if($ instanceof Date)return $.toISOString();if(typeof $==="string"&&$.trim())return $.trim();return null}function lK1($){if($ instanceof Date)return Math.floor($.getTime()/1000);if(typeof $==="string"&&$.trim()){let I=Date.parse($.trim().replace(" ","T"));if(Number.isFinite(I))return Math.floor(I/1000)}return null}function IG($){let I=new Map;return $.getRow(1).eachCell((U,Y)=>I.set(String(U.value??"").trim(),Y)),I}function e3($,I,U){let Y=I.get(U);return Y?$.getCell(Y).value:void 0}function oK1($,I){return[["会议编号","meeting_id","TEXT"],["会议名称","meeting_name","TEXT"],["状态","status","TEXT"],["总金额","total_amount","AMOUNT"],["税前劳务总额","pretax_labor_total","AMOUNT"],["报销事由","reimbursement_reason","TEXT"],["po码","po_code","TEXT"],["快递单号","tracking_number","TEXT"],["申请日期","application_date","DATE"],["更新日期","updated_date","DATE"]].flatMap(([Y,J,Q])=>{let K=e3($,I,Y);if(K==null||K==="")return[];return[Q==="TEXT"?zZ0(J,Y,K):Q==="AMOUNT"?AZ0(J,Y,K):lD(J,Y,Q,PZ0(K))]})}function NZ0($,I,U){return U.flatMap(([Y,J,Q])=>{let K=e3($,I,Y);if(K==null||K==="")return[];return[Q==="TEXT"?zZ0(J,Y,K):Q==="AM Line truncated
`);let F=new FormData,E=await hh(Y.fileBuffer,O),A=D.split("/").pop()??D;F.append("files",new File([new Uint8Array(E)],A));let T=await fetch(`${J}/api/v1/integrations/webhook/${encodeURIComponent(Q)}/attachments`,{method:"POST",headers:cy({},U.secret),body:F});if(!T.ok)throw Error(`附件上传失败 ${T.status}: ${await T.text()}`);let v=await T.json();W.set(D,v.attachments?.map((u)=>u.data)??(v.data===void 0?[]:[v.data])),process.stderr.write(`✓ 附件上传成功: ${D}
`)}process.stderr.write(`\uD83D\uDCE4 推送单据: ${G.document.documentId}
`);let X=uh(G.document,H,W),Z=await fetch(`${J}/api/v1/integrations/webhook/${encodeURIComponent(Q)}/document`,{method:"POST",headers:{"Content-Type":"application/json",...cy({webhookId:Q,...X},U.secret)},body:JSON.stringify(X)});if(!Z.ok)throw Error(`Webhook 单据推送失败 ${Z.status}: ${await Z.text()}`);K.push({documentId:X.documentId,document:X,pushResult:await Z.json()}),process.stderr.write(`✓ 单据推送成功: ${X.documentId}
`)}return{warnings:[],results:K}}function II($){return{fileBuffer:aK1($),fileName:$.split(/[\\\/]/).pop()??"material-pack.zip"}}import{existsSync as Iq1}from"node:fs";async function rD($,I,U={}){let J=D4().stateful?"stateful":"stateless",Q="ok",K,q,G;try{let A=await F$($);G={id:A.user.id,name:A.user.name,isAdmin:A.user.isAdmin},q={id:A.tenant.id,name:A.tenant.name,tenantSlug:A.tenant.tenantSlug,corporationName:A.tenant.hoseCorpConfig?.corporationName}}catch(A){Q="error",K=A instanceof Error?A.message:String(A)}let H=[];if(Q==="ok")try{H=await Z9($,I.seal.endpoints.approvalStylePreferences)}catch(A){Q="error",K=`读取 Webhook 配置失败: ${A instanceof Error?A.message:String(A)}`}let W=H.length===1,V=H.map((A)=>({id:A.id,name:A.name,mode:A.mode,incomingDocumentWebhookUrl:A.incomingDocumentWebhook.url,outgoingResultWebhookUrl:A.outgoingResultWebhook,autoApprovalRate:A.autoApprovalRate,...W?{isDefault:!0}:{}})),X=W?{id:H[0].id,name:H[0].name,mode:H[0].mode}:null,Z;if(U.filePath)if(!Iq1(U.filePath))Z={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[`文件不存在: ${U.filePath}`]};else try{let A=II(U.filePath),T=await $I(A.fileBuffer,A.fileName);Z={valid:!0,filePath:U.filePath,fileName:A.fileName,documentCount:T.documents.length,warnings:T.warnings}}catch(A){Z={valid:!1,filePath:U.filePath,fileName:U.filePath.split(/[\\/]/).pop()??U.filePath,documentCount:0,errors:[A instanceof Error?A.message:String(A)]}}let w=Z?Z.valid:!0,D=Q==="ok"&&V.length>0&&w,O=J==="stateful"?"":` --corp ${I.id}`,F="",E="";if(Q!=="ok")E=`凭证鉴权异常: ${K}`,F=`seal-use auth diagnose${O}`;else if(V.length===0)E="当前企业尚未配置任何 Webhook 集成通道",F=`seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${O}`;else if(Z&&!Z.valid)E=`材料包预检失败: ${Z.errors?.join("; ")}`,F=`seal-use webhook material-pack preview ${Z.filePath}${O}`;else{E=W?"所有通道正常,已自动锁定唯一 Webhook 通道,等待载入":`所有通道正常,检测到 ${V.length} 个 Webhook 通道,等待载入`;let A=Z?.filePath??"<材料包.zip>",T=W?"":` --webhook ${X?X.id:"<webhookIdOrName>"}`;F=`seal-use webhook material-pack push ${A}${T}${O}`}return{ready:D,corp:{id:I.id,name:I.name,sourceType:I.source.type,tenant:q,user:G},stateMode:J,authStatus:Q,authError:K,activeWebhooks:V,defaultWebhook:X,materialPack:Z,statusMessage:E,nextAction:F}}var YG=[{name:"seal_whoami",description:"查询当前 Seal 用户身份及租户信息",parameters:L.object({}),handler:async($)=>F$($)},{name:"seal_session_get",description:"查询当前 Seal Bearer session、用户和过期时间",parameters:L.object({}),handler:async($)=>jd($)},{name:"seal_delegation_list",description:"查询当前 Seal 租户下的授权链接 (Delegation) 列表",parameters:L.object({}),handler:async($)=>$m($)},{name:"seal_delegation_create",description:"创建新的 Seal 授权链接 (Delegation)",parameters:L.object({note:L.string().optional().describe("授权链接的备注或说明信息")}),handler:async($,I)=>XU($,I)},{name:"seal_delegation_revoke",description:"撤销/废除指定的 Seal 授权链接 (Delegation)",parameters:L.object({tokenId:L.string().describe("授权链接 ID (delegation record ID)")}),handler:async($,I)=>Im($,I.tokenId)},{name:"seal_user_create",description:"创建本地 Seal 用户,生成并返回初始随机密码",parameters:L.object({name:L.string().describe("用户姓名"),phone:L.string().describe("手机号码 (例如 13300001111 或 +8613300001111)"),permissions:L.array(L.string()).optional().describe("权限列表,默认为 []"),departmentIds:L.array(L.string()).optional().describe("关联部门 ID 数组")}),handler:async($,I)=>Um($,I)},{name:"seal_user_reset_password",description:"重置指定 Seal 用户的默认/随机密码,并返回生成的新密码",parameters:L.object({userId:L.string().describe("用户 ID (_id)")}),handler:async($,I)=>ME($,I.userId)},{name:"seal_user_get",description:"获取指定 Seal 用户的详细信息",parameters:L.object({userId:L.string().describe("用户 ID (_id)")}),handler:async($,I)=>RV($,I.userId)},{name:"seal_user_search",description:"按姓名、手机号或邮箱搜索 Seal 成员用户列表",parameters:L.object({keyword:L.string().optional().describe("搜索关键词(姓名、手机号、邮箱等),不传或传空字符串可列出租户成员")}),handler:async($,I)=>vV($,I.keyword??"")},{name:"seal_user_delete",description:"删除指定 Seal 本地用户",parameters:L.object({userId:L.string().describe("用户 ID (_id)")}),handler:async($,I)=>Ym($,I.userId)},{name:"seal_user_activate",description:"启用/激活已离职的 Seal 用户账号",parameters:L.object({userId:L.string().describe("用户 ID (_id)")}),handler:async($,I)=>zE($,I.userId)},{name:"seal_user_delegation_create",description:"为指定 Seal 用户(按用户ID、手机号或姓名)重置密码登录 Line truncated
`);return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,document:MJ({id:I?.id,sn:I?.sn??I?.sourceDocumentSN??$.sourceDocumentSN,title:I?.title??I?.name,template:eD(I,["template.name","templateName","form.name","formName","formTitle"]),amount:aD(U,["金额","报销金额","付款金额","合计","价税合计"])??eD(I,["amount","totalAmount","expenseAmount"]),expenseType:aD(U,["费用类型","费用类别","报销类型"]),costCompany:aD(U,["费用承担公司","承担公司","成本中心","费用归属"]),payee:aD(U,["收款方","收款账户","收款信息","开户名","银行账号"]),keyFields:U.slice(0,30)}),invoices:Dq1($),attachments:HJ($,{summary:!0}).attachments,aiResult:IO($),manualResult:YI($)?.value,hints:MJ({amountMentions:jZ0(Y,["金额","合计","税率"],8),partyMentions:jZ0(Y,["买方","卖方","甲方","乙方","收款"],8)})}}function Zq1($){let I=[["result.citedRules",b5($,"result.citedRules")],["result.matchedRules",b5($,"result.matchedRules")],["result.ruleResults",b5($,"result.ruleResults")],["result.rules",b5($,"result.rules")],["pipelineData.citedRules",b5($,"pipelineData.citedRules")],["pipelineData.matchedRules",b5($,"pipelineData.matchedRules")]],U=[],Y=new Set;for(let[J,Q]of I)(Array.isArray(Q)?Q:Q&&typeof Q==="object"?Object.values(Q):[]).forEach((q,G)=>{let H=JG(q);if(!H)return;let W=$4(H.runtimeRuleId)??$4(H.runtimeId)??$4(H.id)??$4(H.ruleId),V=$4(H.ruleCode)??$4(H.code)??(W?Fq1(W):void 0),X=MJ({runtimeRuleId:W,ruleCode:V,versionNumber:Lq1(H.versionNumber)??$.ruleSetVersionNumber,scope:$4(H.scope),strictness:$4(H.strictness),appliedAnalysis:H.appliedAnalysis??H.analysis??H.reasoning,checkResult:H.checkResult??H.result??H.decision,findings:H.findings??H.riskPoints??H.evidence,sourcePath:`${J}.${G}`}),Z=JSON.stringify(X);if(!Y.has(Z))Y.add(Z),U.push(X)});return{recordId:$.id,sourceDocumentSN:$.sourceDocumentSN,sourceDocumentId:$.sourceDocumentId,ruleSetVersionNumber:$.ruleSetVersionNumber,count:U.length,rules:U}}function eD($,I){if(!$)return;for(let U of I){let Y=b5($,U);if(Y!==void 0)return Y}return}function CZ0($,I){if(!$)return 0;for(let U of I){let Y=b5($,U);if(Array.isArray(Y))return Y.length;if(Y&&typeof Y==="object")return Object.keys(Y).length;if(typeof Y==="number")return Y}return 0}function b5($,I){return I.split(".").reduce((U,Y)=>{if(U===void 0||U===null)return;if(Array.isArray(U)){let J=Number(Y);return Number.isInteger(J)?U[J]:void 0}if(typeof U==="object")return U[Y];return},$)}function Xq1($,I,U){let Y=I.split("."),J=$;for(let Q of Y.slice(0,-1)){let K=J[Q];if(!K||typeof K!=="object"||Array.isArray(K))J[Q]={};J=J[Q]}J[Y[Y.length-1]??I]=U}function MJ($){return Object.fromEntries(Object.entries($).filter(([,I])=>I!==void 0))}function JG($){return $&&typeof $==="object"&&!Array.isArray($)?$:void 0}function Lq1($){return typeof $==="number"&&Number.isFinite($)?$:void 0}function wq1($){let I=[];return ih($,"document",I),I}function ih($,I,U){if(Array.isArray($)){$.forEach((K,q)=>ih(K,`${I}.${q}`,U));return}let Y=JG($);if(!Y)return;let J=$4(Y.label)??$4(Y.name)??$4(Y.title)??$4(Y.fieldName),Q=Y.value??Y.displayValue??Y.text??Y.content;if(J&&Q!==void 0&&typeof Q!=="object")U.push(MJ({path:I,label:J,value:Q,type:$4(Y.type)??$4(Y.fieldType)}));for(let[K,q]of Object.entries(Y)){if(K==="attachments")continue;ih(q,`${I}.${K}`,U)}}function aD($,I){return $.find((Y)=>{let J=$4(Y.label)??"";return I.some((Q)=>J.includes(Q))})?.value}function Dq1($){let I=[];return $O($.result,"result",I),$O($.document,"document",I),I.slice(0,20)}function $O($,I,U){if(Array.isArray($)){$.forEach((J,Q)=>$O(J,`${I}.${Q}`,U));return}let Y=JG($);if(!Y)return;if(/invoice|发票/i.test(I))U.push(MJ({path:I,fileName:$4(Y.fileName)??$4(Y.filename)??$4(Y.name),buyer:Y.buyer??Y.buyerName??Y.purchaserName,seller:Y.seller??Y.sellerName,amount:Y.amount??Y.totalAmount??Y.total,taxRate:Y.taxRate,category:Y.category??Y.type}));for(let[J,Q]of Object.entries(Y))$O(Q,`${I}.${J}`,U)}function jZ0($,I,U){return $.split(/\r?\n/).filter((Y)=>I.some((J)=>Y.includes(J))).slice(0,U)}function sD($){return $.map((I)=>{let U=UI(I);return{recordId:U.id,tenantId:U.tenantId,agentId:U.agentId,sourceDocumentSN:U.sourceDocumentSN,sourceDocumentId:U.sourceDocumentId,simulationBatchId:U.simulationBatchId,langfuseTraceId:U.langfuseTraceId,langfuseSessionFallback:U.langfuseSessionFallback,ruleSetVersionNumber:U.ruleSetVersionNumber,ruleSetPublishedAt:U.ruleSetPublishedAt,ruleSetPublishedByName:U.ruleSetPublishedByName,resolution:U.langfuseTraceId?"trace":U.langfuseSessionFallback?"session-fallback":"unresolved"}})}function fh($){return{id:$.id,tenantId:$.tenantId,versionNumber:$.versionNumber,versionName:$.versionName,publishedBy:$.publishedBy,publishedByName:$.publishedByName,rulesCount:$.rules.length,publishedAt:$.publishedAt,createdAt:$.createdAt}}async function Oq1($,I){if(I.recordId&&!I.versionId&&!I.versionNumber&&!I.latest){let U=await f4($,I.recordId);if(!U.ruleSetVersionNumber)throw Er Line truncated
`)}
`}function _u(n){return n.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function B(n,i={}){zF(n,i);let r=`${JSON.stringify(n,null,2)}
`;if(i.outputFile){qF(i.outputFile,r),console.log(JSON.stringify({outputFile:i.outputFile,bytes:Buffer.byteLength(r,"utf-8")},null,2));return}console.log(r.trimEnd())}function zF(n,i={}){if(i.allowFull||i.outputFile)return;let r=Buffer.byteLength(JSON.stringify(n),"utf-8");if(r>MF)throw Error(`Output is large (${r} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function eL(n,i){if(i)return;let r=n&&typeof n==="object"?n:{},o=typeof r.count==="number"?r.count:void 0,t=Array.isArray(r.rules)?r.rules.length:void 0,u=Buffer.byteLength(JSON.stringify(n),"utf-8"),e=o??t??0;if(e>_F||u>ZF)throw Error(`Rule list is large (${e} rules, ${u} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`)}function J(n){return{allowFull:_(n.full)===!0,outputFile:D(n.outputFile)??D(n["output-file"])}}function lL(){console.log(`seal-use CLI
`}function qG($){return $.replace(/([?&](?:accessToken|token|returnToken)=)[^&\s]+/gi,"$1<redacted>").replace(/(Bearer\s+)[A-Za-z0-9._~+/=-]+/gi,"$1<redacted>")}function E0($,I={}){Sq1($,I);let U=`${JSON.stringify($,null,2)}
`;if(I.outputFile){vq1(I.outputFile,U),console.log(JSON.stringify({outputFile:I.outputFile,bytes:Buffer.byteLength(U,"utf-8")},null,2));return}console.log(U.trimEnd())}function Sq1($,I={}){if(I.allowFull||I.outputFile)return;let U=Buffer.byteLength(JSON.stringify($),"utf-8");if(U>_q1)throw Error(`Output is large (${U} bytes). Use --summary, --fields, --count, or --output-file; pass --full only when you really need the full response.`)}function sZ0($,I){if(I)return;let U=$&&typeof $==="object"?$:{},Y=typeof U.count==="number"?U.count:void 0,J=Array.isArray(U.rules)?U.rules.length:void 0,Q=Buffer.byteLength(JSON.stringify($),"utf-8"),K=Y??J??0;if(K>Cq1||Q>jq1)throw Error(`Rule list is large (${K} rules, ${Q} bytes). Use "seal-use rules list --summary" or "seal-use rules count"; pass --full only when you really need full descriptions.`)}function O0($){return{allowFull:_0($.full)===!0,outputFile:h($.outputFile)??h($["output-file"])}}function eZ0(){console.log(`seal-use CLI
Usage:
seal-use version
@@ -93,6 +334,8 @@ Usage:
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use config test-dir [<path>|--clear]
seal-use config lint [status|enable|disable] [--linter <name|path>] [--min-score <score>]
seal-use update [--check] [--force] [--version <v>]
seal-use update check
seal-use update changelog [--limit <n>]
@@ -122,11 +365,15 @@ Usage:
seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook ready [<材料包.zip>] [--corp <corpId>]
seal-use webhook status [<材料包.zip>] [--corp <corpId>]
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--corp <corpId>]
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
@@ -153,12 +400,14 @@ Usage:
seal-use approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp <corpId>]
seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] [--corp <corpId>]
seal-use approval-runs count [--status APPROVED] [--corp <corpId>]
seal-use approval-runs export [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--limit <n>] [--downloads] [--out <file>] [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
seal-use approval-runs cited-rules <recordId> [--corp <corpId>]
seal-use approval-runs document-summary <recordId> [--corp <corpId>]
seal-use approval-runs attachments <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] [--corp <corpId>]
seal-use approval-runs result <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs url [--corp <corpId>]
seal-use approval-runs url <recordId> [--corp <corpId>]
@@ -176,12 +425,12 @@ Usage:
seal-use simulation templates [--corp <corpId>]
seal-use simulation integrations [--corp <corpId>]
seal-use simulation package-upload <材料包.zip> [--corp <corpId>]
`)}function Ln(n){let i=Yi(),r=bi();return Rr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n},Kt())}function r$(n=bi()){return{mode:n.stateful?"stateful":"stateless",stateful:n.stateful,...n.stateful&&n.defaultCorpId?{defaultCorpId:n.defaultCorpId}:{},configFile:Yu()}}async function X(n,i,r,o,t={}){B(await xr(n,i,r,o),t)}async function xr(n,i,r,o){let t=Tu.find((l)=>l.name===n);if(!t)throw Error(`Unknown Seal tool: ${n}`);let u=Object.fromEntries(Object.entries(o).filter(([,l])=>l!==void 0)),e=t.handler;return e(i,u,{corp:r})}async function vL(n,i,r,o,t){if(n==="summary"){let u=await xr("seal_approval_runs_summary",r,o,{date:D(t.options.date),timezone:D(t.options.timezone),limit:ln(t.options.limit),startDate:D(t.options.startDate),endDate:D(t.options.endDate),status:D(t.options.status),taskMode:D(t.options.taskMode),manualApprovalStatus:D(t.options.manualApprovalStatus),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),humanResult:D(t.options.humanResult),query:D(t.options.query)});if(u?.matched===0&&u?.total>0)console.error(`提示:在 ${u.date} 未匹配到记录(该企业共有 ${u.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-use approval-runs list --limit 10 查看最近记录。`);B(u,J(t.options));return}if(n==="stats"){await X("seal_approval_runs_stats",r,o,{since:D(t.options.since),dedupeBy:D(t.options.dedupeBy)??D(t.options["dedupe-by"]),status:D(t.options.status),sourceSystem:D(t.options.sourceSystem)??D(t.options["source-system"]),taskMode:D(t.options.taskMode)??D(t.options["task-mode"])},J(t.options));return}if(n==="count"){await X("seal_approval_runs_count",r,o,{status:D(t.options.status),sourceSystem:D(t.options.sourceSystem)??D(t.options["source-system"]),taskMode:D(t.options.taskMode)??D(t.options["task-mode"]),search:D(t.options.search)??D(t.options.query)},J(t.options));return}if(n==="search"||n==="list"){await X("seal_approval_runs_search",r,o,{limit:ln(t.options.limit),offset:ln(t.options.offset),startDate:D(t.options.startDate),endDate:D(t.options.endDate),status:D(t.options.status),taskMode:D(t.options.taskMode),manualApprovalStatus:D(t.options.manualApprovalStatus),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),humanResult:D(t.options.humanResult),query:D(t.options.query),includeBridge:_(t.options.includeBridge)},J(t.options));return}if(n==="bridge"){await X("seal_approval_run_langfuse_bridge_get",r,o,{recordId:D(t.options.recordId),sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId),simulationBatchId:D(t.options.simulationBatchId),limit:ln(t.options.limit)},J(t.options));return}if(n==="pick"){let u=i??D(t.options.query)??D(t.options.sn);if(!u)throw Error("Usage: seal-use approval-runs pick --sn <documentSN>");await X("seal_approval_run_pick",r,o,{query:u,sn:D(t.options.sn),batchId:D(t.options.batch)??D(t.options.batchId),latest:_(t.options.latest),fields:D(t.options.fields),limit:ln(t.options.limit),includeBridge:_(t.options.includeBridge)},J(t.options));return}if(n==="get"){let u=t.command[2];if(!u)throw Error("Missing approval run recordId");await X("seal_approval_run_get",r,o,{recordId:u,fields:D(t.options.fields),summary:_(t.options.summary)},J(t.options));return}if(n==="cited-rules"){let u=t.command[2];if(!u)throw Error("Usage: seal-use approval-runs cited-rules <recordId>");await X("seal_approval_run_cited_rules_get",r,o,{recordId:u},J(t.options));return}if(n==="document-summary"){let u=t.command[2];if(!u)throw Error("Usage: seal-use approval-runs document-summary <recordId>");await X("seal_approval_run_document_summary_get",r,o,{recordId:u},J(t.options));return}if(n==="attachments"){let u=t.command[2];if(!u)throw Error("Usage: seal-use approval-runs attachments <recordId>");await X("seal_approval_run_attachments_get",r,o,{recordId:u,summary:_(t.options.summary)},J(t.options));return}if(n==="result"){let u=t.command[2];if(!u)throw Error("Usage: seal-use approval-runs result <recordId> [--summary]");await X("seal_approval_run_result_get",r,o,{recordId:u,summary:_(t.options.summary)},J(t.options));return}if(n==="url"){await X("seal_approval_run_url_get",r,o,{recordId:i,sourceDocumentSN:D(t.options.sourceDocumentSN),sourceDocumentId:D(t.options.sourceDocumentId)},J(t.options));return}throw Error(`Unknown approval-runs command: ${n??""}. Run 'seal-use help' for available commands.`)}async function gL(n,i,r){if(n==="diagnose"){B(await CF(i));return}if(n==="hose-link"){let o=ln(r.options.expire)??7200;B(await ik(i,o));return}throw Error(`Unknown auth command: ${n??""}. Run 'seal-use help' for available commands.`)}async function CF(n){if(n.source.type!=="hose"){let c=await On(n),S=await Qi(c);return{corp:{id:n.id,name:n.name,sourceType:n.source.type},ok:!0,stages:[{name:"seal.whoami",ok:!0,user:S.user,tenant:S.tenant}]}}Hv(n.id);let i=n.source,r=i.appKey??i.key,o=i.appSecurity??i.password,t=(n Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${Wn.length} candidate administrators:
- ${jn}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!S)if(!g&&u)S=u;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let d=Un(n,"id")??w,k=f??w,P=Un(n,"sealUrl")??`https://${w.toLowerCase()}.sealai.cc`,Q={id:d,name:k,seal:{url:P,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:b,appKey:r,appSecurity:o,corpId:w,staffId:S},auth:{refreshTtl:300}};if(g)Hv(d),await ar(Q);let W=l4();SL(W,{recursive:!0,mode:448});let N=OL(W,`${Q4(d)}.json`);if(DL(N)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${N}. Pass "overwrite": true to replace it.`);AL(N,`${JSON.stringify(Q,null,2)}
`,{mode:384}),B({id:d,name:k,corpId:w,domain:b,staffId:S,verified:g,path:N})}async function sF(n){let i=St(n,"token"),r=(Un(n,"sealUrl")??Un(n,"url")??"").replace(/\/+$/,"");if(!r)throw Error("Missing required JSON field: sealUrl");let o=nL(n,"expiresIn")??2592000,t=n.force===!0||n.verify===!1?!1:!0,u=t?await iK(r,i):void 0;kL(n,{token:i,sealUrl:r,expiresIn:o,verify:t,remote:u})}async function nK(n,i,r){let o=await Yv(n),t=Xu(o.sealUrl,o.token),u=await Qi(t),e={user:u.user,tenant:u.tenant};pv(o.corpId,e.tenant),kL({id:o.corpId,corpId:o.corpId,name:i,provider:"hosecloud",overwrite:r},{token:o.token,sealUrl:o.sealUrl,expiresIn:o.expiresIn,verify:!0,remote:e})}function kL(n,i){let{token:r,sealUrl:o,expiresIn:t,verify:u,remote:e}=i,l=e?.user,$=e?.tenant,I=Un(n,"tenantSlug")??At($?.tenantSlug),g=Un(n,"tenantId")??At($?.id),b=Un(n,"tenantName")??At($?.name),w=Un(n,"id")??I??g;if(!w)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let f=Un(n,"staffId")??At(l?.providerUserId)??At(l?.id)??"seal",c=Un(n,"provider")??At(l?.provider)??At($?.providerConfig?.provider),S=Un(n,"corpId")??I??g??w,d={id:w,name:Un(n,"name")??b??w,seal:{url:o,tenantSlug:I,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:r,sealUrl:o,expiresIn:t,staffId:f,corpId:S,tenantId:g,tenantSlug:I,tenantName:b,providerUserId:At(l?.providerUserId),provider:c},auth:{refreshTtl:300}},k=l4();SL(k,{recursive:!0,mode:448});let P=OL(k,`${Q4(w)}.json`);if(DL(P)&&n.overwrite!==!0)throw Error(`Enterprise config already exists: ${P}. Pass "overwrite": true to replace it.`);AL(P,`${JSON.stringify(d,null,2)}
`,{mode:384}),B({id:w,name:d.name,tenantId:g,tenantSlug:I,verified:u,path:P})}async function iK(n,i){let r=await tK(`${n}/api/v1/auth/me`,{authorization:`Bearer ${i}`}),o=u$(r.data);return{user:u$(o.user??r.user),tenant:u$(o.tenant??r.tenant)}}async function tK(n,i={}){let r=await fetch(n,{headers:i}),o=await r.text();if(!r.ok)throw Error(`${r.status} ${o}`);let t=JSON.parse(o);return u$(t)}function u$(n){return n&&typeof n==="object"&&!Array.isArray(n)?n:{}}function At(n){return typeof n==="string"&&n?n:void 0}async function NL(n,i){let r=await Yv(n),o=Xu(r.sealUrl,r.token),t=await Qi(o);pv(r.corpId,t.tenant);let u=await hr(o,{note:i});B({tenant:{id:t.tenant.id,name:t.tenant.name,tenantSlug:t.tenant.tenantSlug,corpId:r.corpId},user:{id:t.user.id,name:t.user.name,providerUserId:t.user.providerUserId,isAdmin:t.user.isAdmin},delegation:u,expiresIn:r.expiresIn})}async function LL(n,i,r,o,t){if(n==="list"){await X("seal_delegation_list",r,o,{},J(t.options));return}if(n==="create"){let u=D(t.options.note)??(i?[i,...t.command.slice(2)].join(" "):void 0);await X("seal_delegation_create",r,o,{note:u},J(t.options));return}if(n==="revoke"){let u=i??D(t.options.tokenId);if(!u)throw Error("Usage: seal-use delegation revoke <tokenId>");await X("seal_delegation_revoke",r,o,{tokenId:u},J(t.options));return}throw Error(`Unknown delegation command: ${n??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as rK}from"node:fs";async function yL(n,i,r,o,t,u){if(!n||n==="help")throw Error(`Usage: seal-use deploy <system> <action> [options]
`)}function O4($){let I=b8(),U=D4();return WJ(I,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$},o3())}function JI($=D4()){return{mode:$.stateful?"stateful":"stateless",stateful:$.stateful,...$.stateful&&$.defaultCorpId?{defaultCorpId:$.defaultCorpId}:{},...$.testEnterprisesDir?{testEnterprisesDir:$.testEnterprisesDir}:{},lint:$.lint,configFile:r3()}}async function F0($,I,U,Y,J={}){E0(await QI($,I,U,Y),J)}async function QI($,I,U,Y){let J=YG.find((q)=>q.name===$);if(!J)throw Error(`Unknown Seal tool: ${$}`);let Q=Object.fromEntries(Object.entries(Y).filter(([,q])=>q!==void 0)),K=J.handler;return K(I,Q,{corp:U})}async function $X0($,I,U,Y,J){if($==="summary"){let Q=await QI("seal_approval_runs_summary",U,Y,{date:h(J.options.date),timezone:h(J.options.timezone),limit:U1(J.options.limit),startDate:h(J.options.startDate),endDate:h(J.options.endDate),status:h(J.options.status),taskMode:h(J.options.taskMode),manualApprovalStatus:h(J.options.manualApprovalStatus),sourceDocumentSN:h(J.options.sourceDocumentSN),sourceDocumentId:h(J.options.sourceDocumentId),humanResult:h(J.options.humanResult),query:h(J.options.query)});if(Q?.matched===0&&Q?.total>0)console.error(`提示:在 ${Q.date} 未匹配到记录(该企业共有 ${Q.total} 条历史记录)。可使用 --date YYYY-MM-DD 指定日期,或运行 seal-use approval-runs list --limit 10 查看最近记录。`);E0(Q,O0(J.options));return}if($==="stats"){await F0("seal_approval_runs_stats",U,Y,{since:h(J.options.since),dedupeBy:h(J.options.dedupeBy)??h(J.options["dedupe-by"]),status:h(J.options.status),sourceSystem:h(J.options.sourceSystem)??h(J.options["source-system"]),taskMode:h(J.options.taskMode)??h(J.options["task-mode"])},O0(J.options));return}if($==="count"){await F0("seal_approval_runs_count",U,Y,{status:h(J.options.status),sourceSystem:h(J.options.sourceSystem)??h(J.options["source-system"]),taskMode:h(J.options.taskMode)??h(J.options["task-mode"]),search:h(J.options.search)??h(J.options.query)},O0(J.options));return}if($==="search"||$==="list"){await F0("seal_approval_runs_search",U,Y,{limit:U1(J.options.limit),offset:U1(J.options.offset),startDate:h(J.options.startDate),endDate:h(J.options.endDate),status:h(J.options.status),taskMode:h(J.options.taskMode),manualApprovalStatus:h(J.options.manualApprovalStatus),sourceDocumentSN:h(J.options.sourceDocumentSN),sourceDocumentId:h(J.options.sourceDocumentId),humanResult:h(J.options.humanResult),query:h(J.options.query),includeBridge:_0(J.options.includeBridge)},O0(J.options));return}if($==="bridge"){await F0("seal_approval_run_langfuse_bridge_get",U,Y,{recordId:h(J.options.recordId),sourceDocumentSN:h(J.options.sourceDocumentSN),sourceDocumentId:h(J.options.sourceDocumentId),simulationBatchId:h(J.options.simulationBatchId),limit:U1(J.options.limit)},O0(J.options));return}if($==="pick"){let Q=I??h(J.options.query)??h(J.options.sn);if(!Q)throw Error("Usage: seal-use approval-runs pick --sn <documentSN>");await F0("seal_approval_run_pick",U,Y,{query:Q,sn:h(J.options.sn),batchId:h(J.options.batch)??h(J.options.batchId),latest:_0(J.options.latest),fields:h(J.options.fields),limit:U1(J.options.limit),includeBridge:_0(J.options.includeBridge)},O0(J.options));return}if($==="get"){let Q=J.command[2];if(!Q)throw Error("Missing approval run recordId");await F0("seal_approval_run_get",U,Y,{recordId:Q,fields:h(J.options.fields),summary:_0(J.options.summary)},O0(J.options));return}if($==="cited-rules"){let Q=J.command[2];if(!Q)throw Error("Usage: seal-use approval-runs cited-rules <recordId>");await F0("seal_approval_run_cited_rules_get",U,Y,{recordId:Q},O0(J.options));return}if($==="document-summary"){let Q=J.command[2];if(!Q)throw Error("Usage: seal-use approval-runs document-summary <recordId>");await F0("seal_approval_run_document_summary_get",U,Y,{recordId:Q},O0(J.options));return}if($==="attachments"){if(J.command[2]==="download"){let H=J.command[3];if(!H)throw Error("Usage: seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>]");let W=await f4(U,H),V=await PD({record:W,all:_0(J.options.all),name:h(J.options.name),outDir:h(J.options["out-dir"])??h(J.options.outDir)??h(J.options.dir)});if(E0(V,O0(J.options)),V.total>0&&V.downloaded===0)throw Error(`所有 ${V.total} 个附件下载均失败。`);return}let K=J.command[2];if(!K)throw Error("Usage: seal-use approval-runs attachments <recordId> | seal-use approval-runs attachments download <recordId>");if(_0(J.options.download)){let H=await f4(U,K),W=await PD({record:H,all:_0(J.options.all)??!0,name:h(J.options.name),outDir:h(J.options["out-dir"])??h(J.options.outDir)??h(J.options.dir)});if(E0(W,O0(J.options)),W.total>0&&W.downloaded===0)throw Error(`所有 ${W.total} 个附件下载均失败。`);return}let q=await f4(U,K),G=HJ(q,{summary:_0(J.options.summary)});E0(G,O0(J.options));return}if($==="download"){let Q=J.command[2];if(!Q)throw Error("Usage: seal-use approval-runs download <recordId> [--all] [--name <n Line truncated
- `);throw Error(`Missing required parameter: staffId. Found ${C.length} candidate administrators:
- ${n}
Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an account (or pass force:true to bypass).`)}}}if(!D)if(!W&&Q)D=Q;else throw Error("Missing required parameter: staffId (or proxyStaffBizId). Run 'seal-use corps hose-staffs' to discover available administrators.");let O=i1($,"id")??X,F=Z??X,E=i1($,"sealUrl")??`https://${X.toLowerCase()}.sealai.cc`,A={id:O,name:F,seal:{url:E,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"hose",domain:V,appKey:U,appSecurity:Y,corpId:X,staffId:D},auth:{refreshTtl:300}};if(W)DV(O),await zJ(A);let T=ky();WX0(T,{recursive:!0,mode:448});let v=ZX0(T,`${oh(O)}.json`);if(HX0(v)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${v}. Pass "overwrite": true to replace it.`);VX0(v,`${JSON.stringify(A,null,2)}
`,{mode:384}),E0({id:O,name:F,corpId:X,domain:V,staffId:D,verified:W,path:v})}async function fq1($){let I=Z7($,"token"),U=(i1($,"sealUrl")??i1($,"url")??"").replace(/\/+$/,"");if(!U)throw Error("Missing required JSON field: sealUrl");let Y=mZ0($,"expiresIn")??2592000,J=$.force===!0||$.verify===!1?!1:!0,Q=J?await iq1(U,I):void 0;LX0($,{token:I,sealUrl:U,expiresIn:Y,verify:J,remote:Q})}async function bq1($,I,U){let Y=await OV($),J=Q2(Y.sealUrl,Y.token),Q=await F$(J),K={user:Q.user,tenant:Q.tenant};NV(Y.corpId,K.tenant),LX0({id:Y.corpId,corpId:Y.corpId,name:I,provider:"hosecloud",overwrite:U},{token:Y.token,sealUrl:Y.sealUrl,expiresIn:Y.expiresIn,verify:!0,remote:K})}function LX0($,I){let{token:U,sealUrl:Y,expiresIn:J,verify:Q,remote:K}=I,q=K?.user,G=K?.tenant,H=i1($,"tenantSlug")??X7(G?.tenantSlug),W=i1($,"tenantId")??X7(G?.id),V=i1($,"tenantName")??X7(G?.name),X=i1($,"id")??H??W;if(!X)throw Error("Missing required JSON field: id. Seal whoami did not return tenantSlug or tenantId.");let Z=i1($,"staffId")??X7(q?.providerUserId)??X7(q?.id)??"seal",w=i1($,"provider")??X7(q?.provider)??X7(G?.providerConfig?.provider),D=i1($,"corpId")??H??W??X,O={id:X,name:i1($,"name")??V??X,seal:{url:Y,tenantSlug:H,endpoints:{approvalStylePreferences:"api/v1/agent/ai-approval/config"}},source:{type:"seal",token:U,sealUrl:Y,expiresIn:J,staffId:Z,corpId:D,tenantId:W,tenantSlug:H,tenantName:V,providerUserId:X7(q?.providerUserId),provider:w},auth:{refreshTtl:300}},F=ky();WX0(F,{recursive:!0,mode:448});let E=ZX0(F,`${oh(X)}.json`);if(HX0(E)&&$.overwrite!==!0)throw Error(`Enterprise config already exists: ${E}. Pass "overwrite": true to replace it.`);VX0(E,`${JSON.stringify(O,null,2)}
`,{mode:384}),E0({id:X,name:O.name,tenantId:W,tenantSlug:H,verified:Q,path:E})}async function iq1($,I){let U=await pq1(`${$}/api/v1/auth/me`,{authorization:`Bearer ${I}`}),Y=YO(U.data);return{user:YO(Y.user??U.user),tenant:YO(Y.tenant??U.tenant)}}async function pq1($,I={}){let U=await fetch($,{headers:I}),Y=await U.text();if(!U.ok)throw Error(`${U.status} ${Y}`);let J=JSON.parse(Y);return YO(J)}function YO($){return $&&typeof $==="object"&&!Array.isArray($)?$:{}}function X7($){return typeof $==="string"&&$?$:void 0}async function wX0($,I){let U=await OV($),Y=Q2(U.sealUrl,U.token),J=await F$(Y);NV(U.corpId,J.tenant);let Q=await XU(Y,{note:I});E0({tenant:{id:J.tenant.id,name:J.tenant.name,tenantSlug:J.tenant.tenantSlug,corpId:U.corpId},user:{id:J.user.id,name:J.user.name,providerUserId:J.user.providerUserId,isAdmin:J.user.isAdmin},delegation:Q,expiresIn:U.expiresIn})}async function DX0($,I,U,Y,J){if($==="list"){await F0("seal_delegation_list",U,Y,{},O0(J.options));return}if($==="create"){let Q=h(J.options.note)??(I?[I,...J.command.slice(2)].join(" "):void 0);await F0("seal_delegation_create",U,Y,{note:Q},O0(J.options));return}if($==="revoke"){let Q=I??h(J.options.tokenId);if(!Q)throw Error("Usage: seal-use delegation revoke <tokenId>");await F0("seal_delegation_revoke",U,Y,{tokenId:Q},O0(J.options));return}throw Error(`Unknown delegation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as nq1}from"node:fs";async function OX0($,I,U,Y,J,Q){if(!$||$==="help")throw Error(`Usage: seal-use deploy <system> <action> [options]
`+`支持的审批系统与发布目标:
`+` • hosecloud (合思费控): seal-use deploy hosecloud <requirements|list|get|status|configure|sync> --corp <corpId>
@@ -189,18 +438,25 @@ Please specify 'staffId', 'staffName', or 'staffPhone' to explicitly select an a
`+` • feishu (飞书审批): 建议使用 Webhook 模式对接
`+` • weaver (泛微 OA): 建议使用 Webhook 模式对接
`+` • helios (汇联易): 建议使用 Webhook 模式对接
`+" • maycur (每刻报销): 建议使用 Webhook 模式对接");if(n==="webhook"||n==="webhooks")throw Error("Webhook 审批流发布请直接使用专有命令:seal-use webhook <list|get|add|update|delete> --corp <corpId>");if(n==="feishu"||n==="lark")throw Error("飞书审批发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '飞书审批' --result-url <url> --corp <corpId>");if(n==="weaver")throw Error("泛微 OA 发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '泛微OA' --result-url <url> --corp <corpId>");if(n==="maycur"||n==="helios"){let I=n==="maycur"?"每刻报销":"汇联易";throw Error(`${I}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${I}' --result-url <url> --corp <corpId>`)}let e=n==="hosecloud",l=n==="hosecloud"?i:n,$=n==="hosecloud"?r:i;if(!e)throw Error(`未知的发布目标系统: ${n}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(l==="requirements"){await X("seal_deploy_hosecloud_requirements",o,t,{},J(u.options));return}if(l==="list"){await X("seal_deploy_hosecloud_list",o,t,{},J(u.options));return}if(l==="get"){let I=$??D(u.options.signKey)??D(u.options["sign-key"]);if(!I)throw Error("Usage: seal-use deploy hosecloud get <sign-key>");await X("seal_deploy_hosecloud_get",o,t,{signKey:I},J(u.options));return}if(l==="status"){await X("seal_deploy_hosecloud_status",o,t,{},J(u.options));return}if(l==="configure"){let I=D(u.options.input),g=I?JSON.parse(rK(I,"utf8")):ri(u.json);if(!g||Object.keys(g).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await X("seal_deploy_hosecloud_configure",o,t,g,J(u.options));return}if(l==="sync"){let I=$??D(u.options.signKey)??D(u.options["sign-key"]);if(!I)throw Error("Usage: seal-use deploy hosecloud sync <sign-key>");await X("seal_deploy_hosecloud_sync",o,t,{signKey:I},J(u.options));return}throw Error(`Unknown deploy hosecloud action: ${l??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as vK}from"node:http";import{URL as uK}from"node:url";var GL={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.3",description:`Planned HTTP contract for the seal-use wrapped backend API.
`+" • maycur (每刻报销): 建议使用 Webhook 模式对接");if($==="webhook"||$==="webhooks")throw Error("Webhook 审批流发布请直接使用专有命令:seal-use webhook <list|get|add|update|delete> --corp <corpId>");if($==="feishu"||$==="lark")throw Error("飞书审批发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '飞书审批' --result-url <url> --corp <corpId>");if($==="weaver")throw Error("泛微 OA 发布:建议使用 Webhook 通用发布模式对接。命令:seal-use webhook add --name '泛微OA' --result-url <url> --corp <corpId>");if($==="maycur"||$==="helios"){let H=$==="maycur"?"每刻报销":"汇联易";throw Error(`${H}发布:目前可通过 Webhook 模式接入。命令:seal-use webhook add --name '${H}' --result-url <url> --corp <corpId>`)}let K=$==="hosecloud",q=$==="hosecloud"?I:$,G=$==="hosecloud"?U:I;if(!K)throw Error(`未知的发布目标系统: ${$}。当前支持: hosecloud (合思费控) 与 webhook (通用回调)。`);if(q==="requirements"){await F0("seal_deploy_hosecloud_requirements",Y,J,{},O0(Q.options));return}if(q==="list"){await F0("seal_deploy_hosecloud_list",Y,J,{},O0(Q.options));return}if(q==="get"){let H=G??h(Q.options.signKey)??h(Q.options["sign-key"]);if(!H){let V=((await q4(Y)).integrations??[]).filter((X)=>X.type==="hosecloud");if(V.length===0)throw Error(`当前企业 (${J.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${J.id}`);console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${J.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let X of V){let Z=X.outboundName??"SealAI 审批",w=X.signKey,D=X.apiOrigin??"production";console.error(` • "${Z}" (signKey: ${w}, 环境: ${D})`),console.error(` \uD83D\uDC49 查看命令: seal-use deploy hosecloud get ${w} --corp ${J.id}
`)}throw Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。")}await F0("seal_deploy_hosecloud_get",Y,J,{signKey:H},O0(Q.options));return}if(q==="status"){await F0("seal_deploy_hosecloud_status",Y,J,{},O0(Q.options));return}if(q==="configure"){let H=h(Q.options.input),W=H?JSON.parse(nq1(H,"utf8")):t6(Q.json);if(!W||Object.keys(W).length===0)throw Error("Usage: seal-use deploy hosecloud configure --json '{...}' or --input <file>");await F0("seal_deploy_hosecloud_configure",Y,J,W,O0(Q.options));return}if(q==="sync"){let H=G??h(Q.options.signKey)??h(Q.options["sign-key"]),W=_0(Q.options.auto)??_0(Q.options.yes);if(!H){let X=((await q4(Y)).integrations??[]).filter((w)=>w.type==="hosecloud");if(X.length===0)throw Error(`当前企业 (${J.name}) 尚未添加合思发布配置。
`+`\uD83D\uDC49 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${J.id}`);let Z=X[0];if(Z&&X.length===1&&W){let w=Z.signKey;console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${w})`),await F0("seal_deploy_hosecloud_sync",Y,J,{signKey:w},O0(Q.options));return}console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${J.id}]
`),console.error("ℹ️ 当前企业发现以下可用的合思配置卡片:");for(let w of X){let D=w.outboundName??"SealAI 审批",O=w.signKey,F=w.apiOrigin??"production";console.error(` • "${D}" (signKey: ${O}, 环境: ${F})`),console.error(` \uD83D\uDC49 同步命令: seal-use deploy hosecloud sync ${O} --corp ${J.id}
`)}if(X.length===1)console.error(`\uD83D\uDCA1 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${J.id}
`);throw Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。")}await F0("seal_deploy_hosecloud_sync",Y,J,{signKey:H},O0(Q.options));return}throw Error(`Unknown deploy hosecloud action: ${q??""}. Available: requirements, list, get, status, configure, sync.`)}import{createServer as oq1}from"node:http";import{URL as dq1}from"node:url";var NX0={openapi:"3.1.0",info:{title:"seal-use Wrapped API",version:"0.10.13",description:`Planned HTTP contract for the seal-use wrapped backend API.
These endpoints describe the intended stable API for frontend developers and agents once
the HTTP adapter is implemented.
They are not the raw downstream Seal endpoints. seal-use is responsible for enterprise
selection, source authentication, response compaction, and diagnostics-friendly fields.
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"2 Line truncated
`},servers:[{url:"http://localhost:8787",description:"Reserved for a future local HTTP adapter; the current service uses MCP stdio."}],security:[{localSession:[]}],tags:[{name:"Corps",description:"Local enterprise configuration selection."},{name:"Source",description:"Source-derived Seal enterprise configuration."},{name:"Auth",description:"Wrapped authentication diagnostics and current identity."},{name:"Approval Runs",description:"Wrapped approval run history, summaries, document URLs, and trace bridge helpers."},{name:"Approval Knowledge",description:"Wrapped approval rules, documents, preferences, and search."},{name:"Simulation",description:"Wrapped simulation batch record access."}],paths:{"/v1/corps":{get:{tags:["Corps"],operationId:"listCorps",summary:"List configured enterprises",responses:{"200":{description:"Configured enterprises.",content:{"application/json":{schema:{type:"array",items:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}}},"/v1/corps/current":{get:{tags:["Corps"],operationId:"getCurrentCorp",summary:"Get current enterprise",description:"Returns the configured default enterprise in stateful mode. Stateless mode has no current enterprise and requires an explicit corpId for enterprise operations.",responses:{"200":{description:"Current enterprise.",content:{"application/json":{schema:{type:"object",required:["id","name","sourceType","current"],properties:{id:{type:"string"},name:{type:"string"},sourceType:{type:"string",enum:["hose","direct","seal"]},current:{type:"boolean"}}}}}}}}},"/v1/corps/current/switch":{post:{tags:["Corps"],operationId:"switchCurrentCorp",summary:"Switch current enterprise",requestBody:{required:!0,content:{"application/json":{schema:{type:"object",required:["corpId"],properties:{corpId:{type:"string"}}}}}},responses:{"200":{description:"Switched enterprise.",content:{"application/json":{schema:{type:"object",required:["current","id","name"],properties:{current:{type:"boolean"},id:{type:"string"},name:{type:"string"}}}}}},"404":{description:"Requested resource was not found.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/source/config":{get:{tags:["Source"],operationId:"getSourceConfig",summary:"Resolve source-derived Seal enterprise config",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Redacted Seal enterprise config.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,description:"Redacted Seal enterprise config resolved from the configured source."}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/auth/diagnose":{get:{tags:["Auth"],operationId:"diagnoseAuth",summary:"Diagnose wrapped source-to-Seal authentication",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Authentication stage diagnosis.",content:{"application/json":{schema:{type:"object",required:["stages"],properties:{stages:{type:"array",items:{$ref:"#/components/schemas/AuthStage"}}}}}}}}}},"/v1/whoami":{get:{tags:["Auth"],operationId:"whoami",summary:"Get current wrapped Seal identity",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"200":{description:"Current Seal user and tenant.",content:{"application/json":{schema:{type:"object",required:["user","tenant"],properties:{user:{$ref:"#/components/schemas/SealUser"},tenant:{$ref:"#/components/schemas/SealTenant"}}}}}},"401":{description:"Local service authentication failed or downstream Seal auth failed.",content:{"application/json":{schema:{type:"object",additionalProperties:!0,required:["error"],properties:{error:{type:"string"},message:{type:"string"},details:{}}}}}}}}},"/v1/session":{get:{tags:["Auth"],operationId:"getSession",summary:"Get current wrapped Seal session metadata",parameters:[{name:"corpId",in:"query",schema:{type:"string"},description:"Local enterprise config ID. Required when global selection mode is stateless; optional in stateful mode, where the configured default enterprise is used."}],responses:{"2 Line truncated
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" />
<title>Seal Home API Docs (v${x})</title>
<title>Seal Home API Docs (v${e0})</title>
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>\uD83E\uDDAD</text></svg>" />
<style>
body {
@@ -219,20 +475,21 @@ selection, source authentication, response compaction, and diagnostics-friendly
src="https://cdn.jsdelivr.net/npm/@scalar/api-reference@1.25.101/dist/browser/standalone.js"
></script>
</body>
</html>`}async function Xn(n,i,r,o){let t=n.handler;return t(i,r,{corp:o})}async function jL(n,i){if(i.setHeader("Access-Control-Allow-Origin","*"),i.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),i.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),n.method==="OPTIONS"){i.writeHead(204),i.end();return}let r=n.headers.host||"localhost",o=n.headers["x-forwarded-proto"]||"http",t=new uK(n.url||"/",`${o}://${r}`),u=t.pathname.replace(/\/+$/,"")||"/",e=(n.method||"GET").toUpperCase();try{if(e==="GET"&&u==="/"){Sn(i,200,{name:"seal-use",version:x,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(e==="GET"&&u==="/docs"){lK(i,200,WL());return}if(e==="GET"&&u==="/openapi.json"){Sn(i,200,e$());return}if(e==="GET"&&u==="/health"){Sn(i,200,{status:"ok",version:x,name:"seal-use",timestamp:new Date().toISOString()});return}if(e==="POST"&&u==="/api/cli"){let l=await v$(n),$=(typeof l?.command==="string"?l.command:"").trim();if(!$){l$(i,400,"Missing 'command' property in request body");return}let I=T4($),g=I[0]==="seal-use"||I[0]==="seal-home"||I[0]?.endsWith("/seal-use")||I[0]?.endsWith("/seal-home")?I.slice(1):I,b=await Mu(g),w=void 0;try{if(b.stdout.trim().startsWith("{")||b.stdout.trim().startsWith("["))w=JSON.parse(b.stdout)}catch{}Sn(i,b.isError?400:200,{success:!b.isError,stdout:b.stdout,stderr:b.stderr,exitCode:b.exitCode,data:w});return}if(e==="POST"&&u.startsWith("/api/tool/")){let l=u.slice(10).trim(),$=Gn(l,{includeMcpAliases:!0});if(!$){l$(i,404,`Tool not found: '${l}'`);return}let I=await v$(n)||{},g=Rn(n,t,I),b=Ln(g),w=await On(b),f={...I};delete f.corp;let c=await Xn($,w,f,b);Sn(i,200,c);return}if(u.startsWith("/v1/")){if(await eK(n,i,e,u,t))return}l$(i,404,`Cannot ${e} ${u}. Visit /docs for available endpoints.`)}catch(l){let $=l instanceof Error?l.message:String(l);l$(i,500,$)}}async function eK(n,i,r,o,t){let u=Object.fromEntries(t.searchParams.entries());if(r==="GET"&&o==="/v1/corps"){let e=Yi(),l=bi();return Sn(i,200,{count:e.length,mode:l.stateful?"stateful":"stateless",defaultCorpId:l.defaultCorpId,corps:e.map(($)=>({id:$.id,name:$.name,sourceType:$.source.type,sealUrl:$.seal?.url}))}),!0}if(r==="GET"&&o==="/v1/whoami"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_whoami"),g=await Xn(I,$,{},l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/session"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_session_get"),g=await Xn(I,$,{},l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/summary"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_runs_summary"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/stats"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_runs_stats"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/pick"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_run_pick"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval-runs/url"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_run_url_get"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(o.startsWith("/v1/approval-runs/")){let e=o.slice(18).split("/"),l=e[0],$=e[1];if(l&&!["summary","pick","stats","url","bridge"].includes(l)){let I=Rn(n,t,u),g=Ln(I),b=await On(g);if(!$){let w=Gn("seal_approval_run_get"),f=await Xn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}if($==="attachments"){let w=Gn("seal_approval_run_attachments_get"),f=await Xn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}if($==="cited-rules"){let w=Gn("seal_approval_run_cited_rules_get"),f=await Xn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}if($==="document-summary"){let w=Gn("seal_approval_run_document_summary_get"),f=await Xn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}if($==="result"){let w=Gn("seal_approval_run_result_get"),f=await Xn(w,b,{recordId:l,...u},g);return Sn(i,200,f),!0}}}if(r==="GET"&&o==="/v1/approval-runs"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_runs_search"),g=await Xn(I,$,{...u,limit:u.limit?Number(u.limit):void 0,offset:u.offset?Number(u.offset):void 0,includeBridge:u.includeBridge==="true"},l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/approval/rules"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_approval_rules_list"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(r==="GET"&&o==="/v1/simulation/batches"){let e=Rn(n,t,u),l=Ln(e),$=await On(l),I=Gn("seal_simulation_batches_list"),g=await Xn(I,$,u,l);return Sn(i,200,g),!0}if(r==="POST"&&o==="/v1/simulation/create-batch"){let e=await v$(n)||{},l=Rn(n,t,e),$=Ln(l),I=await On($),g=Gn("seal_simulation_batch_create"),b=await Xn(g,I,e,$);return Sn(i,200,b),!0}if(r==="GET"&&o.startsWith("/v1/simulation/batch/")){let l=o.slice(21).split("/")[0];if(l){let $=Rn(n,t,u),I=LnLine truncated
\uD83D\uDE80 seal-use HTTP Server (v${x}) started`),console.error(` URL: http://${r}:${i}`),console.error(` Docs: http://${r}:${i}/docs`),console.error(` OpenAPI: http://${r}:${i}/openapi.json`),console.error(` CLI Exec: POST http://${r}:${i}/api/cli`),console.error(` REST API: http://${r}:${i}/v1/...
`);t(o)})})}async function XL(n){let i=ln(n.options.port)??ln(n.options.p),r=D(n.options.host)??D(n.options.h),o=await JL({port:i,host:r}),t=()=>{o.close(()=>{process.exit(0)})};process.on("SIGINT",t),process.on("SIGTERM",t),await new Promise(()=>{})}async function HL(n,i,r,o){if(n==="config"||n==="get"){await X("seal_llm_config_get",i,r,{},J(o.options));return}if(n==="providers"||n==="list"){await X("seal_llm_providers_list",i,r,{},J(o.options));return}throw Error(`Unknown llm command: ${n??""}. Run 'seal-use help' for available commands.`)}async function YL(n,i){if(n==="config"||n==="json"){V4();return}await q4()}function V4(){B({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function pL(n){let i=e$();B(i,{...J(n.options),allowFull:!0})}async function QL(n,i,r,o){if(n==="available"){await X("seal_permissions_available_list",i,r,{},J(o.options));return}if(n==="configs"||n==="list"){await X("seal_permissions_configs_list",i,r,{},J(o.options));return}throw Error(`Unknown permissions command: ${n??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as PL}from"node:fs";async function FL(n,i,r,o,t,u,e){if(!n||n==="get"){await X("seal_preference_get",t,u,{},J(e.options));return}if(n==="decision"){if(i==="update"||!i){let l=D(e.options.input),$=l?JSON.parse(PL(l,"utf8")):ri(e.json);if(!$||Object.keys($).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await X("seal_preference_decision_update",t,u,$,J(e.options));return}}if(n==="thinking-depth"||n==="thinkingDepth"){if(i==="set"){let l=D(e.options.default)??D(e.options.level)??o;if(l!=="medium"&&l!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await X("seal_preference_thinking_depth_set",t,u,{defaultLevel:l},J(e.options));return}if(i==="policies"){if(r==="list"||!r){await X("seal_preference_thinking_depth_policies_list",t,u,{},J(e.options));return}if(r==="upsert"){let l=D(e.options.input),$=l?JSON.parse(PL(l,"utf8")):ri(e.json);if(!$||!$.id||!$.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await X("seal_preference_thinking_depth_policies_upsert",t,u,$,J(e.options));return}if(r==="remove"||r==="delete"){let l=o??D(e.options.id)??D(e.options.policyId);if(!l)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await X("seal_preference_thinking_depth_policies_remove",t,u,{policyId:l},J(e.options));return}}}throw Error(`Unknown preference action: ${n??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function KL(n={}){let i=Yi(),r=bi(),o=Rr(i,{stateful:r.stateful,defaultCorpId:r.defaultCorpId,corpId:n.corpId},Kt());console.log(`[probe] corp=${o.id} source=${o.source.type}`);let t=await ar(o);console.log("[probe] seal enterprise"),console.log(JSON.stringify(t,null,2));let u=await On(o),e=await hv(u,{documentLimit:20,stylePreferencesEndpoint:o.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:e.rules.rules.length,hasPendingRuleDeletes:e.rules.hasPendingDeletes,documents:e.documents.articles.length,documentsTotal:e.documents.total,stylePreferences:e.stylePreferences.ok?"ok":`error: ${e.stylePreferences.error}`},null,2))}async function BL(n,i,r){let o=i??D(r.options.corp)??(n&&n!=="--corp"?n:void 0);await KL({corpId:o})}async function EL(n,i,r,o,t){if(n==="count"){await X("seal_approval_rules_list",r,o,{countOnly:!0},J(t.options));return}if(n==="list"){if(_(t.options.count)){await X("seal_approval_rules_list",r,o,{countOnly:!0},J(t.options));return}let u=ln(t.options.limit),e=ln(t.options.offset);if(_(t.options.summary)){await X("seal_approval_rules_list",r,o,{fields:uL,limit:u,offset:e},J(t.options));return}let l=await xr("seal_approval_rules_list",r,o,{limit:u,offset:e});eL(l,_(t.options.full)===!0),B(l);return}if(n==="clear"){let u=_(t.options.yes)===!0,e=_(t.options.dryRun)??_(t.options["dry-run"])??!u;if(!u&&!e)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let l=await xr("seal_approval_rules_clear",r,o,{dryRun:e,recode:_(t.options.recode)});if(!u&&e&&l&&typeof l==="object"){B({...l,nextCommand:`seal-use rules clear --corp ${o.id} --yes`},J(t.options));return}B(l,J(t.options));return}if(n==="versions"){await X("seal_approval_rule_versions_list",r,o,{},J(t.options));return}if(n==="version"){let u=i??D(t.options.version);if(!u)throw Error("Usage: seal-use rules version <versionId|versionNumber|latest>");await X("seal_approval_rule_version_get",r,o,Vu(u),J(t.options));return}if(n==="get"){await X("seal_approval_rule_get",r,o,{...oL(D(t.options.version)),code:D(t.options.code),runtimeId:D(t.options.runtimeId)??D(t.options["runtime-id"]),recordId:D(t.options.recordId)??D(t.options["record-id"])},J(t.options));return}if( Line truncated
`,{mode:384}),I$(r,`running pid=${process.pid}`);let o=()=>{if(Z4(i)===process.pid)$$(i,{force:!0});I$(r,`stopped pid=${process.pid}`)};await new Promise((t)=>{let u=!1,e=setInterval(()=>{},60000),l=()=>{if(u)return;u=!0,o(),clearInterval(e),process.off("SIGTERM",l),process.off("SIGINT",l),t()};process.once("SIGTERM",l),process.once("SIGINT",l)})}function TL(n){ZL(n.stateDir);let i=sr(n);if(i.running)return i;let r=n.launcher??{command:process.execPath,args:[n.entryFile]},o=$K(r.command,[...r.args??[],"service","run"],{cwd:n.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});o.unref();let t=g$(n);return _4(t,`${o.pid}
`,{mode:384}),I$(b$(n),`started pid=${o.pid}`),{started:!0,...sr(n)}}function VL(n,i={}){let r=g$(n),o=Z4(r);if(!o||!_L(o,n.appRoot))return $$(r,{force:!0}),i.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(o,"SIGTERM"),$$(r,{force:!0}),I$(b$(n),`stop requested pid=${o}`),i.quiet?void 0:{stopped:!0,pid:o}}function _L(n,i){if(!cK(n))return!1;try{let r=IK("ps",["-p",String(n),"-o","command="],{encoding:"utf8"});return(r.includes(i)||r.includes("seal-use")||r.includes("src/cli.ts"))&&r.includes("service")&&r.includes("run")}catch{return!1}}function cK(n){try{return process.kill(n,0),!0}catch{return!1}}function g$(n){return qL(n.stateDir,"service.pid")}function b$(n){return qL(n.stateDir,"service.log")}function Z4(n){if(!gK(n))return;let i=Number(wK(n,"utf8").trim());return Number.isInteger(i)&&i>0?i:void 0}function ZL(n){bK(n,{recursive:!0,mode:448})}function I$(n,i){_4(n,`${new Date().toISOString()} ${i}
`,{flag:"a",mode:384})}var M4=DK(UK(),".config","seal-use");async function ML(n,i){let r=await _t(n,{appRoot:i.appRoot,entryFile:i.entryFile,stateDir:M4,version:x,launcher:i.launcher});if(r!==void 0)B(r)}import{existsSync as SK,readFileSync as zL}from"node:fs";async function CL(n,i,r,o,t){if(n==="batch-records"||n==="records"){let u=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!u)throw Error("Usage: seal-use simulation batch-records <batchId>");await X("seal_simulation_batch_records_get",r,o,{batchId:u,query:D(t.options.query)},J(t.options));return}if(n==="create"||n==="run"){let u=D(t.options.mode)??D(t.options.sourceSystem)??D(t.options["source-system"])??"hosecloud",e=u==="material-pack"?"material_pack":u,l=D(t.options.schemaConfig)??D(t.options["schema-config"]),$=l?JSON.parse(zL(l,"utf8")):void 0,I=D(t.options.input),g=I?JSON.parse(zL(I,"utf8")):ri(t.json),b=D(t.options.packageId)??D(t.options["package-id"]),w=Vn(t.options.packageIds)??Vn(t.options["package-ids"])??(b?[b]:void 0),f=Vn(t.options.flowIds)??Vn(t.options["flow-ids"])??Vn(t.options.documentSn)??Vn(t.options["document-sn"]),c=D(t.options.signKey)??D(t.options["sign-key"])??D(t.options.integration);await X("seal_simulation_batch_create",r,o,{mode:e,sourceSystem:e,flowIds:f,documentSn:f,rejectNodeName:D(t.options.rejectNode)??D(t.options["reject-node"])??null,thinkingDepthOverride:D(t.options.thinkingDepth)??D(t.options["thinking-depth"]),skipInvoiceGeneration:_(t.options.skipInvoiceGeneration)??_(t.options["skip-invoice-generation"]),skipExpenseExtraction:_(t.options.skipExpenseExtraction)??_(t.options["skip-expense-extraction"]),disableAttachmentCache:_(t.options.disableAttachmentCache)??_(t.options["disable-attachment-cache"]),signKey:c,packageIds:w,packageId:b,templateId:D(t.options.templateId)??D(t.options["template-id"]),schemaConfig:$,requestIds:Vn(t.options.requestIds)??Vn(t.options["request-ids"]),workflowTypeId:D(t.options.workflowTypeId)??D(t.options["workflow-type-id"]),flowStatusList:Vn(t.options.flowStatusList)?.map(Number)??Vn(t.options["flow-status-list"])?.map(Number),businessCodes:Vn(t.options.businessCodes)??Vn(t.options["business-codes"]),documentType:D(t.options.documentType)??D(t.options["document-type"]),startTime:ln(t.options.startTime)??ln(t.options["start-time"]),endTime:ln(t.options.endTime)??ln(t.options["end-time"]),status:Vn(t.options.status),limit:ln(t.options.limit),rawParams:g},J(t.options));return}if(n==="wait"){let u=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!u)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await X("seal_simulation_batch_wait",r,o,{batchId:u,timeout:D(t.options.timeout),pollInterval:D(t.options.pollInterval)??D(t.options["poll-interval"])},J(t.options));return}if(n==="clean"||n==="delete"){let u=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!u)throw Error("Usage: seal-use simulation clean <batchId>");await X("seal_simulation_batch_clean",r,o,{batchId:u},J(t.options));return}if(n==="specifications"){let u=i??D(t.options.integration)??D(t.options.signKey)??D(t.options["sign-key"]);await X("seal_simulation_specifications_list",r,o,{signKey:u},J(t.options));return}if(n==="list"){await X("seal_simulation_batches_list",r,o,{limit:ln(t.options.limit)},J(t.options));return}if(n==="get"){let u=i??D(t.options.batchId)??D(t.options["batch-id"]);if(!u)throw Error("Usage: seal-use simulation get <batchId>");await X("seal_simulation_batch_get",r,o,{batchId:u},J(t.options));return}if(n==="templates"){await X("seal_simulation_templates_get",r,o,{},J(t.options));return}if(n==="integrations"){await X("seal_simulation_integrations_get",r,o,{},J(t.options));return}if(n==="package-upload"){let u=i??D(t.options.file);if(!u)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!SK(u))throw Error(`File not found: ${u}`);await X("seal_simulation_material_package_upload",r,o,{filePath:u},J(t.options));return}throw Error(`Unknown simulation command: ${n??""}. Run 'seal-use help' for available commands.`)}import{existsSync as gy}from"node:fs";import{join as w$}from"node:path";import{existsSync as z4,mkdirSync as uy,rmSync as XK,writeFileSync as HK}from"node:fs";import{homedir as ey}from"node:os";import{dirname as YK,join as C4}from"node:path";var RL=`---
</html>`}async function k4($,I,U,Y){let J=$.handler;return J(I,U,{corp:Y})}async function MX0($,I){if(I.setHeader("Access-Control-Allow-Origin","*"),I.setHeader("Access-Control-Allow-Methods","GET, POST, PUT, DELETE, OPTIONS, PATCH"),I.setHeader("Access-Control-Allow-Headers","Content-Type, Authorization, X-Seal-Corp, X-Seal-Home-Session"),$.method==="OPTIONS"){I.writeHead(204),I.end();return}let U=$.headers.host||"localhost",Y=$.headers["x-forwarded-proto"]||"http",J=new dq1($.url||"/",`${Y}://${U}`),Q=J.pathname.replace(/\/+$/,"")||"/",K=($.method||"GET").toUpperCase();try{if(K==="GET"&&Q==="/"){d1(I,200,{name:"seal-use",version:e0,description:"Seal tenant operations and approval automation HTTP API",docs:"/docs",openapi:"/openapi.json",health:"/health",endpoints:{cli:"POST /api/cli",tools:"GET /api/tools",toolInvoke:"POST /api/tool/:name",restV1:"GET/POST /v1/*"}});return}if(K==="GET"&&Q==="/docs"){lq1(I,200,FX0());return}if(K==="GET"&&Q==="/openapi.json"){d1(I,200,JO());return}if(K==="GET"&&Q==="/health"){d1(I,200,{status:"ok",version:e0,name:"seal-use",timestamp:new Date().toISOString()});return}if(K==="POST"&&(Q==="/shutdown"||Q==="/api/shutdown")){d1(I,200,{success:!0,message:"Shutting down seal-use background daemon",pid:process.pid}),setTimeout(()=>{process.kill(process.pid,"SIGTERM")},50);return}if(K==="POST"&&Q==="/api/cli"){let q=await KO($),G=(typeof q?.command==="string"?q.command:"").trim();if(!G){QO(I,400,"Missing 'command' property in request body");return}let H=$x(G),W=H[0]==="seal-use"||H[0]==="seal-home"||H[0]?.endsWith("/seal-use")||H[0]?.endsWith("/seal-home")?H.slice(1):H,V=await HG(W),X=void 0;try{if(V.stdout.trim().startsWith("{")||V.stdout.trim().startsWith("["))X=JSON.parse(V.stdout)}catch{}d1(I,V.isError?400:200,{success:!V.isError,stdout:V.stdout,stderr:V.stderr,exitCode:V.exitCode,data:X});return}if(K==="POST"&&Q.startsWith("/api/tool/")){let q=Q.slice(10).trim(),G=C4(q);if(!G){QO(I,404,`Tool not found: '${q}'`);return}let H=await KO($)||{},W=g6($,J,H),V=O4(W),X=await U4(V),Z={...H};delete Z.corp;let w=await k4(G,X,Z,V);d1(I,200,w);return}if(Q.startsWith("/v1/")){if(await mq1($,I,K,Q,J))return}QO(I,404,`Cannot ${K} ${Q}. Visit /docs for available endpoints.`)}catch(q){let G=q instanceof Error?q.message:String(q);QO(I,500,G)}}async function mq1($,I,U,Y,J){let Q=Object.fromEntries(J.searchParams.entries());if(U==="GET"&&Y==="/v1/corps"){let K=b8(),q=D4();return d1(I,200,{count:K.length,mode:q.stateful?"stateful":"stateless",defaultCorpId:q.defaultCorpId,corps:K.map((G)=>({id:G.id,name:G.name,sourceType:G.source.type,sealUrl:G.seal?.url}))}),!0}if(U==="GET"&&Y==="/v1/whoami"){let K=g6($,J,Q),q=O4(K),G=await U4(q),H=C4("seal_whoami"),W=await k4(H,G,{},q);return d1(I,200,W),!0}if(U==="GET"&&Y==="/v1/session"){let K=g6($,J,Q),q=O4(K),G=await U4(q),H=C4("seal_session_get"),W=await k4(H,G,{},q);return d1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/summary"){let K=g6($,J,Q),q=O4(K),G=await U4(q),H=C4("seal_approval_runs_summary"),W=await k4(H,G,Q,q);return d1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/stats"){let K=g6($,J,Q),q=O4(K),G=await U4(q),H=C4("seal_approval_runs_stats"),W=await k4(H,G,Q,q);return d1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/pick"){let K=g6($,J,Q),q=O4(K),G=await U4(q),H=C4("seal_approval_run_pick"),W=await k4(H,G,Q,q);return d1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval-runs/url"){let K=g6($,J,Q),q=O4(K),G=await U4(q),H=C4("seal_approval_run_url_get"),W=await k4(H,G,Q,q);return d1(I,200,W),!0}if(Y.startsWith("/v1/approval-runs/")){let K=Y.slice(18).split("/"),q=K[0],G=K[1];if(q&&!["summary","pick","stats","url","bridge"].includes(q)){let H=g6($,J,Q),W=O4(H),V=await U4(W);if(!G){let X=C4("seal_approval_run_get"),Z=await k4(X,V,{recordId:q,...Q},W);return d1(I,200,Z),!0}if(G==="attachments"){let X=C4("seal_approval_run_attachments_get"),Z=await k4(X,V,{recordId:q,...Q},W);return d1(I,200,Z),!0}if(G==="cited-rules"){let X=C4("seal_approval_run_cited_rules_get"),Z=await k4(X,V,{recordId:q,...Q},W);return d1(I,200,Z),!0}if(G==="document-summary"){let X=C4("seal_approval_run_document_summary_get"),Z=await k4(X,V,{recordId:q,...Q},W);return d1(I,200,Z),!0}if(G==="result"){let X=C4("seal_approval_run_result_get"),Z=await k4(X,V,{recordId:q,...Q},W);return d1(I,200,Z),!0}}}if(U==="GET"&&Y==="/v1/approval-runs"){let K=g6($,J,Q),q=O4(K),G=await U4(q),H=C4("seal_approval_runs_search"),W=await k4(H,G,{...Q,limit:Q.limit?Number(Q.limit):void 0,offset:Q.offset?Number(Q.offset):void 0,includeBridge:Q.includeBridge==="true"},q);return d1(I,200,W),!0}if(U==="GET"&&Y==="/v1/approval/rules"){let K=g6($,J,Q),q=O4(K),G=await U4(q),H=C4("seal_approval_rules_list"),W=await k4(H,G,Q,q);return d1(I,200,W),!0}if(U==="GET"&&Y==="/v1/simulation/batches"){let K=g6($,J,Q),q=O4(K),G=await U4(q),H=C4("seal_simulation_batches_list"),W=await k4(H,G,Q,q);return d1(I,200,W),!0}if(U==="POST"&&Y==="/v1/simulation/create-batch"){let K=await KO($)||{},q=g6($,J,K),G=O4(q),H=await U4Line truncated
\uD83D\uDE80 seal-use HTTP Server (v${e0}) started`),console.error(` URL: http://${U}:${I}`),console.error(` Docs: http://${U}:${I}/docs`),console.error(` OpenAPI: http://${U}:${I}/openapi.json`),console.error(` CLI Exec: POST http://${U}:${I}/api/cli`),console.error(` REST API: http://${U}:${I}/v1/...
`);J(Y)})})}async function zX0($){let I=U1($.options.port)??U1($.options.p),U=h($.options.host)??h($.options.h),Y=await HO({port:I,host:U}),J=()=>{Y.close(()=>{process.exit(0)})};process.on("SIGINT",J),process.on("SIGTERM",J),await new Promise(()=>{})}async function AX0($,I,U,Y){if($==="config"||$==="get"){await F0("seal_llm_config_get",I,U,{},O0(Y.options));return}if($==="providers"||$==="list"){await F0("seal_llm_providers_list",I,U,{},O0(Y.options));return}throw Error(`Unknown llm command: ${$??""}. Run 'seal-use help' for available commands.`)}async function PX0($,I){if($==="config"||$==="json"){Ix();return}await Ux()}function Ix(){E0({mcpServers:{"seal-use":{type:"stdio",command:"seal-use",args:["mcp"],env:{SEAL_USE_MCP_ENABLED:"true"}}}})}function TX0($){let I=JO();E0(I,{...O0($.options),allowFull:!0})}async function EX0($,I,U,Y){if($==="available"){await F0("seal_permissions_available_list",I,U,{},O0(Y.options));return}if($==="configs"||$==="list"){await F0("seal_permissions_configs_list",I,U,{},O0(Y.options));return}throw Error(`Unknown permissions command: ${$??""}. Run 'seal-use help' for available commands.`)}import{readFileSync as BX0}from"node:fs";async function RX0($,I,U,Y,J,Q,K){if(!$||$==="get"){await F0("seal_preference_get",J,Q,{},O0(K.options));return}if($==="decision"){if(I==="update"||!I){let q=h(K.options.input),G=q?JSON.parse(BX0(q,"utf8")):t6(K.json);if(!G||Object.keys(G).length===0)throw Error(`Usage: seal-use preference decision update --json '{"explicitApprove":"..."}'`);await F0("seal_preference_decision_update",J,Q,G,O0(K.options));return}}if($==="thinking-depth"||$==="thinkingDepth"){if(I==="set"){let q=h(K.options.default)??h(K.options.level)??Y;if(q!=="medium"&&q!=="high")throw Error("Usage: seal-use preference thinking-depth set --default <medium|high>");await F0("seal_preference_thinking_depth_set",J,Q,{defaultLevel:q},O0(K.options));return}if(I==="policies"){if(U==="list"||!U){await F0("seal_preference_thinking_depth_policies_list",J,Q,{},O0(K.options));return}if(U==="upsert"){let q=h(K.options.input),G=q?JSON.parse(BX0(q,"utf8")):t6(K.json);if(!G||!G.id||!G.name)throw Error(`Usage: seal-use preference thinking-depth policies upsert --json '{"id":"...","name":"...","level":"high"}'`);await F0("seal_preference_thinking_depth_policies_upsert",J,Q,G,O0(K.options));return}if(U==="remove"||U==="delete"){let q=Y??h(K.options.id)??h(K.options.policyId);if(!q)throw Error("Usage: seal-use preference thinking-depth policies remove <policyId>");await F0("seal_preference_thinking_depth_policies_remove",J,Q,{policyId:q},O0(K.options));return}}}throw Error(`Unknown preference action: ${$??""}. Available: get, decision update, thinking-depth set, thinking-depth policies list/upsert/remove.`)}async function vX0($={}){let I=b8(),U=D4(),Y=WJ(I,{stateful:U.stateful,defaultCorpId:U.defaultCorpId,corpId:$.corpId},o3());console.log(`[probe] corp=${Y.id} source=${Y.source.type}`);let J=await zJ(Y);console.log("[probe] seal enterprise"),console.log(JSON.stringify(J,null,2));let Q=await U4(Y),K=await _V(Q,{documentLimit:20,stylePreferencesEndpoint:Y.seal.endpoints.approvalStylePreferences});console.log("[probe] approval context summary"),console.log(JSON.stringify({rules:K.rules.rules.length,hasPendingRuleDeletes:K.rules.hasPendingDeletes,documents:K.documents.articles.length,documentsTotal:K.documents.total,stylePreferences:K.stylePreferences.ok?"ok":`error: ${K.stylePreferences.error}`},null,2))}async function CX0($,I,U){let Y=I??h(U.options.corp)??($&&$!=="--corp"?$:void 0);await vX0({corpId:Y})}async function Yx($,I,U,Y,J){if($==="count"){await F0("seal_approval_rules_list",U,Y,{countOnly:!0},O0(J.options));return}if($==="list"){if(_0(J.options.count)){await F0("seal_approval_rules_list",U,Y,{countOnly:!0},O0(J.options));return}let Q=U1(J.options.limit),K=U1(J.options.offset);if(_0(J.options.summary)){await F0("seal_approval_rules_list",U,Y,{fields:aZ0,limit:Q,offset:K},O0(J.options));return}let q=await QI("seal_approval_rules_list",U,Y,{limit:Q,offset:K});sZ0(q,_0(J.options.full)===!0),E0(q);return}if($==="clear"){let Q=_0(J.options.yes)===!0,K=_0(J.options.dryRun)??_0(J.options["dry-run"])??!Q;if(!Q&&!K)throw Error("Refusing to clear rules without --yes. Use --dry-run to preview.");let q=await QI("seal_approval_rules_clear",U,Y,{dryRun:K,recode:_0(J.options.recode)});if(!Q&&K&&q&&typeof q==="object"){E0({...q,nextCommand:`seal-use rules clear --corp ${Y.id} --yes`},O0(J.options));return}E0(q,O0(J.options));return}if($==="versions"){await F0("seal_approval_rule_versions_list",U,Y,{},O0(J.options));return}if($==="version"){let Q=I??h(J.options.version);if(!Q)throw Error("Usage: seal-use rules version <versionId|versionNumber|latest>");await F0("seal_approval_rule_version_get",U,Y,QG(Q),O0(J.options));return}if($==="get"){await F0("seal_approval_rule_get",U,Y,{...tZ0(h(J.options.version)),code:h(J.options.code),runtimeId:h(J.options.runtimeId)??h(J.options["runtime-id"]),recordId:h(J.options.r Line truncated
`).filter(Boolean),Q=J.slice(-I);return{logFile:U,lines:Q,totalLines:J.length}}async function eq1($){let I=XO($),U=Kx($),Y=WG($);gX0($.stateDir);let J=$.port??(process.env.PORT?Number.parseInt(process.env.PORT,10):qO),Q=$.host??(process.env.HOST?process.env.HOST:GO);VO(I,`${process.pid}
`,{mode:384}),VO(U,JSON.stringify({pid:process.pid,port:J,host:Q,version:$.version,startedAt:new Date().toISOString()},null,2),{mode:384}),AJ(Y,`service starting on http://${Q}:${J} pid=${process.pid}`);let K=null;try{K=await HO({port:J,host:Q,silent:!0}),AJ(Y,`service listening pid=${process.pid}`)}catch(G){if(AJ(Y,`service failed to bind port ${J}: ${G instanceof Error?G.message:String(G)}`),ZO(I)===process.pid)n8(I,{force:!0}),n8(U,{force:!0});throw G}let q=()=>{if(K)K.close(),K=null;if(ZO(I)===process.pid)n8(I,{force:!0}),n8(U,{force:!0});AJ(Y,`stopped pid=${process.pid}`)};await new Promise((G)=>{let H=!1,W=()=>{if(H)return;H=!0,q(),process.off("SIGTERM",W),process.off("SIGINT",W),G()};process.once("SIGTERM",W),process.once("SIGINT",W)})}function jX0($){gX0($.stateDir);let I=PJ($);if(I.running)return I;let U=$.launcher??{command:process.execPath,args:[$.entryFile]},Y=[...U.args??[],"service","run"];if($.port)Y.push("--port",String($.port));if($.host)Y.push("--host",String($.host));let J=rq1(U.command,Y,{cwd:$.appRoot,detached:!0,stdio:["ignore","ignore","ignore"],env:process.env});J.unref();let Q=XO($);return VO(Q,`${J.pid}
`,{mode:384}),AJ(WG($),`started pid=${J.pid}`),{started:!0,...PJ($)}}function _X0($,I={}){let U=XO($),Y=Kx($),J=ZO(U);if(!J||!SX0(J,$.appRoot))return n8(U,{force:!0}),n8(Y,{force:!0}),I.quiet?void 0:{stopped:!1,reason:"not running"};return process.kill(J,"SIGTERM"),n8(U,{force:!0}),n8(Y,{force:!0}),AJ(WG($),`stop requested pid=${J}`),I.quiet?void 0:{stopped:!0,pid:J}}function SX0($,I){if(!$G1($))return!1;try{let U=tq1("ps",["-p",String($),"-o","command="],{encoding:"utf8"});return(U.includes(I)||U.includes("seal-use")||U.includes("src/cli.ts"))&&U.includes("service")&&U.includes("run")}catch{return!1}}function $G1($){try{return process.kill($,0),!0}catch{return!1}}function XO($){return Qx($.stateDir,"service.pid")}function Kx($){return Qx($.stateDir,"service.json")}function WG($){return Qx($.stateDir,"service.log")}function ZO($){if(!WO($))return;let I=Number(Jx($,"utf8").trim());return Number.isInteger(I)&&I>0?I:void 0}function gX0($){aq1($,{recursive:!0,mode:448})}function AJ($,I){VO($,`${new Date().toISOString()} ${I}
`,{flag:"a",mode:384})}var qx=UG1(IG1(),".config","seal-use");async function Gx($,I,U){let Y=U?U1(U.options.port)??U1(U.options.p):void 0,J=U?h(U.options.host)??h(U.options.h):void 0,Q=U?U1(U.options.lines)??U1(U.options.n):void 0,K=await KI($,{appRoot:I.appRoot,entryFile:I.entryFile,stateDir:qx,version:e0,launcher:I.launcher,port:Y,host:J},{maxLines:Q});if(K!==void 0)E0(K)}import{existsSync as YG1,readFileSync as yX0}from"node:fs";async function hX0($,I,U,Y,J){if($==="batch-records"||$==="records"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation batch-records <batchId>");await F0("seal_simulation_batch_records_get",U,Y,{batchId:Q,query:h(J.options.query)},O0(J.options));return}if($==="create"||$==="run"){let Q=h(J.options.mode)??h(J.options.sourceSystem)??h(J.options["source-system"])??"hosecloud",K=Q==="material-pack"?"material_pack":Q,q=h(J.options.schemaConfig)??h(J.options["schema-config"]),G=q?JSON.parse(yX0(q,"utf8")):void 0,H=h(J.options.input),W=H?JSON.parse(yX0(H,"utf8")):t6(J.json),V=h(J.options.packageId)??h(J.options["package-id"]),X=M6(J.options.packageIds)??M6(J.options["package-ids"])??(V?[V]:void 0),Z=M6(J.options.flowIds)??M6(J.options["flow-ids"])??M6(J.options.documentSn)??M6(J.options["document-sn"]),w=h(J.options.signKey)??h(J.options["sign-key"])??h(J.options.integration);await F0("seal_simulation_batch_create",U,Y,{mode:K,sourceSystem:K,flowIds:Z,documentSn:Z,rejectNodeName:h(J.options.rejectNode)??h(J.options["reject-node"])??null,thinkingDepthOverride:h(J.options.thinkingDepth)??h(J.options["thinking-depth"]),skipInvoiceGeneration:_0(J.options.skipInvoiceGeneration)??_0(J.options["skip-invoice-generation"]),skipExpenseExtraction:_0(J.options.skipExpenseExtraction)??_0(J.options["skip-expense-extraction"]),disableAttachmentCache:_0(J.options.disableAttachmentCache)??_0(J.options["disable-attachment-cache"]),signKey:w,packageIds:X,packageId:V,templateId:h(J.options.templateId)??h(J.options["template-id"]),schemaConfig:G,requestIds:M6(J.options.requestIds)??M6(J.options["request-ids"]),workflowTypeId:h(J.options.workflowTypeId)??h(J.options["workflow-type-id"]),flowStatusList:M6(J.options.flowStatusList)?.map(Number)??M6(J.options["flow-status-list"])?.map(Number),businessCodes:M6(J.options.businessCodes)??M6(J.options["business-codes"]),documentType:h(J.options.documentType)??h(J.options["document-type"]),startTime:U1(J.options.startTime)??U1(J.options["start-time"]),endTime:U1(J.options.endTime)??U1(J.options["end-time"]),status:M6(J.options.status),limit:U1(J.options.limit),rawParams:W},O0(J.options));return}if($==="wait"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation wait <batchId> [--timeout 10m] [--poll-interval 2s]");await F0("seal_simulation_batch_wait",U,Y,{batchId:Q,timeout:h(J.options.timeout),pollInterval:h(J.options.pollInterval)??h(J.options["poll-interval"])},O0(J.options));return}if($==="clean"||$==="delete"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation clean <batchId>");await F0("seal_simulation_batch_clean",U,Y,{batchId:Q},O0(J.options));return}if($==="specifications"){let Q=I??h(J.options.integration)??h(J.options.signKey)??h(J.options["sign-key"]);await F0("seal_simulation_specifications_list",U,Y,{signKey:Q},O0(J.options));return}if($==="list"){await F0("seal_simulation_batches_list",U,Y,{limit:U1(J.options.limit)},O0(J.options));return}if($==="get"){let Q=I??h(J.options.batchId)??h(J.options["batch-id"]);if(!Q)throw Error("Usage: seal-use simulation get <batchId>");await F0("seal_simulation_batch_get",U,Y,{batchId:Q},O0(J.options));return}if($==="templates"){await F0("seal_simulation_templates_get",U,Y,{},O0(J.options));return}if($==="integrations"){await F0("seal_simulation_integrations_get",U,Y,{},O0(J.options));return}if($==="package-upload"){let Q=I??h(J.options.file);if(!Q)throw Error("Usage: seal-use simulation package-upload <材料包.zip>");if(!YG1(Q))throw Error(`File not found: ${Q}`);await F0("seal_simulation_material_package_upload",U,Y,{filePath:Q},O0(J.options));return}throw Error(`Unknown simulation command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as eX0}from"node:fs";import{join as LO}from"node:path";import{existsSync as Hx,mkdirSync as lX0,rmSync as wG1,writeFileSync as DG1}from"node:fs";import{homedir as oX0}from"node:os";import{dirname as OG1,join as Wx}from"node:path";var xX0=`---
name: seal-use
description: "v0.10.3: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.10.13: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.10.3
short-description: Seal tenant and Hose approval automation (v0.10.3)
version: 0.10.13
short-description: Seal tenant and Hose approval automation (v0.10.13)
---
# Seal Use (v0.10.3)
# Seal Use (v0.10.13)
Use the \`seal_cli\` MCP tool when it is available; pass the command string as its \`command\` argument. If MCP is unavailable, fall back to the global \`seal-use\` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
@@ -291,8 +548,11 @@ seal-use corps list
- LLM Model Config & Providers: \`seal-use llm config --corp <corpId>\`, \`seal-use llm providers --corp <corpId>\`.
- System Permissions Config: \`seal-use permissions available --corp <corpId>\`, \`seal-use permissions configs --corp <corpId>\`.
- Billing & Feature Quotas: \`seal-use billing status --corp <corpId>\`, \`seal-use billing plans --corp <corpId>\`, \`seal-use billing features --corp <corpId>\`.
- Webhook 审批回调管理: \`seal-use webhook <list|get|add|update|delete> --corp <corpId>\`.
- Webhook 准备看板与审批回调管理: \`seal-use webhook ready [<材料包.zip>] --corp <corpId>\` (别名 \`status\`) 检查企业环境、租户连通性、已激活通道与材料包预检;\`seal-use webhook <list|get|add|update|delete> --corp <corpId>\`.
- Webhook 材料包导入: \`seal-use webhook material-pack preview <材料包.zip> --corp <corpId>\` 只做本地校验和解析(无网络请求);\`... push <材料包.zip> [--webhook <idOrName>] --corp <corpId>\` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 \`--webhook\`)。材料包格式:ZIP 根目录名 = \`documentId\`(或 \`documentId@annotation\`),Excel 附件列以 \`[附件]\` 为前缀(如 \`[附件]合同协议\`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明的路径必须在 ZIP 中存在,ZIP 中的文件必须在某个 \`[附件]\` 列中声明)。详见 \`references/cli.md\` 中 "Material Pack Workflow" 一节。它与 \`simulation material_pack\` 的官方服务端导入流程相互独立。
- HTTP REST API & Docs Server: \`seal-use http [--port 8787] [--host 127.0.0.1]\` (提供 \`/docs\` 交互文档、\`/openapi.json\`、\`POST /api/cli\` 与 \`/v1/*\` REST API)。
- 审批规则质量校验 (Linter): \`seal-use rules lint [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary] --corp <corpId>\`; read \`references/rule-lint.md\`. 全局配置默认关闭 (\`config lint <enable|disable>\`)。
- Full CLI inventory: read \`references/cli.md\`.
## High-Value Commands
@@ -308,6 +568,7 @@ seal-use approval-runs attachments <recordId> --corp <corpId> --summary
seal-use approval-runs result <recordId> --corp <corpId> --summary
seal-use rules count --corp <corpId>
seal-use rules list --corp <corpId> --summary
seal-use rules lint --corp <corpId> --summary
seal-use rules clear --corp <corpId> --dry-run
seal-use rules clear --corp <corpId> --yes
seal-use rules get --corp <corpId> --version 16 --code '#0038'
@@ -338,6 +599,7 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
- \`references/enterprise-onboarding.md\`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- \`references/approval-run-lightweight.md\`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
- \`references/rule-lightweight.md\`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
- \`references/rule-lint.md\`: 规则质量检查器(Linter)、模糊词拦截、悬空例外闭环、多 TS 校验器切换与发布门禁。
- \`references/customer-feedback-rule-remediation.md\`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
- \`references/hose-enterprise-auth.md\`: Hose 企业配置、认证诊断、授权链接。
- \`references/hose-enterprise-init.md\`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
@@ -348,11 +610,11 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
## Safety
Rule, document, style preference, and publish actions mutate Seal configuration. Make the target enterprise explicit, show the intended payload, and verify after the write. Never send real \`enterprises/*.json\` files, tokens, signed URLs, or full raw documents to GitHub, tickets, logs, or chat unless the user explicitly requests a safe export.
`;var hL=`interface:
`;var kX0=`interface:
display_name: "Seal Use"
short_description: "Diagnose approval feedback and publish minimal rule fixes"
default_prompt: "Use $seal-use to resolve a customer feedback package to the correct tenant, diagnose the approval run, propose a minimal rule diff, and publish only after explicit confirmation."
`;var mL=`# Rule Lightweight Queries
`;var uX0=`# Rule Lightweight Queries
Use this reference when the user wants rule counts, compact rule lists, one rule from a historical version, or approval knowledge search without dumping hundreds of rule descriptions.
@@ -457,7 +719,7 @@ Use current search only when the question is about current draft/current knowled
## Output Discipline
If a rule command would return many descriptions or more than about 20 rules, use \`rules count\`, \`rules list --summary\`, \`fields\`, \`snippetOnly\`, or \`--output-file\`. Use \`--full\` only for deliberate exports.
`;var xL=`# Approval Bad Case Catalog
`;var fX0=`# Approval Bad Case Catalog
Use this file only as a comparison catalog after inspecting the current trace. Do not treat any case below as a default diagnosis.
@@ -507,7 +769,7 @@ Important nuance:
- This is a bad-case pattern, not a general rule that every amount-total dispute is caused by \`pre_analysis\`.
- Use it when the current trace shows recognized amounts being excluded downstream or duplicate attachments producing inconsistent conclusions.
`;var aL="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use <command>\n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged.\n- User-level configs override same-ID local configs.\n\nEnterprise selection is stateless by default. Commands that access an enterprise require\n`--corp <corpId>` unless stateful mode is explicitly enabled:\n\n```bash\nseal-use config mode stateful --corp <corpId>\nseal-use corps switch <corpId>\nseal-use config mode stateless\n```\n\nThe global mode is stored in `~/.config/seal-use/config.json`; set `SEAL_USE_CONFIG_FILE` to\noverride that path. The legacy `current-corp` file is not read.\n\n## Stream & Exit Code Contract\n\n- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.\n- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).\n- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.\n\n## Top-Level Commands\n\n```bash\nseal-use version\nseal-use config paths\nseal-use config get\nseal-use config mode <stateful|stateless> [--corp <corpId>]\nseal-use service <start|stop|restart|status>\nseal-use http [--port 8787] [--host 127.0.0.1]\nseal-use serve [--port 8787]\nseal-use update\nseal-use tools list\nseal-use corps list [--corp <corpId>]\nseal-use corps current [--corp <corpId>]\nseal-use corps switch <corpId>\nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-use corps add-seal --json '{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]\nseal-use auth diagnose [--corp <corpId>]\nseal-use auth hose-link [--corp <corpId>] [--expire 7200]\nseal-use delegation list [--corp <corpId>]\nseal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]\nseal-use delegation revoke <tokenId> [--corp <corpId>]\nseal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]\nseal-use users reset-password <userId> [--corp <corpId>]\nseal-use users get <userId> [--corp <corpId>]\nseal-use users delete <userId> [--corp <corpId>]\nseal-use llm config [--corp <corpId>]\nseal-use llm providers [--corp <corpId>]\nseal-use permissions available [--corp <corpId>]\nseal-use permissions configs [--corp <corpId>]\nseal-use billing status [--corp <corpId>]\nseal-use billing plans [--corp <corpId>]\nseal-use billing features [--corp <corpId>]\nseal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]\nseal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]\nseal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]\nseal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]\nseal-use webhook delete <idOrName> --yes [--corp <corpId>]\nseal-use deploy hosecloud requirements [--corp <corpId>]\nseal-use deploy hosecloud list [--corp <corpId>]\nseal-use deploy hosecloud get <sign-key> [--corp <corpId>]\nseal-use deploy hosecloud status [--corp <corpId>]\nseal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]\nseal-use deploy hosecloud sync <sign-key> [--corp <corpId>]\nseal-use preference get [--corp <corpId>]\nseal-use preference decision update --json '{\"explicitApprove\":\"...\"}' [--corp <corpId>]\nseal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]\nseal-use preference thinking-depth policies list [--corp <corpId>]\nseal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]\nseal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]\nseal-use source config [--corp <corpId>]\nseal-use tool <toolName> [--corp <corpId>] [--json '{\"key\":\"value\"}']\nseal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]\nseal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]\nseal-use approval-runs count --corp <corpId> [--status APPROVED]\nseal-use approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]\nseal-use approval-runs get <recordId> --corp <corpId> [--fields metadata|document.fields,result.summary] [--output-file file.json]\nseal-use approval-runs attachments <recordId> --corp <corpId>\nseal-use approval-runs result <recordId> --corp <corpId> [--summary]\nseal-use approval-runs url --corp <corpId>\nseal-use approval-runLine truncated
`;var bX0="# Seal Use CLI Reference\n\nRun from any directory after installing the global CLI:\n\n```bash\nseal-use <command>\n```\n\nEnterprise config lookup:\n\n- If `SEAL_USE_ENTERPRISES_DIR` is set, only that directory is loaded.\n- Otherwise `./enterprises` and `~/.config/seal-use/enterprises` are merged.\n- User-level configs override same-ID local configs.\n\nEnterprise selection is stateless by default. Commands that access an enterprise require\n`--corp <corpId>` unless stateful mode is explicitly enabled:\n\n```bash\nseal-use config mode stateful --corp <corpId>\nseal-use corps switch <corpId>\nseal-use config mode stateless\n```\n\nThe global mode is stored in `~/.config/seal-use/config.json`; set `SEAL_USE_CONFIG_FILE` to\noverride that path. The legacy `current-corp` file is not read.\n\n## Stream & Exit Code Contract\n\n- **`stdout`**: Pure, deterministic JSON for machine/Agent parsing.\n- **`stderr`**: Diagnostics, probing logs, and **Next-Step Command Suggestions** (e.g. `👉 Next action: ...`).\n- **`Exit Code`**: `0` on success, non-zero (e.g. `1`) on failure to trigger Agent error self-remediation.\n\n## Top-Level Commands\n\n```bash\nseal-use version\nseal-use config paths\nseal-use config get\nseal-use config mode <stateful|stateless> [--corp <corpId>]\nseal-use config test-dir [<path>|--clear]\nseal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]\nseal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]\nseal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]\nseal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]\nseal-use service <start|stop|restart|status|logs> [--port 8787] [--host 127.0.0.1] [--lines 50]\nseal-use http [--port 8787] [--host 127.0.0.1]\nseal-use serve [--port 8787]\nseal-use update\nseal-use tools list\nseal-use corps list [--corp <corpId>]\nseal-use corps current [--corp <corpId>]\nseal-use corps switch <corpId>\nseal-use corps add-hose --json '{\"name\":\"企业名称\",\"domain\":\"https://app.ekuaibao.com\",\"appKey\":\"...\",\"appSecurity\":\"...\",\"proxyStaffBizId\":\"corpId:staffId\"}'\nseal-use corps add-seal --json '{\"sealUrl\":\"https://tenant.sealai.cc\",\"token\":\"seal-bearer-token\"}'\nseal-use corps add-link <https://.../web/thirdparty.html?...> [--name <customName>] [--overwrite]\nseal-use auth diagnose [--corp <corpId>]\nseal-use auth hose-link [--corp <corpId>] [--expire 7200]\nseal-use delegation list [--corp <corpId>]\nseal-use delegation create [--note <note>] [--from-link <url>] [--corp <corpId>]\nseal-use delegation revoke <tokenId> [--corp <corpId>]\nseal-use users create --name <name> --phone <phone> [--dept <deptId>] [--corp <corpId>]\nseal-use users reset-password <userId> [--corp <corpId>]\nseal-use users get <userId> [--corp <corpId>]\nseal-use users delete <userId> [--corp <corpId>]\nseal-use llm config [--corp <corpId>]\nseal-use llm providers [--corp <corpId>]\nseal-use permissions available [--corp <corpId>]\nseal-use permissions configs [--corp <corpId>]\nseal-use billing status [--corp <corpId>]\nseal-use billing plans [--corp <corpId>]\nseal-use billing features [--corp <corpId>]\nseal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]\nseal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]\nseal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]\nseal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]\nseal-use webhook delete <idOrName> --yes [--corp <corpId>]\nseal-use deploy hosecloud requirements [--corp <corpId>]\nseal-use deploy hosecloud list [--corp <corpId>]\nseal-use deploy hosecloud get [<sign-key>] [--corp <corpId>]\nseal-use deploy hosecloud status [--corp <corpId>]\nseal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]\nseal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]\nseal-use preference get [--corp <corpId>]\nseal-use preference decision update --json '{\"explicitApprove\":\"...\"}' [--corp <corpId>]\nseal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]\nseal-use preference thinking-depth policies list [--corp <corpId>]\nseal-use preference thinking-depth policies upsert --json '{...}' [--corp <corpId>]\nseal-use preference thinking-depth policies remove <policyId> [--corp <corpId>]\nseal-use source config [--corp <corpId>]\nseal-use tool <toolName> [--corp <corpId>] [--json '{\"key\":\"value\"}']\nseal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]\nseal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by soLine truncated
Use this workflow when a customer disputes an AI approval finding about an attachment, invoice, receipt, OCR result, or a UI-highlighted audit result.
@@ -728,7 +990,7 @@ Manual image check:
- The customer's objection that they were receipts rather than invoices was reasonable.
However, the final rejection also had an independent rule-37 reason: payment screenshots totaled 699.48 while reimbursement was 700.00.
`;var iy=`# Customer Feedback Rule Remediation
`;var nX0=`# Customer Feedback Rule Remediation
Use this low-freedom workflow when the user provides packaged customer feedback from WeChat, screenshots, rejection notifications, a document number, or expected business behavior and wants diagnosis or an approval-rule change.
@@ -892,7 +1154,7 @@ Return a compact report containing:
- New version number and version name, if published
- Verification result
- Whether a regression rerun was performed
`;var ty="# Enterprise Onboarding\n\nRead this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.\n\n## Start With Discovery\n\nRun this before asking for setup parameters (if `seal-use` is not installed, first run `curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash`):\n\n```bash\nseal-use version\nseal-use corps list\n```\n\n- If `seal-use` is not installed on the system, run the curl install script above to install it.\n- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.\n- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.\n- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”\n\nDo not open with a JSON template or a list of internal fields.\n\nAll command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.\n\n## Keep Two Concepts Separate\n\nClassify both the enterprise identity origin and how the current credential was acquired:\n\n| Enterprise identity origin | Credential material the user may have | Meaning |\n| --- | --- | --- |\n| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |\n| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |\n| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |\n| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |\n| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |\n\nCredential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.\n\n## Parameter Ownership\n\nAsk the user only for information that cannot be discovered safely:\n\n| Field | Owner and behavior |\n| --- | --- |\n| `appKey`, `appSecurity` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |\n| `domain` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |\n| Enterprise name and `corpId` | Discover from the credential response or Seal `whoami`. Do not ask the user to invent or locate them first. |\n| Administrator and `staffId` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |\n| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal `whoami`. |\n| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |\n\n## Route 1: Standard Hose Credentials\n\nThis is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:\n\n```bash\nseal-use corps add-hose --json '{\"appKey\":\"...\",\"appSecurity\":\"...\"}'\n```\n\nThe CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:\n\n```bash\nseal-use auth diagnose --corp <discovered-id>\n```\n\nDo not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.\n\n## Route 2: Incoming Assistance Link\n\nFirst distinguish the link by its host and purpose:\n\n- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.\n- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.\n- `seal-use auth hose-link` and `seal-use delegation create` generate Line truncated
`;var cX0="# Enterprise Onboarding\n\nRead this reference for first installation, zero configured enterprises, incoming credentials or assistance links, and browser-copied cURL. The goal is to identify the enterprise with the least user effort while keeping authentication material confidential.\n\n## Start With Discovery\n\nRun this before asking for setup parameters (if `seal-use` is not installed, first run `curl -fsSL https://git.ying-qing.cn/gitea/seal-use/raw/branch/main/scripts/install.sh | bash`):\n\n```bash\nseal-use version\nseal-use corps list\n```\n\n- If `seal-use` is not installed on the system, run the curl install script above to install it.\n- If the target enterprise is listed, match the user's human enterprise name to its returned `id` and use that value as `--corp` on every command. Do not ask the user for `corpId`.\n- If multiple configured enterprises plausibly match, show their human names and let the user choose. Keep their IDs as implementation details.\n- If none are configured, ask one plain-language question: “你现在手上有哪一种接入材料:合思开放平台 appKey/appSecurity、合思授权/协助链接、Seal 协助链接,还是从已登录的合思或 Seal 网页复制的 cURL?”\n\nDo not open with a JSON template or a list of internal fields.\n\nAll command examples in this reference are for the Agent to run. Do not hand them to the user as setup instructions. Communicate with the user in natural language and translate their answer into CLI/MCP parameters yourself.\n\n## Keep Two Concepts Separate\n\nClassify both the enterprise identity origin and how the current credential was acquired:\n\n| Enterprise identity origin | Credential material the user may have | Meaning |\n| --- | --- | --- |\n| Hose/合思-sourced Seal tenant | Hose `appKey` + `appSecurity` | Stable, refreshable standard integration |\n| Hose/合思-sourced Seal tenant | Hose authorization/assistance link | Temporary Hose authorization that can lead into the Seal SSO session |\n| Hose/合思-sourced Seal tenant | cURL copied from an authenticated Hose or Seal page | Snapshot of a signed-in browser session; it may expire |\n| Seal-native tenant | Seal assistance/delegation link | Temporary delegated access to a Seal tenant |\n| Seal-native tenant | cURL copied from an authenticated Seal page | Snapshot containing the Seal host and session authentication |\n\nCredential shape alone does not define identity origin. In particular, a Hose-sourced user eventually receives a Seal Bearer session after SSO. When `whoami` returns provider metadata, preserve it and use it to describe the tenant accurately.\n\n## Parameter Ownership\n\nAsk the user only for information that cannot be discovered safely:\n\n| Field | Owner and behavior |\n| --- | --- |\n| `appKey`, `appSecurity` | User supplies these for standard Hose OpenAPI onboarding. Explain that they come from the enterprise's 合思开放平台 application credentials. Treat both as secrets. |\n| `domain` | Probe the standard Hose SaaS domains automatically. Ask only when probing fails and the enterprise uses a private or dedicated deployment. |\n| Enterprise name and `corpId` | Discover from the credential response or Seal `whoami`. Do not ask the user to invent or locate them first. |\n| Administrator and `staffId` | Discover administrator candidates. If more than one is eligible, present name and masked phone for the user to choose; pass the selected ID internally. |\n| Seal URL, tenant ID, tenant slug | Discover from the assistance link, cURL host, and Seal `whoami`. |\n| Bearer token, cookies, signed query tokens | Extract only from user-supplied authentication material. Never print them back or include them in summaries. |\n\n## Route 1: Standard Hose Credentials\n\nThis is the preferred durable route for a Hose-sourced tenant. Read `hose-enterprise-init.md`, then use:\n\n```bash\nseal-use corps add-hose --json '{\"appKey\":\"...\",\"appSecurity\":\"...\"}'\n```\n\nThe CLI probes the standard domains, discovers the corporation, and discovers administrator candidates. If it returns multiple candidates, show only useful identifying information and ask which person should be used; retry with `staffName`, `staffPhone`, or the selected `staffId` internally. After creation, run:\n\n```bash\nseal-use auth diagnose --corp <discovered-id>\n```\n\nDo not ask for `domain`, `corpId`, or `proxyStaffBizId` up front. For a dedicated/private Hose deployment, add `domain` only after standard probing reports that it cannot find the enterprise.\n\n## Route 2: Incoming Assistance Link\n\nFirst distinguish the link by its host and purpose:\n\n- A Hose authorization/provisional link opens a Hose session and may continue through Seal SSO. It is not a Seal delegation link.\n- A Seal assistance/delegation link grants temporary delegated access on a Seal tenant. It is not a Hose OpenAPI credential.\n- `seal-use auth hose-link` and `seal-use delegation create` generat Line truncated
Use this reference for Hose/合思 enterprise configuration and user-facing Hose authorization links.
@@ -957,7 +1219,7 @@ Important:
- \`seal-use auth diagnose\` proves this stage works but redacts the token, so it is not enough when the user needs the actual clickable Hose link.
- **Formatting Requirement**: When returning a Hose authorization link to the user, ALWAYS provide BOTH a code block (\` \`\`\`text ... \`\`\` \`) for easy copying without accidental default browser redirection, AND a clickable hyperlink.
- If the CLI later provides a dedicated command for this, prefer that command.
`;var oy=`# Hose Enterprise Initialization & Automated Discovery
`;var mX0=`# Hose Enterprise Initialization & Automated Discovery
Use this reference for automated Hose/合思 enterprise onboarding, multi-domain probing (including dedicated private cloud domains like 美年大健康), OpenAPI role and staff discovery, and non-TUI safe administrator selection.
@@ -1063,12 +1325,12 @@ seal-use corps hose-staffs --json '{
}'
\`\`\`
* 直接使用指定 ID 完成接入并进行连通性验证。
`;var ly={"SKILL.md":RL,"agents/openai.yaml":hL,"references/rule-lightweight.md":mL,"references/approval-bad-cases.md":xL,"references/cli.md":aL,"references/approval-run-lightweight.md":sL,"references/approval-attachment-trace.md":ny,"references/customer-feedback-rule-remediation.md":iy,"references/enterprise-onboarding.md":ty,"references/hose-enterprise-auth.md":ry,"references/hose-enterprise-init.md":oy};function vy(){return ly["SKILL.md"]||""}function zu(){return C4(ey(),".agents","skills","seal-use")}function $y(){return C4(ey(),".agents","skills","seal-home")}function Iy(){let n=$y();if(z4(n))try{return XK(n,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function R4(n=zu()){Iy(),uy(n,{recursive:!0});let i=[];for(let[r,o]of Object.entries(ly)){let t=C4(n,r);uy(YK(t),{recursive:!0}),HK(t,o,"utf8"),i.push(r)}return{targetDir:n,files:i}}function h4(){let n=$y(),i=zu(),r=z4(n),o=z4(i);if(r||o)return Iy(),R4(i),{synced:!0,targetDir:i};return{synced:!1}}function by(n,i,r){if(n==="dump"||n==="cat"||n==="show"){process.stdout.write(`${vy()}
`);return}if(n==="install"||n==="init"||n==="sync"){let o=_(r.options.local)||_(r.options.workspace),t=D(r.options.dir)??D(r.options.target)??i,u=t?t:o?w$(process.cwd(),".agents","skills","seal-use"):zu(),e=R4(u);B({installed:!0,targetDir:e.targetDir,fileCount:e.files.length,files:e.files});return}if(n==="status"||n==="get"||!n){let o=zu(),t=w$(process.cwd(),".agents","skills","seal-use");B({global:{dir:o,installed:gy(w$(o,"SKILL.md"))},local:{dir:t,installed:gy(w$(t,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${n}. Run 'seal-use help' for available commands.`)}async function wy(n,i){if(n==="config"){B(await ar(i));return}throw Error(`Unknown source command: ${n??""}. Run 'seal-use help' for available commands.`)}async function fy(n,i,r,o){if(!n)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await X(n,i,r,ri(o.json),J(o.options))}function cy(){B(Tu.map((n)=>({name:n.name,description:n.description})))}import{chmodSync as pK,mkdirSync as QK,renameSync as m4,rmSync as PK,unlinkSync as Oy,writeFileSync as Uy}from"node:fs";import{dirname as FK,join as Dy}from"node:path";import{spawnSync as Zt}from"node:child_process";function f$(n=process.execPath,i=import.meta.url){if(i.includes("/$bunfs/")||i.includes("\\$bunfs\\"))return!0;let r=n.toLowerCase().replace(/\\/g,"/");return!r.endsWith("/bun")&&!r.endsWith("/bun.exe")&&!r.endsWith("/node")&&!r.endsWith("/node.exe")}var dy="yunyingk/seal-use",Ru="yunyingk/seal-home";var KK="SEAL_USE_GITHUB_REPO",BK="SEAL_HOME_GITHUB_REPO";async function ky(n,i={}){let r={appRoot:n.appRoot,entryFile:n.entryFile,stateDir:M4,version:x,launcher:n.launcher},o=i.repo||process.env[KK]?.trim()||process.env[BK]?.trim()||dy,t=i.targetVersion?.trim(),u=t&&t.toLowerCase()!=="latest"?t:void 0;if(u){let W=u.replace(/^v/,""),N=Ny(W,x);if(N<0){B({updated:!1,currentVersion:x,targetVersion:W,mode:f$()?"binary":"source",message:`Cannot downgrade seal-use from v${x} to older version v${W}. Updates must be forward-only.`});return}if(N===0&&!i.force){B({updated:!1,currentVersion:x,targetVersion:W,mode:f$()?"binary":"source",message:`seal-use is already at version v${x}. Use --force to reinstall.`});return}}if(i.changelogOnly){let W=await x4(o,i.limit??10);B({currentVersion:x,totalQueried:W.length,releases:W.map((N)=>({version:N.version,tagName:N.tagName,publishedAt:N.publishedAt,author:N.author,releaseNotes:N.notes,releaseUrl:N.htmlUrl,isCurrent:N.version===x,isNewer:Cu(N.version,x)}))});return}if(!f$()){if(i.checkOnly){let N=await x4(o,30),M=N[0],q=M?.version??x,An=N.find((nn)=>nn.version===x),Wn=Cu(q,x),jn=N.filter((nn)=>Cu(nn.version,x));B({updated:!1,updateAvailable:Wn,currentVersion:x,currentVersionPublishedAt:An?.publishedAt,latestVersion:q,latestVersionPublishedAt:M?.publishedAt,behindCount:jn.length,pendingReleases:jn.map((nn)=>({version:nn.version,tagName:nn.tagName,publishedAt:nn.publishedAt,author:nn.author,releaseNotes:nn.notes,releaseUrl:nn.htmlUrl})),releaseNotes:M?.notes??"",releaseUrl:M?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let W=sr(r).running;if(W)await _t("stop",r);try{Ay("git",["-C",n.appRoot,"pull","--ff-only"])}catch(N){console.error(`git pull skipped: ${N instanceof Error?N.message:String(N)}`)}if(Ay("bun",["install"],{cwd:n.appRoot}),W)await _t("start",r);B({updated:!0,serviceRestarted:W,version:x,mode:"source"});return}let e=EK(),l=TK(),$=await x4(o,30),I=u?$.find((W)=>W.version===u||W.tagName===u||W.tagName===`v${u}`)??await Sy(o,u):$[0]??await Sy(o);if(!I){B({updated:!1,currentVersion:x,mode:"binary",message:`Failed to query releases from repository '${o}'`});return}let g=I.version,b=$.find((W)=>W.version===x),w=Cu(g,x),f=w||Boolean(i.force),c=$.filter((W)=>Cu(W.version,x));if(i.checkOnly){B({updated:!1,updateAvailable:w,currentVersion:x,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,behindCount:c.length,pendingReleases:c.map((W)=>({version:W.version,tagName:W.tagName,publishedAt:W.publishedAt,author:W.author,releaseNotes:W.notes,releaseUrl:W.htmlUrl})),releaseNotes:I.notes,releaseUrl:I.htmlUrl,mode:"binary"});return}if(!f){B({updated:!1,currentVersion:x,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:I.publishedAt,mode:"binary",message:`seal-use is already up to date (v${x})`});return}let S=VK(I.assets,e,l);if(!S)throw Error(`No compatible binary found for ${e}-${l} in release v${g}. Available assets: ${I.assets.map((W)=>W.name).join(", ")}`);let d=sr(r).running;if(d)await _t("stop",r);let k=process.execPath,P=FK(k),Q=Dy(P,`.tmp-update-${Date.now()}`);QK(Q,{recursive:!0});try{let W=Dy(Q,S.name);await qK(S.downloadUrl,W,I.tagName,S.name);let N=W;if(S.name.endsWith(".tar.gz")||S.name.endsWith(".tgz"))N=_K(W,Q,e);else if(S.name.endsWith(".zip"))N=ZK(W,Q,e);if(pK(N,493),process.platform==="darwin")try{Zt("/usr/bin/codesign",["--remove-signature",N],{stdio:"ignore"}),Zt("/usr/ Line truncated
`)}catch{}}async function qK(n,i,r,o){let t=a4(),u=[],e=r?r.startsWith("v")?r:`v${r}`:void 0,l=o||n.split("/").pop()||"";if(t!=="github"){if(e&&l)u.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${e}/${l}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${e}/${l}`);if(n.startsWith("https://git.ying-qing.cn"))u.push(n)}if(t!=="gitea")if(e&&l){let S=`https://github.com/${dy}/releases/download/${e}/${l}`;if(!process.env.CI)u.push(`https://ghfast.top/${S}`,`https://gh.ddlc.top/${S}`);u.push(S)}else if(n.includes("github.com")){if(!process.env.CI)u.push(`https://ghfast.top/${n}`,`https://gh.ddlc.top/${n}`);u.push(n)}else u.push(n);let $=Array.from(new Set(u)),I,g=6000,b=6000,w=307200,f=1e4,c=180000;for(let S=0;S<$.length;S++){let d=$[S],k=new AbortController,P="",Q=(q)=>{P=q;try{k.abort()}catch{}},W=setTimeout(()=>{Q("Connection timed out (no response headers within 6s)")},g),N,M;try{c$(`==> [${S+1}/${$.length}] Downloading via: ${d}`);let q=await fetch(d,{signal:k.signal});if(W)clearTimeout(W),W=void 0;if(!q.ok)throw Error(`HTTP ${q.status} ${q.statusText}`);N=setTimeout(()=>{Q("Overall download time exceeded 3 minutes")},c);let An=Number(q.headers.get("content-length"))||0,Wn=q.body?.getReader();if(!Wn){let Ni=Buffer.from(await q.arrayBuffer());if(Ni.length<1000)throw Error(`Downloaded content is suspiciously small (${Ni.length} bytes)`);Uy(i,Ni),c$(`✓ Download succeeded (${(Ni.length/1024/1024).toFixed(1)} MB)`);return}let jn=[],nn=0,no=0;M=setTimeout(()=>{if(nn<w){let Ni=(nn/1024).toFixed(1);Q(`Initial transfer too slow (${Ni} KB < 300 KB in 6s), switching mirror...`)}},b);while(!0){let Ni=Wn.read(),U$,Xy=new Promise((S$,A$)=>{U$=setTimeout(()=>{A$(Error("Data transfer stalled (no chunk received for 10s)"))},f)}),i0;try{i0=await Promise.race([Ni,Xy])}finally{if(U$)clearTimeout(U$)}let{done:Hy,value:D$}=i0;if(Hy)break;if(D$){if(jn.push(D$),nn+=D$.length,M&&nn>=w)clearTimeout(M),M=void 0;let S$=Date.now();if(S$-no>200){no=S$;let A$=An?Math.round(nn/An*100):0,Yy=(nn/1048576).toFixed(1),py=An?(An/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${A$}% (${Yy} / ${py} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let Ot=Buffer.concat(jn);if(Ot.length<1000)throw Error(`Downloaded content is suspiciously small (${Ot.length} bytes)`);Uy(i,Ot),c$(`✓ Download completed successfully (${(Ot.length/1024/1024).toFixed(1)} MB)`);return}catch(q){if(W)clearTimeout(W);if(M)clearTimeout(M);if(N)clearTimeout(N);let An=P||(q instanceof Error?q.message:String(q));I=Error(An),c$(`
↳ Mirror failed: ${I.message}`)}finally{if(W)clearTimeout(W);if(M)clearTimeout(M);if(N)clearTimeout(N)}}throw Error(`Failed to download asset from all mirrors: ${I?.message}`)}function _K(n,i,r){let o=Zt("tar",["-xzf",n,"-C",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract tar archive: ${o.stderr.toString()}`);Oy(n);let t=r==="windows"?"seal-use.exe":"seal-use",u=Zt("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),e=u.find((l)=>l.endsWith(`/${t}`)||l.endsWith(t));if(e)return e;return u[0]||n}function ZK(n,i,r){let o=Zt("unzip",["-q","-o",n,"-d",i],{stdio:"pipe"});if(o.status!==0)throw Error(`Failed to extract zip archive: ${o.stderr.toString()}`);Oy(n);let t=r==="windows"?"seal-use.exe":"seal-use",u=Zt("find",[i,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),e=u.find((l)=>l.endsWith(`/${t}`)||l.endsWith(t));if(e)return e;return u[0]||n}function Ny(n,i){let r=n.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0),o=i.replace(/^v/,"").split(".").map((t)=>Number.parseInt(t,10)||0);for(let t=0;t<Math.max(r.length,o.length);t++){let u=r[t]??0,e=o[t]??0;if(u>e)return 1;if(u<e)return-1}return 0}function Cu(n,i){return Ny(n,i)>0}function Ay(n,i,r={}){let o=Zt(n,i,{cwd:r.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(o.stdout)console.error(o.stdout.trimEnd());if(o.stderr)console.error(o.stderr.trimEnd());if(o.status!==0)throw Error(`${n} ${i.join(" ")} failed with status ${o.status}`)}async function Ly(n,i,r,o,t){if(n==="create"){let u=D(t.options.name)??i,e=D(t.options.phone);if(!u||!e)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let l=D(t.options.dept)??D(t.options.departmentId);await X("seal_user_create",r,o,{name:u,phone:e,departmentIds:l?[l]:void 0},J(t.options));return}if(n==="reset-password"){let u=i??D(t.options.userId);if(!u)throw Error("Usage: seal-use users reset-password <userId>");await X("seal_user_reset_password",r,o,{userId:u},J(t.options));return}if(n==="search"||n==="list"){let u=i??D(t.options.keyword)??D(t.options.query)??"";await X("seal_user_search",r,o,{keyword:u},J(t.options));return}if(n==="get"){let u=i??D(t.options.userId);if(!u)throw Error("Usage: seal-use users get <userId>");await X("seal_user_get",r,o,{userId:u},J(t.options));return}if(n==="delete"){let u=i??D(t.options.userId);if(!u)throw Error("Usage: seal-use users delete <userId>");await X("seal_user_delete",r,o,{userId:u},J(t.options));return}if(n==="activate"){let u=i??D(t.options.userId);if(!u)throw Error("Usage: seal-use users activate <userId>");await X("seal_user_activate",r,o,{userId:u},J(t.options));return}if(n==="delegation"||n==="impersonate"){let u=i??D(t.options.userId)??D(t.options.phone);if(!u)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let e=D(t.options.note);await X("seal_user_delegation_create",r,o,{userIdOrPhone:u,note:e},J(t.options));return}throw Error(`Unknown users command: ${n??""}. Run 'seal-use help' for available commands.`)}async function yy(n,i,r,o,t){if(n==="list"){await X("seal_webhook_list",r,o,{query:D(t.options.query)??D(t.options.keyword),includeSecret:K4(t.options)},J(t.options));return}if(n==="get"||n==="find"){let u=i??D(t.options.selector)??D(t.options.id);if(!u)throw Error("Usage: seal-use webhook get <idOrName> [--show-secret]");await X("seal_webhook_get",r,o,{selector:u,includeSecret:K4(t.options)},J(t.options));return}if(n==="add"||n==="create"){let u=D(t.options.name)??i,e=D(t.options.resultUrl)??D(t.options["result-url"])??D(t.options.outgoingResultWebhook)??D(t.options["outgoing-result-webhook"]);if(!u||!e)throw Error("Usage: seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic]");let l=F4(t.options);await X("seal_webhook_add",r,o,{name:u,mode:P4(D(t.options.mode)),outgoingResultWebhook:e,autoApprovalRate:l,secret:D(t.options.secret)},J(t.options));return}if(n==="update"){let u=i??D(t.options.selector)??D(t.options.id);if(!u)throw Error("Usage: seal-use webhook update <idOrName> [options]");let e=D(t.options.secret),l=_(t.options.rotateSecret)??_(t.options["rotate-secret"]);if(e!==void 0&&l)throw Error("Use either --secret or --rotate-secret, not both");let $=D(t.options.name),I=P4(D(t.options.mode)),g=D(t.options.resultUrl)??D(t.options["result-url"])??D(t.options.outgoingResultWebhook)??D(t.options["outgoing-result-webhook"]),b=F4(t.options);if($===void 0&&I===void 0&&g===void 0&&b===void 0&&e===void 0&&!l)throw Error("Webhook update requires at least one field option");await X("seal_webhook_update",r,o,{selector:u,name:$,mode:I,outgoingResultWebhook:g,autoApprovalRate:b,secret:e,rotateSecret:l},J(t.options));return}if(n==="delete"){let u=i??D(t.options.selector)??D(t.options.id);if(!u)throw Error("Usage: seal-use webhook delete <idOrName> --yes");if(_(t.options.yes)!==!0)throw Error("Refusing to delete Webhook integration without --yes");await X("seal_webhook_delete",r,o,{selector:u,confirm:!0},J(t.options));return}throw Error(`Unknown webhook command: ${n??""}. Run 'seal-use help' for available commands.`)}var Gy=s4(s4(s4(zK(import.meta.url)))),CK=new Set(["config","service","http","serve","update","tools","corps","tool","source","auth","delegation","users","llm","permissions","billing","webhook","webhooks","context","rules","approval-runs","simulation","deploy","preference","preferences","mcp","server","mcp-config","skill","openapi","probe","changelog"]),Wy=Promise.resolve();function Mu(n,i={}){let r=Wy.then(()=>RK(n,i));return Wy=r.then(()=>{return},()=>{return}),r}async function RK(n,i){let r=[],o=[],t=console.log,u=console.error,e={appRoot:i.appRoot??Gy,entryFile:i.entryFile??MK(i.appRoot??Gy,"src","cli.ts"),launcher:i.launcher};console.log=(...l)=>{r.push(B4(l))},c Line truncated
`;var rX0={"SKILL.md":xX0,"agents/openai.yaml":kX0,"references/rule-lightweight.md":uX0,"references/approval-bad-cases.md":fX0,"references/cli.md":bX0,"references/approval-run-lightweight.md":iX0,"references/approval-attachment-trace.md":pX0,"references/customer-feedback-rule-remediation.md":nX0,"references/enterprise-onboarding.md":cX0,"references/hose-enterprise-auth.md":dX0,"references/hose-enterprise-init.md":mX0};function tX0(){return rX0["SKILL.md"]||""}function VG(){return Wx(oX0(),".agents","skills","seal-use")}function aX0(){return Wx(oX0(),".agents","skills","seal-home")}function sX0(){let $=aX0();if(Hx($))try{return wG1($,{recursive:!0,force:!0}),!0}catch{return!1}return!1}function Vx($=VG()){sX0(),lX0($,{recursive:!0});let I=[];for(let[U,Y]of Object.entries(rX0)){let J=Wx($,U);lX0(OG1(J),{recursive:!0}),DG1(J,Y,"utf8"),I.push(U)}return{targetDir:$,files:I}}function Zx(){let $=aX0(),I=VG(),U=Hx($),Y=Hx(I);if(U||Y)return sX0(),Vx(I),{synced:!0,targetDir:I};return{synced:!1}}function $L0($,I,U){if($==="dump"||$==="cat"||$==="show"){process.stdout.write(`${tX0()}
`);return}if($==="install"||$==="init"||$==="sync"){let Y=_0(U.options.local)||_0(U.options.workspace),J=h(U.options.dir)??h(U.options.target)??I,Q=J?J:Y?LO(process.cwd(),".agents","skills","seal-use"):VG(),K=Vx(Q);E0({installed:!0,targetDir:K.targetDir,fileCount:K.files.length,files:K.files});return}if($==="status"||$==="get"||!$){let Y=VG(),J=LO(process.cwd(),".agents","skills","seal-use");E0({global:{dir:Y,installed:eX0(LO(Y,"SKILL.md"))},local:{dir:J,installed:eX0(LO(J,"SKILL.md"))}});return}throw Error(`Unknown skill command: ${$}. Run 'seal-use help' for available commands.`)}async function IL0($,I){if($==="config"){E0(await zJ(I));return}throw Error(`Unknown source command: ${$??""}. Run 'seal-use help' for available commands.`)}async function UL0($,I,U,Y){if(!$)throw Error("Usage: seal-use tool <toolName> [--json '{...}']");await F0($,I,U,t6(Y.json),O0(Y.options))}function YL0(){E0(YG.map(($)=>({name:$.name,description:$.description})))}import{chmodSync as NG1,mkdirSync as FG1,renameSync as Xx,rmSync as MG1,unlinkSync as GL0,writeFileSync as JL0}from"node:fs";import{dirname as zG1,join as QL0}from"node:path";import{spawnSync as qI}from"node:child_process";function wO($=process.execPath,I=import.meta.url){if(I.includes("/$bunfs/")||I.includes("\\$bunfs\\"))return!0;let U=$.toLowerCase().replace(/\\/g,"/");return!U.endsWith("/bun")&&!U.endsWith("/bun.exe")&&!U.endsWith("/node")&&!U.endsWith("/node.exe")}var HL0="yunyingk/seal-use",XG="yunyingk/seal-home";var AG1="SEAL_USE_GITHUB_REPO",PG1="SEAL_HOME_GITHUB_REPO";async function WL0($,I={}){let U={appRoot:$.appRoot,entryFile:$.entryFile,stateDir:qx,version:e0,launcher:$.launcher},Y=I.repo||process.env[AG1]?.trim()||process.env[PG1]?.trim()||HL0,J=I.targetVersion?.trim(),Q=J&&J.toLowerCase()!=="latest"?J:void 0;if(Q){let T=Q.replace(/^v/,""),v=VL0(T,e0);if(v<0){E0({updated:!1,currentVersion:e0,targetVersion:T,mode:wO()?"binary":"source",message:`Cannot downgrade seal-use from v${e0} to older version v${T}. Updates must be forward-only.`});return}if(v===0&&!I.force){E0({updated:!1,currentVersion:e0,targetVersion:T,mode:wO()?"binary":"source",message:`seal-use is already at version v${e0}. Use --force to reinstall.`});return}}if(I.changelogOnly){let T=await Lx(Y,I.limit??10);E0({currentVersion:e0,totalQueried:T.length,releases:T.map((v)=>({version:v.version,tagName:v.tagName,publishedAt:v.publishedAt,author:v.author,releaseNotes:v.notes,releaseUrl:v.htmlUrl,isCurrent:v.version===e0,isNewer:ZG(v.version,e0)}))});return}if(!wO()){if(I.checkOnly){let v=await Lx(Y,30),u=v[0],g=u?.version??e0,b=v.find((p)=>p.version===e0),C=ZG(g,e0),n=v.filter((p)=>ZG(p.version,e0));E0({updated:!1,updateAvailable:C,currentVersion:e0,currentVersionPublishedAt:b?.publishedAt,latestVersion:g,latestVersionPublishedAt:u?.publishedAt,behindCount:n.length,pendingReleases:n.map((p)=>({version:p.version,tagName:p.tagName,publishedAt:p.publishedAt,author:p.author,releaseNotes:p.notes,releaseUrl:p.htmlUrl})),releaseNotes:u?.notes??"",releaseUrl:u?.htmlUrl??"",mode:"source",message:"Running in source development mode. Run 'seal-use update' to git pull & bun install."});return}let T=PJ(U).running;if(T)await KI("stop",U);try{qL0("git",["-C",$.appRoot,"pull","--ff-only"])}catch(v){console.error(`git pull skipped: ${v instanceof Error?v.message:String(v)}`)}if(qL0("bun",["install"],{cwd:$.appRoot}),T)await KI("start",U);E0({updated:!0,serviceRestarted:T,version:e0,mode:"source"});return}let K=TG1(),q=EG1(),G=await Lx(Y,30),H=Q?G.find((T)=>T.version===Q||T.tagName===Q||T.tagName===`v${Q}`)??await KL0(Y,Q):G[0]??await KL0(Y);if(!H){E0({updated:!1,currentVersion:e0,mode:"binary",message:`Failed to query releases from repository '${Y}'`});return}let W=H.version,V=G.find((T)=>T.version===e0),X=ZG(W,e0),Z=X||Boolean(I.force),w=G.filter((T)=>ZG(T.version,e0));if(I.checkOnly){E0({updated:!1,updateAvailable:X,currentVersion:e0,currentVersionPublishedAt:V?.publishedAt,latestVersion:W,latestVersionPublishedAt:H.publishedAt,behindCount:w.length,pendingReleases:w.map((T)=>({version:T.version,tagName:T.tagName,publishedAt:T.publishedAt,author:T.author,releaseNotes:T.notes,releaseUrl:T.htmlUrl})),releaseNotes:H.notes,releaseUrl:H.htmlUrl,mode:"binary"});return}if(!Z){E0({updated:!1,currentVersion:e0,currentVersionPublishedAt:V?.publishedAt,latestVersion:W,latestVersionPublishedAt:H.publishedAt,mode:"binary",message:`seal-use is already up to date (v${e0})`});return}let D=BG1(H.assets,K,q);if(!D)throw Error(`No compatible binary found for ${K}-${q} in release v${W}. Available assets: ${H.assets.map((T)=>T.name).join(", ")}`);let O=PJ(U).running;if(O)await KI("stop",U);let F=process.execPath,E=zG1(F),A=QL0(E,`.tmp-update-${Date.now()}`);FG1(A,{recursive:!0});try{let T=QL0(A,D.name);await RG1(D.downloadUrl,T,H.tagName,D.name);let v=T;if(D.name.endsWith(".tar.gz")||D.name.endsWith(".tgz"))v=vG1(T,A,K);else if(D.name.endsWith(".zip"))v=CG1(T,A,K);if(NG1(v,493),process.platform==="darwin")try{qI("/usr/bin/codesig Line truncated
`)}catch{}}async function RG1($,I,U,Y){let J=wx(),Q=[],K=U?U.startsWith("v")?U:`v${U}`:void 0,q=Y||$.split("/").pop()||"";if(J!=="github"){if(K&&q)Q.push(`https://git.ying-qing.cn/gitea/seal-use/releases/download/${K}/${q}`,`https://git.ying-qing.cn/gitea/seal-home/releases/download/${K}/${q}`);if($.startsWith("https://git.ying-qing.cn"))Q.push($)}if(J!=="gitea")if(K&&q){let D=`https://github.com/${HL0}/releases/download/${K}/${q}`;if(!process.env.CI)Q.push(`https://ghfast.top/${D}`,`https://gh.ddlc.top/${D}`);Q.push(D)}else if($.includes("github.com")){if(!process.env.CI)Q.push(`https://ghfast.top/${$}`,`https://gh.ddlc.top/${$}`);Q.push($)}else Q.push($);let G=Array.from(new Set(Q)),H,W=6000,V=6000,X=307200,Z=1e4,w=180000;for(let D=0;D<G.length;D++){let O=G[D],F=new AbortController,E="",A=(g)=>{E=g;try{F.abort()}catch{}},T=setTimeout(()=>{A("Connection timed out (no response headers within 6s)")},W),v,u;try{DO(`==> [${D+1}/${G.length}] Downloading via: ${O}`);let g=await fetch(O,{signal:F.signal});if(T)clearTimeout(T),T=void 0;if(!g.ok)throw Error(`HTTP ${g.status} ${g.statusText}`);v=setTimeout(()=>{A("Overall download time exceeded 3 minutes")},w);let b=Number(g.headers.get("content-length"))||0,C=g.body?.getReader();if(!C){let i=Buffer.from(await g.arrayBuffer());if(i.length<1000)throw Error(`Downloaded content is suspiciously small (${i.length} bytes)`);JL0(I,i),DO(`✓ Download succeeded (${(i.length/1024/1024).toFixed(1)} MB)`);return}let n=[],p=0,S=0;u=setTimeout(()=>{if(p<X){let i=(p/1024).toFixed(1);A(`Initial transfer too slow (${i} KB < 300 KB in 6s), switching mirror...`)}},V);while(!0){let i=C.read(),Y0,B=new Promise((K0,W0)=>{Y0=setTimeout(()=>{W0(Error("Data transfer stalled (no chunk received for 10s)"))},Z)}),k;try{k=await Promise.race([i,B])}finally{if(Y0)clearTimeout(Y0)}let{done:d,value:t}=k;if(d)break;if(t){if(n.push(t),p+=t.length,u&&p>=X)clearTimeout(u),u=void 0;let K0=Date.now();if(K0-S>200){S=K0;let W0=b?Math.round(p/b*100):0,z0=(p/1048576).toFixed(1),B0=b?(b/1048576).toFixed(1):"?";try{process.stderr.write(`\r ↳ Progress: ${W0}% (${z0} / ${B0} MB)...`)}catch{}}}}try{process.stderr.write(`
`)}catch{}let f=Buffer.concat(n);if(f.length<1000)throw Error(`Downloaded content is suspiciously small (${f.length} bytes)`);JL0(I,f),DO(`✓ Download completed successfully (${(f.length/1024/1024).toFixed(1)} MB)`);return}catch(g){if(T)clearTimeout(T);if(u)clearTimeout(u);if(v)clearTimeout(v);let b=E||(g instanceof Error?g.message:String(g));H=Error(b),DO(`
↳ Mirror failed: ${H.message}`)}finally{if(T)clearTimeout(T);if(u)clearTimeout(u);if(v)clearTimeout(v)}}throw Error(`Failed to download asset from all mirrors: ${H?.message}`)}function vG1($,I,U){let Y=qI("tar",["-xzf",$,"-C",I],{stdio:"pipe"});if(Y.status!==0)throw Error(`Failed to extract tar archive: ${Y.stderr.toString()}`);GL0($);let J=U==="windows"?"seal-use.exe":"seal-use",Q=qI("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),K=Q.find((q)=>q.endsWith(`/${J}`)||q.endsWith(J));if(K)return K;return Q[0]||$}function CG1($,I,U){let Y=qI("unzip",["-q","-o",$,"-d",I],{stdio:"pipe"});if(Y.status!==0)throw Error(`Failed to extract zip archive: ${Y.stderr.toString()}`);GL0($);let J=U==="windows"?"seal-use.exe":"seal-use",Q=qI("find",[I,"-type","f"],{encoding:"utf8"}).stdout.trim().split(`
`).filter(Boolean),K=Q.find((q)=>q.endsWith(`/${J}`)||q.endsWith(J));if(K)return K;return Q[0]||$}function VL0($,I){let U=$.replace(/^v/,"").split(".").map((J)=>Number.parseInt(J,10)||0),Y=I.replace(/^v/,"").split(".").map((J)=>Number.parseInt(J,10)||0);for(let J=0;J<Math.max(U.length,Y.length);J++){let Q=U[J]??0,K=Y[J]??0;if(Q>K)return 1;if(Q<K)return-1}return 0}function ZG($,I){return VL0($,I)>0}function qL0($,I,U={}){let Y=qI($,I,{cwd:U.cwd,encoding:"utf8",stdio:["ignore","pipe","pipe"]});if(Y.stdout)console.error(Y.stdout.trimEnd());if(Y.stderr)console.error(Y.stderr.trimEnd());if(Y.status!==0)throw Error(`${$} ${I.join(" ")} failed with status ${Y.status}`)}async function ZL0($,I,U,Y,J){if($==="create"){let Q=h(J.options.name)??I,K=h(J.options.phone);if(!Q||!K)throw Error("Usage: seal-use users create --name <name> --phone <phone> [--dept <deptId>]");let q=h(J.options.dept)??h(J.options.departmentId);await F0("seal_user_create",U,Y,{name:Q,phone:K,departmentIds:q?[q]:void 0},O0(J.options));return}if($==="reset-password"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users reset-password <userId>");await F0("seal_user_reset_password",U,Y,{userId:Q},O0(J.options));return}if($==="search"||$==="list"){let Q=I??h(J.options.keyword)??h(J.options.query)??"";await F0("seal_user_search",U,Y,{keyword:Q},O0(J.options));return}if($==="get"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users get <userId>");await F0("seal_user_get",U,Y,{userId:Q},O0(J.options));return}if($==="delete"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users delete <userId>");await F0("seal_user_delete",U,Y,{userId:Q},O0(J.options));return}if($==="activate"){let Q=I??h(J.options.userId);if(!Q)throw Error("Usage: seal-use users activate <userId>");await F0("seal_user_activate",U,Y,{userId:Q},O0(J.options));return}if($==="delegation"||$==="impersonate"){let Q=I??h(J.options.userId)??h(J.options.phone);if(!Q)throw Error("Usage: seal-use users delegation <userIdOrPhone> [--note <note>]");let K=h(J.options.note);await F0("seal_user_delegation_create",U,Y,{userIdOrPhone:Q,note:K},O0(J.options));return}throw Error(`Unknown users command: ${$??""}. Run 'seal-use help' for available commands.`)}import{existsSync as XL0}from"node:fs";async function LL0($){if(!XL0($))throw Error(`File not found: ${$}`);let I=II($);console.log(JSON.stringify(await $I(I.fileBuffer,I.fileName),null,2))}async function wL0($,I,U,Y,J){if($==="ready"||$==="status"){let Q=I??h(J.options.file)??h(J.options.input),K=await rD(U,Y,{filePath:Q});if(console.error(`[webhook-ready] 企业环境: ${K.corp.name} (${K.corp.id}) [${K.stateMode}]`),K.corp.tenant?.name)console.error(`[webhook-ready] 租户信息: ${K.corp.tenant.name} (${K.corp.tenant.id})`);console.error(`[webhook-ready] 凭证状态: ${K.authStatus==="ok"?"OK":`异常 (${K.authError})`}`),console.error(`[webhook-ready] Webhook 通道: ${K.activeWebhooks.length} 个可用`);for(let q of K.activeWebhooks){let G=q.isDefault?" [默认通道]":"";console.error(` - ${q.name} (${q.id}) mode=${q.mode}${G}`)}if(K.materialPack)console.error(`[webhook-ready] 材料包预检: ${K.materialPack.valid?`通过 (${K.materialPack.documentCount} 单)`:`失败 (${K.materialPack.errors?.join("; ")})`}`);if(K.ready)console.error(`\uD83D\uDFE2 ${K.statusMessage}`),console.error(`\uD83D\uDC49 Next action: ${K.nextAction}`);else console.error(`\uD83D\uDD34 准备阶段未通过: ${K.statusMessage}`),console.error(`\uD83D\uDC49 Next action: ${K.nextAction}`);console.log(JSON.stringify(K,null,2));return}if($==="material-pack"||$==="material-pack-push"){let Q=$==="material-pack-push"?"push":I,K=$==="material-pack-push"?h(J.options.file)??h(J.options.input):J.command[3]??h(J.options.file)??h(J.options.input);if(!K)throw Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");if(!XL0(K))throw Error(`File not found: ${K}`);let q=II(K);if(Q==="preview"){console.log(JSON.stringify(await $I(q.fileBuffer,q.fileName),null,2));return}if(Q!=="push")throw Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");let G=h(J.options.webhook)??h(J.options.selector),H=await Z9(U,Y.seal.endpoints.approvalStylePreferences),W;if(G)W=LU(H,G);else if(H.length===1)W=H[0],console.error(`\uD83D\uDC49 自动锁定唯一可用 Webhook 通道: ${W.name} (${W.id})`);else if(H.length>1){let X=H.map((Z)=>`"${Z.name}" (${Z.id})`).join(", ");throw Error(`当前租户存在多个 Webhook 通道 [${X}],请通过 --webhook <idOrName> 指定目标通道。`)}else throw Error("当前租户未配置任何 Webhook 集成通道。请先运行 'seal-use webhook add --name ... --result-url ...' 创建通道。");let V=await oD(q.fileBuffer,q.fileName,{webhookUrl:W.incomingDocumentWebhook.url,secret:W.secret});console.log(JSON.stringify(V,null,2));return}if($==="list"){await F0("seal_webhook_list",U,Y,{query:h(J.options.query)??h(J.options.keyword),includeSecret:ah(J.options)},O0(J.options Line truncated
`)?"":`
`}`);process.exitCode=n.exitCode}var o3=Boolean(r0.main==r0.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&jy(process.argv[1])===jy(Ri));if(o3)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await r3();else q4().catch((n)=>{console.error(n),process.exitCode=1});export{T4 as tokenizeCommand,q4 as startServer,n3 as resolveMcpEnabled,i3 as createServer,aK as SEAL_MCP_ENABLED_ENV,xK as SEAL_CLI_TOOL_NAME,sK as LEGACY_SEAL_MCP_ENABLED_ENV};
`}`);process.exitCode=$.exitCode}var cG1=Boolean(r.main==r.module||!import.meta.url.includes("$bunfs")&&process.argv[1]&&FL0(process.argv[1])===FL0(p5));if(cG1)if(process.argv[2]==="--seal-use-cli"||process.argv[2]==="--seal-home-cli")await nG1();else Ux().catch(($)=>{console.error($),process.exitCode=1});export{$x as tokenizeCommand,Ux as startServer,bG1 as resolveMcpEnabled,iG1 as createServer,uG1 as SEAL_MCP_ENABLED_ENV,kG1 as SEAL_CLI_TOOL_NAME,fG1 as LEGACY_SEAL_MCP_ENABLED_ENV};
+1 -1
View File
@@ -2,7 +2,7 @@
"openapi": "3.1.0",
"info": {
"title": "seal-use Wrapped API",
"version": "0.10.3",
"version": "0.10.13",
"description": "Planned HTTP contract for the seal-use wrapped backend API.\n\nThese endpoints describe the intended stable API for frontend developers and agents once\nthe HTTP adapter is implemented.\nThey are not the raw downstream Seal endpoints. seal-use is responsible for enterprise\nselection, source authentication, response compaction, and diagnostics-friendly fields.\n"
},
"servers": [
+1 -1
View File
@@ -1,7 +1,7 @@
openapi: 3.1.0
info:
title: seal-use Wrapped API
version: 0.10.3
version: 0.10.13
description: |
Planned HTTP contract for the seal-use wrapped backend API.
+6 -1
View File
@@ -1,6 +1,6 @@
{
"name": "seal-use",
"version": "0.10.3",
"version": "0.10.13",
"type": "module",
"module": "src/server.ts",
"bin": {
@@ -22,11 +22,16 @@
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.29.0",
"exceljs": "^4.4.0",
"iconv-lite": "^0.7.3",
"ky": "^2.0.2",
"pinyin-pro": "^3.29.3",
"yauzl": "^3.4.0",
"zod": "^4.4.3"
},
"devDependencies": {
"@types/bun": "^1.3.14",
"@types/yauzl": "^3.4.0",
"bun-types": "^1.3.14",
"typescript": "^5.9.3",
"yaml": "^2.9.0"
+10 -5
View File
@@ -1,12 +1,12 @@
---
name: seal-use
description: "v0.10.3: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
description: "v0.10.13: Use for Seal Use first-time enterprise onboarding, Hose/合思 or Seal-native authentication, assistance links and browser cURL intake, plus tenant approval operations, diagnosis, simulation, rules, users, configuration, and search."
metadata:
version: 0.10.3
short-description: Seal tenant and Hose approval automation (v0.10.3)
version: 0.10.13
short-description: Seal tenant and Hose approval automation (v0.10.13)
---
# Seal Use (v0.10.3)
# Seal Use (v0.10.13)
Use the `seal_cli` MCP tool when it is available; pass the command string as its `command` argument. If MCP is unavailable, fall back to the global `seal-use` CLI. This skill is a routing layer for agents: keep this file short, choose the right command, and read a focused reference only when the task needs detail.
@@ -65,8 +65,11 @@ seal-use corps list
- LLM Model Config & Providers: `seal-use llm config --corp <corpId>`, `seal-use llm providers --corp <corpId>`.
- System Permissions Config: `seal-use permissions available --corp <corpId>`, `seal-use permissions configs --corp <corpId>`.
- Billing & Feature Quotas: `seal-use billing status --corp <corpId>`, `seal-use billing plans --corp <corpId>`, `seal-use billing features --corp <corpId>`.
- Webhook 审批回调管理: `seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
- Webhook 准备看板与审批回调管理: `seal-use webhook ready [<材料包.zip>] --corp <corpId>` (别名 `status`) 检查企业环境、租户连通性、已激活通道与材料包预检;`seal-use webhook <list|get|add|update|delete> --corp <corpId>`.
- Webhook 材料包导入: `seal-use webhook material-pack preview <材料包.zip> --corp <corpId>` 只做本地校验和解析(无网络请求);`... push <材料包.zip> [--webhook <idOrName>] --corp <corpId>` 上传附件并通过入站 Webhook 触发 AI 审批(租户仅有 1 个通道时自动锁定无需指定 `--webhook`)。材料包格式:ZIP 根目录名 = `documentId`(或 `documentId@annotation`),Excel 附件列以 `[附件]` 为前缀(如 `[附件]合同协议`),单元格值为 ZIP 相对路径(支持多行/逗号/分号分隔);系统执行严格双向验证(Excel 声明的路径必须在 ZIP 中存在,ZIP 中的文件必须在某个 `[附件]` 列中声明)。详见 `references/cli.md` 中 "Material Pack Workflow" 一节。它与 `simulation material_pack` 的官方服务端导入流程相互独立。
- HTTP REST API & Docs Server: `seal-use http [--port 8787] [--host 127.0.0.1]` (提供 `/docs` 交互文档、`/openapi.json`、`POST /api/cli` 与 `/v1/*` REST API)。
- 审批规则质量校验 (Linter): `seal-use rules lint [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary] --corp <corpId>`; read `references/rule-lint.md`. 全局配置默认关闭 (`config lint <enable|disable>`)。
- Full CLI inventory: read `references/cli.md`.
## High-Value Commands
@@ -82,6 +85,7 @@ seal-use approval-runs attachments <recordId> --corp <corpId> --summary
seal-use approval-runs result <recordId> --corp <corpId> --summary
seal-use rules count --corp <corpId>
seal-use rules list --corp <corpId> --summary
seal-use rules lint --corp <corpId> --summary
seal-use rules clear --corp <corpId> --dry-run
seal-use rules clear --corp <corpId> --yes
seal-use rules get --corp <corpId> --version 16 --code '#0038'
@@ -112,6 +116,7 @@ seal-use tool seal_approval_search --corp <corpId> --json '{"keywords":["差旅"
- `references/enterprise-onboarding.md`: 首次安装、零配置、合思来源与 Seal 原生来源的区分、标准密钥/协助链接/F12 cURL 接入、参数责任与安全边界。
- `references/approval-run-lightweight.md`: 单号定位、字段裁剪、摘要、引用规则、单据摘要、附件摘要。
- `references/rule-lightweight.md`: 规则 count/list summary、按版本/编号取单条规则、规则搜索裁剪。
- `references/rule-lint.md`: 规则质量检查器(Linter)、模糊词拦截、悬空例外闭环、多 TS 校验器切换与发布门禁。
- `references/customer-feedback-rule-remediation.md`: 微信/截图反馈包到企业定位、审批追踪、根因分类、最小规则 diff、确认、发布与验收的固定闭环。
- `references/hose-enterprise-auth.md`: Hose 企业配置、认证诊断、授权链接。
- `references/hose-enterprise-init.md`: 合思标准密钥的域名、企业与管理员自动发现,以及多候选管理员的安全选择。
@@ -62,7 +62,14 @@ If the user then wants the full text of one cited rule, use `rules get --record-
Use:
```bash
# 查看附件列表摘要(包含文件名、类型、大小及直链可用性)
seal-use approval-runs attachments <recordId> --corp <corpId> --summary
# 下载全部附件到本地目录(优先使用 ossSignedUrl 签名直链)
seal-use approval-runs attachments download <recordId> --all --out-dir ./downloads --corp <corpId>
# 按名称或 fileId 过滤下载单个附件
seal-use approval-runs attachments download <recordId> --name 发票 --corp <corpId>
```
This should be enough for file names, file IDs, mime types, positions, invoice/attachment grouping, and links when available. For customer disputes about OCR, receipt/invoice classification, or image content, switch to `approval-attachment-trace.md`.
+114 -49
View File
@@ -37,7 +37,12 @@ seal-use version
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use service <start|stop|restart|status>
seal-use config test-dir [<path>|--clear]
seal-use config lint <enable|disable|status> [--linter <name>] [--min-score <score>]
seal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]
seal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]
seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]
seal-use service <start|stop|restart|status|logs> [--port 8787] [--host 127.0.0.1] [--lines 50]
seal-use http [--port 8787] [--host 127.0.0.1]
seal-use serve [--port 8787]
seal-use update
@@ -71,10 +76,10 @@ seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
seal-use deploy hosecloud get [<sign-key>] [--corp <corpId>]
seal-use deploy hosecloud status [--corp <corpId>]
seal-use deploy hosecloud configure --json '{...}' [--corp <corpId>]
seal-use deploy hosecloud sync <sign-key> [--corp <corpId>]
seal-use deploy hosecloud sync [<sign-key>] [--auto] [--corp <corpId>]
seal-use preference get [--corp <corpId>]
seal-use preference decision update --json '{"explicitApprove":"..."}' [--corp <corpId>]
seal-use preference thinking-depth set --default <medium|high> [--corp <corpId>]
@@ -86,9 +91,11 @@ seal-use tool <toolName> [--corp <corpId>] [--json '{"key":"value"}']
seal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]
seal-use approval-runs stats --corp <corpId> [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id]
seal-use approval-runs count --corp <corpId> [--status APPROVED]
seal-use approval-runs export --corp <corpId> [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--limit <n>] [--downloads] [--out <file>]
seal-use approval-runs search --corp <corpId> [--query text] [--limit 20] [--includeBridge true]
seal-use approval-runs get <recordId> --corp <corpId> [--fields metadata|document.fields,result.summary] [--output-file file.json]
seal-use approval-runs attachments <recordId> --corp <corpId>
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] --corp <corpId>
seal-use approval-runs result <recordId> --corp <corpId> [--summary]
seal-use approval-runs url --corp <corpId>
seal-use approval-runs url <recordId> --corp <corpId>
@@ -108,7 +115,7 @@ seal-use simulation integrations --corp <corpId>
seal-use simulation package-upload <材料包.zip> --corp <corpId>
```
## Fine-Grained Tools
## CLI Command Overview
`seal-use version` returns:
@@ -119,28 +126,24 @@ seal-use simulation package-upload <材料包.zip> --corp <corpId>
}
```
`seal-use service status` returns the PID, version, state directory, PID file, and log file for the optional local background process.
`seal-use service <start|stop|restart|status|logs>` manages the persistent background service daemon with embedded HTTP server (serving `/docs`, `/openapi.json`, and `POST /api/cli`). `status` returns the PID, version, host, port, active HTTP URL, state directory, PID file, and log file.
`seal-use update` updates the git checkout, runs `bun install`, and restarts the local service if it was running.
Identity and session:
- `seal-use auth diagnose --corp <corpId>`
- `seal_whoami`
- `seal_session_get`
- `seal-use corps list`
- `seal-use corps current`
Approval rule maintenance:
- `seal-use rules count [--corp <corpId>]`
- `seal-use rules list --summary [--corp <corpId>]`
- `seal-use rules pull [--corp <corpId>] [--version <id|num|latest>] [--out <file>]`
- `seal-use rules lint [--file <path>] [--corp <corpId>] [--linter <name|path>] [--version <num>] [--code <code>] [--min-score <score>] [--summary]`
- `seal-use rules push [--file <path>] [--corp <corpId>] [--publish] [--version-name <name>] [--dry-run|--yes]`
- `seal-use rules clear [--corp <corpId>] [--dry-run|--yes]`
- `seal_approval_rules_list`
- `seal_approval_rules_clear`
- `seal_approval_rule_create`
- `seal_approval_rule_update`
- `seal_approval_rule_delete`
- `seal_approval_rule_versions_list`
- `seal_approval_rule_version_publish`
Approval run lightweight queries:
@@ -151,59 +154,41 @@ Approval run lightweight queries:
- `seal-use approval-runs cited-rules <recordId> --corp <corpId>`
- `seal-use approval-runs get <recordId> --corp <corpId> --fields document.fields,result.summary`
- `seal-use approval-runs attachments <recordId> --corp <corpId> --summary`
- `seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] --corp <corpId>`
- `seal-use approval-runs result <recordId> --corp <corpId> --summary`
- `seal_approval_run_get` with `fields`
- `seal_approval_run_pick`
- `seal_approval_run_cited_rules_get`
- `seal_approval_run_document_summary_get`
- `seal_approval_run_attachments_get`
- `seal_approval_run_result_get` with `{"summary":true}`
Approval knowledge documents:
Approval knowledge documents & style:
- `seal_approval_documents_list`
- `seal_approval_document_get`
- `seal_approval_document_create`
- `seal_approval_document_update`
Approval search and context:
- `seal_approval_search`
- `seal_approval_context_get`
- `seal-use rules get --corp <corpId> --version <number> --code '#0038'`
- `seal-use rules get --corp <corpId> --record-id <recordId> --runtime-id rule-205`
Style preferences:
- `seal_approval_style_preferences_get`
- `seal_approval_style_preferences_update`
Webhook integrations:
- `seal-use webhook ready [<材料包.zip|信息表.xlsx>] [--corp <corpId>]`
- `seal-use webhook status [<材料包.zip|信息表.xlsx>] [--corp <corpId>]`
- `seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]`
- `seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]`
- `seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]`
- `seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]`
- `seal-use webhook delete <idOrName> --yes [--corp <corpId>]`
- `seal_webhook_list`
- `seal_webhook_get`
- `seal_webhook_add`
- `seal_webhook_update`
- `seal_webhook_delete`
- `seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> --corp <corpId>`
- `seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] --corp <corpId>`
Webhook writes read the current AI approval config and POST the merged full config back to `api/v1/agent/ai-approval/config`, preserving non-Webhook integrations. List/get mask `secret` by default; add returns the generated secret once.
Approval runs, simulations, and Langfuse bridge:
- `seal_approval_runs_search`
- `seal_approval_runs_summary`
- `seal_simulation_batch_records_get`
- `seal_simulation_batch_create`
- `seal_simulation_batches_list`
- `seal_simulation_batch_get`
- `seal_simulation_templates_get`
- `seal_simulation_integrations_get`
- `seal_approval_run_langfuse_bridge_get`
- `seal-use approval-runs search --corp <corpId> [--query <text>] [--limit 20]`
- `seal-use approval-runs summary --corp <corpId> [--date YYYY-MM-DD] [--timezone Asia/Shanghai]`
- `seal-use approval-runs bridge --corp <corpId> [--sourceDocumentSN <sn>]`
- `seal-use simulation create --mode hosecloud --flow-ids ... --corp <corpId>`
- `seal-use simulation wait <batchId> --corp <corpId>`
- `seal-use simulation clean <batchId> --corp <corpId>`
- `seal-use simulation list --corp <corpId>`
- `seal-use simulation get <batchId> --corp <corpId>`
- `seal-use simulation batch-records <batchId> --corp <corpId>`
- `seal-use simulation templates --corp <corpId>`
- `seal-use simulation integrations --corp <corpId>`
## Common Examples
@@ -361,6 +346,86 @@ Update style preferences:
}
```
## Material Pack Workflow
A **material pack** (材料包) is a ZIP file that bundles an Excel information sheet (`信息表.xlsx`) with attachments organised by document ID. It is the primary input to the Webhook-based AI approval ingestion pipeline.
### ZIP structure convention
```
材料包.zip
├── 信息表.xlsx ← must exist at ZIP root
├── BX20260826003/ ← root dir name = documentId (or documentId@annotation)
│ ├── 合同协议/
│ │ └── 采购合同.pdf
│ └── 支付凭证/
│ └── 支付宝交易明细.pdf
└── BX20260826004@重新提交v2/ ← @annotation is stripped when matching documentId
└── 发票/
└── 增值税专用发票.pdf
```
- The root directory name **must equal** the `documentId` **OR** start with `documentId@` (the `@` separates an optional annotation ignored during matching).
- `信息表.xlsx` at the ZIP root is the only file not associated with any document directory.
### Excel column convention
| Column type | Naming | Purpose |
|---|---|---|
| Regular column | Any header (e.g. `会议编号`, `总金额`) | Standard document fields |
| Attachment column | Header starts with `[附件]` (e.g. `[附件]合同协议`) | Declares attached files for this row |
- The `[附件]` prefix is stripped to produce the field `label` sent to Seal.
- The cell value contains full ZIP-relative path(s) to the declared files (multiple paths separated by newline, comma, or semicolon).
- Example: column `[附件]合同协议`, cell value `BX20260826003/合同协议/采购合同.pdf`
### Sheet → document level mapping
| Excel sheet | Maps to |
|---|---|
| First sheet (main / 会议) | Root document `categoryFields` |
| 费用明细表 (has `报销金额` column) | Per-row entries in `mingxi_list` |
| 劳务明细 (has `姓名` column) | Per-person entries in `daoshi_list` |
### Strict bidirectional validation
Before pushing or previewing, the system enforces:
1. **Excel → ZIP**: Every path declared in an `[附件]` column cell **must** exist as a ZIP entry. Error: `Excel 声明的附件路径在 ZIP 中不存在: <path>`
2. **ZIP → Excel**: Every ZIP file (excluding `信息表.xlsx`) **must** be declared in exactly one `[附件]` column. Error: `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>`
3. **Document Directory Scope Isolation**: All attachments declared for a document `DOC_X` **must** reside in its own root directory (`DOC_X/` or `DOC_X@annotation/`). Cross-document references are strictly forbidden. Error: `单据「X」声明了跨单据或非本单据目录的附件路径: <path>。附件必须位于该单据自己的根目录...`
4. **Strict Declaration Uniqueness**: A given ZIP file path **cannot** be declared more than once across the entire material pack (even within the same document across multiple rows or fields). If the same logical document is needed in multiple places, separate files must be placed in distinct paths. Error: `附件路径「<path>」被重复声明了 N 次...`
5. **documentId ↔ ZIP root**: Every `documentId` in the Excel main sheet must have a matching ZIP root dir (exact match or `documentId@annotation`). Errors: `Excel 会议编号「X」在 ZIP 中找不到对应的根目录...` / `ZIP 根目录对应的编号「X」在信息表中找不到对应的会议编号`
All validation errors are collected and reported together in a single `MaterialPackValidationError`.
### CLI usage
```bash
# Check environment readiness and optionally pre-validate the material pack
seal-use webhook ready [--file <pack.zip>] [--corp <corpId>]
# Dry-run: local parse & validation only, no network calls, returns preview JSON
seal-use webhook material-pack preview <pack.zip> --corp <corpId>
# Upload attachments and push documents via inbound Webhook
seal-use webhook material-pack push <pack.zip> [--webhook <nameOrId>] --corp <corpId>
# When there is exactly one webhook channel, --webhook can be omitted (auto-locked)
```
### Error messages reference
| Error message | Meaning | Fix |
|---|---|---|
| `Excel 声明的附件路径在 ZIP 中不存在: <path>` | Cell value references a file not in ZIP | Add the file to ZIP at exactly that path |
| `ZIP 中的文件未在 Excel 任何 [附件] 列中声明: <path>` | ZIP contains a file not referenced by any `[附件]` column | Add an `[附件]` column entry or remove the file from ZIP |
| `单据「X」声明了跨单据或非本单据目录的附件路径: <path>` | Document X declared a path inside another document's folder | Move file into Document X's own folder and update Excel |
| `附件路径「<path>」被重复声明了 N 次` | The same file path was declared in multiple columns/rows/documents | Each declaration must point to a unique file path; duplicate file if needed |
| `Excel 会议编号「X」在 ZIP 中找不到对应的根目录` | No ZIP root dir matches documentId `X` | Rename the ZIP folder to match the documentId |
| `ZIP 根目录对应的编号「X」在信息表中找不到` | ZIP folder has no matching documentId in Excel | Remove the folder or add the document to Excel |
| `ZIP 根目录缺少信息表.xlsx` | No `信息表.xlsx` found at ZIP root | Add the Excel file to the ZIP root |
| `附件上传失败 <status>` | Network/server error during file upload | Check webhook URL, secret, and server availability |
## Failure Handling
- CLI commands are short-lived processes. In-memory auth/search caches only live for that single process. Use `seal-use service restart` after updates so the optional local service picks up new code.
@@ -69,8 +69,12 @@ seal-use deploy hosecloud configure --corp <corpId> --json '{
# 5. 一键同步发布到合思审批流
seal-use deploy hosecloud sync <signKey> --corp <corpId>
# 6. 查看单项配置详情
seal-use deploy hosecloud get <signKey> --corp <corpId>
# 5.1 单配置企业一键自动同步 (--auto)
# 若企业内仅存在 1 个合思配置卡片,可直接传入 --auto 自动锁定执行,免去查询复制 signKey:
seal-use deploy hosecloud sync --auto --corp <corpId>
# 6. 查看单项配置详情(未传 signKey 时自动列出当前企业候选列表与查看命令)
seal-use deploy hosecloud get [<signKey>] --corp <corpId>
# 7. 检查发布与多平台集成状态
seal-use deploy hosecloud status --corp <corpId>
+90
View File
@@ -0,0 +1,90 @@
# Seal Approval Rule Linter & Quality Validation
Use this reference when analyzing, validating, or linting Seal AI approval rules to detect vague phrasing, missing exception evidence, or formatting defects before publishing.
## Key Principles
- **Default State**: Linter is **disabled by default** in global configuration (`lint.enabled: false`) to avoid unsolicited noise during standard operations.
- **Explicit Triggering**: `seal-use rules lint` always runs regardless of global configuration.
- **Draft Hook**: When `seal-use config lint enable` is set, `seal_approval_rule_update` outputs real-time diagnostic warnings to `stderr` without mutating `stdout` payloads.
- **Fault-Tolerant Fallback**: If a custom `.ts` linter file has syntax errors, runtime exceptions, or is missing, the engine logs a warning to `stderr` and **silently falls back to the built-in heuristic linter without failing**.
## CLI Commands
### 1. Lint Current Draft Rules (Whole-RuleSet Scan)
```bash
seal-use rules lint --corp <corpId>
```
### 2. Lint Specific Historical Version or Single Rule
```bash
# Lint rules in published version 16
seal-use rules lint --version 16 --corp <corpId>
# Lint a specific rule by code (#0038)
seal-use rules lint --code '#0038' --corp <corpId>
# Summary mode (only show rules with issues)
seal-use rules lint --summary --corp <corpId>
```
### 3. Quality Gate for CI / Release
```bash
# If overall score is below 85, terminates with exit code 1
seal-use rules lint --min-score 85 --level error --corp <corpId>
```
### 4. Configure Global Linter Settings
```bash
# Check status
seal-use config lint status
# Enable auto lint on rule updates
seal-use config lint enable --linter builtin --min-score 80
# Disable auto lint
seal-use config lint disable
```
## Built-In Detection Rules
| Code | Level | Description | Recommendation |
| :--- | :---: | :--- | :--- |
| `TOO_SHORT` | `error` | Rule description is under 5 characters. | Add concrete conditions and criteria. |
| `VAGUE_WORD` | `error` | Contains subjective/fuzziness words (`原则上`, `尽量`, `适当`, `酌情`, `一般情况下`, `合理控制`). | Replace with rigid thresholds, enums, or criteria. |
| `HANGING_EXCEPTION` | `warning` | Exception trigger found (`除非`, `特殊情况`, `经批准`) without verifiable evidence keyword (`备注`, `附件`, `证明`, `邮件`, `截图`). | Specify exact evidence source in invoice/document. |
## Custom TS Linters (Plugin-as-Code)
Place custom TypeScript linter functions in `~/.config/seal-use/linters/<name>.ts` or `./linters/<name>.ts`:
```typescript
// ~/.config/seal-use/linters/finance-strict.ts
export default function customLinter(rule: { description: string }) {
const issues = [];
if (rule.description.includes("商务舱") && !rule.description.includes("副总裁")) {
issues.push({
level: "error",
code: "FLIGHT_CABIN_RESTRICTION",
snippet: "商务舱",
message: "乘坐商务舱必须限定副总裁及以上级别",
suggestion: "补充限制: '仅副总裁及以上职级允许报销商务舱'"
});
}
return {
score: issues.length === 0 ? 100 : 60,
passed: issues.length === 0,
issues
};
}
```
Run with custom linter:
```bash
seal-use rules lint --linter finance-strict --corp <corpId>
```
+108 -11
View File
@@ -1,5 +1,11 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import * as api from "../../domains/seal/api.js";
import { exportApprovalRunsToExcel } from "../../domains/seal/approval-runs-export.js";
import {
downloadApprovalRunAttachments,
extractApprovalRunAttachments
} from "../../domains/seal/attachments.js";
import { runTool, runToolResult } from "../helpers.js";
import { booleanOption, numberOption, stringOption } from "../parser.js";
import { outputOptions, printJson } from "../printer.js";
@@ -168,18 +174,84 @@ export async function handleApprovalRunsCommand(
}
if (action === "attachments") {
const subAction = args.command[2];
if (subAction === "download") {
const recordId = args.command[3];
if (!recordId) {
throw new Error(
"Usage: seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>]"
);
}
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
record,
all: booleanOption(args.options.all),
name: stringOption(args.options.name),
outDir:
stringOption(args.options["out-dir"]) ??
stringOption(args.options.outDir) ??
stringOption(args.options.dir)
});
printJson(downloadResult, outputOptions(args.options));
if (downloadResult.total > 0 && downloadResult.downloaded === 0) {
throw new Error(`所有 ${downloadResult.total} 个附件下载均失败。`);
}
return;
}
const recordId = args.command[2];
if (!recordId) throw new Error("Usage: seal-use approval-runs attachments <recordId>");
await runTool(
"seal_approval_run_attachments_get",
client,
corp,
{
recordId,
summary: booleanOption(args.options.summary)
},
outputOptions(args.options)
);
if (!recordId) throw new Error("Usage: seal-use approval-runs attachments <recordId> | seal-use approval-runs attachments download <recordId>");
if (booleanOption(args.options.download)) {
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
record,
all: booleanOption(args.options.all) ?? true,
name: stringOption(args.options.name),
outDir:
stringOption(args.options["out-dir"]) ??
stringOption(args.options.outDir) ??
stringOption(args.options.dir)
});
printJson(downloadResult, outputOptions(args.options));
if (downloadResult.total > 0 && downloadResult.downloaded === 0) {
throw new Error(`所有 ${downloadResult.total} 个附件下载均失败。`);
}
return;
}
const record = await api.getApprovalRun(client, recordId);
const result = extractApprovalRunAttachments(record, {
summary: booleanOption(args.options.summary)
});
printJson(result, outputOptions(args.options));
return;
}
if (action === "download") {
const recordId = args.command[2];
if (!recordId) {
throw new Error(
"Usage: seal-use approval-runs download <recordId> [--all] [--name <name>] [--out-dir <dir>]"
);
}
const record = await api.getApprovalRun(client, recordId);
const downloadResult = await downloadApprovalRunAttachments({
record,
all: booleanOption(args.options.all),
name: stringOption(args.options.name),
outDir:
stringOption(args.options["out-dir"]) ??
stringOption(args.options.outDir) ??
stringOption(args.options.dir)
});
printJson(downloadResult, outputOptions(args.options));
if (downloadResult.total > 0 && downloadResult.downloaded === 0) {
throw new Error(`所有 ${downloadResult.total} 个附件下载均失败。`);
}
return;
}
@@ -214,5 +286,30 @@ export async function handleApprovalRunsCommand(
return;
}
if (action === "export") {
const result = await exportApprovalRunsToExcel(client, corp, {
limit: numberOption(args.options.limit),
startDate:
stringOption(args.options.start) ??
stringOption(args.options.startDate) ??
stringOption(args.options.since),
endDate: stringOption(args.options.end) ?? stringOption(args.options.endDate),
status: stringOption(args.options.status),
manualApprovalStatus:
stringOption(args.options["manual-status"]) ??
stringOption(args.options.manualStatus) ??
stringOption(args.options.manualApprovalStatus),
includeCompletedOnly:
booleanOption(args.options["completed-only"]) ?? booleanOption(args.options.completedOnly),
outputFile:
stringOption(args.options.out) ??
stringOption(args.options.output) ??
stringOption(args.options.file),
toDownloads: booleanOption(args.options.downloads) ?? booleanOption(args.options.download)
});
printJson(result, outputOptions(args.options));
return;
}
throw new Error(`Unknown approval-runs command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
+1 -1
View File
@@ -22,7 +22,7 @@ export async function handleAuthCommand(action: string | undefined, corp: CorpCo
throw new Error(`Unknown auth command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
}
export async function diagnoseAuth(corp: CorpConfig) {
async function diagnoseAuth(corp: CorpConfig) {
if (corp.source.type !== "hose") {
const client = await createSealClient(corp);
const me = await getMe(client);
+72 -1
View File
@@ -45,6 +45,7 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
: previousConfig.defaultCorpId
: undefined;
const config = saveGlobalConfig({
...previousConfig,
stateful,
...(defaultCorpId ? { defaultCorpId } : {})
});
@@ -52,5 +53,75 @@ export function handleConfigCommand(action: string | undefined, maybeName: strin
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
if (action === "lint") {
const subAction = maybeName ?? stringOption(args.options.state) ?? stringOption(args.options.enable);
const previousConfig = loadGlobalConfig();
const currentLint = previousConfig.lint ?? { enabled: false, activeLinter: "builtin", minScore: 0 };
if (!subAction || subAction === "status" || subAction === "get") {
printJson({ lint: currentLint, configFile: resolveGlobalConfigFile() });
return;
}
let enabled = currentLint.enabled;
if (subAction === "enable" || subAction === "on" || subAction === "true") {
enabled = true;
} else if (subAction === "disable" || subAction === "off" || subAction === "false") {
enabled = false;
}
const activeLinter = stringOption(args.options.linter) ?? currentLint.activeLinter;
const minScore = args.options.minScore !== undefined || args.options["min-score"] !== undefined
? Number(args.options.minScore ?? args.options["min-score"])
: currentLint.minScore;
const nextLint = {
enabled,
activeLinter,
minScore: isNaN(minScore) ? 0 : Math.max(0, Math.min(100, minScore))
};
const config = saveGlobalConfig({
...previousConfig,
lint: nextLint
});
printJson(globalConfigSummary(config));
return;
}
if (action === "test-dir" || action === "test-enterprises-dir") {
const isClear = args.options.clear === true || maybeName === "--clear" || maybeName === "clear";
const previousConfig = loadGlobalConfig();
if (isClear) {
const config = saveGlobalConfig({
...previousConfig,
testEnterprisesDir: undefined
});
printJson(globalConfigSummary(config));
return;
}
const newPath = maybeName && !maybeName.startsWith("-")
? maybeName
: stringOption(args.options.path) ?? stringOption(args.options.dir);
if (!newPath) {
printJson({
testEnterprisesDir: previousConfig.testEnterprisesDir ?? null,
configFile: resolveGlobalConfigFile()
});
return;
}
const config = saveGlobalConfig({
...previousConfig,
testEnterprisesDir: newPath
});
printJson(globalConfigSummary(config));
return;
}
throw new Error(`Unknown config command: ${action ?? ""}. Available: paths, get, status, mode, lint, test-dir. Run 'seal-use help' for available commands.`);
}
+60 -3
View File
@@ -2,9 +2,10 @@ import { readFileSync } from "node:fs";
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { runTool } from "../helpers.js";
import { jsonObject, stringOption } from "../parser.js";
import { booleanOption, jsonObject, stringOption } from "../parser.js";
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
import * as api from "../../domains/seal/api.js";
export async function handleDeployCommand(
systemOrAction: string | undefined,
@@ -64,7 +65,26 @@ export async function handleDeployCommand(
if (action === "get") {
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
if (!signKey) throw new Error("Usage: seal-use deploy hosecloud get <sign-key>");
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
if (hoseConfigs.length === 0) {
throw new Error(
`当前企业 (${corp.name}) 尚未添加合思发布配置。\n` +
`👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${corp.id}`
);
}
console.error(`Usage: seal-use deploy hosecloud get <sign-key> [--corp ${corp.id}]\n`);
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
for (const item of hoseConfigs) {
const name = (item as any).outboundName ?? "SealAI 审批";
const key = item.signKey;
const origin = (item as any).apiOrigin ?? "production";
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
console.error(` 👉 查看命令: seal-use deploy hosecloud get ${key} --corp ${corp.id}\n`);
}
throw new Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey。");
}
await runTool("seal_deploy_hosecloud_get", client, corp, { signKey }, outputOptions(args.options));
return;
}
@@ -88,7 +108,44 @@ export async function handleDeployCommand(
if (action === "sync") {
const signKey = target ?? stringOption(args.options.signKey) ?? stringOption(args.options["sign-key"]);
if (!signKey) throw new Error("Usage: seal-use deploy hosecloud sync <sign-key>");
const autoOpt = booleanOption(args.options.auto) ?? booleanOption(args.options.yes);
if (!signKey) {
const config = await api.getApprovalStylePreferences(client);
const hoseConfigs = (config.integrations ?? []).filter((i: any) => i.type === "hosecloud");
if (hoseConfigs.length === 0) {
throw new Error(
`当前企业 (${corp.name}) 尚未添加合思发布配置。\n` +
`👉 请先运行配置命令:seal-use deploy hosecloud configure --json '{...}' --corp ${corp.id}`
);
}
const firstHose = hoseConfigs[0];
if (firstHose && hoseConfigs.length === 1 && autoOpt) {
const singleKey = firstHose.signKey;
console.error(`ℹ️ [auto] 检测到企业仅有 1 个合思配置,已自动选择 (signKey: ${singleKey})`);
await runTool("seal_deploy_hosecloud_sync", client, corp, { signKey: singleKey }, outputOptions(args.options));
return;
}
console.error(`Usage: seal-use deploy hosecloud sync <sign-key> [--corp ${corp.id}]\n`);
console.error(`ℹ️ 当前企业发现以下可用的合思配置卡片:`);
for (const item of hoseConfigs) {
const name = (item as any).outboundName ?? "SealAI 审批";
const key = item.signKey;
const origin = (item as any).apiOrigin ?? "production";
console.error(` • "${name}" (signKey: ${key}, 环境: ${origin})`);
console.error(` 👉 同步命令: seal-use deploy hosecloud sync ${key} --corp ${corp.id}\n`);
}
if (hoseConfigs.length === 1) {
console.error(`💡 提示:若希望单配置自动同步,可附加 --auto 参数:seal-use deploy hosecloud sync --auto --corp ${corp.id}\n`);
}
throw new Error("缺少必需参数 <sign-key>。请从上述候选列表中选择并指定 signKey 执行同步。");
}
await runTool("seal_deploy_hosecloud_sync", client, corp, { signKey }, outputOptions(args.options));
return;
}
+71 -1
View File
@@ -140,5 +140,75 @@ export async function handleRulesCommand(
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Run 'seal-use help' for available commands.`);
if (action === "pull") {
const version = stringOption(args.options.version) ?? maybeName;
const out = stringOption(args.options.out) ?? stringOption(args.options.file) ?? stringOption(args.options.f);
await runTool(
"seal_approval_rules_pull",
client,
corp,
{
version,
out
},
outputOptions(args.options)
);
return;
}
if (action === "push") {
const file = stringOption(args.options.file) ?? stringOption(args.options.f) ?? maybeName;
const confirmed = booleanOption(args.options.yes) === true;
const dryRun = booleanOption(args.options.dryRun) ?? booleanOption(args.options["dry-run"]) ?? !confirmed;
const publish = booleanOption(args.options.publish);
const versionName = stringOption(args.options.versionName) ?? stringOption(args.options["version-name"]);
const result = await runToolResult(
"seal_approval_rules_push",
client,
corp,
{
file,
dryRun,
confirm: confirmed,
publish,
versionName
}
);
if (!confirmed && dryRun && result && typeof result === "object") {
printJson(
{
...result,
nextCommand: `seal-use rules push --file ${file ?? "./rules.local.json"} --corp ${corp.id} --yes${publish ? " --publish" : ""}`
},
outputOptions(args.options)
);
return;
}
printJson(result, outputOptions(args.options));
return;
}
if (action === "lint") {
await runTool(
"seal_approval_rules_lint",
client,
corp,
{
file: stringOption(args.options.file) ?? stringOption(args.options.f),
linter: stringOption(args.options.linter),
version: stringOption(args.options.version),
code: stringOption(args.options.code),
ruleId: stringOption(args.options.rule) ?? maybeName,
minScore: numberOption(args.options.minScore) ?? numberOption(args.options["min-score"]),
level: stringOption(args.options.level),
summary: booleanOption(args.options.summary)
},
outputOptions(args.options)
);
return;
}
throw new Error(`Unknown rules command: ${action ?? ""}. Available: count, list, clear, versions, version, get, search, lint, pull, push. Run 'seal-use help' for available commands.`);
}
+24 -9
View File
@@ -3,17 +3,32 @@ import { join } from "node:path";
import { VERSION } from "../../version.js";
import { runServiceCommand } from "../service.js";
import { printJson } from "../printer.js";
import type { CliRuntime } from "../types.js";
import { numberOption, stringOption } from "../parser.js";
import type { CliRuntime, ParsedArgs } from "../types.js";
export const STATE_DIR = join(homedir(), ".config", "seal-use");
export async function handleServiceCommand(action: string | undefined, runtime: CliRuntime) {
const result = await runServiceCommand(action, {
appRoot: runtime.appRoot,
entryFile: runtime.entryFile,
stateDir: STATE_DIR,
version: VERSION,
launcher: runtime.launcher
});
export async function handleServiceCommand(
action: string | undefined,
runtime: CliRuntime,
args?: ParsedArgs
) {
const port = args ? numberOption(args.options.port) ?? numberOption(args.options.p) : undefined;
const host = args ? stringOption(args.options.host) ?? stringOption(args.options.h) : undefined;
const maxLines = args ? numberOption(args.options.lines) ?? numberOption(args.options.n) : undefined;
const result = await runServiceCommand(
action,
{
appRoot: runtime.appRoot,
entryFile: runtime.entryFile,
stateDir: STATE_DIR,
version: VERSION,
launcher: runtime.launcher,
port,
host
},
{ maxLines }
);
if (result !== undefined) printJson(result);
}
+83
View File
@@ -1,6 +1,16 @@
import type { CorpConfig } from "../../core/config/types.js";
import type { createSealClient } from "../../core/http/factory.js";
import { existsSync } from "node:fs";
import { runTool } from "../helpers.js";
import * as api from "../../domains/seal/api.js";
import { findWebhookIntegration } from "../../domains/seal/api.js";
import type { WebhookIntegration } from "../../domains/seal/types.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "../../domains/seal/material-pack/index.js";
import {
booleanOption,
parseWebhookMode,
@@ -11,6 +21,12 @@ import {
import { outputOptions } from "../printer.js";
import type { ParsedArgs } from "../types.js";
export async function handleWebhookMaterialPackPreview(filePath: string) {
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2));
}
export async function handleWebhookCommand(
action: string | undefined,
maybeName: string | undefined,
@@ -18,6 +34,73 @@ export async function handleWebhookCommand(
corp: CorpConfig,
args: ParsedArgs
) {
if (action === "ready" || action === "status") {
const filePath = maybeName ?? stringOption(args.options.file) ?? stringOption(args.options.input);
const result = await checkWebhookReadiness(client, corp, { filePath });
console.error(`[webhook-ready] 企业环境: ${result.corp.name} (${result.corp.id}) [${result.stateMode}]`);
if (result.corp.tenant?.name) {
console.error(`[webhook-ready] 租户信息: ${result.corp.tenant.name} (${result.corp.tenant.id})`);
}
console.error(`[webhook-ready] 凭证状态: ${result.authStatus === "ok" ? "OK" : `异常 (${result.authError})`}`);
console.error(`[webhook-ready] Webhook 通道: ${result.activeWebhooks.length} 个可用`);
for (const hook of result.activeWebhooks) {
const defLabel = hook.isDefault ? " [默认通道]" : "";
console.error(` - ${hook.name} (${hook.id}) mode=${hook.mode}${defLabel}`);
}
if (result.materialPack) {
console.error(
`[webhook-ready] 材料包预检: ${
result.materialPack.valid
? `通过 (${result.materialPack.documentCount} 单)`
: `失败 (${result.materialPack.errors?.join("; ")})`
}`
);
}
if (result.ready) {
console.error(`🟢 ${result.statusMessage}`);
console.error(`👉 Next action: ${result.nextAction}`);
} else {
console.error(`🔴 准备阶段未通过: ${result.statusMessage}`);
console.error(`👉 Next action: ${result.nextAction}`);
}
console.log(JSON.stringify(result, null, 2));
return;
}
if (action === "material-pack" || action === "material-pack-push") {
const operation = action === "material-pack-push" ? "push" : maybeName;
const filePath = action === "material-pack-push"
? stringOption(args.options.file) ?? stringOption(args.options.input)
: args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
if (!existsSync(filePath)) throw new Error(`File not found: ${filePath}`);
const input = readMaterialPackFile(filePath);
if (operation === "preview") {
console.log(JSON.stringify(await previewMaterialPack(input.fileBuffer, input.fileName), null, 2));
return;
}
if (operation !== "push") throw new Error("Usage: seal-use webhook material-pack <preview|push> <材料包.zip>");
const selector = stringOption(args.options.webhook) ?? stringOption(args.options.selector);
const integrations = await api.listWebhookIntegrations(client, corp.seal.endpoints.approvalStylePreferences);
let integration: WebhookIntegration;
if (selector) {
integration = findWebhookIntegration(integrations, selector);
} else if (integrations.length === 1) {
integration = integrations[0]!;
console.error(`👉 自动锁定唯一可用 Webhook 通道: ${integration.name} (${integration.id})`);
} else if (integrations.length > 1) {
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 --webhook <idOrName> 指定目标通道。`);
} else {
throw new Error("当前租户未配置任何 Webhook 集成通道。请先运行 'seal-use webhook add --name ... --result-url ...' 创建通道。");
}
const result = await pushMaterialPack(input.fileBuffer, input.fileName, {
webhookUrl: integration.incomingDocumentWebhook.url,
secret: integration.secret
});
console.log(JSON.stringify(result, null, 2));
return;
}
if (action === "list") {
await runTool(
"seal_webhook_list",
+4
View File
@@ -27,6 +27,10 @@ export function globalConfigSummary(config: GlobalConfig = loadGlobalConfig()) {
...(config.stateful && config.defaultCorpId
? { defaultCorpId: config.defaultCorpId }
: {}),
...(config.testEnterprisesDir
? { testEnterprisesDir: config.testEnterprisesDir }
: {}),
lint: config.lint,
configFile: resolveGlobalConfigFile()
};
}
+10 -3
View File
@@ -19,12 +19,19 @@ export function parseArgs(argv: string[]): ParsedArgs {
}
if (arg.startsWith("-")) {
const key = arg.replace(/^-+/, "");
const raw = arg.replace(/^-+/, "");
if (raw.includes("=")) {
const eqIdx = raw.indexOf("=");
const key = raw.slice(0, eqIdx);
const val = raw.slice(eqIdx + 1);
options[key] = val;
continue;
}
const next = argv[index + 1];
if (!next || next.startsWith("-")) {
options[key] = true;
options[raw] = true;
} else {
options[key] = next;
options[raw] = next;
index += 1;
}
continue;
+12 -4
View File
@@ -2,10 +2,10 @@ import { writeFileSync } from "node:fs";
import { booleanOption, stringOption } from "./parser.js";
import type { OutputOptions } from "./types.js";
export const RULE_LIST_FULL_COUNT_LIMIT = 100;
export const RULE_LIST_FULL_BYTES_LIMIT = 120_000;
const RULE_LIST_FULL_COUNT_LIMIT = 100;
const RULE_LIST_FULL_BYTES_LIMIT = 120_000;
export const RULE_SUMMARY_FIELDS = ["id", "code", "status", "strictness", "scope", "createdAt", "updatedAt"];
export const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
const DEFAULT_OUTPUT_BYTES_LIMIT = 200_000;
export function formatConsoleOutput(values: unknown[]): string {
return values.map((value) => (typeof value === "string" ? value : String(value))).join(" ");
@@ -33,7 +33,7 @@ export function printJson(value: unknown, options: OutputOptions = {}) {
console.log(json.trimEnd());
}
export function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
function protectLargeOutput(result: unknown, options: OutputOptions = {}) {
if (options.allowFull || options.outputFile) return;
const bodyBytes = Buffer.byteLength(JSON.stringify(result), "utf-8");
if (bodyBytes > DEFAULT_OUTPUT_BYTES_LIMIT) {
@@ -87,6 +87,8 @@ Usage:
seal-use config paths
seal-use config get
seal-use config mode <stateful|stateless> [--corp <corpId>]
seal-use config test-dir [<path>|--clear]
seal-use config lint [status|enable|disable] [--linter <name|path>] [--min-score <score>]
seal-use update [--check] [--force] [--version <v>]
seal-use update check
seal-use update changelog [--limit <n>]
@@ -116,11 +118,15 @@ Usage:
seal-use billing status [--corp <corpId>]
seal-use billing plans [--corp <corpId>]
seal-use billing features [--corp <corpId>]
seal-use webhook ready [<材料包.zip>] [--corp <corpId>]
seal-use webhook status [<材料包.zip>] [--corp <corpId>]
seal-use webhook list [--query <text>] [--show-secret] [--corp <corpId>]
seal-use webhook get|find <idOrName> [--show-secret] [--corp <corpId>]
seal-use webhook add --name <name> --result-url <url> [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>] [--corp <corpId>]
seal-use webhook update <idOrName> [--name <name>] [--result-url <url>] [--mode assisted|semi_automatic|fully_automatic] [--auto-approval-rate 60] [--secret <secret>|--rotate-secret] [--corp <corpId>]
seal-use webhook delete <idOrName> --yes [--corp <corpId>]
seal-use webhook material-pack preview <材料包.zip|信息表.xlsx> [--corp <corpId>]
seal-use webhook material-pack push <材料包.zip|信息表.xlsx> [--webhook <idOrName>] [--corp <corpId>]
seal-use deploy hosecloud requirements [--corp <corpId>]
seal-use deploy hosecloud list [--corp <corpId>]
seal-use deploy hosecloud get <sign-key> [--corp <corpId>]
@@ -147,12 +153,14 @@ Usage:
seal-use approval-runs summary [--date YYYY-MM-DD] [--timezone Asia/Shanghai] [--corp <corpId>]
seal-use approval-runs stats [--since 3months] [--dedupe-by sourceDocumentSN|sourceDocumentId|id] [--corp <corpId>]
seal-use approval-runs count [--status APPROVED] [--corp <corpId>]
seal-use approval-runs export [--start <YYYY-MM-DD|ms>] [--end <YYYY-MM-DD|ms>] [--limit <n>] [--downloads] [--out <file>] [--corp <corpId>]
seal-use approval-runs list|search [--query text] [--humanResult 驳回] [--manualApprovalStatus TERMINATED] [--startDate ms] [--endDate ms] [--limit 20] [--includeBridge true] [--corp <corpId>]
seal-use approval-runs pick --sn <documentSN> [--batch <batchId>] [--latest] [--fields recordId,status,aiDecision] [--corp <corpId>]
seal-use approval-runs get <recordId> [--summary] [--fields metadata|document.fields,result.summary] [--full] [--output-file file.json] [--corp <corpId>]
seal-use approval-runs cited-rules <recordId> [--corp <corpId>]
seal-use approval-runs document-summary <recordId> [--corp <corpId>]
seal-use approval-runs attachments <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs attachments download <recordId> [--all] [--name <name>] [--out-dir <dir>] [--corp <corpId>]
seal-use approval-runs result <recordId> [--summary] [--corp <corpId>]
seal-use approval-runs url [--corp <corpId>]
seal-use approval-runs url <recordId> [--corp <corpId>]
+45 -2
View File
@@ -3,6 +3,7 @@
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { createSealClient } from "../core/http/factory.js";
import type { CorpConfig } from "../core/config/types.js";
import { VERSION } from "../version.js";
import { handleApprovalRunsCommand } from "./commands/approval-runs.js";
import { handleAuthCommand } from "./commands/auth.js";
@@ -28,7 +29,7 @@ import { handleToolCommand } from "./commands/tool.js";
import { handleToolsListCommand } from "./commands/tools.js";
import { handleUpdateCommand } from "./commands/update.js";
import { handleUsersCommand } from "./commands/users.js";
import { handleWebhookCommand } from "./commands/webhook.js";
import { handleWebhookCommand, handleWebhookMaterialPackPreview } from "./commands/webhook.js";
import { selectCorp } from "./helpers.js";
import { booleanOption, numberOption, parseArgs, stringOption } from "./parser.js";
import {
@@ -44,6 +45,7 @@ const DEFAULT_APP_ROOT = dirname(dirname(dirname(fileURLToPath(import.meta.url))
const KNOWN_AREAS = new Set([
"config",
"service",
"stop",
"http",
"serve",
"update",
@@ -77,9 +79,23 @@ const KNOWN_AREAS = new Set([
export type { CliResult, CliRunOptions } from "./types.js";
const STANDING_COMMANDS = new Set(["http", "server", "web", "mcp"]);
function isStandingCommand(argv: string[]): boolean {
if (!argv.length) return false;
const first = argv[0]?.toLowerCase();
const second = argv[1]?.toLowerCase();
if (first && STANDING_COMMANDS.has(first)) return true;
if ((first === "service" || first === "daemon") && second === "run") return true;
return false;
}
let runQueue = Promise.resolve();
export function runCli(argv: string[], options: CliRunOptions = {}): Promise<CliResult> {
if (isStandingCommand(argv)) {
return runCliOnce(argv, options);
}
const run = runQueue.then(() => runCliOnce(argv, options));
runQueue = run.then(
() => undefined,
@@ -155,6 +171,13 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
throw new Error(`Unknown command: ${args.command.join(" ")}. Run 'seal-use help' for available commands.`);
}
if (area === "webhook" && action === "material-pack" && maybeName === "preview") {
const filePath = args.command[3] ?? stringOption(args.options.file) ?? stringOption(args.options.input);
if (!filePath) throw new Error("Usage: seal-use webhook material-pack preview <材料包.zip>");
await handleWebhookMaterialPackPreview(filePath);
return;
}
if (area === "openapi") {
handleOpenApiCommand(args);
return;
@@ -186,7 +209,12 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
}
if (area === "service") {
await handleServiceCommand(action, runtime);
await handleServiceCommand(action, runtime, args);
return;
}
if (area === "stop") {
await handleServiceCommand("stop", runtime, args);
return;
}
@@ -241,6 +269,21 @@ async function dispatch(argv: string[], runtime: CliRuntime) {
return;
}
if (area === "rules" && action === "lint" && ("file" in args.options || "f" in args.options)) {
let corp: CorpConfig;
try {
corp = selectCorp(stringOption(args.options.corp));
} catch {
corp = {
id: "local",
name: "Local Workspace",
source: { type: "native" }
} as any;
}
await handleRulesCommand(action, maybeName, null as any, corp, args);
return;
}
const corp = selectCorp(stringOption(args.options.corp));
if (area === "source") {
+67 -1
View File
@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test";
import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { serviceStatus } from "./service.js";
import { serviceStatus, readServiceLogs, runServiceCommand } from "./service.js";
const tempDirs: string[] = [];
@@ -27,5 +27,71 @@ describe("service lifecycle state", () => {
expect(status.running).toBe(false);
expect(status.pid).toBeUndefined();
expect(status.port).toBe(8787);
expect(status.host).toBe("127.0.0.1");
expect(status.url).toBeUndefined();
});
test("respects custom port and host configuration", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const status = serviceStatus({
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir,
version: "0.10.7",
port: 9090,
host: "0.0.0.0"
});
expect(status.port).toBe(9090);
expect(status.host).toBe("0.0.0.0");
});
test("reads service log file lines safely", () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const emptyLogs = readServiceLogs({
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(emptyLogs.lines).toEqual([]);
expect(emptyLogs.totalLines).toBe(0);
const logFile = join(stateDir, "service.log");
writeFileSync(logFile, "line 1\nline 2\nline 3\nline 4\nline 5\n");
const logs = readServiceLogs(
{
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
},
3
);
expect(logs.totalLines).toBe(5);
expect(logs.lines).toEqual(["line 3", "line 4", "line 5"]);
});
test("runServiceCommand handles logs and status actions", async () => {
const stateDir = mkdtempSync(join(tmpdir(), "seal-use-service-"));
tempDirs.push(stateDir);
const status = await runServiceCommand("status", {
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(status).toHaveProperty("running");
const logs = await runServiceCommand("logs", {
appRoot: "/tmp/seal-use",
entryFile: "/tmp/seal-use/src/cli.ts",
stateDir
});
expect(logs).toHaveProperty("lines");
});
});
+106 -12
View File
@@ -1,6 +1,7 @@
import { spawn, execFileSync } from "node:child_process";
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { startHttpServer, DEFAULT_HTTP_PORT, DEFAULT_HTTP_HOST } from "../http/server.js";
export type ServiceConfig = {
appRoot: string;
@@ -11,12 +12,14 @@ export type ServiceConfig = {
command: string;
args?: string[];
};
port?: number;
host?: string;
};
export async function runServiceCommand(
action: string | undefined,
config: ServiceConfig,
options: { quiet?: boolean } = {}
options: { quiet?: boolean; maxLines?: number } = {}
) {
switch (action) {
case "run":
@@ -25,31 +28,55 @@ export async function runServiceCommand(
case "start":
return startService(config);
case "stop":
case "kill":
case "down":
case "shutdown":
return stopService(config, options);
case "restart":
stopService(config, { quiet: true });
return startService(config);
case "logs":
case "log":
return readServiceLogs(config, options.maxLines);
case "status":
case undefined:
return serviceStatus(config);
default:
throw new Error("Usage: seal-use service <start|stop|restart|status>");
throw new Error("Usage: seal-use service <start|stop|restart|status|logs>");
}
}
export function serviceStatus(config: ServiceConfig) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const pid = readServicePid(pidFile);
const running = pid ? isSealHomeProcess(pid, config.appRoot) : false;
if (pid && !running) {
rmSync(pidFile, { force: true });
if (!running) {
if (pid) rmSync(pidFile, { force: true });
if (existsSync(metaFile)) rmSync(metaFile, { force: true });
}
let storedMeta: { port?: number; host?: string; version?: string } | undefined;
if (running && existsSync(metaFile)) {
try {
storedMeta = JSON.parse(readFileSync(metaFile, "utf8"));
} catch {
// ignore
}
}
const port = config.port ?? storedMeta?.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? storedMeta?.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
const version = config.version ?? storedMeta?.version;
return {
running,
pid: running ? pid : undefined,
version: config.version,
version,
port,
host,
url: running ? `http://${host}:${port}` : undefined,
appRoot: config.appRoot,
stateDir: config.stateDir,
pidFile,
@@ -57,28 +84,84 @@ export function serviceStatus(config: ServiceConfig) {
};
}
export function readServiceLogs(config: ServiceConfig, maxLines = 50) {
const logFile = getLogFile(config);
if (!existsSync(logFile)) {
return {
logFile,
lines: [],
totalLines: 0
};
}
const content = readFileSync(logFile, "utf8");
const allLines = content.split("\n").filter(Boolean);
const lines = allLines.slice(-maxLines);
return {
logFile,
lines,
totalLines: allLines.length
};
}
async function runService(config: ServiceConfig) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const logFile = getLogFile(config);
ensureStateDir(config.stateDir);
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
appendLog(logFile, `running pid=${process.pid}`);
const cleanup = () => {
const port = config.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = config.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
writeFileSync(pidFile, `${process.pid}\n`, { mode: 0o600 });
writeFileSync(
metaFile,
JSON.stringify(
{
pid: process.pid,
port,
host,
version: config.version,
startedAt: new Date().toISOString()
},
null,
2
),
{ mode: 0o600 }
);
appendLog(logFile, `service starting on http://${host}:${port} pid=${process.pid}`);
let server: Awaited<ReturnType<typeof startHttpServer>> | null = null;
try {
server = await startHttpServer({ port, host, silent: true });
appendLog(logFile, `service listening pid=${process.pid}`);
} catch (err: unknown) {
appendLog(logFile, `service failed to bind port ${port}: ${err instanceof Error ? err.message : String(err)}`);
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
}
throw err;
}
const cleanup = () => {
if (server) {
server.close();
server = null;
}
if (readServicePid(pidFile) === process.pid) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
}
appendLog(logFile, `stopped pid=${process.pid}`);
};
await new Promise<void>((resolve) => {
let stopped = false;
const heartbeat = setInterval(() => {}, 60_000);
const stop = () => {
if (stopped) return;
stopped = true;
cleanup();
clearInterval(heartbeat);
process.off("SIGTERM", stop);
process.off("SIGINT", stop);
resolve();
@@ -96,11 +179,15 @@ function startService(config: ServiceConfig) {
}
const launcher = config.launcher ?? { command: process.execPath, args: [config.entryFile] };
const child = spawn(launcher.command, [
const serviceArgs = [
...(launcher.args ?? []),
"service",
"run"
], {
];
if (config.port) serviceArgs.push("--port", String(config.port));
if (config.host) serviceArgs.push("--host", String(config.host));
const child = spawn(launcher.command, serviceArgs, {
cwd: config.appRoot,
detached: true,
stdio: ["ignore", "ignore", "ignore"],
@@ -116,14 +203,17 @@ function startService(config: ServiceConfig) {
function stopService(config: ServiceConfig, options: { quiet?: boolean } = {}) {
const pidFile = getPidFile(config);
const metaFile = getMetaFile(config);
const pid = readServicePid(pidFile);
if (!pid || !isSealHomeProcess(pid, config.appRoot)) {
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
return options.quiet ? undefined : { stopped: false, reason: "not running" };
}
process.kill(pid, "SIGTERM");
rmSync(pidFile, { force: true });
rmSync(metaFile, { force: true });
appendLog(getLogFile(config), `stop requested pid=${pid}`);
return options.quiet ? undefined : { stopped: true, pid };
}
@@ -156,6 +246,10 @@ function getPidFile(config: ServiceConfig) {
return join(config.stateDir, "service.pid");
}
function getMetaFile(config: ServiceConfig) {
return join(config.stateDir, "service.json");
}
function getLogFile(config: ServiceConfig) {
return join(config.stateDir, "service.log");
}
-4
View File
@@ -39,10 +39,6 @@ export async function getSealSessionForCorp(corp: CorpConfig): Promise<SealSessi
return next;
}
export async function getSealToken(corp: CorpConfig): Promise<string> {
return (await getSealSessionForCorp(corp)).token;
}
export async function resolveSealEnterpriseConfig(
corp: CorpConfig
): Promise<SealEnterpriseConfig> {
+47 -12
View File
@@ -84,39 +84,74 @@ describe("loadCorpConfigs", () => {
expect(loadCorpConfigs()).toEqual([]);
});
test("merges local and user enterprise directories with user configs taking precedence", () => {
test("does not load current directory enterprises by default, only reading user directory", () => {
const workspace = makeTempDir();
const workspaceEnterprises = join(workspace, "enterprises");
const userDir = makeTempDir();
mkdirSync(workspaceEnterprises, { recursive: true });
writeCorpConfig(join(workspaceEnterprises, "shared.json"), "shared", "Workspace");
writeCorpConfig(join(userDir, "shared.json"), "shared", "User");
writeCorpConfig(join(workspaceEnterprises, "cwd-only.json"), "cwd-only", "CWD Enterprise");
writeCorpConfig(join(userDir, "user-only.json"), "user-only", "User Only");
process.chdir(workspace);
process.env.SEAL_USE_USER_ENTERPRISES_DIR = userDir;
expect(loadCorpConfigs().map((corp) => [corp.id, corp.name])).toEqual([
["shared", "User"],
["user-only", "User Only"]
]);
// cwd enterprises/ should NOT be loaded by default
expect(loadCorpConfigs().map((corp) => corp.id)).toEqual(["user-only"]);
});
test("loads testEnterprisesDir from global config when specified", () => {
const testDir = makeTempDir();
const userDir = makeTempDir();
writeCorpConfig(join(testDir, "test-corp.json"), "test-corp", "Test Corp");
writeCorpConfig(join(userDir, "user-corp.json"), "user-corp", "User Corp");
const configFile = join(makeTempDir(), "config.json");
process.env.SEAL_USE_CONFIG_FILE = configFile;
process.env.SEAL_USE_USER_ENTERPRISES_DIR = userDir;
saveGlobalConfig({ testEnterprisesDir: testDir });
const corps = loadCorpConfigs();
expect(corps.map((corp) => corp.id).sort()).toEqual(["test-corp", "user-corp"].sort());
});
test("defaults global config to stateless", () => {
process.env.SEAL_USE_CONFIG_FILE = join(makeTempDir(), "config.json");
expect(loadGlobalConfig()).toEqual({ stateful: false });
expect(loadGlobalConfig()).toEqual({
stateful: false,
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
test("saves and loads the global state mode", () => {
test("saves and loads the global state mode and testEnterprisesDir", () => {
const file = join(makeTempDir(), "nested", "config.json");
process.env.SEAL_USE_CONFIG_FILE = file;
expect(saveGlobalConfig({ stateful: true, defaultCorpId: "corp-a" })).toEqual({
expect(saveGlobalConfig({ stateful: true, defaultCorpId: "corp-a", testEnterprisesDir: "/tmp/test-corps" })).toEqual({
stateful: true,
defaultCorpId: "corp-a"
defaultCorpId: "corp-a",
testEnterprisesDir: "/tmp/test-corps",
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
expect(resolveGlobalConfigFile()).toBe(file);
expect(loadGlobalConfig()).toEqual({ stateful: true, defaultCorpId: "corp-a" });
expect(loadGlobalConfig()).toEqual({
stateful: true,
defaultCorpId: "corp-a",
testEnterprisesDir: "/tmp/test-corps",
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
});
+15 -20
View File
@@ -1,9 +1,8 @@
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, join } from "node:path";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigSchema } from "./types.js";
import { CorpConfig, CorpConfigSchema, GlobalConfig, GlobalConfigInput, GlobalConfigSchema } from "./types.js";
const ENTERPRISES_DIR = "enterprises";
const CONFIG_ENV = "SEAL_USE_ENTERPRISES_DIR";
const LEGACY_CONFIG_ENV = "SEAL_HOME_ENTERPRISES_DIR";
const USER_DIR_ENV = "SEAL_USE_USER_ENTERPRISES_DIR";
@@ -13,7 +12,6 @@ const LEGACY_GLOBAL_CONFIG_ENV = "SEAL_HOME_CONFIG_FILE";
export const PRIMARY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-use", "enterprises");
export const LEGACY_USER_ENTERPRISES_DIR = join(homedir(), ".config", "seal-home", "enterprises");
export const USER_ENTERPRISES_DIR = PRIMARY_USER_ENTERPRISES_DIR;
const PRIMARY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-use", "config.json");
const LEGACY_GLOBAL_CONFIG_FILE = join(homedir(), ".config", "seal-home", "config.json");
@@ -39,18 +37,21 @@ export function resolveEnterprisesDir(): string | undefined {
return resolveEnterprisesDirs()[0];
}
export function resolveEnterprisesDirs(): string[] {
function resolveEnterprisesDirs(): string[] {
const configured = (process.env[CONFIG_ENV] ?? process.env[LEGACY_CONFIG_ENV])?.trim();
if (configured) return existsSync(configured) ? [configured] : [];
const configuredUserDir = (process.env[USER_DIR_ENV] ?? process.env[LEGACY_USER_DIR_ENV])?.trim();
if (configuredUserDir) {
return [ENTERPRISES_DIR, configuredUserDir].filter((dir) => existsSync(dir));
}
const userDirs = configuredUserDir
? (existsSync(configuredUserDir) ? [configuredUserDir] : [])
: [PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
const dirs = [ENTERPRISES_DIR, PRIMARY_USER_ENTERPRISES_DIR, LEGACY_USER_ENTERPRISES_DIR];
const globalConfig = loadGlobalConfig();
const testDir = globalConfig.testEnterprisesDir?.trim();
const candidates = testDir ? [testDir, ...userDirs] : userDirs;
const uniqueExisting: string[] = [];
for (const d of dirs) {
for (const d of candidates) {
if (existsSync(d) && !uniqueExisting.includes(d)) {
uniqueExisting.push(d);
}
@@ -58,27 +59,21 @@ export function resolveEnterprisesDirs(): string[] {
return uniqueExisting;
}
export function resolvePrimaryEnterprisesDir(): string | undefined {
const configured = (process.env[CONFIG_ENV] ?? process.env[LEGACY_CONFIG_ENV])?.trim();
if (configured) return existsSync(configured) ? configured : undefined;
if (existsSync(ENTERPRISES_DIR)) return ENTERPRISES_DIR;
if (existsSync(PRIMARY_USER_ENTERPRISES_DIR)) return PRIMARY_USER_ENTERPRISES_DIR;
if (existsSync(LEGACY_USER_ENTERPRISES_DIR)) return LEGACY_USER_ENTERPRISES_DIR;
return undefined;
}
export function resolveWritableEnterprisesDir(): string {
const configured = (process.env[CONFIG_ENV] ?? process.env[LEGACY_CONFIG_ENV])?.trim();
if (configured) return configured;
const configuredUserDir = (process.env[USER_DIR_ENV] ?? process.env[LEGACY_USER_DIR_ENV])?.trim();
if (configuredUserDir) return configuredUserDir;
const testDir = loadGlobalConfig().testEnterprisesDir?.trim();
if (testDir && existsSync(testDir)) return testDir;
return PRIMARY_USER_ENTERPRISES_DIR;
}
export function getEnterprisesDirCandidates(): string[] {
const testDir = loadGlobalConfig().testEnterprisesDir?.trim();
return [
`${CONFIG_ENV}=<path>`,
ENTERPRISES_DIR,
...(testDir ? [`testEnterprisesDir: ${testDir}`] : []),
PRIMARY_USER_ENTERPRISES_DIR,
LEGACY_USER_ENTERPRISES_DIR
];
@@ -101,7 +96,7 @@ export function loadGlobalConfig(): GlobalConfig {
return GlobalConfigSchema.parse(JSON.parse(readFileSync(file, "utf-8")));
}
export function saveGlobalConfig(config: GlobalConfig): GlobalConfig {
export function saveGlobalConfig(config: GlobalConfigInput): GlobalConfig {
const normalized = GlobalConfigSchema.parse(config);
const configured = (process.env[GLOBAL_CONFIG_ENV] ?? process.env[LEGACY_GLOBAL_CONFIG_ENV])?.trim();
const file = configured || PRIMARY_GLOBAL_CONFIG_FILE;
+14 -2
View File
@@ -82,7 +82,14 @@ describe("CorpConfigSchema", () => {
describe("GlobalConfigSchema", () => {
test("defaults to stateless mode", () => {
expect(GlobalConfigSchema.parse({})).toEqual({ stateful: false });
expect(GlobalConfigSchema.parse({})).toEqual({
stateful: false,
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
test("accepts a stateful default enterprise", () => {
@@ -91,7 +98,12 @@ describe("GlobalConfigSchema", () => {
defaultCorpId: "corp-a"
})).toEqual({
stateful: true,
defaultCorpId: "corp-a"
defaultCorpId: "corp-a",
lint: {
enabled: false,
activeLinter: "builtin",
minScore: 0
}
});
});
});
+15 -1
View File
@@ -84,9 +84,21 @@ export const CorpConfigSchema = z.object({
auth: CorpAuthConfigSchema
});
export const GlobalLintConfigSchema = z.object({
enabled: z.boolean().default(false),
activeLinter: z.string().default("builtin"),
minScore: z.number().min(0).max(100).default(0)
}).default({
enabled: false,
activeLinter: "builtin",
minScore: 0
});
export const GlobalConfigSchema = z.object({
stateful: z.boolean().default(false),
defaultCorpId: z.string().min(1).optional()
defaultCorpId: z.string().min(1).optional(),
testEnterprisesDir: z.string().min(1).optional(),
lint: GlobalLintConfigSchema
});
export type HoseSealSource = z.infer<typeof HoseSealSourceSchema>;
@@ -95,4 +107,6 @@ export type NativeSealSource = z.infer<typeof NativeSealSourceSchema>;
export type SealSource = z.infer<typeof SealSourceSchema>;
export type CorpAuthConfig = z.infer<typeof CorpAuthConfigSchema>;
export type CorpConfig = z.infer<typeof CorpConfigSchema>;
export type GlobalLintConfig = z.infer<typeof GlobalLintConfigSchema>;
export type GlobalConfig = z.infer<typeof GlobalConfigSchema>;
export type GlobalConfigInput = z.input<typeof GlobalConfigSchema>;
+2 -2
View File
@@ -36,11 +36,11 @@ export function getDefaultGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "seal-use");
}
export function getLegacyGlobalSkillDir(): string {
function getLegacyGlobalSkillDir(): string {
return join(homedir(), ".agents", "skills", "seal-home");
}
export function cleanLegacySkillDir(): boolean {
function cleanLegacySkillDir(): boolean {
const legacyDir = getLegacyGlobalSkillDir();
if (existsSync(legacyDir)) {
try {
@@ -0,0 +1,191 @@
import { describe, expect, test } from "bun:test";
import { existsSync, rmSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
import ExcelJS from "exceljs";
import {
getRuleBriefTitle,
normalizeManualApprovalStatus,
normalizeTimestamp,
resolveOutputFilePath,
exportApprovalRunsToExcel
} from "./approval-runs-export.js";
import type { CorpConfig } from "../../core/config/types.js";
describe("approval-runs-export helpers", () => {
test("normalizeTimestamp converts YYYY-MM-DD to Beijing time epoch string", () => {
const start = normalizeTimestamp("2026-08-07", false);
expect(start).toBe(String(new Date("2026-08-07T00:00:00.000+08:00").getTime()));
const end = normalizeTimestamp("2026-08-07", true);
expect(end).toBe(String(new Date("2026-08-07T23:59:59.999+08:00").getTime()));
// 10-digit epoch
expect(normalizeTimestamp("1786032000")).toBe("1786032000000");
// 13-digit epoch
expect(normalizeTimestamp("1786032000123")).toBe("1786032000123");
// number
expect(normalizeTimestamp(1786032000000)).toBe("1786032000000");
// undefined/empty
expect(normalizeTimestamp(undefined)).toBeUndefined();
expect(normalizeTimestamp("")).toBeUndefined();
});
test("normalizeManualApprovalStatus maps human words to backend enum", () => {
expect(normalizeManualApprovalStatus("APPROVED")).toEqual(["APPROVED"]);
expect(normalizeManualApprovalStatus("已通过")).toEqual(["APPROVED"]);
expect(normalizeManualApprovalStatus("已支付/审批完成")).toEqual(["APPROVED"]);
expect(normalizeManualApprovalStatus("TERMINATED")).toEqual(["TERMINATED"]);
expect(normalizeManualApprovalStatus("被驳回")).toEqual(["TERMINATED"]);
expect(normalizeManualApprovalStatus("处理中")).toEqual(["PROCESSING"]);
expect(normalizeManualApprovalStatus("已撤回")).toEqual(["CANCELLED"]);
expect(normalizeManualApprovalStatus(["已通过", "被驳回"])).toEqual(["APPROVED", "TERMINATED"]);
expect(normalizeManualApprovalStatus(undefined)).toBeUndefined();
});
test("getRuleBriefTitle extracts clean concise summary", () => {
expect(getRuleBriefTitle("rule-0", "所有单据:报销公司不是浙江大黄蜂建筑机械设备有限公司时提示")).toBe(
"所有单据:报销公司不是浙江大黄蜂建筑机械设备"
);
expect(getRuleBriefTitle("rule-1", "### 发票合规校验\n第二行内容")).toBe("发票合规校验");
expect(getRuleBriefTitle("rule-2", undefined, "通用范围")).toBe("rule-2 (通用范围)");
});
test("resolveOutputFilePath supports custom path, downloads, and default exports dir", () => {
const custom = resolveOutputFilePath({
outputFile: "/tmp/custom-export.xlsx",
corpName: "TestCorp",
recordCount: 10
});
expect(custom).toBe("/tmp/custom-export.xlsx");
const dl = resolveOutputFilePath({
toDownloads: true,
corpName: "大黄蜂",
dateTag: "2026-08-07至今",
recordCount: 50
});
expect(dl).toContain("Downloads/大黄蜂_审核记录_2026-08-07至今_50条.xlsx");
});
});
describe("exportApprovalRunsToExcel integration", () => {
const testCorp: CorpConfig = {
id: "test-corp",
name: "测试企业",
seal: {
endpoints: {
approvalStylePreferences: "api/v1/agent/ai-approval/config"
}
},
source: {
type: "direct",
token: "test-token",
sealUrl: "https://mock.sealai.cc",
expiresIn: 3600,
staffId: "direct"
},
auth: {
refreshTtl: 300
}
};
test("generates valid formatted excel workbook", async () => {
const mockClient = {
get: (url: string, opts?: any) => {
if (url.includes("api/v1/rules")) {
return {
json: async () => ({
rules: [
{ id: "r1", code: 0, description: "发票与收据真实性核验", scope: "全局", strictness: "SHOULD_FOLLOW" },
{ id: "r2", code: 1, description: "差旅标准不得超标", scope: "差旅", strictness: "MUST_FOLLOW" }
]
})
};
}
if (url.includes("api/v1/approvals")) {
return {
json: async () => ({
total: 2,
records: [
{
id: "run-1",
sourceDocumentSN: "B26001",
status: "completed",
taskMode: "assisted",
sourceSystem: "hosecloud",
document: {
fields: [{ label: "单据模板", value: "差旅报销单" }]
},
result: {
decision: "APPROVE",
rulesResult: [{ id: "rule-0", checkResult: "PASS" }]
},
manualApprovalRecord: {
status: { label: "已支付/审批完成", type: "APPROVED" }
},
createdAt: 1788760000000,
updatedAt: 1788760020000
},
{
id: "run-2",
sourceDocumentSN: "B26002",
status: "completed",
taskMode: "assisted",
sourceSystem: "hosecloud",
document: {
fields: [{ label: "单据模板", value: "差旅报销单" }]
},
result: {
decision: "REJECT",
rulesResult: [{ id: "rule-0", checkResult: "FAIL" }]
},
manualApprovalRecord: {
status: { label: "被驳回", type: "TERMINATED" },
rejectComment: "请上传正确的行程单凭据"
},
createdAt: 1788760000000,
updatedAt: 1788760030000
}
]
})
};
}
throw new Error(`Unexpected url: ${url}`);
}
} as any;
const tmpOut = join(tmpdir(), `test-export-${Date.now()}.xlsx`);
try {
const result = await exportApprovalRunsToExcel(mockClient, testCorp, {
outputFile: tmpOut,
limit: 10,
pageDelayMs: 0
});
expect(result.recordCount).toBe(2);
expect(result.ruleColumnCount).toBe(2);
expect(result.statusCounts["已支付/审批完成"]).toBe(1);
expect(result.statusCounts["被驳回"]).toBe(1);
expect(result.rejectReasonCount).toBe(1);
expect(existsSync(tmpOut)).toBe(true);
// Verify Excel contents with ExcelJS
const wb = new ExcelJS.Workbook();
await wb.xlsx.readFile(tmpOut);
const ws = wb.worksheets[0]!;
expect(ws.rowCount).toBe(3); // 1 header + 2 rows
expect(ws.getRow(1).getCell(1).value).toBe("单据编号");
expect(ws.getRow(2).getCell(1).value).toBe("B26001");
expect(ws.getRow(2).getCell(9).value).toBe("已支付/审批完成");
expect(ws.getRow(3).getCell(1).value).toBe("B26002");
expect(ws.getRow(3).getCell(9).value).toBe("被驳回");
expect(ws.getRow(3).getCell(10).value).toBe("请上传正确的行程单凭据");
} finally {
if (existsSync(tmpOut)) {
rmSync(tmpOut, { force: true });
}
}
});
});
+531
View File
@@ -0,0 +1,531 @@
import { existsSync, mkdirSync, statSync } from "node:fs";
import { homedir } from "node:os";
import { dirname, resolve } from "node:path";
import ExcelJS from "exceljs";
import type { KyInstance } from "ky";
import type { CorpConfig } from "../../core/config/types.js";
import * as api from "./api.js";
import type { ApprovalRun, ApprovalRunListData } from "./types.js";
export interface ApprovalRunsExportOptions {
limit?: number;
startDate?: string | number;
endDate?: string | number;
status?: string;
manualApprovalStatus?: string | string[];
includeCompletedOnly?: boolean;
outputFile?: string;
toDownloads?: boolean;
pageSize?: number;
pageDelayMs?: number;
}
export interface ApprovalRunsExportResult {
filePath: string;
corpId: string;
corpName: string;
recordCount: number;
ruleColumnCount: number;
statusCounts: Record<string, number>;
rejectReasonCount: number;
fileSizeBytes: number;
exportedAt: string;
}
export function normalizeTimestamp(val?: string | number, endOfDay = false): string | undefined {
if (val === undefined || val === null || val === "") return undefined;
if (typeof val === "number") return String(val);
const str = String(val).trim();
if (!str) return undefined;
if (/^\d{10,13}$/.test(str)) {
return str.length === 10 ? `${str}000` : str;
}
if (/^\d{4}-\d{2}-\d{2}$/.test(str)) {
const timeSuffix = endOfDay ? "T23:59:59.999+08:00" : "T00:00:00.000+08:00";
const parsed = new Date(`${str}${timeSuffix}`).getTime();
if (!Number.isNaN(parsed)) return String(parsed);
}
const parsed = new Date(str).getTime();
if (!Number.isNaN(parsed)) return String(parsed);
return str;
}
export function normalizeManualApprovalStatus(status?: string | string[]): string[] | undefined {
if (!status) return undefined;
const rawList = Array.isArray(status) ? status : [status];
const list: string[] = [];
for (const s of rawList) {
const normalized = s.trim().toUpperCase();
if (["APPROVED", "已通过", "已完成", "已支付", "已支付/审批完成"].includes(normalized)) {
list.push("APPROVED");
} else if (["TERMINATED", "REJECTED", "REJECT", "驳回", "被驳回", "已驳回"].includes(normalized)) {
list.push("TERMINATED");
} else if (["PROCESSING", "审批中", "处理中"].includes(normalized)) {
list.push("PROCESSING");
} else if (["CANCELLED", "CANCELED", "已撤回", "已撤销"].includes(normalized)) {
list.push("CANCELLED");
} else if (normalized) {
list.push(normalized);
}
}
return list.length > 0 ? list : undefined;
}
export function getRuleBriefTitle(ruleId: string, desc?: string, scope?: string): string {
if (!desc) return scope ? `${ruleId} (${scope})` : ruleId;
const firstSentence = desc.split(/[。\n\r;;!!]/)[0]?.trim() || desc.trim();
const clean = firstSentence.replace(/[*#`_]/g, "").trim();
return clean.slice(0, 22);
}
export function resolveOutputFilePath(options: {
outputFile?: string;
toDownloads?: boolean;
corpName: string;
dateTag?: string;
recordCount: number;
}): string {
if (options.outputFile) {
const p = resolve(options.outputFile);
const dir = dirname(p);
if (!existsSync(dir)) {
mkdirSync(dir, { recursive: true });
}
return p;
}
const safeCorpName = options.corpName.replace(/[/\\?%*:|"<>]/g, "_").trim() || "审批记录";
const dateTag = options.dateTag || new Date().toISOString().slice(0, 10);
const countTag = options.recordCount > 0 ? `${options.recordCount}条` : "空数据";
const fileName = `${safeCorpName}_审核记录_${dateTag}_${countTag}.xlsx`;
let targetDir: string;
if (options.toDownloads) {
targetDir = resolve(homedir(), "Downloads");
} else {
targetDir = resolve(process.cwd(), "exports");
}
if (!existsSync(targetDir)) {
mkdirSync(targetDir, { recursive: true });
}
return resolve(targetDir, fileName);
}
export async function exportApprovalRunsToExcel(
client: KyInstance,
corp: CorpConfig,
options: ApprovalRunsExportOptions = {}
): Promise<ApprovalRunsExportResult> {
const corpName = corp.name || corp.id;
const pageSize = options.pageSize ?? 100;
const pageDelayMs = options.pageDelayMs ?? 250;
const limit = options.limit ?? 100000;
const startDateTs = normalizeTimestamp(options.startDate, false);
const endDateTs = normalizeTimestamp(options.endDate, true);
const manualStatusFilter = normalizeManualApprovalStatus(options.manualApprovalStatus);
// 1. 动态加载企业规则集,生成列定义
console.error(`正在加载企业「${corpName}」审核规则集...`);
const ruleMap = new Map<string, { id: string; code: string; title: string; desc: string }>();
try {
const rulesData = await api.listApprovalRules(client);
rulesData.rules.forEach((r, idx) => {
const runtimeId = `rule-${r.code ?? idx}`;
const title = getRuleBriefTitle(runtimeId, r.description, r.scope);
ruleMap.set(runtimeId, {
id: runtimeId,
code: String(r.code ?? idx),
title: `[${runtimeId}] ${title}`,
desc: r.description
});
});
} catch (err: any) {
console.error(`⚠️ 加载规则字典失败: ${err.message},将仅导出基础信息列。`);
}
const sortedRuleKeys = Array.from(ruleMap.keys()).sort((a, b) => {
const numA = parseInt(a.replace(/\D/g, ""), 10) || 0;
const numB = parseInt(b.replace(/\D/g, ""), 10) || 0;
return numA - numB;
});
console.error(`已就绪 ${sortedRuleKeys.length} 个规则列。开始拉取单据...`);
// 2. 温和分页拉取单据记录
const fetchedRecords: ApprovalRun[] = [];
let offset = 0;
let totalAvailable = 0;
while (fetchedRecords.length < limit) {
let batch: ApprovalRunListData | undefined;
let retries = 3;
while (retries > 0) {
try {
batch = await api.listApprovalRuns(client, {
limit: pageSize,
offset,
startDate: startDateTs,
endDate: endDateTs,
status: options.status,
manualApprovalStatus: manualStatusFilter
});
break;
} catch (e: any) {
retries--;
console.error(`分页拉取失败 (offset=${offset}): ${e.message},剩余重试 ${retries} 次...`);
if (retries === 0) throw e;
await new Promise((r) => setTimeout(r, 1000));
}
}
if (!batch || !batch.records || batch.records.length === 0) break;
totalAvailable = batch.total ?? totalAvailable;
for (const r of batch.records) {
if (options.includeCompletedOnly && r.status !== "completed") {
continue;
}
// 如果是已完成单据但列表未附带规则结果,做安全补查
if (r.status === "completed" && (!r.result || !(r.result as any).rulesResult)) {
try {
const full = await api.getApprovalRun(client, r.id);
fetchedRecords.push(full);
} catch {
fetchedRecords.push(r);
}
} else {
fetchedRecords.push(r);
}
if (fetchedRecords.length >= limit) break;
}
offset += batch.records.length;
const currentProgress = totalAvailable > 0 ? ((offset / totalAvailable) * 100).toFixed(1) : "-";
if (offset % 500 === 0 || offset >= totalAvailable || fetchedRecords.length >= limit) {
console.error(
`[进度] 已读取单据: ${offset}/${totalAvailable} (${currentProgress}%),有效加入: ${fetchedRecords.length} 条`
);
}
if (batch.records.length < pageSize || offset >= totalAvailable) {
break;
}
if (pageDelayMs > 0) {
await new Promise((r) => setTimeout(r, pageDelayMs));
}
}
console.error(`成功拉取 ${fetchedRecords.length} 条单据数据,正在生成高保真 Excel...`);
// 3. 构建 Excel 工作簿
const workbook = new ExcelJS.Workbook();
workbook.creator = "Seal AI (seal-use)";
workbook.created = new Date();
const worksheet = workbook.addWorksheet("审核记录明细", {
views: [{ state: "frozen", ySplit: 1, xSplit: 2 }]
});
const baseColumns: Array<{ header: string; key: string; width: number }> = [
{ header: "单据编号", key: "sn", width: 16 },
{ header: "单据模板名称", key: "templateName", width: 26 },
{ header: "来源系统", key: "sourceSystem", width: 12 },
{ header: "任务模式", key: "taskMode", width: 12 },
{ header: "状态", key: "status", width: 12 },
{ header: "AI行为", key: "aiAction", width: 14 },
{ header: "AI决策", key: "aiDecision", width: 14 },
{ header: "思考深度", key: "thinkingDepth", width: 12 },
{ header: "人工审核", key: "manualStatus", width: 16 },
{ header: "人工驳回原因", key: "humanRejectReason", width: 36 },
{ header: "创建时间", key: "createdAt", width: 20 },
{ header: "任务耗时", key: "duration", width: 12 },
{ header: "关联规则数", key: "hitRuleCount", width: 12 },
{ header: "关联规则汇总", key: "hitRulesSummary", width: 30 },
{ header: "AI审核结论摘要", key: "aiSummary", width: 45 }
];
const ruleColumns = sortedRuleKeys.map((ruleKey) => {
const rInfo = ruleMap.get(ruleKey)!;
return {
header: rInfo.title,
key: `rule_${ruleKey}`,
width: 22
};
});
worksheet.columns = [...baseColumns, ...ruleColumns];
// 表头样式设置
const headerRow = worksheet.getRow(1);
headerRow.height = 32;
headerRow.eachCell((cell, colNumber) => {
const isBase = colNumber <= baseColumns.length;
cell.font = {
name: "Microsoft YaHei",
bold: true,
color: { argb: "FFFFFFFF" },
size: 11
};
cell.fill = {
type: "pattern",
pattern: "solid",
fgColor: { argb: isBase ? "FF1E3A8A" : "FF334155" }
};
cell.alignment = {
vertical: "middle",
horizontal: isBase && colNumber <= 2 ? "left" : "center",
wrapText: false
};
});
const statusCounts: Record<string, number> = {};
let rejectReasonCount = 0;
// 填充数据行
for (const record of fetchedRecords) {
const res = (record.result as any) || {};
const doc = (record.document as any) || {};
// 1. 提取单据模板名称
let templateName = "未知模板";
if (Array.isArray(doc.fields)) {
const tField = doc.fields.find(
(f: any) =>
f.label === "单据模板" ||
f.label === "流程名称" ||
f.key === "templateName" ||
f.key === "specificationId" ||
f.key === "formName"
);
if (tField?.value) templateName = String(tField.value);
}
if (templateName === "未知模板" && (doc.name || doc.title)) {
templateName = doc.name || doc.title;
}
// 2. 映射任务模式
let taskModeDesc = record.taskMode || "-";
if (taskModeDesc === "assisted") taskModeDesc = "辅助审核";
else if (taskModeDesc === "simulation") taskModeDesc = "测试任务";
else if (taskModeDesc === "automatic") taskModeDesc = "自动审批";
// 3. 映射状态
let statusDesc = record.status || "-";
if (statusDesc === "completed") statusDesc = "已完成";
else if (statusDesc === "processing") statusDesc = "处理中";
else if (statusDesc === "failed") statusDesc = "失败";
// 4. AI 决策与行为
const aiDecision = res.decision || (record as any).aiDecision || "-";
let aiDecisionDesc = aiDecision;
let aiAction = "-";
if (aiDecision === "APPROVE") {
aiDecisionDesc = "通过";
aiAction = "添加评论";
} else if (aiDecision === "REVIEW") {
aiDecisionDesc = "转交复核";
aiAction = "转交复核";
} else if (aiDecision === "REJECT") {
aiDecisionDesc = "驳回";
aiAction = "驳回";
}
// 5. 耗时计算
let durationStr = "-";
if (record.createdAt && record.updatedAt && record.status === "completed") {
const diffSec = Math.round((Number(record.updatedAt) - Number(record.createdAt)) / 1000);
if (diffSec >= 60) {
durationStr = `${Math.floor(diffSec / 60)}分${diffSec % 60}秒`;
} else if (diffSec > 0) {
durationStr = `${diffSec}秒`;
}
}
// 6. 人工审核状态与驳回原因
const mar = (record as any).manualApprovalRecord || {};
let manualStatus = "-";
if (mar.status?.label) {
manualStatus = String(mar.status.label);
} else if (mar.status?.type) {
const t = String(mar.status.type);
if (t === "APPROVED") manualStatus = "已通过";
else if (t === "TERMINATED") manualStatus = "被驳回";
else if (t === "PROCESSING") manualStatus = "处理中";
else if (t === "CANCELLED") manualStatus = "已撤回";
else manualStatus = t;
}
statusCounts[manualStatus] = (statusCounts[manualStatus] || 0) + 1;
const humanRejectReason = mar.rejectComment ? String(mar.rejectComment).trim() : "-";
if (humanRejectReason !== "-") {
rejectReasonCount++;
}
// 7. 解析规则核验结果
const ruleResultMap = new Map<string, string>();
const hitRuleIds: string[] = [];
if (Array.isArray(res.rulesResult)) {
for (const rr of res.rulesResult) {
if (rr.id) {
ruleResultMap.set(rr.id, rr.checkResult || "PASS");
hitRuleIds.push(rr.id);
}
}
}
if (Array.isArray(res.hitRules)) {
for (const hr of res.hitRules) {
if (hr.id && !ruleResultMap.has(hr.id)) {
ruleResultMap.set(hr.id, "TRIGGERED");
hitRuleIds.push(hr.id);
}
}
}
// 8. 创建时间
let createdAtStr = "-";
if (record.createdAt) {
const d = new Date(Number(record.createdAt));
createdAtStr = d.toLocaleString("zh-CN", { timeZone: "Asia/Shanghai", hour12: false });
}
const rowData: Record<string, any> = {
sn: record.sourceDocumentSN || record.sourceDocumentId || "-",
templateName,
sourceSystem: record.sourceSystem || "合思",
taskMode: taskModeDesc,
status: statusDesc,
aiAction,
aiDecision: aiDecisionDesc,
thinkingDepth: "标准",
manualStatus,
humanRejectReason,
createdAt: createdAtStr,
duration: durationStr,
hitRuleCount: hitRuleIds.length,
hitRulesSummary: hitRuleIds.join(", ") || "-",
aiSummary: res.summary || "-"
};
for (const ruleKey of sortedRuleKeys) {
const checkResult = ruleResultMap.get(ruleKey);
if (checkResult) {
if (checkResult === "PASS") rowData[`rule_${ruleKey}`] = "关联 (通过)";
else if (checkResult === "FAIL") rowData[`rule_${ruleKey}`] = "关联 (不通过)";
else if (checkResult === "UNKNOWN") rowData[`rule_${ruleKey}`] = "关联 (待复核)";
else rowData[`rule_${ruleKey}`] = "已关联";
} else {
rowData[`rule_${ruleKey}`] = "未关联";
}
}
const addedRow = worksheet.addRow(rowData);
addedRow.height = 24;
addedRow.eachCell((cell, colNumber) => {
const val = String(cell.value || "");
cell.font = { name: "Microsoft YaHei", size: 10 };
cell.border = {
top: { style: "thin", color: { argb: "FFE2E8F0" } },
bottom: { style: "thin", color: { argb: "FFE2E8F0" } },
left: { style: "thin", color: { argb: "FFE2E8F0" } },
right: { style: "thin", color: { argb: "FFE2E8F0" } }
};
if (colNumber <= baseColumns.length) {
cell.alignment = {
vertical: "middle",
horizontal: [1, 2, 10, 14, 15].includes(colNumber) ? "left" : "center",
wrapText: [10, 14, 15].includes(colNumber)
};
// AI 决策颜色区分
if (colNumber === 7) {
if (val === "通过") cell.font = { color: { argb: "FF16A34A" }, bold: true };
else if (val === "转交复核") cell.font = { color: { argb: "FFD97706" }, bold: true };
else if (val === "驳回") cell.font = { color: { argb: "FFDC2626" }, bold: true };
}
// 人工审核高亮
if (colNumber === 9) {
if (val.includes("驳回")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FFDC2626" }, bold: true };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
} else if (val.includes("通过") || val.includes("支付") || val.includes("完成")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF16A34A" }, bold: true };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFDCFCE7" } };
} else if (val.includes("处理中") || val.includes("审批中")) {
cell.font = { name: "Microsoft YaHei", size: 10, color: { argb: "FF2563EB" } };
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFEFF6FF" } };
}
}
// 人工驳回原因字体
if (colNumber === 10 && val !== "-") {
cell.font = { name: "Microsoft YaHei", size: 9, color: { argb: "FF991B1B" } };
}
} else {
cell.alignment = { vertical: "middle", horizontal: "center" };
if (val.includes("不通过")) {
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEE2E2" } };
cell.font = { color: { argb: "FF991B1B" }, bold: true };
} else if (val.includes("通过")) {
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFDCFCE7" } };
cell.font = { color: { argb: "FF166534" }, bold: true };
} else if (val.includes("待复核") || val.includes("已关联")) {
cell.fill = { type: "pattern", pattern: "solid", fgColor: { argb: "FFFEF3C7" } };
cell.font = { color: { argb: "FF92400E" } };
} else {
cell.font = { color: { argb: "FF94A3B8" } };
}
}
});
}
// 4. 保存文件落地
let dateTag: string | undefined;
if (options.startDate) {
const rawStart = String(options.startDate);
if (/^\d{4}-\d{2}-\d{2}/.test(rawStart)) {
dateTag = `${rawStart.slice(0, 10)}至今`;
} else if (/^\d+$/.test(rawStart)) {
const d = new Date(Number(rawStart));
dateTag = `${d.getFullYear()}${String(d.getMonth() + 1).padStart(2, "0")}${String(d.getDate()).padStart(2, "0")}至今`;
}
}
const targetPath = resolveOutputFilePath({
outputFile: options.outputFile,
toDownloads: options.toDownloads,
corpName,
dateTag,
recordCount: fetchedRecords.length
});
await workbook.xlsx.writeFile(targetPath);
console.error(`Excel 文件已成功落地: ${targetPath}`);
const stat = statSync(targetPath);
return {
filePath: targetPath,
corpId: corp.id,
corpName,
recordCount: fetchedRecords.length,
ruleColumnCount: sortedRuleKeys.length,
statusCounts,
rejectReasonCount,
fileSizeBytes: stat.size,
exportedAt: new Date().toISOString()
};
}
+352
View File
@@ -0,0 +1,352 @@
import { describe, test, expect, beforeEach, afterEach } from "bun:test";
import fs from "node:fs";
import path from "node:path";
import os from "node:os";
import {
extractApprovalRunAttachments,
downloadApprovalRunAttachments,
sanitizeUrlForLog,
sanitizeFileName,
type FetchLike
} from "./attachments.js";
import type { ApprovalRun } from "./types.js";
describe("attachments domain", () => {
let tmpDir: string;
beforeEach(async () => {
tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "seal-att-test-"));
});
afterEach(async () => {
try {
await fs.promises.rm(tmpDir, { recursive: true, force: true });
} catch {}
});
test("sanitizeUrlForLog masks query string signatures", () => {
const rawUrl = "https://oss-bucket.aliyuncs.com/tenant/doc1/pic.jpg?X-Amz-Signature=secret123&OSSAccessKeyId=key456";
const masked = sanitizeUrlForLog(rawUrl);
expect(masked).toBe("https://oss-bucket.aliyuncs.com/tenant/doc1/pic.jpg?[MASKED]");
expect(masked).not.toContain("secret123");
expect(masked).not.toContain("key456");
const plainUrl = "https://example.com/files/receipt.pdf";
expect(sanitizeUrlForLog(plainUrl)).toBe("https://example.com/files/receipt.pdf");
});
test("sanitizeFileName strips dangerous characters", () => {
expect(sanitizeFileName("foo/bar:baz?.png")).toBe("foo_bar_baz_.png");
expect(sanitizeFileName("../../evil.exe")).toBe(".._.._evil.exe");
expect(sanitizeFileName("")).toBe("attachment");
});
test("extractApprovalRunAttachments extracts attachments from Issue #35 field structure", () => {
const fixture: ApprovalRun = {
id: "run-hose-1",
status: "completed",
sourceDocumentSN: "BX2026080001",
sourceDocumentId: "doc-hose-1",
document: {
id: "doc-1",
sn: "BX2026080001",
fields: [
{ key: "expense_type", label: "费用类型", value: "差旅" },
{
key: "attachments",
type: "ATTACHMENT",
label: "附件",
value: [
{
url: "https://oss-bucket.aliyuncs.com/tenant/attachments/doc1/receipt1.jpg",
ossSignedUrl: "https://oss-bucket.aliyuncs.com/tenant/attachments/doc1/receipt1.jpg?X-Amz-Signature=sig1",
name: "发票1.jpg",
token: JSON.stringify({ source: "hosecloud", fileId: "file-101", key: "obj-key-101" }),
fileId: "file-101",
ossPath: "tenant/attachments/doc1/obj-key-101",
category: "file",
mimeType: "image/jpeg",
ossFileSize: 1024
},
{
url: "https://oss-bucket.aliyuncs.com/tenant/attachments/doc1/receipt2.jpg",
ossSignedUrl: "https://oss-bucket.aliyuncs.com/tenant/attachments/doc1/receipt2.jpg?X-Amz-Signature=sig2",
name: "水单2.jpg",
token: JSON.stringify({ source: "hosecloud", fileId: "file-102", key: "obj-key-102" }),
fileId: "file-102",
ossPath: "tenant/attachments/doc1/obj-key-102",
category: "file",
mimeType: "image/jpeg",
ossFileSize: 2048
},
{
url: "https://oss-bucket.aliyuncs.com/tenant/attachments/doc1/doc3.pdf",
ossSignedUrl: "https://oss-bucket.aliyuncs.com/tenant/attachments/doc1/doc3.pdf?X-Amz-Signature=sig3",
name: "行程单.pdf",
token: JSON.stringify({ source: "hosecloud", fileId: "file-103", key: "obj-key-103" }),
fileId: "file-103",
category: "file",
mimeType: "application/pdf",
ossFileSize: 4096
},
{
url: "https://oss-bucket.aliyuncs.com/tenant/attachments/doc1/photo4.png",
ossSignedUrl: "https://oss-bucket.aliyuncs.com/tenant/attachments/doc1/photo4.png?X-Amz-Signature=sig4",
name: "现场打卡.png",
token: JSON.stringify({ source: "hosecloud", fileId: "file-104", key: "obj-key-104" }),
fileId: "file-104",
category: "file",
mimeType: "image/png",
ossFileSize: 8192
}
]
}
]
}
};
const fullResult = extractApprovalRunAttachments(fixture);
expect(fullResult.count).toBe(4);
expect(fullResult.recordId).toBe("run-hose-1");
expect(fullResult.sourceDocumentSN).toBe("BX2026080001");
const first = fullResult.attachments[0] as any;
expect(first.fileName).toBe("发票1.jpg");
expect(first.fileId).toBe("file-101");
expect(first.tokenKey).toBe("obj-key-101");
expect(first.ossFileSize).toBe(1024);
expect(first.ossSignedUrl).toContain("X-Amz-Signature=sig1");
expect(first.sourceField).toBe("附件");
expect(first.kind).toBe("invoice"); // "发票" in name triggers invoice kind
const summaryResult = extractApprovalRunAttachments(fixture, { summary: true });
expect(summaryResult.count).toBe(4);
expect((summaryResult.attachments[0] as any).hasSignedUrl).toBe(true);
expect((summaryResult.attachments[0] as any).ossFileSize).toBe(1024);
expect((summaryResult.attachments[0] as any).ossSignedUrl).toBeUndefined(); // summary masks raw url
});
test("extractApprovalRunAttachments extracts attachments from legacy layout", () => {
const fixture: ApprovalRun = {
id: "run-legacy-1",
status: "completed",
document: {
fields: [
{
label: "附件",
attachments: [
{
fileName: "legacy.pdf",
fileId: "file-legacy-1",
mimeType: "application/pdf",
ossPath: "oss://bucket/legacy.pdf"
}
]
}
]
}
};
const result = extractApprovalRunAttachments(fixture);
expect(result.count).toBe(1);
expect((result.attachments[0] as any).fileName).toBe("legacy.pdf");
expect((result.attachments[0] as any).fileId).toBe("file-legacy-1");
});
test("downloadApprovalRunAttachments downloads all files with --all and matches size", async () => {
const content1 = Buffer.from("Invoice mock data 12345");
const content2 = Buffer.from("Receipt mock data 67890");
const fakeFetch: FetchLike = async (url: any) => {
const urlStr = String(url);
if (urlStr.includes("att1.jpg")) {
return new Response(content1, { status: 200 });
}
if (urlStr.includes("att2.jpg")) {
return new Response(content2, { status: 200 });
}
return new Response("Not found", { status: 404 });
};
const record: ApprovalRun = {
id: "run-dl-1",
document: {
fields: [
{
key: "attachments",
type: "ATTACHMENT",
label: "附件",
value: [
{
name: "发票.jpg",
ossSignedUrl: "https://oss.example.com/att1.jpg?sign=abc",
ossFileSize: content1.length
},
{
name: "水单.jpg",
ossSignedUrl: "https://oss.example.com/att2.jpg?sign=def",
ossFileSize: content2.length
}
]
}
]
}
};
const result = await downloadApprovalRunAttachments({
record,
all: true,
outDir: tmpDir,
fetchFn: fakeFetch
});
expect(result.total).toBe(2);
expect(result.downloaded).toBe(2);
expect(result.failed).toBe(0);
const file1Path = path.join(tmpDir, "发票.jpg");
const file2Path = path.join(tmpDir, "水单.jpg");
expect(fs.existsSync(file1Path)).toBe(true);
expect(fs.existsSync(file2Path)).toBe(true);
expect(fs.readFileSync(file1Path)).toEqual(content1);
expect(fs.readFileSync(file2Path)).toEqual(content2);
});
test("downloadApprovalRunAttachments filters by --name", async () => {
const content = Buffer.from("Target attachment data");
const fakeFetch: FetchLike = async () => new Response(content, { status: 200 });
const record: ApprovalRun = {
id: "run-dl-2",
document: {
fields: [
{
key: "attachments",
type: "ATTACHMENT",
value: [
{ name: "test_a.pdf", ossSignedUrl: "https://oss.example.com/a.pdf" },
{ name: "target_b.pdf", ossSignedUrl: "https://oss.example.com/b.pdf" }
]
}
]
}
};
const result = await downloadApprovalRunAttachments({
record,
name: "target_b",
outDir: tmpDir,
fetchFn: fakeFetch
});
expect(result.total).toBe(1);
expect(result.downloaded).toBe(1);
expect(result.files[0]!.name).toBe("target_b.pdf");
expect(fs.existsSync(path.join(tmpDir, "target_b.pdf"))).toBe(true);
expect(fs.existsSync(path.join(tmpDir, "test_a.pdf"))).toBe(false);
});
test("downloadApprovalRunAttachments requires --all when multiple attachments exist without filter", async () => {
const record: ApprovalRun = {
id: "run-dl-3",
document: {
fields: [
{
key: "attachments",
type: "ATTACHMENT",
value: [
{ name: "f1.jpg", ossSignedUrl: "https://oss.example.com/1.jpg" },
{ name: "f2.jpg", ossSignedUrl: "https://oss.example.com/2.jpg" }
]
}
]
}
};
expect(
downloadApprovalRunAttachments({
record,
outDir: tmpDir
})
).rejects.toThrow("请使用 --all 下载全部附件");
});
test("downloadApprovalRunAttachments handles expired URL (HTTP 403) gracefully without aborting others", async () => {
const validContent = Buffer.from("Valid attachment data");
const fakeFetch: FetchLike = async (url: any) => {
const urlStr = String(url);
if (urlStr.includes("expired.jpg")) {
return new Response("Access Denied / Expired", { status: 403, statusText: "Forbidden" });
}
return new Response(validContent, { status: 200 });
};
const record: ApprovalRun = {
id: "run-dl-4",
document: {
fields: [
{
key: "attachments",
type: "ATTACHMENT",
value: [
{ name: "expired.jpg", ossSignedUrl: "https://oss.example.com/expired.jpg?sign=old" },
{ name: "valid.jpg", ossSignedUrl: "https://oss.example.com/valid.jpg?sign=fresh" }
]
}
]
}
};
const result = await downloadApprovalRunAttachments({
record,
all: true,
outDir: tmpDir,
fetchFn: fakeFetch
});
expect(result.total).toBe(2);
expect(result.downloaded).toBe(1);
expect(result.failed).toBe(1);
const failedItem = result.files.find((f) => f.name === "expired.jpg");
expect(failedItem?.status).toBe("failed");
expect(failedItem?.error).toContain("403");
const successItem = result.files.find((f) => f.name === "valid.jpg");
expect(successItem?.status).toBe("success");
expect(fs.existsSync(path.join(tmpDir, "valid.jpg"))).toBe(true);
});
test("downloadApprovalRunAttachments disambiguates duplicate filenames", async () => {
const fakeFetch: FetchLike = async () => new Response("data", { status: 200 });
const record: ApprovalRun = {
id: "run-dl-5",
document: {
fields: [
{
key: "attachments",
type: "ATTACHMENT",
value: [
{ name: "same.jpg", ossSignedUrl: "https://oss.example.com/1.jpg" },
{ name: "same.jpg", ossSignedUrl: "https://oss.example.com/2.jpg" }
]
}
]
}
};
const result = await downloadApprovalRunAttachments({
record,
all: true,
outDir: tmpDir,
fetchFn: fakeFetch
});
expect(result.downloaded).toBe(2);
expect(result.files.map((f) => f.name)).toEqual(["same.jpg", "same_1.jpg"]);
expect(fs.existsSync(path.join(tmpDir, "same.jpg"))).toBe(true);
expect(fs.existsSync(path.join(tmpDir, "same_1.jpg"))).toBe(true);
});
});
+427
View File
@@ -0,0 +1,427 @@
import fs from "node:fs";
import path from "node:path";
import type { ApprovalRun } from "./types.js";
export interface ApprovalRunAttachment {
path: string;
fieldPath: string;
kind: string;
fileName?: string;
mimeType?: string;
fileId?: string;
ossPath?: string;
url?: string;
ossSignedUrl?: string;
token?: unknown;
tokenKey?: string;
category?: string;
ossFileSize?: number;
invoiceId?: string;
sourceField?: string;
}
export interface ApprovalRunAttachmentsResult {
recordId: string;
sourceDocumentSN?: string;
sourceDocumentId?: string;
count: number;
attachments: Array<Record<string, unknown>>;
}
export type FetchLike = (input: RequestInfo | URL, init?: RequestInit) => Promise<Response>;
export interface DownloadAttachmentsOptions {
record: ApprovalRun;
all?: boolean;
name?: string;
outDir?: string;
fetchFn?: FetchLike;
}
export interface DownloadedAttachmentFile {
name: string;
fileId?: string;
path?: string;
size?: number;
expectedSize?: number;
status: "success" | "failed";
error?: string;
sourceField?: string;
tokenKey?: string;
}
export interface DownloadAttachmentsResult {
recordId: string;
outDir: string;
total: number;
downloaded: number;
failed: number;
files: DownloadedAttachmentFile[];
}
interface CollectContext {
fieldLabel?: string;
fieldKey?: string;
fieldType?: string;
}
export function sanitizeUrlForLog(url: string): string {
try {
const parsed = new URL(url);
if (parsed.search) {
return `${parsed.origin}${parsed.pathname}?[MASKED]`;
}
return url;
} catch {
return url.replace(/\?.*$/, "?[MASKED]");
}
}
export function sanitizeFileName(name: string): string {
const cleaned = name.replace(/[/\\?%*:|"<>]/g, "_").trim();
return cleaned || "attachment";
}
function compactObject(object: Record<string, unknown>) {
return Object.fromEntries(Object.entries(object).filter(([, value]) => value !== undefined));
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value)
? value as Record<string, unknown>
: undefined;
}
function stringFromUnknown(value: unknown): string | undefined {
return typeof value === "string" && value.trim() ? value.trim() : undefined;
}
function numberFromUnknown(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
function tryParseToken(token: unknown): Record<string, unknown> | undefined {
if (!token) return undefined;
if (typeof token === "string") {
try {
const parsed = JSON.parse(token);
if (parsed && typeof parsed === "object") return parsed as Record<string, unknown>;
} catch {
return undefined;
}
}
if (typeof token === "object" && !Array.isArray(token)) {
return token as Record<string, unknown>;
}
return undefined;
}
function looksLikeAttachment(object: Record<string, unknown>, path: string, context?: CollectContext): boolean {
// If parent field explicitly declares ATTACHMENT type, any item with file properties is an attachment
if (context?.fieldType?.toUpperCase() === "ATTACHMENT") {
const hasIdentifier = Boolean(
object.fileName ||
object.filename ||
object.name ||
object.originalName ||
object.fileId ||
object.ossPath ||
object.url ||
object.ossSignedUrl ||
object.signedUrl ||
object.token
);
if (hasIdentifier) return true;
}
// Explicit signed URL presence always indicates a download-ready attachment
if (object.ossSignedUrl || object.signedUrl) {
return true;
}
// Check common file identity properties
const fileName = object.fileName ?? object.filename ?? object.name ?? object.originalName;
const fileId = object.fileId ?? object.id ?? object.attachmentId;
const ossPath = object.ossPath ?? object.ossKey;
const url = object.url ?? object.downloadUrl ?? object.previewUrl;
const mimeType = object.mimeType ?? object.mimetype ?? object.contentType;
const ossFileSize = object.ossFileSize ?? object.fileSize ?? object.size;
if (fileName && (url || ossPath || fileId || ossFileSize)) {
return true;
}
if (fileId && (mimeType || ossFileSize || ossPath || url)) {
return true;
}
// Legacy path and keyword based heuristics
const keys = Object.keys(object).map((k) => k.toLowerCase());
const pathHint = /(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(path) ||
Boolean(context?.fieldKey && /(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(context.fieldKey)) ||
Boolean(context?.fieldLabel && /(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(context.fieldLabel));
const fileHints = [
"filename", "filename", "mimetype", "contenttype",
"fileid", "osspath", "signedurl", "downloadurl",
"previewurl", "attachmentid", "ossfilesize", "osssignedurl"
];
return pathHint && fileHints.some((hint) => keys.includes(hint));
}
function inferAttachmentKind(path: string, object: Record<string, unknown>, context?: CollectContext): string {
const normalized = `${path} ${context?.fieldLabel ?? ""} ${context?.fieldKey ?? ""} ${stringFromUnknown(object.type) ?? ""} ${stringFromUnknown(object.category) ?? ""}`.toLowerCase();
if (normalized.includes("invoice") || normalized.includes("发票")) return "invoice";
if (normalized.includes("receipt")) return "receipt";
const name = (stringFromUnknown(object.fileName) ?? stringFromUnknown(object.name) ?? "").toLowerCase();
if (name.includes("发票") || name.includes("invoice")) return "invoice";
return "attachment";
}
function collectAttachments(
value: unknown,
path: string,
output: Array<Record<string, unknown>>,
seen: Set<string>,
context?: CollectContext
) {
if (Array.isArray(value)) {
value.forEach((item, index) => collectAttachments(item, `${path}.${index}`, output, seen, context));
return;
}
const object = asRecord(value);
if (!object) return;
// Determine if this object is a field container (e.g. in document.fields[])
const isFieldContainer = (object.type && typeof object.type === "string") ||
("label" in object && "value" in object) ||
("key" in object && "value" in object);
let nextContext = context;
if (isFieldContainer) {
nextContext = {
fieldLabel: stringFromUnknown(object.label) ?? context?.fieldLabel,
fieldKey: stringFromUnknown(object.key) ?? context?.fieldKey,
fieldType: stringFromUnknown(object.type) ?? context?.fieldType
};
}
// If this object itself qualifies as an attachment file
// (containers that just have array value without url/fileId are not attachment files)
const isContainerOnly = Array.isArray(object.value) && !object.url && !object.ossSignedUrl && !object.fileId;
if (!isContainerOnly && looksLikeAttachment(object, path, context)) {
const parsedToken = tryParseToken(object.token);
const tokenKey = stringFromUnknown(parsedToken?.key);
const tokenFileId = stringFromUnknown(parsedToken?.fileId);
const attachment = compactObject({
path,
fieldPath: path,
kind: inferAttachmentKind(path, object, context),
fileName: stringFromUnknown(object.fileName) ?? stringFromUnknown(object.filename) ?? stringFromUnknown(object.name) ?? stringFromUnknown(object.originalName),
mimeType: stringFromUnknown(object.mimeType) ?? stringFromUnknown(object.mimetype) ?? stringFromUnknown(object.contentType),
fileId: stringFromUnknown(object.fileId) ?? stringFromUnknown(object.id) ?? stringFromUnknown(object.attachmentId) ?? tokenFileId,
ossPath: stringFromUnknown(object.ossPath) ?? stringFromUnknown(object.ossKey) ?? tokenKey,
url: stringFromUnknown(object.url) ?? stringFromUnknown(object.signedUrl) ?? stringFromUnknown(object.downloadUrl) ?? stringFromUnknown(object.previewUrl),
ossSignedUrl: stringFromUnknown(object.ossSignedUrl) ?? stringFromUnknown(object.signedUrl),
token: object.token,
tokenKey,
category: stringFromUnknown(object.category),
ossFileSize: numberFromUnknown(object.ossFileSize) ?? numberFromUnknown(object.fileSize) ?? numberFromUnknown(object.size),
invoiceId: stringFromUnknown(object.invoiceId),
sourceField: stringFromUnknown(object.fieldName) ?? stringFromUnknown(object.label) ?? context?.fieldLabel ?? context?.fieldKey
});
const key = JSON.stringify(attachment);
if (!seen.has(key)) {
seen.add(key);
output.push(attachment);
}
}
for (const [key, child] of Object.entries(object)) {
collectAttachments(child, `${path}.${key}`, output, seen, nextContext);
}
}
export function extractApprovalRunAttachments(
record: ApprovalRun,
options: { summary?: boolean } = {}
): ApprovalRunAttachmentsResult {
const roots: Array<[string, unknown]> = [
["document", record.document],
["result", record.result],
["pipelineData", record.pipelineData],
["sourceExtendData", record.sourceExtendData]
];
const attachments: Array<Record<string, unknown>> = [];
const seen = new Set<string>();
for (const [path, value] of roots) {
collectAttachments(value, path, attachments, seen);
}
return {
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
count: attachments.length,
attachments: options.summary
? attachments.map((attachment) => compactObject({
path: attachment.path,
kind: attachment.kind,
fileName: attachment.fileName,
mimeType: attachment.mimeType,
fileId: attachment.fileId,
sourceField: attachment.sourceField,
ossFileSize: attachment.ossFileSize,
hasSignedUrl: Boolean(attachment.ossSignedUrl)
}))
: attachments
};
}
export async function downloadApprovalRunAttachments(
options: DownloadAttachmentsOptions
): Promise<DownloadAttachmentsResult> {
const { record, fetchFn = globalThis.fetch } = options;
const extraction = extractApprovalRunAttachments(record, { summary: false });
const allAttachments = extraction.attachments as unknown as ApprovalRunAttachment[];
const resolvedOutDir = path.resolve(options.outDir ?? "./attachments");
if (allAttachments.length === 0) {
return {
recordId: record.id,
outDir: resolvedOutDir,
total: 0,
downloaded: 0,
failed: 0,
files: []
};
}
let selected: ApprovalRunAttachment[] = [];
if (options.name) {
const term = options.name.toLowerCase();
selected = allAttachments.filter((att) => {
const fileName = att.fileName?.toLowerCase() ?? "";
const fileId = att.fileId?.toLowerCase() ?? "";
const tokenKey = att.tokenKey?.toLowerCase() ?? "";
return fileName.includes(term) || fileId === term || tokenKey.includes(term);
});
if (selected.length === 0) {
const available = allAttachments.map((a) => a.fileName ?? a.fileId).filter(Boolean).join(", ");
throw new Error(`未找到匹配 "${options.name}" 的附件。可选附件: ${available || "无"}`);
}
} else if (!options.all) {
if (allAttachments.length > 1) {
const available = allAttachments.map((a) => a.fileName ?? a.fileId).filter(Boolean).join(", ");
throw new Error(
`共发现 ${allAttachments.length} 个附件。请使用 --all 下载全部附件,或使用 --name <名称|fileId> 指定下载项。可选附件: ${available}`
);
}
selected = allAttachments;
} else {
selected = allAttachments;
}
await fs.promises.mkdir(resolvedOutDir, { recursive: true });
const files: DownloadedAttachmentFile[] = [];
const usedNames = new Set<string>();
for (const attachment of selected) {
const rawName = attachment.fileName ?? attachment.fileId ?? "attachment";
const safeBase = sanitizeFileName(rawName);
let targetName = safeBase;
const lastDot = safeBase.lastIndexOf(".");
const stem = lastDot > 0 ? safeBase.slice(0, lastDot) : safeBase;
const ext = lastDot > 0 ? safeBase.slice(lastDot) : "";
let counter = 1;
while (usedNames.has(targetName.toLowerCase())) {
targetName = `${stem}_${counter}${ext}`;
counter++;
}
usedNames.add(targetName.toLowerCase());
const downloadUrl = attachment.ossSignedUrl ?? attachment.url;
if (!downloadUrl) {
console.error(`⚠️ [跳过] 附件 "${rawName}": 记录中无下载直链 (ossSignedUrl/url)`);
files.push({
name: targetName,
fileId: attachment.fileId,
status: "failed",
error: "缺少可用的下载直链 (ossSignedUrl/url)。",
sourceField: attachment.sourceField,
tokenKey: attachment.tokenKey
});
continue;
}
const sanitizedUrl = sanitizeUrlForLog(downloadUrl);
try {
const response = await fetchFn(downloadUrl, {
signal: AbortSignal.timeout(60000)
});
if (!response.ok) {
const errorMsg = response.status === 403
? "HTTP 403 Forbidden: 签名直链可能已过期"
: `HTTP ${response.status} ${response.statusText}`;
throw new Error(errorMsg);
}
const arrayBuffer = await response.arrayBuffer();
const buffer = Buffer.from(arrayBuffer);
if (attachment.ossFileSize !== undefined && buffer.length !== attachment.ossFileSize) {
console.error(`⚠️ [校验] 附件 "${targetName}" 实际大小 (${buffer.length} 字节) 与 ossFileSize (${attachment.ossFileSize} 字节) 不一致`);
}
const filePath = path.join(resolvedOutDir, targetName);
await fs.promises.writeFile(filePath, buffer);
console.error(`✓ 已下载: ${targetName} (${buffer.length} 字节)`);
files.push({
name: targetName,
fileId: attachment.fileId,
path: filePath,
size: buffer.length,
expectedSize: attachment.ossFileSize,
status: "success",
sourceField: attachment.sourceField,
tokenKey: attachment.tokenKey
});
} catch (err: any) {
const msg = err.message ?? String(err);
console.error(`⚠️ [失败] 附件 "${rawName}" 下载失败: ${msg} [${sanitizedUrl}]`);
files.push({
name: targetName,
fileId: attachment.fileId,
status: "failed",
error: msg,
sourceField: attachment.sourceField,
tokenKey: attachment.tokenKey
});
}
}
const downloaded = files.filter((f) => f.status === "success").length;
const failed = files.filter((f) => f.status === "failed").length;
return {
recordId: record.id,
outDir: resolvedOutDir,
total: selected.length,
downloaded,
failed,
files
};
}
+89
View File
@@ -0,0 +1,89 @@
import type { RuleLintIssue, RuleLintResult, RuleLintTarget } from "./types.js";
export const BUILTIN_VAGUE_WORDS = [
"原则上",
"尽量",
"适当",
"酌情",
"一般情况下",
"尽可能",
"合理控制",
"视情况",
"视具体情况"
];
export const BUILTIN_EXCEPTION_TRIGGERS = [
"除非",
"特殊情况",
"特殊原因",
"经批准",
"经审批",
"经领导同意",
"除外",
"例外"
];
export const BUILTIN_EVIDENCE_KEYWORDS = [
"备注",
"说明",
"附件",
"证明",
"邮件",
"截图",
"凭证",
"审批",
"单据",
"发票"
];
export function builtinRuleLinter(rule: RuleLintTarget): RuleLintResult {
const text = (rule.description || "").trim();
const issues: RuleLintIssue[] = [];
// 1. 规则过短检查
if (text.length < 5) {
issues.push({
level: "error",
code: "TOO_SHORT",
message: "规则描述过于简短(少于 5 个字),大模型难以形成明确的判定逻辑",
suggestion: "请补充具体的费用类型、核验条件与限制标准"
});
}
// 2. 主观模糊词拦截
for (const word of BUILTIN_VAGUE_WORDS) {
if (text.includes(word)) {
issues.push({
level: "error",
code: "VAGUE_WORD",
snippet: word,
message: `包含主观模糊词 "${word}",容易导致大模型判定标准产生波动与幻觉`,
suggestion: `建议移除 "${word}",改为具体的金额上限、枚举范围或刚性判定条件`
});
}
}
// 3. 悬空例外条款检测
const matchedTrigger = BUILTIN_EXCEPTION_TRIGGERS.find((trigger) => text.includes(trigger));
const hasEvidence = BUILTIN_EVIDENCE_KEYWORDS.some((kw) => text.includes(kw));
if (matchedTrigger && !hasEvidence) {
issues.push({
level: "warning",
code: "HANGING_EXCEPTION",
snippet: matchedTrigger,
message: `包含例外条款 "${matchedTrigger}",但未指定 AI 从何处核验该例外成立的依据`,
suggestion: `建议补充明确的凭据来源(例如:"需在【单据备注】中说明原因" 或 "需在【附件】中上传审批截图")`
});
}
const errorCount = issues.filter((i) => i.level === "error").length;
const warningCount = issues.filter((i) => i.level === "warning").length;
const score = Math.max(0, 100 - errorCount * 25 - warningCount * 10);
return {
score,
passed: errorCount === 0,
issues
};
}
+4
View File
@@ -0,0 +1,4 @@
export * from "./types.js";
export * from "./builtin.js";
export * from "./loader.js";
export * from "./service.js";
+112
View File
@@ -0,0 +1,112 @@
import { describe, expect, test } from "bun:test";
import { builtinRuleLinter } from "./builtin.js";
import { loadRuleLinter } from "./loader.js";
import { lintRuleBatch, lintSingleRule } from "./service.js";
import { writeFileSync, unlinkSync, mkdirSync, existsSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";
describe("Rule Linter", () => {
test("builtinRuleLinter detects short text, vague words, and hanging exceptions", () => {
// 1. 过短文本
const shortResult = builtinRuleLinter({ description: "测试" });
expect(shortResult.passed).toBe(false);
expect(shortResult.issues.some((i) => i.code === "TOO_SHORT")).toBe(true);
// 2. 主观模糊词
const vagueResult = builtinRuleLinter({
description: "原则上差旅住宿费尽量控制在500元以内"
});
expect(vagueResult.passed).toBe(false);
expect(vagueResult.issues.filter((i) => i.code === "VAGUE_WORD").length).toBe(2);
expect(vagueResult.score).toBeLessThanOrEqual(50);
// 3. 悬空例外条款(无证据说明)
const exceptionResult = builtinRuleLinter({
description: "差旅住宿费单日不得超过500元,特殊情况除外"
});
expect(exceptionResult.issues.some((i) => i.code === "HANGING_EXCEPTION")).toBe(true);
// 4. 完美高质量规则
const cleanResult = builtinRuleLinter({
description: "差旅住宿费每日不可超过500元。若因特殊情况超标,必须在【单据备注】中说明原因并在【附件】中提供总监审批邮件截图。"
});
expect(cleanResult.passed).toBe(true);
expect(cleanResult.score).toBe(100);
expect(cleanResult.issues.length).toBe(0);
});
test("loadRuleLinter returns builtin linter for default or non-existent files safely", async () => {
const builtinLoaded = await loadRuleLinter("builtin");
expect(builtinLoaded.type).toBe("builtin");
// 不存在的文件安全降级至 builtin,不抛错崩溃
const nonExistent = await loadRuleLinter("/tmp/non-existent-linter-xyz.ts");
expect(nonExistent.type).toBe("builtin");
const res = await nonExistent.linter({ description: "原则上不能超标" });
expect(res.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true);
});
test("loadRuleLinter safely executes custom TS/JS linter and catches runtime exceptions", async () => {
const testDir = join(tmpdir(), "seal-use-linter-test");
if (!existsSync(testDir)) mkdirSync(testDir, { recursive: true });
// 1. 有效的自定义校验器
const customTsPath = join(testDir, "custom-valid.ts");
writeFileSync(
customTsPath,
`export default function customLinter(rule) {
if (rule.description.includes("商务舱")) {
return { score: 40, passed: false, issues: [{ level: "error", code: "CUSTOM_FLIGHT", message: "禁止报销商务舱" }] };
}
return { score: 100, passed: true, issues: [] };
}`
);
const loadedCustom = await loadRuleLinter(customTsPath);
expect(loadedCustom.type).toBe("custom");
const customRes = await loadedCustom.linter({ description: "报销商务舱机票一张" });
expect(customRes.passed).toBe(false);
expect(customRes.issues[0]?.code).toBe("CUSTOM_FLIGHT");
// 2. 运行时崩溃的自定义校验器(安全捕获并降级)
const crashingTsPath = join(testDir, "custom-crash.ts");
writeFileSync(
customTsPath,
`export default function crashLinter() {
throw new Error("Intentional Crash");
}`
);
const loadedCrash = await loadRuleLinter(crashingTsPath);
const crashFallbackRes = await loadedCrash.linter({ description: "原则上不能超标" });
// 应当安全降级运行 builtin,返回模糊词拦截结果
expect(crashFallbackRes.issues.some((i) => i.code === "VAGUE_WORD")).toBe(true);
// 清理临时文件
try {
unlinkSync(customTsPath);
} catch {}
});
test("lintRuleBatch computes overall summary, score average, and filters by level", async () => {
const loaded = await loadRuleLinter("builtin");
const rules = [
{ id: "1", code: "#0001", name: "清晰规则", description: "差旅住宿费每日不可超过500元,超标需在【单据备注】中说明并附【审批截图】。" },
{ id: "2", code: "#0002", name: "模糊规则", description: "原则上差旅住宿费尽量控制在500元以内" },
{ id: "3", code: "#0003", name: "悬空例外", description: "差旅住宿费单日不得超过500元,特殊情况除外" }
];
const batchRes = await lintRuleBatch(rules, loaded, undefined, { level: "all" });
expect(batchRes.totalRules).toBe(3);
expect(batchRes.healthyCount).toBe(1);
expect(batchRes.issueCount).toBe(2);
expect(batchRes.overallScore).toBeLessThan(100);
expect(batchRes.passed).toBe(false);
// 摘要模式:只返回有问题的规则
const summaryRes = await lintRuleBatch(rules, loaded, undefined, { summary: true });
expect(summaryRes.issues.length).toBe(2);
expect(summaryRes.issues.map((i) => i.ruleCode)).toEqual(["#0002", "#0003"]);
});
});
+146
View File
@@ -0,0 +1,146 @@
import { existsSync, readdirSync } from "node:fs";
import { homedir } from "node:os";
import { isAbsolute, join, resolve } from "node:path";
import { pathToFileURL } from "node:url";
import { builtinRuleLinter } from "./builtin.js";
import type { RuleLintContext, RuleLintResult, RuleLintTarget, RuleLinterFn } from "./types.js";
export const PRIMARY_LINTERS_DIR = join(homedir(), ".config", "seal-use", "linters");
export const LOCAL_LINTERS_DIR = join(process.cwd(), "linters");
export interface LoadedLinter {
name: string;
type: "builtin" | "custom";
filePath?: string;
linter: RuleLinterFn;
}
export function listAvailableLinters(): Array<{ name: string; type: "builtin" | "custom"; path?: string }> {
const list: Array<{ name: string; type: "builtin" | "custom"; path?: string }> = [
{ name: "builtin", type: "builtin" }
];
const searchDirs = [PRIMARY_LINTERS_DIR, LOCAL_LINTERS_DIR];
for (const dir of searchDirs) {
if (existsSync(dir)) {
try {
const files = readdirSync(dir);
for (const file of files) {
if (file.endsWith(".ts") || file.endsWith(".js") || file.endsWith(".mjs")) {
const baseName = file.replace(/\.(ts|js|mjs)$/, "");
if (!list.some((item) => item.name === baseName)) {
list.push({
name: baseName,
type: "custom",
path: join(dir, file)
});
}
}
}
} catch {
// 忽略目录读取异常
}
}
}
return list;
}
function resolveLinterPath(nameOrPath: string): string | undefined {
if (!nameOrPath || nameOrPath === "builtin") {
return undefined;
}
// 1. 绝对路径或显式相对路径
if (isAbsolute(nameOrPath) || nameOrPath.startsWith("./") || nameOrPath.startsWith("../")) {
const absPath = resolve(nameOrPath);
if (existsSync(absPath)) return absPath;
for (const ext of [".ts", ".js", ".mjs"]) {
if (existsSync(`${absPath}${ext}`)) return `${absPath}${ext}`;
}
}
// 2. 搜索预设目录
const candidates = [
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.ts`),
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.js`),
join(PRIMARY_LINTERS_DIR, `${nameOrPath}.mjs`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.ts`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.js`),
join(LOCAL_LINTERS_DIR, `${nameOrPath}.mjs`)
];
for (const path of candidates) {
if (existsSync(path)) return path;
}
return undefined;
}
export async function loadRuleLinter(nameOrPath?: string): Promise<LoadedLinter> {
if (!nameOrPath || nameOrPath === "builtin") {
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
const resolvedPath = resolveLinterPath(nameOrPath);
if (!resolvedPath) {
console.error(`⚠️ [linter] 未找到自定义校验器 "${nameOrPath}",已自动安全降级至内置校验器。`);
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
try {
const fileUrl = pathToFileURL(resolvedPath).href;
const mod = await import(fileUrl);
const candidateFn = mod.default ?? mod.lintRule ?? mod.linter ?? mod.lint;
if (typeof candidateFn !== "function") {
console.error(
`⚠️ [linter] 自定义校验器 "${resolvedPath}" 未导出标准函数 (default / lintRule),已安全降级至内置校验器。`
);
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
// 执行期安全包装器:捕获用户自定义函数在运行期间可能抛出的任何未捕获异常
const safeLinter: RuleLinterFn = async (rule: RuleLintTarget, context?: RuleLintContext): Promise<RuleLintResult> => {
try {
const result = await candidateFn(rule, context);
if (result && typeof result === "object" && typeof result.score === "number" && Array.isArray(result.issues)) {
return result;
}
console.error(`⚠️ [linter] 自定义校验器返回值格式不符合 RuleLintResult 契约,已回退至内置结果。`);
return builtinRuleLinter(rule);
} catch (runtimeErr) {
console.error(`⚠️ [linter] 自定义校验器执行异常:`, runtimeErr);
return builtinRuleLinter(rule);
}
};
return {
name: nameOrPath,
type: "custom",
filePath: resolvedPath,
linter: safeLinter
};
} catch (err: any) {
console.error(
`⚠️ [linter] 加载自定义校验器脚本 "${resolvedPath}" 失败(语法错误或依赖缺失: ${err?.message ?? err}),已自动安全降级至内置校验器。`
);
return {
name: "builtin",
type: "builtin",
linter: builtinRuleLinter
};
}
}
+94
View File
@@ -0,0 +1,94 @@
import type { LoadedLinter } from "./loader.js";
import type {
RuleLintBatchResult,
RuleLintContext,
RuleLintItemResult,
RuleLintResult,
RuleLintTarget
} from "./types.js";
export interface LintServiceOptions {
level?: "all" | "error" | "warning";
minScore?: number;
summary?: boolean;
}
export async function lintSingleRule(
rule: RuleLintTarget,
loadedLinter: LoadedLinter,
context?: RuleLintContext
): Promise<RuleLintItemResult> {
const result = await loadedLinter.linter(rule, context);
return {
ruleId: rule.id,
ruleCode: rule.code,
ruleName: rule.name,
score: result.score,
passed: result.passed,
issues: result.issues,
description: rule.description
};
}
export async function lintRuleBatch(
rules: RuleLintTarget[],
loadedLinter: LoadedLinter,
context?: RuleLintContext,
options?: LintServiceOptions
): Promise<RuleLintBatchResult> {
const minScoreThreshold = options?.minScore ?? 0;
const levelFilter = options?.level ?? "all";
const itemResults: RuleLintItemResult[] = [];
let totalScoreSum = 0;
for (const rule of rules) {
const rawItem = await lintSingleRule(rule, loadedLinter, context);
totalScoreSum += rawItem.score;
// 根据 level 进行过滤
let filteredIssues = rawItem.issues;
if (levelFilter === "error") {
filteredIssues = rawItem.issues.filter((i) => i.level === "error");
} else if (levelFilter === "warning") {
filteredIssues = rawItem.issues.filter((i) => i.level === "warning" || i.level === "error");
}
const itemPassed = filteredIssues.every((i) => i.level !== "error");
if (options?.summary) {
// 总结模式:只记录有问题的规则项
if (filteredIssues.length > 0) {
itemResults.push({
...rawItem,
passed: itemPassed,
issues: filteredIssues
});
}
} else {
itemResults.push({
...rawItem,
passed: itemPassed,
issues: filteredIssues
});
}
}
const totalRules = rules.length;
const overallScore = totalRules === 0 ? 100 : Math.round(totalScoreSum / totalRules);
const issueCount = itemResults.filter((r) => r.issues.length > 0).length;
const healthyCount = totalRules - issueCount;
const passed = overallScore >= minScoreThreshold && itemResults.every((r) => r.passed);
return {
linter: loadedLinter.name,
linterType: loadedLinter.type,
totalRules,
healthyCount,
issueCount,
overallScore,
passed,
issues: itemResults
};
}
+61
View File
@@ -0,0 +1,61 @@
import { z } from "zod";
export const RuleLintIssueSchema = z.object({
level: z.enum(["error", "warning", "info"]),
code: z.string(),
message: z.string(),
snippet: z.string().optional(),
suggestion: z.string().optional()
});
export const RuleLintResultSchema = z.object({
score: z.number().min(0).max(100),
passed: z.boolean(),
issues: z.array(RuleLintIssueSchema)
});
export const RuleLintItemResultSchema = z.object({
ruleId: z.string().optional(),
ruleCode: z.string().optional(),
ruleName: z.string().optional(),
score: z.number().min(0).max(100),
passed: z.boolean(),
issues: z.array(RuleLintIssueSchema),
description: z.string().optional()
});
export const RuleLintBatchResultSchema = z.object({
linter: z.string(),
linterType: z.enum(["builtin", "custom"]),
totalRules: z.number(),
healthyCount: z.number(),
issueCount: z.number(),
overallScore: z.number().min(0).max(100),
passed: z.boolean(),
issues: z.array(RuleLintItemResultSchema)
});
export type RuleLintIssue = z.infer<typeof RuleLintIssueSchema>;
export type RuleLintResult = z.infer<typeof RuleLintResultSchema>;
export type RuleLintItemResult = z.infer<typeof RuleLintItemResultSchema>;
export type RuleLintBatchResult = z.infer<typeof RuleLintBatchResultSchema>;
export interface RuleLintTarget {
id?: string;
code?: string;
name?: string;
description: string;
scope?: string;
strictness?: string;
}
export interface RuleLintContext {
corpId?: string;
versionNumber?: number;
allRules?: RuleLintTarget[];
}
export type RuleLinterFn = (
rule: RuleLintTarget,
context?: RuleLintContext
) => Promise<RuleLintResult> | RuleLintResult;
@@ -0,0 +1,154 @@
import type { AttachmentGroup, MaterialAttachmentPlan, MaterialDocument, MaterialField } from "./types.js"
import { MaterialPackValidationError } from "./types.js"
import type { ZipEntry } from "./validate.js"
import type { Parsed } from "./parse.js"
// ─── Key deduplication (applied at call site in parse.ts; exported for tests) ─
export function deduplicateKeys(groups: AttachmentGroup[]): AttachmentGroup[] {
const seen = new Map<string, number>()
return groups.map((g) => {
const count = (seen.get(g.key) ?? 0) + 1
seen.set(g.key, count)
return count === 1 ? g : { ...g, key: `${g.key}-${count}` }
})
}
// ─── Build attachment plans with strict bidirectional validation ──────────────
export function buildAttachmentPlans(
entries: ZipEntry[],
parsed: Parsed[]
): MaterialAttachmentPlan[] {
const errors: string[] = []
// Map of path -> Array of declaration locations: { documentId, location }
const declaredPathLocations = new Map<string, Array<{ documentId: string; location: string }>>()
const plans: MaterialAttachmentPlan[] = parsed.map((item) => {
const { documentAttachments, expenseAttachments, personAttachments } = item
const docId = item.document.documentId
const recordPath = (path: string, location: string) => {
// 1. Check directory scope: path must start with docId/ or docId@.../
const rootDir = path.split("/")[0]!
const atIdx = rootDir.indexOf("@")
const dirDocId = atIdx >= 0 ? rootDir.slice(0, atIdx) : rootDir
if (dirDocId !== docId) {
errors.push(
`单据「${docId}」声明了跨单据或非本单据目录的附件路径: ${path}。附件必须位于该单据自己的根目录「${docId}/」或「${docId}@备注/」下。`
)
}
// 2. Track path location for uniqueness check
const existing = declaredPathLocations.get(path)
if (existing) {
existing.push({ documentId: docId, location })
} else {
declaredPathLocations.set(path, [{ documentId: docId, location }])
}
}
for (const g of documentAttachments) {
g.paths.forEach((p) => recordPath(p, `主表 [附件]${g.label}`))
}
for (const [rowIdxStr, groups] of Object.entries(expenseAttachments)) {
const rowNum = Number(rowIdxStr) + 1
for (const g of groups) {
g.paths.forEach((p) => recordPath(p, `费用明细行 ${rowNum} [附件]${g.label}`))
}
}
for (const [personName, groups] of Object.entries(personAttachments)) {
for (const g of groups) {
g.paths.forEach((p) => recordPath(p, `劳务人员「${personName}」[附件]${g.label}`))
}
}
return {
documentId: docId,
categoryFields: documentAttachments,
expenseAttachments,
personAttachments,
}
})
// Duplicate path check: the same path cannot be declared multiple times (even in same document)
for (const [path, locs] of declaredPathLocations.entries()) {
if (locs.length > 1) {
const locDescriptions = locs.map((l) => `单据「${l.documentId}」的 ${l.location}`).join("、")
errors.push(
`附件路径「${path}」被重复声明了 ${locs.length} 次(出现在 ${locDescriptions})。禁止复用同一路径,若需在不同单据或不同字段使用,请分别放置到独立的附件文件路径。`
)
}
}
// xlsx-only mode: skip file-level checks against ZIP entries
if (!entries.length) {
if (errors.length) throw new MaterialPackValidationError(errors)
return plans
}
// Check 3: every declared path must exist as a ZIP entry
const zipFileSet = new Set(entries.map((e) => e.fileName))
for (const path of declaredPathLocations.keys()) {
if (!zipFileSet.has(path)) {
errors.push(`Excel 声明的附件路径在 ZIP 中不存在: ${path}`)
}
}
// Check 4: every ZIP file (non-信息表.xlsx) must be declared in exactly one [附件] column
for (const entry of entries) {
if (entry.fileName === "信息表.xlsx") continue
if (!declaredPathLocations.has(entry.fileName)) {
errors.push(`ZIP 中的文件未在 Excel 任何 [附件] 列中声明: ${entry.fileName}`)
}
}
if (errors.length) throw new MaterialPackValidationError(errors)
return plans
}
// ─── Inject attachment plan into document ─────────────────────────────────────
export function injectAttachmentPlan(
document: MaterialDocument,
plan: MaterialAttachmentPlan,
uploaded: Map<string, unknown[]>
): MaterialDocument {
const clone = structuredClone(document)
const lookup = (path: string) => {
if (uploaded.has(path)) return uploaded.get(path)!
// preview fallback: return a placeholder representing the file
return [{ path, fileName: path.split("/").pop() ?? path }]
}
// Root-level document fields
for (const group of plan.categoryFields) {
const value = group.paths.flatMap(lookup)
clone.fields.push({ key: group.key, label: group.label, type: "ATTACHMENT", value })
}
// daoshi_list (labor) rows
const laborList = clone.fields.find((f) => f.key === "daoshi_list" && f.type === "LIST")
if (laborList && Array.isArray(laborList.value)) {
for (const row of laborList.value as MaterialField[][]) {
const name = row.find((f) => f.key === "name")?.value
for (const group of plan.personAttachments[String(name)] ?? []) {
row.push({ key: group.key, label: group.label, type: "ATTACHMENT", value: group.paths.flatMap(lookup) })
}
}
}
// mingxi_list (expense) rows
const expenseList = clone.fields.find((f) => f.key === "mingxi_list" && f.type === "LIST")
if (expenseList && Array.isArray(expenseList.value)) {
for (let i = 0; i < expenseList.value.length; i++) {
const row = expenseList.value[i] as MaterialField[]
for (const group of plan.expenseAttachments[i] ?? []) {
row.push({ key: group.key, label: group.label, type: "ATTACHMENT", value: group.paths.flatMap(lookup) })
}
}
}
return clone
}
+7
View File
@@ -0,0 +1,7 @@
export * from "./types.js";
export * from "./signature.js";
export * from "./validate.js";
export * from "./parse.js";
export * from "./attachments.js";
export * from "./service.js";
export * from "./ready.js";
@@ -0,0 +1,489 @@
import ExcelJS from "exceljs"
import { describe, expect, test } from "bun:test"
import { previewMaterialPack } from "./service.js"
import { signWebhookPayload } from "./signature.js"
import {
isAttachmentColumn,
attachmentLabel,
attachmentKey,
parsePaths,
collectRowAttachments,
} from "./parse.js"
import { buildAttachmentPlans } from "./attachments.js"
import { MaterialPackValidationError } from "./types.js"
// ─── Workbook fixtures ────────────────────────────────────────────────────────
async function workbookBuffer() {
const workbook = new ExcelJS.Workbook()
const main = workbook.addWorksheet("会议")
main.addRow(["会议编号", "会议名称", "总金额", "申请日期", "[附件]合同协议", "[附件]支付凭证"])
main.addRow(["DOC-001", "测试单据", 100, "2026-09-03 12:00:00", "", ""])
const labor = workbook.addWorksheet("劳务明细")
labor.addRow(["会议编号", "姓名", "劳务费用", "[附件]身份证"])
labor.addRow(["DOC-001", "张三", 100, ""])
return Buffer.from(await workbook.xlsx.writeBuffer())
}
async function workbookWithAttachmentPaths() {
const workbook = new ExcelJS.Workbook()
const main = workbook.addWorksheet("会议")
main.addRow(["会议编号", "会议名称", "总金额", "申请日期", "[附件]合同协议", "[附件]支付凭证"])
main.addRow([
"DOC-001",
"测试单据",
100,
"2026-09-03 12:00:00",
"DOC-001/合同协议/采购合同.pdf",
"DOC-001/支付凭证/支付宝.pdf",
])
return Buffer.from(await workbook.xlsx.writeBuffer())
}
// ─── Unit tests: attachment column helpers ───────────────────────────────────
describe("attachment column helpers", () => {
test("isAttachmentColumn", () => {
expect(isAttachmentColumn("[附件]合同协议")).toBe(true)
expect(isAttachmentColumn("合同协议")).toBe(false)
expect(isAttachmentColumn("[附件]")).toBe(true)
})
test("attachmentLabel strips prefix", () => {
expect(attachmentLabel("[附件]合同协议")).toBe("合同协议")
expect(attachmentLabel("合同协议")).toBe("合同协议")
})
test("attachmentKey lowercases and replaces spaces", () => {
expect(attachmentKey("[附件]Contract Doc")).toBe("contract_doc")
expect(attachmentKey("[附件]合同协议")).toBe("合同协议")
})
test("parsePaths splits by newline, comma, semicolon", () => {
expect(parsePaths("a/b.pdf\nc/d.pdf")).toEqual(["a/b.pdf", "c/d.pdf"])
expect(parsePaths("a/b.pdf,c/d.pdf")).toEqual(["a/b.pdf", "c/d.pdf"])
expect(parsePaths("a/b.pdf;c/d.pdf")).toEqual(["a/b.pdf", "c/d.pdf"])
expect(parsePaths("a/b.pdf,c/d.pdf")).toEqual(["a/b.pdf", "c/d.pdf"])
expect(parsePaths(null)).toEqual([])
expect(parsePaths("")).toEqual([])
})
})
// ─── Unit tests: buildAttachmentPlans ───────────────────────────────────────
describe("buildAttachmentPlans", () => {
test("xlsx-only mode: no file checks performed", async () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
// No ZIP entries = xlsx-only mode, no validation
const plans = buildAttachmentPlans([], parsed)
expect(plans).toHaveLength(1)
expect(plans[0]?.categoryFields[0]?.paths).toEqual(["DOC-001/合同/a.pdf"])
})
test("throws when Excel declares path missing from ZIP", async () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/b.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
expect(() => buildAttachmentPlans(entries, parsed)).toThrow(MaterialPackValidationError)
try {
buildAttachmentPlans(entries, parsed)
} catch (e) {
const err = e as MaterialPackValidationError
expect(err.errors.some((m) => m.includes("DOC-001/合同/a.pdf") && m.includes("不存在"))).toBe(true)
expect(err.errors.some((m) => m.includes("DOC-001/合同/b.pdf") && m.includes("未在 Excel"))).toBe(true)
}
})
test("throws when ZIP file is not declared in any [附件] column", async () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/undeclared.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
expect(() => buildAttachmentPlans(entries, parsed)).toThrow(MaterialPackValidationError)
try {
buildAttachmentPlans(entries, parsed)
} catch (e) {
const err = e as MaterialPackValidationError
expect(err.errors.some((m) => m.includes("undeclared.pdf"))).toBe(true)
}
})
test("passes when all paths match bidirectionally", () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
const plans = buildAttachmentPlans(entries, parsed)
expect(plans[0]?.categoryFields[0]?.paths).toEqual(["DOC-001/合同/a.pdf"])
})
test("throws when document declares attachment outside its own directory", () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-002/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
{
document: { type: "document" as const, documentId: "DOC-002", documentSN: "DOC-002", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-002/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
try {
buildAttachmentPlans(entries, parsed)
expect(true).toBe(false)
} catch (e) {
const err = e as MaterialPackValidationError
expect(err.errors.some((m) => m.includes("DOC-001") && m.includes("跨单据或非本单据目录"))).toBe(true)
}
})
test("throws when same path is declared multiple times within the same document", () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {
0: [{ key: "invoice", label: "发票", paths: ["DOC-001/合同/a.pdf"] }],
},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
try {
buildAttachmentPlans(entries, parsed)
expect(true).toBe(false)
} catch (e) {
const err = e as MaterialPackValidationError
expect(err.errors.some((m) => m.includes("重复声明") && m.includes("DOC-001/合同/a.pdf"))).toBe(true)
}
})
test("throws when same path is declared across different documents", () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
{
document: { type: "document" as const, documentId: "DOC-002", documentSN: "DOC-002", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
try {
buildAttachmentPlans(entries, parsed)
expect(true).toBe(false)
} catch (e) {
const err = e as MaterialPackValidationError
expect(err.errors.some((m) => m.includes("重复声明") && m.includes("DOC-001/合同/a.pdf"))).toBe(true)
}
})
test("accepts attachment paths in directory with @annotation", () => {
const parsed = [
{
document: { type: "document" as const, documentId: "DOC-001", documentSN: "DOC-001", startTime: null, fields: [] },
laborNames: [],
documentAttachments: [{ key: "contract", label: "合同", paths: ["DOC-001@广州技术服务/合同/a.pdf"] }],
expenseAttachments: {},
personAttachments: {},
},
]
const entries = [
{ fileName: "信息表.xlsx", uncompressedSize: 100, compressedSize: 80, raw: {} },
{ fileName: "DOC-001@广州技术服务/合同/a.pdf", uncompressedSize: 100, compressedSize: 80, raw: {} },
]
const plans = buildAttachmentPlans(entries, parsed)
expect(plans).toHaveLength(1)
expect(plans[0]?.categoryFields[0]?.paths).toEqual(["DOC-001@广州技术服务/合同/a.pdf"])
})
})
// ─── Integration tests: previewMaterialPack ──────────────────────────────────
describe("Webhook material pack", () => {
test("previews official workbook shape without network access", async () => {
const result = await previewMaterialPack(await workbookBuffer(), "材料包.xlsx")
expect(result.documents).toHaveLength(1)
expect(result.documents[0]).toMatchObject({ documentId: "DOC-001", documentSN: "DOC-001" })
expect(result.documents[0]?.fields).toContainEqual(expect.objectContaining({ key: "daoshi_list", type: "LIST" }))
})
test("parses [附件] columns from main sheet into categoryFields", async () => {
const result = await previewMaterialPack(await workbookWithAttachmentPaths(), "材料包.xlsx")
const plan = result.attachmentPlan[0]!
expect(plan.categoryFields).toHaveLength(2)
expect(plan.categoryFields[0]).toMatchObject({ label: "合同协议", paths: ["DOC-001/合同协议/采购合同.pdf"] })
expect(plan.categoryFields[1]).toMatchObject({ label: "支付凭证", paths: ["DOC-001/支付凭证/支付宝.pdf"] })
})
test("injects ATTACHMENT fields into document on preview", async () => {
const result = await previewMaterialPack(await workbookWithAttachmentPaths(), "材料包.xlsx")
const doc = result.documents[0]!
const contractField = doc.fields.find((f) => f.label === "合同协议")
expect(contractField).toBeDefined()
expect(contractField?.type).toBe("ATTACHMENT")
expect(Array.isArray(contractField?.value)).toBe(true)
})
test("uses the confirmed timestamp.nonce.payload HMAC contract", () => {
expect(signWebhookPayload(1700000000, "nonce", { webhookId: "wh-1", value: 1 }, "secret"))
.toBe("d65d858afb6adc33dc640ebc6b259861c2b73ef0e6f0995ff822b41465fbfdf1")
})
test("checkWebhookReadiness locks single webhook as default", async () => {
const { checkWebhookReadiness } = await import("./ready.js")
const mockCorp: any = {
id: "test-corp",
name: "测试企业",
seal: { url: "https://test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal" }
}
const client: any = {
get: (url: string) => {
if (url.includes("auth/me")) return { json: async () => ({ data: { user: { id: "u-1", name: "管理员", tenantId: "t-1" }, tenant: { id: "t-1", name: "测试租户" } } }) }
if (url.includes("ai-approval/config")) return {
json: async () => ({
data: {
integrations: [{
type: "webhook",
id: "wh-only",
name: "唯一通道",
mode: "assisted",
incomingDocumentWebhook: { id: "in-1", url: "https://test.sealai.cc/webhook/wh-only/document" },
outgoingResultWebhook: "https://example.com/callback",
incomingManualResultWebhook: { id: "man-1", url: "https://test.sealai.cc/webhook/wh-only/manual" },
secret: "sec-1"
}]
}
})
}
throw new Error(url)
}
}
const res = await checkWebhookReadiness(client, mockCorp)
expect(res.ready).toBe(true)
expect(res.authStatus).toBe("ok")
expect(res.corp.name).toBe("测试企业")
expect(res.corp.tenant?.name).toBe("测试租户")
expect(res.activeWebhooks).toHaveLength(1)
expect(res.activeWebhooks[0]?.isDefault).toBe(true)
expect(res.defaultWebhook).toEqual({ id: "wh-only", name: "唯一通道", mode: "assisted" })
expect(res.nextAction).toContain("seal-use webhook material-pack push")
expect(res.statusMessage).toContain("已自动锁定唯一 Webhook 通道")
})
test("checkWebhookReadiness lists multiple webhooks without auto-locking", async () => {
const { checkWebhookReadiness } = await import("./ready.js")
const mockCorp: any = {
id: "test-corp",
name: "测试企业",
seal: { url: "https://test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal" }
}
const client: any = {
get: (url: string) => {
if (url.includes("auth/me")) return { json: async () => ({ data: { user: { id: "u-1", name: "管理员", tenantId: "t-1" }, tenant: { id: "t-1", name: "测试租户" } } }) }
if (url.includes("ai-approval/config")) return {
json: async () => ({
data: {
integrations: [
{
type: "webhook",
id: "wh-1",
name: "通道A",
mode: "assisted",
incomingDocumentWebhook: { id: "in-1", url: "https://test.sealai.cc/webhook/wh-1/document" },
outgoingResultWebhook: "https://example.com/callback-a",
incomingManualResultWebhook: { id: "man-1", url: "https://test.sealai.cc/webhook/wh-1/manual" },
secret: "sec-1"
},
{
type: "webhook",
id: "wh-2",
name: "通道B",
mode: "fully_automatic",
incomingDocumentWebhook: { id: "in-2", url: "https://test.sealai.cc/webhook/wh-2/document" },
outgoingResultWebhook: "https://example.com/callback-b",
incomingManualResultWebhook: { id: "man-2", url: "https://test.sealai.cc/webhook/wh-2/manual" },
secret: "sec-2"
}
]
}
})
}
throw new Error(url)
}
}
const res = await checkWebhookReadiness(client, mockCorp)
expect(res.ready).toBe(true)
expect(res.activeWebhooks).toHaveLength(2)
expect(res.defaultWebhook).toBeNull()
expect(res.activeWebhooks[0]?.isDefault).toBeUndefined()
expect(res.nextAction).toContain("--webhook <webhookIdOrName>")
expect(res.statusMessage).toContain("检测到 2 个 Webhook 通道")
})
test("checkWebhookReadiness flags not ready when no webhooks exist", async () => {
const { checkWebhookReadiness } = await import("./ready.js")
const mockCorp: any = {
id: "test-corp",
name: "测试企业",
seal: { url: "https://test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal" }
}
const client: any = {
get: (url: string) => {
if (url.includes("auth/me")) return { json: async () => ({ data: { user: { id: "u-1", name: "管理员", tenantId: "t-1" }, tenant: { id: "t-1", name: "测试租户" } } }) }
if (url.includes("ai-approval/config")) return { json: async () => ({ data: { integrations: [] } }) }
throw new Error(url)
}
}
const res = await checkWebhookReadiness(client, mockCorp)
expect(res.ready).toBe(false)
expect(res.activeWebhooks).toHaveLength(0)
expect(res.nextAction).toContain("seal-use webhook add")
})
test("checkWebhookReadiness flags not ready when auth fails", async () => {
const { checkWebhookReadiness } = await import("./ready.js")
const mockCorp: any = {
id: "test-corp",
name: "测试企业",
seal: { url: "https://test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal" }
}
const client: any = {
get: () => {
throw new Error("401 Unauthorized")
}
}
const res = await checkWebhookReadiness(client, mockCorp)
expect(res.ready).toBe(false)
expect(res.authStatus).toBe("error")
expect(res.nextAction).toContain("seal-use auth diagnose")
})
test("checkWebhookReadiness validates material pack file when provided", async () => {
const { checkWebhookReadiness } = await import("./ready.js")
const mockCorp: any = {
id: "test-corp",
name: "测试企业",
seal: { url: "https://test.sealai.cc", endpoints: { approvalStylePreferences: "api/v1/agent/ai-approval/config" } },
source: { type: "seal" }
}
const client: any = {
get: (url: string) => {
if (url.includes("auth/me")) return { json: async () => ({ data: { user: { id: "u-1", name: "管理员", tenantId: "t-1" }, tenant: { id: "t-1", name: "测试租户" } } }) }
if (url.includes("ai-approval/config")) return {
json: async () => ({
data: {
integrations: [{
type: "webhook",
id: "wh-1",
name: "通道A",
mode: "assisted",
incomingDocumentWebhook: { id: "in-1", url: "https://test.sealai.cc/webhook/wh-1/document" },
outgoingResultWebhook: "https://example.com/callback",
incomingManualResultWebhook: { id: "man-1", url: "https://test.sealai.cc/webhook/wh-1/manual" },
secret: "sec-1"
}]
}
})
}
throw new Error(url)
}
}
const notFoundRes = await checkWebhookReadiness(client, mockCorp, { filePath: "/tmp/non-existent-pack.zip" })
expect(notFoundRes.ready).toBe(false)
expect(notFoundRes.materialPack?.valid).toBe(false)
expect(notFoundRes.statusMessage).toContain("材料包预检失败")
const tmpFile = `/tmp/test-material-${Date.now()}.xlsx`
const { writeFileSync, unlinkSync } = await import("node:fs")
writeFileSync(tmpFile, await workbookBuffer())
try {
const validRes = await checkWebhookReadiness(client, mockCorp, { filePath: tmpFile })
expect(validRes.ready).toBe(true)
expect(validRes.materialPack?.valid).toBe(true)
expect(validRes.materialPack?.documentCount).toBe(1)
expect(validRes.nextAction).toContain(tmpFile)
} finally {
unlinkSync(tmpFile)
}
})
test("@ annotation in ZIP dir names is accepted by validateDocIdDirectories", async () => {
// This tests that DOC-001@重新提交v2 correctly matches documentId DOC-001
// We build a ZIP-like structure by constructing entries manually and checking service's prepare path
// Since we can't easily build a real ZIP without writing to disk, we test the logic via buildAttachmentPlans
// with the paths already having the @annotation stripped in service.ts
// Verify the path stripping logic: if a ZIP entry has root "DOC-001@v2", its documentId becomes "DOC-001"
const rootWithAnnotation = "DOC-001@重新提交v2"
const atIdx = rootWithAnnotation.indexOf("@")
const stripped = atIdx >= 0 ? rootWithAnnotation.slice(0, atIdx) : rootWithAnnotation
expect(stripped).toBe("DOC-001")
})
})
+200
View File
@@ -0,0 +1,200 @@
import ExcelJS from "exceljs"
import { MaterialPackValidationError, type MaterialDocument, type MaterialField } from "./types.js"
export type DeclaredAttachment = { key: string; label: string; paths: string[] }
export type Parsed = {
document: MaterialDocument;
laborNames: string[];
documentAttachments: DeclaredAttachment[];
expenseAttachments: Record<number, DeclaredAttachment[]>;
personAttachments: Record<string, DeclaredAttachment[]>;
}
// ─── Attachment column helpers ───────────────────────────────────────────────
export function isAttachmentColumn(label: string): boolean {
return label.startsWith("[附件]")
}
export function attachmentLabel(label: string): string {
return label.startsWith("[附件]") ? label.slice(4) : label
}
export function attachmentKey(label: string): string {
const stripped = attachmentLabel(label)
return stripped.toLowerCase().replace(/\s+/g, "_") || "attachment"
}
export function parsePaths(raw: unknown): string[] {
if (raw == null || raw === "") return []
return String(raw)
.split(/[\n,;,;]/)
.map((s) => s.trim())
.filter(Boolean)
}
export function collectRowAttachments(
row: ExcelJS.Row,
map: Map<string, number>
): DeclaredAttachment[] {
const groups: DeclaredAttachment[] = []
for (const [colLabel, colIdx] of map.entries()) {
if (!isAttachmentColumn(colLabel)) continue
const raw = row.getCell(colIdx).value
const paths = parsePaths(raw)
if (!paths.length) continue
groups.push({
key: attachmentKey(colLabel),
label: attachmentLabel(colLabel),
paths,
})
}
return groups
}
// ─── Key deduplication ───────────────────────────────────────────────────────
function deduplicateKeys(groups: DeclaredAttachment[]): DeclaredAttachment[] {
const seen = new Map<string, number>()
return groups.map((g) => {
const count = (seen.get(g.key) ?? 0) + 1
seen.set(g.key, count)
return count === 1 ? g : { ...g, key: `${g.key}-${count}` }
})
}
// ─── Field builders ──────────────────────────────────────────────────────────
function field(key: string, label: string, type: string, value: unknown): MaterialField {
return { key, label, type, value }
}
function text(key: string, label: string, value: unknown) {
return field(key, label, "TEXT", value == null ? "" : String(value))
}
function amount(key: string, label: string, value: unknown) {
return field(key, label, "AMOUNT", typeof value === "number" ? { amount: value, currency: "CNY" } : null)
}
function dateValue(value: unknown): string | null {
if (value instanceof Date) return value.toISOString()
if (typeof value === "string" && value.trim()) return value.trim()
return null
}
function startTimeValue(value: unknown): number | null {
if (value instanceof Date) return Math.floor(value.getTime() / 1000)
if (typeof value === "string" && value.trim()) {
const timestamp = Date.parse(value.trim().replace(" ", "T"))
if (Number.isFinite(timestamp)) return Math.floor(timestamp / 1000)
}
return null
}
function headerMap(sheet: ExcelJS.Worksheet): Map<string, number> {
const map = new Map<string, number>()
sheet.getRow(1).eachCell((cell, index) => map.set(String(cell.value ?? "").trim(), index))
return map
}
function cell(row: ExcelJS.Row, map: Map<string, number>, name: string): unknown {
const index = map.get(name)
return index ? row.getCell(index).value : undefined
}
function buildMainFields(row: ExcelJS.Row, map: Map<string, number>): MaterialField[] {
const specs: Array<[string, string, string]> = [
["会议编号", "meeting_id", "TEXT"], ["会议名称", "meeting_name", "TEXT"], ["状态", "status", "TEXT"],
["总金额", "total_amount", "AMOUNT"], ["税前劳务总额", "pretax_labor_total", "AMOUNT"],
["报销事由", "reimbursement_reason", "TEXT"], ["po码", "po_code", "TEXT"], ["快递单号", "tracking_number", "TEXT"],
["申请日期", "application_date", "DATE"], ["更新日期", "updated_date", "DATE"]
]
return specs.flatMap(([label, key, type]) => {
const value = cell(row, map, label)
if (value == null || value === "") return []
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))]
})
}
function buildDetailFields(row: ExcelJS.Row, map: Map<string, number>, specs: Array<[string, string, string]>): MaterialField[] {
return specs.flatMap(([label, key, type]) => {
const value = cell(row, map, label)
if (value == null || value === "") return []
return [type === "TEXT" ? text(key, label, value) : type === "AMOUNT" ? amount(key, label, value) : field(key, label, type, dateValue(value))]
})
}
const laborSpecs: Array<[string, string, string]> = [["姓名", "name", "TEXT"], ["身份证号码", "id_number", "TEXT"], ["手机号", "phone", "TEXT"], ["劳务费用", "labor_fee", "AMOUNT"], ["税前费用", "pretax_fee", "AMOUNT"], ["开户行", "bank", "TEXT"], ["支行名称", "branch_name", "TEXT"], ["联行号", "bank_code", "TEXT"], ["银行卡号", "bank_card_number", "TEXT"]]
const expenseSpecs: Array<[string, string, string]> = [["报销金额", "reimbursement_amount", "AMOUNT"], ["费用类型", "expense_type", "TEXT"], ["发生时间", "occurrence_time", "DATE"], ["收款人", "payee", "TEXT"], ["开户行", "bank", "TEXT"], ["支行名称", "branch_name", "TEXT"], ["支行行号", "branch_code", "TEXT"], ["银行卡号", "bank_card_number", "TEXT"], ["费用说明", "expense_description", "TEXT"]]
// ─── Main parser ─────────────────────────────────────────────────────────────
export async function parseMaterialWorkbook(buffer: Uint8Array): Promise<Parsed[]> {
const workbook = new ExcelJS.Workbook()
await workbook.xlsx.load(Buffer.from(buffer) as any)
if (!workbook.worksheets.length) throw new MaterialPackValidationError(["信息表没有任何 Sheet"])
const sheets = workbook.worksheets
const mainSheet = sheets[0]!
const mainMap = headerMap(mainSheet)
const idColumn = mainMap.get("会议编号") ?? 1
const mainRows = (mainSheet.getRows(2, mainSheet.rowCount) ?? []).filter(
(row) => row.getCell(idColumn).value != null && row.getCell(idColumn).value !== ""
)
const ids = new Set<string>()
const laborSheet = sheets.find((sheet, index) => index > 0 && headerMap(sheet).has("姓名"))
const expenseSheet = sheets.find((sheet, index) => index > 0 && headerMap(sheet).has("报销金额"))
const laborMap = laborSheet ? headerMap(laborSheet) : undefined
const expenseMap = expenseSheet ? headerMap(expenseSheet) : undefined
const parsed: Parsed[] = mainRows.map((row) => {
const id = String(row.getCell(idColumn).value).trim()
if (!id) throw new MaterialPackValidationError(["主表会议编号不能为空"])
if (ids.has(id)) throw new MaterialPackValidationError([`主表会议编号重复: ${id}`])
ids.add(id)
const apply = cell(row, mainMap, "申请日期")
const laborRows = (laborSheet?.getRows(2, laborSheet.rowCount) ?? []).filter(
(r) => String(cell(r, laborMap!, "会议编号") ?? "").trim() === id
)
const expenseRows = (expenseSheet?.getRows(2, expenseSheet.rowCount) ?? []).filter(
(r) => String(cell(r, expenseMap!, "会议编号") ?? "").trim() === id
)
const laborNames = laborRows
.map((r) => String(cell(r, laborMap!, "姓名") ?? "").trim())
.filter(Boolean)
// Collect attachment declarations from main sheet row
const documentAttachments = deduplicateKeys(collectRowAttachments(row, mainMap))
// Collect expense attachment declarations per row index
const expenseAttachments: Record<number, DeclaredAttachment[]> = {}
expenseRows.forEach((r, rowIdx) => {
const groups = deduplicateKeys(collectRowAttachments(r, expenseMap!))
if (groups.length) expenseAttachments[rowIdx] = groups
})
// Collect person attachment declarations per person name
const personAttachments: Record<string, DeclaredAttachment[]> = {}
laborRows.forEach((r) => {
const name = String(cell(r, laborMap!, "姓名") ?? "").trim()
if (!name) return
const groups = deduplicateKeys(collectRowAttachments(r, laborMap!))
if (groups.length) personAttachments[name] = groups
})
const fields = buildMainFields(row, mainMap)
if (laborRows.length) fields.push({ key: "daoshi_list", label: "导师列表", type: "LIST", value: laborRows.map((r) => buildDetailFields(r, laborMap!, laborSpecs)) })
if (expenseRows.length) fields.push({ key: "mingxi_list", label: "明细列表", type: "LIST", value: expenseRows.map((r) => buildDetailFields(r, expenseMap!, expenseSpecs)) })
return {
laborNames,
documentAttachments,
expenseAttachments,
personAttachments,
document: { type: "document", documentId: id, documentSN: id, startTime: startTimeValue(apply), fields },
}
})
return parsed
}
+146
View File
@@ -0,0 +1,146 @@
import type { KyInstance } from "ky";
import { existsSync } from "node:fs";
import type { CorpConfig } from "../../../core/config/types.js";
import { loadGlobalConfig } from "../../../core/config/loader.js";
import * as api from "../api.js";
import type { WebhookIntegration } from "../types.js";
import { previewMaterialPack, readMaterialPackFile } from "./service.js";
import type { WebhookReadyResult } from "./types.js";
export async function checkWebhookReadiness(
client: KyInstance,
corp: CorpConfig,
options: { filePath?: string } = {}
): Promise<WebhookReadyResult> {
const globalConfig = loadGlobalConfig();
const stateMode = globalConfig.stateful ? "stateful" : "stateless";
let authStatus: "ok" | "error" = "ok";
let authError: string | undefined;
let tenantInfo: WebhookReadyResult["corp"]["tenant"];
let userInfo: WebhookReadyResult["corp"]["user"];
try {
const me = await api.getMe(client);
userInfo = {
id: me.user.id,
name: me.user.name,
isAdmin: me.user.isAdmin
};
tenantInfo = {
id: me.tenant.id,
name: me.tenant.name,
tenantSlug: me.tenant.tenantSlug,
corporationName: me.tenant.hoseCorpConfig?.corporationName
};
} catch (err) {
authStatus = "error";
authError = err instanceof Error ? err.message : String(err);
}
let rawWebhooks: WebhookIntegration[] = [];
if (authStatus === "ok") {
try {
rawWebhooks = await api.listWebhookIntegrations(
client,
corp.seal.endpoints.approvalStylePreferences
);
} catch (err) {
authStatus = "error";
authError = `读取 Webhook 配置失败: ${err instanceof Error ? err.message : String(err)}`;
}
}
const isSingle = rawWebhooks.length === 1;
const activeWebhooks = rawWebhooks.map((w) => ({
id: w.id,
name: w.name,
mode: w.mode,
incomingDocumentWebhookUrl: w.incomingDocumentWebhook.url,
outgoingResultWebhookUrl: w.outgoingResultWebhook,
autoApprovalRate: w.autoApprovalRate,
...(isSingle ? { isDefault: true } : {})
}));
const defaultWebhook = isSingle
? { id: rawWebhooks[0]!.id, name: rawWebhooks[0]!.name, mode: rawWebhooks[0]!.mode }
: null;
let materialPack: WebhookReadyResult["materialPack"];
if (options.filePath) {
if (!existsSync(options.filePath)) {
materialPack = {
valid: false,
filePath: options.filePath,
fileName: options.filePath.split(/[\\/]/).pop() ?? options.filePath,
documentCount: 0,
errors: [`文件不存在: ${options.filePath}`]
};
} else {
try {
const input = readMaterialPackFile(options.filePath);
const preview = await previewMaterialPack(input.fileBuffer, input.fileName);
materialPack = {
valid: true,
filePath: options.filePath,
fileName: input.fileName,
documentCount: preview.documents.length,
warnings: preview.warnings
};
} catch (err) {
materialPack = {
valid: false,
filePath: options.filePath,
fileName: options.filePath.split(/[\\/]/).pop() ?? options.filePath,
documentCount: 0,
errors: [err instanceof Error ? err.message : String(err)]
};
}
}
}
const materialPackOk = materialPack ? materialPack.valid : true;
const ready = authStatus === "ok" && activeWebhooks.length > 0 && materialPackOk;
const corpFlag = stateMode === "stateful" ? "" : ` --corp ${corp.id}`;
let nextAction = "";
let statusMessage = "";
if (authStatus !== "ok") {
statusMessage = `凭证鉴权异常: ${authError}`;
nextAction = `seal-use auth diagnose${corpFlag}`;
} else if (activeWebhooks.length === 0) {
statusMessage = "当前企业尚未配置任何 Webhook 集成通道";
nextAction = `seal-use webhook add --name "默认入站通道" --result-url "https://your-domain.com/callback"${corpFlag}`;
} else if (materialPack && !materialPack.valid) {
statusMessage = `材料包预检失败: ${materialPack.errors?.join("; ")}`;
nextAction = `seal-use webhook material-pack preview ${materialPack.filePath}${corpFlag}`;
} else {
statusMessage = isSingle
? "所有通道正常,已自动锁定唯一 Webhook 通道,等待载入"
: `所有通道正常,检测到 ${activeWebhooks.length} 个 Webhook 通道,等待载入`;
const targetFile = materialPack?.filePath ?? "<材料包.zip>";
const webhookOption = isSingle ? "" : ` --webhook ${defaultWebhook ? defaultWebhook.id : "<webhookIdOrName>"}`;
nextAction = `seal-use webhook material-pack push ${targetFile}${webhookOption}${corpFlag}`;
}
return {
ready,
corp: {
id: corp.id,
name: corp.name,
sourceType: corp.source.type,
tenant: tenantInfo,
user: userInfo
},
stateMode,
authStatus,
authError,
activeWebhooks,
defaultWebhook,
materialPack,
statusMessage,
nextAction
};
}
+144
View File
@@ -0,0 +1,144 @@
import { readFileSync } from "node:fs"
import { webhookHeaders } from "./signature.js"
import { buildAttachmentPlans, injectAttachmentPlan } from "./attachments.js"
import { parseMaterialWorkbook } from "./parse.js"
import { extractZipEntry, readZipEntries, validatePackEntries, type ZipEntry } from "./validate.js"
import { MaterialPackValidationError, type MaterialPackPreview, type MaterialPackPushResult } from "./types.js"
function webhookInfo(url: string): { baseUrl: string; webhookId: string } {
const parsed = new URL(url)
const match = parsed.pathname.match(/\/webhook\/([^/]+)/)
if (!match) throw new Error("Webhook URL 必须包含 /webhook/{webhookId}/document")
return { baseUrl: `${parsed.protocol}//${parsed.host}`, webhookId: match[1]! }
}
function isZip(buffer: Uint8Array, fileName: string): boolean {
return fileName.toLowerCase().endsWith(".zip") || (buffer[0] === 0x50 && buffer[1] === 0x4b && !fileName.toLowerCase().endsWith(".xlsx"))
}
function validateDocIdDirectories(entries: ZipEntry[], documentIds: string[]): void {
if (!entries.length) return // xlsx-only mode, skip
// Extract documentId from dir name: strip @annotation suffix
const zipDocIds = new Set(
entries
.map((e) => {
const root = e.fileName.split("/")[0]!
const atIdx = root.indexOf("@")
return atIdx >= 0 ? root.slice(0, atIdx) : root
})
.filter((r) => r !== "信息表.xlsx")
)
const errors: string[] = []
// Every documentId must have a matching root directory (possibly with @annotation)
for (const id of documentIds) {
if (!zipDocIds.has(id)) {
errors.push(
`Excel 会议编号「${id}」在 ZIP 中找不到对应的根目录「${id}/」或「${id}@.../」。`
)
}
}
// Every root directory must correspond to a known documentId
const docIdSet = new Set(documentIds)
for (const zipDocId of zipDocIds) {
if (!docIdSet.has(zipDocId)) {
errors.push(
`ZIP 根目录对应的编号「${zipDocId}」在信息表中找不到对应的会议编号。`
)
}
}
if (errors.length) throw new MaterialPackValidationError(errors)
}
async function prepare(fileBuffer: Uint8Array, fileName: string) {
let entries: ZipEntry[] = []
let workbook = fileBuffer
if (isZip(fileBuffer, fileName)) {
entries = await readZipEntries(fileBuffer)
validatePackEntries(entries)
const info = entries.find((entry) => entry.fileName === "信息表.xlsx")
if (!info) throw new Error("ZIP 根目录缺少信息表.xlsx")
workbook = await extractZipEntry(fileBuffer, info)
}
const parsed = await parseMaterialWorkbook(workbook)
// Validate: ZIP root dir names must correspond to documentIds (supports @annotation suffix)
validateDocIdDirectories(entries, parsed.map((p) => p.document.documentId))
const plans = buildAttachmentPlans(entries, parsed)
const documents = parsed.map((item) => item.document)
return { entries, parsed, plans, documents, fileBuffer }
}
export async function previewMaterialPack(fileBuffer: Uint8Array, fileName: string): Promise<MaterialPackPreview> {
const prepared = await prepare(fileBuffer, fileName)
const documents = prepared.parsed.map((item, index) =>
injectAttachmentPlan(item.document, prepared.plans[index]!, new Map())
)
return { warnings: [], documents, attachmentPlan: prepared.plans }
}
export async function pushMaterialPack(
fileBuffer: Uint8Array,
fileName: string,
config: { webhookUrl: string; secret: string; docIdSuffix?: string }
): Promise<MaterialPackPushResult> {
const prepared = await prepare(fileBuffer, fileName)
const { baseUrl, webhookId } = webhookInfo(config.webhookUrl)
const results: MaterialPackPushResult["results"] = []
for (let index = 0; index < prepared.parsed.length; index += 1) {
const item = prepared.parsed[index]!
const plan = prepared.plans[index]!
const uploaded = new Map<string, unknown[]>()
// Collect all groups from all attachment levels
const allGroups = [
...plan.categoryFields,
...Object.values(plan.personAttachments).flat(),
...Object.values(plan.expenseAttachments).flat(),
]
for (const group of allGroups) {
for (const path of group.paths) {
if (uploaded.has(path)) continue // already uploaded this path
const zipEntry = prepared.entries.find((e) => e.fileName === path)
if (!zipEntry) continue
process.stderr.write(`⬆ 上传附件: ${path}\n`)
const body = new FormData()
const attachment = await extractZipEntry(prepared.fileBuffer, zipEntry)
const baseName = path.split("/").pop() ?? path
body.append("files", new File([new Uint8Array(attachment)], baseName))
const response = await fetch(
`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/attachments`,
{ method: "POST", headers: webhookHeaders({}, config.secret), body }
)
if (!response.ok) throw new Error(`附件上传失败 ${response.status}: ${await response.text()}`)
const json = await response.json() as { data?: unknown; attachments?: Array<{ data: unknown }> }
uploaded.set(path, json.attachments?.map((v) => v.data) ?? (json.data === undefined ? [] : [json.data]))
process.stderr.write(`✓ 附件上传成功: ${path}\n`)
}
}
process.stderr.write(`📤 推送单据: ${item.document.documentId}\n`)
const document = injectAttachmentPlan(item.document, plan, uploaded)
const response = await fetch(
`${baseUrl}/api/v1/integrations/webhook/${encodeURIComponent(webhookId)}/document`,
{
method: "POST",
headers: { "Content-Type": "application/json", ...webhookHeaders({ webhookId, ...document }, config.secret) },
body: JSON.stringify(document),
}
)
if (!response.ok) throw new Error(`Webhook 单据推送失败 ${response.status}: ${await response.text()}`)
results.push({ documentId: document.documentId, document, pushResult: await response.json() })
process.stderr.write(`✓ 单据推送成功: ${document.documentId}\n`)
}
return { warnings: [], results }
}
export function readMaterialPackFile(filePath: string): { fileBuffer: Buffer; fileName: string } {
return { fileBuffer: readFileSync(filePath), fileName: filePath.split(/[\\\/]/).pop() ?? "material-pack.zip" }
}
@@ -0,0 +1,18 @@
import { createHmac, randomBytes } from "node:crypto";
export function signWebhookPayload(timestamp: number, nonce: string, payload: unknown, secret: string): string {
return createHmac("sha256", secret)
.update(`${timestamp}.${nonce}.${JSON.stringify(payload)}`)
.digest("hex");
}
export function webhookHeaders(payload: unknown, secret: string): Record<string, string> {
const timestamp = Math.floor(Date.now() / 1000);
const nonce = randomBytes(16).toString("hex");
return {
Authorization: `Bearer ${secret}`,
"x-webhook-signature": signWebhookPayload(timestamp, nonce, payload, secret),
"x-webhook-timestamp": String(timestamp),
"x-webhook-nonce": nonce
};
}
+92
View File
@@ -0,0 +1,92 @@
export type MaterialField = {
key: string;
label: string;
type: string;
value: unknown;
};
export type MaterialDocument = {
type: "document";
documentId: string;
documentSN: string;
startTime: number | null;
fields: MaterialField[];
};
export type AttachmentGroup = {
key: string; // derived from label: attachmentKey(label)
label: string; // [附件] prefix stripped
paths: string[]; // full ZIP-relative paths
};
export type MaterialAttachmentPlan = {
documentId: string;
categoryFields: AttachmentGroup[]; // root document level
personAttachments: Record<string, AttachmentGroup[]>; // daoshi_list, keyed by person name
expenseAttachments: Record<number, AttachmentGroup[]>; // mingxi_list, keyed by row index
};
export type MaterialPackPreview = {
warnings: string[];
documents: MaterialDocument[];
attachmentPlan: MaterialAttachmentPlan[];
};
export type MaterialPackPushResult = {
warnings: string[];
results: Array<{ documentId: string; document: MaterialDocument; pushResult: unknown }>;
};
export class MaterialPackValidationError extends Error {
constructor(public readonly errors: string[], public readonly warnings: string[] = []) {
super(`材料包校验失败:${errors.length} 个错误`)
this.name = "MaterialPackValidationError"
}
}
export type WebhookReadyResult = {
ready: boolean;
corp: {
id: string;
name: string;
sourceType: string;
tenant?: {
id: string;
name: string;
tenantSlug?: string;
corporationName?: string;
};
user?: {
id: string;
name: string;
isAdmin?: boolean;
};
};
stateMode: "stateful" | "stateless";
authStatus: "ok" | "error";
authError?: string;
activeWebhooks: Array<{
id: string;
name: string;
mode: string;
incomingDocumentWebhookUrl: string;
outgoingResultWebhookUrl: string;
autoApprovalRate?: number;
isDefault?: boolean;
}>;
defaultWebhook: {
id: string;
name: string;
mode: string;
} | null;
materialPack?: {
valid: boolean;
filePath: string;
fileName: string;
documentCount: number;
errors?: string[];
warnings?: string[];
};
statusMessage: string;
nextAction: string;
};
@@ -0,0 +1,77 @@
import yauzl from "yauzl";
import iconv from "iconv-lite";
import { MaterialPackValidationError } from "./types.js";
export const MATERIAL_PACK_LIMITS = { maxEntries: 1000, maxTotalSize: 500 * 1024 * 1024, maxCompressionRatio: 150 };
export type ZipEntry = { fileName: string; uncompressedSize: number; compressedSize: number; raw: unknown };
export async function readZipEntries(buffer: Uint8Array): Promise<ZipEntry[]> {
return new Promise((resolve, reject) => {
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true, decodeStrings: false }, (openError: Error | null, zipFile: any) => {
if (openError || !zipFile) return reject(openError ?? new Error("无法打开 ZIP"));
const entries: ZipEntry[] = [];
zipFile.readEntry();
zipFile.on("entry", (entry: any) => {
const fileName = decodeZipEntryName(entry);
if (!fileName.endsWith("/") && !isJunk(fileName)) {
entries.push({ fileName, uncompressedSize: entry.uncompressedSize, compressedSize: entry.compressedSize, raw: entry });
}
zipFile.readEntry();
});
zipFile.on("end", () => resolve(entries));
zipFile.on("error", reject);
});
});
}
function decodeZipEntryName(entry: any): string {
const raw: Buffer = Buffer.isBuffer(entry.fileName)
? entry.fileName
: Buffer.from(String(entry.fileName), "binary");
const utf8 = raw.toString("utf8");
if (!utf8.includes("\uFFFD")) return utf8;
const gbk = iconv.decode(raw, "gbk");
if (!gbk.includes("\uFFFD")) return gbk;
return utf8;
}
function isJunk(name: string): boolean {
const base = name.split("/").pop() ?? "";
return name.split("/").includes("__MACOSX") || base === ".DS_Store" || base.startsWith("._") || base.startsWith(".~") || base.startsWith("~$");
}
export function validatePackEntries(entries: ZipEntry[]): void {
const errors: string[] = [];
if (entries.length > MATERIAL_PACK_LIMITS.maxEntries) errors.push(`文件数超过 ${MATERIAL_PACK_LIMITS.maxEntries}`);
const total = entries.reduce((sum, entry) => sum + entry.uncompressedSize, 0);
if (total > MATERIAL_PACK_LIMITS.maxTotalSize) errors.push("解压后总大小超过 500MB");
for (const entry of entries) {
if (entry.fileName.startsWith("/") || entry.fileName.split("/").includes("..")) errors.push(`存在不安全路径: ${entry.fileName}`);
if (entry.compressedSize > 0 && entry.uncompressedSize / entry.compressedSize > MATERIAL_PACK_LIMITS.maxCompressionRatio) errors.push(`压缩比超过 150: ${entry.fileName}`);
}
const info = entries.find((entry) => entry.fileName === "信息表.xlsx");
if (!info) errors.push("ZIP 根目录缺少精确名为「信息表.xlsx」的文件");
if (entries.some((entry) => entry.fileName.toLowerCase().endsWith(".zip"))) errors.push("不允许嵌套 ZIP");
if (errors.length) throw new MaterialPackValidationError(errors);
}
export function extractZipEntry(buffer: Uint8Array, target: ZipEntry): Promise<Buffer> {
return new Promise((resolve, reject) => {
yauzl.fromBuffer(Buffer.from(buffer), { lazyEntries: true, autoClose: true, decodeStrings: false }, (openError: Error | null, zipFile: any) => {
if (openError || !zipFile) return reject(openError ?? new Error("无法打开 ZIP"));
zipFile.readEntry();
zipFile.on("entry", (entry: any) => {
if (decodeZipEntryName(entry) !== target.fileName) return zipFile.readEntry();
zipFile.openReadStream(entry, (error: Error | null, stream: any) => {
if (error || !stream) return reject(error ?? new Error(`无法读取 ${target.fileName}`));
const chunks: Buffer[] = [];
stream.on("data", (chunk: Buffer) => chunks.push(chunk));
stream.on("end", () => resolve(Buffer.concat(chunks)));
stream.on("error", reject);
});
});
zipFile.on("error", reject);
});
});
}
+163
View File
@@ -0,0 +1,163 @@
import { describe, expect, test, afterEach } from "bun:test";
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
parseLocalRulesContent,
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets
} from "./rules-local.js";
import { findSealTool } from "./tools.js";
const tempDirs: string[] = [];
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("rules-local workspace", () => {
test("parses wrapped rules object", () => {
const raw = JSON.stringify({
corpId: "corp-1",
source: "draft",
rules: [
{ code: 1, description: "餐饮发票必须提供水单", scope: "MEAL", strictness: "MUST_FOLLOW" },
{ code: 2, description: "单张发票金额不得超标", scope: "ALL" }
]
});
const parsed = parseLocalRulesContent(raw);
expect(parsed.rules.length).toBe(2);
expect(parsed.meta.corpId).toBe("corp-1");
expect(parsed.meta.source).toBe("draft");
expect(parsed.rules[0]!.description).toBe("餐饮发票必须提供水单");
expect(parsed.rules[0]!.strictness).toBe("MUST_FOLLOW");
expect(parsed.rules[1]!.strictness).toBe("MUST_FOLLOW"); // default
});
test("parses raw rules array", () => {
const raw = JSON.stringify([
{ description: "打车必须备注起止地点", scope: "TAXI" }
]);
const parsed = parseLocalRulesContent(raw);
expect(parsed.rules.length).toBe(1);
expect(parsed.rules[0]!.description).toBe("打车必须备注起止地点");
expect(parsed.rules[0]!.code).toBe(1);
});
test("rejects invalid format or empty description", () => {
expect(() => parseLocalRulesContent("not-json")).toThrow("JSON 解析失败");
expect(() => parseLocalRulesContent(JSON.stringify({ other: 123 }))).toThrow("本地规则文件格式错误");
expect(() => parseLocalRulesContent(JSON.stringify([{ code: 1 }]))).toThrow("缺少有效的 'description'");
});
test("saves and loads local rules file accurately", () => {
const dir = mkdtempSync(join(tmpdir(), "seal-rules-test-"));
tempDirs.push(dir);
const filePath = join(dir, "sub", "rules.json");
const savedPath = saveLocalRulesFile(filePath, {
corpId: "test-corp",
source: "version:5",
rules: [
{ code: 10, description: "酒店住宿必须提供明细清单", scope: "HOTEL", strictness: "MUST_FOLLOW" }
]
});
expect(savedPath).toBe(filePath);
const loaded = loadLocalRulesFile(filePath);
expect(loaded.rules.length).toBe(1);
expect(loaded.meta.corpId).toBe("test-corp");
expect(loaded.rules[0]!.code).toBe(10);
expect(loaded.rules[0]!.description).toBe("酒店住宿必须提供明细清单");
});
test("converts local rules to lint targets", () => {
const targets = localRulesToLintTargets([
{ code: 1, description: "规则一", name: "R1" },
{ code: "0002", description: "规则二" },
{ description: "规则三" }
]);
expect(targets[0]!.code).toBe("#0001");
expect(targets[0]!.name).toBe("R1");
expect(targets[1]!.code).toBe("#0002");
expect(targets[2]!.code).toBe("#0003");
});
});
describe("rules-local offline lint tool integration", () => {
test("lints local file directly with 0 network calls and high score", async () => {
const dir = mkdtempSync(join(tmpdir(), "seal-lint-test-"));
tempDirs.push(dir);
const filePath = join(dir, "clean-rules.json");
saveLocalRulesFile(filePath, {
corpId: "test-corp",
rules: [
{
code: 1,
description: "单张发票金额超过500元时,必须提供经办人签字的费用明细水单与消费清单。",
scope: "MEAL",
strictness: "MUST_FOLLOW"
}
]
});
const lintTool = findSealTool("seal_approval_rules_lint")!;
expect(lintTool).toBeDefined();
const result = await lintTool.handler(
null as any,
{ file: filePath } as any,
{ corp: { id: "test-corp" } } as any
) as any;
expect(result.totalRules).toBe(1);
expect(result.passed).toBe(true);
expect(result.overallScore).toBe(100);
});
test("detects vague wording in local rules file and enforces minScore gate", async () => {
const dir = mkdtempSync(join(tmpdir(), "seal-lint-test-"));
tempDirs.push(dir);
const filePath = join(dir, "vague-rules.json");
saveLocalRulesFile(filePath, {
corpId: "test-corp",
rules: [
{
code: 1,
description: "金额适当即可,视情况而定。",
scope: "ALL"
}
]
});
const lintTool = findSealTool("seal_approval_rules_lint")!;
const result = await lintTool.handler(
null as any,
{ file: filePath } as any,
{ corp: { id: "test-corp" } } as any
) as any;
expect(result.totalRules).toBe(1);
expect(result.overallScore).toBeLessThan(100);
expect(result.issues[0].issues.some((i: any) => i.code === "VAGUE_WORD")).toBe(true);
// minScore enforcement
await expect(
lintTool.handler(
null as any,
{ file: filePath, minScore: 95 } as any,
{ corp: { id: "test-corp" } } as any
)
).rejects.toThrow("Linter 质量门禁未通过");
});
});
+153
View File
@@ -0,0 +1,153 @@
import { existsSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import { dirname, resolve } from "node:path";
import type { RuleLintTarget } from "./linter/types.js";
export interface LocalRuleItem {
id?: string;
code?: number | string;
name?: string;
description: string;
scope?: string;
strictness?: string;
status?: string;
[key: string]: unknown;
}
export interface LocalRulesPayload {
corpId?: string;
source?: string;
versionNumber?: number;
exportedAt?: string;
rulesCount?: number;
rules: LocalRuleItem[];
}
/**
* Parses raw local rule content (JSON array or object with `rules` array)
* and normalizes them into a consistent structure.
*/
export function parseLocalRulesContent(rawText: string): {
rules: LocalRuleItem[];
meta: Omit<LocalRulesPayload, "rules">;
} {
let parsed: unknown;
try {
parsed = JSON.parse(rawText);
} catch (err) {
throw new Error(`本地规则文件 JSON 解析失败: ${err instanceof Error ? err.message : String(err)}`);
}
if (Array.isArray(parsed)) {
return {
rules: normalizeRuleItems(parsed),
meta: {
rulesCount: parsed.length
}
};
}
if (parsed && typeof parsed === "object") {
const obj = parsed as Record<string, unknown>;
const rawRules = Array.isArray(obj.rules) ? obj.rules : undefined;
if (!rawRules) {
throw new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象");
}
return {
rules: normalizeRuleItems(rawRules),
meta: {
corpId: typeof obj.corpId === "string" ? obj.corpId : undefined,
source: typeof obj.source === "string" ? obj.source : undefined,
versionNumber: typeof obj.versionNumber === "number" ? obj.versionNumber : undefined,
exportedAt: typeof obj.exportedAt === "string" ? obj.exportedAt : undefined,
rulesCount: rawRules.length
}
};
}
throw new Error("本地规则文件格式错误: 顶层必须为规则数组或包含 'rules' 数组的对象");
}
function normalizeRuleItems(items: unknown[]): LocalRuleItem[] {
return items.map((item, idx) => {
if (!item || typeof item !== "object") {
throw new Error(`第 ${idx + 1} 条规则格式错误: 必须为对象`);
}
const r = item as Record<string, unknown>;
const description = typeof r.description === "string" ? r.description.trim() : "";
if (!description) {
throw new Error(`第 ${idx + 1} 条规则缺少有效的 'description' (规则描述) 字段`);
}
const code =
typeof r.code === "number" || typeof r.code === "string"
? r.code
: idx + 1;
return {
...r,
code,
description,
scope: typeof r.scope === "string" ? r.scope : "ALL",
strictness: typeof r.strictness === "string" ? r.strictness : "MUST_FOLLOW"
};
});
}
/**
* Loads a local rules file from path.
*/
export function loadLocalRulesFile(filePath: string): {
rules: LocalRuleItem[];
meta: Omit<LocalRulesPayload, "rules">;
resolvedPath: string;
} {
const resolved = resolve(filePath);
if (!existsSync(resolved)) {
throw new Error(`未找到本地规则文件: ${filePath} (${resolved})`);
}
const content = readFileSync(resolved, "utf8");
const parsed = parseLocalRulesContent(content);
return {
...parsed,
resolvedPath: resolved
};
}
/**
* Saves rules to a formatted JSON file.
*/
export function saveLocalRulesFile(
filePath: string,
data: LocalRulesPayload
): string {
const resolved = resolve(filePath);
mkdirSync(dirname(resolved), { recursive: true });
writeFileSync(resolved, `${JSON.stringify(data, null, 2)}\n`, "utf8");
return resolved;
}
/**
* Converts local rule items to linter targets.
*/
export function localRulesToLintTargets(rules: LocalRuleItem[]): RuleLintTarget[] {
return rules.map((r, idx) => {
let codeStr: string | undefined;
if (typeof r.code === "number") {
codeStr = `#${String(r.code).padStart(4, "0")}`;
} else if (typeof r.code === "string") {
codeStr = r.code.startsWith("#") ? r.code : `#${r.code}`;
} else {
codeStr = `#${String(idx + 1).padStart(4, "0")}`;
}
return {
id: r.id,
code: codeStr,
name: r.name,
description: r.description,
scope: r.scope,
strictness: r.strictness
};
});
}
+3 -45
View File
@@ -5,7 +5,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { CorpConfig } from "../../core/config/types.js";
import { findSealMcpTool, findSealTool, sealMcpTools, sealTools } from "./tools.js";
import { findSealTool, sealTools } from "./tools.js";
type ToolHandler = (
client: KyInstance,
@@ -230,50 +230,9 @@ describe("sealTools", () => {
expect(sealTools.find((item) => item.name === "seal_approval_run_langfuse_bridge_get")).toBeDefined();
});
test("keeps the MCP exposed tool surface narrow", () => {
expect(sealMcpTools.map((tool) => tool.name)).toEqual([
"seal_whoami",
"seal_approval_search",
"seal_approval_context_get",
"seal_runs_search",
"seal_action"
]);
});
test("routes low-frequency management tools through seal_action", async () => {
const tool = sealMcpTools.find((item) => item.name === "seal_action");
expect(tool).toBeDefined();
const handler = tool!.handler as ToolHandler;
const result = await handler(
fakeApprovalRunsClient(),
{ action: "runs.summary", payload: { date: "2026-06-08", timezone: "Asia/Shanghai" } },
fakeContext()
) as { matched: number };
expect(result.matched).toBe(2);
});
test("routes lightweight approval run actions through seal_action", async () => {
const tool = sealMcpTools.find((item) => item.name === "seal_action");
expect(tool).toBeDefined();
const handler = tool!.handler as ToolHandler;
const result = await handler(
fakeApprovalRunsClient(),
{ action: "runs.citedRules", payload: { recordId: "run-1" } },
fakeContext()
) as { count: number };
expect(result.count).toBe(1);
});
test("keeps old fine-grained tools available to compatibility callers but hidden from MCP list", () => {
expect(sealMcpTools.find((item) => item.name === "seal_approval_rule_create")).toBeUndefined();
expect(findSealMcpTool("seal_approval_rule_create")).toBeUndefined();
test("can find tools by name in sealTools", () => {
expect(findSealTool("seal_approval_rule_create")).toBeDefined();
expect(findSealMcpTool("seal_action")).toBeDefined();
expect(findSealMcpTool("seal_runs_search")?.name).toBe("seal_runs_search");
expect(findSealTool("non_existent_tool")).toBeUndefined();
});
test("approval run search omits bridge unless requested", async () => {
@@ -1034,4 +993,3 @@ function fakeDeployClient(): KyInstance {
}
} as unknown as KyInstance;
}
+370 -291
View File
@@ -5,8 +5,26 @@ import { randomBytes } from "node:crypto";
import * as api from "./api.js";
import { defaultSealUrl, getHoseEnterpriseUrl, probeHoseDomain } from "../../core/auth/hose.js";
import { CorpConfig } from "../../core/config/types.js";
import { loadGlobalConfig } from "../../core/config/loader.js";
import { createSealClientForToken } from "../../core/http/factory.js";
import { searchApprovalContent } from "./search.js";
import { loadRuleLinter, lintRuleBatch, lintSingleRule, type RuleLintTarget } from "./linter/index.js";
import {
loadLocalRulesFile,
saveLocalRulesFile,
localRulesToLintTargets,
type LocalRuleItem
} from "./rules-local.js";
import {
checkWebhookReadiness,
previewMaterialPack,
pushMaterialPack,
readMaterialPackFile
} from "./material-pack/index.js";
import {
extractApprovalRunAttachments
} from "./attachments.js";
import { exportApprovalRunsToExcel } from "./approval-runs-export.js";
import {
ThinkingPolicySchema,
type ApprovalRule,
@@ -315,7 +333,30 @@ export const sealTools = [
params: { ruleId: string; description?: string; scope?: string; strictness?: string }
) => {
const { ruleId, ...rest } = params;
return api.updateApprovalRule(client, ruleId, rest);
const result = await api.updateApprovalRule(client, ruleId, rest);
if (params.description) {
try {
const globalConfig = loadGlobalConfig();
if (globalConfig.lint?.enabled) {
const loaded = await loadRuleLinter(globalConfig.lint.activeLinter);
const lintResult = await lintSingleRule({ id: ruleId, description: params.description }, loaded);
if (lintResult.issues.length > 0) {
console.error(`⚠️ [Linter 质检提醒] 规则质量评分: ${lintResult.score}/100 (发现 ${lintResult.issues.length} 处潜在风险):`);
for (const issue of lintResult.issues) {
console.error(` • [${issue.level.toUpperCase()}] ${issue.message}${issue.snippet ? ` ("${issue.snippet}")` : ""}`);
if (issue.suggestion) {
console.error(` 👉 建议: ${issue.suggestion}`);
}
}
}
}
} catch {
// 容错降级:质检异常绝不阻断规则更新
}
}
return result;
}
},
{
@@ -412,6 +453,260 @@ export const sealTools = [
return rule;
}
},
{
name: "seal_approval_rules_lint",
description: "对 Seal 本地规则文件、草稿审批规则或指定发布版本规则进行质量与可执行性检查(模糊词、悬空例外检测)",
parameters: z.object({
file: z.string().optional().describe("指定本地规则文件路径进行离线质检(支持 .json),0网络请求、不污染远端草稿"),
linter: z.string().optional().describe("指定使用的校验器名称或脚本路径(如 builtin、strict、./my-linter.ts)"),
version: z.string().optional().describe("指定要质检的历史发布版本号或 ID(如 16 或 latest),不传默认质检当前草稿"),
code: z.string().optional().describe("按规则展示编号过滤(如 #0038)"),
ruleId: z.string().optional().describe("按规则 ID 过滤"),
minScore: z.number().optional().describe("最低合格质量分阈值(0~100),低于该分值抛出错误以返回非零退出码"),
level: z.enum(["all", "error", "warning"]).default("all").describe("问题报告等级过滤"),
summary: z.boolean().optional().describe("为 true 时仅返回存在瑕疵/扣分的规则")
}),
handler: async (
client: KyInstance,
params: {
file?: string;
linter?: string;
version?: string;
code?: string;
ruleId?: string;
minScore?: number;
level?: "all" | "error" | "warning";
summary?: boolean;
},
context: ToolContext
) => {
let targets: RuleLintTarget[] = [];
let versionNumber: number | undefined;
if (params.file) {
const local = loadLocalRulesFile(params.file);
targets = localRulesToLintTargets(local.rules);
versionNumber = local.meta.versionNumber;
} else if (params.version) {
const versions = await api.listApprovalRuleVersions(client);
const versionNumberParsed = Number(params.version);
const version = isNaN(versionNumberParsed)
? params.version === "latest"
? versions[0]
: versions.find((v) => v.id === params.version)
: versions.find((v) => v.versionNumber === versionNumberParsed);
if (!version) {
throw new Error(`未找到指定的规则版本: ${params.version}`);
}
versionNumber = version.versionNumber;
targets = (version.rules ?? []).map((r, idx) => ({
id: (r as any).id ?? (r as any).runtimeId,
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: (r as any).scope,
strictness: (r as any).strictness
}));
} else {
const draftData = await api.listApprovalRules(client);
targets = (draftData.rules ?? []).map((r, idx) => ({
id: r.id,
code: (r as any).code ?? `#${String(idx + 1).padStart(4, "0")}`,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: r.scope,
strictness: r.strictness
}));
}
if (params.code) {
targets = targets.filter(
(r) => r.code === params.code || r.code?.replace(/[#\s]/g, "") === params.code?.replace(/[#\s]/g, "")
);
}
if (params.ruleId) {
targets = targets.filter((r) => r.id === params.ruleId || r.code === params.ruleId);
}
const globalConfig = loadGlobalConfig();
const linterNameOrPath = params.linter ?? globalConfig.lint?.activeLinter ?? "builtin";
const loadedLinter = await loadRuleLinter(linterNameOrPath);
const batchResult = await lintRuleBatch(
targets,
loadedLinter,
{ corpId: context?.corp?.id, versionNumber, allRules: targets },
{ minScore: params.minScore, level: params.level, summary: params.summary }
);
if (params.minScore && batchResult.overallScore < params.minScore) {
throw new Error(
`[Linter 质量门禁未通过] 综合评分 ${batchResult.overallScore} 低于要求的最低分 ${params.minScore} 分 (共发现 ${batchResult.issueCount} 条问题规则)。`
);
}
return batchResult;
}
},
{
name: "seal_approval_rules_pull",
description: "从 Seal 远端拉取草稿或指定版本规则,保存至本地规则文件(支持离线编辑与本地 Lint,绝不污染远端草稿)",
parameters: z.object({
version: z.string().optional().describe("指定拉取的历史发布版本号或 ID(如 16 或 latest),不传默认拉取当前草稿规则"),
out: z.string().optional().describe("保存的目标本地文件路径,默认为 ./rules.local.json")
}),
handler: async (
client: KyInstance,
params: {
version?: string;
out?: string;
},
context: ToolContext
) => {
const outPath = params.out ?? "./rules.local.json";
let rules: LocalRuleItem[] = [];
let source = "draft";
let versionNumber: number | undefined;
if (params.version) {
const versions = await api.listApprovalRuleVersions(client);
const versionNumberParsed = Number(params.version);
const targetVersion = isNaN(versionNumberParsed)
? params.version === "latest"
? versions[0]
: versions.find((v) => v.id === params.version)
: versions.find((v) => v.versionNumber === versionNumberParsed);
if (!targetVersion) {
throw new Error(`未找到指定的规则版本: ${params.version}`);
}
versionNumber = targetVersion.versionNumber;
source = `version:${versionNumber}`;
rules = (targetVersion.rules ?? []).map((r, idx) => ({
code: (r as any).code ? Number(String((r as any).code).replace(/^#/, "")) || idx + 1 : idx + 1,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: (r as any).scope ?? "ALL",
strictness: (r as any).strictness ?? "MUST_FOLLOW"
}));
} else {
const draftData = await api.listApprovalRules(client);
rules = (draftData.rules ?? []).map((r, idx) => ({
id: r.id,
code: r.code ?? idx + 1,
name: (r as any).name ?? (r as any).title,
description: r.description ?? "",
scope: r.scope ?? "ALL",
strictness: r.strictness ?? "MUST_FOLLOW",
status: r.status
}));
}
const savedPath = saveLocalRulesFile(outPath, {
corpId: context.corp.id,
source,
versionNumber,
exportedAt: new Date().toISOString(),
rulesCount: rules.length,
rules
});
return {
saved: true,
path: savedPath,
rulesCount: rules.length,
corpId: context.corp.id,
source,
versionNumber
};
}
},
{
name: "seal_approval_rules_push",
description: "将本地规则文件推送到远端草稿(本地调优通过后一键应用,支持直接发布为正式版本)",
parameters: z.object({
file: z.string().optional().describe("要推送的本地规则文件路径,默认为 ./rules.local.json"),
dryRun: z.boolean().optional().describe("是否仅预览变更而不实际写入远端(默认 true,传 --yes 或 confirm: true 执行写入)"),
confirm: z.boolean().optional().describe("确认覆盖写入远端草稿"),
publish: z.boolean().optional().describe("写入草稿后是否直接发布为一个正式版本"),
versionName: z.string().optional().describe("发布版本的名称(仅在 publish=true 时有效)")
}),
handler: async (
client: KyInstance,
params: {
file?: string;
dryRun?: boolean;
confirm?: boolean;
publish?: boolean;
versionName?: string;
},
context: ToolContext
) => {
const filePath = params.file ?? "./rules.local.json";
const local = loadLocalRulesFile(filePath);
const isConfirmed = params.confirm === true;
const isDryRun = params.dryRun ?? !isConfirmed;
const before = await api.listApprovalRules(client);
if (isDryRun) {
return {
corpId: context.corp.id,
dryRun: true,
localFile: local.resolvedPath,
localRulesCount: local.rules.length,
remoteDraftCount: before.rules.length,
willPublish: Boolean(params.publish),
message: "Preview mode. Use --yes or confirm=true to apply local rules to remote draft."
};
}
// Step 1: Clear existing draft rules
let deleted = 0;
for (const rule of before.rules) {
await api.deleteApprovalRule(client, rule.id);
deleted += 1;
}
// Step 2: Create new rules from local
const created: Array<{ id: string; description: string; code?: number }> = [];
for (const rule of local.rules) {
const strictness = rule.strictness?.toUpperCase()?.includes("SHOULD")
? "SHOULD_FOLLOW"
: rule.strictness?.toUpperCase()?.includes("SUGGEST")
? "SUGGESTION"
: "MUST_FOLLOW";
const newRule = await api.createApprovalRule(client, {
description: rule.description,
scope: rule.scope ?? "ALL",
strictness
});
created.push({ id: newRule.id, description: newRule.description, code: newRule.code });
}
// Step 3: Recode
await api.recodeApprovalRules(client);
// Step 4: Optional publish
let publishedVersion: unknown = undefined;
if (params.publish) {
const dateStr = new Date().toISOString().slice(0, 10).replace(/-/g, "");
const name = params.versionName || `v-local-${dateStr}-${Date.now().toString().slice(-4)}`;
publishedVersion = await api.publishApprovalRuleVersion(client, name);
}
return {
corpId: context.corp.id,
dryRun: false,
localFile: local.resolvedPath,
clearedDraftRules: deleted,
createdRules: created.length,
published: publishedVersion ?? false
};
}
},
{
name: "seal_approval_documents_list",
description: "列出 Seal 审批知识文档",
@@ -875,6 +1170,34 @@ export const sealTools = [
});
}
},
{
name: "seal_approval_runs_export",
description: "将企业的审批审核记录导出为高保真 Excel 报表(包含单据模板、AI决策、人工审核结论、驳回原因及企业规则列细分结果)",
parameters: z.object({
startDate: z.string().optional().describe("起始时间,支持 YYYY-MM-DD 或毫秒时间戳"),
endDate: z.string().optional().describe("截止时间,支持 YYYY-MM-DD 或毫秒时间戳"),
limit: z.number().int().positive().optional().describe("最大拉取记录条数"),
status: z.string().optional().describe("单据状态过滤,如 completed, processing, failed"),
manualApprovalStatus: z.union([z.string(), z.array(z.string())]).optional().describe("人工审核状态过滤,如 APPROVED, TERMINATED, PROCESSING"),
includeCompletedOnly: z.boolean().optional().describe("是否仅导出已完成单据"),
outputFile: z.string().optional().describe("输出 Excel 文件的自定义绝对或相对路径"),
toDownloads: z.boolean().optional().describe("是否直接保存到用户的系统下载目录")
}),
handler: async (
client: KyInstance,
params: {
startDate?: string;
endDate?: string;
limit?: number;
status?: string;
manualApprovalStatus?: string | string[];
includeCompletedOnly?: boolean;
outputFile?: string;
toDownloads?: boolean;
},
context: ToolContext
) => exportApprovalRunsToExcel(client, context.corp, params)
},
{
name: "seal_approval_run_get",
description: "获取 Seal 单条审批/审核运行记录详情;可用 fields 只取 metadata、document.fields、result.summary 等局部字段",
@@ -1246,6 +1569,49 @@ export const sealTools = [
};
}
},
{
name: "seal_webhook_ready",
description: "检查当前企业的 Webhook 就绪状态看板(包括企业环境、租户身份、凭证连通性、已激活 Webhook 通道及材料包预检)",
parameters: z.object({
filePath: z.string().optional().describe("可选的材料包路径(ZIP 或 信息表.xlsx),用于同步做本地预检")
}),
handler: async (
client: KyInstance,
params: { filePath?: string },
context: ToolContext
) => {
return checkWebhookReadiness(client, context.corp, { filePath: params.filePath });
}
},
{
name: "seal_webhook_material_pack",
description: "将官方材料包格式本地校验、解析并通过 Seal 入站 Webhook 触发 AI 审批;preview 模式不联网,push 模式单通道自动选择",
parameters: z.object({
filePath: z.string().describe("材料包 ZIP 或 信息表.xlsx 文件路径"),
mode: z.enum(["preview", "push"]).default("preview"),
webhook: z.string().optional().describe("Webhook ID 或名称;当租户仅配置 1 个通道时可省略")
}),
handler: async (client: KyInstance, params: { filePath: string; mode?: "preview" | "push"; webhook?: string }) => {
const input = readMaterialPackFile(params.filePath);
if (params.mode !== "push") return previewMaterialPack(input.fileBuffer, input.fileName);
const integrations = await api.listWebhookIntegrations(client);
let integration: WebhookIntegration;
if (params.webhook) {
integration = api.findWebhookIntegration(integrations, params.webhook);
} else if (integrations.length === 1) {
integration = integrations[0]!;
} else if (integrations.length > 1) {
const options = integrations.map((i) => `"${i.name}" (${i.id})`).join(", ");
throw new Error(`当前租户存在多个 Webhook 通道 [${options}],请通过 webhook 参数指定目标通道。`);
} else {
throw new Error("当前租户未配置任何 Webhook 集成通道。");
}
return pushMaterialPack(input.fileBuffer, input.fileName, {
webhookUrl: integration.incomingDocumentWebhook.url,
secret: integration.secret
});
}
},
{
name: "seal_approval_run_langfuse_bridge_get",
description: "从 Seal approval run 中抽取 Langfuse 定位信息;优先返回 _langfuseTraceId,没有时给出 hosecloud-{sourceDocumentSN} session 回退",
@@ -1724,212 +2090,10 @@ const sealToolByName = new Map<string, SealTool>(
sealTools.map((tool) => [tool.name, tool])
);
const mcpDirectToolNames = [
"seal_whoami",
"seal_approval_search",
"seal_approval_context_get"
] as const;
const sealActionNames = [
"seal_session_get",
"seal_approval_rules_list",
"seal_approval_rules_clear",
"seal_approval_rule_create",
"seal_approval_rule_update",
"seal_approval_rule_delete",
"seal_approval_rule_versions_list",
"seal_approval_rule_version_get",
"seal_approval_rule_get",
"seal_approval_rule_version_publish",
"seal_approval_documents_list",
"seal_approval_document_get",
"seal_approval_document_create",
"seal_approval_document_update",
"seal_approval_style_preferences_get",
"seal_approval_style_preferences_update",
"seal_webhook_list",
"seal_webhook_get",
"seal_webhook_add",
"seal_webhook_update",
"seal_webhook_delete",
"seal_approval_runs_summary",
"seal_approval_runs_stats",
"seal_approval_runs_count",
"seal_approval_run_get",
"seal_approval_run_cited_rules_get",
"seal_approval_run_document_summary_get",
"seal_approval_run_attachments_get",
"seal_approval_run_result_get",
"seal_approval_run_url_get",
"seal_approval_run_pick",
"seal_simulation_batch_records_get",
"seal_simulation_batch_create",
"seal_simulation_batch_wait",
"seal_simulation_batch_clean",
"seal_simulation_batches_list",
"seal_simulation_batch_get",
"seal_simulation_templates_get",
"seal_simulation_integrations_get",
"seal_simulation_specifications_list",
"seal_simulation_material_package_upload",
"seal_deploy_hosecloud_requirements",
"seal_deploy_hosecloud_list",
"seal_deploy_hosecloud_get",
"seal_deploy_hosecloud_status",
"seal_deploy_hosecloud_configure",
"seal_deploy_hosecloud_sync",
"seal_preference_get",
"seal_preference_decision_update",
"seal_preference_thinking_depth_set",
"seal_preference_thinking_depth_policies_list",
"seal_preference_thinking_depth_policies_upsert",
"seal_preference_thinking_depth_policies_remove",
"seal_approval_run_langfuse_bridge_get"
] as const;
const sealActionAliases: Record<string, (typeof sealActionNames)[number]> = {
"session.get": "seal_session_get",
"rule.list": "seal_approval_rules_list",
"rule.clear": "seal_approval_rules_clear",
"rule.create": "seal_approval_rule_create",
"rule.update": "seal_approval_rule_update",
"rule.delete": "seal_approval_rule_delete",
"rule.versions.list": "seal_approval_rule_versions_list",
"rule.version.get": "seal_approval_rule_version_get",
"rule.get": "seal_approval_rule_get",
"rule.publish": "seal_approval_rule_version_publish",
"doc.list": "seal_approval_documents_list",
"doc.get": "seal_approval_document_get",
"doc.create": "seal_approval_document_create",
"doc.update": "seal_approval_document_update",
"style.get": "seal_approval_style_preferences_get",
"style.update": "seal_approval_style_preferences_update",
"webhook.list": "seal_webhook_list",
"webhook.get": "seal_webhook_get",
"webhook.add": "seal_webhook_add",
"webhook.update": "seal_webhook_update",
"webhook.delete": "seal_webhook_delete",
"runs.summary": "seal_approval_runs_summary",
"runs.stats": "seal_approval_runs_stats",
"runs.count": "seal_approval_runs_count",
"runs.get": "seal_approval_run_get",
"runs.citedRules": "seal_approval_run_cited_rules_get",
"runs.documentSummary": "seal_approval_run_document_summary_get",
"runs.attachments": "seal_approval_run_attachments_get",
"runs.result": "seal_approval_run_result_get",
"runs.url": "seal_approval_run_url_get",
"runs.pick": "seal_approval_run_pick",
"batch.records.get": "seal_simulation_batch_records_get",
"batch.create": "seal_simulation_batch_create",
"batch.wait": "seal_simulation_batch_wait",
"batch.clean": "seal_simulation_batch_clean",
"batch.list": "seal_simulation_batches_list",
"batch.get": "seal_simulation_batch_get",
"batch.templates.list": "seal_simulation_templates_get",
"batch.integrations.get": "seal_simulation_integrations_get",
"batch.specifications.list": "seal_simulation_specifications_list",
"batch.materialPackageUpload": "seal_simulation_material_package_upload",
"deploy.hosecloud.requirements": "seal_deploy_hosecloud_requirements",
"deploy.hosecloud.list": "seal_deploy_hosecloud_list",
"deploy.hosecloud.get": "seal_deploy_hosecloud_get",
"deploy.hosecloud.status": "seal_deploy_hosecloud_status",
"deploy.hosecloud.configure": "seal_deploy_hosecloud_configure",
"deploy.hosecloud.sync": "seal_deploy_hosecloud_sync",
"preference.get": "seal_preference_get",
"preference.decision.update": "seal_preference_decision_update",
"preference.thinkingDepth.set": "seal_preference_thinking_depth_set",
"preference.thinkingDepth.policies.list": "seal_preference_thinking_depth_policies_list",
"preference.thinkingDepth.policies.upsert": "seal_preference_thinking_depth_policies_upsert",
"preference.thinkingDepth.policies.remove": "seal_preference_thinking_depth_policies_remove",
"langfuse.bridge.get": "seal_approval_run_langfuse_bridge_get"
};
export const sealMcpTools: SealToolDefinition[] = [
...mcpDirectToolNames.map((name) => requiredTool(name)),
{
...requiredTool("seal_approval_runs_search"),
name: "seal_runs_search",
description: "查询 Seal 审批/审核运行记录,返回精简记录并按需提供 Langfuse trace/session 关联"
},
{
name: "seal_action",
description: "Seal 低频管理操作统一入口。传 action=help 查看可用动作;支持 rule/doc/style/webhook/runs/batch/langfuse 等管理与诊断操作。",
parameters: z.object({
action: z.string().describe("动作名,如 help、rule.create、doc.update、webhook.list、runs.summary、langfuse.bridge.get;也兼容旧 tool 名"),
payload: z.record(z.string(), z.unknown()).optional().describe("动作参数对象")
}),
handler: async (
client: KyInstance,
params: { action: string; payload?: Record<string, unknown> },
context: ToolContext
) => runSealAction(client, params, context)
}
];
export function findSealTool(name: string, options: { includeMcpAliases?: boolean } = {}) {
if (options.includeMcpAliases && name === "seal_runs_search") {
return requiredTool("seal_approval_runs_search");
}
export function findSealTool(name: string): SealTool | undefined {
return sealToolByName.get(name);
}
export function findSealMcpTool(name: string) {
return sealMcpTools.find((tool) => tool.name === name);
}
async function runSealAction(
client: KyInstance,
params: { action: string; payload?: Record<string, unknown> },
context: ToolContext
) {
const action = params.action?.trim();
if (!action || action === "help") {
return sealActionHelp(params.payload?.topic);
}
const toolName = sealActionAliases[action] ?? action;
if (!isSealActionToolName(toolName)) {
return {
error: `Unsupported seal_action action: ${action}`,
help: sealActionHelp(params.payload?.topic)
};
}
const tool = requiredTool(toolName);
const payload = params.payload ?? {};
return tool.handler(client, payload as never, context);
}
function sealActionHelp(topic: unknown) {
const normalizedTopic = typeof topic === "string" ? topic.trim() : undefined;
const actions = Object.entries(sealActionAliases)
.filter(([action]) => !normalizedTopic || action.startsWith(`${normalizedTopic}.`))
.map(([action, toolName]) => {
const tool = requiredTool(toolName);
return {
action,
toolName,
description: tool.description
};
});
return {
usage: "seal_action({ action, payload })",
topics: ["session", "rule", "doc", "style", "webhook", "runs", "batch", "langfuse"],
actions
};
}
function requiredTool(name: string): SealTool {
const tool = sealToolByName.get(name);
if (!tool) throw new Error(`Missing Seal tool: ${name}`);
return tool;
}
function isSealActionToolName(name: string): name is (typeof sealActionNames)[number] {
return sealActionNames.includes(name as (typeof sealActionNames)[number]);
}
function presentWebhookIntegration(
integration: WebhookIntegration,
includeSecret: boolean
@@ -2050,7 +2214,7 @@ export type SimulationBatchCreateInput = {
rawParams?: Record<string, unknown>;
};
export function parseDurationMs(duration: string): number {
function parseDurationMs(duration: string): number {
const match = duration.match(/^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i);
if (!match || !match[1]) return 600000;
const val = parseFloat(match[1]);
@@ -2065,7 +2229,7 @@ export function parseDurationMs(duration: string): number {
}
}
export function redactIntegrationSecrets(integration: Record<string, unknown>) {
function redactIntegrationSecrets(integration: Record<string, unknown>) {
return Object.fromEntries(
Object.entries(integration).map(([key, value]) => [
key,
@@ -2372,38 +2536,6 @@ function summarizeApprovalRunDocument(record: ApprovalRun) {
};
}
function extractApprovalRunAttachments(record: ApprovalRun, options: { summary?: boolean } = {}) {
const roots: Array<[string, unknown]> = [
["document", record.document],
["result", record.result],
["pipelineData", record.pipelineData],
["sourceExtendData", record.sourceExtendData]
];
const attachments: Array<Record<string, unknown>> = [];
const seen = new Set<string>();
for (const [path, value] of roots) {
collectAttachments(value, path, attachments, seen);
}
return {
recordId: record.id,
sourceDocumentSN: record.sourceDocumentSN,
sourceDocumentId: record.sourceDocumentId,
count: attachments.length,
attachments: options.summary
? attachments.map((attachment) => compactObject({
path: attachment.path,
kind: attachment.kind,
fileName: attachment.fileName,
mimeType: attachment.mimeType,
fileId: attachment.fileId,
sourceField: attachment.sourceField
}))
: attachments
};
}
function extractCitedRules(record: ApprovalRun) {
const candidates: Array<[string, unknown]> = [
["result.citedRules", getPath(record, "result.citedRules")],
@@ -2456,59 +2588,6 @@ function extractCitedRules(record: ApprovalRun) {
};
}
function collectAttachments(
value: unknown,
path: string,
output: Array<Record<string, unknown>>,
seen: Set<string>
) {
if (Array.isArray(value)) {
value.forEach((item, index) => collectAttachments(item, `${path}.${index}`, output, seen));
return;
}
const object = asRecord(value);
if (!object) return;
if (looksLikeAttachment(object, path)) {
const attachment = compactObject({
path,
fieldPath: path,
kind: inferAttachmentKind(path, object),
fileName: stringFromUnknown(object.fileName) ?? stringFromUnknown(object.filename) ?? stringFromUnknown(object.name) ?? stringFromUnknown(object.originalName),
mimeType: stringFromUnknown(object.mimeType) ?? stringFromUnknown(object.mimetype) ?? stringFromUnknown(object.contentType),
fileId: stringFromUnknown(object.fileId) ?? stringFromUnknown(object.id) ?? stringFromUnknown(object.attachmentId),
ossPath: stringFromUnknown(object.ossPath) ?? stringFromUnknown(object.ossKey) ?? stringFromUnknown(object.key),
url: stringFromUnknown(object.url) ?? stringFromUnknown(object.signedUrl) ?? stringFromUnknown(object.downloadUrl) ?? stringFromUnknown(object.previewUrl),
invoiceId: stringFromUnknown(object.invoiceId),
sourceField: stringFromUnknown(object.fieldName) ?? stringFromUnknown(object.label)
});
const key = JSON.stringify(attachment);
if (!seen.has(key)) {
seen.add(key);
output.push(attachment);
}
}
for (const [key, child] of Object.entries(object)) {
collectAttachments(child, `${path}.${key}`, output, seen);
}
}
function looksLikeAttachment(object: Record<string, unknown>, path: string) {
const keys = Object.keys(object).map((key) => key.toLowerCase());
const pathHint = /(attachment|attachments|invoice|receipt|file|files|附件|发票)/i.test(path);
const fileHints = ["filename", "fileName", "mimeType", "mimetype", "contentType", "fileId", "ossPath", "signedUrl", "downloadUrl", "previewUrl", "attachmentId"];
return pathHint && fileHints.some((key) => keys.includes(key.toLowerCase()));
}
function inferAttachmentKind(path: string, object: Record<string, unknown>) {
const normalized = `${path} ${stringFromUnknown(object.type) ?? ""}`.toLowerCase();
if (normalized.includes("invoice") || normalized.includes("发票")) return "invoice";
if (normalized.includes("receipt")) return "receipt";
return "attachment";
}
function firstPath(object: Record<string, unknown> | undefined, paths: readonly string[]) {
if (!object) return undefined;
for (const path of paths) {
+26 -23
View File
@@ -75,6 +75,18 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
return;
}
if (method === "POST" && (pathname === "/shutdown" || pathname === "/api/shutdown")) {
sendJson(res, 200, {
success: true,
message: "Shutting down seal-use background daemon",
pid: process.pid
});
setTimeout(() => {
process.kill(process.pid, "SIGTERM");
}, 50);
return;
}
// 3. Command Execution Endpoint: POST /api/cli
if (method === "POST" && pathname === "/api/cli") {
const body = await parseJsonBody(req);
@@ -112,7 +124,7 @@ export async function handleHttpRequest(req: IncomingMessage, res: ServerRespons
// 5. Generic Tool Invocation endpoint (POST /api/tool/:name)
if (method === "POST" && pathname.startsWith("/api/tool/")) {
const toolName = pathname.slice("/api/tool/".length).trim();
const tool = findSealTool(toolName, { includeMcpAliases: true });
const tool = findSealTool(toolName);
if (!tool) {
sendError(res, 404, `Tool not found: '${toolName}'`);
return;
@@ -393,28 +405,19 @@ export function extractCorpId(
}
export async function parseJsonBody(req: IncomingMessage): Promise<Record<string, unknown>> {
return new Promise((resolve, reject) => {
let raw = "";
req.on("data", (chunk) => {
raw += chunk;
if (raw.length > 20 * 1024 * 1024) {
// 20MB limit
reject(new Error("Payload too large"));
}
});
req.on("end", () => {
if (!raw.trim()) {
resolve({});
return;
}
try {
resolve(JSON.parse(raw));
} catch (err) {
reject(new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`));
}
});
req.on("error", reject);
});
let raw = "";
for await (const chunk of req) {
raw += chunk;
if (raw.length > 20 * 1024 * 1024) {
throw new Error("Payload too large");
}
}
if (!raw.trim()) return {};
try {
return JSON.parse(raw);
} catch (err) {
throw new Error(`Invalid JSON body: ${err instanceof Error ? err.message : String(err)}`);
}
}
export function sendJson(res: ServerResponse, statusCode: number, data: unknown) {
+5 -2
View File
@@ -8,9 +8,12 @@ export type HttpServerOptions = {
silent?: boolean;
};
export const DEFAULT_HTTP_PORT = 8787;
export const DEFAULT_HTTP_HOST = "127.0.0.1";
export async function startHttpServer(options: HttpServerOptions = {}): Promise<Server> {
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : 8787);
const host = options.host ?? (process.env.HOST ? process.env.HOST : "127.0.0.1");
const port = options.port ?? (process.env.PORT ? Number.parseInt(process.env.PORT, 10) : DEFAULT_HTTP_PORT);
const host = options.host ?? (process.env.HOST ? process.env.HOST : DEFAULT_HTTP_HOST);
const server = createServer(async (req, res) => {
try {